@systemfsoftware/agent-storage-cloudflare 0.0.0-stage → 0.1.0-beta.192

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (101) hide show
  1. package/LICENSE +21 -0
  2. package/dist/DoMemoryStore-AaGtt8CZ.d.mts +29 -0
  3. package/dist/DoMemoryStore-DVun329p.mjs +67 -0
  4. package/dist/DoMemoryStore-DVun329p.mjs.map +1 -0
  5. package/dist/DoMemoryStore.d.mts +2 -0
  6. package/dist/DoMemoryStore.mjs +1 -0
  7. package/dist/DoMessageDeliveryStore-BvB6OPI1.mjs +34 -0
  8. package/dist/DoMessageDeliveryStore-BvB6OPI1.mjs.map +1 -0
  9. package/dist/DoMessageDeliveryStore-Cb-DNN5s.d.mts +16 -0
  10. package/dist/DoMessageDeliveryStore.d.mts +2 -0
  11. package/dist/DoMessageDeliveryStore.mjs +1 -0
  12. package/dist/DoScheduleStore-BiTgDvX1.d.mts +36 -0
  13. package/dist/DoScheduleStore-C7GkSReF.mjs +167 -0
  14. package/dist/DoScheduleStore-C7GkSReF.mjs.map +1 -0
  15. package/dist/DoScheduleStore.d.mts +2 -0
  16. package/dist/DoScheduleStore.mjs +1 -0
  17. package/dist/DoStorageConfig-BqezsbD6.mjs +43 -0
  18. package/dist/DoStorageConfig-BqezsbD6.mjs.map +1 -0
  19. package/dist/DoStorageConfig-CuB6ZOtX.d.mts +36 -0
  20. package/dist/DoStorageConfig.d.mts +2 -0
  21. package/dist/DoStorageConfig.mjs +1 -0
  22. package/dist/DoStorageError-C-F5Z_FZ.d.mts +82 -0
  23. package/dist/DoStorageError-DSQzuCb0.mjs +138 -0
  24. package/dist/DoStorageError-DSQzuCb0.mjs.map +1 -0
  25. package/dist/DoStorageError.d.mts +2 -0
  26. package/dist/DoStorageError.mjs +1 -0
  27. package/dist/DoStorageFailpoint-C7zLUULu.d.mts +19 -0
  28. package/dist/DoStorageFailpoint-WO3B_DQl.mjs +20 -0
  29. package/dist/DoStorageFailpoint-WO3B_DQl.mjs.map +1 -0
  30. package/dist/DoStorageFailpoint.d.mts +2 -0
  31. package/dist/DoStorageFailpoint.mjs +1 -0
  32. package/dist/DoStorageFailpointTesting.d.mts +21 -0
  33. package/dist/DoStorageFailpointTesting.mjs +18 -0
  34. package/dist/DoStorageFailpointTesting.mjs.map +1 -0
  35. package/dist/DoStorageVersion-BrolfBDS.mjs +7 -0
  36. package/dist/DoStorageVersion-BrolfBDS.mjs.map +1 -0
  37. package/dist/DoStorageVersion-D7CIxFc_.d.mts +8 -0
  38. package/dist/DoStorageVersion.d.mts +3 -0
  39. package/dist/DoStorageVersion.mjs +2 -0
  40. package/dist/DoSubmissionLedger-Oq5OstxL.mjs +1878 -0
  41. package/dist/DoSubmissionLedger-Oq5OstxL.mjs.map +1 -0
  42. package/dist/DoSubmissionLedger-tLjwidUn.d.mts +25 -0
  43. package/dist/DoSubmissionLedger.d.mts +2 -0
  44. package/dist/DoSubmissionLedger.mjs +1 -0
  45. package/dist/DoSubscriptionStore-BMJiFxt3.mjs +185 -0
  46. package/dist/DoSubscriptionStore-BMJiFxt3.mjs.map +1 -0
  47. package/dist/DoSubscriptionStore-zx6nfbbh.d.mts +25 -0
  48. package/dist/DoSubscriptionStore.d.mts +2 -0
  49. package/dist/DoSubscriptionStore.mjs +1 -0
  50. package/dist/DoThreadStore-2zTSfui-.d.mts +81 -0
  51. package/dist/DoThreadStore-CeYHcRR9.mjs +411 -0
  52. package/dist/DoThreadStore-CeYHcRR9.mjs.map +1 -0
  53. package/dist/DoThreadStore.d.mts +2 -0
  54. package/dist/DoThreadStore.mjs +5 -0
  55. package/dist/MemoryProtocol-CtCFYe4s.mjs +221 -0
  56. package/dist/MemoryProtocol-CtCFYe4s.mjs.map +1 -0
  57. package/dist/MemoryProtocol-DXV77CcJ.d.mts +38160 -0
  58. package/dist/MemoryProtocol.d.mts +2 -0
  59. package/dist/MemoryProtocol.mjs +1 -0
  60. package/dist/PortProtocol-4xvMyCgP.mjs +322 -0
  61. package/dist/PortProtocol-4xvMyCgP.mjs.map +1 -0
  62. package/dist/PortProtocol-DXuguAgD.d.mts +966 -0
  63. package/dist/PortProtocol.d.mts +2 -0
  64. package/dist/PortProtocol.mjs +1 -0
  65. package/dist/PortRouting-B9302ouX.mjs +683 -0
  66. package/dist/PortRouting-B9302ouX.mjs.map +1 -0
  67. package/dist/PortRouting-DsoI6soW.d.mts +105 -0
  68. package/dist/PortRouting.d.mts +2 -0
  69. package/dist/PortRouting.mjs +1 -0
  70. package/dist/do-journal-nPNEAjV5.mjs +769 -0
  71. package/dist/do-journal-nPNEAjV5.mjs.map +1 -0
  72. package/dist/index.d.mts +14 -0
  73. package/dist/index.mjs +14 -0
  74. package/dist/migrations-BRTvj8Ue.mjs +233 -0
  75. package/dist/migrations-BRTvj8Ue.mjs.map +1 -0
  76. package/dist/owned-state-DrOD9s0c.mjs +157 -0
  77. package/dist/owned-state-DrOD9s0c.mjs.map +1 -0
  78. package/dist/rolldown-runtime-D3KUYPsf.mjs +12 -0
  79. package/package.json +106 -3
  80. package/src/DoMemoryStore.ts +71 -0
  81. package/src/DoMessageDeliveryStore.ts +46 -0
  82. package/src/DoScheduleStore.ts +276 -0
  83. package/src/DoStorageConfig.ts +45 -0
  84. package/src/DoStorageError.ts +146 -0
  85. package/src/DoStorageFailpoint.ts +25 -0
  86. package/src/DoStorageFailpointTesting.ts +42 -0
  87. package/src/DoStorageVersion.ts +2 -0
  88. package/src/DoSubmissionLedger.ts +3980 -0
  89. package/src/DoSubscriptionStore.ts +331 -0
  90. package/src/DoThreadStore.ts +602 -0
  91. package/src/MemoryProtocol.ts +357 -0
  92. package/src/PortProtocol.ts +626 -0
  93. package/src/PortRouting.ts +1888 -0
  94. package/src/index.ts +13 -0
  95. package/src/internal/canonical-append.ts +15 -0
  96. package/src/internal/do-journal.ts +1449 -0
  97. package/src/internal/migrations.ts +395 -0
  98. package/src/internal/owned-state.ts +300 -0
  99. package/src/internal/prompt-checkpoint.ts +170 -0
  100. package/src/internal/storage-span.ts +54 -0
  101. package/README.md +0 -3
