@effect-agent/storage-cloudflare 0.1.0-beta.9 → 0.1.0-beta.91

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