@effect-agent/storage-cloudflare 0.1.0-beta.11 → 0.1.0-beta.110

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 (74) hide show
  1. package/dist/DoMemoryStore.d.mts +29 -0
  2. package/dist/DoMemoryStore.mjs +55 -0
  3. package/dist/DoMemoryStore.mjs.map +1 -0
  4. package/dist/DoMessageDeliveryStore.d.mts +17 -0
  5. package/dist/DoMessageDeliveryStore.mjs +32 -0
  6. package/dist/DoMessageDeliveryStore.mjs.map +1 -0
  7. package/dist/DoScheduleStore.d.mts +36 -0
  8. package/dist/DoScheduleStore.mjs +388 -0
  9. package/dist/DoScheduleStore.mjs.map +1 -0
  10. package/dist/DoStorageConfig.d.mts +45 -0
  11. package/dist/DoStorageConfig.mjs +52 -0
  12. package/dist/DoStorageConfig.mjs.map +1 -0
  13. package/dist/DoStorageError-Cmhvl4TQ.d.mts +98 -0
  14. package/dist/DoStorageError.d.mts +2 -0
  15. package/dist/DoStorageError.mjs +164 -0
  16. package/dist/DoStorageError.mjs.map +1 -0
  17. package/dist/DoStorageFailpoint.d.mts +17 -0
  18. package/dist/DoStorageFailpoint.mjs +14 -0
  19. package/dist/DoStorageFailpoint.mjs.map +1 -0
  20. package/dist/DoStorageFailpointTesting.d.mts +33 -0
  21. package/dist/DoStorageFailpointTesting.mjs +35 -0
  22. package/dist/DoStorageFailpointTesting.mjs.map +1 -0
  23. package/dist/DoStorageVersion-Db6fjP-I.d.mts +12 -0
  24. package/dist/DoStorageVersion.d.mts +2 -0
  25. package/dist/DoStorageVersion.mjs +8 -0
  26. package/dist/DoStorageVersion.mjs.map +1 -0
  27. package/dist/DoSubmissionLedger.d.mts +23 -0
  28. package/dist/DoSubmissionLedger.mjs +1864 -0
  29. package/dist/DoSubmissionLedger.mjs.map +1 -0
  30. package/dist/DoSubscriptionStore.d.mts +25 -0
  31. package/dist/DoSubscriptionStore.mjs +183 -0
  32. package/dist/DoSubscriptionStore.mjs.map +1 -0
  33. package/dist/DoThreadStore.d.mts +59 -0
  34. package/dist/DoThreadStore.mjs +481 -0
  35. package/dist/DoThreadStore.mjs.map +1 -0
  36. package/dist/MemoryProtocol.d.mts +38160 -0
  37. package/dist/MemoryProtocol.mjs +219 -0
  38. package/dist/MemoryProtocol.mjs.map +1 -0
  39. package/dist/PortProtocol.d.mts +4933 -0
  40. package/dist/PortProtocol.mjs +193 -0
  41. package/dist/PortProtocol.mjs.map +1 -0
  42. package/dist/PortRouting.d.mts +86 -0
  43. package/dist/PortRouting.mjs +439 -0
  44. package/dist/PortRouting.mjs.map +1 -0
  45. package/dist/do-journal-THW8-ZeP.mjs +1041 -0
  46. package/dist/do-journal-THW8-ZeP.mjs.map +1 -0
  47. package/dist/index.d.mts +14 -1525
  48. package/dist/index.mjs +14 -3695
  49. package/dist/migrations-DZKTNU88.mjs +291 -0
  50. package/dist/migrations-DZKTNU88.mjs.map +1 -0
  51. package/dist/rolldown-runtime-D7D4PA-g.mjs +13 -0
  52. package/package.json +1 -45
  53. package/src/DoMemoryStore.ts +56 -0
  54. package/src/DoMessageDeliveryStore.ts +53 -0
  55. package/src/DoScheduleStore.ts +622 -0
  56. package/src/{errors.ts → DoStorageError.ts} +10 -3
  57. package/src/DoStorageFailpoint.ts +20 -0
  58. package/src/{do-storage-failpoint.ts → DoStorageFailpointTesting.ts} +5 -18
  59. package/src/DoStorageVersion.ts +2 -0
  60. package/src/{do-ledger.ts → DoSubmissionLedger.ts} +960 -237
  61. package/src/DoSubscriptionStore.ts +329 -0
  62. package/src/DoThreadStore.ts +1039 -0
  63. package/src/MemoryProtocol.ts +351 -0
  64. package/src/{port-protocol.ts → PortProtocol.ts} +76 -38
  65. package/src/{routing.ts → PortRouting.ts} +374 -264
  66. package/src/index.ts +13 -32
  67. package/src/internal/do-journal.ts +1656 -0
  68. package/src/internal/message-delivery-schema.ts +24 -0
  69. package/src/{migrations.ts → internal/migrations.ts} +55 -35
  70. package/src/internal/recovery-checkpoint-schema.ts +17 -0
  71. package/dist/index.mjs.map +0 -1
  72. package/src/do-conversation-store.ts +0 -850
  73. package/src/do-journal.ts +0 -1078
  74. /package/src/{do-storage-config.ts → DoStorageConfig.ts} +0 -0
