@effect-agent/storage-cloudflare 0.1.0-beta.12 → 0.1.0-beta.120

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