@@ -0,0 +1,3980 @@
1
+ import * as BrowserCrypto from '@effect/platform-browser/BrowserCrypto'
2
+ import * as SqliteClient from '@effect/sql-sqlite-do/SqliteClient'
3
+ import {
4
+ decodeAbortFact,
5
+ decodeAdmissionFact,
6
+ decodeApprovalFact,
7
+ decodeResolutionFact,
8
+ } from '@systemfsoftware/agent-storage-sql/sql-admission-facts'
9
+ import {
10
+ definitionJson,
11
+ makeCanonicalStorage,
12
+ recordBatchId,
13
+ runKey,
14
+ } from '@systemfsoftware/agent-storage-sql/sql-canonical-storage'
15
+ import {
16
+ SqlStorageProgress,
17
+ type SqlStorageProgressKind,
18
+ } from '@systemfsoftware/agent-storage-sql/sql-storage-progress'
19
+ import {
20
+ BoundedIdentifier,
21
+ BoundedTimestamp,
22
+ makeSubmissionRowFields,
23
+ } from '@systemfsoftware/agent-storage-sql/sql-submission-rows'
24
+ import { canonicalRecordJson } from '@systemfsoftware/agent-storage-sql/sql-thread-archive-range'
25
+ import type { LifecyclePublicationFact } from '@systemfsoftware/agent/lifecycle-publication'
26
+ import { InputMessage } from '@systemfsoftware/agent/messaging'
27
+ import {
28
+ CanonicalSequence,
29
+ DefinitionDigests,
30
+ PersistedJson,
31
+ RecordEnvelope,
32
+ SettlementOutcome,
33
+ WorkerAdmission,
34
+ } from '@systemfsoftware/agent/records'
35
+ import { runIdForSubmission } from '@systemfsoftware/agent/run-journal'
36
+ import { StorageOwner } from '@systemfsoftware/agent/run-storage'
37
+ import {
38
+ SettlementPublicationResult,
39
+ SettlementPublisher,
40
+ validateCanonicalSettlement,
41
+ validateJoinedSettlement,
42
+ validatePublication,
43
+ } from '@systemfsoftware/agent/settlement-publisher'
44
+ import {
45
+ AbortCommand,
46
+ AbortIntent,
47
+ AbortIntentRequest,
48
+ AdmissionAdmitted,
49
+ AdmissionConflict,
50
+ AdmissionFence,
51
+ AdmissionNotAdmitted,
52
+ AdmissionPolicyError,
53
+ AdmissionRequest,
54
+ AdmissionResult,
55
+ ApprovalConflict,
56
+ ApprovalDecisionCommand,
57
+ ApprovalDecisionIntent,
58
+ approvalDecisionsCover,
59
+ AttachChildToReservationRequest,
60
+ BeginChildBudgetReleaseRequest,
61
+ ChildAttachmentSnapshot,
62
+ ChildBudgetReservationRequest,
63
+ ChildBudgetReservationSnapshot,
64
+ ChildReservationConflict,
65
+ ChildSettledNotification,
66
+ type ChildSettledOutcome,
67
+ Claim,
68
+ ClaimJoiningRequest,
69
+ ClaimRequest,
70
+ FundingOwner,
71
+ FundingOwnerRequest,
72
+ InputAppliedMarker,
73
+ JoinedToHost,
74
+ JoiningClaim,
75
+ JoinSnapshot,
76
+ LedgerCapabilities,
77
+ LedgerError,
78
+ MarkInputAppliedRequest,
79
+ MarkJoinedRequest,
80
+ MarkReadyRequest,
81
+ MarkUnknownRequest,
82
+ OwnershipLost,
83
+ ParentLinkage,
84
+ QueueSequence,
85
+ RecoverySnapshot,
86
+ RecoverySnapshotRequest,
87
+ ReleaseChildBudgetRequest,
88
+ ReservedChildBudget,
89
+ RevertJoiningRequest,
90
+ Settlement,
91
+ SettlementConflict,
92
+ settlementFailureFromRecord,
93
+ SettlementFinalization,
94
+ submissionAbortRecordId,
95
+ SubmissionAdmissionFence,
96
+ submissionInputBatchId,
97
+ submissionInputRecordId,
98
+ SubmissionLedger,
99
+ SubmissionLookup,
100
+ SubmissionLookupByKey,
101
+ submissionSettlementBatchId,
102
+ submissionSettlementRecordId,
103
+ SubmissionSnapshot,
104
+ SubmissionWorkItem,
105
+ SuspendRequest,
106
+ type SuspensionOutcome,
107
+ SuspensionReason,
108
+ SuspensionSnapshot,
109
+ UnknownResolution,
110
+ UnknownResolutionCommand,
111
+ UnknownResolutionConflict,
112
+ UnknownResolutionIntent,
113
+ unknownResolutionKind,
114
+ unknownResolutionMatchesResult,
115
+ WorkerLedgerState,
116
+ WorkerStopCommand,
117
+ workerTerminalFromRecord,
118
+ } from '@systemfsoftware/agent/submission-ledger'
119
+ import {
120
+ AppendConflict,
121
+ makeTransferFactCheck,
122
+ ThreadNotMaterialized,
123
+ ThreadStoreDiagnostic,
124
+ ThreadStoreError,
125
+ } from '@systemfsoftware/agent/thread-store'
126
+ import { AssignmentTerminal } from '@systemfsoftware/agent/worker'
127
+ import * as Cause from 'effect/Cause'
128
+ import * as Clock from 'effect/Clock'
129
+ import * as Context from 'effect/Context'
130
+ import * as CryptoDigest from 'effect/crypto/Digest'
131
+ import * as SecureRandom from 'effect/crypto/SecureRandom'
132
+ import * as DateTime from 'effect/DateTime'
133
+ import * as Effect from 'effect/Effect'
134
+ import * as Layer from 'effect/Layer'
135
+ import * as Option from 'effect/Option'
136
+ import * as Schema from 'effect/Schema'
137
+ import * as SqlClientService from 'effect/sql/SqlClient'
138
+ import type * as SqlError from 'effect/sql/SqlError'
139
+ import * as Stream from 'effect/Stream'
140
+
141
+ import { DoStorageConfig } from './DoStorageConfig'
142
+ import {
143
+ DoLedgerError,
144
+ DoStorageCorruptionError,
145
+ DoStorageError,
146
+ type DoStorageFailpointLocation,
147
+ } from './DoStorageError'
148
+ import { DoStorageFailpoint } from './DoStorageFailpoint'
149
+ import {
150
+ type DoStorageInitializationError,
151
+ type DoStorageOptions,
152
+ storageConfigLayer,
153
+ storageFailpointLayer,
154
+ } from './DoThreadStore'
155
+ import { prepareCanonicalAppend } from './internal/canonical-append'
156
+ import { decodeRows, initializeDoJournal } from './internal/do-journal'
157
+ import { ownedRows } from './internal/owned-state'
158
+
159
+ type SubmissionId = SubmissionSnapshot['submissionId']
160
+
161
+ /**
162
+ * Static decode-side ceiling; writes are bounded in bytes by the configured
163
+ * `maxStoredValueBytes` (see do-journal.ts).
164
+ */
165
+ const BoundedStoredText = Schema.String.check(Schema.isMaxLength(2_000_000))
166
+
167
+ const rowFields = makeSubmissionRowFields({
168
+ storedText: BoundedStoredText,
169
+ queueSequence: QueueSequence,
170
+ canonicalSequence: CanonicalSequence,
171
+ })
172
+
173
+ const SCAN_PAGE_SIZE = 256
174
+ const admissionFitsTransfer = makeTransferFactCheck(AdmissionRequest)
175
+ const RESUME_IMMEDIATELY: SuspensionOutcome = 'resume-immediately'
176
+ const SUSPENDED: SuspensionOutcome = 'suspended'
177
+ const NOT_WAITING: ChildSettledOutcome = 'not-waiting'
178
+ const STILL_WAITING: ChildSettledOutcome = 'still-waiting'
179
+ const WOKEN: ChildSettledOutcome = 'woken'
180
+ const MAX_IDENTIFIER_LENGTH = 1_024
181
+
182
+ class SubmissionRow extends Schema.Class<SubmissionRow>('SubmissionRow')(rowFields.submission) {}
183
+
184
+ // Discovery retains identity and state, never every queued input payload.
185
+ const SubmissionWorkRow = Schema.Struct({
186
+ submission_id: SubmissionRow.fields.submission_id,
187
+ thread_id: SubmissionRow.fields.thread_id,
188
+ queue_sequence: SubmissionRow.fields.queue_sequence,
189
+ principal: SubmissionRow.fields.principal,
190
+ idempotency_key: SubmissionRow.fields.idempotency_key,
191
+ deployment_id: SubmissionRow.fields.deployment_id,
192
+ receipt_id: SubmissionRow.fields.receipt_id,
193
+ state: SubmissionRow.fields.state,
194
+ })
195
+
196
+ class ChildReservationRow extends Schema.Class<ChildReservationRow>('ChildReservationRow')(
197
+ rowFields.childReservation,
198
+ ) {}
199
+
200
+ class ChildSettlementMarkerRow extends Schema.Class<ChildSettlementMarkerRow>(
201
+ 'ChildSettlementMarkerRow',
202
+ )({
203
+ parent_submission_id: BoundedIdentifier,
204
+ child_submission_id: BoundedIdentifier,
205
+ child_outcome: Schema.NullOr(SettlementOutcome),
206
+ recorded_at: BoundedTimestamp,
207
+ }) {}
208
+
209
+ class ApprovalDecisionRow extends Schema.Class<ApprovalDecisionRow>('ApprovalDecisionRow')(
210
+ rowFields.approvalDecision,
211
+ ) {}
212
+
213
+ class UnknownResolutionRow extends Schema.Class<UnknownResolutionRow>('UnknownResolutionRow')(
214
+ rowFields.unknownResolution,
215
+ ) {}
216
+
217
+ class AbortIntentRow extends Schema.Class<AbortIntentRow>('AbortIntentRow')(
218
+ rowFields.abortIntent,
219
+ ) {}
220
+
221
+ class WorkerStopRow extends Schema.Class<WorkerStopRow>('WorkerStopRow')({
222
+ thread_id: BoundedIdentifier,
223
+ terminal: Schema.NullOr(AssignmentTerminal),
224
+ }) {}
225
+
226
+ class MaxQueueSequenceRow extends Schema.Class<MaxQueueSequenceRow>('MaxQueueSequenceRow')({
227
+ max_queue_sequence: Schema.Int.check(Schema.isGreaterThanOrEqualTo(0)),
228
+ }) {}
229
+
230
+ const SUBMISSION_COLUMNS = `
231
+ submission_id,
232
+ thread_id,
233
+ queue_sequence,
234
+ principal,
235
+ idempotency_key,
236
+ agent_id,
237
+ deployment_id,
238
+ input_json,
239
+ input_digest,
240
+ receipt_id,
241
+ state,
242
+ settled_outcome,
243
+ settled_record_id,
244
+ finalized_at,
245
+ created_at,
246
+ ready_at,
247
+ input_applied_record_id,
248
+ input_applied_sequence,
249
+ joined_host_submission_id,
250
+ suspended_reason_json,
251
+ suspended_at,
252
+ unknown_reason,
253
+ unknown_tool_call_ids_json,
254
+ parent_submission_id,
255
+ parent_tool_call_id,
256
+ admission_group,
257
+ admission_fence_json,
258
+ worker_admission_json,
259
+ message_admission_json
260
+ `
261
+
262
+ const CHILD_RESERVATION_COLUMNS = `
263
+ reservation_id,
264
+ parent_submission_id,
265
+ parent_tool_call_id,
266
+ child_submission_id,
267
+ status,
268
+ allocation_json,
269
+ allocation_digest,
270
+ accounting_json,
271
+ reserved_at,
272
+ release_began_at,
273
+ released_at
274
+ `
275
+
276
+ /** The branded ToolCallId schema, reached through the thread port so no core import is needed. */
277
+ const ToolCallIdSchema = ApprovalDecisionCommand.fields.toolCallId
278
+ const ToolCallIdList = Schema.Array(ToolCallIdSchema)
279
+
280
+ const encodePersistedJsonText = Schema.encodeEffect(Schema.fromJsonString(PersistedJson))
281
+ const encodeDefinitionDigestsText = Schema.encodeEffect(Schema.fromJsonString(DefinitionDigests))
282
+ const decodeRecordEnvelopeText = Schema.decodeEffect(Schema.fromJsonString(RecordEnvelope))
283
+ const encodeSuspensionReasonText = Schema.encodeEffect(Schema.fromJsonString(SuspensionReason))
284
+ const encodeUnknownResolutionText = Schema.encodeEffect(Schema.fromJsonString(UnknownResolution))
285
+ const encodeToolCallIdsText = Schema.encodeEffect(Schema.fromJsonString(ToolCallIdList))
286
+ const decodeToolCallIdsText = Schema.decodeEffect(Schema.fromJsonString(ToolCallIdList))
287
+ const parseStoredJsonText = Schema.decodeEffect(Schema.fromJsonString(Schema.Json))
288
+ const decodeAdmissionResult = Schema.decodeUnknownEffect(AdmissionResult)
289
+ const decodeClaim = Schema.decodeUnknownEffect(Claim)
290
+ const decodeSettlement = Schema.decodeUnknownEffect(Settlement)
291
+ const decodeAbortIntent = Schema.decodeUnknownEffect(AbortIntent)
292
+ const decodeInputAppliedMarker = Schema.decodeUnknownEffect(InputAppliedMarker)
293
+
294
+ const decodeSubmissionSnapshotType = (input: SubmissionSnapshot) =>
295
+ SubmissionSnapshot.makeEffect(input).pipe(
296
+ Effect.mapError((issue) => new Schema.SchemaError(issue)),
297
+ )
298
+
299
+ const decodeSubmissionId = Schema.decodeUnknownEffect(SubmissionSnapshot.fields.submissionId)
300
+ const decodeQueueSequence = Schema.decodeUnknownEffect(QueueSequence)
301
+ const decodeUtcInstant = Schema.decodeUnknownEffect(Schema.DateTimeUtcFromString)
302
+ const decodeJoiningClaim = Schema.decodeUnknownEffect(JoiningClaim)
303
+ const decodeJoinSnapshot = Schema.decodeUnknownEffect(JoinSnapshot)
304
+ const decodeSuspensionSnapshot = Schema.decodeUnknownEffect(SuspensionSnapshot)
305
+ const decodeApprovalDecisionIntent = Schema.decodeUnknownEffect(ApprovalDecisionIntent)
306
+ const decodeUnknownResolutionIntent = Schema.decodeUnknownEffect(UnknownResolutionIntent)
307
+ const decodeParentLinkage = Schema.decodeUnknownEffect(ParentLinkage)
308
+
309
+ const decodeChildReservationSnapshotUnknown = Schema.decodeUnknownEffect(
310
+ ChildBudgetReservationSnapshot,
311
+ )
312
+
313
+ const decodeChildAttachmentSnapshot = Schema.decodeUnknownEffect(ChildAttachmentSnapshot)
314
+ const equivalentPersistedJson = Schema.toEquivalence(PersistedJson)
315
+ const equivalentUnknownResolution = Schema.toEquivalence(UnknownResolution)
316
+ const decodeAdmissionRequestType = Schema.decodeEffect(Schema.toType(AdmissionRequest))
317
+ const decodeSubmissionLookupType = Schema.decodeEffect(Schema.toType(SubmissionLookup))
318
+ const decodeClaimRequestType = Schema.decodeEffect(Schema.toType(ClaimRequest))
319
+
320
+ const decodeMarkInputAppliedRequestType = Schema.decodeEffect(
321
+ Schema.toType(MarkInputAppliedRequest),
322
+ )
323
+
324
+ const decodeSettlementFinalizationType = Schema.decodeEffect(Schema.toType(SettlementFinalization))
325
+ const decodeClaimJoiningRequestType = Schema.decodeEffect(Schema.toType(ClaimJoiningRequest))
326
+
327
+ const decodeAbortIntentRequestType = Schema.decodeEffect(Schema.toType(AbortIntentRequest))
328
+
329
+ const decodeRecoverySnapshotRequestType = Schema.decodeEffect(
330
+ Schema.toType(RecoverySnapshotRequest),
331
+ )
332
+
333
+ const SubmissionRows = Schema.Array(SubmissionRow)
334
+ const ChildReservationRows = Schema.Array(ChildReservationRow)
335
+ const MaxQueueSequenceRows = Schema.Array(MaxQueueSequenceRow)
336
+ const SubmissionWorkItems = Schema.Array(SubmissionWorkItem)
337
+ const decodeSubmissionWorkItems = Schema.decodeEffect(SubmissionWorkItems)
338
+ const equivalentWorkerOrigin = Schema.toEquivalence(Schema.optional(WorkerAdmission.fields.origin))
339
+
340
+ const decodeFirstWorkerAdmissions = Schema.decodeUnknownEffect(
341
+ Schema.Array(
342
+ Schema.Struct({
343
+ worker_admission_json: Schema.NullOr(BoundedStoredText),
344
+ }),
345
+ ),
346
+ )
347
+
348
+ const CanonicalSettlementRows = Schema.Array(
349
+ Schema.Struct({
350
+ batch_id: Schema.fromJsonString(BoundedIdentifier),
351
+ record_id: Schema.fromJsonString(BoundedIdentifier),
352
+ record_json: BoundedStoredText,
353
+ }),
354
+ )
355
+
356
+ const isDoStorageError = Schema.is(DoStorageError)
357
+
358
+ /** Wrap an adapter-internal failure into the port's LedgerError without erasing its tag. */
359
+ const internalFailure = (operation: string) => (error: { readonly message: string }): LedgerError =>
360
+ LedgerError.make({ operation, message: error.message, cause: error })
361
+
362
+ /**
363
+ * Classify raw SQL failures. Within one Durable Object there is exactly one writer, so the
364
+ * Node adapter's retryable `SqliteWriteContention` classification has no analogue: every raw
365
+ * failure is a `DoLedgerError` preserved as the LedgerError's cause.
366
+ */
367
+ const sqlFailure = (operation: string) => (error: SqlError.SqlError): LedgerError =>
368
+ internalFailure(operation)(
369
+ DoLedgerError.make({
370
+ cause: error,
371
+ operation,
372
+ message: error.message,
373
+ }),
374
+ )
375
+
376
+ const corruptionFailure = (operation: string, table: string, rowKey: string, message: string) =>
377
+ internalFailure(operation)(DoStorageCorruptionError.make({ table, rowKey, message }))
378
+
379
+ const submissionsRows = ownedRows(
380
+ SubmissionRow,
381
+ 'effect_agent_submissions',
382
+ (row) => row.submission_id,
383
+ 'submission_id',
384
+ [['thread_id', 'principal', 'idempotency_key']],
385
+ (sql) => sql`*, ${definitionJson(sql)} AS agent_digests_json`,
386
+ )
387
+
388
+ const abortsRows = ownedRows(
389
+ AbortIntentRow,
390
+ 'effect_agent_abort_intents',
391
+ (row) => row.submission_id,
392
+ 'submission_id',
393
+ )
394
+
395
+ const approvalsRows = ownedRows(
396
+ ApprovalDecisionRow,
397
+ 'effect_agent_approval_decisions',
398
+ (row) => JSON.stringify([row.submission_id, row.tool_call_id]),
399
+ )
400
+
401
+ const resolutionsRows = ownedRows(
402
+ UnknownResolutionRow,
403
+ 'effect_agent_unknown_resolutions',
404
+ (row) => JSON.stringify([row.submission_id, row.tool_call_id, row.resolution_kind]),
405
+ )
406
+
407
+ const childSettlementsRows = ownedRows(
408
+ ChildSettlementMarkerRow,
409
+ 'effect_agent_child_settlements',
410
+ (row) => JSON.stringify([row.parent_submission_id, row.child_submission_id]),
411
+ )
412
+
413
+ const childReservationsRows = ownedRows(
414
+ ChildReservationRow,
415
+ 'effect_agent_child_reservations',
416
+ (row) => row.reservation_id,
417
+ 'reservation_id',
418
+ )
419
+
420
+ const workerStopsRows = ownedRows(
421
+ WorkerStopRow,
422
+ 'effect_agent_worker_stops',
423
+ (row) => row.thread_id,
424
+ 'thread_id',
425
+ )
426
+
427
+ const submissionWorkRows = ownedRows(
428
+ SubmissionWorkRow,
429
+ 'effect_agent_submissions',
430
+ (row) => row.submission_id,
431
+ )
432
+
433
+ const makeServices = Effect.fnUntraced(function*() {
434
+ const progress = yield* SqlStorageProgress
435
+
436
+ const recordProgress = (kind: SqlStorageProgressKind, operation: string) =>
437
+ progress
438
+ .committed(kind)
439
+ .pipe(
440
+ Effect.catchCause((cause) => Effect.failCause(Cause.map(cause, internalFailure(operation)))),
441
+ )
442
+
443
+ const config = yield* DoStorageConfig
444
+ const failpoint = yield* DoStorageFailpoint
445
+ const sql = yield* SqlClientService.SqlClient
446
+ const crypto = yield* CryptoDigest.Digest
447
+ const random = yield* SecureRandom.SecureRandom
448
+ const physical = yield* makeCanonicalStorage()
449
+ const submissionColumns = sql`${sql.literal(SUBMISSION_COLUMNS)}, ${definitionJson(sql)} AS agent_digests_json`
450
+ const admissionFence = yield* SubmissionAdmissionFence
451
+ const journal = yield* initializeDoJournal(sql, failpoint.hit, config.maxStoredValueBytes)
452
+ const lifecycle = journal.lifecycle
453
+ const state = journal.state
454
+ const owner = state.owner
455
+ const submissionViews = submissionsRows(state, sql)
456
+ const workRows = submissionWorkRows(state, sql)
457
+
458
+ const rows = {
459
+ submissions: {
460
+ by: submissionViews.by,
461
+ byFields: submissionViews.byFields,
462
+ seed: submissionViews.seed,
463
+ // The same RETURNING rows update the full-row views and the small discovery index.
464
+ write: <E, R>(effect: Effect.Effect<ReadonlyArray<unknown>, E, R>) =>
465
+ submissionViews
466
+ .write(effect)
467
+ .pipe(Effect.tap((changed) => workRows.write(Effect.succeed(changed)))),
468
+ },
469
+ aborts: abortsRows(state, sql),
470
+ approvals: approvalsRows(state, sql),
471
+ resolutions: resolutionsRows(state, sql),
472
+ childSettlements: childSettlementsRows(state, sql),
473
+ childReservations: childReservationsRows(state, sql),
474
+ threads: journal.threads,
475
+ workerStops: workerStopsRows(state, sql),
476
+ }
477
+
478
+ const cached = <A>(
479
+ effect: Effect.Effect<A, SqlError.SqlError | DoStorageCorruptionError>,
480
+ operation: string,
481
+ ) => effect.pipe(Effect.mapError(internalFailure(operation)))
482
+
483
+ const byKey = Effect.fnUntraced(function*(
484
+ request: Pick<SubmissionLookupByKey, 'threadId' | 'principal' | 'idempotencyKey'>,
485
+ operation: string,
486
+ ) {
487
+ return yield* cached(
488
+ rows.submissions.byFields([
489
+ ['thread_id', request.threadId],
490
+ ['principal', request.principal],
491
+ ['idempotency_key', request.idempotencyKey],
492
+ ]),
493
+ operation,
494
+ )
495
+ }, state.read)
496
+
497
+ const retainLifecycle = (submission: SubmissionRow, fact: LifecyclePublicationFact) =>
498
+ lifecycle === undefined
499
+ ? Effect.void
500
+ : Effect.gen(function*() {
501
+ const ownerThreadId = yield* Schema.decodeEffect(SubmissionSnapshot.fields.threadId)(
502
+ submission.thread_id,
503
+ ).pipe(Effect.mapError(internalFailure('lifecycle owner')))
504
+
505
+ yield* lifecycle
506
+ .retain({ ownerThreadId, createdAt: yield* DateTime.now, fact })
507
+ .pipe(Effect.mapError(internalFailure('retain lifecycle publication')))
508
+ })
509
+
510
+ const retainWorkerSeal = (
511
+ threadId: string,
512
+ terminal: Extract<LifecyclePublicationFact, { readonly _tag: 'WorkerInboxSealed' }>['terminal'],
513
+ ) =>
514
+ lifecycle === undefined
515
+ ? Effect.void
516
+ : Effect.gen(function*() {
517
+ const operation = 'retain worker inbox seal'
518
+
519
+ const ownerThreadId = yield* Schema.decodeEffect(SubmissionSnapshot.fields.threadId)(
520
+ threadId,
521
+ ).pipe(Effect.mapError(internalFailure(operation)))
522
+
523
+ const active =
524
+ yield* sql`SELECT submission_id FROM effect_agent_submissions WHERE thread_id = ${threadId} AND state <> 'settled' ORDER BY queue_sequence`
525
+ .pipe(
526
+ Effect.mapError(sqlFailure(operation)),
527
+ )
528
+
529
+ const activeSubmissionIds = yield* Effect.forEach(active, (row) =>
530
+ decodeSubmissionId(row.submission_id).pipe(Effect.mapError(internalFailure(operation))))
531
+
532
+ yield* lifecycle
533
+ .retain({
534
+ id: JSON.stringify([threadId, 'inbox-sealed']),
535
+ ownerThreadId,
536
+ createdAt: yield* DateTime.now,
537
+ fact: {
538
+ _tag: 'WorkerInboxSealed',
539
+ threadId: ownerThreadId,
540
+ activeSubmissionIds,
541
+ terminal,
542
+ },
543
+ })
544
+ .pipe(Effect.mapError(internalFailure(operation)))
545
+ })
546
+
547
+ const hitFailpoint = (
548
+ location: DoStorageFailpointLocation,
549
+ operation: string,
550
+ ): Effect.Effect<void, LedgerError> =>
551
+ failpoint.hit(location).pipe(Effect.mapError((error) => internalFailure(operation)(error)))
552
+
553
+ /**
554
+ * Run one ledger mutation under the journal's Durable Object storage-backed transaction so
555
+ * ownership-token and epoch checks are atomic with their writes (DUR-006). Transaction
556
+ * failures surface as LedgerError carrying the typed `DoStorageError` as cause.
557
+ */
558
+ const inWriteTransaction = <
559
+ A,
560
+ E extends
561
+ | AdmissionConflict
562
+ | AdmissionPolicyError
563
+ | ApprovalConflict
564
+ | ChildReservationConflict
565
+ | JoinedToHost
566
+ | OwnershipLost
567
+ | SettlementConflict
568
+ | UnknownResolutionConflict
569
+ | LedgerError,
570
+ >(
571
+ operation: string,
572
+ effect: Effect.Effect<A, E>,
573
+ expected?: (error: { readonly _tag: string }) => boolean,
574
+ ): Effect.Effect<A, E | LedgerError> =>
575
+ journal
576
+ .withWriteTransaction(
577
+ operation,
578
+ expected,
579
+ )(effect)
580
+ .pipe(
581
+ Effect.mapError((error) => isDoStorageError(error) ? internalFailure(operation)(error) : error),
582
+ )
583
+
584
+ const mintUuid = () => random.uuidV7()
585
+
586
+ const currentInstant = Effect.map(Clock.currentTimeMillis, (millis) => ({
587
+ millis,
588
+ iso: new Date(millis).toISOString(),
589
+ }))
590
+
591
+ const decodeSubmissionRows = (operation: string, rowKey: string, rows: unknown) =>
592
+ decodeRows(SubmissionRows, 'effect_agent_submissions', rowKey, rows).pipe(
593
+ Effect.mapError(internalFailure(operation)),
594
+ )
595
+
596
+ const readSubmission = Effect.fnUntraced(function*(
597
+ operation: string,
598
+ submissionId: string,
599
+ ): Effect.fn.Return<Option.Option<SubmissionRow>, LedgerError> {
600
+ const found = yield* cached(rows.submissions.by('submission_id', submissionId), operation)
601
+
602
+ return Option.fromUndefinedOr(found[0])
603
+ })
604
+
605
+ const requireSubmission = Effect.fnUntraced(function*(
606
+ operation: string,
607
+ submissionId: string,
608
+ ): Effect.fn.Return<SubmissionRow, LedgerError> {
609
+ const submission = yield* readSubmission(operation, submissionId)
610
+
611
+ if (Option.isNone(submission)) {
612
+ return yield* LedgerError.make({
613
+ operation,
614
+ message: `Unknown submission ${submissionId}.`,
615
+ })
616
+ }
617
+
618
+ return submission.value
619
+ })
620
+
621
+ const requireOwner = Effect.fnUntraced(function*(
622
+ operation: string,
623
+ submission: SubmissionRow,
624
+ ): Effect.fn.Return<void, OwnershipLost | LedgerError> {
625
+ if (owner.hasOwner(submission.thread_id, submission.submission_id)) return
626
+
627
+ const submissionId = yield* decodeSubmissionId(submission.submission_id).pipe(
628
+ Effect.mapError(internalFailure(operation)),
629
+ )
630
+
631
+ return yield* OwnershipLost.make({ submissionId })
632
+ })
633
+
634
+ const submissions = new WeakMap<SubmissionRow, SubmissionSnapshot>()
635
+
636
+ const decodeSubmissionSnapshot = Effect.fnUntraced(function*(
637
+ operation: string,
638
+ row: SubmissionRow,
639
+ ): Effect.fn.Return<SubmissionSnapshot, LedgerError> {
640
+ const existing = submissions.get(row)
641
+
642
+ if (existing !== undefined) return existing
643
+
644
+ const decodeFailure = (error: Schema.SchemaError) =>
645
+ internalFailure(operation)(
646
+ DoStorageCorruptionError.make({
647
+ table: 'effect_agent_submissions',
648
+ rowKey: row.submission_id,
649
+ message: 'Stored submission does not satisfy the ledger schema',
650
+ diagnostic: ThreadStoreDiagnostic.make({
651
+ causeTag: error._tag,
652
+ operation,
653
+ decoder: 'SubmissionSnapshot',
654
+ issueTag: error.issue._tag,
655
+ }),
656
+ }),
657
+ )
658
+
659
+ if ((row.parent_submission_id === null) !== (row.parent_tool_call_id === null)) {
660
+ return yield* corruptionFailure(
661
+ operation,
662
+ 'effect_agent_submissions',
663
+ row.submission_id,
664
+ 'A parent linkage must record both the parent Submission and the parent Tool Call.',
665
+ )
666
+ }
667
+
668
+ const admission = yield* decodeAdmissionFact(row).pipe(Effect.mapError(decodeFailure))
669
+
670
+ const settledAt = row.finalized_at === null
671
+ ? undefined
672
+ : yield* decodeUtcInstant(row.finalized_at).pipe(Effect.mapError(decodeFailure))
673
+
674
+ const readyAt = row.ready_at === null
675
+ ? undefined
676
+ : yield* decodeUtcInstant(row.ready_at).pipe(Effect.mapError(decodeFailure))
677
+
678
+ const snapshot = yield* decodeSubmissionSnapshotType({
679
+ ...admission,
680
+ state: row.state,
681
+ ...(row.settled_outcome === null ? {} : { settledOutcome: row.settled_outcome }),
682
+ ...(settledAt === undefined ? {} : { settledAt }),
683
+ ...(row.settled_record_id === null ? {} : { settledRecordId: row.settled_record_id }),
684
+ ...(readyAt === undefined ? {} : { readyAt }),
685
+ }).pipe(Effect.mapError(decodeFailure))
686
+
687
+ submissions.set(row, snapshot)
688
+
689
+ return snapshot
690
+ })
691
+
692
+ const readCanonicalSettlement = Effect.fnUntraced(function*(
693
+ operation: string,
694
+ submission: SubmissionRow,
695
+ ) {
696
+ const expected = yield* decodeSubmissionSnapshot(operation, submission)
697
+ const recordId = submissionSettlementRecordId(expected.submissionId)
698
+
699
+ const found = yield* sql`SELECT ${recordBatchId(sql)} AS batch_id, record_id, ${
700
+ canonicalRecordJson(sql)
701
+ } AS record_json
702
+ FROM effect_agent_canonical_records WHERE thread_id = ${submission.thread_id}
703
+ AND record_id = ${JSON.stringify(recordId)}`.pipe(Effect.mapError(sqlFailure(operation)))
704
+
705
+ const decoded = yield* decodeRows(
706
+ CanonicalSettlementRows,
707
+ 'effect_agent_canonical_records',
708
+ recordId,
709
+ found,
710
+ ).pipe(Effect.mapError(internalFailure(operation)))
711
+
712
+ if (decoded.length === 0) return undefined
713
+ const row = decoded[0]
714
+
715
+ if (
716
+ decoded.length !== 1 ||
717
+ row.batch_id !== submissionSettlementBatchId(expected.submissionId) ||
718
+ row.record_id !== recordId
719
+ ) {
720
+ return yield* corruptionFailure(
721
+ operation,
722
+ 'effect_agent_canonical_records',
723
+ recordId,
724
+ 'Canonical settlement identity is inconsistent.',
725
+ )
726
+ }
727
+
728
+ const record = yield* decodeRecordEnvelopeText(row.record_json).pipe(
729
+ Effect.mapError(internalFailure(operation)),
730
+ )
731
+
732
+ const settlement = yield* validateCanonicalSettlement(record, expected)
733
+
734
+ return { record, settlement }
735
+ })
736
+
737
+ const readAbortIntent = Effect.fnUntraced(function*(
738
+ operation: string,
739
+ submissionId: string,
740
+ ): Effect.fn.Return<Option.Option<AbortIntentRow>, LedgerError> {
741
+ const found = yield* cached(rows.aborts.by('submission_id', submissionId), operation)
742
+
743
+ return Option.fromUndefinedOr(found[0])
744
+ })
745
+
746
+ /**
747
+ * Read the durable cross-store child-settlement markers recorded against one parent
748
+ * Submission (the DC realization of the port's "cross-store adapters record a durable
749
+ * notification marker" contract).
750
+ */
751
+ const readChildSettlementMarkers = Effect.fnUntraced(function*(
752
+ operation: string,
753
+ parentSubmissionId: string,
754
+ ): Effect.fn.Return<ReadonlyArray<ChildSettlementMarkerRow>, LedgerError> {
755
+ const found = yield* cached(
756
+ rows.childSettlements.by('parent_submission_id', parentSubmissionId),
757
+ operation,
758
+ )
759
+
760
+ return found.toSorted((a, b) =>
761
+ a.child_submission_id < b.child_submission_id
762
+ ? -1
763
+ : a.child_submission_id > b.child_submission_id
764
+ ? 1
765
+ : 0
766
+ )
767
+ })
768
+
769
+ /**
770
+ * Whether one listed child is provably settled from THIS store: either its own row lives
771
+ * here and is settled (single-store evidence, identical to the Node adapter), or a durable
772
+ * cross-store notification marker was recorded for it (the child's row lives in another
773
+ * Durable Object and its owner reported the settlement through `recordChildSettled`).
774
+ */
775
+ const childProvablySettled = Effect.fnUntraced(function*(
776
+ operation: string,
777
+ markerChildren: ReadonlySet<string>,
778
+ childSubmissionId: string,
779
+ ): Effect.fn.Return<boolean, LedgerError> {
780
+ if (markerChildren.has(childSubmissionId)) return true
781
+ const childRow = yield* readSubmission(operation, childSubmissionId)
782
+
783
+ return (
784
+ Option.isSome(childRow) &&
785
+ (yield* readCanonicalSettlement(operation, childRow.value)) !== undefined
786
+ )
787
+ })
788
+
789
+ const decodeChildReservationRows = (operation: string, rowKey: string, rows: unknown) =>
790
+ decodeRows(ChildReservationRows, 'effect_agent_child_reservations', rowKey, rows).pipe(
791
+ Effect.mapError(internalFailure(operation)),
792
+ )
793
+
794
+ const readChildReservation = Effect.fnUntraced(function*(
795
+ operation: string,
796
+ reservationId: string,
797
+ ): Effect.fn.Return<Option.Option<ChildReservationRow>, LedgerError> {
798
+ const rows = yield* sql<Record<string, unknown>>`
799
+ SELECT ${sql.literal(CHILD_RESERVATION_COLUMNS)}
800
+ FROM effect_agent_child_reservations
801
+ WHERE reservation_id = ${reservationId}
802
+ `.pipe(Effect.mapError(sqlFailure(operation)))
803
+
804
+ const decoded = yield* decodeChildReservationRows(operation, reservationId, rows)
805
+
806
+ if (decoded.length > 1) {
807
+ return yield* corruptionFailure(
808
+ operation,
809
+ 'effect_agent_child_reservations',
810
+ reservationId,
811
+ 'A child reservation primary key returned more than one row.',
812
+ )
813
+ }
814
+
815
+ return decoded.length === 0 ? Option.none() : Option.some(decoded[0])
816
+ })
817
+
818
+ const readChildReservationForCall = Effect.fnUntraced(function*(
819
+ operation: string,
820
+ parentSubmissionId: string,
821
+ parentToolCallId: string,
822
+ ): Effect.fn.Return<Option.Option<ChildReservationRow>, LedgerError> {
823
+ const rows = yield* sql<Record<string, unknown>>`
824
+ SELECT ${sql.literal(CHILD_RESERVATION_COLUMNS)}
825
+ FROM effect_agent_child_reservations
826
+ WHERE parent_submission_id = ${parentSubmissionId}
827
+ AND parent_tool_call_id = ${parentToolCallId}
828
+ `.pipe(Effect.mapError(sqlFailure(operation)))
829
+
830
+ const decoded = yield* decodeChildReservationRows(
831
+ operation,
832
+ `${parentSubmissionId}/${parentToolCallId}`,
833
+ rows,
834
+ )
835
+
836
+ if (decoded.length > 1) {
837
+ return yield* corruptionFailure(
838
+ operation,
839
+ 'effect_agent_child_reservations',
840
+ `${parentSubmissionId}/${parentToolCallId}`,
841
+ 'A parent Tool Call returned more than one child reservation.',
842
+ )
843
+ }
844
+
845
+ return decoded.length === 0 ? Option.none() : Option.some(decoded[0])
846
+ })
847
+
848
+ const childReservationSnapshotFromRow = Effect.fnUntraced(function*(
849
+ operation: string,
850
+ row: ChildReservationRow,
851
+ ): Effect.fn.Return<ChildBudgetReservationSnapshot, LedgerError> {
852
+ const rowFailure = (error: { readonly message: string }) =>
853
+ corruptionFailure(
854
+ operation,
855
+ 'effect_agent_child_reservations',
856
+ row.reservation_id,
857
+ error.message,
858
+ )
859
+
860
+ const allocation = yield* parseStoredJsonText(row.allocation_json).pipe(
861
+ Effect.mapError(rowFailure),
862
+ )
863
+
864
+ const accounting = row.accounting_json === null
865
+ ? undefined
866
+ : yield* parseStoredJsonText(row.accounting_json).pipe(Effect.mapError(rowFailure))
867
+
868
+ return yield* decodeChildReservationSnapshotUnknown({
869
+ reservationId: row.reservation_id,
870
+ parentSubmissionId: row.parent_submission_id,
871
+ parentToolCallId: row.parent_tool_call_id,
872
+ status: row.status,
873
+ allocation,
874
+ allocationDigest: row.allocation_digest,
875
+ reservedAt: row.reserved_at,
876
+ ...(row.child_submission_id === null ? {} : { childSubmissionId: row.child_submission_id }),
877
+ ...(accounting === undefined ? {} : { accounting }),
878
+ ...(row.release_began_at === null ? {} : { releaseBeganAt: row.release_began_at }),
879
+ ...(row.released_at === null ? {} : { releasedAt: row.released_at }),
880
+ }).pipe(Effect.mapError(rowFailure))
881
+ })
882
+
883
+ const readApprovalDecisions = Effect.fnUntraced(function*(
884
+ operation: string,
885
+ submissionId: string,
886
+ ): Effect.fn.Return<ReadonlyArray<ApprovalDecisionRow>, LedgerError> {
887
+ const found = yield* cached(rows.approvals.by('submission_id', submissionId), operation)
888
+
889
+ return found.toSorted((a, b) => a.tool_call_id < b.tool_call_id ? -1 : a.tool_call_id > b.tool_call_id ? 1 : 0)
890
+ })
891
+
892
+ const approvalIntentFromRow = (
893
+ operation: string,
894
+ row: ApprovalDecisionRow,
895
+ ): Effect.Effect<ApprovalDecisionIntent, LedgerError> =>
896
+ decodeApprovalFact(row).pipe(
897
+ Effect.mapError((error) =>
898
+ corruptionFailure(
899
+ operation,
900
+ 'effect_agent_approval_decisions',
901
+ `${row.submission_id}/${row.tool_call_id}`,
902
+ error.message,
903
+ )
904
+ ),
905
+ )
906
+
907
+ const readUnknownResolutions = Effect.fnUntraced(function*(
908
+ operation: string,
909
+ submissionId: string,
910
+ ): Effect.fn.Return<ReadonlyArray<UnknownResolutionRow>, LedgerError> {
911
+ const found = yield* cached(rows.resolutions.by('submission_id', submissionId), operation)
912
+
913
+ return found.toSorted((a, b) => a.tool_call_id < b.tool_call_id ? -1 : a.tool_call_id > b.tool_call_id ? 1 : 0)
914
+ })
915
+
916
+ const unknownResolutionIntentFromRow = Effect.fnUntraced(function*(
917
+ operation: string,
918
+ row: UnknownResolutionRow,
919
+ ): Effect.fn.Return<UnknownResolutionIntent, LedgerError> {
920
+ return yield* decodeResolutionFact(row).pipe(
921
+ Effect.mapError((error) =>
922
+ corruptionFailure(
923
+ operation,
924
+ 'effect_agent_unknown_resolutions',
925
+ `${row.submission_id}/${row.tool_call_id}`,
926
+ error.message,
927
+ )
928
+ ),
929
+ )
930
+ })
931
+
932
+ /** The Submission's marked-unknown open Tool Call identities, empty when never marked. */
933
+ const storedUnknownToolCallIds = Effect.fnUntraced(function*(
934
+ operation: string,
935
+ submission: SubmissionRow,
936
+ ): Effect.fn.Return<ReadonlyArray<typeof ToolCallIdSchema.Type>, LedgerError> {
937
+ if (submission.unknown_tool_call_ids_json === null) return []
938
+
939
+ return yield* decodeToolCallIdsText(submission.unknown_tool_call_ids_json).pipe(
940
+ Effect.mapError((error) =>
941
+ corruptionFailure(
942
+ operation,
943
+ 'effect_agent_submissions',
944
+ submission.submission_id,
945
+ error.message,
946
+ )
947
+ ),
948
+ )
949
+ })
950
+
951
+ /**
952
+ * Canonical history is the abort authority (DUR-015): the intent's canonicalRecordId is
953
+ * derived from the shared canonical-records table using the deterministic abort record
954
+ * identity, never from a cached ledger marker.
955
+ */
956
+ const canonicalAbortRecordId = Effect.fnUntraced(function*(
957
+ operation: string,
958
+ threadId: string,
959
+ submissionId: SubmissionId,
960
+ ): Effect.fn.Return<AbortIntent['canonicalRecordId'], LedgerError> {
961
+ const recordId = submissionAbortRecordId(submissionId)
962
+
963
+ const present = yield* journal
964
+ .hasRecord(threadId, recordId)
965
+ .pipe(Effect.mapError(internalFailure(operation)))
966
+
967
+ return present ? recordId : undefined
968
+ })
969
+
970
+ const abortIntentFromRow = Effect.fnUntraced(function*(
971
+ operation: string,
972
+ submission: SubmissionRow,
973
+ submissionId: SubmissionId,
974
+ row: AbortIntentRow,
975
+ ): Effect.fn.Return<AbortIntent, LedgerError> {
976
+ const canonicalRecordId = yield* canonicalAbortRecordId(
977
+ operation,
978
+ submission.thread_id,
979
+ submissionId,
980
+ )
981
+
982
+ const fact = yield* decodeAbortFact(row).pipe(
983
+ Effect.mapError((error) =>
984
+ corruptionFailure(
985
+ operation,
986
+ 'effect_agent_abort_intents',
987
+ row.submission_id,
988
+ error.message,
989
+ )
990
+ ),
991
+ )
992
+
993
+ return AbortIntent.make({
994
+ ...fact,
995
+ ...(canonicalRecordId === undefined ? {} : { canonicalRecordId }),
996
+ })
997
+ })
998
+
999
+ // Durable Object storage is the single serialized owner: writes confirm through output
1000
+ // gates before any response is observable, which is exactly the single-owner crash
1001
+ // durability this adapter claims — under its own honest label (P7 WP0).
1002
+ const capabilities = Effect.succeed(
1003
+ LedgerCapabilities.make({ durability: 'durable-cloudflare' }),
1004
+ )
1005
+
1006
+ const admit: SubmissionLedger['Service']['admit'] = Effect.fnUntraced(function*(
1007
+ request: AdmissionRequest,
1008
+ options?: { readonly readyIfInitialized?: boolean },
1009
+ ) {
1010
+ const operation = 'ledger admit'
1011
+
1012
+ const validated = yield* decodeAdmissionRequestType(request).pipe(
1013
+ Effect.mapError(internalFailure(operation)),
1014
+ )
1015
+
1016
+ const inputJson = yield* encodePersistedJsonText(validated.inputPayload).pipe(
1017
+ Effect.mapError(internalFailure(operation)),
1018
+ )
1019
+
1020
+ // The platform's ~2 MB per-value bound, refused typed BEFORE any durable mutation
1021
+ // (resource-limits gate; oversized payloads are the designed R2 overflow path).
1022
+ yield* journal
1023
+ .checkValueBound(operation, inputJson)
1024
+ .pipe(Effect.mapError(internalFailure(operation)))
1025
+
1026
+ const workerAdmissionJson = validated.workerAdmission === undefined
1027
+ ? null
1028
+ : yield* Schema.encodeEffect(Schema.fromJsonString(WorkerAdmission))(
1029
+ validated.workerAdmission,
1030
+ ).pipe(Effect.mapError(internalFailure(operation)))
1031
+
1032
+ if (
1033
+ workerAdmissionJson !== null &&
1034
+ new TextEncoder().encode(workerAdmissionJson).byteLength > config.maxStoredValueBytes
1035
+ ) {
1036
+ return yield* LedgerError.make({
1037
+ operation,
1038
+ message: 'Worker admission metadata exceeds the stored value bound',
1039
+ })
1040
+ }
1041
+
1042
+ const messageAdmissionJson = validated.messageAdmission === undefined
1043
+ ? null
1044
+ : yield* Schema.encodeEffect(Schema.fromJsonString(InputMessage))(
1045
+ validated.messageAdmission,
1046
+ ).pipe(Effect.mapError(internalFailure(operation)))
1047
+
1048
+ if (
1049
+ messageAdmissionJson !== null &&
1050
+ new TextEncoder().encode(messageAdmissionJson).byteLength > config.maxStoredValueBytes
1051
+ ) {
1052
+ return yield* LedgerError.make({
1053
+ operation,
1054
+ message: 'Message admission metadata exceeds the stored value bound',
1055
+ })
1056
+ }
1057
+
1058
+ const agentDigestsJson = yield* encodeDefinitionDigestsText(validated.agentDigests).pipe(
1059
+ Effect.mapError(internalFailure(operation)),
1060
+ )
1061
+
1062
+ // Routable Submission identity (D-P6-5): `{uuidv7}:{threadId}`. The cross-DO
1063
+ // routing layer parses ITS OWN minted format (split at the first ":") to address
1064
+ // submissionId-only operations to the owning Thread Object; the id stays opaque
1065
+ // to every other component, exactly like DN's `submission-{uuid}` prefix.
1066
+ const mintedSubmissionId = `${yield* mintUuid()}:${validated.threadId}`
1067
+
1068
+ if (mintedSubmissionId.length > MAX_IDENTIFIER_LENGTH) {
1069
+ return yield* LedgerError.make({
1070
+ operation,
1071
+ message: `A routable Submission identity of ${mintedSubmissionId.length} characters exceeds ` +
1072
+ `the ${MAX_IDENTIFIER_LENGTH}-character ledger row bound; shorten the Thread identity.`,
1073
+ })
1074
+ }
1075
+ const mintedReceiptId = `receipt-${yield* mintUuid()}`
1076
+
1077
+ yield* hitFailpoint('ledger:admit:before', operation)
1078
+
1079
+ const result = yield* inWriteTransaction(
1080
+ operation,
1081
+ Effect.gen(function*() {
1082
+ const keyRowKey = `${validated.threadId}/${validated.principal}/${validated.idempotencyKey}`
1083
+
1084
+ const existing = yield* byKey(validated, operation)
1085
+
1086
+ if (existing.length > 1) {
1087
+ return yield* corruptionFailure(
1088
+ operation,
1089
+ 'effect_agent_submissions',
1090
+ keyRowKey,
1091
+ 'An admission idempotency key returned more than one row.',
1092
+ )
1093
+ }
1094
+ if (existing.length === 1) {
1095
+ // A replay must repeat the exact canonical input AND the exact parent linkage (or
1096
+ // its absence): linkage is immutable child lineage (spec §12 step 5, SUB-016).
1097
+ const sameLinkage = validated.parentLinkage === undefined
1098
+ ? existing[0].parent_submission_id === null &&
1099
+ existing[0].parent_tool_call_id === null
1100
+ : existing[0].parent_submission_id === validated.parentLinkage.parentSubmissionId &&
1101
+ existing[0].parent_tool_call_id === validated.parentLinkage.parentToolCallId
1102
+
1103
+ if (existing[0].input_digest !== validated.inputDigest || !sameLinkage) {
1104
+ return yield* AdmissionConflict.make({
1105
+ threadId: validated.threadId,
1106
+ principal: validated.principal,
1107
+ idempotencyKey: validated.idempotencyKey,
1108
+ existingInputDigest: existing[0].input_digest,
1109
+ attemptedInputDigest: validated.inputDigest,
1110
+ })
1111
+ }
1112
+
1113
+ const retainedWorkerAdmission = existing[0].worker_admission_json === null
1114
+ ? undefined
1115
+ : yield* Schema.decodeEffect(Schema.fromJsonString(WorkerAdmission))(
1116
+ existing[0].worker_admission_json,
1117
+ ).pipe(Effect.mapError(internalFailure(operation)))
1118
+
1119
+ const retainedInputMessage = existing[0].message_admission_json === null
1120
+ ? undefined
1121
+ : yield* Schema.decodeEffect(Schema.fromJsonString(InputMessage))(
1122
+ existing[0].message_admission_json,
1123
+ ).pipe(Effect.mapError(internalFailure(operation)))
1124
+
1125
+ const retainedFence = existing[0].admission_fence_json === null
1126
+ ? undefined
1127
+ : yield* Schema.decodeEffect(Schema.fromJsonString(AdmissionFence))(
1128
+ existing[0].admission_fence_json,
1129
+ ).pipe(Effect.mapError(internalFailure(operation)))
1130
+
1131
+ if (
1132
+ (existing[0].admission_group ?? undefined) !== validated.admissionGroup ||
1133
+ !Schema.toEquivalence(Schema.optional(WorkerAdmission))(
1134
+ retainedWorkerAdmission,
1135
+ validated.workerAdmission,
1136
+ ) ||
1137
+ !Schema.toEquivalence(Schema.optional(InputMessage))(
1138
+ retainedInputMessage,
1139
+ validated.messageAdmission,
1140
+ ) ||
1141
+ !Schema.toEquivalence(Schema.optional(AdmissionFence))(
1142
+ retainedFence,
1143
+ validated.admissionFence,
1144
+ )
1145
+ ) {
1146
+ return yield* AdmissionConflict.make({
1147
+ threadId: validated.threadId,
1148
+ principal: validated.principal,
1149
+ idempotencyKey: validated.idempotencyKey,
1150
+ existingInputDigest: existing[0].input_digest,
1151
+ attemptedInputDigest: validated.inputDigest,
1152
+ })
1153
+ }
1154
+
1155
+ return yield* decodeAdmissionResult({
1156
+ submissionId: existing[0].submission_id,
1157
+ receiptId: existing[0].receipt_id,
1158
+ queueSequence: existing[0].queue_sequence,
1159
+ state: existing[0].state,
1160
+ replayed: true,
1161
+ }).pipe(Effect.mapError(internalFailure(operation)))
1162
+ }
1163
+
1164
+ if (!admissionFitsTransfer(validated.threadId, validated)) {
1165
+ return yield* LedgerError.make({
1166
+ operation,
1167
+ message: 'Admission exceeds the complete transfer page byte bound',
1168
+ })
1169
+ }
1170
+
1171
+ const stopped = yield* cached(
1172
+ rows.workerStops.by('thread_id', validated.threadId),
1173
+ operation,
1174
+ )
1175
+
1176
+ if (stopped.length > 0) {
1177
+ return yield* AdmissionPolicyError.make({ reason: 'refused', code: 'worker-stopped' })
1178
+ }
1179
+
1180
+ // The first accepted input fixes ordinary/worker lane identity atomically with admission.
1181
+ // Canonical origin materialization can lag admission; a log scan cannot fence that race.
1182
+ const firstRows = yield* sql<Record<string, unknown>>`
1183
+ SELECT worker_admission_json FROM effect_agent_submissions
1184
+ WHERE thread_id=${validated.threadId} ORDER BY queue_sequence LIMIT 1
1185
+ `.pipe(Effect.mapError(sqlFailure(operation)))
1186
+
1187
+ const first = yield* decodeFirstWorkerAdmissions(firstRows).pipe(
1188
+ Effect.mapError(internalFailure(operation)),
1189
+ )
1190
+
1191
+ if (first[0] !== undefined) {
1192
+ const previous = first[0].worker_admission_json === null
1193
+ ? undefined
1194
+ : yield* Schema.decodeEffect(Schema.fromJsonString(WorkerAdmission))(
1195
+ first[0].worker_admission_json,
1196
+ ).pipe(Effect.mapError(internalFailure(operation)))
1197
+
1198
+ if (!equivalentWorkerOrigin(previous?.origin, validated.workerAdmission?.origin)) {
1199
+ return yield* AdmissionPolicyError.make({
1200
+ reason: 'refused',
1201
+ code: 'worker-origin-conflict',
1202
+ })
1203
+ }
1204
+ }
1205
+
1206
+ yield* admissionFence.check(validated)
1207
+ if (validated.admissionGroup !== undefined) {
1208
+ const occupied = yield* sql<Record<string, unknown>>`
1209
+ SELECT submission_id FROM effect_agent_submissions
1210
+ WHERE thread_id=${validated.threadId} AND admission_group=${validated.admissionGroup} AND state<>'settled' LIMIT 1
1211
+ `.pipe(Effect.mapError(sqlFailure(operation)))
1212
+
1213
+ if (occupied.length > 0) {
1214
+ return yield* AdmissionPolicyError.make({
1215
+ reason: 'occupied',
1216
+ code: 'admission-group',
1217
+ })
1218
+ }
1219
+ }
1220
+
1221
+ const maxRows = yield* sql<Record<string, unknown>>`
1222
+ SELECT COALESCE(MAX(queue_sequence), 0) AS max_queue_sequence
1223
+ FROM effect_agent_submissions
1224
+ WHERE thread_id = ${validated.threadId}
1225
+ `.pipe(Effect.mapError(sqlFailure(operation)))
1226
+
1227
+ const decodedMax = yield* decodeRows(
1228
+ MaxQueueSequenceRows,
1229
+ 'effect_agent_submissions',
1230
+ validated.threadId,
1231
+ maxRows,
1232
+ ).pipe(Effect.mapError(internalFailure(operation)))
1233
+
1234
+ const queueSequence = yield* decodeQueueSequence(
1235
+ (decodedMax[0]?.max_queue_sequence ?? 0) + 1,
1236
+ ).pipe(Effect.mapError(internalFailure(operation)))
1237
+
1238
+ const now = yield* currentInstant
1239
+
1240
+ // The first canonical record is ThreadCreated. This is the same positive-tail proof
1241
+ // used by ensureThreadCreated, captured under this admission's owner transaction.
1242
+ const ready = options?.readyIfInitialized === true &&
1243
+ validated.workerAdmission === undefined &&
1244
+ (yield* journal
1245
+ .getThread(validated.threadId)
1246
+ .pipe(Effect.mapError(internalFailure(operation)))).some(
1247
+ (thread) => thread.tail_sequence > 0,
1248
+ )
1249
+
1250
+ yield* sql`
1251
+ INSERT INTO effect_agent_submissions (
1252
+ submission_id,
1253
+ thread_id,
1254
+ queue_sequence,
1255
+ principal,
1256
+ idempotency_key,
1257
+ agent_id,
1258
+ definition_key,
1259
+ deployment_id,
1260
+ input_json,
1261
+ input_digest,
1262
+ receipt_id,
1263
+ state,
1264
+ created_at,
1265
+ ready_at,
1266
+ parent_submission_id,
1267
+ parent_tool_call_id,
1268
+ admission_group,
1269
+ admission_fence_json,
1270
+ worker_admission_json,
1271
+ message_admission_json
1272
+ ) VALUES (
1273
+ ${mintedSubmissionId},
1274
+ ${validated.threadId},
1275
+ ${queueSequence},
1276
+ ${validated.principal},
1277
+ ${validated.idempotencyKey},
1278
+ ${validated.agentId},
1279
+ ${yield* physical.definition(agentDigestsJson).pipe(Effect.mapError(internalFailure(operation)))},
1280
+ ${validated.deploymentId},
1281
+ ${inputJson},
1282
+ ${validated.inputDigest},
1283
+ ${mintedReceiptId},
1284
+ ${ready ? 'ready' : 'admitted'},
1285
+ ${now.iso},
1286
+ ${ready ? now.iso : null},
1287
+ ${validated.parentLinkage?.parentSubmissionId ?? null},
1288
+ ${validated.parentLinkage?.parentToolCallId ?? null},
1289
+ ${validated.admissionGroup ?? null},
1290
+ ${validated.admissionFence === undefined ? null : JSON.stringify(validated.admissionFence)},
1291
+ ${workerAdmissionJson},
1292
+ ${messageAdmissionJson}
1293
+ )
1294
+ RETURNING *, ${definitionJson(sql)} AS agent_digests_json`.pipe(
1295
+ rows.submissions.write,
1296
+ Effect.mapError(internalFailure(operation)),
1297
+ )
1298
+
1299
+ if (queueSequence === 1) {
1300
+ const threads = yield* journal
1301
+ .getThread(validated.threadId)
1302
+ .pipe(Effect.mapError(internalFailure(operation)))
1303
+
1304
+ if (threads.length === 0) {
1305
+ yield* journal.work
1306
+ .initialize(validated.threadId)
1307
+ .pipe(Effect.mapError(internalFailure(operation)))
1308
+ }
1309
+ }
1310
+
1311
+ // The INSERT (never replay or hydration) proves these new submission-owned sets
1312
+ // empty. Gated writes update them; rollback/invalidation discards that proof.
1313
+ // MAX(queue_sequence) and this insert share the transaction: no later row exists.
1314
+ // Every matching admission invalidates this complete empty suffix before readiness.
1315
+ submissionViews.seedMatching(
1316
+ JSON.stringify(['joining-suffix', validated.threadId, queueSequence]),
1317
+ (row) => row.thread_id === validated.threadId && row.queue_sequence > queueSequence,
1318
+ [],
1319
+ 0,
1320
+ )
1321
+ rows.aborts.seed('submission_id', mintedSubmissionId, [])
1322
+ rows.submissions.seed('joined_host_submission_id', mintedSubmissionId, [])
1323
+ rows.approvals.seed('submission_id', mintedSubmissionId, [])
1324
+ rows.resolutions.seed('submission_id', mintedSubmissionId, [])
1325
+ rows.childReservations.seed('parent_submission_id', mintedSubmissionId, [])
1326
+ rows.childSettlements.seed('parent_submission_id', mintedSubmissionId, [])
1327
+
1328
+ yield* recordProgress('submission', operation)
1329
+
1330
+ const admitted = yield* decodeAdmissionResult({
1331
+ submissionId: mintedSubmissionId,
1332
+ receiptId: mintedReceiptId,
1333
+ queueSequence,
1334
+ state: ready ? 'ready' : 'admitted',
1335
+ replayed: false,
1336
+ }).pipe(Effect.mapError(internalFailure(operation)))
1337
+
1338
+ if (ready && lifecycle !== undefined) {
1339
+ yield* retainLifecycle(yield* requireSubmission(operation, mintedSubmissionId), {
1340
+ _tag: 'SubmissionReady',
1341
+ submissionId: admitted.submissionId,
1342
+ })
1343
+ }
1344
+
1345
+ return admitted
1346
+ }),
1347
+ )
1348
+
1349
+ yield* hitFailpoint('ledger:admit:after', operation)
1350
+
1351
+ return result
1352
+ })
1353
+
1354
+ const markReady: SubmissionLedger['Service']['markReady'] = Effect.fnUntraced(function*(
1355
+ request: MarkReadyRequest,
1356
+ ) {
1357
+ const operation = 'ledger mark ready'
1358
+
1359
+ const validated = yield* Schema.decodeEffect(Schema.toType(MarkReadyRequest))(request).pipe(
1360
+ Effect.mapError(internalFailure(operation)),
1361
+ )
1362
+
1363
+ yield* hitFailpoint('ledger:mark-ready:before', operation)
1364
+ yield* inWriteTransaction(
1365
+ operation,
1366
+ Effect.gen(function*() {
1367
+ const submission = yield* requireSubmission(operation, validated.submissionId)
1368
+
1369
+ if (submission.state !== 'admitted') return
1370
+ const now = yield* currentInstant
1371
+
1372
+ yield* sql`
1373
+ UPDATE effect_agent_submissions
1374
+ SET state = 'ready', ready_at = ${now.iso}
1375
+ WHERE submission_id = ${validated.submissionId}
1376
+ RETURNING *, ${definitionJson(sql)} AS agent_digests_json`.pipe(
1377
+ rows.submissions.write,
1378
+ Effect.mapError(internalFailure(operation)),
1379
+ )
1380
+ yield* recordProgress('submission', operation)
1381
+ yield* retainLifecycle(submission, {
1382
+ _tag: 'SubmissionReady',
1383
+ submissionId: validated.submissionId,
1384
+ })
1385
+ }),
1386
+ )
1387
+ yield* hitFailpoint('ledger:mark-ready:after', operation)
1388
+ })
1389
+
1390
+ const resolveFundingOwner: NonNullable<SubmissionLedger['Service']['resolveFundingOwner']> = Effect.fnUntraced(
1391
+ function*(input) {
1392
+ const operation = 'resolve funding owner'
1393
+
1394
+ const request = yield* Schema.decodeEffect(FundingOwnerRequest)(input).pipe(
1395
+ Effect.mapError(internalFailure(operation)),
1396
+ )
1397
+
1398
+ const selected = yield* requireSubmission(operation, request.submissionId)
1399
+
1400
+ if (selected.thread_id !== request.threadId) {
1401
+ return yield* LedgerError.make({
1402
+ operation,
1403
+ message: 'Selected funding input belongs to another Thread.',
1404
+ })
1405
+ }
1406
+ if (selected.state === 'joining') {
1407
+ return yield* LedgerError.make({
1408
+ operation,
1409
+ message: 'Selected funding input is still joining; retry after durable binding.',
1410
+ })
1411
+ }
1412
+ const hostId = selected.joined_host_submission_id
1413
+
1414
+ if (hostId === null && selected.state === 'joined') {
1415
+ return yield* corruptionFailure(
1416
+ operation,
1417
+ 'effect_agent_submissions',
1418
+ selected.submission_id,
1419
+ 'Joined input has no stable host identity.',
1420
+ )
1421
+ }
1422
+ if (hostId !== null && selected.state !== 'joined' && selected.state !== 'settled') {
1423
+ return yield* corruptionFailure(
1424
+ operation,
1425
+ 'effect_agent_submissions',
1426
+ selected.submission_id,
1427
+ 'Host linkage is inconsistent with selected input state.',
1428
+ )
1429
+ }
1430
+ const owner = hostId === null ? selected : yield* requireSubmission(operation, hostId)
1431
+
1432
+ if (
1433
+ owner.thread_id !== request.threadId ||
1434
+ (hostId !== null &&
1435
+ (owner.submission_id === selected.submission_id ||
1436
+ owner.joined_host_submission_id !== null ||
1437
+ owner.state === 'joining' ||
1438
+ owner.state === 'joined' ||
1439
+ owner.queue_sequence >= selected.queue_sequence))
1440
+ ) {
1441
+ return yield* corruptionFailure(
1442
+ operation,
1443
+ 'effect_agent_submissions',
1444
+ selected.submission_id,
1445
+ 'Funding host is not a stable earlier input in this Thread.',
1446
+ )
1447
+ }
1448
+
1449
+ return yield* Schema.decodeEffect(Schema.toType(FundingOwner))({
1450
+ selected: yield* decodeSubmissionSnapshot(operation, selected),
1451
+ owner: yield* decodeSubmissionSnapshot(operation, owner),
1452
+ }).pipe(Effect.mapError(internalFailure(operation)))
1453
+ },
1454
+ state.read,
1455
+ )
1456
+
1457
+ const lookup: SubmissionLedger['Service']['lookup'] = Effect.fnUntraced(function*(
1458
+ request: SubmissionLookup,
1459
+ ) {
1460
+ const operation = 'ledger lookup'
1461
+
1462
+ const validated = yield* decodeSubmissionLookupType(request).pipe(
1463
+ Effect.mapError(internalFailure(operation)),
1464
+ )
1465
+
1466
+ if (validated._tag === 'SubmissionLookupById') {
1467
+ const row = yield* readSubmission(operation, validated.submissionId)
1468
+
1469
+ if (Option.isNone(row)) return Option.none()
1470
+
1471
+ return Option.some(yield* decodeSubmissionSnapshot(operation, row.value))
1472
+ }
1473
+
1474
+ const decoded = yield* byKey(validated, operation)
1475
+
1476
+ if (decoded.length > 1) {
1477
+ return yield* corruptionFailure(
1478
+ operation,
1479
+ 'effect_agent_submissions',
1480
+ `${validated.threadId}/${validated.principal}/${validated.idempotencyKey}`,
1481
+ 'An admission idempotency key returned more than one row.',
1482
+ )
1483
+ }
1484
+ if (decoded.length === 0) return Option.none()
1485
+
1486
+ return Option.some(yield* decodeSubmissionSnapshot(operation, decoded[0]))
1487
+ })
1488
+
1489
+ // This LOCAL facet is the authoritative owner of every Thread stored in this Durable
1490
+ // Object, so the key-scoped read IS the admission truth and the tri-state degenerates to
1491
+ // NotAdmitted or Admitted (SUB-031). `AdmissionIndeterminate` becomes real one layer out:
1492
+ // the WP2 routed decorator answers it when the OWNING Durable Object is unreachable.
1493
+ const resolveAdmission: SubmissionLedger['Service']['resolveAdmission'] = Effect.fnUntraced(
1494
+ function*(request: SubmissionLookupByKey) {
1495
+ const operation = 'ledger resolve admission'
1496
+
1497
+ const validated = yield* Schema.decodeEffect(Schema.toType(SubmissionLookupByKey))(
1498
+ request,
1499
+ ).pipe(Effect.mapError(internalFailure(operation)))
1500
+
1501
+ const decoded = yield* byKey(validated, operation)
1502
+
1503
+ if (decoded.length > 1) {
1504
+ return yield* corruptionFailure(
1505
+ operation,
1506
+ 'effect_agent_submissions',
1507
+ `${validated.threadId}/${validated.principal}/${validated.idempotencyKey}`,
1508
+ 'An admission idempotency key returned more than one row.',
1509
+ )
1510
+ }
1511
+ if (decoded.length === 0) return AdmissionNotAdmitted.make()
1512
+
1513
+ return AdmissionAdmitted.make({
1514
+ submission: yield* decodeSubmissionSnapshot(operation, decoded[0]),
1515
+ })
1516
+ },
1517
+ )
1518
+
1519
+ const selectHead: SubmissionLedger['Service']['selectHead'] = Effect.fn(
1520
+ 'DoSubmissionLedger.selectHead',
1521
+ )(function*(request: ClaimRequest) {
1522
+ const operation = 'ledger select head'
1523
+
1524
+ const validated = yield* decodeClaimRequestType(request).pipe(
1525
+ Effect.mapError(internalFailure(operation)),
1526
+ )
1527
+
1528
+ const attemptId = `attempt-${yield* mintUuid()}`
1529
+
1530
+ yield* hitFailpoint('ledger:claim:before', operation)
1531
+
1532
+ const claimed = yield* owner.withMutation(
1533
+ Effect.gen(function*() {
1534
+ if (owner.hasOwner(validated.threadId)) return Option.none<Claim>()
1535
+
1536
+ const active = yield* activeNonterminal
1537
+ const heads: Array<SubmissionRow> = []
1538
+
1539
+ const limit = validated.handoff === undefined ? 1 : validated.handoff.deferredSubmissionIds.length + 1
1540
+
1541
+ if (active.length <= 128) {
1542
+ const candidates = active
1543
+ .filter((row) => row.thread_id === validated.threadId)
1544
+ .sort((left, right) => left.queue_sequence - right.queue_sequence)
1545
+
1546
+ for (const candidate of candidates) {
1547
+ if (
1548
+ candidate.state === 'unknown' &&
1549
+ Option.isNone(yield* readAbortIntent(operation, candidate.submission_id))
1550
+ ) {
1551
+ continue
1552
+ }
1553
+ heads.push(yield* requireSubmission(operation, candidate.submission_id))
1554
+ if (heads.length === limit) break
1555
+ }
1556
+ } else {
1557
+ const headRows = yield* sql<Record<string, unknown>>`
1558
+ SELECT ${submissionColumns}
1559
+ FROM effect_agent_submissions
1560
+ WHERE thread_id = ${validated.threadId}
1561
+ AND state <> 'settled'
1562
+ AND (
1563
+ state <> 'unknown' OR EXISTS (
1564
+ SELECT 1 FROM effect_agent_abort_intents
1565
+ WHERE submission_id = effect_agent_submissions.submission_id
1566
+ )
1567
+ )
1568
+ ORDER BY queue_sequence ASC
1569
+ LIMIT ${validated.handoff === undefined ? 1 : validated.handoff.deferredSubmissionIds.length + 1}
1570
+ `.pipe(Effect.mapError(sqlFailure(operation)))
1571
+
1572
+ heads.push(...(yield* decodeSubmissionRows(operation, validated.threadId, headRows)))
1573
+ }
1574
+
1575
+ if (heads.length === 0) return Option.none<Claim>()
1576
+ let head = heads[0]
1577
+
1578
+ if (validated.handoff !== undefined) {
1579
+ const handoff = validated.handoff
1580
+
1581
+ for (const candidate of heads) {
1582
+ if (candidate.submission_id === handoff.submissionId) {
1583
+ head = candidate
1584
+ break
1585
+ }
1586
+ if (
1587
+ !handoff.deferredSubmissionIds.some((id) => id === candidate.submission_id) ||
1588
+ candidate.state !== 'input-applied' ||
1589
+ Option.isSome(yield* readAbortIntent(operation, candidate.submission_id))
1590
+ ) {
1591
+ return Option.none<Claim>()
1592
+ }
1593
+ }
1594
+ if (
1595
+ head.submission_id !== handoff.submissionId ||
1596
+ (head.state !== 'ready' && head.state !== 'input-applied')
1597
+ ) {
1598
+ return Option.none<Claim>()
1599
+ }
1600
+ }
1601
+
1602
+ // Approval/delegation suspension and joined work retain their queue barrier.
1603
+ // Unknown work with an abort intent is selected for cleanup without Tool replay.
1604
+ if (
1605
+ head.state === 'joining' ||
1606
+ head.state === 'joined' ||
1607
+ head.state === 'suspended' ||
1608
+ (head.state === 'unknown' &&
1609
+ Option.isNone(yield* readAbortIntent(operation, head.submission_id)))
1610
+ ) {
1611
+ return Option.none<Claim>()
1612
+ }
1613
+
1614
+ const inputPayload = yield* parseStoredJsonText(head.input_json).pipe(
1615
+ Effect.mapError((error) =>
1616
+ corruptionFailure(
1617
+ operation,
1618
+ 'effect_agent_submissions',
1619
+ head.submission_id,
1620
+ error.message,
1621
+ )
1622
+ ),
1623
+ )
1624
+
1625
+ return Option.some(
1626
+ yield* decodeClaim({
1627
+ submissionId: head.submission_id,
1628
+ attemptId,
1629
+ inputPayload,
1630
+ }).pipe(Effect.mapError(internalFailure(operation))),
1631
+ )
1632
+ }),
1633
+ )
1634
+
1635
+ yield* hitFailpoint('ledger:claim:after', operation)
1636
+
1637
+ return claimed
1638
+ })
1639
+
1640
+ const markInputAppliedInTransaction = Effect.fnUntraced(function*(
1641
+ validated: MarkInputAppliedRequest,
1642
+ ) {
1643
+ const operation = 'ledger mark input applied'
1644
+
1645
+ const submission = yield* requireSubmission(operation, validated.submissionId)
1646
+
1647
+ yield* requireOwner(operation, submission)
1648
+ if (submission.input_applied_record_id !== null) {
1649
+ if (
1650
+ submission.input_applied_record_id === validated.recordId &&
1651
+ submission.input_applied_sequence === validated.sequence
1652
+ ) {
1653
+ return
1654
+ }
1655
+
1656
+ return yield* corruptionFailure(
1657
+ operation,
1658
+ 'effect_agent_submissions',
1659
+ validated.submissionId,
1660
+ 'A different canonical input marker is already recorded for this Submission.',
1661
+ )
1662
+ }
1663
+ yield* sql`
1664
+ UPDATE effect_agent_submissions
1665
+ SET
1666
+ input_applied_record_id = ${validated.recordId},
1667
+ input_applied_sequence = ${validated.sequence},
1668
+ state = CASE
1669
+ WHEN state IN ('admitted', 'ready') THEN 'input-applied'
1670
+ ELSE state
1671
+ END
1672
+ WHERE submission_id = ${validated.submissionId}
1673
+ RETURNING *, ${definitionJson(sql)} AS agent_digests_json`.pipe(
1674
+ rows.submissions.write,
1675
+ Effect.mapError(internalFailure(operation)),
1676
+ )
1677
+ })
1678
+
1679
+ const markInputApplied: SubmissionLedger['Service']['markInputApplied'] = Effect.fnUntraced(
1680
+ function*(request: MarkInputAppliedRequest) {
1681
+ const operation = 'ledger mark input applied'
1682
+
1683
+ const validated = yield* decodeMarkInputAppliedRequestType(request).pipe(
1684
+ Effect.mapError(internalFailure(operation)),
1685
+ )
1686
+
1687
+ yield* hitFailpoint('ledger:mark-input-applied:before', operation)
1688
+ yield* inWriteTransaction(operation, markInputAppliedInTransaction(validated))
1689
+ yield* hitFailpoint('ledger:mark-input-applied:after', operation)
1690
+ },
1691
+ )
1692
+
1693
+ const appendInput: NonNullable<SubmissionLedger['Service']['appendInput']> = Effect.fnUntraced(
1694
+ function*(submissionId, request) {
1695
+ const operation = 'append original input and context'
1696
+
1697
+ const prepared = yield* prepareCanonicalAppend(request).pipe(
1698
+ Effect.provideService(CryptoDigest.Digest, crypto),
1699
+ )
1700
+
1701
+ const record = prepared.request.batch.records[0]
1702
+
1703
+ const context = prepared.request.executions
1704
+ ?.flatMap((update) => update.facts ?? [])
1705
+ .find(({ payload }) => payload._tag === 'RunContextRecorded')
1706
+
1707
+ if (
1708
+ prepared.request.executions?.length !== 1 ||
1709
+ prepared.request.executions[0]?.previousRevision !== 0 ||
1710
+ prepared.request.batch.records.length !== 1 ||
1711
+ record?.payload._tag !== 'UserInputRecorded' ||
1712
+ record.payload.kind !== 'user' ||
1713
+ record.payload.submissionId !== submissionId ||
1714
+ record.payload.runId !== runIdForSubmission(submissionId) ||
1715
+ record.recordId !== submissionInputRecordId(submissionId) ||
1716
+ prepared.request.batch.batchId !== submissionInputBatchId(submissionId) ||
1717
+ (context?.payload._tag === 'RunContextRecorded' &&
1718
+ context.payload.historyThrough !== prepared.request.expectedTailSequence)
1719
+ ) {
1720
+ return yield* ThreadStoreError.make({
1721
+ operation,
1722
+ message: 'Original input publication has a different context boundary',
1723
+ })
1724
+ }
1725
+
1726
+ const mapError = (cause: { readonly message: string }) =>
1727
+ ThreadStoreError.make({ operation, message: cause.message, cause })
1728
+
1729
+ yield* journal.prepareAppend(prepared.raw).pipe(Effect.mapError(mapError))
1730
+
1731
+ return yield* owner.withProgress(
1732
+ prepared.request.threadId,
1733
+ owner.withMutation(
1734
+ Effect.gen(function*() {
1735
+ yield* hitFailpoint('append:before', operation)
1736
+ yield* hitFailpoint('ledger:mark-input-applied:before', operation)
1737
+
1738
+ const result = yield* journal
1739
+ .withWriteTransaction(operation)(
1740
+ Effect.gen(function*() {
1741
+ const submission = yield* requireSubmission(operation, submissionId)
1742
+
1743
+ yield* requireOwner(operation, submission)
1744
+ if (submission.thread_id !== prepared.request.threadId) {
1745
+ return yield* LedgerError.make({
1746
+ operation,
1747
+ message: 'Original input belongs to another Thread',
1748
+ })
1749
+ }
1750
+ const result = yield* journal.appendPrepared(prepared.raw)
1751
+
1752
+ yield* markInputAppliedInTransaction(
1753
+ MarkInputAppliedRequest.make({
1754
+ submissionId,
1755
+ recordId: record.recordId,
1756
+ sequence: result.firstSequence,
1757
+ }),
1758
+ )
1759
+
1760
+ return result
1761
+ }),
1762
+ )
1763
+ .pipe(
1764
+ Effect.mapError((error) =>
1765
+ error._tag === 'DoAppendConflict'
1766
+ ? AppendConflict.make({
1767
+ threadId: prepared.request.threadId,
1768
+ batchId: prepared.request.batch.batchId,
1769
+ reason: error.reason,
1770
+ ...(error.actualTailSequence === undefined
1771
+ ? {}
1772
+ : { actualTailSequence: error.actualTailSequence }),
1773
+ })
1774
+ : error._tag === 'OwnershipLost'
1775
+ ? error
1776
+ : mapError(error)
1777
+ ),
1778
+ )
1779
+
1780
+ yield* hitFailpoint('ledger:mark-input-applied:after', operation)
1781
+ yield* hitFailpoint('append:after', operation)
1782
+
1783
+ return result
1784
+ }).pipe(
1785
+ Effect.mapError((error) =>
1786
+ error._tag === 'OwnershipLost' ||
1787
+ error._tag === 'ThreadStoreError' ||
1788
+ error._tag === 'AppendConflict'
1789
+ ? error
1790
+ : mapError(error)
1791
+ ),
1792
+ ),
1793
+ ),
1794
+ )
1795
+ },
1796
+ )
1797
+
1798
+ const publish: SettlementPublisher['Service']['publish'] = Effect.fn(
1799
+ 'DoSubmissionLedger.publishSettlement',
1800
+ )(function*(input) {
1801
+ const operation = 'publish settlement'
1802
+ const { request, record, settlement } = yield* validatePublication(input)
1803
+
1804
+ const prepared = yield* prepareCanonicalAppend(request.append).pipe(
1805
+ Effect.provideService(CryptoDigest.Digest, crypto),
1806
+ )
1807
+
1808
+ const mapAppendError = (error: { readonly _tag: string; readonly message: string }) =>
1809
+ ThreadStoreError.make({ operation, message: error.message, cause: error })
1810
+
1811
+ yield* journal.prepareAppend(prepared.raw).pipe(Effect.mapError(mapAppendError))
1812
+
1813
+ return yield* owner.withProgress(
1814
+ request.append.threadId,
1815
+ owner.withMutation(
1816
+ Effect.gen(function*() {
1817
+ yield* hitFailpoint('append:before', operation)
1818
+
1819
+ const result = yield* journal
1820
+ .withWriteTransaction(operation)(
1821
+ Effect.gen(function*() {
1822
+ const submission = yield* requireSubmission(operation, request.submissionId)
1823
+
1824
+ if (submission.thread_id !== prepared.request.threadId) {
1825
+ return yield* LedgerError.make({
1826
+ operation,
1827
+ message: 'Settlement publication belongs to another Thread.',
1828
+ })
1829
+ }
1830
+ const snapshot = yield* decodeSubmissionSnapshot(operation, submission)
1831
+
1832
+ yield* validateCanonicalSettlement(record, snapshot)
1833
+ const existing = yield* readCanonicalSettlement(operation, submission)
1834
+ const thread = (yield* journal.getThread(prepared.request.threadId))[0]
1835
+
1836
+ if (thread === undefined) {
1837
+ return yield* ThreadNotMaterialized.make({ threadId: prepared.request.threadId })
1838
+ }
1839
+
1840
+ // Replay still requires authority: finalization releases Owned tokens, while
1841
+ // retained host linkage or abort intent can authorize tokenless settled replay.
1842
+ switch (request.authority._tag) {
1843
+ case 'Owned':
1844
+ yield* requireOwner(operation, submission)
1845
+ yield* validateCanonicalSettlement(record, {
1846
+ submissionId: request.submissionId,
1847
+ receiptId: snapshot.receiptId,
1848
+ ...(settlement.outcome === 'aborted' && settlement.runId === undefined
1849
+ ? {}
1850
+ : { runId: runIdForSubmission(request.submissionId) }),
1851
+ })
1852
+ break
1853
+ case 'Joined': {
1854
+ if (
1855
+ (submission.state !== 'joined' &&
1856
+ !(submission.state === 'settled' && existing !== undefined)) ||
1857
+ submission.joined_host_submission_id !== request.authority.hostSubmissionId
1858
+ ) {
1859
+ return yield* LedgerError.make({
1860
+ operation,
1861
+ message: 'Submission is not joined to the named host.',
1862
+ })
1863
+ }
1864
+
1865
+ const host = yield* requireSubmission(
1866
+ operation,
1867
+ request.authority.hostSubmissionId,
1868
+ )
1869
+
1870
+ if (host.thread_id !== submission.thread_id) {
1871
+ return yield* LedgerError.make({
1872
+ operation,
1873
+ message: 'Joined host belongs to another Thread.',
1874
+ })
1875
+ }
1876
+ const canonicalHost = yield* readCanonicalSettlement(operation, host)
1877
+
1878
+ if (canonicalHost === undefined) {
1879
+ return yield* LedgerError.make({
1880
+ operation,
1881
+ message: 'Joined host has no canonical settlement.',
1882
+ })
1883
+ }
1884
+ yield* validateJoinedSettlement(settlement, canonicalHost.settlement)
1885
+ break
1886
+ }
1887
+ case 'QueuedAbort':
1888
+ if (
1889
+ (submission.state !== 'ready' &&
1890
+ !(submission.state === 'settled' && existing !== undefined)) ||
1891
+ settlement.outcome !== 'aborted' ||
1892
+ Option.isNone(yield* readAbortIntent(operation, request.submissionId)) ||
1893
+ owner.hasOwner(submission.thread_id, request.submissionId)
1894
+ ) {
1895
+ return yield* LedgerError.make({
1896
+ operation,
1897
+ message: 'Queued abort is no longer authorized.',
1898
+ })
1899
+ }
1900
+ yield* validateCanonicalSettlement(record, {
1901
+ submissionId: request.submissionId,
1902
+ receiptId: snapshot.receiptId,
1903
+ runId: undefined,
1904
+ })
1905
+ }
1906
+ if (existing !== undefined) {
1907
+ yield* journal.checkCommitIntent(prepared.raw)
1908
+
1909
+ return SettlementPublicationResult.make({
1910
+ record: existing.record,
1911
+ tailSequence: thread.tail_sequence,
1912
+ replayed: true,
1913
+ })
1914
+ }
1915
+ if (submission.state === 'settled') {
1916
+ return yield* LedgerError.make({
1917
+ operation,
1918
+ message: 'Finalized Submission has no canonical settlement.',
1919
+ })
1920
+ }
1921
+ const appended = yield* journal.appendPrepared(prepared.raw)
1922
+
1923
+ return SettlementPublicationResult.make({
1924
+ record,
1925
+ tailSequence: appended.lastSequence,
1926
+ replayed: appended.replayed,
1927
+ })
1928
+ }),
1929
+ )
1930
+ .pipe(
1931
+ Effect.mapError((error) => {
1932
+ if (error._tag === 'DoAppendConflict') {
1933
+ return AppendConflict.make({
1934
+ threadId: prepared.request.threadId,
1935
+ batchId: prepared.request.batch.batchId,
1936
+ reason: error.reason,
1937
+ ...(error.actualTailSequence !== undefined
1938
+ ? {
1939
+ actualTailSequence: error.actualTailSequence,
1940
+ }
1941
+ : {}),
1942
+ })
1943
+ }
1944
+
1945
+ return isDoStorageError(error) ||
1946
+ error._tag === 'DoStorageCorruptionError' ||
1947
+ error._tag === 'DoStorageFailpointError' ||
1948
+ error._tag === 'DoValueBoundExceeded'
1949
+ ? mapAppendError(error)
1950
+ : error
1951
+ }),
1952
+ )
1953
+
1954
+ yield* hitFailpoint('append:after', operation)
1955
+
1956
+ return result
1957
+ }),
1958
+ ),
1959
+ )
1960
+ })
1961
+
1962
+ const validateFinalization = Effect.fnUntraced(function*(
1963
+ validated: SettlementFinalization,
1964
+ submission: SubmissionRow,
1965
+ ) {
1966
+ const operation = 'ledger finalize settlement'
1967
+ const canonical = yield* readCanonicalSettlement(operation, submission)
1968
+
1969
+ if (canonical === undefined) {
1970
+ return yield* LedgerError.make({
1971
+ operation,
1972
+ message: `No canonical settlement exists for submission ${validated.submissionId}.`,
1973
+ })
1974
+ }
1975
+ if (canonical.settlement.settlementId !== validated.settlementId) {
1976
+ return yield* SettlementConflict.make({
1977
+ submissionId: validated.submissionId,
1978
+ existingOutcome: canonical.settlement.outcome,
1979
+ })
1980
+ }
1981
+
1982
+ return { ...canonical, settlementFailure: settlementFailureFromRecord(canonical.record) }
1983
+ })
1984
+
1985
+ const replayFinalization = Effect.fnUntraced(function*(
1986
+ validated: SettlementFinalization,
1987
+ submission: SubmissionRow,
1988
+ {
1989
+ record,
1990
+ settlement,
1991
+ settlementFailure,
1992
+ }: Effect.Success<ReturnType<typeof validateFinalization>>,
1993
+ ) {
1994
+ const operation = 'ledger finalize settlement'
1995
+
1996
+ if (
1997
+ submission.finalized_at === null ||
1998
+ submission.settled_record_id !== record.recordId ||
1999
+ submission.settled_outcome !== settlement.outcome
2000
+ ) {
2001
+ return yield* corruptionFailure(
2002
+ operation,
2003
+ 'effect_agent_submissions',
2004
+ validated.submissionId,
2005
+ 'Settled projection disagrees with its canonical settlement.',
2006
+ )
2007
+ }
2008
+
2009
+ return yield* decodeSettlement({
2010
+ submissionId: validated.submissionId,
2011
+ settlementId: validated.settlementId,
2012
+ receiptId: submission.receipt_id,
2013
+ outcome: settlement.outcome,
2014
+ ...(settlementFailure === undefined ? {} : { failure: settlementFailure }),
2015
+ settledAt: submission.finalized_at,
2016
+ }).pipe(Effect.mapError(internalFailure(operation)))
2017
+ })
2018
+
2019
+ const finalizeSettlement: SubmissionLedger['Service']['finalizeSettlement'] = Effect.fn(
2020
+ 'DoSubmissionLedger.finalizeSettlement',
2021
+ )(function*(request: SettlementFinalization) {
2022
+ const operation = 'ledger finalize settlement'
2023
+
2024
+ const validated = yield* decodeSettlementFinalizationType(request).pipe(
2025
+ Effect.mapError(internalFailure(operation)),
2026
+ )
2027
+
2028
+ yield* hitFailpoint('ledger:finalize-settlement:before', operation)
2029
+
2030
+ // Read the immutable receipt under the same gate as every local write.
2031
+ const replay = yield* state.read(
2032
+ Effect.gen(function*() {
2033
+ const submission = yield* readSubmission(operation, validated.submissionId)
2034
+
2035
+ if (Option.isNone(submission) || submission.value.state !== 'settled') return Option.none()
2036
+
2037
+ const finalization = yield* validateFinalization(validated, submission.value)
2038
+
2039
+ return Option.some({
2040
+ settlement: yield* replayFinalization(validated, submission.value, finalization),
2041
+ threadId: submission.value.thread_id,
2042
+ })
2043
+ }),
2044
+ )
2045
+
2046
+ if (Option.isSome(replay)) {
2047
+ owner.closeSubmission(replay.value.threadId, validated.submissionId)
2048
+ yield* hitFailpoint('ledger:finalize-settlement:after', operation)
2049
+
2050
+ return replay.value.settlement
2051
+ }
2052
+
2053
+ const settlement = yield* inWriteTransaction(
2054
+ operation,
2055
+ Effect.gen(function*() {
2056
+ const submission = yield* requireSubmission(operation, validated.submissionId)
2057
+ const state = yield* validateFinalization(validated, submission)
2058
+
2059
+ const {
2060
+ settlement: canonicalSettlement,
2061
+ record: canonicalRecord,
2062
+ settlementFailure,
2063
+ } = state
2064
+
2065
+ if (submission.state === 'settled') {
2066
+ return {
2067
+ settlement: yield* replayFinalization(validated, submission, state),
2068
+ threadId: submission.thread_id,
2069
+ }
2070
+ }
2071
+ const now = yield* currentInstant
2072
+
2073
+ const terminal = submission.worker_admission_json === null
2074
+ ? undefined
2075
+ : workerTerminalFromRecord(
2076
+ yield* decodeSubmissionSnapshot(operation, submission),
2077
+ canonicalRecord,
2078
+ )
2079
+
2080
+ let sealedTerminal: typeof terminal
2081
+
2082
+ if (terminal !== undefined) {
2083
+ // Admission and finalization serialize here. An accepted correction that this Run
2084
+ // has not applied vetoes its completion, including admission after RunCompleted.
2085
+ const pending = terminal === 'completed'
2086
+ ? yield* sql`SELECT submission_id FROM effect_agent_submissions
2087
+ WHERE thread_id = ${submission.thread_id} AND queue_sequence > ${submission.queue_sequence}
2088
+ AND queue_sequence = (SELECT MAX(queue_sequence) FROM effect_agent_submissions WHERE thread_id = ${submission.thread_id})
2089
+ AND (joined_host_submission_id IS NULL OR joined_host_submission_id <> ${submission.submission_id}
2090
+ OR input_applied_record_id IS NULL) LIMIT 1`.pipe(
2091
+ Effect.mapError(sqlFailure(operation)),
2092
+ )
2093
+ : []
2094
+
2095
+ if (pending.length === 0) {
2096
+ const sealed = yield* sql`INSERT OR IGNORE INTO effect_agent_worker_stops (thread_id, terminal)
2097
+ VALUES (${submission.thread_id}, ${terminal}) RETURNING *`.pipe(
2098
+ rows.workerStops.write,
2099
+ Effect.mapError(internalFailure(operation)),
2100
+ )
2101
+
2102
+ yield* sql`INSERT OR IGNORE INTO effect_agent_abort_intents (submission_id, author, reason, requested_at)
2103
+ SELECT submission_id, ${submission.principal}, ${`Worker assignment ${terminal}`}, ${now.iso}
2104
+ FROM effect_agent_submissions WHERE thread_id = ${submission.thread_id} AND state <> 'settled'
2105
+ AND submission_id <> ${submission.submission_id}
2106
+ AND (joined_host_submission_id IS NULL OR joined_host_submission_id <> ${submission.submission_id}
2107
+ OR input_applied_record_id IS NULL) RETURNING *`.pipe(
2108
+ rows.aborts.write,
2109
+ Effect.mapError(internalFailure(operation)),
2110
+ )
2111
+ if (sealed.length > 0) sealedTerminal = terminal
2112
+ }
2113
+ }
2114
+
2115
+ yield* sql`
2116
+ UPDATE effect_agent_submissions
2117
+ SET state = 'settled', settled_outcome = ${canonicalSettlement.outcome},
2118
+ settled_record_id = ${canonicalRecord.recordId}, finalized_at = ${now.iso}
2119
+ WHERE submission_id = ${validated.submissionId}
2120
+ RETURNING *, ${definitionJson(sql)} AS agent_digests_json`.pipe(
2121
+ rows.submissions.write,
2122
+ Effect.mapError(internalFailure(operation)),
2123
+ )
2124
+
2125
+ yield* recordProgress('submission', operation)
2126
+
2127
+ if (sealedTerminal !== undefined) {
2128
+ yield* retainWorkerSeal(submission.thread_id, sealedTerminal)
2129
+ }
2130
+
2131
+ return {
2132
+ threadId: submission.thread_id,
2133
+ settlement: yield* decodeSettlement({
2134
+ submissionId: validated.submissionId,
2135
+ settlementId: validated.settlementId,
2136
+ receiptId: submission.receipt_id,
2137
+ outcome: canonicalSettlement.outcome,
2138
+ ...(settlementFailure === undefined ? {} : { failure: settlementFailure }),
2139
+ settledAt: now.iso,
2140
+ }).pipe(Effect.mapError(internalFailure(operation))),
2141
+ }
2142
+ }),
2143
+ )
2144
+
2145
+ owner.closeSubmission(settlement.threadId, validated.submissionId)
2146
+ yield* hitFailpoint('ledger:finalize-settlement:after', operation)
2147
+
2148
+ return settlement.settlement
2149
+ })
2150
+
2151
+ const inspectWorker = Effect.fnUntraced(function*(threadId: SubmissionSnapshot['threadId']) {
2152
+ const operation = 'inspect worker'
2153
+
2154
+ return yield* state
2155
+ .transaction(
2156
+ Effect.gen(function*() {
2157
+ const read = Effect.fnUntraced(function*(active: boolean) {
2158
+ const rows = yield* sql`SELECT ${submissionColumns} FROM effect_agent_submissions
2159
+ WHERE thread_id = ${threadId} ${active ? sql`AND state <> 'settled'` : sql``}
2160
+ ORDER BY queue_sequence ${active ? sql`ASC` : sql`DESC`} LIMIT 1`.pipe(
2161
+ Effect.mapError(sqlFailure(operation)),
2162
+ )
2163
+
2164
+ const decoded = yield* decodeSubmissionRows(operation, threadId, rows)
2165
+
2166
+ return decoded[0] === undefined
2167
+ ? null
2168
+ : yield* decodeSubmissionSnapshot(operation, decoded[0])
2169
+ })
2170
+
2171
+ const latest = yield* read(false)
2172
+ const active = yield* read(true)
2173
+
2174
+ const stops = yield* cached(rows.workerStops.by('thread_id', threadId), operation)
2175
+
2176
+ return yield* Schema.decodeEffect(Schema.toType(WorkerLedgerState))({
2177
+ latest,
2178
+ active,
2179
+ stopped: stops.length > 0,
2180
+ ...(stops[0] === undefined || stops[0].terminal === null
2181
+ ? {}
2182
+ : { terminal: stops[0].terminal }),
2183
+ }).pipe(Effect.mapError(internalFailure(operation)))
2184
+ }),
2185
+ )
2186
+ .pipe(
2187
+ Effect.provideService(SqlClientService.SqlClient, sql),
2188
+ Effect.catchTag('SqlError', (cause) => sqlFailure(operation)(cause)),
2189
+ )
2190
+ })
2191
+
2192
+ const stopWorker = Effect.fnUntraced(function*(request: WorkerStopCommand) {
2193
+ const operation = 'ledger stop worker'
2194
+
2195
+ const validated = yield* Schema.decodeEffect(WorkerStopCommand)(request).pipe(
2196
+ Effect.mapError(internalFailure(operation)),
2197
+ )
2198
+
2199
+ return yield* inWriteTransaction(
2200
+ operation,
2201
+ Effect.gen(function*() {
2202
+ const now = yield* currentInstant
2203
+
2204
+ const sealed =
2205
+ yield* sql`INSERT OR IGNORE INTO effect_agent_worker_stops (thread_id) VALUES (${validated.threadId}) RETURNING *`
2206
+ .pipe(
2207
+ rows.workerStops.write,
2208
+ Effect.mapError(internalFailure(operation)),
2209
+ )
2210
+
2211
+ const aborted =
2212
+ yield* sql`INSERT OR IGNORE INTO effect_agent_abort_intents (submission_id, author, reason, requested_at)
2213
+ SELECT submission_id, ${validated.author}, 'Worker owner stopped the worker', ${now.iso}
2214
+ FROM effect_agent_submissions WHERE thread_id = ${validated.threadId} AND state <> 'settled' RETURNING *`.pipe(
2215
+ rows.aborts.write,
2216
+ Effect.mapError(internalFailure(operation)),
2217
+ )
2218
+
2219
+ if (sealed.length > 0 || aborted.length > 0) yield* recordProgress('control', operation)
2220
+ if (sealed.length > 0) yield* retainWorkerSeal(validated.threadId, null)
2221
+
2222
+ return owner.hasOwner(validated.threadId) ? 1 : 0
2223
+ }),
2224
+ )
2225
+ })
2226
+
2227
+ const requestAbort: SubmissionLedger['Service']['requestAbort'] = Effect.fnUntraced(function*(
2228
+ request: AbortCommand,
2229
+ ) {
2230
+ const operation = 'ledger request abort'
2231
+
2232
+ const validated = yield* Schema.decodeEffect(Schema.toType(AbortCommand))(request).pipe(
2233
+ Effect.mapError(internalFailure(operation)),
2234
+ )
2235
+
2236
+ yield* hitFailpoint('ledger:request-abort:before', operation)
2237
+
2238
+ const intent = yield* inWriteTransaction(
2239
+ operation,
2240
+ Effect.gen(function*() {
2241
+ const submission = yield* requireSubmission(operation, validated.submissionId)
2242
+
2243
+ if (submission.state === 'settled') {
2244
+ if (submission.settled_outcome === null) {
2245
+ return yield* corruptionFailure(
2246
+ operation,
2247
+ 'effect_agent_submissions',
2248
+ validated.submissionId,
2249
+ 'A settled Submission carries no terminal outcome.',
2250
+ )
2251
+ }
2252
+
2253
+ return yield* SettlementConflict.make({
2254
+ submissionId: validated.submissionId,
2255
+ existingOutcome: submission.settled_outcome,
2256
+ })
2257
+ }
2258
+ // A joined Submission settles WITH its host; the abort target is the host (plan
2259
+ // §2.5). A joining Submission still records the intent: it is honored only if the
2260
+ // host has not consumed the input (revert-then-abort).
2261
+ if (submission.state === 'joined') {
2262
+ if (submission.joined_host_submission_id === null) {
2263
+ return yield* corruptionFailure(
2264
+ operation,
2265
+ 'effect_agent_submissions',
2266
+ validated.submissionId,
2267
+ 'A joined Submission carries no host linkage.',
2268
+ )
2269
+ }
2270
+
2271
+ const hostSubmissionId = yield* decodeSubmissionId(
2272
+ submission.joined_host_submission_id,
2273
+ ).pipe(Effect.mapError(internalFailure(operation)))
2274
+
2275
+ return yield* JoinedToHost.make({
2276
+ submissionId: validated.submissionId,
2277
+ hostSubmissionId,
2278
+ })
2279
+ }
2280
+ const existing = yield* readAbortIntent(operation, validated.submissionId)
2281
+
2282
+ if (Option.isSome(existing)) {
2283
+ return yield* abortIntentFromRow(
2284
+ operation,
2285
+ submission,
2286
+ validated.submissionId,
2287
+ existing.value,
2288
+ )
2289
+ }
2290
+ const now = yield* currentInstant
2291
+
2292
+ yield* sql`
2293
+ INSERT INTO effect_agent_abort_intents (
2294
+ submission_id,
2295
+ author,
2296
+ reason,
2297
+ requested_at
2298
+ ) VALUES (
2299
+ ${validated.submissionId},
2300
+ ${validated.author},
2301
+ ${validated.reason},
2302
+ ${now.iso}
2303
+ )
2304
+ RETURNING *`.pipe(rows.aborts.write, Effect.mapError(internalFailure(operation)))
2305
+
2306
+ yield* recordProgress('control', operation)
2307
+
2308
+ const canonicalRecordId = yield* canonicalAbortRecordId(
2309
+ operation,
2310
+ submission.thread_id,
2311
+ validated.submissionId,
2312
+ )
2313
+
2314
+ const intent = yield* decodeAbortIntent({
2315
+ submissionId: validated.submissionId,
2316
+ author: validated.author,
2317
+ reason: validated.reason,
2318
+ requestedAt: now.iso,
2319
+ ...(canonicalRecordId === undefined ? {} : { canonicalRecordId }),
2320
+ }).pipe(Effect.mapError(internalFailure(operation)))
2321
+
2322
+ yield* retainLifecycle(submission, { _tag: 'AbortIntentRecorded', intent })
2323
+
2324
+ return intent
2325
+ }),
2326
+ )
2327
+
2328
+ yield* hitFailpoint('ledger:request-abort:after', operation)
2329
+
2330
+ return intent
2331
+ })
2332
+
2333
+ const claimJoining: SubmissionLedger['Service']['claimJoining'] = Effect.fnUntraced(function*(
2334
+ request: ClaimJoiningRequest,
2335
+ ) {
2336
+ const operation = 'ledger claim joining'
2337
+
2338
+ const validated = yield* decodeClaimJoiningRequestType(request).pipe(
2339
+ Effect.mapError(internalFailure(operation)),
2340
+ )
2341
+
2342
+ yield* hitFailpoint('ledger:claim-joining:before', operation)
2343
+
2344
+ const claims = yield* owner.withMutation(
2345
+ Effect.gen(function*() {
2346
+ const host = yield* requireSubmission(operation, validated.hostSubmissionId)
2347
+
2348
+ if (host.thread_id !== validated.threadId) {
2349
+ return yield* LedgerError.make({
2350
+ operation,
2351
+ message: `Host submission ${validated.hostSubmissionId} does not belong to thread ${validated.threadId}.`,
2352
+ })
2353
+ }
2354
+ // The host Attempt retains its local ownership while the ready prefix joins it.
2355
+ yield* requireOwner(operation, host)
2356
+
2357
+ const stopped = yield* cached(
2358
+ rows.workerStops.by('thread_id', validated.threadId),
2359
+ operation,
2360
+ )
2361
+
2362
+ if (stopped.length > 0) return []
2363
+
2364
+ // Retain only an empty complete suffix. Any later admission invalidates this view;
2365
+ // nonempty rows keep their SQL ordering, and rollback discards the empty proof.
2366
+ const later = yield* submissionViews
2367
+ .matching(
2368
+ JSON.stringify(['joining-suffix', validated.threadId, host.queue_sequence]),
2369
+ (row) => row.thread_id === validated.threadId && row.queue_sequence > host.queue_sequence,
2370
+ sql`
2371
+ SELECT ${submissionColumns}
2372
+ FROM effect_agent_submissions
2373
+ WHERE thread_id = ${validated.threadId}
2374
+ AND queue_sequence > ${host.queue_sequence}
2375
+ ORDER BY queue_sequence ASC
2376
+ `,
2377
+ 0,
2378
+ )
2379
+ .pipe(
2380
+ Effect.mapError((error) =>
2381
+ error._tag === 'SqlError'
2382
+ ? sqlFailure(operation)(error)
2383
+ : internalFailure(operation)(error)
2384
+ ),
2385
+ )
2386
+
2387
+ if (later.length === 0) return []
2388
+
2389
+ // The reader gate stays held through promotion. Nonempty candidates retain
2390
+ // their native transaction, live-owner checks and contiguous-prefix rules.
2391
+ return yield* inWriteTransaction(
2392
+ operation,
2393
+ Effect.gen(function*() {
2394
+ const claimed: Array<JoiningClaim> = []
2395
+
2396
+ for (const row of later) {
2397
+ if (claimed.length >= validated.maxCount) break
2398
+ // Rows already claimed by THIS host extend its contiguous prefix and are skipped;
2399
+ // the coordinator re-delivers already-joined input through the coverage rule.
2400
+ if (
2401
+ (row.state === 'joining' || row.state === 'joined') &&
2402
+ row.joined_host_submission_id === validated.hostSubmissionId
2403
+ ) {
2404
+ continue
2405
+ }
2406
+ // P7 §7(c): an aborted-settled row is a CLOSED obligation, not a gap — recovery
2407
+ // settles aborted never-claimed queued work immediately, and settlement order of
2408
+ // never-run work is not execution order (DUR-004 bounds execution).
2409
+ if (row.state === 'settled' && row.settled_outcome === 'aborted') continue
2410
+ // Any other non-ready row — an admitted-not-ready gap in particular — breaks the
2411
+ // contiguous ready prefix (plan §2.5); later ready work stays queued (DUR-004).
2412
+ if (row.state !== 'ready') break
2413
+ const canonical = yield* readCanonicalSettlement(operation, row)
2414
+
2415
+ if (canonical?.settlement.outcome === 'aborted') continue
2416
+ if (canonical !== undefined) break
2417
+ yield* sql`
2418
+ UPDATE effect_agent_submissions
2419
+ SET state = 'joining', joined_host_submission_id = ${validated.hostSubmissionId}
2420
+ WHERE submission_id = ${row.submission_id}
2421
+ RETURNING *, ${definitionJson(sql)} AS agent_digests_json`.pipe(
2422
+ rows.submissions.write,
2423
+ Effect.mapError(internalFailure(operation)),
2424
+ )
2425
+
2426
+ const inputPayload = yield* parseStoredJsonText(row.input_json).pipe(
2427
+ Effect.mapError((error) =>
2428
+ corruptionFailure(
2429
+ operation,
2430
+ 'effect_agent_submissions',
2431
+ row.submission_id,
2432
+ error.message,
2433
+ )
2434
+ ),
2435
+ )
2436
+
2437
+ claimed.push(
2438
+ yield* decodeJoiningClaim({
2439
+ submissionId: row.submission_id,
2440
+ queueSequence: row.queue_sequence,
2441
+ inputPayload,
2442
+ }).pipe(Effect.mapError(internalFailure(operation))),
2443
+ )
2444
+ }
2445
+
2446
+ return claimed
2447
+ }),
2448
+ )
2449
+ }),
2450
+ )
2451
+
2452
+ yield* hitFailpoint('ledger:claim-joining:after', operation)
2453
+
2454
+ return claims
2455
+ })
2456
+
2457
+ const markJoined: SubmissionLedger['Service']['markJoined'] = Effect.fnUntraced(function*(
2458
+ request: MarkJoinedRequest,
2459
+ ) {
2460
+ const operation = 'ledger mark joined'
2461
+
2462
+ const validated = yield* Schema.decodeEffect(Schema.toType(MarkJoinedRequest))(request).pipe(
2463
+ Effect.mapError(internalFailure(operation)),
2464
+ )
2465
+
2466
+ yield* hitFailpoint('ledger:mark-joined:before', operation)
2467
+ yield* inWriteTransaction(
2468
+ operation,
2469
+ Effect.gen(function*() {
2470
+ const submission = yield* requireSubmission(operation, validated.submissionId)
2471
+
2472
+ if (submission.joined_host_submission_id === null) {
2473
+ return yield* LedgerError.make({
2474
+ operation,
2475
+ message: `Submission ${validated.submissionId} was never claimed for joining.`,
2476
+ })
2477
+ }
2478
+ const host = yield* requireSubmission(operation, submission.joined_host_submission_id)
2479
+
2480
+ // The lane is host-owned: the presented token must own the HOST's ownership period,
2481
+ // which also lets a later host Attempt repair a lost marker from history (DUR-016).
2482
+ yield* requireOwner(operation, host)
2483
+ if (submission.input_applied_record_id !== null) {
2484
+ if (
2485
+ submission.input_applied_record_id === validated.recordId &&
2486
+ submission.input_applied_sequence === validated.sequence
2487
+ ) {
2488
+ return
2489
+ }
2490
+
2491
+ return yield* corruptionFailure(
2492
+ operation,
2493
+ 'effect_agent_submissions',
2494
+ validated.submissionId,
2495
+ 'A different join marker is already recorded for this Submission.',
2496
+ )
2497
+ }
2498
+ if (submission.state !== 'joining' && submission.state !== 'joined') {
2499
+ return yield* LedgerError.make({
2500
+ operation,
2501
+ message: `Cannot mark submission ${validated.submissionId} joined from state ${submission.state}.`,
2502
+ })
2503
+ }
2504
+ yield* sql`
2505
+ UPDATE effect_agent_submissions
2506
+ SET
2507
+ input_applied_record_id = ${validated.recordId},
2508
+ input_applied_sequence = ${validated.sequence},
2509
+ state = 'joined'
2510
+ WHERE submission_id = ${validated.submissionId}
2511
+ RETURNING *, ${definitionJson(sql)} AS agent_digests_json`.pipe(
2512
+ rows.submissions.write,
2513
+ Effect.mapError(internalFailure(operation)),
2514
+ )
2515
+ }),
2516
+ )
2517
+ yield* hitFailpoint('ledger:mark-joined:after', operation)
2518
+ })
2519
+
2520
+ const revertJoining: SubmissionLedger['Service']['revertJoining'] = Effect.fnUntraced(function*(
2521
+ request: RevertJoiningRequest,
2522
+ ) {
2523
+ const operation = 'ledger revert joining'
2524
+
2525
+ const validated = yield* Schema.decodeEffect(Schema.toType(RevertJoiningRequest))(request).pipe(
2526
+ Effect.mapError(internalFailure(operation)),
2527
+ )
2528
+
2529
+ yield* hitFailpoint('ledger:revert-joining:before', operation)
2530
+ yield* inWriteTransaction(
2531
+ operation,
2532
+ Effect.gen(function*() {
2533
+ const submission = yield* requireSubmission(operation, validated.submissionId)
2534
+
2535
+ // Idempotent and recovery-only: only a still-`joining` Submission reverts; an
2536
+ // already-joined (or already-reverted) Submission is a no-op (DUR-016).
2537
+ if (submission.state !== 'joining') return
2538
+ const guard = validated.guard
2539
+
2540
+ if (guard !== undefined) {
2541
+ if (submission.joined_host_submission_id !== guard.hostSubmissionId) return
2542
+ const host = yield* requireSubmission(operation, guard.hostSubmissionId)
2543
+
2544
+ if (host.thread_id !== submission.thread_id) {
2545
+ return yield* corruptionFailure(
2546
+ operation,
2547
+ 'effect_agent_submissions',
2548
+ validated.submissionId,
2549
+ 'The joined host belongs to another Thread.',
2550
+ )
2551
+ }
2552
+ if (host.state !== 'settled') {
2553
+ yield* requireOwner(operation, host).pipe(
2554
+ Effect.mapError((cause) =>
2555
+ cause._tag === 'OwnershipLost'
2556
+ ? LedgerError.make({
2557
+ operation,
2558
+ message: 'Joining recovery no longer owns the linked host.',
2559
+ cause,
2560
+ })
2561
+ : cause
2562
+ ),
2563
+ )
2564
+ }
2565
+ }
2566
+ yield* sql`
2567
+ UPDATE effect_agent_submissions
2568
+ SET state = 'ready', joined_host_submission_id = NULL
2569
+ WHERE submission_id = ${validated.submissionId}
2570
+ RETURNING *, ${definitionJson(sql)} AS agent_digests_json`.pipe(
2571
+ rows.submissions.write,
2572
+ Effect.mapError(internalFailure(operation)),
2573
+ )
2574
+ }),
2575
+ )
2576
+ yield* hitFailpoint('ledger:revert-joining:after', operation)
2577
+ })
2578
+
2579
+ const suspend: SubmissionLedger['Service']['suspend'] = Effect.fnUntraced(function*(
2580
+ request: SuspendRequest,
2581
+ ) {
2582
+ const operation = 'ledger suspend'
2583
+
2584
+ const validated = yield* Schema.decodeEffect(Schema.toType(SuspendRequest))(request).pipe(
2585
+ Effect.mapError(internalFailure(operation)),
2586
+ )
2587
+
2588
+ const reasonJson = yield* encodeSuspensionReasonText(validated.reason).pipe(
2589
+ Effect.mapError(internalFailure(operation)),
2590
+ )
2591
+
2592
+ yield* hitFailpoint('ledger:suspend:before', operation)
2593
+
2594
+ const outcome = yield* inWriteTransaction(
2595
+ operation,
2596
+ Effect.gen(function*() {
2597
+ const submission = yield* requireSubmission(operation, validated.submissionId)
2598
+
2599
+ if (submission.state === 'settled') {
2600
+ if (submission.settled_outcome === null) {
2601
+ return yield* corruptionFailure(
2602
+ operation,
2603
+ 'effect_agent_submissions',
2604
+ validated.submissionId,
2605
+ 'A settled Submission carries no terminal outcome.',
2606
+ )
2607
+ }
2608
+
2609
+ return yield* SettlementConflict.make({
2610
+ submissionId: validated.submissionId,
2611
+ existingOutcome: submission.settled_outcome,
2612
+ })
2613
+ }
2614
+ // Canonical terminal intent wins over a later suspension.
2615
+ const canonical = yield* readCanonicalSettlement(operation, submission)
2616
+
2617
+ if (canonical !== undefined) {
2618
+ return yield* SettlementConflict.make({
2619
+ submissionId: validated.submissionId,
2620
+ existingOutcome: canonical.settlement.outcome,
2621
+ })
2622
+ }
2623
+ yield* requireOwner(operation, submission)
2624
+ // A covering event that raced ahead of the suspend transaction resumes the caller
2625
+ // immediately WITHOUT releasing the lane (plan §2.6, §12). For WaitingForChild the
2626
+ // covering evidence is EITHER a locally settled child row OR a durable cross-store
2627
+ // notification marker: parent and child Threads live in different Durable
2628
+ // Objects, and the port contract requires that a child settlement reported (via
2629
+ // `recordChildSettled` → marker) before this suspend commits is observed here.
2630
+ if (validated.reason._tag === 'ApprovalPending') {
2631
+ const decisions = yield* readApprovalDecisions(operation, validated.submissionId)
2632
+ const decided = new Map(decisions.map((row) => [row.tool_call_id, row.decision]))
2633
+
2634
+ if (
2635
+ approvalDecisionsCover(validated.reason.toolCallIds, (toolCallId) => decided.get(toolCallId))
2636
+ ) {
2637
+ return { outcome: RESUME_IMMEDIATELY, threadId: submission.thread_id }
2638
+ }
2639
+ } else {
2640
+ const markers = yield* readChildSettlementMarkers(operation, validated.submissionId)
2641
+ const markerChildren = new Set(markers.map((row) => row.child_submission_id))
2642
+ let allSettled = true
2643
+
2644
+ for (const child of validated.reason.children) {
2645
+ const settled = yield* childProvablySettled(
2646
+ operation,
2647
+ markerChildren,
2648
+ child.childSubmissionId,
2649
+ )
2650
+
2651
+ if (!settled) {
2652
+ allSettled = false
2653
+ break
2654
+ }
2655
+ }
2656
+ if (allSettled) {
2657
+ return { outcome: RESUME_IMMEDIATELY, threadId: submission.thread_id }
2658
+ }
2659
+ }
2660
+ const now = yield* currentInstant
2661
+
2662
+ yield* sql`
2663
+ UPDATE effect_agent_submissions
2664
+ SET
2665
+ state = 'suspended',
2666
+ suspended_reason_json = ${reasonJson},
2667
+ suspended_at = ${now.iso}
2668
+ WHERE submission_id = ${validated.submissionId}
2669
+ RETURNING *, ${definitionJson(sql)} AS agent_digests_json`.pipe(
2670
+ rows.submissions.write,
2671
+ Effect.mapError(internalFailure(operation)),
2672
+ )
2673
+ // Suspension ends the ownership period WITHOUT settling: the accepted-work
2674
+ // obligation stays owed while the lane consumes no worker permit (plan §2.6).
2675
+
2676
+ yield* retainLifecycle(submission, {
2677
+ _tag: 'SubmissionSuspended',
2678
+ submissionId: validated.submissionId,
2679
+ reason: validated.reason,
2680
+ })
2681
+
2682
+ return { outcome: SUSPENDED, threadId: submission.thread_id }
2683
+ }),
2684
+ )
2685
+
2686
+ if (outcome.outcome === SUSPENDED) {
2687
+ owner.closeSubmission(outcome.threadId, validated.submissionId)
2688
+ }
2689
+ yield* hitFailpoint('ledger:suspend:after', operation)
2690
+
2691
+ return outcome.outcome
2692
+ })
2693
+
2694
+ /**
2695
+ * Once one pending call is denied or every pending call has a decision intent,
2696
+ * the lane wakes: suspended → input-applied, suspension cleared (plan §2.6). A
2697
+ * WaitingForChild suspension wakes only through recordChildSettled. Runs inside the caller's
2698
+ * write transaction.
2699
+ */
2700
+ const wakeSuspendedIfCovered = Effect.fnUntraced(function*(
2701
+ operation: string,
2702
+ submission: SubmissionRow,
2703
+ ): Effect.fn.Return<void, LedgerError> {
2704
+ if (submission.state !== 'suspended' || submission.suspended_reason_json === null) return
2705
+
2706
+ const reason = yield* Schema.decodeEffect(Schema.fromJsonString(SuspensionReason))(
2707
+ submission.suspended_reason_json,
2708
+ ).pipe(
2709
+ Effect.mapError((error) =>
2710
+ corruptionFailure(
2711
+ operation,
2712
+ 'effect_agent_submissions',
2713
+ submission.submission_id,
2714
+ error.message,
2715
+ )
2716
+ ),
2717
+ )
2718
+
2719
+ if (reason._tag !== 'ApprovalPending') return
2720
+ const decisions = yield* readApprovalDecisions(operation, submission.submission_id)
2721
+ const decided = new Map(decisions.map((row) => [row.tool_call_id, row.decision]))
2722
+
2723
+ if (!approvalDecisionsCover(reason.toolCallIds, (toolCallId) => decided.get(toolCallId))) {
2724
+ return
2725
+ }
2726
+ yield* sql`
2727
+ UPDATE effect_agent_submissions
2728
+ SET
2729
+ state = 'input-applied',
2730
+ suspended_reason_json = NULL,
2731
+ suspended_at = NULL
2732
+ WHERE submission_id = ${submission.submission_id}
2733
+ RETURNING *, ${definitionJson(sql)} AS agent_digests_json`.pipe(
2734
+ rows.submissions.write,
2735
+ Effect.mapError(internalFailure(operation)),
2736
+ )
2737
+ yield* retainLifecycle(submission, {
2738
+ _tag: 'SubmissionResumed',
2739
+ submissionId: yield* decodeSubmissionId(submission.submission_id).pipe(
2740
+ Effect.mapError(internalFailure(operation)),
2741
+ ),
2742
+ })
2743
+ })
2744
+
2745
+ const recordApprovalDecision: SubmissionLedger['Service']['recordApprovalDecision'] = Effect.fnUntraced(
2746
+ function*(command: ApprovalDecisionCommand) {
2747
+ const operation = 'ledger record approval decision'
2748
+
2749
+ const validated = yield* Schema.decodeEffect(Schema.toType(ApprovalDecisionCommand))(
2750
+ command,
2751
+ ).pipe(Effect.mapError(internalFailure(operation)))
2752
+
2753
+ yield* hitFailpoint('ledger:approval-decision:before', operation)
2754
+
2755
+ const intent = yield* inWriteTransaction(
2756
+ operation,
2757
+ Effect.gen(function*() {
2758
+ const submission = yield* requireSubmission(operation, validated.submissionId)
2759
+
2760
+ if (submission.state === 'settled') {
2761
+ if (submission.settled_outcome === null) {
2762
+ return yield* corruptionFailure(
2763
+ operation,
2764
+ 'effect_agent_submissions',
2765
+ validated.submissionId,
2766
+ 'A settled Submission carries no terminal outcome.',
2767
+ )
2768
+ }
2769
+
2770
+ return yield* SettlementConflict.make({
2771
+ submissionId: validated.submissionId,
2772
+ existingOutcome: submission.settled_outcome,
2773
+ })
2774
+ }
2775
+ const decisions = yield* readApprovalDecisions(operation, validated.submissionId)
2776
+ const existing = decisions.find((row) => row.tool_call_id === validated.toolCallId)
2777
+
2778
+ if (existing !== undefined) {
2779
+ // Idempotent per (submissionId, toolCallId): repeating the SAME decision replays
2780
+ // the recorded intent unchanged; a divergent re-decision conflicts.
2781
+ if (existing.decision !== validated.decision) {
2782
+ return yield* ApprovalConflict.make({
2783
+ submissionId: validated.submissionId,
2784
+ toolCallId: validated.toolCallId,
2785
+ existingDecision: existing.decision,
2786
+ })
2787
+ }
2788
+
2789
+ return yield* approvalIntentFromRow(operation, existing)
2790
+ }
2791
+ const now = yield* currentInstant
2792
+
2793
+ yield* sql`
2794
+ INSERT INTO effect_agent_approval_decisions (
2795
+ submission_id,
2796
+ tool_call_id,
2797
+ decision,
2798
+ resolver,
2799
+ reason,
2800
+ decided_at
2801
+ ) VALUES (
2802
+ ${validated.submissionId},
2803
+ ${validated.toolCallId},
2804
+ ${validated.decision},
2805
+ ${validated.resolver},
2806
+ ${validated.reason},
2807
+ ${now.iso}
2808
+ )
2809
+ RETURNING *`.pipe(rows.approvals.write, Effect.mapError(internalFailure(operation)))
2810
+ yield* recordProgress('control', operation)
2811
+ yield* wakeSuspendedIfCovered(operation, submission)
2812
+
2813
+ return yield* decodeApprovalDecisionIntent({
2814
+ submissionId: validated.submissionId,
2815
+ toolCallId: validated.toolCallId,
2816
+ decision: validated.decision,
2817
+ resolver: validated.resolver,
2818
+ reason: validated.reason,
2819
+ decidedAt: now.iso,
2820
+ }).pipe(Effect.mapError(internalFailure(operation)))
2821
+ }),
2822
+ )
2823
+
2824
+ yield* hitFailpoint('ledger:approval-decision:after', operation)
2825
+
2826
+ return intent
2827
+ },
2828
+ )
2829
+
2830
+ const markUnknown: SubmissionLedger['Service']['markUnknown'] = Effect.fnUntraced(function*(
2831
+ request: MarkUnknownRequest,
2832
+ ) {
2833
+ const operation = 'ledger mark unknown'
2834
+
2835
+ const validated = yield* Schema.decodeEffect(Schema.toType(MarkUnknownRequest))(request).pipe(
2836
+ Effect.mapError(internalFailure(operation)),
2837
+ )
2838
+
2839
+ yield* hitFailpoint('ledger:mark-unknown:before', operation)
2840
+ yield* inWriteTransaction(
2841
+ operation,
2842
+ Effect.gen(function*() {
2843
+ const submission = yield* requireSubmission(operation, validated.submissionId)
2844
+
2845
+ if (submission.state === 'settled') {
2846
+ if (submission.settled_outcome === null) {
2847
+ return yield* corruptionFailure(
2848
+ operation,
2849
+ 'effect_agent_submissions',
2850
+ validated.submissionId,
2851
+ 'A settled Submission carries no terminal outcome.',
2852
+ )
2853
+ }
2854
+
2855
+ return yield* SettlementConflict.make({
2856
+ submissionId: validated.submissionId,
2857
+ existingOutcome: submission.settled_outcome,
2858
+ })
2859
+ }
2860
+ // Canonical terminal intent wins over a late Unknown marking.
2861
+ const canonical = yield* readCanonicalSettlement(operation, submission)
2862
+
2863
+ if (canonical !== undefined) {
2864
+ return yield* SettlementConflict.make({
2865
+ submissionId: validated.submissionId,
2866
+ existingOutcome: canonical.settlement.outcome,
2867
+ })
2868
+ }
2869
+ // Idempotent merge: repeating is a no-op; additional open calls extend the marked
2870
+ // set while the first recorded reason is kept.
2871
+ const existingIds = yield* storedUnknownToolCallIds(operation, submission)
2872
+ const known = new Set(existingIds)
2873
+
2874
+ const merged = [
2875
+ ...existingIds,
2876
+ ...validated.toolCallIds.filter((toolCallId) => !known.has(toolCallId)),
2877
+ ]
2878
+
2879
+ const idsJson = yield* encodeToolCallIdsText(merged).pipe(
2880
+ Effect.mapError(internalFailure(operation)),
2881
+ )
2882
+
2883
+ yield* sql`
2884
+ UPDATE effect_agent_submissions
2885
+ SET
2886
+ state = 'unknown',
2887
+ unknown_reason = ${submission.unknown_reason ?? validated.reason},
2888
+ unknown_tool_call_ids_json = ${idsJson}
2889
+ WHERE submission_id = ${validated.submissionId}
2890
+ RETURNING *, ${definitionJson(sql)} AS agent_digests_json`.pipe(
2891
+ rows.submissions.write,
2892
+ Effect.mapError(internalFailure(operation)),
2893
+ )
2894
+ if (submission.state !== 'unknown') {
2895
+ yield* retainLifecycle(submission, {
2896
+ _tag: 'SubmissionUnknown',
2897
+ submissionId: validated.submissionId,
2898
+ })
2899
+ }
2900
+ }),
2901
+ )
2902
+ yield* hitFailpoint('ledger:mark-unknown:after', operation)
2903
+ })
2904
+
2905
+ const recordUnknownResolution: SubmissionLedger['Service']['recordUnknownResolution'] = Effect.fnUntraced(
2906
+ function*(command: UnknownResolutionCommand) {
2907
+ const operation = 'ledger record unknown resolution'
2908
+
2909
+ const validated = yield* Schema.decodeEffect(Schema.toType(UnknownResolutionCommand))(
2910
+ command,
2911
+ ).pipe(Effect.mapError(internalFailure(operation)))
2912
+
2913
+ const resolutionJson = yield* encodeUnknownResolutionText(validated.resolution).pipe(
2914
+ Effect.mapError(internalFailure(operation)),
2915
+ )
2916
+
2917
+ yield* hitFailpoint('ledger:unknown-resolution:before', operation)
2918
+
2919
+ const intent = yield* inWriteTransaction(
2920
+ operation,
2921
+ Effect.gen(function*() {
2922
+ const submission = yield* requireSubmission(operation, validated.submissionId)
2923
+
2924
+ if (submission.state === 'settled') {
2925
+ if (submission.settled_outcome === null) {
2926
+ return yield* corruptionFailure(
2927
+ operation,
2928
+ 'effect_agent_submissions',
2929
+ validated.submissionId,
2930
+ 'A settled Submission carries no terminal outcome.',
2931
+ )
2932
+ }
2933
+
2934
+ // Factual closure may outlive settlement; it never restores execution authority.
2935
+ if (
2936
+ validated.resolution._tag !== 'CompletedWithResult' &&
2937
+ validated.resolution._tag !== 'NeverHappened'
2938
+ ) {
2939
+ return yield* SettlementConflict.make({
2940
+ submissionId: validated.submissionId,
2941
+ existingOutcome: submission.settled_outcome,
2942
+ })
2943
+ }
2944
+ }
2945
+ const resolutions = yield* readUnknownResolutions(operation, validated.submissionId)
2946
+ const kind = unknownResolutionKind(validated.resolution)
2947
+
2948
+ const existing = resolutions.find(
2949
+ (row) => row.tool_call_id === validated.toolCallId && row.resolution_kind === kind,
2950
+ )
2951
+
2952
+ const existingIntent = existing === undefined
2953
+ ? undefined
2954
+ : yield* unknownResolutionIntentFromRow(operation, existing)
2955
+
2956
+ if (
2957
+ (existingIntent !== undefined &&
2958
+ !equivalentUnknownResolution(existingIntent.resolution, validated.resolution)) ||
2959
+ (existing === undefined &&
2960
+ kind === 'execution' &&
2961
+ resolutions.some(
2962
+ (row) => row.tool_call_id === validated.toolCallId && row.resolution_kind === 'factual',
2963
+ ))
2964
+ ) {
2965
+ return yield* UnknownResolutionConflict.make({
2966
+ submissionId: validated.submissionId,
2967
+ toolCallId: validated.toolCallId,
2968
+ })
2969
+ }
2970
+
2971
+ if (existingIntent === undefined && kind === 'factual') {
2972
+ const runId = runIdForSubmission(validated.submissionId)
2973
+
2974
+ const found = yield* sql`
2975
+ SELECT ${canonicalRecordJson(sql)} AS record_json FROM effect_agent_canonical_records
2976
+ WHERE thread_id = ${submission.thread_id}
2977
+ AND record_tag = 27
2978
+ AND run_id = ${runKey(sql, sql`${submission.thread_id}`, sql`${JSON.stringify(runId)}`)}
2979
+ AND tool_call_id = ${JSON.stringify(validated.toolCallId)}
2980
+ LIMIT 2
2981
+ `.pipe(Effect.mapError(sqlFailure(operation)))
2982
+
2983
+ const outcomes = yield* decodeRows(
2984
+ Schema.Array(Schema.Struct({ record_json: BoundedStoredText })),
2985
+ 'effect_agent_canonical_records',
2986
+ validated.toolCallId,
2987
+ found,
2988
+ ).pipe(Effect.mapError(internalFailure(operation)))
2989
+
2990
+ const result = outcomes[0] === undefined
2991
+ ? undefined
2992
+ : (yield* decodeRecordEnvelopeText(outcomes[0].record_json).pipe(
2993
+ Effect.mapError(internalFailure(operation)),
2994
+ )).payload
2995
+
2996
+ if (
2997
+ outcomes.length > 1 ||
2998
+ (result !== undefined &&
2999
+ (result._tag !== 'ToolCallSettled' ||
3000
+ result.runId !== runId ||
3001
+ result.toolCallId !== validated.toolCallId))
3002
+ ) {
3003
+ return yield* corruptionFailure(
3004
+ operation,
3005
+ 'effect_agent_canonical_records',
3006
+ validated.toolCallId,
3007
+ 'Canonical Tool result identity is inconsistent.',
3008
+ )
3009
+ }
3010
+
3011
+ if (
3012
+ result?._tag === 'ToolCallSettled' &&
3013
+ !unknownResolutionMatchesResult(validated.resolution, result)
3014
+ ) {
3015
+ return yield* UnknownResolutionConflict.make({
3016
+ submissionId: validated.submissionId,
3017
+ toolCallId: validated.toolCallId,
3018
+ })
3019
+ }
3020
+ }
3021
+ let resolved: UnknownResolutionIntent
3022
+
3023
+ if (existingIntent !== undefined) {
3024
+ // Idempotent replay of the recorded intent (author/reason may differ; the stored
3025
+ // audit fields win, exactly like requestAbort).
3026
+ resolved = existingIntent
3027
+ } else {
3028
+ const now = yield* currentInstant
3029
+
3030
+ yield* sql`
3031
+ INSERT INTO effect_agent_unknown_resolutions (
3032
+ submission_id,
3033
+ tool_call_id,
3034
+ resolution_kind,
3035
+ author,
3036
+ reason,
3037
+ resolution_json,
3038
+ resolved_at
3039
+ ) VALUES (
3040
+ ${validated.submissionId},
3041
+ ${validated.toolCallId},
3042
+ ${kind},
3043
+ ${validated.author},
3044
+ ${validated.reason},
3045
+ ${resolutionJson},
3046
+ ${now.iso}
3047
+ )
3048
+ RETURNING *`.pipe(rows.resolutions.write, Effect.mapError(internalFailure(operation)))
3049
+ yield* recordProgress('control', operation)
3050
+
3051
+ const resolution = yield* parseStoredJsonText(resolutionJson).pipe(
3052
+ Effect.mapError(internalFailure(operation)),
3053
+ )
3054
+
3055
+ resolved = yield* decodeUnknownResolutionIntent({
3056
+ submissionId: validated.submissionId,
3057
+ toolCallId: validated.toolCallId,
3058
+ author: validated.author,
3059
+ reason: validated.reason,
3060
+ resolution,
3061
+ resolvedAt: now.iso,
3062
+ }).pipe(Effect.mapError(internalFailure(operation)))
3063
+ }
3064
+ // The lane reopens only when EVERY marked open call has a durable resolution intent:
3065
+ // unknown → input-applied (DUR-017). Replays re-run the coverage check so a
3066
+ // recovering caller can wake the lane idempotently.
3067
+ if (submission.state === 'unknown' && submission.unknown_tool_call_ids_json !== null) {
3068
+ const markedIds = yield* storedUnknownToolCallIds(operation, submission)
3069
+ const covering = yield* readUnknownResolutions(operation, validated.submissionId)
3070
+ const coveredIds = new Set(covering.map((row) => row.tool_call_id))
3071
+
3072
+ if (markedIds.every((toolCallId) => coveredIds.has(toolCallId))) {
3073
+ yield* sql`
3074
+ UPDATE effect_agent_submissions
3075
+ SET
3076
+ state = 'input-applied',
3077
+ unknown_reason = NULL,
3078
+ unknown_tool_call_ids_json = NULL
3079
+ WHERE submission_id = ${validated.submissionId}
3080
+ RETURNING *, ${definitionJson(sql)} AS agent_digests_json`.pipe(
3081
+ rows.submissions.write,
3082
+ Effect.mapError(internalFailure(operation)),
3083
+ )
3084
+ yield* retainLifecycle(submission, {
3085
+ _tag: 'SubmissionResumed',
3086
+ submissionId: validated.submissionId,
3087
+ })
3088
+ }
3089
+ }
3090
+
3091
+ return resolved
3092
+ }),
3093
+ )
3094
+
3095
+ yield* hitFailpoint('ledger:unknown-resolution:after', operation)
3096
+
3097
+ return intent
3098
+ },
3099
+ )
3100
+
3101
+ const recordChildSettled: SubmissionLedger['Service']['recordChildSettled'] = Effect.fnUntraced(
3102
+ function*(request: ChildSettledNotification) {
3103
+ const operation = 'ledger record child settled'
3104
+
3105
+ const validated = yield* Schema.decodeEffect(Schema.toType(ChildSettledNotification))(
3106
+ request,
3107
+ ).pipe(Effect.mapError(internalFailure(operation)))
3108
+
3109
+ yield* hitFailpoint('ledger:child-settled:before', operation)
3110
+
3111
+ const outcome = yield* inWriteTransaction(
3112
+ operation,
3113
+ Effect.gen(function*() {
3114
+ const parent = yield* requireSubmission(operation, validated.parentSubmissionId)
3115
+ // The child's canonical Settlement is the authority for this wake. When the child's
3116
+ // row lives in THIS store (single-store latitude, and every conformance lane), either a
3117
+ // canonical settlement admits the notification: the
3118
+ // runtime calls only after the canonical append and before ledger finalization. When the
3119
+ // row does not live here — the normal cross-DO case — the routed notification from the
3120
+ // child's owning Durable Object is the settlement evidence this store records durably.
3121
+ const child = yield* readSubmission(operation, validated.childSubmissionId)
3122
+
3123
+ const childCanonical = Option.isSome(child)
3124
+ ? yield* readCanonicalSettlement(operation, child.value)
3125
+ : undefined
3126
+
3127
+ if (Option.isSome(child) && childCanonical === undefined) {
3128
+ return yield* LedgerError.make({
3129
+ operation,
3130
+ message: `Child submission ${validated.childSubmissionId} has no recorded settlement.`,
3131
+ })
3132
+ }
3133
+ // Record the durable notification marker FIRST and unconditionally (idempotent):
3134
+ // the port's cross-store race guarantee requires that a notification committed
3135
+ // before the parent's suspend transaction is observed by that suspend's covering
3136
+ // check, even when the parent is not (or not yet) suspended.
3137
+ const now = yield* currentInstant
3138
+
3139
+ const added = yield* sql`
3140
+ INSERT INTO effect_agent_child_settlements (
3141
+ parent_submission_id,
3142
+ child_submission_id,
3143
+ child_outcome,
3144
+ recorded_at
3145
+ ) VALUES (
3146
+ ${validated.parentSubmissionId},
3147
+ ${validated.childSubmissionId},
3148
+ ${childCanonical?.settlement.outcome ?? null},
3149
+ ${now.iso}
3150
+ )
3151
+ ON CONFLICT (parent_submission_id, child_submission_id) DO NOTHING
3152
+ RETURNING *`.pipe(
3153
+ rows.childSettlements.write,
3154
+ Effect.mapError(internalFailure(operation)),
3155
+ )
3156
+
3157
+ if (added.length > 0) yield* recordProgress('control', operation)
3158
+
3159
+ if (parent.state !== 'suspended' || parent.suspended_reason_json === null) {
3160
+ return NOT_WAITING
3161
+ }
3162
+
3163
+ const reason = yield* Schema.decodeEffect(Schema.fromJsonString(SuspensionReason))(
3164
+ parent.suspended_reason_json,
3165
+ ).pipe(
3166
+ Effect.mapError((error) =>
3167
+ corruptionFailure(
3168
+ operation,
3169
+ 'effect_agent_submissions',
3170
+ parent.submission_id,
3171
+ error.message,
3172
+ )
3173
+ ),
3174
+ )
3175
+
3176
+ if (reason._tag !== 'WaitingForChild') {
3177
+ return NOT_WAITING
3178
+ }
3179
+ if (
3180
+ !reason.children.some(
3181
+ (entry) => entry.childSubmissionId === validated.childSubmissionId,
3182
+ )
3183
+ ) {
3184
+ return NOT_WAITING
3185
+ }
3186
+
3187
+ // The parent wakes exactly when EVERY listed child is provably settled — from its
3188
+ // local row or a recorded marker (spec §12 step 10); replays re-run the coverage
3189
+ // check so a recovering caller wakes the lane idempotently.
3190
+ const markers = yield* readChildSettlementMarkers(
3191
+ operation,
3192
+ validated.parentSubmissionId,
3193
+ )
3194
+
3195
+ const markerChildren = new Set(markers.map((row) => row.child_submission_id))
3196
+
3197
+ for (const entry of reason.children) {
3198
+ const settled = yield* childProvablySettled(
3199
+ operation,
3200
+ markerChildren,
3201
+ entry.childSubmissionId,
3202
+ )
3203
+
3204
+ if (!settled) {
3205
+ return STILL_WAITING
3206
+ }
3207
+ }
3208
+ yield* sql`
3209
+ UPDATE effect_agent_submissions
3210
+ SET
3211
+ state = 'input-applied',
3212
+ suspended_reason_json = NULL,
3213
+ suspended_at = NULL
3214
+ WHERE submission_id = ${validated.parentSubmissionId}
3215
+ RETURNING *, ${definitionJson(sql)} AS agent_digests_json`.pipe(
3216
+ rows.submissions.write,
3217
+ Effect.mapError(internalFailure(operation)),
3218
+ )
3219
+
3220
+ yield* retainLifecycle(parent, {
3221
+ _tag: 'SubmissionResumed',
3222
+ submissionId: validated.parentSubmissionId,
3223
+ })
3224
+
3225
+ return WOKEN
3226
+ }),
3227
+ )
3228
+
3229
+ yield* hitFailpoint('ledger:child-settled:after', operation)
3230
+
3231
+ return outcome
3232
+ },
3233
+ )
3234
+
3235
+ const reserveChildBudget: SubmissionLedger['Service']['reserveChildBudget'] = Effect.fnUntraced(
3236
+ function*(request: ChildBudgetReservationRequest) {
3237
+ const operation = 'ledger reserve child budget'
3238
+
3239
+ const validated = yield* Schema.decodeEffect(Schema.toType(ChildBudgetReservationRequest))(
3240
+ request,
3241
+ ).pipe(Effect.mapError(internalFailure(operation)))
3242
+
3243
+ const allocationJson = yield* encodePersistedJsonText(validated.allocation).pipe(
3244
+ Effect.mapError(internalFailure(operation)),
3245
+ )
3246
+
3247
+ yield* hitFailpoint('ledger:child-reservation:before', operation)
3248
+
3249
+ const reserved = yield* inWriteTransaction(
3250
+ operation,
3251
+ Effect.gen(function*() {
3252
+ const existing = yield* readChildReservation(operation, validated.reservationId)
3253
+
3254
+ if (Option.isSome(existing)) {
3255
+ const existingSnapshot = yield* childReservationSnapshotFromRow(
3256
+ operation,
3257
+ existing.value,
3258
+ )
3259
+
3260
+ // Identical replays short-circuit before the fence, retaining its first committed allocation: a
3261
+ // replay creates nothing, so a recovering caller resumes rather than duplicates.
3262
+ const identical = existing.value.parent_submission_id === validated.parentSubmissionId &&
3263
+ existing.value.parent_tool_call_id === validated.parentToolCallId &&
3264
+ existing.value.allocation_digest === validated.allocationDigest &&
3265
+ equivalentPersistedJson(existingSnapshot.allocation, validated.allocation)
3266
+
3267
+ if (!identical) {
3268
+ return yield* ChildReservationConflict.make({
3269
+ reservationId: validated.reservationId,
3270
+ status: existing.value.status,
3271
+ message: 'A reservation with this identity exists with a different parent Tool Call or allocation.',
3272
+ })
3273
+ }
3274
+
3275
+ return ReservedChildBudget.make({
3276
+ reservation: existingSnapshot,
3277
+ replayed: true,
3278
+ })
3279
+ }
3280
+
3281
+ const collision = yield* readChildReservationForCall(
3282
+ operation,
3283
+ validated.parentSubmissionId,
3284
+ validated.parentToolCallId,
3285
+ )
3286
+
3287
+ if (Option.isSome(collision)) {
3288
+ return yield* ChildReservationConflict.make({
3289
+ reservationId: validated.reservationId,
3290
+ status: collision.value.status,
3291
+ message:
3292
+ `Parent Tool Call ${validated.parentToolCallId} already owns reservation ${collision.value.reservation_id}.`,
3293
+ })
3294
+ }
3295
+ const parent = yield* requireSubmission(operation, validated.parentSubmissionId)
3296
+
3297
+ // Creation is fenced by the parent lane's live ownership (spec §12 step 2): a stale
3298
+ // parent Attempt can never create new reservation state.
3299
+ yield* requireOwner(operation, parent)
3300
+ const now = yield* currentInstant
3301
+
3302
+ yield* sql`
3303
+ INSERT INTO effect_agent_child_reservations (
3304
+ reservation_id,
3305
+ parent_submission_id,
3306
+ parent_tool_call_id,
3307
+ status,
3308
+ allocation_json,
3309
+ allocation_digest,
3310
+ reserved_at
3311
+ ) VALUES (
3312
+ ${validated.reservationId},
3313
+ ${validated.parentSubmissionId},
3314
+ ${validated.parentToolCallId},
3315
+ 'reserved',
3316
+ ${allocationJson},
3317
+ ${validated.allocationDigest},
3318
+ ${now.iso}
3319
+ )
3320
+ RETURNING *`.pipe(
3321
+ rows.childReservations.write,
3322
+ Effect.mapError(internalFailure(operation)),
3323
+ )
3324
+ const inserted = yield* readChildReservation(operation, validated.reservationId)
3325
+
3326
+ if (Option.isNone(inserted)) {
3327
+ return yield* corruptionFailure(
3328
+ operation,
3329
+ 'effect_agent_child_reservations',
3330
+ validated.reservationId,
3331
+ 'An inserted child reservation row is missing inside its own transaction.',
3332
+ )
3333
+ }
3334
+
3335
+ return ReservedChildBudget.make({
3336
+ reservation: yield* childReservationSnapshotFromRow(operation, inserted.value),
3337
+ replayed: false,
3338
+ })
3339
+ }),
3340
+ )
3341
+
3342
+ yield* hitFailpoint('ledger:child-reservation:after', operation)
3343
+
3344
+ return reserved
3345
+ },
3346
+ )
3347
+
3348
+ const attachChildToReservation: SubmissionLedger['Service']['attachChildToReservation'] = Effect.fnUntraced(
3349
+ function*(request: AttachChildToReservationRequest) {
3350
+ const operation = 'ledger attach child to reservation'
3351
+
3352
+ const validated = yield* Schema.decodeEffect(Schema.toType(AttachChildToReservationRequest))(
3353
+ request,
3354
+ ).pipe(Effect.mapError(internalFailure(operation)))
3355
+
3356
+ yield* hitFailpoint('ledger:child-attach:before', operation)
3357
+
3358
+ const attached = yield* inWriteTransaction(
3359
+ operation,
3360
+ Effect.gen(function*() {
3361
+ const existing = yield* readChildReservation(operation, validated.reservationId)
3362
+
3363
+ if (Option.isNone(existing)) {
3364
+ return yield* LedgerError.make({
3365
+ operation,
3366
+ message: `Unknown child reservation ${validated.reservationId}.`,
3367
+ })
3368
+ }
3369
+ if (existing.value.child_submission_id !== null) {
3370
+ // Idempotent replay of the recorded attachment (unfenced — it mutates nothing).
3371
+ if (existing.value.child_submission_id === validated.childSubmissionId) {
3372
+ return yield* childReservationSnapshotFromRow(operation, existing.value)
3373
+ }
3374
+
3375
+ return yield* ChildReservationConflict.make({
3376
+ reservationId: validated.reservationId,
3377
+ status: existing.value.status,
3378
+ message:
3379
+ `Reservation ${validated.reservationId} already records child ${existing.value.child_submission_id}.`,
3380
+ })
3381
+ }
3382
+ const parent = yield* requireSubmission(operation, existing.value.parent_submission_id)
3383
+
3384
+ yield* requireOwner(operation, parent)
3385
+ if (existing.value.status !== 'reserved') {
3386
+ return yield* ChildReservationConflict.make({
3387
+ reservationId: validated.reservationId,
3388
+ status: existing.value.status,
3389
+ message: `Cannot attach a child to a ${existing.value.status} reservation.`,
3390
+ })
3391
+ }
3392
+ // Unlike the single-store Node adapter, the admitted child's row lives in ANOTHER
3393
+ // Durable Object, so no local existence check is possible here. The canonical
3394
+ // `SubagentStarted` record remains the attachment's repair authority (DUR-015),
3395
+ // and the coordinator only attaches after the child's admission committed.
3396
+ yield* sql`
3397
+ UPDATE effect_agent_child_reservations
3398
+ SET child_submission_id = ${validated.childSubmissionId}
3399
+ WHERE reservation_id = ${validated.reservationId}
3400
+ RETURNING *`.pipe(
3401
+ rows.childReservations.write,
3402
+ Effect.mapError(internalFailure(operation)),
3403
+ )
3404
+ const updated = yield* readChildReservation(operation, validated.reservationId)
3405
+
3406
+ if (Option.isNone(updated)) {
3407
+ return yield* corruptionFailure(
3408
+ operation,
3409
+ 'effect_agent_child_reservations',
3410
+ validated.reservationId,
3411
+ 'An updated child reservation row is missing inside its own transaction.',
3412
+ )
3413
+ }
3414
+
3415
+ return yield* childReservationSnapshotFromRow(operation, updated.value)
3416
+ }),
3417
+ )
3418
+
3419
+ yield* hitFailpoint('ledger:child-attach:after', operation)
3420
+
3421
+ return attached
3422
+ },
3423
+ )
3424
+
3425
+ const beginChildBudgetRelease: SubmissionLedger['Service']['beginChildBudgetRelease'] = Effect.fnUntraced(
3426
+ function*(request: BeginChildBudgetReleaseRequest) {
3427
+ const operation = 'ledger begin child budget release'
3428
+
3429
+ const validated = yield* Schema.decodeEffect(Schema.toType(BeginChildBudgetReleaseRequest))(
3430
+ request,
3431
+ ).pipe(Effect.mapError(internalFailure(operation)))
3432
+
3433
+ const accountingJson = yield* encodePersistedJsonText(validated.accounting).pipe(
3434
+ Effect.mapError(internalFailure(operation)),
3435
+ )
3436
+
3437
+ yield* hitFailpoint('ledger:child-release-pending:before', operation)
3438
+
3439
+ const frozen = yield* inWriteTransaction(
3440
+ operation,
3441
+ Effect.gen(function*() {
3442
+ const existing = yield* readChildReservation(operation, validated.reservationId)
3443
+
3444
+ if (Option.isNone(existing)) {
3445
+ return yield* LedgerError.make({
3446
+ operation,
3447
+ message: `Unknown child reservation ${validated.reservationId}.`,
3448
+ })
3449
+ }
3450
+ if (existing.value.status !== 'reserved') {
3451
+ const existingSnapshot = yield* childReservationSnapshotFromRow(
3452
+ operation,
3453
+ existing.value,
3454
+ )
3455
+
3456
+ // The accounting decision was already frozen exactly once; an identical replay is a
3457
+ // no-op and a divergent decision conflicts (spec §12 join step 6).
3458
+ if (
3459
+ existingSnapshot.accounting !== undefined &&
3460
+ equivalentPersistedJson(existingSnapshot.accounting, validated.accounting)
3461
+ ) {
3462
+ return existingSnapshot
3463
+ }
3464
+
3465
+ return yield* ChildReservationConflict.make({
3466
+ reservationId: validated.reservationId,
3467
+ status: existing.value.status,
3468
+ message: 'A different accounting decision is already frozen for this reservation.',
3469
+ })
3470
+ }
3471
+ const now = yield* currentInstant
3472
+
3473
+ yield* sql`
3474
+ UPDATE effect_agent_child_reservations
3475
+ SET
3476
+ status = 'releasePending',
3477
+ accounting_json = ${accountingJson},
3478
+ release_began_at = ${now.iso}
3479
+ WHERE reservation_id = ${validated.reservationId}
3480
+ RETURNING *`.pipe(
3481
+ rows.childReservations.write,
3482
+ Effect.mapError(internalFailure(operation)),
3483
+ )
3484
+ const updated = yield* readChildReservation(operation, validated.reservationId)
3485
+
3486
+ if (Option.isNone(updated)) {
3487
+ return yield* corruptionFailure(
3488
+ operation,
3489
+ 'effect_agent_child_reservations',
3490
+ validated.reservationId,
3491
+ 'An updated child reservation row is missing inside its own transaction.',
3492
+ )
3493
+ }
3494
+
3495
+ return yield* childReservationSnapshotFromRow(operation, updated.value)
3496
+ }),
3497
+ )
3498
+
3499
+ yield* hitFailpoint('ledger:child-release-pending:after', operation)
3500
+
3501
+ return frozen
3502
+ },
3503
+ )
3504
+
3505
+ const releaseChildBudget: SubmissionLedger['Service']['releaseChildBudget'] = Effect.fnUntraced(
3506
+ function*(request: ReleaseChildBudgetRequest) {
3507
+ const operation = 'ledger release child budget'
3508
+
3509
+ const validated = yield* Schema.decodeEffect(Schema.toType(ReleaseChildBudgetRequest))(
3510
+ request,
3511
+ ).pipe(Effect.mapError(internalFailure(operation)))
3512
+
3513
+ yield* hitFailpoint('ledger:child-release:before', operation)
3514
+
3515
+ const released = yield* inWriteTransaction(
3516
+ operation,
3517
+ Effect.gen(function*() {
3518
+ const existing = yield* readChildReservation(operation, validated.reservationId)
3519
+
3520
+ if (Option.isNone(existing)) {
3521
+ return yield* LedgerError.make({
3522
+ operation,
3523
+ message: `Unknown child reservation ${validated.reservationId}.`,
3524
+ })
3525
+ }
3526
+ // Applied exactly once: replaying a released reservation returns the stored row
3527
+ // unchanged (spec §12: "never available twice").
3528
+ if (existing.value.status === 'released') {
3529
+ return yield* childReservationSnapshotFromRow(operation, existing.value)
3530
+ }
3531
+ if (existing.value.status !== 'releasePending') {
3532
+ return yield* ChildReservationConflict.make({
3533
+ reservationId: validated.reservationId,
3534
+ status: existing.value.status,
3535
+ message: 'Cannot release a reservation whose accounting decision is not frozen.',
3536
+ })
3537
+ }
3538
+ const now = yield* currentInstant
3539
+
3540
+ yield* sql`
3541
+ UPDATE effect_agent_child_reservations
3542
+ SET status = 'released', released_at = ${now.iso}
3543
+ WHERE reservation_id = ${validated.reservationId}
3544
+ RETURNING *`.pipe(
3545
+ rows.childReservations.write,
3546
+ Effect.mapError(internalFailure(operation)),
3547
+ )
3548
+ const updated = yield* readChildReservation(operation, validated.reservationId)
3549
+
3550
+ if (Option.isNone(updated)) {
3551
+ return yield* corruptionFailure(
3552
+ operation,
3553
+ 'effect_agent_child_reservations',
3554
+ validated.reservationId,
3555
+ 'An updated child reservation row is missing inside its own transaction.',
3556
+ )
3557
+ }
3558
+
3559
+ return yield* childReservationSnapshotFromRow(operation, updated.value)
3560
+ }),
3561
+ )
3562
+
3563
+ yield* hitFailpoint('ledger:child-release:after', operation)
3564
+
3565
+ return released
3566
+ },
3567
+ )
3568
+
3569
+ interface ScanCursor {
3570
+ readonly threadId: string
3571
+ readonly queueSequence: number
3572
+ }
3573
+
3574
+ const scanPage = Effect.fnUntraced(function*(
3575
+ cursor: ScanCursor | undefined,
3576
+ ): Effect.fn.Return<
3577
+ readonly [ReadonlyArray<SubmissionWorkItem>, Option.Option<ScanCursor | undefined>],
3578
+ LedgerError
3579
+ > {
3580
+ const operation = 'ledger scan nonterminal'
3581
+
3582
+ const rows = yield* (
3583
+ cursor === undefined
3584
+ ? sql<Record<string, unknown>>`
3585
+ SELECT submission_id AS "submissionId", thread_id AS "threadId",
3586
+ queue_sequence AS "queueSequence", principal, idempotency_key AS "idempotencyKey",
3587
+ deployment_id AS "deploymentId", receipt_id AS "receiptId", state
3588
+ FROM effect_agent_submissions
3589
+ WHERE state <> 'settled'
3590
+ ORDER BY thread_id ASC, queue_sequence ASC
3591
+ LIMIT ${SCAN_PAGE_SIZE}
3592
+ `
3593
+ : sql<Record<string, unknown>>`
3594
+ SELECT submission_id AS "submissionId", thread_id AS "threadId",
3595
+ queue_sequence AS "queueSequence", principal, idempotency_key AS "idempotencyKey",
3596
+ deployment_id AS "deploymentId", receipt_id AS "receiptId", state
3597
+ FROM effect_agent_submissions
3598
+ WHERE state <> 'settled'
3599
+ AND (thread_id, queue_sequence) > (${cursor.threadId}, ${cursor.queueSequence})
3600
+ ORDER BY thread_id ASC, queue_sequence ASC
3601
+ LIMIT ${SCAN_PAGE_SIZE}
3602
+ `
3603
+ ).pipe(Effect.mapError(sqlFailure(operation)))
3604
+
3605
+ const decoded = yield* decodeRows(
3606
+ SubmissionWorkItems,
3607
+ 'effect_agent_submissions',
3608
+ 'nonterminal_scan',
3609
+ rows,
3610
+ 'SubmissionWorkItem',
3611
+ ).pipe(Effect.mapError(internalFailure(operation)))
3612
+
3613
+ const last = decoded[decoded.length - 1]
3614
+
3615
+ const next: Option.Option<ScanCursor | undefined> = last === undefined || decoded.length < SCAN_PAGE_SIZE
3616
+ ? Option.none()
3617
+ : Option.some({
3618
+ threadId: last.threadId,
3619
+ queueSequence: last.queueSequence,
3620
+ })
3621
+
3622
+ return [decoded, next] as const
3623
+ })
3624
+
3625
+ // Both discovery and head selection use this same complete, owner-invalidated bounded view.
3626
+ const activeNonterminal = cached(
3627
+ workRows.matching(
3628
+ 'nonterminal',
3629
+ (row) => row.state !== 'settled',
3630
+ sql`SELECT submission_id, thread_id, queue_sequence, principal, idempotency_key,
3631
+ deployment_id, receipt_id, state
3632
+ FROM effect_agent_submissions WHERE state <> 'settled' LIMIT 129`,
3633
+ 128,
3634
+ ),
3635
+ 'ledger scan nonterminal',
3636
+ )
3637
+
3638
+ const boundedNonterminal = state.read(
3639
+ Effect.gen(function*() {
3640
+ // Cache only a complete bounded active set. Large hosts keep the paged scan.
3641
+ const active = yield* activeNonterminal
3642
+
3643
+ if (active.length > 128) return undefined
3644
+
3645
+ const sorted = [...active].sort((left, right) =>
3646
+ left.thread_id < right.thread_id
3647
+ ? -1
3648
+ : left.thread_id > right.thread_id
3649
+ ? 1
3650
+ : left.queue_sequence - right.queue_sequence
3651
+ )
3652
+
3653
+ const work = yield* decodeSubmissionWorkItems(
3654
+ sorted.map((row) => ({
3655
+ submissionId: row.submission_id,
3656
+ threadId: row.thread_id,
3657
+ queueSequence: row.queue_sequence,
3658
+ principal: row.principal,
3659
+ idempotencyKey: row.idempotency_key,
3660
+ deploymentId: row.deployment_id,
3661
+ receiptId: row.receipt_id,
3662
+ state: row.state,
3663
+ })),
3664
+ ).pipe(Effect.mapError(internalFailure('ledger scan nonterminal')))
3665
+
3666
+ return work
3667
+ }),
3668
+ )
3669
+
3670
+ const pagedNonterminal = Stream.paginate<ScanCursor | undefined, SubmissionWorkItem, LedgerError>(
3671
+ undefined,
3672
+ scanPage,
3673
+ )
3674
+
3675
+ // Large scans keep their bounded page lifetime and streaming backpressure.
3676
+ const scanNonterminal = Stream.unwrap(
3677
+ Effect.map(boundedNonterminal, (work) => work === undefined ? pagedNonterminal : Stream.fromIterable(work)),
3678
+ )
3679
+
3680
+ const listNonterminal = Effect.filterOrElse(
3681
+ boundedNonterminal,
3682
+ (work) => work !== undefined,
3683
+ () => Stream.runCollect(pagedNonterminal),
3684
+ )
3685
+
3686
+ const readAbortIntentForSubmission: SubmissionLedger['Service']['readAbortIntent'] = Effect.fnUntraced(
3687
+ function*(request) {
3688
+ const operation = 'ledger read abort intent'
3689
+
3690
+ const validated = yield* decodeAbortIntentRequestType(request).pipe(
3691
+ Effect.mapError(internalFailure(operation)),
3692
+ )
3693
+
3694
+ return yield* state.read(
3695
+ Effect.gen(function*() {
3696
+ const submission = yield* requireSubmission(operation, validated.submissionId)
3697
+ const intent = yield* readAbortIntent(operation, validated.submissionId)
3698
+
3699
+ return Option.isNone(intent)
3700
+ ? undefined
3701
+ : yield* abortIntentFromRow(
3702
+ operation,
3703
+ submission,
3704
+ validated.submissionId,
3705
+ intent.value,
3706
+ )
3707
+ }),
3708
+ )
3709
+ },
3710
+ )
3711
+
3712
+ const loadRecoverySnapshot: SubmissionLedger['Service']['loadRecoverySnapshot'] = Effect.fnUntraced(
3713
+ function*(request: RecoverySnapshotRequest) {
3714
+ const operation = 'ledger load recovery snapshot'
3715
+
3716
+ const validated = yield* decodeRecoverySnapshotRequestType(request).pipe(
3717
+ Effect.mapError(internalFailure(operation)),
3718
+ )
3719
+
3720
+ return yield* state.read(
3721
+ Effect.gen(function*() {
3722
+ const submissionRow = yield* requireSubmission(operation, validated.submissionId)
3723
+ const submission = yield* decodeSubmissionSnapshot(operation, submissionRow)
3724
+
3725
+ let inputApplied: InputAppliedMarker | undefined
3726
+
3727
+ if (
3728
+ submissionRow.input_applied_record_id !== null &&
3729
+ submissionRow.input_applied_sequence !== null
3730
+ ) {
3731
+ inputApplied = yield* decodeInputAppliedMarker({
3732
+ recordId: submissionRow.input_applied_record_id,
3733
+ sequence: submissionRow.input_applied_sequence,
3734
+ }).pipe(Effect.mapError(internalFailure(operation)))
3735
+ }
3736
+
3737
+ let abortIntent: AbortIntent | undefined
3738
+ const abortRow = yield* readAbortIntent(operation, validated.submissionId)
3739
+
3740
+ if (Option.isSome(abortRow)) {
3741
+ abortIntent = yield* abortIntentFromRow(
3742
+ operation,
3743
+ submissionRow,
3744
+ validated.submissionId,
3745
+ abortRow.value,
3746
+ )
3747
+ }
3748
+
3749
+ // Host-side view: every Submission whose host linkage points here, in queue order
3750
+ // (the terminalize loop settles them with the host outcome, DUR-002).
3751
+ const joinRows = (yield* cached(
3752
+ rows.submissions.by('joined_host_submission_id', validated.submissionId),
3753
+ operation,
3754
+ ))
3755
+ .filter((row) => row.joined_host_submission_id === validated.submissionId)
3756
+ .sort((a, b) => a.queue_sequence - b.queue_sequence)
3757
+
3758
+ const joins: Array<JoinSnapshot> = []
3759
+
3760
+ for (const row of joinRows) {
3761
+ joins.push(
3762
+ yield* decodeJoinSnapshot({
3763
+ submissionId: row.submission_id,
3764
+ state: row.state,
3765
+ hostSubmissionId: validated.submissionId,
3766
+ }).pipe(Effect.mapError(internalFailure(operation))),
3767
+ )
3768
+ }
3769
+
3770
+ let hostSubmissionId: RecoverySnapshot['hostSubmissionId']
3771
+
3772
+ if (submissionRow.joined_host_submission_id !== null) {
3773
+ hostSubmissionId = yield* decodeSubmissionId(
3774
+ submissionRow.joined_host_submission_id,
3775
+ ).pipe(Effect.mapError(internalFailure(operation)))
3776
+ }
3777
+
3778
+ let suspension: SuspensionSnapshot | undefined
3779
+
3780
+ if (submissionRow.suspended_reason_json !== null && submissionRow.suspended_at !== null) {
3781
+ const reason = yield* parseStoredJsonText(submissionRow.suspended_reason_json).pipe(
3782
+ Effect.mapError((error) =>
3783
+ corruptionFailure(
3784
+ operation,
3785
+ 'effect_agent_submissions',
3786
+ validated.submissionId,
3787
+ error.message,
3788
+ )
3789
+ ),
3790
+ )
3791
+
3792
+ suspension = yield* decodeSuspensionSnapshot({
3793
+ reason,
3794
+ suspendedAt: submissionRow.suspended_at,
3795
+ }).pipe(
3796
+ Effect.mapError((error) =>
3797
+ corruptionFailure(
3798
+ operation,
3799
+ 'effect_agent_submissions',
3800
+ validated.submissionId,
3801
+ error.message,
3802
+ )
3803
+ ),
3804
+ )
3805
+ }
3806
+
3807
+ const decisionRows = yield* readApprovalDecisions(operation, validated.submissionId)
3808
+
3809
+ const approvalDecisions: Array<ApprovalDecisionIntent> = []
3810
+
3811
+ for (const row of decisionRows) {
3812
+ approvalDecisions.push(yield* approvalIntentFromRow(operation, row))
3813
+ }
3814
+
3815
+ const resolutionRows = yield* readUnknownResolutions(operation, validated.submissionId)
3816
+
3817
+ const unknownResolutions: Array<UnknownResolutionIntent> = []
3818
+
3819
+ for (const row of resolutionRows) {
3820
+ unknownResolutions.push(yield* unknownResolutionIntentFromRow(operation, row))
3821
+ }
3822
+
3823
+ // Parent-side subagent view: this Submission's child budget reservations in parent
3824
+ // Tool Call order, plus each attached child's current lane state (a disposable
3825
+ // derived view; canonical records stay the recovery truth, DUR-015). The child's
3826
+ // state comes from its local row when this store holds it, and otherwise from the
3827
+ // durable cross-store settlement marker; a child that is neither local nor marked
3828
+ // settled is enriched by the routed per-child lookup one layer out (plan §1.3).
3829
+ const childReservationRows = (yield* cached(
3830
+ rows.childReservations.by('parent_submission_id', validated.submissionId),
3831
+ operation,
3832
+ ))
3833
+ .filter((row) => row.parent_submission_id === validated.submissionId)
3834
+ .sort((a, b) => a.parent_tool_call_id.localeCompare(b.parent_tool_call_id))
3835
+
3836
+ const childReservations: Array<ChildBudgetReservationSnapshot> = []
3837
+
3838
+ for (const row of childReservationRows) {
3839
+ childReservations.push(yield* childReservationSnapshotFromRow(operation, row))
3840
+ }
3841
+
3842
+ const markers = yield* readChildSettlementMarkers(operation, validated.submissionId)
3843
+ const markersByChild = new Map(markers.map((row) => [row.child_submission_id, row]))
3844
+ const childAttachments: Array<ChildAttachmentSnapshot> = []
3845
+
3846
+ for (const row of childReservationRows) {
3847
+ if (row.child_submission_id === null) continue
3848
+ const child = yield* readSubmission(operation, row.child_submission_id)
3849
+
3850
+ if (Option.isSome(child)) {
3851
+ childAttachments.push(
3852
+ yield* decodeChildAttachmentSnapshot({
3853
+ toolCallId: row.parent_tool_call_id,
3854
+ childSubmissionId: row.child_submission_id,
3855
+ childState: child.value.state,
3856
+ ...(child.value.settled_outcome === null
3857
+ ? {}
3858
+ : { childOutcome: child.value.settled_outcome }),
3859
+ }).pipe(Effect.mapError(internalFailure(operation))),
3860
+ )
3861
+ continue
3862
+ }
3863
+ const marker = markersByChild.get(row.child_submission_id)
3864
+
3865
+ if (marker === undefined) continue
3866
+ childAttachments.push(
3867
+ yield* decodeChildAttachmentSnapshot({
3868
+ toolCallId: row.parent_tool_call_id,
3869
+ childSubmissionId: row.child_submission_id,
3870
+ childState: 'settled',
3871
+ ...(marker.child_outcome === null ? {} : { childOutcome: marker.child_outcome }),
3872
+ }).pipe(Effect.mapError(internalFailure(operation))),
3873
+ )
3874
+ }
3875
+
3876
+ let parentLinkage: ParentLinkage | undefined
3877
+
3878
+ if (
3879
+ submissionRow.parent_submission_id !== null &&
3880
+ submissionRow.parent_tool_call_id !== null
3881
+ ) {
3882
+ parentLinkage = yield* decodeParentLinkage({
3883
+ parentSubmissionId: submissionRow.parent_submission_id,
3884
+ parentToolCallId: submissionRow.parent_tool_call_id,
3885
+ }).pipe(Effect.mapError(internalFailure(operation)))
3886
+ }
3887
+
3888
+ return RecoverySnapshot.make({
3889
+ submission,
3890
+ joins,
3891
+ approvalDecisions,
3892
+ unknownResolutions,
3893
+ childReservations,
3894
+ childAttachments,
3895
+ ...(parentLinkage === undefined ? {} : { parentLinkage }),
3896
+ ...(hostSubmissionId === undefined ? {} : { hostSubmissionId }),
3897
+ ...(suspension === undefined ? {} : { suspension }),
3898
+ hasOwner: owner.hasOwner(submissionRow.thread_id, submissionRow.submission_id),
3899
+ ...(inputApplied === undefined ? {} : { inputApplied }),
3900
+ ...(abortIntent === undefined ? {} : { abortIntent }),
3901
+ })
3902
+ }),
3903
+ )
3904
+ },
3905
+ )
3906
+
3907
+ return Context.make(
3908
+ SubmissionLedger,
3909
+ SubmissionLedger.of({
3910
+ capabilities,
3911
+ admit,
3912
+ markReady,
3913
+ lookup,
3914
+ resolveFundingOwner,
3915
+ resolveAdmission,
3916
+ selectHead,
3917
+ markInputApplied,
3918
+ appendInput,
3919
+ finalizeSettlement: (request) => owner.withMutation(finalizeSettlement(request)),
3920
+ requestAbort,
3921
+ stopWorker,
3922
+ inspectWorker,
3923
+ claimJoining,
3924
+ markJoined,
3925
+ revertJoining,
3926
+ suspend: (request) => owner.withMutation(suspend(request)),
3927
+ recordApprovalDecision,
3928
+ markUnknown,
3929
+ recordUnknownResolution,
3930
+ recordChildSettled,
3931
+ reserveChildBudget,
3932
+ attachChildToReservation,
3933
+ beginChildBudgetRelease,
3934
+ releaseChildBudget,
3935
+ scanNonterminal,
3936
+ listNonterminal,
3937
+ loadRecoverySnapshot,
3938
+ readAbortIntent: readAbortIntentForSubmission,
3939
+ }),
3940
+ ).pipe(Context.add(StorageOwner, owner), Context.add(SettlementPublisher, { publish }))
3941
+ })
3942
+
3943
+ /**
3944
+ * Durable Object SubmissionLedger implementation sharing the journal's private SQLite
3945
+ * database, storage-backed transactions, and scoped local owner.
3946
+ * Configuration, failpoint, SQL, Digest, and SecureRandom authority stay visible in the input channel.
3947
+ */
3948
+ export const submissionLedgerLayer: Layer.Layer<
3949
+ SubmissionLedger | SettlementPublisher | StorageOwner,
3950
+ DoStorageInitializationError,
3951
+ | DoStorageConfig
3952
+ | DoStorageFailpoint
3953
+ | SqlClientService.SqlClient
3954
+ | CryptoDigest.Digest
3955
+ | SecureRandom.SecureRandom
3956
+ > = Layer.effectContext(makeServices())
3957
+
3958
+ /**
3959
+ * A composition-root convenience Layer for the durable Submission Ledger. Point it at the
3960
+ * same `ctx.storage` as the ThreadStore so both share the same scoped storage owner.
3961
+ */
3962
+ export const ledgerLayer = (
3963
+ options: DoStorageOptions,
3964
+ ): Layer.Layer<
3965
+ SubmissionLedger | SettlementPublisher | StorageOwner,
3966
+ DoStorageInitializationError
3967
+ > =>
3968
+ Layer.unwrap(
3969
+ Effect.map(DoStorageConfig, (config) =>
3970
+ submissionLedgerLayer.pipe(
3971
+ Layer.provide(
3972
+ Layer.mergeAll(
3973
+ Layer.succeed(DoStorageConfig)(config),
3974
+ storageFailpointLayer(options),
3975
+ SqliteClient.layer({ storage: options.storage }),
3976
+ BrowserCrypto.layer,
3977
+ ),
3978
+ ),
3979
+ )),
3980
+ ).pipe(Layer.provide(storageConfigLayer(options)))