@@ -0,0 +1,1864 @@
1
+ import { t as __exportAll } from "./rolldown-runtime-D7D4PA-g.mjs";
2
+ import { DoStorageConfig } from "./DoStorageConfig.mjs";
3
+ import { DoStorageFailpoint } from "./DoStorageFailpoint.mjs";
4
+ import { DoLedgerError, DoStorageCorruptionError, DoStorageError } from "./DoStorageError.mjs";
5
+ import { a as initializeDoJournal, i as decodeRows } from "./do-journal-THW8-ZeP.mjs";
6
+ import { storageConfigLayer, storageFailpointLayer } from "./DoThreadStore.mjs";
7
+ import { Clock, Context, Crypto, DateTime, Effect, Layer, Option, Schema, Stream } from "effect";
8
+ import * as SqlClientService from "effect/unstable/sql/SqlClient";
9
+ import { SqliteClient } from "@effect/sql-sqlite-do";
10
+ import { EMPTY_TAIL_DIGEST } from "effect-agent/digest";
11
+ import { ApprovalDecision, CanonicalSequence, DefinitionDigests, Digest, PersistedJson, ProducerEpoch, RecordEnvelope, SettlementOutcome, WorkerAdmission } from "effect-agent/records";
12
+ import { BrowserCrypto } from "@effect/platform-browser";
13
+ import { InputMessage } from "effect-agent/messaging";
14
+ import { AbortCommand, AbortIntent, AbortIntentRequest, AdmissionAdmitted, AdmissionConflict, AdmissionFence, AdmissionGroup, AdmissionNotAdmitted, AdmissionPolicyError, AdmissionRequest, AdmissionResult, ApprovalConflict, ApprovalDecisionCommand, ApprovalDecisionIntent, AttachChildToReservationRequest, BeginChildBudgetReleaseRequest, ChildAttachmentSnapshot, ChildBudgetReservationRequest, ChildBudgetReservationSnapshot, ChildReservationConflict, ChildReservationStatus, ChildSettledNotification, Claim, ClaimJoiningRequest, ClaimRequest, InputAppliedMarker, JoinSnapshot, JoinedToHost, JoiningClaim, LedgerCapabilities, LedgerError, MarkInputAppliedRequest, MarkJoinedRequest, MarkReadyRequest, MarkUnknownRequest, OwnershipLost, OwnershipRenewal, OwnershipSnapshot, ParentLinkage, QueueSequence, RecoverySnapshot, RecoverySnapshotRequest, ReleaseChildBudgetRequest, ReleaseOwnershipRequest, RenewOwnershipRequest, ReservedChildBudget, ReservedSettlement, RevertJoiningRequest, Settlement, SettlementConflict, SettlementFinalization, SettlementReservation, SettlementReservationSnapshot, SubmissionAdmissionFence, SubmissionLedger, SubmissionLookup, SubmissionLookupByKey, SubmissionSnapshot, SubmissionState, SuspendRequest, SuspensionReason, SuspensionSnapshot, UnknownResolution, UnknownResolutionCommand, UnknownResolutionConflict, UnknownResolutionIntent, settlementFailureFromRecord, submissionAbortRecordId } from "effect-agent/submission-ledger";
15
+ //#region src/DoSubmissionLedger.ts
16
+ var DoSubmissionLedger_exports = /* @__PURE__ */ __exportAll({
17
+ ledgerLayer: () => ledgerLayer,
18
+ submissionLedgerLayer: () => submissionLedgerLayer
19
+ });
20
+ /**
21
+ * Static decode-side ceiling; writes are bounded in bytes by the configured
22
+ * `maxStoredValueBytes` (see do-journal.ts).
23
+ */
24
+ const BoundedStoredText = Schema.String.check(Schema.isMaxLength(2e6));
25
+ const BoundedIdentifier = Schema.NonEmptyString.check(Schema.isMaxLength(1024));
26
+ const BoundedTimestamp = Schema.NonEmptyString.check(Schema.isMaxLength(128));
27
+ const SCAN_PAGE_SIZE = 256;
28
+ const EPOCH_ZERO = Schema.decodeSync(ProducerEpoch)(0);
29
+ const RESUME_IMMEDIATELY = "resume-immediately";
30
+ const SUSPENDED = "suspended";
31
+ const NOT_WAITING = "not-waiting";
32
+ const STILL_WAITING = "still-waiting";
33
+ const WOKEN = "woken";
34
+ const MAX_IDENTIFIER_LENGTH = 1024;
35
+ var SubmissionRow = class extends Schema.Class("SubmissionRow")({
36
+ submission_id: BoundedIdentifier,
37
+ thread_id: BoundedIdentifier,
38
+ queue_sequence: QueueSequence,
39
+ principal: BoundedIdentifier,
40
+ idempotency_key: BoundedIdentifier,
41
+ agent_id: BoundedIdentifier,
42
+ agent_digests_json: BoundedStoredText,
43
+ deployment_id: BoundedIdentifier,
44
+ input_json: BoundedStoredText,
45
+ input_digest: Digest,
46
+ receipt_id: BoundedIdentifier,
47
+ state: SubmissionState,
48
+ settled_outcome: Schema.NullOr(SettlementOutcome),
49
+ created_at: BoundedTimestamp,
50
+ ready_at: Schema.NullOr(BoundedTimestamp),
51
+ input_applied_record_id: Schema.NullOr(BoundedIdentifier),
52
+ input_applied_sequence: Schema.NullOr(CanonicalSequence),
53
+ joined_host_submission_id: Schema.NullOr(BoundedIdentifier),
54
+ suspended_reason_json: Schema.NullOr(BoundedStoredText),
55
+ suspended_at: Schema.NullOr(BoundedTimestamp),
56
+ unknown_reason: Schema.NullOr(BoundedStoredText),
57
+ unknown_tool_call_ids_json: Schema.NullOr(BoundedStoredText),
58
+ parent_submission_id: Schema.NullOr(BoundedIdentifier),
59
+ parent_tool_call_id: Schema.NullOr(BoundedIdentifier),
60
+ admission_group: Schema.NullOr(AdmissionGroup),
61
+ admission_fence_json: Schema.NullOr(BoundedStoredText),
62
+ worker_admission_json: Schema.NullOr(BoundedStoredText),
63
+ message_admission_json: Schema.NullOr(BoundedStoredText)
64
+ }) {};
65
+ var ChildReservationRow = class extends Schema.Class("ChildReservationRow")({
66
+ reservation_id: BoundedIdentifier,
67
+ parent_submission_id: BoundedIdentifier,
68
+ parent_tool_call_id: BoundedIdentifier,
69
+ child_submission_id: Schema.NullOr(BoundedIdentifier),
70
+ status: ChildReservationStatus,
71
+ allocation_json: BoundedStoredText,
72
+ allocation_digest: Digest,
73
+ accounting_json: Schema.NullOr(BoundedStoredText),
74
+ reserved_at: BoundedTimestamp,
75
+ release_began_at: Schema.NullOr(BoundedTimestamp),
76
+ released_at: Schema.NullOr(BoundedTimestamp)
77
+ }) {};
78
+ var ChildSettlementMarkerRow = class extends Schema.Class("ChildSettlementMarkerRow")({
79
+ parent_submission_id: BoundedIdentifier,
80
+ child_submission_id: BoundedIdentifier,
81
+ child_outcome: Schema.NullOr(SettlementOutcome),
82
+ recorded_at: BoundedTimestamp
83
+ }) {};
84
+ var ApprovalDecisionRow = class extends Schema.Class("ApprovalDecisionRow")({
85
+ submission_id: BoundedIdentifier,
86
+ tool_call_id: BoundedIdentifier,
87
+ decision: ApprovalDecision,
88
+ resolver: BoundedIdentifier,
89
+ reason: BoundedStoredText,
90
+ decided_at: BoundedTimestamp
91
+ }) {};
92
+ var UnknownResolutionRow = class extends Schema.Class("UnknownResolutionRow")({
93
+ submission_id: BoundedIdentifier,
94
+ tool_call_id: BoundedIdentifier,
95
+ author: BoundedIdentifier,
96
+ reason: BoundedStoredText,
97
+ resolution_json: BoundedStoredText,
98
+ resolved_at: BoundedTimestamp
99
+ }) {};
100
+ var OwnershipRow = class extends Schema.Class("OwnershipRow")({
101
+ submission_id: BoundedIdentifier,
102
+ attempt_id: BoundedIdentifier,
103
+ ownership_token: BoundedIdentifier,
104
+ producer_epoch: ProducerEpoch,
105
+ owner_producer_id: BoundedIdentifier,
106
+ lease_expires_at: BoundedTimestamp
107
+ }) {};
108
+ var ReservationRow = class extends Schema.Class("ReservationRow")({
109
+ submission_id: BoundedIdentifier,
110
+ settlement_id: BoundedIdentifier,
111
+ outcome: SettlementOutcome,
112
+ record_id: BoundedIdentifier,
113
+ record_json: BoundedStoredText,
114
+ record_digest: Digest,
115
+ reserved_at: BoundedTimestamp,
116
+ finalized_at: Schema.NullOr(BoundedTimestamp)
117
+ }) {};
118
+ var AbortIntentRow = class extends Schema.Class("AbortIntentRow")({
119
+ submission_id: BoundedIdentifier,
120
+ author: BoundedIdentifier,
121
+ reason: BoundedStoredText,
122
+ requested_at: BoundedTimestamp,
123
+ canonical_record_id: Schema.NullOr(BoundedIdentifier)
124
+ }) {};
125
+ var MaxQueueSequenceRow = class extends Schema.Class("MaxQueueSequenceRow")({ max_queue_sequence: Schema.Int.check(Schema.isGreaterThanOrEqualTo(0)) }) {};
126
+ var AbortIntentLookupRow = class extends Schema.Class("AbortIntentLookupRow")({
127
+ submission_id: BoundedIdentifier,
128
+ abort_submission_id: Schema.NullOr(BoundedIdentifier),
129
+ author: Schema.NullOr(BoundedIdentifier),
130
+ reason: Schema.NullOr(BoundedStoredText),
131
+ requested_at: Schema.NullOr(BoundedTimestamp),
132
+ canonical_record_id: Schema.NullOr(BoundedIdentifier)
133
+ }) {};
134
+ var CanonicalRecordIdRow = class extends Schema.Class("CanonicalRecordIdRow")({ record_id: BoundedIdentifier }) {};
135
+ const SUBMISSION_COLUMNS = `
136
+ submission_id,
137
+ thread_id,
138
+ queue_sequence,
139
+ principal,
140
+ idempotency_key,
141
+ agent_id,
142
+ agent_digests_json,
143
+ deployment_id,
144
+ input_json,
145
+ input_digest,
146
+ receipt_id,
147
+ state,
148
+ settled_outcome,
149
+ created_at,
150
+ ready_at,
151
+ input_applied_record_id,
152
+ input_applied_sequence,
153
+ joined_host_submission_id,
154
+ suspended_reason_json,
155
+ suspended_at,
156
+ unknown_reason,
157
+ unknown_tool_call_ids_json,
158
+ parent_submission_id,
159
+ parent_tool_call_id,
160
+ admission_group,
161
+ admission_fence_json,
162
+ worker_admission_json,
163
+ message_admission_json
164
+ `;
165
+ const CHILD_RESERVATION_COLUMNS = `
166
+ reservation_id,
167
+ parent_submission_id,
168
+ parent_tool_call_id,
169
+ child_submission_id,
170
+ status,
171
+ allocation_json,
172
+ allocation_digest,
173
+ accounting_json,
174
+ reserved_at,
175
+ release_began_at,
176
+ released_at
177
+ `;
178
+ /** The branded ToolCallId schema, reached through the thread port so no core import is needed. */
179
+ const ToolCallIdSchema = ApprovalDecisionCommand.fields.toolCallId;
180
+ const ToolCallIdList = Schema.Array(ToolCallIdSchema);
181
+ const encodePersistedJsonText = Schema.encodeEffect(Schema.fromJsonString(PersistedJson));
182
+ const encodeDefinitionDigestsText = Schema.encodeEffect(Schema.fromJsonString(DefinitionDigests));
183
+ const encodeRecordEnvelopeText = Schema.encodeEffect(Schema.fromJsonString(RecordEnvelope));
184
+ const decodeRecordEnvelopeText = Schema.decodeEffect(Schema.fromJsonString(RecordEnvelope));
185
+ const encodeSuspensionReasonText = Schema.encodeEffect(Schema.fromJsonString(SuspensionReason));
186
+ const encodeUnknownResolutionText = Schema.encodeEffect(Schema.fromJsonString(UnknownResolution));
187
+ const encodeToolCallIdsText = Schema.encodeEffect(Schema.fromJsonString(ToolCallIdList));
188
+ const decodeToolCallIdsText = Schema.decodeEffect(Schema.fromJsonString(ToolCallIdList));
189
+ const parseStoredJsonText = Schema.decodeEffect(Schema.fromJsonString(Schema.Json));
190
+ const decodeAdmissionResult = Schema.decodeUnknownEffect(AdmissionResult);
191
+ const decodeClaim = Schema.decodeUnknownEffect(Claim);
192
+ const decodeOwnershipRenewal = Schema.decodeUnknownEffect(OwnershipRenewal);
193
+ const decodeSettlement = Schema.decodeUnknownEffect(Settlement);
194
+ const decodeAbortIntent = Schema.decodeUnknownEffect(AbortIntent);
195
+ const decodeOwnershipSnapshot = Schema.decodeUnknownEffect(OwnershipSnapshot);
196
+ const decodeInputAppliedMarker = Schema.decodeUnknownEffect(InputAppliedMarker);
197
+ const decodeSubmissionSnapshotUnknown = Schema.decodeUnknownEffect(SubmissionSnapshot);
198
+ const decodeSubmissionId = Schema.decodeUnknownEffect(SubmissionSnapshot.fields.submissionId);
199
+ const decodeQueueSequence = Schema.decodeUnknownEffect(QueueSequence);
200
+ const decodeUtcInstant = Schema.decodeUnknownEffect(Schema.DateTimeUtcFromString);
201
+ const decodeJoiningClaim = Schema.decodeUnknownEffect(JoiningClaim);
202
+ const decodeJoinSnapshot = Schema.decodeUnknownEffect(JoinSnapshot);
203
+ const decodeSuspensionSnapshot = Schema.decodeUnknownEffect(SuspensionSnapshot);
204
+ const decodeApprovalDecisionIntent = Schema.decodeUnknownEffect(ApprovalDecisionIntent);
205
+ const decodeUnknownResolutionIntent = Schema.decodeUnknownEffect(UnknownResolutionIntent);
206
+ const decodeParentLinkage = Schema.decodeUnknownEffect(ParentLinkage);
207
+ const decodeChildReservationSnapshotUnknown = Schema.decodeUnknownEffect(ChildBudgetReservationSnapshot);
208
+ const decodeChildAttachmentSnapshot = Schema.decodeUnknownEffect(ChildAttachmentSnapshot);
209
+ const equivalentPersistedJson = Schema.toEquivalence(PersistedJson);
210
+ const equivalentUnknownResolution = Schema.toEquivalence(UnknownResolution);
211
+ const isDoStorageError = Schema.is(DoStorageError);
212
+ /** Wrap an adapter-internal failure into the port's LedgerError without erasing its tag. */
213
+ const internalFailure = (operation) => (error) => LedgerError.make({
214
+ operation,
215
+ message: error.message,
216
+ cause: error
217
+ });
218
+ /**
219
+ * Classify raw SQL failures. Within one Durable Object there is exactly one writer, so the
220
+ * Node adapter's retryable `SqliteWriteContention` classification has no analogue: every raw
221
+ * failure is a `DoLedgerError` preserved as the LedgerError's cause.
222
+ */
223
+ const sqlFailure = (operation) => (error) => internalFailure(operation)(DoLedgerError.make({
224
+ cause: error,
225
+ operation,
226
+ message: error.message
227
+ }));
228
+ const corruptionFailure = (operation, table, rowKey, message) => internalFailure(operation)(DoStorageCorruptionError.make({
229
+ table,
230
+ rowKey,
231
+ message
232
+ }));
233
+ const makeServices = Effect.fn("DoSubmissionLedger.makeServices")(function* () {
234
+ const config = yield* DoStorageConfig;
235
+ const failpoint = yield* DoStorageFailpoint;
236
+ const sql = yield* SqlClientService.SqlClient;
237
+ const crypto = yield* Crypto.Crypto;
238
+ const admissionFence = yield* SubmissionAdmissionFence;
239
+ const journal = yield* initializeDoJournal(sql, failpoint.hit, config.maxStoredValueBytes);
240
+ const hitFailpoint = (location, operation) => failpoint.hit(location).pipe(Effect.mapError((error) => internalFailure(operation)(error)));
241
+ /**
242
+ * Run one ledger mutation under the journal's Durable Object storage-backed transaction so
243
+ * ownership-token and epoch checks are atomic with their writes (DUR-006). Transaction
244
+ * failures surface as LedgerError carrying the typed `DoStorageError` as cause.
245
+ */
246
+ const inWriteTransaction = (operation, effect) => journal.withWriteTransaction(operation)(effect).pipe(Effect.mapError((error) => isDoStorageError(error) ? internalFailure(operation)(error) : error));
247
+ const mintUuid = (operation) => crypto.randomUUIDv7.pipe(Effect.mapError((error) => internalFailure(operation)(error)));
248
+ const currentInstant = Effect.map(Clock.currentTimeMillis, (millis) => ({
249
+ millis,
250
+ iso: new Date(millis).toISOString()
251
+ }));
252
+ const timestampMillis = (operation, rowKey) => (timestamp) => decodeUtcInstant(timestamp).pipe(Effect.map(DateTime.toEpochMillis), Effect.mapError((error) => corruptionFailure(operation, "effect_agent_submission_ownership", rowKey, error.message)));
253
+ const decodeSubmissionRows = (operation, rowKey, rows) => decodeRows(Schema.Array(SubmissionRow), "effect_agent_submissions", rowKey, rows).pipe(Effect.mapError(internalFailure(operation)));
254
+ const readSubmission = Effect.fn("DoSubmissionLedger.readSubmission")(function* (operation, submissionId) {
255
+ const rows = yield* sql`
256
+ SELECT ${sql.literal(SUBMISSION_COLUMNS)}
257
+ FROM effect_agent_submissions
258
+ WHERE submission_id = ${submissionId}
259
+ `.pipe(Effect.mapError(sqlFailure(operation)));
260
+ const decoded = yield* decodeSubmissionRows(operation, submissionId, rows);
261
+ if (decoded.length > 1) return yield* corruptionFailure(operation, "effect_agent_submissions", submissionId, "A submission primary key returned more than one row.");
262
+ return decoded.length === 0 ? Option.none() : Option.some(decoded[0]);
263
+ });
264
+ const requireSubmission = Effect.fn("DoSubmissionLedger.requireSubmission")(function* (operation, submissionId) {
265
+ const submission = yield* readSubmission(operation, submissionId);
266
+ if (Option.isNone(submission)) return yield* LedgerError.make({
267
+ operation,
268
+ message: `Unknown submission ${submissionId}.`
269
+ });
270
+ return submission.value;
271
+ });
272
+ const readOwnership = Effect.fn("DoSubmissionLedger.readOwnership")(function* (operation, submissionId) {
273
+ const rows = yield* sql`
274
+ SELECT
275
+ submission_id,
276
+ attempt_id,
277
+ ownership_token,
278
+ producer_epoch,
279
+ owner_producer_id,
280
+ lease_expires_at
281
+ FROM effect_agent_submission_ownership
282
+ WHERE submission_id = ${submissionId}
283
+ `.pipe(Effect.mapError(sqlFailure(operation)));
284
+ const decoded = yield* decodeRows(Schema.Array(OwnershipRow), "effect_agent_submission_ownership", submissionId, rows).pipe(Effect.mapError(internalFailure(operation)));
285
+ if (decoded.length > 1) return yield* corruptionFailure(operation, "effect_agent_submission_ownership", submissionId, "An ownership primary key returned more than one row.");
286
+ return decoded.length === 0 ? Option.none() : Option.some(decoded[0]);
287
+ });
288
+ const threadEpoch = Effect.fn("DoSubmissionLedger.threadEpoch")(function* (operation, threadId) {
289
+ const threads = yield* journal.getThread(threadId).pipe(Effect.mapError(internalFailure(operation)));
290
+ return threads.length === 0 ? EPOCH_ZERO : threads[0].producer_epoch;
291
+ });
292
+ /**
293
+ * Verify inside the surrounding write transaction that the presented token still owns the
294
+ * Submission's lane; a superseded or missing token fails with OwnershipLost carrying the
295
+ * Thread's current producer epoch (DUR-006).
296
+ */
297
+ const requireOwnership = Effect.fn("DoSubmissionLedger.requireOwnership")(function* (operation, submission, ownershipToken) {
298
+ const ownership = yield* readOwnership(operation, submission.submission_id);
299
+ const actualEpoch = yield* threadEpoch(operation, submission.thread_id);
300
+ if (Option.isNone(ownership) || ownership.value.ownership_token !== ownershipToken || ownership.value.producer_epoch !== actualEpoch) {
301
+ const submissionId = yield* Schema.decodeEffect(SubmissionSnapshot.fields.submissionId)(submission.submission_id).pipe(Effect.mapError(internalFailure(operation)));
302
+ return yield* OwnershipLost.make({
303
+ submissionId,
304
+ actualEpoch
305
+ });
306
+ }
307
+ return ownership.value;
308
+ });
309
+ const decodeSubmissionSnapshot = Effect.fn("DoSubmissionLedger.decodeSubmissionSnapshot")(function* (operation, row) {
310
+ const agentDigests = yield* parseStoredJsonText(row.agent_digests_json).pipe(Effect.mapError((error) => corruptionFailure(operation, "effect_agent_submissions", row.submission_id, error.message)));
311
+ const inputPayload = yield* parseStoredJsonText(row.input_json).pipe(Effect.mapError((error) => corruptionFailure(operation, "effect_agent_submissions", row.submission_id, error.message)));
312
+ if (row.parent_submission_id === null !== (row.parent_tool_call_id === null)) return yield* corruptionFailure(operation, "effect_agent_submissions", row.submission_id, "A parent linkage must record both the parent Submission and the parent Tool Call.");
313
+ return yield* decodeSubmissionSnapshotUnknown({
314
+ submissionId: row.submission_id,
315
+ threadId: row.thread_id,
316
+ queueSequence: row.queue_sequence,
317
+ principal: row.principal,
318
+ idempotencyKey: row.idempotency_key,
319
+ agentId: row.agent_id,
320
+ agentDigests,
321
+ deploymentId: row.deployment_id,
322
+ inputPayload,
323
+ inputDigest: row.input_digest,
324
+ receiptId: row.receipt_id,
325
+ state: row.state,
326
+ createdAt: row.created_at,
327
+ ...row.admission_group === null ? {} : { admissionGroup: row.admission_group },
328
+ ...row.worker_admission_json === null ? {} : { workerAdmission: yield* parseStoredJsonText(row.worker_admission_json).pipe(Effect.mapError(internalFailure(operation))) },
329
+ ...row.message_admission_json === null ? {} : { messageAdmission: yield* parseStoredJsonText(row.message_admission_json).pipe(Effect.mapError(internalFailure(operation))) },
330
+ ...row.admission_fence_json === null ? {} : { admissionFence: yield* parseStoredJsonText(row.admission_fence_json).pipe(Effect.mapError(internalFailure(operation))) },
331
+ ...row.settled_outcome === null ? {} : { settledOutcome: row.settled_outcome },
332
+ ...row.ready_at === null ? {} : { readyAt: row.ready_at },
333
+ ...row.parent_submission_id === null || row.parent_tool_call_id === null ? {} : { parentLinkage: {
334
+ parentSubmissionId: row.parent_submission_id,
335
+ parentToolCallId: row.parent_tool_call_id
336
+ } }
337
+ }).pipe(Effect.mapError((error) => corruptionFailure(operation, "effect_agent_submissions", row.submission_id, error.message)));
338
+ });
339
+ const readReservation = Effect.fn("DoSubmissionLedger.readReservation")(function* (operation, submissionId) {
340
+ const rows = yield* sql`
341
+ SELECT
342
+ submission_id,
343
+ settlement_id,
344
+ outcome,
345
+ record_id,
346
+ record_json,
347
+ record_digest,
348
+ reserved_at,
349
+ finalized_at
350
+ FROM effect_agent_settlement_reservations
351
+ WHERE submission_id = ${submissionId}
352
+ `.pipe(Effect.mapError(sqlFailure(operation)));
353
+ const decoded = yield* decodeRows(Schema.Array(ReservationRow), "effect_agent_settlement_reservations", submissionId, rows).pipe(Effect.mapError(internalFailure(operation)));
354
+ if (decoded.length > 1) return yield* corruptionFailure(operation, "effect_agent_settlement_reservations", submissionId, "A settlement reservation primary key returned more than one row.");
355
+ return decoded.length === 0 ? Option.none() : Option.some(decoded[0]);
356
+ });
357
+ const readAbortIntent = Effect.fn("DoSubmissionLedger.readAbortIntent")(function* (operation, submissionId) {
358
+ const rows = yield* sql`
359
+ SELECT
360
+ submission_id,
361
+ author,
362
+ reason,
363
+ requested_at,
364
+ canonical_record_id
365
+ FROM effect_agent_abort_intents
366
+ WHERE submission_id = ${submissionId}
367
+ `.pipe(Effect.mapError(sqlFailure(operation)));
368
+ const decoded = yield* decodeRows(Schema.Array(AbortIntentRow), "effect_agent_abort_intents", submissionId, rows).pipe(Effect.mapError(internalFailure(operation)));
369
+ if (decoded.length > 1) return yield* corruptionFailure(operation, "effect_agent_abort_intents", submissionId, "An abort intent primary key returned more than one row.");
370
+ return decoded.length === 0 ? Option.none() : Option.some(decoded[0]);
371
+ });
372
+ /**
373
+ * Read the durable cross-store child-settlement markers recorded against one parent
374
+ * Submission (the DC realization of the port's "cross-store adapters record a durable
375
+ * notification marker" contract).
376
+ */
377
+ const readChildSettlementMarkers = Effect.fn("DoSubmissionLedger.readChildSettlementMarkers")(function* (operation, parentSubmissionId) {
378
+ const rows = yield* sql`
379
+ SELECT
380
+ parent_submission_id,
381
+ child_submission_id,
382
+ child_outcome,
383
+ recorded_at
384
+ FROM effect_agent_child_settlements
385
+ WHERE parent_submission_id = ${parentSubmissionId}
386
+ ORDER BY child_submission_id ASC
387
+ `.pipe(Effect.mapError(sqlFailure(operation)));
388
+ return yield* decodeRows(Schema.Array(ChildSettlementMarkerRow), "effect_agent_child_settlements", parentSubmissionId, rows).pipe(Effect.mapError(internalFailure(operation)));
389
+ });
390
+ /**
391
+ * Whether one listed child is provably settled from THIS store: either its own row lives
392
+ * here and is settled (single-store evidence, identical to the Node adapter), or a durable
393
+ * cross-store notification marker was recorded for it (the child's row lives in another
394
+ * Durable Object and its owner reported the settlement through `recordChildSettled`).
395
+ */
396
+ const childProvablySettled = Effect.fn("DoSubmissionLedger.childProvablySettled")(function* (operation, markerChildren, childSubmissionId) {
397
+ if (markerChildren.has(childSubmissionId)) return true;
398
+ const childRow = yield* readSubmission(operation, childSubmissionId);
399
+ return Option.isSome(childRow) && childRow.value.state === "settled";
400
+ });
401
+ const decodeChildReservationRows = (operation, rowKey, rows) => decodeRows(Schema.Array(ChildReservationRow), "effect_agent_child_reservations", rowKey, rows).pipe(Effect.mapError(internalFailure(operation)));
402
+ const readChildReservation = Effect.fn("DoSubmissionLedger.readChildReservation")(function* (operation, reservationId) {
403
+ const rows = yield* sql`
404
+ SELECT ${sql.literal(CHILD_RESERVATION_COLUMNS)}
405
+ FROM effect_agent_child_reservations
406
+ WHERE reservation_id = ${reservationId}
407
+ `.pipe(Effect.mapError(sqlFailure(operation)));
408
+ const decoded = yield* decodeChildReservationRows(operation, reservationId, rows);
409
+ if (decoded.length > 1) return yield* corruptionFailure(operation, "effect_agent_child_reservations", reservationId, "A child reservation primary key returned more than one row.");
410
+ return decoded.length === 0 ? Option.none() : Option.some(decoded[0]);
411
+ });
412
+ const readChildReservationForCall = Effect.fn("DoSubmissionLedger.readChildReservationForCall")(function* (operation, parentSubmissionId, parentToolCallId) {
413
+ const rows = yield* sql`
414
+ SELECT ${sql.literal(CHILD_RESERVATION_COLUMNS)}
415
+ FROM effect_agent_child_reservations
416
+ WHERE parent_submission_id = ${parentSubmissionId}
417
+ AND parent_tool_call_id = ${parentToolCallId}
418
+ `.pipe(Effect.mapError(sqlFailure(operation)));
419
+ const decoded = yield* decodeChildReservationRows(operation, `${parentSubmissionId}/${parentToolCallId}`, rows);
420
+ if (decoded.length > 1) return yield* corruptionFailure(operation, "effect_agent_child_reservations", `${parentSubmissionId}/${parentToolCallId}`, "A parent Tool Call returned more than one child reservation.");
421
+ return decoded.length === 0 ? Option.none() : Option.some(decoded[0]);
422
+ });
423
+ const childReservationSnapshotFromRow = Effect.fn("DoSubmissionLedger.childReservationSnapshotFromRow")(function* (operation, row) {
424
+ const rowFailure = (error) => corruptionFailure(operation, "effect_agent_child_reservations", row.reservation_id, error.message);
425
+ const allocation = yield* parseStoredJsonText(row.allocation_json).pipe(Effect.mapError(rowFailure));
426
+ const accounting = row.accounting_json === null ? void 0 : yield* parseStoredJsonText(row.accounting_json).pipe(Effect.mapError(rowFailure));
427
+ return yield* decodeChildReservationSnapshotUnknown({
428
+ reservationId: row.reservation_id,
429
+ parentSubmissionId: row.parent_submission_id,
430
+ parentToolCallId: row.parent_tool_call_id,
431
+ status: row.status,
432
+ allocation,
433
+ allocationDigest: row.allocation_digest,
434
+ reservedAt: row.reserved_at,
435
+ ...row.child_submission_id === null ? {} : { childSubmissionId: row.child_submission_id },
436
+ ...accounting === void 0 ? {} : { accounting },
437
+ ...row.release_began_at === null ? {} : { releaseBeganAt: row.release_began_at },
438
+ ...row.released_at === null ? {} : { releasedAt: row.released_at }
439
+ }).pipe(Effect.mapError(rowFailure));
440
+ });
441
+ const readApprovalDecisions = Effect.fn("DoSubmissionLedger.readApprovalDecisions")(function* (operation, submissionId) {
442
+ const rows = yield* sql`
443
+ SELECT
444
+ submission_id,
445
+ tool_call_id,
446
+ decision,
447
+ resolver,
448
+ reason,
449
+ decided_at
450
+ FROM effect_agent_approval_decisions
451
+ WHERE submission_id = ${submissionId}
452
+ ORDER BY tool_call_id ASC
453
+ `.pipe(Effect.mapError(sqlFailure(operation)));
454
+ return yield* decodeRows(Schema.Array(ApprovalDecisionRow), "effect_agent_approval_decisions", submissionId, rows).pipe(Effect.mapError(internalFailure(operation)));
455
+ });
456
+ const approvalIntentFromRow = Effect.fn("DoSubmissionLedger.approvalIntentFromRow")(function* (operation, row) {
457
+ return yield* decodeApprovalDecisionIntent({
458
+ submissionId: row.submission_id,
459
+ toolCallId: row.tool_call_id,
460
+ decision: row.decision,
461
+ resolver: row.resolver,
462
+ reason: row.reason,
463
+ decidedAt: row.decided_at
464
+ }).pipe(Effect.mapError((error) => corruptionFailure(operation, "effect_agent_approval_decisions", `${row.submission_id}/${row.tool_call_id}`, error.message)));
465
+ });
466
+ const readUnknownResolutions = Effect.fn("DoSubmissionLedger.readUnknownResolutions")(function* (operation, submissionId) {
467
+ const rows = yield* sql`
468
+ SELECT
469
+ submission_id,
470
+ tool_call_id,
471
+ author,
472
+ reason,
473
+ resolution_json,
474
+ resolved_at
475
+ FROM effect_agent_unknown_resolutions
476
+ WHERE submission_id = ${submissionId}
477
+ ORDER BY tool_call_id ASC
478
+ `.pipe(Effect.mapError(sqlFailure(operation)));
479
+ return yield* decodeRows(Schema.Array(UnknownResolutionRow), "effect_agent_unknown_resolutions", submissionId, rows).pipe(Effect.mapError(internalFailure(operation)));
480
+ });
481
+ const unknownResolutionIntentFromRow = Effect.fn("DoSubmissionLedger.unknownResolutionIntentFromRow")(function* (operation, row) {
482
+ const resolution = yield* parseStoredJsonText(row.resolution_json).pipe(Effect.mapError((error) => corruptionFailure(operation, "effect_agent_unknown_resolutions", `${row.submission_id}/${row.tool_call_id}`, error.message)));
483
+ return yield* decodeUnknownResolutionIntent({
484
+ submissionId: row.submission_id,
485
+ toolCallId: row.tool_call_id,
486
+ author: row.author,
487
+ reason: row.reason,
488
+ resolution,
489
+ resolvedAt: row.resolved_at
490
+ }).pipe(Effect.mapError((error) => corruptionFailure(operation, "effect_agent_unknown_resolutions", `${row.submission_id}/${row.tool_call_id}`, error.message)));
491
+ });
492
+ /** The Submission's marked-unknown open Tool Call identities, empty when never marked. */
493
+ const storedUnknownToolCallIds = Effect.fn("DoSubmissionLedger.storedUnknownToolCallIds")(function* (operation, submission) {
494
+ if (submission.unknown_tool_call_ids_json === null) return [];
495
+ return yield* decodeToolCallIdsText(submission.unknown_tool_call_ids_json).pipe(Effect.mapError((error) => corruptionFailure(operation, "effect_agent_submissions", submission.submission_id, error.message)));
496
+ });
497
+ /**
498
+ * Canonical history is the abort authority (DUR-015): the intent's canonicalRecordId is
499
+ * derived from the shared canonical-records table using the deterministic abort record
500
+ * identity, never from a cached ledger marker.
501
+ */
502
+ const canonicalAbortRecordId = Effect.fn("DoSubmissionLedger.canonicalAbortRecordId")(function* (operation, threadId, submissionId) {
503
+ const recordId = submissionAbortRecordId(submissionId);
504
+ const rows = yield* sql`
505
+ SELECT record_id
506
+ FROM effect_agent_canonical_records
507
+ WHERE thread_id = ${threadId}
508
+ AND record_id = ${recordId}
509
+ `.pipe(Effect.mapError(sqlFailure(operation)));
510
+ return (yield* decodeRows(Schema.Array(CanonicalRecordIdRow), "effect_agent_canonical_records", `${threadId}/${recordId}`, rows).pipe(Effect.mapError(internalFailure(operation)))).length === 0 ? void 0 : recordId;
511
+ });
512
+ const abortIntentFromRow = Effect.fn("DoSubmissionLedger.abortIntentFromRow")(function* (operation, submission, submissionId, row) {
513
+ const canonicalRecordId = yield* canonicalAbortRecordId(operation, submission.thread_id, submissionId);
514
+ return yield* decodeAbortIntent({
515
+ submissionId: row.submission_id,
516
+ author: row.author,
517
+ reason: row.reason,
518
+ requestedAt: row.requested_at,
519
+ ...canonicalRecordId === void 0 ? {} : { canonicalRecordId }
520
+ }).pipe(Effect.mapError((error) => corruptionFailure(operation, "effect_agent_abort_intents", row.submission_id, error.message)));
521
+ });
522
+ const capabilities = Effect.succeed(LedgerCapabilities.make({ durability: "durable-cloudflare" }));
523
+ const admit = Effect.fn("DoSubmissionLedger.admit")(function* (request) {
524
+ const operation = "ledger admit";
525
+ const validated = yield* Schema.decodeEffect(Schema.toType(AdmissionRequest))(request).pipe(Effect.mapError(internalFailure(operation)));
526
+ const inputJson = yield* encodePersistedJsonText(validated.inputPayload).pipe(Effect.mapError(internalFailure(operation)));
527
+ yield* journal.checkValueBound(operation, inputJson).pipe(Effect.mapError(internalFailure(operation)));
528
+ const workerAdmissionJson = validated.workerAdmission === void 0 ? null : yield* Schema.encodeEffect(Schema.fromJsonString(WorkerAdmission))(validated.workerAdmission).pipe(Effect.mapError(internalFailure(operation)));
529
+ if (workerAdmissionJson !== null && new TextEncoder().encode(workerAdmissionJson).byteLength > config.maxStoredValueBytes) return yield* LedgerError.make({
530
+ operation,
531
+ message: "Worker admission metadata exceeds the stored value bound"
532
+ });
533
+ const messageAdmissionJson = validated.messageAdmission === void 0 ? null : yield* Schema.encodeEffect(Schema.fromJsonString(InputMessage))(validated.messageAdmission).pipe(Effect.mapError(internalFailure(operation)));
534
+ if (messageAdmissionJson !== null && new TextEncoder().encode(messageAdmissionJson).byteLength > config.maxStoredValueBytes) return yield* LedgerError.make({
535
+ operation,
536
+ message: "Message admission metadata exceeds the stored value bound"
537
+ });
538
+ const agentDigestsJson = yield* encodeDefinitionDigestsText(validated.agentDigests).pipe(Effect.mapError(internalFailure(operation)));
539
+ const mintedSubmissionId = `${yield* mintUuid(operation)}:${validated.threadId}`;
540
+ if (mintedSubmissionId.length > MAX_IDENTIFIER_LENGTH) return yield* LedgerError.make({
541
+ operation,
542
+ message: `A routable Submission identity of ${mintedSubmissionId.length} characters exceeds the ${MAX_IDENTIFIER_LENGTH}-character ledger row bound; shorten the Thread identity.`
543
+ });
544
+ const mintedReceiptId = `receipt-${yield* mintUuid(operation)}`;
545
+ yield* hitFailpoint("ledger:admit:before", operation);
546
+ const result = yield* inWriteTransaction(operation, Effect.gen(function* () {
547
+ const keyRowKey = `${validated.threadId}/${validated.principal}/${validated.idempotencyKey}`;
548
+ const existingRows = yield* sql`
549
+ SELECT ${sql.literal(SUBMISSION_COLUMNS)}
550
+ FROM effect_agent_submissions
551
+ WHERE thread_id = ${validated.threadId}
552
+ AND principal = ${validated.principal}
553
+ AND idempotency_key = ${validated.idempotencyKey}
554
+ `.pipe(Effect.mapError(sqlFailure(operation)));
555
+ const existing = yield* decodeSubmissionRows(operation, keyRowKey, existingRows);
556
+ if (existing.length > 1) return yield* corruptionFailure(operation, "effect_agent_submissions", keyRowKey, "An admission idempotency key returned more than one row.");
557
+ if (existing.length === 1) {
558
+ const sameLinkage = validated.parentLinkage === void 0 ? existing[0].parent_submission_id === null && existing[0].parent_tool_call_id === null : existing[0].parent_submission_id === validated.parentLinkage.parentSubmissionId && existing[0].parent_tool_call_id === validated.parentLinkage.parentToolCallId;
559
+ if (existing[0].input_digest !== validated.inputDigest || !sameLinkage) return yield* AdmissionConflict.make({
560
+ threadId: validated.threadId,
561
+ principal: validated.principal,
562
+ idempotencyKey: validated.idempotencyKey,
563
+ existingInputDigest: existing[0].input_digest,
564
+ attemptedInputDigest: validated.inputDigest
565
+ });
566
+ const retainedWorkerAdmission = existing[0].worker_admission_json === null ? void 0 : yield* Schema.decodeEffect(Schema.fromJsonString(WorkerAdmission))(existing[0].worker_admission_json).pipe(Effect.mapError(internalFailure(operation)));
567
+ const retainedInputMessage = existing[0].message_admission_json === null ? void 0 : yield* Schema.decodeEffect(Schema.fromJsonString(InputMessage))(existing[0].message_admission_json).pipe(Effect.mapError(internalFailure(operation)));
568
+ const retainedFence = existing[0].admission_fence_json === null ? void 0 : yield* Schema.decodeEffect(Schema.fromJsonString(AdmissionFence))(existing[0].admission_fence_json).pipe(Effect.mapError(internalFailure(operation)));
569
+ if ((existing[0].admission_group ?? void 0) !== validated.admissionGroup || !Schema.toEquivalence(Schema.optional(WorkerAdmission))(retainedWorkerAdmission, validated.workerAdmission) || !Schema.toEquivalence(Schema.optional(InputMessage))(retainedInputMessage, validated.messageAdmission) || !Schema.toEquivalence(Schema.optional(AdmissionFence))(retainedFence, validated.admissionFence)) return yield* AdmissionConflict.make({
570
+ threadId: validated.threadId,
571
+ principal: validated.principal,
572
+ idempotencyKey: validated.idempotencyKey,
573
+ existingInputDigest: existing[0].input_digest,
574
+ attemptedInputDigest: validated.inputDigest
575
+ });
576
+ return yield* decodeAdmissionResult({
577
+ submissionId: existing[0].submission_id,
578
+ receiptId: existing[0].receipt_id,
579
+ queueSequence: existing[0].queue_sequence,
580
+ state: existing[0].state,
581
+ replayed: true
582
+ }).pipe(Effect.mapError(internalFailure(operation)));
583
+ }
584
+ const firstRows = yield* sql`
585
+ SELECT worker_admission_json FROM effect_agent_submissions
586
+ WHERE thread_id=${validated.threadId} ORDER BY queue_sequence LIMIT 1
587
+ `.pipe(Effect.mapError(sqlFailure(operation)));
588
+ const first = yield* Schema.decodeUnknownEffect(Schema.Array(Schema.Struct({ worker_admission_json: Schema.NullOr(BoundedStoredText) })))(firstRows).pipe(Effect.mapError(internalFailure(operation)));
589
+ if (first[0] !== void 0) {
590
+ const previous = first[0].worker_admission_json === null ? void 0 : yield* Schema.decodeEffect(Schema.fromJsonString(WorkerAdmission))(first[0].worker_admission_json).pipe(Effect.mapError(internalFailure(operation)));
591
+ if (!Schema.toEquivalence(Schema.optional(WorkerAdmission.fields.origin))(previous?.origin, validated.workerAdmission?.origin)) return yield* AdmissionPolicyError.make({
592
+ reason: "refused",
593
+ code: "worker-origin-conflict"
594
+ });
595
+ }
596
+ yield* admissionFence.check(validated);
597
+ if (validated.admissionGroup !== void 0) {
598
+ if ((yield* sql`
599
+ SELECT submission_id FROM effect_agent_submissions
600
+ WHERE thread_id=${validated.threadId} AND admission_group=${validated.admissionGroup} AND state<>'settled' LIMIT 1
601
+ `.pipe(Effect.mapError(sqlFailure(operation)))).length > 0) return yield* AdmissionPolicyError.make({
602
+ reason: "occupied",
603
+ code: "admission-group"
604
+ });
605
+ }
606
+ const maxRows = yield* sql`
607
+ SELECT COALESCE(MAX(queue_sequence), 0) AS max_queue_sequence
608
+ FROM effect_agent_submissions
609
+ WHERE thread_id = ${validated.threadId}
610
+ `.pipe(Effect.mapError(sqlFailure(operation)));
611
+ const decodedMax = yield* decodeRows(Schema.Array(MaxQueueSequenceRow), "effect_agent_submissions", validated.threadId, maxRows).pipe(Effect.mapError(internalFailure(operation)));
612
+ const queueSequence = yield* decodeQueueSequence((decodedMax[0]?.max_queue_sequence ?? 0) + 1).pipe(Effect.mapError(internalFailure(operation)));
613
+ const now = yield* currentInstant;
614
+ yield* sql`
615
+ INSERT INTO effect_agent_submissions (
616
+ submission_id,
617
+ thread_id,
618
+ queue_sequence,
619
+ principal,
620
+ idempotency_key,
621
+ agent_id,
622
+ agent_digests_json,
623
+ deployment_id,
624
+ input_json,
625
+ input_digest,
626
+ receipt_id,
627
+ state,
628
+ created_at,
629
+ parent_submission_id,
630
+ parent_tool_call_id,
631
+ admission_group,
632
+ admission_fence_json,
633
+ worker_admission_json,
634
+ message_admission_json
635
+ ) VALUES (
636
+ ${mintedSubmissionId},
637
+ ${validated.threadId},
638
+ ${queueSequence},
639
+ ${validated.principal},
640
+ ${validated.idempotencyKey},
641
+ ${validated.agentId},
642
+ ${agentDigestsJson},
643
+ ${validated.deploymentId},
644
+ ${inputJson},
645
+ ${validated.inputDigest},
646
+ ${mintedReceiptId},
647
+ 'admitted',
648
+ ${now.iso},
649
+ ${validated.parentLinkage?.parentSubmissionId ?? null},
650
+ ${validated.parentLinkage?.parentToolCallId ?? null},
651
+ ${validated.admissionGroup ?? null},
652
+ ${validated.admissionFence === void 0 ? null : JSON.stringify(validated.admissionFence)},
653
+ ${workerAdmissionJson},
654
+ ${messageAdmissionJson}
655
+ )
656
+ `.pipe(Effect.mapError(sqlFailure(operation)));
657
+ return yield* decodeAdmissionResult({
658
+ submissionId: mintedSubmissionId,
659
+ receiptId: mintedReceiptId,
660
+ queueSequence,
661
+ state: "admitted",
662
+ replayed: false
663
+ }).pipe(Effect.mapError(internalFailure(operation)));
664
+ }));
665
+ yield* hitFailpoint("ledger:admit:after", operation);
666
+ return result;
667
+ });
668
+ const markReady = Effect.fn("DoSubmissionLedger.markReady")(function* (request) {
669
+ const operation = "ledger mark ready";
670
+ const validated = yield* Schema.decodeEffect(Schema.toType(MarkReadyRequest))(request).pipe(Effect.mapError(internalFailure(operation)));
671
+ yield* hitFailpoint("ledger:mark-ready:before", operation);
672
+ yield* inWriteTransaction(operation, Effect.gen(function* () {
673
+ if ((yield* requireSubmission(operation, validated.submissionId)).state !== "admitted") return;
674
+ const now = yield* currentInstant;
675
+ yield* sql`
676
+ UPDATE effect_agent_submissions
677
+ SET state = 'ready', ready_at = ${now.iso}
678
+ WHERE submission_id = ${validated.submissionId}
679
+ `.pipe(Effect.mapError(sqlFailure(operation)));
680
+ }));
681
+ yield* hitFailpoint("ledger:mark-ready:after", operation);
682
+ });
683
+ const lookup = Effect.fn("DoSubmissionLedger.lookup")(function* (request) {
684
+ const operation = "ledger lookup";
685
+ const validated = yield* Schema.decodeEffect(Schema.toType(SubmissionLookup))(request).pipe(Effect.mapError(internalFailure(operation)));
686
+ if (validated._tag === "SubmissionLookupById") {
687
+ const row = yield* readSubmission(operation, validated.submissionId);
688
+ if (Option.isNone(row)) return Option.none();
689
+ return Option.some(yield* decodeSubmissionSnapshot(operation, row.value));
690
+ }
691
+ const rows = yield* sql`
692
+ SELECT ${sql.literal(SUBMISSION_COLUMNS)}
693
+ FROM effect_agent_submissions
694
+ WHERE thread_id = ${validated.threadId}
695
+ AND principal = ${validated.principal}
696
+ AND idempotency_key = ${validated.idempotencyKey}
697
+ `.pipe(Effect.mapError(sqlFailure(operation)));
698
+ const decoded = yield* decodeSubmissionRows(operation, `${validated.threadId}/${validated.principal}/${validated.idempotencyKey}`, rows);
699
+ if (decoded.length > 1) return yield* corruptionFailure(operation, "effect_agent_submissions", `${validated.threadId}/${validated.principal}/${validated.idempotencyKey}`, "An admission idempotency key returned more than one row.");
700
+ if (decoded.length === 0) return Option.none();
701
+ return Option.some(yield* decodeSubmissionSnapshot(operation, decoded[0]));
702
+ });
703
+ const resolveAdmission = Effect.fn("DoSubmissionLedger.resolveAdmission")(function* (request) {
704
+ const operation = "ledger resolve admission";
705
+ const validated = yield* Schema.decodeEffect(Schema.toType(SubmissionLookupByKey))(request).pipe(Effect.mapError(internalFailure(operation)));
706
+ const rows = yield* sql`
707
+ SELECT ${sql.literal(SUBMISSION_COLUMNS)}
708
+ FROM effect_agent_submissions
709
+ WHERE thread_id = ${validated.threadId}
710
+ AND principal = ${validated.principal}
711
+ AND idempotency_key = ${validated.idempotencyKey}
712
+ `.pipe(Effect.mapError(sqlFailure(operation)));
713
+ const decoded = yield* decodeSubmissionRows(operation, `${validated.threadId}/${validated.principal}/${validated.idempotencyKey}`, rows);
714
+ if (decoded.length > 1) return yield* corruptionFailure(operation, "effect_agent_submissions", `${validated.threadId}/${validated.principal}/${validated.idempotencyKey}`, "An admission idempotency key returned more than one row.");
715
+ if (decoded.length === 0) return AdmissionNotAdmitted.make();
716
+ return AdmissionAdmitted.make({ submission: yield* decodeSubmissionSnapshot(operation, decoded[0]) });
717
+ });
718
+ const claim = Effect.fn("DoSubmissionLedger.claim")(function* (request) {
719
+ const operation = "ledger claim";
720
+ const validated = yield* Schema.decodeEffect(Schema.toType(ClaimRequest))(request).pipe(Effect.mapError(internalFailure(operation)));
721
+ const attemptId = `attempt-${yield* mintUuid(operation)}`;
722
+ const ownershipToken = `owner-${yield* mintUuid(operation)}`;
723
+ yield* hitFailpoint("ledger:claim:before", operation);
724
+ const claimed = yield* inWriteTransaction(operation, Effect.gen(function* () {
725
+ const now = yield* currentInstant;
726
+ const ownershipRows = yield* sql`
727
+ SELECT ownership.*
728
+ FROM effect_agent_submission_ownership AS ownership
729
+ JOIN effect_agent_submissions AS submission
730
+ ON submission.submission_id = ownership.submission_id
731
+ WHERE submission.thread_id = ${validated.threadId}
732
+ ORDER BY ownership.lease_expires_at DESC
733
+ LIMIT 1
734
+ `.pipe(Effect.mapError(sqlFailure(operation)));
735
+ const ownership = yield* decodeRows(Schema.Array(OwnershipRow), "effect_agent_submission_ownership", validated.threadId, ownershipRows).pipe(Effect.mapError(internalFailure(operation)));
736
+ if (ownership.length > 0) {
737
+ if ((yield* timestampMillis(operation, ownership[0].submission_id)(ownership[0].lease_expires_at)) > now.millis) return Option.none();
738
+ }
739
+ const headRows = yield* sql`
740
+ SELECT ${sql.literal(SUBMISSION_COLUMNS)}
741
+ FROM effect_agent_submissions
742
+ WHERE thread_id = ${validated.threadId}
743
+ AND state <> 'settled'
744
+ AND (
745
+ state <> 'unknown' OR EXISTS (
746
+ SELECT 1 FROM effect_agent_abort_intents
747
+ WHERE submission_id = effect_agent_submissions.submission_id
748
+ )
749
+ )
750
+ ORDER BY queue_sequence ASC
751
+ LIMIT 1
752
+ `.pipe(Effect.mapError(sqlFailure(operation)));
753
+ const heads = yield* decodeSubmissionRows(operation, validated.threadId, headRows);
754
+ if (heads.length === 0) return Option.none();
755
+ const head = heads[0];
756
+ if (head.state === "joining" || head.state === "joined" || head.state === "suspended" || head.state === "unknown" && Option.isNone(yield* readAbortIntent(operation, head.submission_id))) return Option.none();
757
+ const threads = yield* journal.getThread(head.thread_id).pipe(Effect.mapError(internalFailure(operation)));
758
+ let producerEpoch;
759
+ if (threads.length === 0) {
760
+ producerEpoch = 1;
761
+ yield* sql`
762
+ INSERT INTO effect_agent_threads (
763
+ thread_id,
764
+ created_at,
765
+ tail_sequence,
766
+ tail_digest,
767
+ producer_epoch
768
+ ) VALUES (
769
+ ${head.thread_id},
770
+ ${now.iso},
771
+ 0,
772
+ ${EMPTY_TAIL_DIGEST},
773
+ ${producerEpoch}
774
+ )
775
+ `.pipe(Effect.mapError(sqlFailure(operation)));
776
+ } else {
777
+ producerEpoch = threads[0].producer_epoch + 1;
778
+ yield* sql`
779
+ UPDATE effect_agent_threads
780
+ SET producer_epoch = ${producerEpoch}
781
+ WHERE thread_id = ${head.thread_id}
782
+ `.pipe(Effect.mapError(sqlFailure(operation)));
783
+ }
784
+ const leaseExpiresAt = new Date(now.millis + config.ownershipLeaseDuration).toISOString();
785
+ yield* sql`
786
+ INSERT INTO effect_agent_submission_ownership (
787
+ submission_id,
788
+ attempt_id,
789
+ ownership_token,
790
+ producer_epoch,
791
+ owner_producer_id,
792
+ lease_expires_at
793
+ ) VALUES (
794
+ ${head.submission_id},
795
+ ${attemptId},
796
+ ${ownershipToken},
797
+ ${producerEpoch},
798
+ ${validated.producerId},
799
+ ${leaseExpiresAt}
800
+ )
801
+ ON CONFLICT (submission_id) DO UPDATE SET
802
+ attempt_id = excluded.attempt_id,
803
+ ownership_token = excluded.ownership_token,
804
+ producer_epoch = excluded.producer_epoch,
805
+ owner_producer_id = excluded.owner_producer_id,
806
+ lease_expires_at = excluded.lease_expires_at
807
+ `.pipe(Effect.mapError(sqlFailure(operation)));
808
+ yield* sql`
809
+ INSERT INTO effect_agent_attempts (
810
+ attempt_id,
811
+ submission_id,
812
+ thread_id,
813
+ owner_producer_id,
814
+ producer_epoch,
815
+ claimed_at
816
+ ) VALUES (
817
+ ${attemptId},
818
+ ${head.submission_id},
819
+ ${head.thread_id},
820
+ ${validated.producerId},
821
+ ${producerEpoch},
822
+ ${now.iso}
823
+ )
824
+ `.pipe(Effect.mapError(sqlFailure(operation)));
825
+ if (head.state === "ready") yield* sql`
826
+ UPDATE effect_agent_submissions
827
+ SET state = 'running'
828
+ WHERE submission_id = ${head.submission_id}
829
+ `.pipe(Effect.mapError(sqlFailure(operation)));
830
+ const inputPayload = yield* parseStoredJsonText(head.input_json).pipe(Effect.mapError((error) => corruptionFailure(operation, "effect_agent_submissions", head.submission_id, error.message)));
831
+ return Option.some(yield* decodeClaim({
832
+ submissionId: head.submission_id,
833
+ attemptId,
834
+ ownershipToken,
835
+ producerEpoch,
836
+ leaseExpiresAt,
837
+ inputPayload
838
+ }).pipe(Effect.mapError(internalFailure(operation))));
839
+ }));
840
+ yield* hitFailpoint("ledger:claim:after", operation);
841
+ return claimed;
842
+ });
843
+ const renewOwnership = Effect.fn("DoSubmissionLedger.renewOwnership")(function* (request) {
844
+ const operation = "ledger renew ownership";
845
+ const validated = yield* Schema.decodeEffect(Schema.toType(RenewOwnershipRequest))(request).pipe(Effect.mapError(internalFailure(operation)));
846
+ yield* hitFailpoint("ledger:renew:before", operation);
847
+ const renewal = yield* inWriteTransaction(operation, Effect.gen(function* () {
848
+ const submission = yield* requireSubmission(operation, validated.submissionId);
849
+ yield* requireOwnership(operation, submission, validated.ownershipToken);
850
+ const now = yield* currentInstant;
851
+ const leaseExpiresAt = new Date(now.millis + config.ownershipLeaseDuration).toISOString();
852
+ yield* sql`
853
+ UPDATE effect_agent_submission_ownership
854
+ SET lease_expires_at = ${leaseExpiresAt}
855
+ WHERE submission_id = ${validated.submissionId}
856
+ `.pipe(Effect.mapError(sqlFailure(operation)));
857
+ return yield* decodeOwnershipRenewal({
858
+ ownershipToken: validated.ownershipToken,
859
+ leaseExpiresAt
860
+ }).pipe(Effect.mapError(internalFailure(operation)));
861
+ }));
862
+ yield* hitFailpoint("ledger:renew:after", operation);
863
+ return renewal;
864
+ });
865
+ const releaseOwnership = Effect.fn("DoSubmissionLedger.releaseOwnership")(function* (request) {
866
+ const operation = "ledger release ownership";
867
+ const validated = yield* Schema.decodeEffect(Schema.toType(ReleaseOwnershipRequest))(request).pipe(Effect.mapError(internalFailure(operation)));
868
+ yield* hitFailpoint("ledger:release:before", operation);
869
+ yield* inWriteTransaction(operation, Effect.gen(function* () {
870
+ const submission = yield* requireSubmission(operation, validated.submissionId);
871
+ yield* requireOwnership(operation, submission, validated.ownershipToken);
872
+ yield* sql`
873
+ DELETE FROM effect_agent_submission_ownership
874
+ WHERE submission_id = ${validated.submissionId}
875
+ `.pipe(Effect.mapError(sqlFailure(operation)));
876
+ if (submission.state === "running") yield* sql`
877
+ UPDATE effect_agent_submissions
878
+ SET state = 'ready'
879
+ WHERE submission_id = ${validated.submissionId}
880
+ `.pipe(Effect.mapError(sqlFailure(operation)));
881
+ }));
882
+ yield* hitFailpoint("ledger:release:after", operation);
883
+ });
884
+ const markInputApplied = Effect.fn("DoSubmissionLedger.markInputApplied")(function* (request) {
885
+ const operation = "ledger mark input applied";
886
+ const validated = yield* Schema.decodeEffect(Schema.toType(MarkInputAppliedRequest))(request).pipe(Effect.mapError(internalFailure(operation)));
887
+ yield* hitFailpoint("ledger:mark-input-applied:before", operation);
888
+ yield* inWriteTransaction(operation, Effect.gen(function* () {
889
+ const submission = yield* requireSubmission(operation, validated.submissionId);
890
+ yield* requireOwnership(operation, submission, validated.ownershipToken);
891
+ if (submission.input_applied_record_id !== null) {
892
+ if (submission.input_applied_record_id === validated.recordId && submission.input_applied_sequence === validated.sequence) return;
893
+ return yield* corruptionFailure(operation, "effect_agent_submissions", validated.submissionId, "A different canonical input marker is already recorded for this Submission.");
894
+ }
895
+ yield* sql`
896
+ UPDATE effect_agent_submissions
897
+ SET
898
+ input_applied_record_id = ${validated.recordId},
899
+ input_applied_sequence = ${validated.sequence},
900
+ state = CASE
901
+ WHEN state IN ('admitted', 'ready', 'running') THEN 'input-applied'
902
+ ELSE state
903
+ END
904
+ WHERE submission_id = ${validated.submissionId}
905
+ `.pipe(Effect.mapError(sqlFailure(operation)));
906
+ }));
907
+ yield* hitFailpoint("ledger:mark-input-applied:after", operation);
908
+ });
909
+ const reserveSettlement = Effect.fn("DoSubmissionLedger.reserveSettlement")(function* (request) {
910
+ const operation = "ledger reserve settlement";
911
+ const validated = yield* Schema.decodeEffect(Schema.toType(SettlementReservation))(request).pipe(Effect.mapError(internalFailure(operation)));
912
+ const recordJson = yield* encodeRecordEnvelopeText(validated.record).pipe(Effect.mapError(internalFailure(operation)));
913
+ yield* journal.checkValueBound(operation, recordJson).pipe(Effect.mapError(internalFailure(operation)));
914
+ yield* hitFailpoint("ledger:reserve-settlement:before", operation);
915
+ const reserved = yield* inWriteTransaction(operation, Effect.gen(function* () {
916
+ const existing = yield* readReservation(operation, validated.submissionId);
917
+ if (Option.isSome(existing)) {
918
+ if (!(existing.value.settlement_id === validated.settlementId && existing.value.outcome === validated.outcome && existing.value.record_digest === validated.recordDigest && existing.value.record_json === recordJson)) return yield* SettlementConflict.make({
919
+ submissionId: validated.submissionId,
920
+ existingOutcome: existing.value.outcome
921
+ });
922
+ const record = yield* decodeRecordEnvelopeText(existing.value.record_json).pipe(Effect.mapError((error) => corruptionFailure(operation, "effect_agent_settlement_reservations", validated.submissionId, error.message)));
923
+ return ReservedSettlement.make({
924
+ submissionId: validated.submissionId,
925
+ settlementId: validated.settlementId,
926
+ outcome: validated.outcome,
927
+ record,
928
+ recordDigest: validated.recordDigest,
929
+ replayed: true
930
+ });
931
+ }
932
+ const submission = yield* requireSubmission(operation, validated.submissionId);
933
+ if (submission.state === "settled") {
934
+ if (submission.settled_outcome === null) return yield* corruptionFailure(operation, "effect_agent_submissions", validated.submissionId, "A settled Submission carries no terminal outcome.");
935
+ return yield* SettlementConflict.make({
936
+ submissionId: validated.submissionId,
937
+ existingOutcome: submission.settled_outcome
938
+ });
939
+ }
940
+ if (!(submission.state === "joined" && submission.joined_host_submission_id !== null)) {
941
+ let queuedAbortSettlement = false;
942
+ if (validated.outcome === "aborted" && (submission.state === "ready" || submission.state === "terminalizing")) {
943
+ const abortIntent = yield* readAbortIntent(operation, validated.submissionId);
944
+ if (Option.isSome(abortIntent)) {
945
+ const ownership = yield* readOwnership(operation, validated.submissionId);
946
+ queuedAbortSettlement = Option.isNone(ownership);
947
+ }
948
+ }
949
+ if (!queuedAbortSettlement) yield* requireOwnership(operation, submission, validated.ownershipToken);
950
+ }
951
+ const now = yield* currentInstant;
952
+ yield* sql`
953
+ INSERT INTO effect_agent_settlement_reservations (
954
+ submission_id,
955
+ settlement_id,
956
+ outcome,
957
+ record_id,
958
+ record_json,
959
+ record_digest,
960
+ reserved_at
961
+ ) VALUES (
962
+ ${validated.submissionId},
963
+ ${validated.settlementId},
964
+ ${validated.outcome},
965
+ ${validated.record.recordId},
966
+ ${recordJson},
967
+ ${validated.recordDigest},
968
+ ${now.iso}
969
+ )
970
+ `.pipe(Effect.mapError(sqlFailure(operation)));
971
+ yield* sql`
972
+ UPDATE effect_agent_submissions
973
+ SET state = 'terminalizing'
974
+ WHERE submission_id = ${validated.submissionId}
975
+ `.pipe(Effect.mapError(sqlFailure(operation)));
976
+ return ReservedSettlement.make({
977
+ submissionId: validated.submissionId,
978
+ settlementId: validated.settlementId,
979
+ outcome: validated.outcome,
980
+ record: validated.record,
981
+ recordDigest: validated.recordDigest,
982
+ replayed: false
983
+ });
984
+ }));
985
+ yield* hitFailpoint("ledger:reserve-settlement:after", operation);
986
+ return reserved;
987
+ });
988
+ const validateFinalization = Effect.fn("DoSubmissionLedger.validateFinalization")(function* (validated, reservation) {
989
+ const operation = "ledger finalize settlement";
990
+ if (Option.isNone(reservation)) return yield* LedgerError.make({
991
+ operation,
992
+ message: `No settlement reservation exists for submission ${validated.submissionId}.`
993
+ });
994
+ if (reservation.value.settlement_id !== validated.settlementId) return yield* SettlementConflict.make({
995
+ submissionId: validated.submissionId,
996
+ existingOutcome: reservation.value.outcome
997
+ });
998
+ const reservationRecord = yield* decodeRecordEnvelopeText(reservation.value.record_json).pipe(Effect.mapError((error) => corruptionFailure(operation, "effect_agent_settlement_reservations", validated.submissionId, error.message)));
999
+ const settlementFailure = settlementFailureFromRecord(reservationRecord);
1000
+ if (reservation.value.outcome === "failed" !== (settlementFailure !== void 0)) return yield* corruptionFailure(operation, "effect_agent_settlement_reservations", validated.submissionId, "The reserved outcome and canonical failure diagnostic disagree.");
1001
+ return {
1002
+ reservation: reservation.value,
1003
+ settlementFailure
1004
+ };
1005
+ });
1006
+ const replayFinalization = Effect.fn("DoSubmissionLedger.replayFinalization")(function* (validated, submission, { reservation, settlementFailure }) {
1007
+ const operation = "ledger finalize settlement";
1008
+ if (reservation.finalized_at === null) return yield* corruptionFailure(operation, "effect_agent_settlement_reservations", validated.submissionId, "A settled Submission's reservation carries no finalization timestamp.");
1009
+ return yield* decodeSettlement({
1010
+ submissionId: validated.submissionId,
1011
+ settlementId: validated.settlementId,
1012
+ receiptId: submission.receipt_id,
1013
+ outcome: reservation.outcome,
1014
+ ...settlementFailure === void 0 ? {} : { failure: settlementFailure },
1015
+ settledAt: reservation.finalized_at
1016
+ }).pipe(Effect.mapError(internalFailure(operation)));
1017
+ });
1018
+ const finalizeSettlement = Effect.fn("DoSubmissionLedger.finalizeSettlement")(function* (request) {
1019
+ const operation = "ledger finalize settlement";
1020
+ const validated = yield* Schema.decodeEffect(Schema.toType(SettlementFinalization))(request).pipe(Effect.mapError(internalFailure(operation)));
1021
+ yield* hitFailpoint("ledger:finalize-settlement:before", operation);
1022
+ const replayRows = yield* sql`
1023
+ SELECT submission.*, reservation.settlement_id, reservation.outcome,
1024
+ reservation.record_id, reservation.record_json, reservation.record_digest,
1025
+ reservation.reserved_at, reservation.finalized_at
1026
+ FROM effect_agent_submissions AS submission
1027
+ INNER JOIN effect_agent_settlement_reservations AS reservation
1028
+ ON reservation.submission_id = submission.submission_id
1029
+ WHERE submission.submission_id = ${validated.submissionId} AND submission.state = 'settled'
1030
+ `.pipe(Effect.mapError(sqlFailure(operation)));
1031
+ if (replayRows.length > 1) return yield* corruptionFailure(operation, "effect_agent_submissions", validated.submissionId, "A submission primary key returned more than one row.");
1032
+ const replayRow = replayRows[0];
1033
+ if (replayRow !== void 0) {
1034
+ const reservations = yield* decodeRows(Schema.Array(ReservationRow), "effect_agent_settlement_reservations", validated.submissionId, replayRows).pipe(Effect.mapError(internalFailure(operation)));
1035
+ const state = yield* validateFinalization(validated, Option.fromUndefinedOr(reservations[0]));
1036
+ const submission = yield* Schema.decodeUnknownEffect(SubmissionRow)(replayRow).pipe(Effect.mapError((error) => corruptionFailure(operation, "effect_agent_submissions", validated.submissionId, error.message)));
1037
+ const settlement = yield* replayFinalization(validated, submission, state);
1038
+ yield* hitFailpoint("ledger:finalize-settlement:after", operation);
1039
+ return settlement;
1040
+ }
1041
+ const settlement = yield* inWriteTransaction(operation, Effect.gen(function* () {
1042
+ const state = yield* validateFinalization(validated, yield* readReservation(operation, validated.submissionId));
1043
+ const { reservation, settlementFailure } = state;
1044
+ const submission = yield* requireSubmission(operation, validated.submissionId);
1045
+ if (submission.state === "settled") return yield* replayFinalization(validated, submission, state);
1046
+ const now = yield* currentInstant;
1047
+ yield* sql`
1048
+ UPDATE effect_agent_submissions
1049
+ SET state = 'settled', settled_outcome = ${reservation.outcome}
1050
+ WHERE submission_id = ${validated.submissionId}
1051
+ `.pipe(Effect.mapError(sqlFailure(operation)));
1052
+ yield* sql`
1053
+ UPDATE effect_agent_settlement_reservations
1054
+ SET finalized_at = ${now.iso}
1055
+ WHERE submission_id = ${validated.submissionId}
1056
+ `.pipe(Effect.mapError(sqlFailure(operation)));
1057
+ yield* sql`
1058
+ DELETE FROM effect_agent_submission_ownership
1059
+ WHERE submission_id = ${validated.submissionId}
1060
+ `.pipe(Effect.mapError(sqlFailure(operation)));
1061
+ return yield* decodeSettlement({
1062
+ submissionId: validated.submissionId,
1063
+ settlementId: validated.settlementId,
1064
+ receiptId: submission.receipt_id,
1065
+ outcome: reservation.outcome,
1066
+ ...settlementFailure === void 0 ? {} : { failure: settlementFailure },
1067
+ settledAt: now.iso
1068
+ }).pipe(Effect.mapError(internalFailure(operation)));
1069
+ }));
1070
+ yield* hitFailpoint("ledger:finalize-settlement:after", operation);
1071
+ return settlement;
1072
+ });
1073
+ const requestAbort = Effect.fn("DoSubmissionLedger.requestAbort")(function* (request) {
1074
+ const operation = "ledger request abort";
1075
+ const validated = yield* Schema.decodeEffect(Schema.toType(AbortCommand))(request).pipe(Effect.mapError(internalFailure(operation)));
1076
+ yield* hitFailpoint("ledger:request-abort:before", operation);
1077
+ const intent = yield* inWriteTransaction(operation, Effect.gen(function* () {
1078
+ const submission = yield* requireSubmission(operation, validated.submissionId);
1079
+ if (submission.state === "settled") {
1080
+ if (submission.settled_outcome === null) return yield* corruptionFailure(operation, "effect_agent_submissions", validated.submissionId, "A settled Submission carries no terminal outcome.");
1081
+ return yield* SettlementConflict.make({
1082
+ submissionId: validated.submissionId,
1083
+ existingOutcome: submission.settled_outcome
1084
+ });
1085
+ }
1086
+ if (submission.state === "joined") {
1087
+ if (submission.joined_host_submission_id === null) return yield* corruptionFailure(operation, "effect_agent_submissions", validated.submissionId, "A joined Submission carries no host linkage.");
1088
+ const hostSubmissionId = yield* decodeSubmissionId(submission.joined_host_submission_id).pipe(Effect.mapError(internalFailure(operation)));
1089
+ return yield* JoinedToHost.make({
1090
+ submissionId: validated.submissionId,
1091
+ hostSubmissionId
1092
+ });
1093
+ }
1094
+ const existing = yield* readAbortIntent(operation, validated.submissionId);
1095
+ if (Option.isSome(existing)) return yield* abortIntentFromRow(operation, submission, validated.submissionId, existing.value);
1096
+ const now = yield* currentInstant;
1097
+ yield* sql`
1098
+ INSERT INTO effect_agent_abort_intents (
1099
+ submission_id,
1100
+ author,
1101
+ reason,
1102
+ requested_at
1103
+ ) VALUES (
1104
+ ${validated.submissionId},
1105
+ ${validated.author},
1106
+ ${validated.reason},
1107
+ ${now.iso}
1108
+ )
1109
+ `.pipe(Effect.mapError(sqlFailure(operation)));
1110
+ const canonicalRecordId = yield* canonicalAbortRecordId(operation, submission.thread_id, validated.submissionId);
1111
+ return yield* decodeAbortIntent({
1112
+ submissionId: validated.submissionId,
1113
+ author: validated.author,
1114
+ reason: validated.reason,
1115
+ requestedAt: now.iso,
1116
+ ...canonicalRecordId === void 0 ? {} : { canonicalRecordId }
1117
+ }).pipe(Effect.mapError(internalFailure(operation)));
1118
+ }));
1119
+ yield* hitFailpoint("ledger:request-abort:after", operation);
1120
+ return intent;
1121
+ });
1122
+ const claimJoining = Effect.fn("DoSubmissionLedger.claimJoining")(function* (request) {
1123
+ const operation = "ledger claim joining";
1124
+ const validated = yield* Schema.decodeEffect(Schema.toType(ClaimJoiningRequest))(request).pipe(Effect.mapError(internalFailure(operation)));
1125
+ yield* hitFailpoint("ledger:claim-joining:before", operation);
1126
+ const claims = yield* inWriteTransaction(operation, Effect.gen(function* () {
1127
+ const host = yield* requireSubmission(operation, validated.hostSubmissionId);
1128
+ if (host.thread_id !== validated.threadId) return yield* LedgerError.make({
1129
+ operation,
1130
+ message: `Host submission ${validated.hostSubmissionId} does not belong to thread ${validated.threadId}.`
1131
+ });
1132
+ yield* requireOwnership(operation, host, validated.ownershipToken);
1133
+ const laterRows = yield* sql`
1134
+ SELECT ${sql.literal(SUBMISSION_COLUMNS)}
1135
+ FROM effect_agent_submissions
1136
+ WHERE thread_id = ${validated.threadId}
1137
+ AND queue_sequence > ${host.queue_sequence}
1138
+ ORDER BY queue_sequence ASC
1139
+ `.pipe(Effect.mapError(sqlFailure(operation)));
1140
+ const later = yield* decodeSubmissionRows(operation, validated.threadId, laterRows);
1141
+ const claimed = [];
1142
+ for (const row of later) {
1143
+ if (claimed.length >= validated.maxCount) break;
1144
+ if ((row.state === "joining" || row.state === "joined") && row.joined_host_submission_id === validated.hostSubmissionId) continue;
1145
+ if (row.state === "settled" && row.settled_outcome === "aborted") continue;
1146
+ if (row.state !== "ready") break;
1147
+ yield* sql`
1148
+ UPDATE effect_agent_submissions
1149
+ SET state = 'joining', joined_host_submission_id = ${validated.hostSubmissionId}
1150
+ WHERE submission_id = ${row.submission_id}
1151
+ `.pipe(Effect.mapError(sqlFailure(operation)));
1152
+ const inputPayload = yield* parseStoredJsonText(row.input_json).pipe(Effect.mapError((error) => corruptionFailure(operation, "effect_agent_submissions", row.submission_id, error.message)));
1153
+ claimed.push(yield* decodeJoiningClaim({
1154
+ submissionId: row.submission_id,
1155
+ queueSequence: row.queue_sequence,
1156
+ inputPayload
1157
+ }).pipe(Effect.mapError(internalFailure(operation))));
1158
+ }
1159
+ return claimed;
1160
+ }));
1161
+ yield* hitFailpoint("ledger:claim-joining:after", operation);
1162
+ return claims;
1163
+ });
1164
+ const markJoined = Effect.fn("DoSubmissionLedger.markJoined")(function* (request) {
1165
+ const operation = "ledger mark joined";
1166
+ const validated = yield* Schema.decodeEffect(Schema.toType(MarkJoinedRequest))(request).pipe(Effect.mapError(internalFailure(operation)));
1167
+ yield* hitFailpoint("ledger:mark-joined:before", operation);
1168
+ yield* inWriteTransaction(operation, Effect.gen(function* () {
1169
+ const submission = yield* requireSubmission(operation, validated.submissionId);
1170
+ if (submission.joined_host_submission_id === null) return yield* LedgerError.make({
1171
+ operation,
1172
+ message: `Submission ${validated.submissionId} was never claimed for joining.`
1173
+ });
1174
+ const host = yield* requireSubmission(operation, submission.joined_host_submission_id);
1175
+ yield* requireOwnership(operation, host, validated.ownershipToken);
1176
+ if (submission.input_applied_record_id !== null) {
1177
+ if (submission.input_applied_record_id === validated.recordId && submission.input_applied_sequence === validated.sequence) return;
1178
+ return yield* corruptionFailure(operation, "effect_agent_submissions", validated.submissionId, "A different join marker is already recorded for this Submission.");
1179
+ }
1180
+ if (submission.state !== "joining" && submission.state !== "joined") return yield* LedgerError.make({
1181
+ operation,
1182
+ message: `Cannot mark submission ${validated.submissionId} joined from state ${submission.state}.`
1183
+ });
1184
+ yield* sql`
1185
+ UPDATE effect_agent_submissions
1186
+ SET
1187
+ input_applied_record_id = ${validated.recordId},
1188
+ input_applied_sequence = ${validated.sequence},
1189
+ state = 'joined'
1190
+ WHERE submission_id = ${validated.submissionId}
1191
+ `.pipe(Effect.mapError(sqlFailure(operation)));
1192
+ }));
1193
+ yield* hitFailpoint("ledger:mark-joined:after", operation);
1194
+ });
1195
+ const revertJoining = Effect.fn("DoSubmissionLedger.revertJoining")(function* (request) {
1196
+ const operation = "ledger revert joining";
1197
+ const validated = yield* Schema.decodeEffect(Schema.toType(RevertJoiningRequest))(request).pipe(Effect.mapError(internalFailure(operation)));
1198
+ yield* hitFailpoint("ledger:revert-joining:before", operation);
1199
+ yield* inWriteTransaction(operation, Effect.gen(function* () {
1200
+ if ((yield* requireSubmission(operation, validated.submissionId)).state !== "joining") return;
1201
+ yield* sql`
1202
+ UPDATE effect_agent_submissions
1203
+ SET state = 'ready', joined_host_submission_id = NULL
1204
+ WHERE submission_id = ${validated.submissionId}
1205
+ `.pipe(Effect.mapError(sqlFailure(operation)));
1206
+ }));
1207
+ yield* hitFailpoint("ledger:revert-joining:after", operation);
1208
+ });
1209
+ const suspend = Effect.fn("DoSubmissionLedger.suspend")(function* (request) {
1210
+ const operation = "ledger suspend";
1211
+ const validated = yield* Schema.decodeEffect(Schema.toType(SuspendRequest))(request).pipe(Effect.mapError(internalFailure(operation)));
1212
+ const reasonJson = yield* encodeSuspensionReasonText(validated.reason).pipe(Effect.mapError(internalFailure(operation)));
1213
+ yield* hitFailpoint("ledger:suspend:before", operation);
1214
+ const outcome = yield* inWriteTransaction(operation, Effect.gen(function* () {
1215
+ const submission = yield* requireSubmission(operation, validated.submissionId);
1216
+ if (submission.state === "settled") {
1217
+ if (submission.settled_outcome === null) return yield* corruptionFailure(operation, "effect_agent_submissions", validated.submissionId, "A settled Submission carries no terminal outcome.");
1218
+ return yield* SettlementConflict.make({
1219
+ submissionId: validated.submissionId,
1220
+ existingOutcome: submission.settled_outcome
1221
+ });
1222
+ }
1223
+ const reservation = yield* readReservation(operation, validated.submissionId);
1224
+ if (Option.isSome(reservation)) return yield* SettlementConflict.make({
1225
+ submissionId: validated.submissionId,
1226
+ existingOutcome: reservation.value.outcome
1227
+ });
1228
+ yield* requireOwnership(operation, submission, validated.ownershipToken);
1229
+ if (validated.reason._tag === "ApprovalPending") {
1230
+ const decisions = yield* readApprovalDecisions(operation, validated.submissionId);
1231
+ const decided = new Set(decisions.map((row) => row.tool_call_id));
1232
+ if (validated.reason.toolCallIds.every((toolCallId) => decided.has(toolCallId))) return RESUME_IMMEDIATELY;
1233
+ } else {
1234
+ const markers = yield* readChildSettlementMarkers(operation, validated.submissionId);
1235
+ const markerChildren = new Set(markers.map((row) => row.child_submission_id));
1236
+ let allSettled = true;
1237
+ for (const child of validated.reason.children) if (!(yield* childProvablySettled(operation, markerChildren, child.childSubmissionId))) {
1238
+ allSettled = false;
1239
+ break;
1240
+ }
1241
+ if (allSettled) return RESUME_IMMEDIATELY;
1242
+ }
1243
+ const now = yield* currentInstant;
1244
+ yield* sql`
1245
+ UPDATE effect_agent_submissions
1246
+ SET
1247
+ state = 'suspended',
1248
+ suspended_reason_json = ${reasonJson},
1249
+ suspended_at = ${now.iso}
1250
+ WHERE submission_id = ${validated.submissionId}
1251
+ `.pipe(Effect.mapError(sqlFailure(operation)));
1252
+ yield* sql`
1253
+ DELETE FROM effect_agent_submission_ownership
1254
+ WHERE submission_id = ${validated.submissionId}
1255
+ `.pipe(Effect.mapError(sqlFailure(operation)));
1256
+ return SUSPENDED;
1257
+ }));
1258
+ yield* hitFailpoint("ledger:suspend:after", operation);
1259
+ return outcome;
1260
+ });
1261
+ /**
1262
+ * Once every pending call of a recorded ApprovalPending suspension has a decision intent,
1263
+ * the lane wakes: suspended → input-applied, suspension cleared (plan §2.6). A
1264
+ * WaitingForChild suspension wakes only through recordChildSettled. Runs inside the caller's
1265
+ * write transaction.
1266
+ */
1267
+ const wakeSuspendedIfCovered = Effect.fn("DoSubmissionLedger.wakeSuspendedIfCovered")(function* (operation, submission) {
1268
+ if (submission.state !== "suspended" || submission.suspended_reason_json === null) return;
1269
+ const reason = yield* Schema.decodeEffect(Schema.fromJsonString(SuspensionReason))(submission.suspended_reason_json).pipe(Effect.mapError((error) => corruptionFailure(operation, "effect_agent_submissions", submission.submission_id, error.message)));
1270
+ if (reason._tag !== "ApprovalPending") return;
1271
+ const decisions = yield* readApprovalDecisions(operation, submission.submission_id);
1272
+ const decided = new Set(decisions.map((row) => row.tool_call_id));
1273
+ if (!reason.toolCallIds.every((toolCallId) => decided.has(toolCallId))) return;
1274
+ yield* sql`
1275
+ UPDATE effect_agent_submissions
1276
+ SET
1277
+ state = 'input-applied',
1278
+ suspended_reason_json = NULL,
1279
+ suspended_at = NULL
1280
+ WHERE submission_id = ${submission.submission_id}
1281
+ `.pipe(Effect.mapError(sqlFailure(operation)));
1282
+ });
1283
+ const recordApprovalDecision = Effect.fn("DoSubmissionLedger.recordApprovalDecision")(function* (command) {
1284
+ const operation = "ledger record approval decision";
1285
+ const validated = yield* Schema.decodeEffect(Schema.toType(ApprovalDecisionCommand))(command).pipe(Effect.mapError(internalFailure(operation)));
1286
+ yield* hitFailpoint("ledger:approval-decision:before", operation);
1287
+ const intent = yield* inWriteTransaction(operation, Effect.gen(function* () {
1288
+ const submission = yield* requireSubmission(operation, validated.submissionId);
1289
+ if (submission.state === "settled") {
1290
+ if (submission.settled_outcome === null) return yield* corruptionFailure(operation, "effect_agent_submissions", validated.submissionId, "A settled Submission carries no terminal outcome.");
1291
+ return yield* SettlementConflict.make({
1292
+ submissionId: validated.submissionId,
1293
+ existingOutcome: submission.settled_outcome
1294
+ });
1295
+ }
1296
+ const existing = (yield* readApprovalDecisions(operation, validated.submissionId)).find((row) => row.tool_call_id === validated.toolCallId);
1297
+ if (existing !== void 0) {
1298
+ if (existing.decision !== validated.decision) return yield* ApprovalConflict.make({
1299
+ submissionId: validated.submissionId,
1300
+ toolCallId: validated.toolCallId,
1301
+ existingDecision: existing.decision
1302
+ });
1303
+ return yield* approvalIntentFromRow(operation, existing);
1304
+ }
1305
+ const now = yield* currentInstant;
1306
+ yield* sql`
1307
+ INSERT INTO effect_agent_approval_decisions (
1308
+ submission_id,
1309
+ tool_call_id,
1310
+ decision,
1311
+ resolver,
1312
+ reason,
1313
+ decided_at
1314
+ ) VALUES (
1315
+ ${validated.submissionId},
1316
+ ${validated.toolCallId},
1317
+ ${validated.decision},
1318
+ ${validated.resolver},
1319
+ ${validated.reason},
1320
+ ${now.iso}
1321
+ )
1322
+ `.pipe(Effect.mapError(sqlFailure(operation)));
1323
+ yield* wakeSuspendedIfCovered(operation, submission);
1324
+ return yield* decodeApprovalDecisionIntent({
1325
+ submissionId: validated.submissionId,
1326
+ toolCallId: validated.toolCallId,
1327
+ decision: validated.decision,
1328
+ resolver: validated.resolver,
1329
+ reason: validated.reason,
1330
+ decidedAt: now.iso
1331
+ }).pipe(Effect.mapError(internalFailure(operation)));
1332
+ }));
1333
+ yield* hitFailpoint("ledger:approval-decision:after", operation);
1334
+ return intent;
1335
+ });
1336
+ const markUnknown = Effect.fn("DoSubmissionLedger.markUnknown")(function* (request) {
1337
+ const operation = "ledger mark unknown";
1338
+ const validated = yield* Schema.decodeEffect(Schema.toType(MarkUnknownRequest))(request).pipe(Effect.mapError(internalFailure(operation)));
1339
+ yield* hitFailpoint("ledger:mark-unknown:before", operation);
1340
+ yield* inWriteTransaction(operation, Effect.gen(function* () {
1341
+ const submission = yield* requireSubmission(operation, validated.submissionId);
1342
+ if (submission.state === "settled") {
1343
+ if (submission.settled_outcome === null) return yield* corruptionFailure(operation, "effect_agent_submissions", validated.submissionId, "A settled Submission carries no terminal outcome.");
1344
+ return yield* SettlementConflict.make({
1345
+ submissionId: validated.submissionId,
1346
+ existingOutcome: submission.settled_outcome
1347
+ });
1348
+ }
1349
+ const reservation = yield* readReservation(operation, validated.submissionId);
1350
+ if (Option.isSome(reservation)) return yield* SettlementConflict.make({
1351
+ submissionId: validated.submissionId,
1352
+ existingOutcome: reservation.value.outcome
1353
+ });
1354
+ const existingIds = yield* storedUnknownToolCallIds(operation, submission);
1355
+ const known = new Set(existingIds);
1356
+ const merged = [...existingIds, ...validated.toolCallIds.filter((toolCallId) => !known.has(toolCallId))];
1357
+ const idsJson = yield* encodeToolCallIdsText(merged).pipe(Effect.mapError(internalFailure(operation)));
1358
+ yield* sql`
1359
+ UPDATE effect_agent_submissions
1360
+ SET
1361
+ state = 'unknown',
1362
+ unknown_reason = ${submission.unknown_reason ?? validated.reason},
1363
+ unknown_tool_call_ids_json = ${idsJson}
1364
+ WHERE submission_id = ${validated.submissionId}
1365
+ `.pipe(Effect.mapError(sqlFailure(operation)));
1366
+ }));
1367
+ yield* hitFailpoint("ledger:mark-unknown:after", operation);
1368
+ });
1369
+ const recordUnknownResolution = Effect.fn("DoSubmissionLedger.recordUnknownResolution")(function* (command) {
1370
+ const operation = "ledger record unknown resolution";
1371
+ const validated = yield* Schema.decodeEffect(Schema.toType(UnknownResolutionCommand))(command).pipe(Effect.mapError(internalFailure(operation)));
1372
+ const resolutionJson = yield* encodeUnknownResolutionText(validated.resolution).pipe(Effect.mapError(internalFailure(operation)));
1373
+ yield* hitFailpoint("ledger:unknown-resolution:before", operation);
1374
+ const intent = yield* inWriteTransaction(operation, Effect.gen(function* () {
1375
+ const submission = yield* requireSubmission(operation, validated.submissionId);
1376
+ if (submission.state === "settled") {
1377
+ if (submission.settled_outcome === null) return yield* corruptionFailure(operation, "effect_agent_submissions", validated.submissionId, "A settled Submission carries no terminal outcome.");
1378
+ return yield* SettlementConflict.make({
1379
+ submissionId: validated.submissionId,
1380
+ existingOutcome: submission.settled_outcome
1381
+ });
1382
+ }
1383
+ const existing = (yield* readUnknownResolutions(operation, validated.submissionId)).find((row) => row.tool_call_id === validated.toolCallId);
1384
+ const existingIntent = existing === void 0 ? void 0 : yield* unknownResolutionIntentFromRow(operation, existing);
1385
+ if (existingIntent !== void 0 && !equivalentUnknownResolution(existingIntent.resolution, validated.resolution)) return yield* UnknownResolutionConflict.make({
1386
+ submissionId: validated.submissionId,
1387
+ toolCallId: validated.toolCallId
1388
+ });
1389
+ let resolved;
1390
+ if (existingIntent !== void 0) resolved = existingIntent;
1391
+ else {
1392
+ const now = yield* currentInstant;
1393
+ yield* sql`
1394
+ INSERT INTO effect_agent_unknown_resolutions (
1395
+ submission_id,
1396
+ tool_call_id,
1397
+ author,
1398
+ reason,
1399
+ resolution_json,
1400
+ resolved_at
1401
+ ) VALUES (
1402
+ ${validated.submissionId},
1403
+ ${validated.toolCallId},
1404
+ ${validated.author},
1405
+ ${validated.reason},
1406
+ ${resolutionJson},
1407
+ ${now.iso}
1408
+ )
1409
+ `.pipe(Effect.mapError(sqlFailure(operation)));
1410
+ const resolution = yield* parseStoredJsonText(resolutionJson).pipe(Effect.mapError(internalFailure(operation)));
1411
+ resolved = yield* decodeUnknownResolutionIntent({
1412
+ submissionId: validated.submissionId,
1413
+ toolCallId: validated.toolCallId,
1414
+ author: validated.author,
1415
+ reason: validated.reason,
1416
+ resolution,
1417
+ resolvedAt: now.iso
1418
+ }).pipe(Effect.mapError(internalFailure(operation)));
1419
+ }
1420
+ if (submission.state === "unknown" && submission.unknown_tool_call_ids_json !== null) {
1421
+ const markedIds = yield* storedUnknownToolCallIds(operation, submission);
1422
+ const covering = yield* readUnknownResolutions(operation, validated.submissionId);
1423
+ const coveredIds = new Set(covering.map((row) => row.tool_call_id));
1424
+ if (markedIds.every((toolCallId) => coveredIds.has(toolCallId))) yield* sql`
1425
+ UPDATE effect_agent_submissions
1426
+ SET
1427
+ state = 'input-applied',
1428
+ unknown_reason = NULL,
1429
+ unknown_tool_call_ids_json = NULL
1430
+ WHERE submission_id = ${validated.submissionId}
1431
+ `.pipe(Effect.mapError(sqlFailure(operation)));
1432
+ }
1433
+ return resolved;
1434
+ }));
1435
+ yield* hitFailpoint("ledger:unknown-resolution:after", operation);
1436
+ return intent;
1437
+ });
1438
+ const recordChildSettled = Effect.fn("DoSubmissionLedger.recordChildSettled")(function* (request) {
1439
+ const operation = "ledger record child settled";
1440
+ const validated = yield* Schema.decodeEffect(Schema.toType(ChildSettledNotification))(request).pipe(Effect.mapError(internalFailure(operation)));
1441
+ yield* hitFailpoint("ledger:child-settled:before", operation);
1442
+ const outcome = yield* inWriteTransaction(operation, Effect.gen(function* () {
1443
+ const parent = yield* requireSubmission(operation, validated.parentSubmissionId);
1444
+ const child = yield* readSubmission(operation, validated.childSubmissionId);
1445
+ const childReservation = yield* readReservation(operation, validated.childSubmissionId);
1446
+ if (Option.isSome(child) && child.value.state !== "settled" && !(child.value.state === "terminalizing" && Option.isSome(childReservation))) return yield* LedgerError.make({
1447
+ operation,
1448
+ message: `Child submission ${validated.childSubmissionId} has no recorded settlement.`
1449
+ });
1450
+ const now = yield* currentInstant;
1451
+ yield* sql`
1452
+ INSERT INTO effect_agent_child_settlements (
1453
+ parent_submission_id,
1454
+ child_submission_id,
1455
+ child_outcome,
1456
+ recorded_at
1457
+ ) VALUES (
1458
+ ${validated.parentSubmissionId},
1459
+ ${validated.childSubmissionId},
1460
+ ${Option.isSome(child) && child.value.state === "settled" ? child.value.settled_outcome : Option.isSome(childReservation) ? childReservation.value.outcome : null},
1461
+ ${now.iso}
1462
+ )
1463
+ ON CONFLICT (parent_submission_id, child_submission_id) DO NOTHING
1464
+ `.pipe(Effect.mapError(sqlFailure(operation)));
1465
+ if (parent.state !== "suspended" || parent.suspended_reason_json === null) return NOT_WAITING;
1466
+ const reason = yield* Schema.decodeEffect(Schema.fromJsonString(SuspensionReason))(parent.suspended_reason_json).pipe(Effect.mapError((error) => corruptionFailure(operation, "effect_agent_submissions", parent.submission_id, error.message)));
1467
+ if (reason._tag !== "WaitingForChild") return NOT_WAITING;
1468
+ if (!reason.children.some((entry) => entry.childSubmissionId === validated.childSubmissionId)) return NOT_WAITING;
1469
+ const markers = yield* readChildSettlementMarkers(operation, validated.parentSubmissionId);
1470
+ const markerChildren = new Set(markers.map((row) => row.child_submission_id));
1471
+ for (const entry of reason.children) if (!(yield* childProvablySettled(operation, markerChildren, entry.childSubmissionId))) return STILL_WAITING;
1472
+ yield* sql`
1473
+ UPDATE effect_agent_submissions
1474
+ SET
1475
+ state = 'input-applied',
1476
+ suspended_reason_json = NULL,
1477
+ suspended_at = NULL
1478
+ WHERE submission_id = ${validated.parentSubmissionId}
1479
+ `.pipe(Effect.mapError(sqlFailure(operation)));
1480
+ return WOKEN;
1481
+ }));
1482
+ yield* hitFailpoint("ledger:child-settled:after", operation);
1483
+ return outcome;
1484
+ });
1485
+ const reserveChildBudget = Effect.fn("DoSubmissionLedger.reserveChildBudget")(function* (request) {
1486
+ const operation = "ledger reserve child budget";
1487
+ const validated = yield* Schema.decodeEffect(Schema.toType(ChildBudgetReservationRequest))(request).pipe(Effect.mapError(internalFailure(operation)));
1488
+ const allocationJson = yield* encodePersistedJsonText(validated.allocation).pipe(Effect.mapError(internalFailure(operation)));
1489
+ yield* hitFailpoint("ledger:child-reservation:before", operation);
1490
+ const reserved = yield* inWriteTransaction(operation, Effect.gen(function* () {
1491
+ const existing = yield* readChildReservation(operation, validated.reservationId);
1492
+ if (Option.isSome(existing)) {
1493
+ const existingSnapshot = yield* childReservationSnapshotFromRow(operation, existing.value);
1494
+ if (!(existing.value.parent_submission_id === validated.parentSubmissionId && existing.value.parent_tool_call_id === validated.parentToolCallId && existing.value.allocation_digest === validated.allocationDigest && equivalentPersistedJson(existingSnapshot.allocation, validated.allocation))) return yield* ChildReservationConflict.make({
1495
+ reservationId: validated.reservationId,
1496
+ status: existing.value.status,
1497
+ message: "A reservation with this identity exists with a different parent Tool Call or allocation."
1498
+ });
1499
+ return ReservedChildBudget.make({
1500
+ reservation: existingSnapshot,
1501
+ replayed: true
1502
+ });
1503
+ }
1504
+ const collision = yield* readChildReservationForCall(operation, validated.parentSubmissionId, validated.parentToolCallId);
1505
+ if (Option.isSome(collision)) return yield* ChildReservationConflict.make({
1506
+ reservationId: validated.reservationId,
1507
+ status: collision.value.status,
1508
+ message: `Parent Tool Call ${validated.parentToolCallId} already owns reservation ${collision.value.reservation_id}.`
1509
+ });
1510
+ const parent = yield* requireSubmission(operation, validated.parentSubmissionId);
1511
+ yield* requireOwnership(operation, parent, validated.ownershipToken);
1512
+ const now = yield* currentInstant;
1513
+ yield* sql`
1514
+ INSERT INTO effect_agent_child_reservations (
1515
+ reservation_id,
1516
+ parent_submission_id,
1517
+ parent_tool_call_id,
1518
+ status,
1519
+ allocation_json,
1520
+ allocation_digest,
1521
+ reserved_at
1522
+ ) VALUES (
1523
+ ${validated.reservationId},
1524
+ ${validated.parentSubmissionId},
1525
+ ${validated.parentToolCallId},
1526
+ 'reserved',
1527
+ ${allocationJson},
1528
+ ${validated.allocationDigest},
1529
+ ${now.iso}
1530
+ )
1531
+ `.pipe(Effect.mapError(sqlFailure(operation)));
1532
+ const inserted = yield* readChildReservation(operation, validated.reservationId);
1533
+ if (Option.isNone(inserted)) return yield* corruptionFailure(operation, "effect_agent_child_reservations", validated.reservationId, "An inserted child reservation row is missing inside its own transaction.");
1534
+ return ReservedChildBudget.make({
1535
+ reservation: yield* childReservationSnapshotFromRow(operation, inserted.value),
1536
+ replayed: false
1537
+ });
1538
+ }));
1539
+ yield* hitFailpoint("ledger:child-reservation:after", operation);
1540
+ return reserved;
1541
+ });
1542
+ const attachChildToReservation = Effect.fn("DoSubmissionLedger.attachChildToReservation")(function* (request) {
1543
+ const operation = "ledger attach child to reservation";
1544
+ const validated = yield* Schema.decodeEffect(Schema.toType(AttachChildToReservationRequest))(request).pipe(Effect.mapError(internalFailure(operation)));
1545
+ yield* hitFailpoint("ledger:child-attach:before", operation);
1546
+ const attached = yield* inWriteTransaction(operation, Effect.gen(function* () {
1547
+ const existing = yield* readChildReservation(operation, validated.reservationId);
1548
+ if (Option.isNone(existing)) return yield* LedgerError.make({
1549
+ operation,
1550
+ message: `Unknown child reservation ${validated.reservationId}.`
1551
+ });
1552
+ if (existing.value.child_submission_id !== null) {
1553
+ if (existing.value.child_submission_id === validated.childSubmissionId) return yield* childReservationSnapshotFromRow(operation, existing.value);
1554
+ return yield* ChildReservationConflict.make({
1555
+ reservationId: validated.reservationId,
1556
+ status: existing.value.status,
1557
+ message: `Reservation ${validated.reservationId} already records child ${existing.value.child_submission_id}.`
1558
+ });
1559
+ }
1560
+ const parent = yield* requireSubmission(operation, existing.value.parent_submission_id);
1561
+ yield* requireOwnership(operation, parent, validated.ownershipToken);
1562
+ if (existing.value.status !== "reserved") return yield* ChildReservationConflict.make({
1563
+ reservationId: validated.reservationId,
1564
+ status: existing.value.status,
1565
+ message: `Cannot attach a child to a ${existing.value.status} reservation.`
1566
+ });
1567
+ yield* sql`
1568
+ UPDATE effect_agent_child_reservations
1569
+ SET child_submission_id = ${validated.childSubmissionId}
1570
+ WHERE reservation_id = ${validated.reservationId}
1571
+ `.pipe(Effect.mapError(sqlFailure(operation)));
1572
+ const updated = yield* readChildReservation(operation, validated.reservationId);
1573
+ if (Option.isNone(updated)) return yield* corruptionFailure(operation, "effect_agent_child_reservations", validated.reservationId, "An updated child reservation row is missing inside its own transaction.");
1574
+ return yield* childReservationSnapshotFromRow(operation, updated.value);
1575
+ }));
1576
+ yield* hitFailpoint("ledger:child-attach:after", operation);
1577
+ return attached;
1578
+ });
1579
+ const beginChildBudgetRelease = Effect.fn("DoSubmissionLedger.beginChildBudgetRelease")(function* (request) {
1580
+ const operation = "ledger begin child budget release";
1581
+ const validated = yield* Schema.decodeEffect(Schema.toType(BeginChildBudgetReleaseRequest))(request).pipe(Effect.mapError(internalFailure(operation)));
1582
+ const accountingJson = yield* encodePersistedJsonText(validated.accounting).pipe(Effect.mapError(internalFailure(operation)));
1583
+ yield* hitFailpoint("ledger:child-release-pending:before", operation);
1584
+ const frozen = yield* inWriteTransaction(operation, Effect.gen(function* () {
1585
+ const existing = yield* readChildReservation(operation, validated.reservationId);
1586
+ if (Option.isNone(existing)) return yield* LedgerError.make({
1587
+ operation,
1588
+ message: `Unknown child reservation ${validated.reservationId}.`
1589
+ });
1590
+ if (existing.value.status !== "reserved") {
1591
+ const existingSnapshot = yield* childReservationSnapshotFromRow(operation, existing.value);
1592
+ if (existingSnapshot.accounting !== void 0 && equivalentPersistedJson(existingSnapshot.accounting, validated.accounting)) return existingSnapshot;
1593
+ return yield* ChildReservationConflict.make({
1594
+ reservationId: validated.reservationId,
1595
+ status: existing.value.status,
1596
+ message: "A different accounting decision is already frozen for this reservation."
1597
+ });
1598
+ }
1599
+ const now = yield* currentInstant;
1600
+ yield* sql`
1601
+ UPDATE effect_agent_child_reservations
1602
+ SET
1603
+ status = 'releasePending',
1604
+ accounting_json = ${accountingJson},
1605
+ release_began_at = ${now.iso}
1606
+ WHERE reservation_id = ${validated.reservationId}
1607
+ `.pipe(Effect.mapError(sqlFailure(operation)));
1608
+ const updated = yield* readChildReservation(operation, validated.reservationId);
1609
+ if (Option.isNone(updated)) return yield* corruptionFailure(operation, "effect_agent_child_reservations", validated.reservationId, "An updated child reservation row is missing inside its own transaction.");
1610
+ return yield* childReservationSnapshotFromRow(operation, updated.value);
1611
+ }));
1612
+ yield* hitFailpoint("ledger:child-release-pending:after", operation);
1613
+ return frozen;
1614
+ });
1615
+ const releaseChildBudget = Effect.fn("DoSubmissionLedger.releaseChildBudget")(function* (request) {
1616
+ const operation = "ledger release child budget";
1617
+ const validated = yield* Schema.decodeEffect(Schema.toType(ReleaseChildBudgetRequest))(request).pipe(Effect.mapError(internalFailure(operation)));
1618
+ yield* hitFailpoint("ledger:child-release:before", operation);
1619
+ const released = yield* inWriteTransaction(operation, Effect.gen(function* () {
1620
+ const existing = yield* readChildReservation(operation, validated.reservationId);
1621
+ if (Option.isNone(existing)) return yield* LedgerError.make({
1622
+ operation,
1623
+ message: `Unknown child reservation ${validated.reservationId}.`
1624
+ });
1625
+ if (existing.value.status === "released") return yield* childReservationSnapshotFromRow(operation, existing.value);
1626
+ if (existing.value.status !== "releasePending") return yield* ChildReservationConflict.make({
1627
+ reservationId: validated.reservationId,
1628
+ status: existing.value.status,
1629
+ message: "Cannot release a reservation whose accounting decision is not frozen."
1630
+ });
1631
+ const now = yield* currentInstant;
1632
+ yield* sql`
1633
+ UPDATE effect_agent_child_reservations
1634
+ SET status = 'released', released_at = ${now.iso}
1635
+ WHERE reservation_id = ${validated.reservationId}
1636
+ `.pipe(Effect.mapError(sqlFailure(operation)));
1637
+ const updated = yield* readChildReservation(operation, validated.reservationId);
1638
+ if (Option.isNone(updated)) return yield* corruptionFailure(operation, "effect_agent_child_reservations", validated.reservationId, "An updated child reservation row is missing inside its own transaction.");
1639
+ return yield* childReservationSnapshotFromRow(operation, updated.value);
1640
+ }));
1641
+ yield* hitFailpoint("ledger:child-release:after", operation);
1642
+ return released;
1643
+ });
1644
+ const scanPage = Effect.fn("DoSubmissionLedger.scanPage")(function* (cursor) {
1645
+ const operation = "ledger scan nonterminal";
1646
+ const rows = yield* (cursor === void 0 ? sql`
1647
+ SELECT ${sql.literal(SUBMISSION_COLUMNS)}
1648
+ FROM effect_agent_submissions
1649
+ WHERE state <> 'settled'
1650
+ ORDER BY thread_id ASC, queue_sequence ASC
1651
+ LIMIT ${SCAN_PAGE_SIZE}
1652
+ ` : sql`
1653
+ SELECT ${sql.literal(SUBMISSION_COLUMNS)}
1654
+ FROM effect_agent_submissions
1655
+ WHERE state <> 'settled'
1656
+ AND (thread_id, queue_sequence) > (${cursor.threadId}, ${cursor.queueSequence})
1657
+ ORDER BY thread_id ASC, queue_sequence ASC
1658
+ LIMIT ${SCAN_PAGE_SIZE}
1659
+ `).pipe(Effect.mapError(sqlFailure(operation)));
1660
+ const decoded = yield* decodeSubmissionRows(operation, "nonterminal_scan", rows);
1661
+ const snapshots = yield* Effect.forEach(decoded, (row) => decodeSubmissionSnapshot(operation, row));
1662
+ const last = decoded[decoded.length - 1];
1663
+ return [snapshots, last === void 0 || decoded.length < SCAN_PAGE_SIZE ? Option.none() : Option.some({
1664
+ threadId: last.thread_id,
1665
+ queueSequence: last.queue_sequence
1666
+ })];
1667
+ });
1668
+ const scanNonterminal = Stream.paginate(void 0, scanPage);
1669
+ const readAbortIntentForSubmission = Effect.fn("DoSubmissionLedger.readAbortIntentForSubmission")(function* (request) {
1670
+ const operation = "ledger read abort intent";
1671
+ const validated = yield* Schema.decodeEffect(Schema.toType(AbortIntentRequest))(request).pipe(Effect.mapError(internalFailure(operation)));
1672
+ const recordId = submissionAbortRecordId(validated.submissionId);
1673
+ const rows = yield* sql`
1674
+ SELECT
1675
+ submission.submission_id,
1676
+ abort.submission_id AS abort_submission_id,
1677
+ abort.author,
1678
+ abort.reason,
1679
+ abort.requested_at,
1680
+ canonical.record_id AS canonical_record_id
1681
+ FROM effect_agent_submissions AS submission
1682
+ LEFT JOIN effect_agent_abort_intents AS abort
1683
+ ON abort.submission_id = submission.submission_id
1684
+ LEFT JOIN effect_agent_canonical_records AS canonical
1685
+ ON canonical.thread_id = submission.thread_id
1686
+ AND canonical.record_id = ${recordId}
1687
+ WHERE submission.submission_id = ${validated.submissionId}
1688
+ `.pipe(Effect.mapError(sqlFailure(operation)));
1689
+ const decoded = yield* decodeRows(Schema.Array(AbortIntentLookupRow), "effect_agent_abort_intents", validated.submissionId, rows).pipe(Effect.mapError(internalFailure(operation)));
1690
+ if (decoded.length === 0) return yield* LedgerError.make({
1691
+ operation,
1692
+ message: `Unknown submission ${validated.submissionId}.`
1693
+ });
1694
+ if (decoded.length !== 1) return yield* corruptionFailure(operation, "effect_agent_abort_intents", validated.submissionId, "An abort intent lookup returned more than one row.");
1695
+ const row = decoded[0];
1696
+ if (row.abort_submission_id === null) return void 0;
1697
+ return yield* decodeAbortIntent({
1698
+ submissionId: row.abort_submission_id,
1699
+ author: row.author,
1700
+ reason: row.reason,
1701
+ requestedAt: row.requested_at,
1702
+ ...row.canonical_record_id === null ? {} : { canonicalRecordId: row.canonical_record_id }
1703
+ }).pipe(Effect.mapError((error) => corruptionFailure(operation, "effect_agent_abort_intents", validated.submissionId, error.message)));
1704
+ });
1705
+ const loadRecoverySnapshot = Effect.fn("DoSubmissionLedger.loadRecoverySnapshot")(function* (request) {
1706
+ const operation = "ledger load recovery snapshot";
1707
+ const validated = yield* Schema.decodeEffect(Schema.toType(RecoverySnapshotRequest))(request).pipe(Effect.mapError(internalFailure(operation)));
1708
+ return yield* sql.withTransaction(Effect.gen(function* () {
1709
+ const submissionRow = yield* requireSubmission(operation, validated.submissionId);
1710
+ const submission = yield* decodeSubmissionSnapshot(operation, submissionRow);
1711
+ let ownership;
1712
+ const ownershipRow = yield* readOwnership(operation, validated.submissionId);
1713
+ if (Option.isSome(ownershipRow)) ownership = yield* decodeOwnershipSnapshot({
1714
+ attemptId: ownershipRow.value.attempt_id,
1715
+ ownerProducerId: ownershipRow.value.owner_producer_id,
1716
+ producerEpoch: ownershipRow.value.producer_epoch,
1717
+ leaseExpiresAt: ownershipRow.value.lease_expires_at
1718
+ }).pipe(Effect.mapError(internalFailure(operation)));
1719
+ let inputApplied;
1720
+ if (submissionRow.input_applied_record_id !== null && submissionRow.input_applied_sequence !== null) inputApplied = yield* decodeInputAppliedMarker({
1721
+ recordId: submissionRow.input_applied_record_id,
1722
+ sequence: submissionRow.input_applied_sequence
1723
+ }).pipe(Effect.mapError(internalFailure(operation)));
1724
+ let reservation;
1725
+ const reservationRow = yield* readReservation(operation, validated.submissionId);
1726
+ if (Option.isSome(reservationRow)) {
1727
+ const record = yield* decodeRecordEnvelopeText(reservationRow.value.record_json).pipe(Effect.mapError((error) => corruptionFailure(operation, "effect_agent_settlement_reservations", validated.submissionId, error.message)));
1728
+ const settlementId = yield* Schema.decodeEffect(SettlementReservationSnapshot.fields.settlementId)(reservationRow.value.settlement_id).pipe(Effect.mapError(internalFailure(operation)));
1729
+ reservation = SettlementReservationSnapshot.make({
1730
+ settlementId,
1731
+ outcome: reservationRow.value.outcome,
1732
+ record,
1733
+ recordDigest: reservationRow.value.record_digest,
1734
+ finalized: reservationRow.value.finalized_at !== null
1735
+ });
1736
+ }
1737
+ let abortIntent;
1738
+ const abortRow = yield* readAbortIntent(operation, validated.submissionId);
1739
+ if (Option.isSome(abortRow)) abortIntent = yield* abortIntentFromRow(operation, submissionRow, validated.submissionId, abortRow.value);
1740
+ const joinRows = yield* sql`
1741
+ SELECT ${sql.literal(SUBMISSION_COLUMNS)}
1742
+ FROM effect_agent_submissions
1743
+ WHERE joined_host_submission_id = ${validated.submissionId}
1744
+ ORDER BY queue_sequence ASC
1745
+ `.pipe(Effect.mapError(sqlFailure(operation)));
1746
+ const joinSubmissions = yield* decodeSubmissionRows(operation, validated.submissionId, joinRows);
1747
+ const joins = yield* Effect.forEach(joinSubmissions, (row) => decodeJoinSnapshot({
1748
+ submissionId: row.submission_id,
1749
+ state: row.state,
1750
+ hostSubmissionId: validated.submissionId
1751
+ }).pipe(Effect.mapError(internalFailure(operation))));
1752
+ let hostSubmissionId;
1753
+ if (submissionRow.joined_host_submission_id !== null) hostSubmissionId = yield* decodeSubmissionId(submissionRow.joined_host_submission_id).pipe(Effect.mapError(internalFailure(operation)));
1754
+ let suspension;
1755
+ if (submissionRow.suspended_reason_json !== null && submissionRow.suspended_at !== null) {
1756
+ const reason = yield* parseStoredJsonText(submissionRow.suspended_reason_json).pipe(Effect.mapError((error) => corruptionFailure(operation, "effect_agent_submissions", validated.submissionId, error.message)));
1757
+ suspension = yield* decodeSuspensionSnapshot({
1758
+ reason,
1759
+ suspendedAt: submissionRow.suspended_at
1760
+ }).pipe(Effect.mapError((error) => corruptionFailure(operation, "effect_agent_submissions", validated.submissionId, error.message)));
1761
+ }
1762
+ const decisionRows = yield* readApprovalDecisions(operation, validated.submissionId);
1763
+ const approvalDecisions = yield* Effect.forEach(decisionRows, (row) => approvalIntentFromRow(operation, row));
1764
+ const resolutionRows = yield* readUnknownResolutions(operation, validated.submissionId);
1765
+ const unknownResolutions = yield* Effect.forEach(resolutionRows, (row) => unknownResolutionIntentFromRow(operation, row));
1766
+ const childReservationRows = yield* sql`
1767
+ SELECT ${sql.literal(CHILD_RESERVATION_COLUMNS)}
1768
+ FROM effect_agent_child_reservations
1769
+ WHERE parent_submission_id = ${validated.submissionId}
1770
+ ORDER BY parent_tool_call_id ASC
1771
+ `.pipe(Effect.mapError(sqlFailure(operation)));
1772
+ const decodedChildReservations = yield* decodeChildReservationRows(operation, validated.submissionId, childReservationRows);
1773
+ const childReservations = yield* Effect.forEach(decodedChildReservations, (row) => childReservationSnapshotFromRow(operation, row));
1774
+ const markers = yield* readChildSettlementMarkers(operation, validated.submissionId);
1775
+ const markersByChild = new Map(markers.map((row) => [row.child_submission_id, row]));
1776
+ const childAttachments = [];
1777
+ for (const row of decodedChildReservations) {
1778
+ if (row.child_submission_id === null) continue;
1779
+ const child = yield* readSubmission(operation, row.child_submission_id);
1780
+ if (Option.isSome(child)) {
1781
+ childAttachments.push(yield* decodeChildAttachmentSnapshot({
1782
+ toolCallId: row.parent_tool_call_id,
1783
+ childSubmissionId: row.child_submission_id,
1784
+ childState: child.value.state,
1785
+ ...child.value.settled_outcome === null ? {} : { childOutcome: child.value.settled_outcome }
1786
+ }).pipe(Effect.mapError(internalFailure(operation))));
1787
+ continue;
1788
+ }
1789
+ const marker = markersByChild.get(row.child_submission_id);
1790
+ if (marker === void 0) continue;
1791
+ childAttachments.push(yield* decodeChildAttachmentSnapshot({
1792
+ toolCallId: row.parent_tool_call_id,
1793
+ childSubmissionId: row.child_submission_id,
1794
+ childState: "settled",
1795
+ ...marker.child_outcome === null ? {} : { childOutcome: marker.child_outcome }
1796
+ }).pipe(Effect.mapError(internalFailure(operation))));
1797
+ }
1798
+ let parentLinkage;
1799
+ if (submissionRow.parent_submission_id !== null && submissionRow.parent_tool_call_id !== null) parentLinkage = yield* decodeParentLinkage({
1800
+ parentSubmissionId: submissionRow.parent_submission_id,
1801
+ parentToolCallId: submissionRow.parent_tool_call_id
1802
+ }).pipe(Effect.mapError(internalFailure(operation)));
1803
+ return RecoverySnapshot.make({
1804
+ submission,
1805
+ joins,
1806
+ approvalDecisions,
1807
+ unknownResolutions,
1808
+ childReservations,
1809
+ childAttachments,
1810
+ ...parentLinkage === void 0 ? {} : { parentLinkage },
1811
+ ...hostSubmissionId === void 0 ? {} : { hostSubmissionId },
1812
+ ...suspension === void 0 ? {} : { suspension },
1813
+ ...ownership === void 0 ? {} : { ownership },
1814
+ ...inputApplied === void 0 ? {} : { inputApplied },
1815
+ ...reservation === void 0 ? {} : { reservation },
1816
+ ...abortIntent === void 0 ? {} : { abortIntent }
1817
+ });
1818
+ })).pipe(Effect.catchTag("SqlError", (error) => Effect.fail(sqlFailure(operation)(error))));
1819
+ });
1820
+ return Context.make(SubmissionLedger, SubmissionLedger.of({
1821
+ capabilities,
1822
+ admit,
1823
+ markReady,
1824
+ lookup,
1825
+ resolveAdmission,
1826
+ claim,
1827
+ renewOwnership,
1828
+ releaseOwnership,
1829
+ markInputApplied,
1830
+ reserveSettlement,
1831
+ finalizeSettlement,
1832
+ requestAbort,
1833
+ claimJoining,
1834
+ markJoined,
1835
+ revertJoining,
1836
+ suspend,
1837
+ recordApprovalDecision,
1838
+ markUnknown,
1839
+ recordUnknownResolution,
1840
+ recordChildSettled,
1841
+ reserveChildBudget,
1842
+ attachChildToReservation,
1843
+ beginChildBudgetRelease,
1844
+ releaseChildBudget,
1845
+ scanNonterminal,
1846
+ loadRecoverySnapshot,
1847
+ readAbortIntent: readAbortIntentForSubmission
1848
+ }));
1849
+ });
1850
+ /**
1851
+ * Durable Object SubmissionLedger implementation sharing the journal's private SQLite
1852
+ * database, storage-backed transaction discipline, and producer-epoch fencing substrate.
1853
+ * Configuration, failpoint, SQL, and Crypto authority stay visible in the input channel.
1854
+ */
1855
+ const submissionLedgerLayer = Layer.effectContext(makeServices());
1856
+ /**
1857
+ * A composition-root convenience Layer for the durable Submission Ledger. Point it at the
1858
+ * same `ctx.storage` as the ThreadStore so claims fence the same producer epochs.
1859
+ */
1860
+ const ledgerLayer = (options) => Layer.unwrap(Effect.map(DoStorageConfig, (config) => submissionLedgerLayer.pipe(Layer.provide(Layer.mergeAll(Layer.succeed(DoStorageConfig)(config), storageFailpointLayer(options), SqliteClient.layer({ storage: options.storage }), BrowserCrypto.layer))))).pipe(Layer.provide(storageConfigLayer(options)));
1861
+ //#endregion
1862
+ export { ledgerLayer, submissionLedgerLayer, DoSubmissionLedger_exports as t };
1863
+
1864
+ //# sourceMappingURL=DoSubmissionLedger.mjs.map