@effect-agent/storage-cloudflare 0.1.0-beta.45 → 0.1.0-beta.46

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