@effect-agent/storage-cloudflare 0.1.0-beta.8 → 0.1.0-beta.80
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.
- package/dist/DoMemoryStore.d.mts +29 -0
- package/dist/DoMemoryStore.mjs +55 -0
- package/dist/DoMemoryStore.mjs.map +1 -0
- package/dist/DoMessageDeliveryStore.d.mts +17 -0
- package/dist/DoMessageDeliveryStore.mjs +32 -0
- package/dist/DoMessageDeliveryStore.mjs.map +1 -0
- package/dist/DoScheduleStore.d.mts +36 -0
- package/dist/DoScheduleStore.mjs +388 -0
- package/dist/DoScheduleStore.mjs.map +1 -0
- package/dist/DoStorageConfig.d.mts +45 -0
- package/dist/DoStorageConfig.mjs +52 -0
- package/dist/DoStorageConfig.mjs.map +1 -0
- package/dist/DoStorageError-Cmhvl4TQ.d.mts +98 -0
- package/dist/DoStorageError.d.mts +2 -0
- package/dist/DoStorageError.mjs +164 -0
- package/dist/DoStorageError.mjs.map +1 -0
- package/dist/DoStorageFailpoint.d.mts +17 -0
- package/dist/DoStorageFailpoint.mjs +14 -0
- package/dist/DoStorageFailpoint.mjs.map +1 -0
- package/dist/DoStorageFailpointTesting.d.mts +34 -0
- package/dist/DoStorageFailpointTesting.mjs +35 -0
- package/dist/DoStorageFailpointTesting.mjs.map +1 -0
- package/dist/DoStorageVersion-x5OOurvZ.d.mts +12 -0
- package/dist/DoStorageVersion.d.mts +2 -0
- package/dist/DoStorageVersion.mjs +8 -0
- package/dist/DoStorageVersion.mjs.map +1 -0
- package/dist/DoSubmissionLedger.d.mts +23 -0
- package/dist/DoSubmissionLedger.mjs +1849 -0
- package/dist/DoSubmissionLedger.mjs.map +1 -0
- package/dist/DoSubscriptionStore.d.mts +25 -0
- package/dist/DoSubscriptionStore.mjs +183 -0
- package/dist/DoSubscriptionStore.mjs.map +1 -0
- package/dist/DoThreadStore.d.mts +59 -0
- package/dist/DoThreadStore.mjs +465 -0
- package/dist/DoThreadStore.mjs.map +1 -0
- package/dist/MemoryProtocol.d.mts +38160 -0
- package/dist/MemoryProtocol.mjs +219 -0
- package/dist/MemoryProtocol.mjs.map +1 -0
- package/dist/PortProtocol.d.mts +3207 -0
- package/dist/PortProtocol.mjs +176 -0
- package/dist/PortProtocol.mjs.map +1 -0
- package/dist/PortRouting.d.mts +83 -0
- package/dist/PortRouting.mjs +410 -0
- package/dist/PortRouting.mjs.map +1 -0
- package/dist/do-journal-DHqCQeBU.mjs +991 -0
- package/dist/do-journal-DHqCQeBU.mjs.map +1 -0
- package/dist/index.d.mts +14 -1521
- package/dist/index.mjs +14 -3695
- package/dist/migrations-Ba_kOrSx.mjs +287 -0
- package/dist/migrations-Ba_kOrSx.mjs.map +1 -0
- package/dist/rolldown-runtime-D7D4PA-g.mjs +13 -0
- package/package.json +1 -45
- package/src/DoMemoryStore.ts +59 -0
- package/src/DoMessageDeliveryStore.ts +53 -0
- package/src/DoScheduleStore.ts +622 -0
- package/src/{errors.ts → DoStorageError.ts} +10 -3
- package/src/DoStorageFailpoint.ts +20 -0
- package/src/{do-storage-failpoint.ts → DoStorageFailpointTesting.ts} +5 -18
- package/src/DoStorageVersion.ts +2 -0
- package/src/{do-ledger.ts → DoSubmissionLedger.ts} +862 -163
- package/src/DoSubscriptionStore.ts +329 -0
- package/src/DoThreadStore.ts +1014 -0
- package/src/MemoryProtocol.ts +355 -0
- package/src/{port-protocol.ts → PortProtocol.ts} +44 -37
- package/src/{routing.ts → PortRouting.ts} +292 -264
- package/src/index.ts +13 -32
- package/src/{do-journal.ts → internal/do-journal.ts} +716 -232
- package/src/internal/message-delivery-schema.ts +24 -0
- package/src/{migrations.ts → internal/migrations.ts} +51 -35
- package/src/internal/recovery-checkpoint-schema.ts +17 -0
- package/dist/index.mjs.map +0 -1
- package/src/do-conversation-store.ts +0 -850
- /package/src/{do-storage-config.ts → DoStorageConfig.ts} +0 -0
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"DoSubmissionLedger.mjs","names":[],"sources":["../src/DoSubmissionLedger.ts"],"sourcesContent":["import { MessageAdmission } from \"@effect-agent/core/Messaging\";\nimport { EMPTY_TAIL_DIGEST } from \"@effect-agent/thread/Digest\";\nimport {\n ApprovalDecision,\n CanonicalSequence,\n DefinitionDigests,\n Digest,\n PersistedJson,\n WorkerAdmission,\n ProducerEpoch,\n RecordEnvelope,\n SettlementOutcome,\n} from \"@effect-agent/thread/Records\";\nimport {\n AbortCommand,\n AbortIntent,\n AbortIntentRequest,\n AdmissionAdmitted,\n AdmissionConflict,\n AdmissionFence,\n AdmissionGroup,\n AdmissionPolicyError,\n AdmissionNotAdmitted,\n AdmissionRequest,\n SubmissionAdmissionFence,\n AdmissionResult,\n ApprovalConflict,\n ApprovalDecisionCommand,\n ApprovalDecisionIntent,\n AttachChildToReservationRequest,\n BeginChildBudgetReleaseRequest,\n ChildAttachmentSnapshot,\n ChildBudgetReservationRequest,\n ChildBudgetReservationSnapshot,\n ChildReservationConflict,\n ChildReservationStatus,\n ChildSettledNotification,\n Claim,\n ClaimJoiningRequest,\n ClaimRequest,\n InputAppliedMarker,\n JoinSnapshot,\n JoinedToHost,\n JoiningClaim,\n LedgerCapabilities,\n LedgerError,\n MarkInputAppliedRequest,\n MarkJoinedRequest,\n MarkReadyRequest,\n MarkUnknownRequest,\n OwnershipLost,\n OwnershipRenewal,\n OwnershipSnapshot,\n ParentLinkage,\n QueueSequence,\n RecoverySnapshot,\n RecoverySnapshotRequest,\n ReleaseChildBudgetRequest,\n ReleaseOwnershipRequest,\n RenewOwnershipRequest,\n ReservedChildBudget,\n ReservedSettlement,\n RevertJoiningRequest,\n Settlement,\n SettlementConflict,\n SettlementFinalization,\n SettlementReservation,\n SubmissionLedger,\n SubmissionLookup,\n SubmissionLookupByKey,\n SubmissionSnapshot,\n SubmissionState,\n SettlementReservationSnapshot,\n settlementFailureFromRecord,\n SuspendRequest,\n SuspensionReason,\n SuspensionSnapshot,\n UnknownResolution,\n UnknownResolutionCommand,\n UnknownResolutionConflict,\n UnknownResolutionIntent,\n submissionAbortRecordId,\n type ChildSettledOutcome,\n type SuspensionOutcome,\n} from \"@effect-agent/thread/SubmissionLedger\";\nimport { BrowserCrypto } from \"@effect/platform-browser\";\nimport { SqliteClient } from \"@effect/sql-sqlite-do\";\nimport { Clock, Context, Crypto, DateTime, Effect, Layer, Option, Schema, Stream } from \"effect\";\nimport * as SqlClientService from \"effect/unstable/sql/SqlClient\";\nimport type { SqlError } from \"effect/unstable/sql/SqlError\";\n\nimport { DoStorageConfig } from \"./DoStorageConfig.ts\";\nimport {\n DoLedgerError,\n DoStorageCorruptionError,\n DoStorageError,\n type DoStorageFailpointLocation,\n} from \"./DoStorageError.ts\";\nimport { DoStorageFailpoint } from \"./DoStorageFailpoint.ts\";\nimport {\n storageConfigLayer,\n storageFailpointLayer,\n type DoStorageInitializationError,\n type DoStorageOptions,\n} from \"./DoThreadStore.ts\";\nimport { decodeRows, initializeDoJournal } from \"./internal/do-journal.ts\";\n\ntype SubmissionId = SubmissionSnapshot[\"submissionId\"];\n\n/**\n * Static decode-side ceiling; writes are bounded in bytes by the configured\n * `maxStoredValueBytes` (see do-journal.ts).\n */\nconst BoundedStoredText = Schema.String.check(Schema.isMaxLength(2_000_000));\nconst BoundedIdentifier = Schema.NonEmptyString.check(Schema.isMaxLength(1024));\nconst BoundedTimestamp = Schema.NonEmptyString.check(Schema.isMaxLength(128));\n\nconst SCAN_PAGE_SIZE = 256;\nconst EPOCH_ZERO = Schema.decodeSync(ProducerEpoch)(0);\nconst RESUME_IMMEDIATELY: SuspensionOutcome = \"resume-immediately\";\nconst SUSPENDED: SuspensionOutcome = \"suspended\";\nconst NOT_WAITING: ChildSettledOutcome = \"not-waiting\";\nconst STILL_WAITING: ChildSettledOutcome = \"still-waiting\";\nconst WOKEN: ChildSettledOutcome = \"woken\";\nconst MAX_IDENTIFIER_LENGTH = 1_024;\n\nclass SubmissionRow extends Schema.Class<SubmissionRow>(\"SubmissionRow\")({\n submission_id: BoundedIdentifier,\n thread_id: BoundedIdentifier,\n queue_sequence: QueueSequence,\n principal: BoundedIdentifier,\n idempotency_key: BoundedIdentifier,\n agent_id: BoundedIdentifier,\n agent_digests_json: BoundedStoredText,\n deployment_id: BoundedIdentifier,\n input_json: BoundedStoredText,\n input_digest: Digest,\n receipt_id: BoundedIdentifier,\n state: SubmissionState,\n settled_outcome: Schema.NullOr(SettlementOutcome),\n created_at: BoundedTimestamp,\n ready_at: Schema.NullOr(BoundedTimestamp),\n input_applied_record_id: Schema.NullOr(BoundedIdentifier),\n input_applied_sequence: Schema.NullOr(CanonicalSequence),\n joined_host_submission_id: Schema.NullOr(BoundedIdentifier),\n suspended_reason_json: Schema.NullOr(BoundedStoredText),\n suspended_at: Schema.NullOr(BoundedTimestamp),\n unknown_reason: Schema.NullOr(BoundedStoredText),\n unknown_tool_call_ids_json: Schema.NullOr(BoundedStoredText),\n parent_submission_id: Schema.NullOr(BoundedIdentifier),\n parent_tool_call_id: Schema.NullOr(BoundedIdentifier),\n admission_group: Schema.NullOr(AdmissionGroup),\n admission_fence_json: Schema.NullOr(BoundedStoredText),\n worker_admission_json: Schema.NullOr(BoundedStoredText),\n message_admission_json: Schema.NullOr(BoundedStoredText),\n}) {}\n\nclass ChildReservationRow extends Schema.Class<ChildReservationRow>(\"ChildReservationRow\")({\n reservation_id: BoundedIdentifier,\n parent_submission_id: BoundedIdentifier,\n parent_tool_call_id: BoundedIdentifier,\n child_submission_id: Schema.NullOr(BoundedIdentifier),\n status: ChildReservationStatus,\n allocation_json: BoundedStoredText,\n allocation_digest: Digest,\n accounting_json: Schema.NullOr(BoundedStoredText),\n reserved_at: BoundedTimestamp,\n release_began_at: Schema.NullOr(BoundedTimestamp),\n released_at: Schema.NullOr(BoundedTimestamp),\n}) {}\n\nclass ChildSettlementMarkerRow extends Schema.Class<ChildSettlementMarkerRow>(\n \"ChildSettlementMarkerRow\",\n)({\n parent_submission_id: BoundedIdentifier,\n child_submission_id: BoundedIdentifier,\n child_outcome: Schema.NullOr(SettlementOutcome),\n recorded_at: BoundedTimestamp,\n}) {}\n\nclass ApprovalDecisionRow extends Schema.Class<ApprovalDecisionRow>(\"ApprovalDecisionRow\")({\n submission_id: BoundedIdentifier,\n tool_call_id: BoundedIdentifier,\n decision: ApprovalDecision,\n resolver: BoundedIdentifier,\n reason: BoundedStoredText,\n decided_at: BoundedTimestamp,\n}) {}\n\nclass UnknownResolutionRow extends Schema.Class<UnknownResolutionRow>(\"UnknownResolutionRow\")({\n submission_id: BoundedIdentifier,\n tool_call_id: BoundedIdentifier,\n author: BoundedIdentifier,\n reason: BoundedStoredText,\n resolution_json: BoundedStoredText,\n resolved_at: BoundedTimestamp,\n}) {}\n\nclass OwnershipRow extends Schema.Class<OwnershipRow>(\"OwnershipRow\")({\n submission_id: BoundedIdentifier,\n attempt_id: BoundedIdentifier,\n ownership_token: BoundedIdentifier,\n producer_epoch: ProducerEpoch,\n owner_producer_id: BoundedIdentifier,\n lease_expires_at: BoundedTimestamp,\n}) {}\n\nclass ReservationRow extends Schema.Class<ReservationRow>(\"ReservationRow\")({\n submission_id: BoundedIdentifier,\n settlement_id: BoundedIdentifier,\n outcome: SettlementOutcome,\n record_id: BoundedIdentifier,\n record_json: BoundedStoredText,\n record_digest: Digest,\n reserved_at: BoundedTimestamp,\n finalized_at: Schema.NullOr(BoundedTimestamp),\n}) {}\n\nclass AbortIntentRow extends Schema.Class<AbortIntentRow>(\"AbortIntentRow\")({\n submission_id: BoundedIdentifier,\n author: BoundedIdentifier,\n reason: BoundedStoredText,\n requested_at: BoundedTimestamp,\n canonical_record_id: Schema.NullOr(BoundedIdentifier),\n}) {}\n\nclass MaxQueueSequenceRow extends Schema.Class<MaxQueueSequenceRow>(\"MaxQueueSequenceRow\")({\n max_queue_sequence: Schema.Int.check(Schema.isGreaterThanOrEqualTo(0)),\n}) {}\n\nclass AbortIntentLookupRow extends Schema.Class<AbortIntentLookupRow>(\"AbortIntentLookupRow\")({\n submission_id: BoundedIdentifier,\n abort_submission_id: Schema.NullOr(BoundedIdentifier),\n author: Schema.NullOr(BoundedIdentifier),\n reason: Schema.NullOr(BoundedStoredText),\n requested_at: Schema.NullOr(BoundedTimestamp),\n canonical_record_id: Schema.NullOr(BoundedIdentifier),\n}) {}\n\nclass CanonicalRecordIdRow extends Schema.Class<CanonicalRecordIdRow>(\"CanonicalRecordIdRow\")({\n record_id: BoundedIdentifier,\n}) {}\n\nconst SUBMISSION_COLUMNS = `\n submission_id,\n thread_id,\n queue_sequence,\n principal,\n idempotency_key,\n agent_id,\n agent_digests_json,\n deployment_id,\n input_json,\n input_digest,\n receipt_id,\n state,\n settled_outcome,\n created_at,\n ready_at,\n input_applied_record_id,\n input_applied_sequence,\n joined_host_submission_id,\n suspended_reason_json,\n suspended_at,\n unknown_reason,\n unknown_tool_call_ids_json,\n parent_submission_id,\n parent_tool_call_id,\n admission_group,\n admission_fence_json,\n worker_admission_json,\n message_admission_json\n`;\n\nconst CHILD_RESERVATION_COLUMNS = `\n reservation_id,\n parent_submission_id,\n parent_tool_call_id,\n child_submission_id,\n status,\n allocation_json,\n allocation_digest,\n accounting_json,\n reserved_at,\n release_began_at,\n released_at\n`;\n\n/** The branded ToolCallId schema, reached through the thread port so no core import is needed. */\nconst ToolCallIdSchema = ApprovalDecisionCommand.fields.toolCallId;\nconst ToolCallIdList = Schema.Array(ToolCallIdSchema);\n\nconst encodePersistedJsonText = Schema.encodeEffect(Schema.fromJsonString(PersistedJson));\nconst encodeDefinitionDigestsText = Schema.encodeEffect(Schema.fromJsonString(DefinitionDigests));\nconst encodeRecordEnvelopeText = Schema.encodeEffect(Schema.fromJsonString(RecordEnvelope));\nconst decodeRecordEnvelopeText = Schema.decodeEffect(Schema.fromJsonString(RecordEnvelope));\nconst encodeSuspensionReasonText = Schema.encodeEffect(Schema.fromJsonString(SuspensionReason));\nconst encodeUnknownResolutionText = Schema.encodeEffect(Schema.fromJsonString(UnknownResolution));\nconst encodeToolCallIdsText = Schema.encodeEffect(Schema.fromJsonString(ToolCallIdList));\nconst decodeToolCallIdsText = Schema.decodeEffect(Schema.fromJsonString(ToolCallIdList));\nconst parseStoredJsonText = Schema.decodeEffect(Schema.fromJsonString(Schema.Json));\nconst decodeAdmissionResult = Schema.decodeUnknownEffect(AdmissionResult);\nconst decodeClaim = Schema.decodeUnknownEffect(Claim);\nconst decodeOwnershipRenewal = Schema.decodeUnknownEffect(OwnershipRenewal);\nconst decodeSettlement = Schema.decodeUnknownEffect(Settlement);\nconst decodeAbortIntent = Schema.decodeUnknownEffect(AbortIntent);\nconst decodeOwnershipSnapshot = Schema.decodeUnknownEffect(OwnershipSnapshot);\nconst decodeInputAppliedMarker = Schema.decodeUnknownEffect(InputAppliedMarker);\nconst decodeSubmissionSnapshotUnknown = Schema.decodeUnknownEffect(SubmissionSnapshot);\nconst decodeSubmissionId = Schema.decodeUnknownEffect(SubmissionSnapshot.fields.submissionId);\nconst decodeQueueSequence = Schema.decodeUnknownEffect(QueueSequence);\nconst decodeUtcInstant = Schema.decodeUnknownEffect(Schema.DateTimeUtcFromString);\nconst decodeJoiningClaim = Schema.decodeUnknownEffect(JoiningClaim);\nconst decodeJoinSnapshot = Schema.decodeUnknownEffect(JoinSnapshot);\nconst decodeSuspensionSnapshot = Schema.decodeUnknownEffect(SuspensionSnapshot);\nconst decodeApprovalDecisionIntent = Schema.decodeUnknownEffect(ApprovalDecisionIntent);\nconst decodeUnknownResolutionIntent = Schema.decodeUnknownEffect(UnknownResolutionIntent);\nconst decodeParentLinkage = Schema.decodeUnknownEffect(ParentLinkage);\n\nconst decodeChildReservationSnapshotUnknown = Schema.decodeUnknownEffect(\n ChildBudgetReservationSnapshot,\n);\n\nconst decodeChildAttachmentSnapshot = Schema.decodeUnknownEffect(ChildAttachmentSnapshot);\nconst equivalentPersistedJson = Schema.toEquivalence(PersistedJson);\nconst equivalentUnknownResolution = Schema.toEquivalence(UnknownResolution);\nconst isDoStorageError = Schema.is(DoStorageError);\n\n/** Wrap an adapter-internal failure into the port's LedgerError without erasing its tag. */\nconst internalFailure =\n (operation: string) =>\n (error: { readonly message: string }): LedgerError =>\n LedgerError.make({ operation, message: error.message, cause: error });\n\n/**\n * Classify raw SQL failures. Within one Durable Object there is exactly one writer, so the\n * Node adapter's retryable `SqliteWriteContention` classification has no analogue: every raw\n * failure is a `DoLedgerError` preserved as the LedgerError's cause.\n */\nconst sqlFailure =\n (operation: string) =>\n (error: SqlError): LedgerError =>\n internalFailure(operation)(\n DoLedgerError.make({\n cause: error,\n operation,\n message: error.message,\n }),\n );\n\nconst corruptionFailure = (operation: string, table: string, rowKey: string, message: string) =>\n internalFailure(operation)(DoStorageCorruptionError.make({ table, rowKey, message }));\n\nconst makeServices = Effect.fn(\"DoSubmissionLedger.makeServices\")(function* () {\n const config = yield* DoStorageConfig;\n const failpoint = yield* DoStorageFailpoint;\n const sql = yield* SqlClientService.SqlClient;\n const crypto = yield* Crypto.Crypto;\n const admissionFence = yield* SubmissionAdmissionFence;\n const journal = yield* initializeDoJournal(sql, failpoint.hit, config.maxStoredValueBytes);\n\n const hitFailpoint = (\n location: DoStorageFailpointLocation,\n operation: string,\n ): Effect.Effect<void, LedgerError> =>\n failpoint.hit(location).pipe(Effect.mapError((error) => internalFailure(operation)(error)));\n\n /**\n * Run one ledger mutation under the journal's Durable Object storage-backed transaction so\n * ownership-token and epoch checks are atomic with their writes (DUR-006). Transaction\n * failures surface as LedgerError carrying the typed `DoStorageError` as cause.\n */\n const inWriteTransaction = <\n A,\n E extends\n | AdmissionConflict\n | AdmissionPolicyError\n | ApprovalConflict\n | ChildReservationConflict\n | JoinedToHost\n | OwnershipLost\n | SettlementConflict\n | UnknownResolutionConflict\n | LedgerError,\n >(\n operation: string,\n effect: Effect.Effect<A, E>,\n ): Effect.Effect<A, E | LedgerError> =>\n journal\n .withWriteTransaction(operation)(effect)\n .pipe(\n Effect.mapError((error) =>\n isDoStorageError(error) ? internalFailure(operation)(error) : error,\n ),\n );\n\n const mintUuid = (operation: string): Effect.Effect<string, LedgerError> =>\n crypto.randomUUIDv7.pipe(Effect.mapError((error) => internalFailure(operation)(error)));\n\n const currentInstant = Effect.map(Clock.currentTimeMillis, (millis) => ({\n millis,\n iso: new Date(millis).toISOString(),\n }));\n\n const timestampMillis = (operation: string, rowKey: string) => (timestamp: string) =>\n decodeUtcInstant(timestamp).pipe(\n Effect.map(DateTime.toEpochMillis),\n Effect.mapError((error) =>\n corruptionFailure(operation, \"effect_agent_submission_ownership\", rowKey, error.message),\n ),\n );\n\n const decodeSubmissionRows = (operation: string, rowKey: string, rows: unknown) =>\n decodeRows(Schema.Array(SubmissionRow), \"effect_agent_submissions\", rowKey, rows).pipe(\n Effect.mapError(internalFailure(operation)),\n );\n\n const readSubmission = Effect.fn(\"DoSubmissionLedger.readSubmission\")(function* (\n operation: string,\n submissionId: string,\n ): Effect.fn.Return<Option.Option<SubmissionRow>, LedgerError> {\n const rows = yield* sql<Record<string, unknown>>`\n SELECT ${sql.literal(SUBMISSION_COLUMNS)}\n FROM effect_agent_submissions\n WHERE submission_id = ${submissionId}\n `.pipe(Effect.mapError(sqlFailure(operation)));\n\n const decoded = yield* decodeSubmissionRows(operation, submissionId, rows);\n\n if (decoded.length > 1) {\n return yield* corruptionFailure(\n operation,\n \"effect_agent_submissions\",\n submissionId,\n \"A submission primary key returned more than one row.\",\n );\n }\n\n return decoded.length === 0 ? Option.none() : Option.some(decoded[0]);\n });\n\n const requireSubmission = Effect.fn(\"DoSubmissionLedger.requireSubmission\")(function* (\n operation: string,\n submissionId: string,\n ): Effect.fn.Return<SubmissionRow, LedgerError> {\n const submission = yield* readSubmission(operation, submissionId);\n\n if (Option.isNone(submission)) {\n return yield* LedgerError.make({\n operation,\n message: `Unknown submission ${submissionId}.`,\n });\n }\n\n return submission.value;\n });\n\n const readOwnership = Effect.fn(\"DoSubmissionLedger.readOwnership\")(function* (\n operation: string,\n submissionId: string,\n ): Effect.fn.Return<Option.Option<OwnershipRow>, LedgerError> {\n const rows = yield* sql<Record<string, unknown>>`\n SELECT\n submission_id,\n attempt_id,\n ownership_token,\n producer_epoch,\n owner_producer_id,\n lease_expires_at\n FROM effect_agent_submission_ownership\n WHERE submission_id = ${submissionId}\n `.pipe(Effect.mapError(sqlFailure(operation)));\n\n const decoded = yield* decodeRows(\n Schema.Array(OwnershipRow),\n \"effect_agent_submission_ownership\",\n submissionId,\n rows,\n ).pipe(Effect.mapError(internalFailure(operation)));\n\n if (decoded.length > 1) {\n return yield* corruptionFailure(\n operation,\n \"effect_agent_submission_ownership\",\n submissionId,\n \"An ownership primary key returned more than one row.\",\n );\n }\n\n return decoded.length === 0 ? Option.none() : Option.some(decoded[0]);\n });\n\n const threadEpoch = Effect.fn(\"DoSubmissionLedger.threadEpoch\")(function* (\n operation: string,\n threadId: string,\n ): Effect.fn.Return<ProducerEpoch, LedgerError> {\n const threads = yield* journal\n .getThread(threadId)\n .pipe(Effect.mapError(internalFailure(operation)));\n\n return threads.length === 0 ? EPOCH_ZERO : threads[0].producer_epoch;\n });\n\n /**\n * Verify inside the surrounding write transaction that the presented token still owns the\n * Submission's lane; a superseded or missing token fails with OwnershipLost carrying the\n * Thread's current producer epoch (DUR-006).\n */\n const requireOwnership = Effect.fn(\"DoSubmissionLedger.requireOwnership\")(function* (\n operation: string,\n submission: SubmissionRow,\n ownershipToken: string,\n ): Effect.fn.Return<OwnershipRow, OwnershipLost | LedgerError> {\n const ownership = yield* readOwnership(operation, submission.submission_id);\n\n if (Option.isNone(ownership) || ownership.value.ownership_token !== ownershipToken) {\n const actualEpoch = yield* threadEpoch(operation, submission.thread_id);\n\n const submissionId = yield* Schema.decodeUnknownEffect(\n SubmissionSnapshot.fields.submissionId,\n )(submission.submission_id).pipe(Effect.mapError(internalFailure(operation)));\n\n return yield* OwnershipLost.make({ submissionId, actualEpoch });\n }\n\n return ownership.value;\n });\n\n const decodeSubmissionSnapshot = Effect.fn(\"DoSubmissionLedger.decodeSubmissionSnapshot\")(\n function* (\n operation: string,\n row: SubmissionRow,\n ): Effect.fn.Return<SubmissionSnapshot, LedgerError> {\n const agentDigests = yield* parseStoredJsonText(row.agent_digests_json).pipe(\n Effect.mapError((error) =>\n corruptionFailure(\n operation,\n \"effect_agent_submissions\",\n row.submission_id,\n error.message,\n ),\n ),\n );\n\n const inputPayload = yield* parseStoredJsonText(row.input_json).pipe(\n Effect.mapError((error) =>\n corruptionFailure(\n operation,\n \"effect_agent_submissions\",\n row.submission_id,\n error.message,\n ),\n ),\n );\n\n if ((row.parent_submission_id === null) !== (row.parent_tool_call_id === null)) {\n return yield* corruptionFailure(\n operation,\n \"effect_agent_submissions\",\n row.submission_id,\n \"A parent linkage must record both the parent Submission and the parent Tool Call.\",\n );\n }\n\n return yield* decodeSubmissionSnapshotUnknown({\n submissionId: row.submission_id,\n threadId: row.thread_id,\n queueSequence: row.queue_sequence,\n principal: row.principal,\n idempotencyKey: row.idempotency_key,\n agentId: row.agent_id,\n agentDigests,\n deploymentId: row.deployment_id,\n inputPayload,\n inputDigest: row.input_digest,\n receiptId: row.receipt_id,\n state: row.state,\n createdAt: row.created_at,\n ...(row.admission_group === null ? {} : { admissionGroup: row.admission_group }),\n ...(row.worker_admission_json === null\n ? {}\n : {\n workerAdmission: yield* parseStoredJsonText(row.worker_admission_json).pipe(\n Effect.mapError(internalFailure(operation)),\n ),\n }),\n ...(row.message_admission_json === null\n ? {}\n : {\n messageAdmission: yield* parseStoredJsonText(row.message_admission_json).pipe(\n Effect.mapError(internalFailure(operation)),\n ),\n }),\n ...(row.admission_fence_json === null\n ? {}\n : {\n admissionFence: yield* parseStoredJsonText(row.admission_fence_json).pipe(\n Effect.mapError(internalFailure(operation)),\n ),\n }),\n ...(row.settled_outcome === null ? {} : { settledOutcome: row.settled_outcome }),\n ...(row.ready_at === null ? {} : { readyAt: row.ready_at }),\n ...(row.parent_submission_id === null || row.parent_tool_call_id === null\n ? {}\n : {\n parentLinkage: {\n parentSubmissionId: row.parent_submission_id,\n parentToolCallId: row.parent_tool_call_id,\n },\n }),\n }).pipe(\n Effect.mapError((error) =>\n corruptionFailure(\n operation,\n \"effect_agent_submissions\",\n row.submission_id,\n error.message,\n ),\n ),\n );\n },\n );\n\n const readReservation = Effect.fn(\"DoSubmissionLedger.readReservation\")(function* (\n operation: string,\n submissionId: string,\n ): Effect.fn.Return<Option.Option<ReservationRow>, LedgerError> {\n const rows = yield* sql<Record<string, unknown>>`\n SELECT\n submission_id,\n settlement_id,\n outcome,\n record_id,\n record_json,\n record_digest,\n reserved_at,\n finalized_at\n FROM effect_agent_settlement_reservations\n WHERE submission_id = ${submissionId}\n `.pipe(Effect.mapError(sqlFailure(operation)));\n\n const decoded = yield* decodeRows(\n Schema.Array(ReservationRow),\n \"effect_agent_settlement_reservations\",\n submissionId,\n rows,\n ).pipe(Effect.mapError(internalFailure(operation)));\n\n if (decoded.length > 1) {\n return yield* corruptionFailure(\n operation,\n \"effect_agent_settlement_reservations\",\n submissionId,\n \"A settlement reservation primary key returned more than one row.\",\n );\n }\n\n return decoded.length === 0 ? Option.none() : Option.some(decoded[0]);\n });\n\n const readAbortIntent = Effect.fn(\"DoSubmissionLedger.readAbortIntent\")(function* (\n operation: string,\n submissionId: string,\n ): Effect.fn.Return<Option.Option<AbortIntentRow>, LedgerError> {\n const rows = yield* sql<Record<string, unknown>>`\n SELECT\n submission_id,\n author,\n reason,\n requested_at,\n canonical_record_id\n FROM effect_agent_abort_intents\n WHERE submission_id = ${submissionId}\n `.pipe(Effect.mapError(sqlFailure(operation)));\n\n const decoded = yield* decodeRows(\n Schema.Array(AbortIntentRow),\n \"effect_agent_abort_intents\",\n submissionId,\n rows,\n ).pipe(Effect.mapError(internalFailure(operation)));\n\n if (decoded.length > 1) {\n return yield* corruptionFailure(\n operation,\n \"effect_agent_abort_intents\",\n submissionId,\n \"An abort intent primary key returned more than one row.\",\n );\n }\n\n return decoded.length === 0 ? Option.none() : Option.some(decoded[0]);\n });\n\n /**\n * Read the durable cross-store child-settlement markers recorded against one parent\n * Submission (the DC realization of the port's \"cross-store adapters record a durable\n * notification marker\" contract).\n */\n const readChildSettlementMarkers = Effect.fn(\"DoSubmissionLedger.readChildSettlementMarkers\")(\n function* (\n operation: string,\n parentSubmissionId: string,\n ): Effect.fn.Return<ReadonlyArray<ChildSettlementMarkerRow>, LedgerError> {\n const rows = yield* sql<Record<string, unknown>>`\n SELECT\n parent_submission_id,\n child_submission_id,\n child_outcome,\n recorded_at\n FROM effect_agent_child_settlements\n WHERE parent_submission_id = ${parentSubmissionId}\n ORDER BY child_submission_id ASC\n `.pipe(Effect.mapError(sqlFailure(operation)));\n\n return yield* decodeRows(\n Schema.Array(ChildSettlementMarkerRow),\n \"effect_agent_child_settlements\",\n parentSubmissionId,\n rows,\n ).pipe(Effect.mapError(internalFailure(operation)));\n },\n );\n\n /**\n * Whether one listed child is provably settled from THIS store: either its own row lives\n * here and is settled (single-store evidence, identical to the Node adapter), or a durable\n * cross-store notification marker was recorded for it (the child's row lives in another\n * Durable Object and its owner reported the settlement through `recordChildSettled`).\n */\n const childProvablySettled = Effect.fn(\"DoSubmissionLedger.childProvablySettled\")(function* (\n operation: string,\n markerChildren: ReadonlySet<string>,\n childSubmissionId: string,\n ): Effect.fn.Return<boolean, LedgerError> {\n if (markerChildren.has(childSubmissionId)) return true;\n const childRow = yield* readSubmission(operation, childSubmissionId);\n\n return Option.isSome(childRow) && childRow.value.state === \"settled\";\n });\n\n const decodeChildReservationRows = (operation: string, rowKey: string, rows: unknown) =>\n decodeRows(\n Schema.Array(ChildReservationRow),\n \"effect_agent_child_reservations\",\n rowKey,\n rows,\n ).pipe(Effect.mapError(internalFailure(operation)));\n\n const readChildReservation = Effect.fn(\"DoSubmissionLedger.readChildReservation\")(function* (\n operation: string,\n reservationId: string,\n ): Effect.fn.Return<Option.Option<ChildReservationRow>, LedgerError> {\n const rows = yield* sql<Record<string, unknown>>`\n SELECT ${sql.literal(CHILD_RESERVATION_COLUMNS)}\n FROM effect_agent_child_reservations\n WHERE reservation_id = ${reservationId}\n `.pipe(Effect.mapError(sqlFailure(operation)));\n\n const decoded = yield* decodeChildReservationRows(operation, reservationId, rows);\n\n if (decoded.length > 1) {\n return yield* corruptionFailure(\n operation,\n \"effect_agent_child_reservations\",\n reservationId,\n \"A child reservation primary key returned more than one row.\",\n );\n }\n\n return decoded.length === 0 ? Option.none() : Option.some(decoded[0]);\n });\n\n const readChildReservationForCall = Effect.fn(\"DoSubmissionLedger.readChildReservationForCall\")(\n function* (\n operation: string,\n parentSubmissionId: string,\n parentToolCallId: string,\n ): Effect.fn.Return<Option.Option<ChildReservationRow>, LedgerError> {\n const rows = yield* sql<Record<string, unknown>>`\n SELECT ${sql.literal(CHILD_RESERVATION_COLUMNS)}\n FROM effect_agent_child_reservations\n WHERE parent_submission_id = ${parentSubmissionId}\n AND parent_tool_call_id = ${parentToolCallId}\n `.pipe(Effect.mapError(sqlFailure(operation)));\n\n const decoded = yield* decodeChildReservationRows(\n operation,\n `${parentSubmissionId}/${parentToolCallId}`,\n rows,\n );\n\n if (decoded.length > 1) {\n return yield* corruptionFailure(\n operation,\n \"effect_agent_child_reservations\",\n `${parentSubmissionId}/${parentToolCallId}`,\n \"A parent Tool Call returned more than one child reservation.\",\n );\n }\n\n return decoded.length === 0 ? Option.none() : Option.some(decoded[0]);\n },\n );\n\n const childReservationSnapshotFromRow = Effect.fn(\n \"DoSubmissionLedger.childReservationSnapshotFromRow\",\n )(function* (\n operation: string,\n row: ChildReservationRow,\n ): Effect.fn.Return<ChildBudgetReservationSnapshot, LedgerError> {\n const rowFailure = (error: { readonly message: string }) =>\n corruptionFailure(\n operation,\n \"effect_agent_child_reservations\",\n row.reservation_id,\n error.message,\n );\n\n const allocation = yield* parseStoredJsonText(row.allocation_json).pipe(\n Effect.mapError(rowFailure),\n );\n\n const accounting =\n row.accounting_json === null\n ? undefined\n : yield* parseStoredJsonText(row.accounting_json).pipe(Effect.mapError(rowFailure));\n\n return yield* decodeChildReservationSnapshotUnknown({\n reservationId: row.reservation_id,\n parentSubmissionId: row.parent_submission_id,\n parentToolCallId: row.parent_tool_call_id,\n status: row.status,\n allocation,\n allocationDigest: row.allocation_digest,\n reservedAt: row.reserved_at,\n ...(row.child_submission_id === null ? {} : { childSubmissionId: row.child_submission_id }),\n ...(accounting === undefined ? {} : { accounting }),\n ...(row.release_began_at === null ? {} : { releaseBeganAt: row.release_began_at }),\n ...(row.released_at === null ? {} : { releasedAt: row.released_at }),\n }).pipe(Effect.mapError(rowFailure));\n });\n\n const readApprovalDecisions = Effect.fn(\"DoSubmissionLedger.readApprovalDecisions\")(function* (\n operation: string,\n submissionId: string,\n ): Effect.fn.Return<ReadonlyArray<ApprovalDecisionRow>, LedgerError> {\n const rows = yield* sql<Record<string, unknown>>`\n SELECT\n submission_id,\n tool_call_id,\n decision,\n resolver,\n reason,\n decided_at\n FROM effect_agent_approval_decisions\n WHERE submission_id = ${submissionId}\n ORDER BY tool_call_id ASC\n `.pipe(Effect.mapError(sqlFailure(operation)));\n\n return yield* decodeRows(\n Schema.Array(ApprovalDecisionRow),\n \"effect_agent_approval_decisions\",\n submissionId,\n rows,\n ).pipe(Effect.mapError(internalFailure(operation)));\n });\n\n const approvalIntentFromRow = Effect.fn(\"DoSubmissionLedger.approvalIntentFromRow\")(function* (\n operation: string,\n row: ApprovalDecisionRow,\n ): Effect.fn.Return<ApprovalDecisionIntent, LedgerError> {\n return yield* decodeApprovalDecisionIntent({\n submissionId: row.submission_id,\n toolCallId: row.tool_call_id,\n decision: row.decision,\n resolver: row.resolver,\n reason: row.reason,\n decidedAt: row.decided_at,\n }).pipe(\n Effect.mapError((error) =>\n corruptionFailure(\n operation,\n \"effect_agent_approval_decisions\",\n `${row.submission_id}/${row.tool_call_id}`,\n error.message,\n ),\n ),\n );\n });\n\n const readUnknownResolutions = Effect.fn(\"DoSubmissionLedger.readUnknownResolutions\")(function* (\n operation: string,\n submissionId: string,\n ): Effect.fn.Return<ReadonlyArray<UnknownResolutionRow>, LedgerError> {\n const rows = yield* sql<Record<string, unknown>>`\n SELECT\n submission_id,\n tool_call_id,\n author,\n reason,\n resolution_json,\n resolved_at\n FROM effect_agent_unknown_resolutions\n WHERE submission_id = ${submissionId}\n ORDER BY tool_call_id ASC\n `.pipe(Effect.mapError(sqlFailure(operation)));\n\n return yield* decodeRows(\n Schema.Array(UnknownResolutionRow),\n \"effect_agent_unknown_resolutions\",\n submissionId,\n rows,\n ).pipe(Effect.mapError(internalFailure(operation)));\n });\n\n const unknownResolutionIntentFromRow = Effect.fn(\n \"DoSubmissionLedger.unknownResolutionIntentFromRow\",\n )(function* (\n operation: string,\n row: UnknownResolutionRow,\n ): Effect.fn.Return<UnknownResolutionIntent, LedgerError> {\n const resolution = yield* parseStoredJsonText(row.resolution_json).pipe(\n Effect.mapError((error) =>\n corruptionFailure(\n operation,\n \"effect_agent_unknown_resolutions\",\n `${row.submission_id}/${row.tool_call_id}`,\n error.message,\n ),\n ),\n );\n\n return yield* decodeUnknownResolutionIntent({\n submissionId: row.submission_id,\n toolCallId: row.tool_call_id,\n author: row.author,\n reason: row.reason,\n resolution,\n resolvedAt: row.resolved_at,\n }).pipe(\n Effect.mapError((error) =>\n corruptionFailure(\n operation,\n \"effect_agent_unknown_resolutions\",\n `${row.submission_id}/${row.tool_call_id}`,\n error.message,\n ),\n ),\n );\n });\n\n /** The Submission's marked-unknown open Tool Call identities, empty when never marked. */\n const storedUnknownToolCallIds = Effect.fn(\"DoSubmissionLedger.storedUnknownToolCallIds\")(\n function* (\n operation: string,\n submission: SubmissionRow,\n ): Effect.fn.Return<ReadonlyArray<typeof ToolCallIdSchema.Type>, LedgerError> {\n if (submission.unknown_tool_call_ids_json === null) return [];\n\n return yield* decodeToolCallIdsText(submission.unknown_tool_call_ids_json).pipe(\n Effect.mapError((error) =>\n corruptionFailure(\n operation,\n \"effect_agent_submissions\",\n submission.submission_id,\n error.message,\n ),\n ),\n );\n },\n );\n\n /**\n * Canonical history is the abort authority (DUR-015): the intent's canonicalRecordId is\n * derived from the shared canonical-records table using the deterministic abort record\n * identity, never from a cached ledger marker.\n */\n const canonicalAbortRecordId = Effect.fn(\"DoSubmissionLedger.canonicalAbortRecordId\")(function* (\n operation: string,\n threadId: string,\n submissionId: SubmissionId,\n ): Effect.fn.Return<string | undefined, LedgerError> {\n const recordId = submissionAbortRecordId(submissionId);\n\n const rows = yield* sql<Record<string, unknown>>`\n SELECT record_id\n FROM effect_agent_canonical_records\n WHERE thread_id = ${threadId}\n AND record_id = ${recordId}\n `.pipe(Effect.mapError(sqlFailure(operation)));\n\n const decoded = yield* decodeRows(\n Schema.Array(CanonicalRecordIdRow),\n \"effect_agent_canonical_records\",\n `${threadId}/${recordId}`,\n rows,\n ).pipe(Effect.mapError(internalFailure(operation)));\n\n return decoded.length === 0 ? undefined : recordId;\n });\n\n const abortIntentFromRow = Effect.fn(\"DoSubmissionLedger.abortIntentFromRow\")(function* (\n operation: string,\n submission: SubmissionRow,\n submissionId: SubmissionId,\n row: AbortIntentRow,\n ): Effect.fn.Return<AbortIntent, LedgerError> {\n const canonicalRecordId = yield* canonicalAbortRecordId(\n operation,\n submission.thread_id,\n submissionId,\n );\n\n return yield* decodeAbortIntent({\n submissionId: row.submission_id,\n author: row.author,\n reason: row.reason,\n requestedAt: row.requested_at,\n ...(canonicalRecordId === undefined ? {} : { canonicalRecordId }),\n }).pipe(\n Effect.mapError((error) =>\n corruptionFailure(\n operation,\n \"effect_agent_abort_intents\",\n row.submission_id,\n error.message,\n ),\n ),\n );\n });\n\n // Durable Object storage is the single serialized owner: writes confirm through output\n // gates before any response is observable, which is exactly the single-owner crash\n // durability this adapter claims — under its own honest label (P7 WP0).\n const capabilities = Effect.succeed(\n LedgerCapabilities.make({ durability: \"durable-cloudflare\" }),\n );\n\n const admit: SubmissionLedger[\"Service\"][\"admit\"] = Effect.fn(\"DoSubmissionLedger.admit\")(\n function* (request: AdmissionRequest) {\n const operation = \"ledger admit\";\n\n const validated = yield* Schema.decodeUnknownEffect(Schema.toType(AdmissionRequest))(\n request,\n ).pipe(Effect.mapError(internalFailure(operation)));\n\n const inputJson = yield* encodePersistedJsonText(validated.inputPayload).pipe(\n Effect.mapError(internalFailure(operation)),\n );\n\n // The platform's ~2 MB per-value bound, refused typed BEFORE any durable mutation\n // (resource-limits gate; oversized payloads are the designed R2 overflow path).\n yield* journal\n .checkValueBound(operation, inputJson)\n .pipe(Effect.mapError(internalFailure(operation)));\n\n const workerAdmissionJson =\n validated.workerAdmission === undefined\n ? null\n : yield* Schema.encodeEffect(Schema.fromJsonString(WorkerAdmission))(\n validated.workerAdmission,\n ).pipe(Effect.mapError(internalFailure(operation)));\n\n if (\n workerAdmissionJson !== null &&\n new TextEncoder().encode(workerAdmissionJson).byteLength > config.maxStoredValueBytes\n ) {\n return yield* LedgerError.make({\n operation,\n message: \"Worker admission metadata exceeds the stored value bound\",\n });\n }\n\n const messageAdmissionJson =\n validated.messageAdmission === undefined\n ? null\n : yield* Schema.encodeEffect(Schema.fromJsonString(MessageAdmission))(\n validated.messageAdmission,\n ).pipe(Effect.mapError(internalFailure(operation)));\n\n if (\n messageAdmissionJson !== null &&\n new TextEncoder().encode(messageAdmissionJson).byteLength > config.maxStoredValueBytes\n ) {\n return yield* LedgerError.make({\n operation,\n message: \"Message admission metadata exceeds the stored value bound\",\n });\n }\n\n const agentDigestsJson = yield* encodeDefinitionDigestsText(validated.agentDigests).pipe(\n Effect.mapError(internalFailure(operation)),\n );\n\n // Routable Submission identity (D-P6-5): `{uuidv7}:{threadId}`. The cross-DO\n // routing layer parses ITS OWN minted format (split at the first \":\") to address\n // submissionId-only operations to the owning Thread Object; the id stays opaque\n // to every other component, exactly like DN's `submission-{uuid}` prefix.\n const mintedSubmissionId = `${yield* mintUuid(operation)}:${validated.threadId}`;\n\n if (mintedSubmissionId.length > MAX_IDENTIFIER_LENGTH) {\n return yield* LedgerError.make({\n operation,\n message:\n `A routable Submission identity of ${mintedSubmissionId.length} characters exceeds ` +\n `the ${MAX_IDENTIFIER_LENGTH}-character ledger row bound; shorten the Thread identity.`,\n });\n }\n const mintedReceiptId = `receipt-${yield* mintUuid(operation)}`;\n\n yield* hitFailpoint(\"ledger:admit:before\", operation);\n\n const result = yield* inWriteTransaction(\n operation,\n Effect.gen(function* () {\n const keyRowKey = `${validated.threadId}/${validated.principal}/${validated.idempotencyKey}`;\n\n const existingRows = yield* sql<Record<string, unknown>>`\n SELECT ${sql.literal(SUBMISSION_COLUMNS)}\n FROM effect_agent_submissions\n WHERE thread_id = ${validated.threadId}\n AND principal = ${validated.principal}\n AND idempotency_key = ${validated.idempotencyKey}\n `.pipe(Effect.mapError(sqlFailure(operation)));\n\n const existing = yield* decodeSubmissionRows(operation, keyRowKey, existingRows);\n\n if (existing.length > 1) {\n return yield* corruptionFailure(\n operation,\n \"effect_agent_submissions\",\n keyRowKey,\n \"An admission idempotency key returned more than one row.\",\n );\n }\n if (existing.length === 1) {\n // A replay must repeat the exact canonical input AND the exact parent linkage (or\n // its absence): linkage is immutable child lineage (spec §12 step 5, SUB-016).\n const sameLinkage =\n validated.parentLinkage === undefined\n ? existing[0].parent_submission_id === null &&\n existing[0].parent_tool_call_id === null\n : existing[0].parent_submission_id === validated.parentLinkage.parentSubmissionId &&\n existing[0].parent_tool_call_id === validated.parentLinkage.parentToolCallId;\n\n if (existing[0].input_digest !== validated.inputDigest || !sameLinkage) {\n return yield* AdmissionConflict.make({\n threadId: validated.threadId,\n principal: validated.principal,\n idempotencyKey: validated.idempotencyKey,\n existingInputDigest: existing[0].input_digest,\n attemptedInputDigest: validated.inputDigest,\n });\n }\n\n const retainedWorkerAdmission =\n existing[0].worker_admission_json === null\n ? undefined\n : yield* Schema.decodeEffect(Schema.fromJsonString(WorkerAdmission))(\n existing[0].worker_admission_json,\n ).pipe(Effect.mapError(internalFailure(operation)));\n\n const retainedMessageAdmission =\n existing[0].message_admission_json === null\n ? undefined\n : yield* Schema.decodeEffect(Schema.fromJsonString(MessageAdmission))(\n existing[0].message_admission_json,\n ).pipe(Effect.mapError(internalFailure(operation)));\n\n const retainedFence =\n existing[0].admission_fence_json === null\n ? undefined\n : yield* Schema.decodeEffect(Schema.fromJsonString(AdmissionFence))(\n existing[0].admission_fence_json,\n ).pipe(Effect.mapError(internalFailure(operation)));\n\n if (\n (existing[0].admission_group ?? undefined) !== validated.admissionGroup ||\n !Schema.toEquivalence(Schema.optional(WorkerAdmission))(\n retainedWorkerAdmission,\n validated.workerAdmission,\n ) ||\n !Schema.toEquivalence(Schema.optional(MessageAdmission))(\n retainedMessageAdmission,\n validated.messageAdmission,\n ) ||\n !Schema.toEquivalence(Schema.optional(AdmissionFence))(\n retainedFence,\n validated.admissionFence,\n )\n )\n return yield* AdmissionConflict.make({\n threadId: validated.threadId,\n principal: validated.principal,\n idempotencyKey: validated.idempotencyKey,\n existingInputDigest: existing[0].input_digest,\n attemptedInputDigest: validated.inputDigest,\n });\n\n return yield* decodeAdmissionResult({\n submissionId: existing[0].submission_id,\n receiptId: existing[0].receipt_id,\n queueSequence: existing[0].queue_sequence,\n state: existing[0].state,\n replayed: true,\n }).pipe(Effect.mapError(internalFailure(operation)));\n }\n\n // The first accepted input fixes ordinary/worker lane identity atomically with admission.\n // Canonical origin materialization can lag admission; a log scan cannot fence that race.\n const firstRows = yield* sql<Record<string, unknown>>`\n SELECT worker_admission_json FROM effect_agent_submissions\n WHERE thread_id=${validated.threadId} ORDER BY queue_sequence LIMIT 1\n `.pipe(Effect.mapError(sqlFailure(operation)));\n\n const first = yield* Schema.decodeUnknownEffect(\n Schema.Array(\n Schema.Struct({\n worker_admission_json: Schema.NullOr(BoundedStoredText),\n }),\n ),\n )(firstRows).pipe(Effect.mapError(internalFailure(operation)));\n\n if (first[0] !== undefined) {\n const previous =\n first[0].worker_admission_json === null\n ? undefined\n : yield* Schema.decodeEffect(Schema.fromJsonString(WorkerAdmission))(\n first[0].worker_admission_json,\n ).pipe(Effect.mapError(internalFailure(operation)));\n\n if (\n !Schema.toEquivalence(Schema.optional(WorkerAdmission.fields.origin))(\n previous?.origin,\n validated.workerAdmission?.origin,\n )\n )\n return yield* AdmissionPolicyError.make({\n reason: \"refused\",\n code: \"worker-origin-conflict\",\n });\n }\n\n yield* admissionFence.check(validated);\n if (validated.admissionGroup !== undefined) {\n const occupied = yield* sql<Record<string, unknown>>`\n SELECT submission_id FROM effect_agent_submissions\n WHERE thread_id=${validated.threadId} AND admission_group=${validated.admissionGroup} AND state<>'settled' LIMIT 1\n `.pipe(Effect.mapError(sqlFailure(operation)));\n\n if (occupied.length > 0)\n return yield* AdmissionPolicyError.make({\n reason: \"occupied\",\n code: \"admission-group\",\n });\n }\n\n const maxRows = yield* sql<Record<string, unknown>>`\n SELECT COALESCE(MAX(queue_sequence), 0) AS max_queue_sequence\n FROM effect_agent_submissions\n WHERE thread_id = ${validated.threadId}\n `.pipe(Effect.mapError(sqlFailure(operation)));\n\n const decodedMax = yield* decodeRows(\n Schema.Array(MaxQueueSequenceRow),\n \"effect_agent_submissions\",\n validated.threadId,\n maxRows,\n ).pipe(Effect.mapError(internalFailure(operation)));\n\n const queueSequence = yield* decodeQueueSequence(\n (decodedMax[0]?.max_queue_sequence ?? 0) + 1,\n ).pipe(Effect.mapError(internalFailure(operation)));\n\n const now = yield* currentInstant;\n\n yield* sql`\n INSERT INTO effect_agent_submissions (\n submission_id,\n thread_id,\n queue_sequence,\n principal,\n idempotency_key,\n agent_id,\n agent_digests_json,\n deployment_id,\n input_json,\n input_digest,\n receipt_id,\n state,\n created_at,\n parent_submission_id,\n parent_tool_call_id,\n admission_group,\n admission_fence_json,\n worker_admission_json,\n message_admission_json\n ) VALUES (\n ${mintedSubmissionId},\n ${validated.threadId},\n ${queueSequence},\n ${validated.principal},\n ${validated.idempotencyKey},\n ${validated.agentId},\n ${agentDigestsJson},\n ${validated.deploymentId},\n ${inputJson},\n ${validated.inputDigest},\n ${mintedReceiptId},\n 'admitted',\n ${now.iso},\n ${validated.parentLinkage?.parentSubmissionId ?? null},\n ${validated.parentLinkage?.parentToolCallId ?? null},\n ${validated.admissionGroup ?? null},\n ${validated.admissionFence === undefined ? null : JSON.stringify(validated.admissionFence)},\n ${workerAdmissionJson},\n ${messageAdmissionJson}\n )\n `.pipe(Effect.mapError(sqlFailure(operation)));\n\n return yield* decodeAdmissionResult({\n submissionId: mintedSubmissionId,\n receiptId: mintedReceiptId,\n queueSequence,\n state: \"admitted\",\n replayed: false,\n }).pipe(Effect.mapError(internalFailure(operation)));\n }),\n );\n\n yield* hitFailpoint(\"ledger:admit:after\", operation);\n\n return result;\n },\n );\n\n const markReady: SubmissionLedger[\"Service\"][\"markReady\"] = Effect.fn(\n \"DoSubmissionLedger.markReady\",\n )(function* (request: MarkReadyRequest) {\n const operation = \"ledger mark ready\";\n\n const validated = yield* Schema.decodeUnknownEffect(Schema.toType(MarkReadyRequest))(\n request,\n ).pipe(Effect.mapError(internalFailure(operation)));\n\n yield* hitFailpoint(\"ledger:mark-ready:before\", operation);\n yield* inWriteTransaction(\n operation,\n Effect.gen(function* () {\n const submission = yield* requireSubmission(operation, validated.submissionId);\n\n if (submission.state !== \"admitted\") return;\n const now = yield* currentInstant;\n\n yield* sql`\n UPDATE effect_agent_submissions\n SET state = 'ready', ready_at = ${now.iso}\n WHERE submission_id = ${validated.submissionId}\n `.pipe(Effect.mapError(sqlFailure(operation)));\n }),\n );\n yield* hitFailpoint(\"ledger:mark-ready:after\", operation);\n });\n\n const lookup: SubmissionLedger[\"Service\"][\"lookup\"] = Effect.fn(\"DoSubmissionLedger.lookup\")(\n function* (request: SubmissionLookup) {\n const operation = \"ledger lookup\";\n\n const validated = yield* Schema.decodeUnknownEffect(Schema.toType(SubmissionLookup))(\n request,\n ).pipe(Effect.mapError(internalFailure(operation)));\n\n if (validated._tag === \"SubmissionLookupById\") {\n const row = yield* readSubmission(operation, validated.submissionId);\n\n if (Option.isNone(row)) return Option.none();\n\n return Option.some(yield* decodeSubmissionSnapshot(operation, row.value));\n }\n\n const rows = yield* sql<Record<string, unknown>>`\n SELECT ${sql.literal(SUBMISSION_COLUMNS)}\n FROM effect_agent_submissions\n WHERE thread_id = ${validated.threadId}\n AND principal = ${validated.principal}\n AND idempotency_key = ${validated.idempotencyKey}\n `.pipe(Effect.mapError(sqlFailure(operation)));\n\n const decoded = yield* decodeSubmissionRows(\n operation,\n `${validated.threadId}/${validated.principal}/${validated.idempotencyKey}`,\n rows,\n );\n\n if (decoded.length > 1) {\n return yield* corruptionFailure(\n operation,\n \"effect_agent_submissions\",\n `${validated.threadId}/${validated.principal}/${validated.idempotencyKey}`,\n \"An admission idempotency key returned more than one row.\",\n );\n }\n if (decoded.length === 0) return Option.none();\n\n return Option.some(yield* decodeSubmissionSnapshot(operation, decoded[0]));\n },\n );\n\n // This LOCAL facet is the authoritative owner of every Thread stored in this Durable\n // Object, so the key-scoped read IS the admission truth and the tri-state degenerates to\n // NotAdmitted or Admitted (SUB-031). `AdmissionIndeterminate` becomes real one layer out:\n // the WP2 routed decorator answers it when the OWNING Durable Object is unreachable.\n const resolveAdmission: SubmissionLedger[\"Service\"][\"resolveAdmission\"] = Effect.fn(\n \"DoSubmissionLedger.resolveAdmission\",\n )(function* (request: SubmissionLookupByKey) {\n const operation = \"ledger resolve admission\";\n\n const validated = yield* Schema.decodeUnknownEffect(Schema.toType(SubmissionLookupByKey))(\n request,\n ).pipe(Effect.mapError(internalFailure(operation)));\n\n const rows = yield* sql<Record<string, unknown>>`\n SELECT ${sql.literal(SUBMISSION_COLUMNS)}\n FROM effect_agent_submissions\n WHERE thread_id = ${validated.threadId}\n AND principal = ${validated.principal}\n AND idempotency_key = ${validated.idempotencyKey}\n `.pipe(Effect.mapError(sqlFailure(operation)));\n\n const decoded = yield* decodeSubmissionRows(\n operation,\n `${validated.threadId}/${validated.principal}/${validated.idempotencyKey}`,\n rows,\n );\n\n if (decoded.length > 1) {\n return yield* corruptionFailure(\n operation,\n \"effect_agent_submissions\",\n `${validated.threadId}/${validated.principal}/${validated.idempotencyKey}`,\n \"An admission idempotency key returned more than one row.\",\n );\n }\n if (decoded.length === 0) return AdmissionNotAdmitted.make();\n\n return AdmissionAdmitted.make({\n submission: yield* decodeSubmissionSnapshot(operation, decoded[0]),\n });\n });\n\n const claim: SubmissionLedger[\"Service\"][\"claim\"] = Effect.fn(\"DoSubmissionLedger.claim\")(\n function* (request: ClaimRequest) {\n const operation = \"ledger claim\";\n\n const validated = yield* Schema.decodeUnknownEffect(Schema.toType(ClaimRequest))(\n request,\n ).pipe(Effect.mapError(internalFailure(operation)));\n\n const attemptId = `attempt-${yield* mintUuid(operation)}`;\n const ownershipToken = `owner-${yield* mintUuid(operation)}`;\n\n yield* hitFailpoint(\"ledger:claim:before\", operation);\n\n const claimed = yield* inWriteTransaction(\n operation,\n Effect.gen(function* () {\n const headRows = yield* sql<Record<string, unknown>>`\n SELECT ${sql.literal(SUBMISSION_COLUMNS)}\n FROM effect_agent_submissions\n WHERE thread_id = ${validated.threadId}\n AND state <> 'settled'\n ORDER BY queue_sequence ASC\n LIMIT 1\n `.pipe(Effect.mapError(sqlFailure(operation)));\n\n const heads = yield* decodeSubmissionRows(operation, validated.threadId, headRows);\n\n if (heads.length === 0) return Option.none<Claim>();\n const head = heads[0];\n\n // Unknown work is claimable only for a durably requested abort: the coordinator\n // cleans up children and settles without replaying ordinary Tools. Read the intent\n // in this claim transaction; retain uncertainty evidence and all ownership fencing.\n if (\n head.state === \"joining\" ||\n head.state === \"joined\" ||\n head.state === \"suspended\" ||\n (head.state === \"unknown\" &&\n Option.isNone(yield* readAbortIntent(operation, head.submission_id)))\n ) {\n return Option.none<Claim>();\n }\n\n const now = yield* currentInstant;\n const ownership = yield* readOwnership(operation, head.submission_id);\n\n if (Option.isSome(ownership)) {\n const expiresAt = yield* timestampMillis(\n operation,\n head.submission_id,\n )(ownership.value.lease_expires_at);\n\n // A live lease blocks every new claim; expiry alone only revokes the liveness\n // assumption — correctness stays with producer-epoch fencing (D5). In DC a live\n // lease under another token can only come from an evicted incarnation.\n if (expiresAt > now.millis) return Option.none<Claim>();\n }\n\n // Bump the Thread's producer epoch atomically with the claim so every stale\n // Attempt is fenced out of canonical appends (DUR-006). A Thread that was\n // never materialized (eviction between admission and materialization) is created\n // here so recovery can claim first and re-materialize idempotently at this epoch.\n const threads = yield* journal\n .getThread(head.thread_id)\n .pipe(Effect.mapError(internalFailure(operation)));\n\n let producerEpoch: number;\n\n if (threads.length === 0) {\n producerEpoch = 1;\n yield* sql`\n INSERT INTO effect_agent_threads (\n thread_id,\n created_at,\n tail_sequence,\n tail_digest,\n producer_epoch\n ) VALUES (\n ${head.thread_id},\n ${now.iso},\n 0,\n ${EMPTY_TAIL_DIGEST},\n ${producerEpoch}\n )\n `.pipe(Effect.mapError(sqlFailure(operation)));\n } else {\n producerEpoch = threads[0].producer_epoch + 1;\n yield* sql`\n UPDATE effect_agent_threads\n SET producer_epoch = ${producerEpoch}\n WHERE thread_id = ${head.thread_id}\n `.pipe(Effect.mapError(sqlFailure(operation)));\n }\n\n const leaseExpiresAt = new Date(now.millis + config.ownershipLeaseDuration).toISOString();\n\n yield* sql`\n INSERT INTO effect_agent_submission_ownership (\n submission_id,\n attempt_id,\n ownership_token,\n producer_epoch,\n owner_producer_id,\n lease_expires_at\n ) VALUES (\n ${head.submission_id},\n ${attemptId},\n ${ownershipToken},\n ${producerEpoch},\n ${validated.producerId},\n ${leaseExpiresAt}\n )\n ON CONFLICT (submission_id) DO UPDATE SET\n attempt_id = excluded.attempt_id,\n ownership_token = excluded.ownership_token,\n producer_epoch = excluded.producer_epoch,\n owner_producer_id = excluded.owner_producer_id,\n lease_expires_at = excluded.lease_expires_at\n `.pipe(Effect.mapError(sqlFailure(operation)));\n\n yield* sql`\n INSERT INTO effect_agent_attempts (\n attempt_id,\n submission_id,\n thread_id,\n owner_producer_id,\n producer_epoch,\n claimed_at\n ) VALUES (\n ${attemptId},\n ${head.submission_id},\n ${head.thread_id},\n ${validated.producerId},\n ${producerEpoch},\n ${now.iso}\n )\n `.pipe(Effect.mapError(sqlFailure(operation)));\n\n if (head.state === \"ready\") {\n yield* sql`\n UPDATE effect_agent_submissions\n SET state = 'running'\n WHERE submission_id = ${head.submission_id}\n `.pipe(Effect.mapError(sqlFailure(operation)));\n }\n\n const inputPayload = yield* parseStoredJsonText(head.input_json).pipe(\n Effect.mapError((error) =>\n corruptionFailure(\n operation,\n \"effect_agent_submissions\",\n head.submission_id,\n error.message,\n ),\n ),\n );\n\n return Option.some(\n yield* decodeClaim({\n submissionId: head.submission_id,\n attemptId,\n ownershipToken,\n producerEpoch,\n leaseExpiresAt,\n inputPayload,\n }).pipe(Effect.mapError(internalFailure(operation))),\n );\n }),\n );\n\n yield* hitFailpoint(\"ledger:claim:after\", operation);\n\n return claimed;\n },\n );\n\n const renewOwnership: SubmissionLedger[\"Service\"][\"renewOwnership\"] = Effect.fn(\n \"DoSubmissionLedger.renewOwnership\",\n )(function* (request: RenewOwnershipRequest) {\n const operation = \"ledger renew ownership\";\n\n const validated = yield* Schema.decodeUnknownEffect(Schema.toType(RenewOwnershipRequest))(\n request,\n ).pipe(Effect.mapError(internalFailure(operation)));\n\n yield* hitFailpoint(\"ledger:renew:before\", operation);\n\n const renewal = yield* inWriteTransaction(\n operation,\n Effect.gen(function* () {\n const submission = yield* requireSubmission(operation, validated.submissionId);\n\n yield* requireOwnership(operation, submission, validated.ownershipToken);\n const now = yield* currentInstant;\n const leaseExpiresAt = new Date(now.millis + config.ownershipLeaseDuration).toISOString();\n\n yield* sql`\n UPDATE effect_agent_submission_ownership\n SET lease_expires_at = ${leaseExpiresAt}\n WHERE submission_id = ${validated.submissionId}\n `.pipe(Effect.mapError(sqlFailure(operation)));\n\n return yield* decodeOwnershipRenewal({\n ownershipToken: validated.ownershipToken,\n leaseExpiresAt,\n }).pipe(Effect.mapError(internalFailure(operation)));\n }),\n );\n\n yield* hitFailpoint(\"ledger:renew:after\", operation);\n\n return renewal;\n });\n\n const releaseOwnership: SubmissionLedger[\"Service\"][\"releaseOwnership\"] = Effect.fn(\n \"DoSubmissionLedger.releaseOwnership\",\n )(function* (request: ReleaseOwnershipRequest) {\n const operation = \"ledger release ownership\";\n\n const validated = yield* Schema.decodeUnknownEffect(Schema.toType(ReleaseOwnershipRequest))(\n request,\n ).pipe(Effect.mapError(internalFailure(operation)));\n\n yield* hitFailpoint(\"ledger:release:before\", operation);\n yield* inWriteTransaction(\n operation,\n Effect.gen(function* () {\n const submission = yield* requireSubmission(operation, validated.submissionId);\n\n yield* requireOwnership(operation, submission, validated.ownershipToken);\n yield* sql`\n DELETE FROM effect_agent_submission_ownership\n WHERE submission_id = ${validated.submissionId}\n `.pipe(Effect.mapError(sqlFailure(operation)));\n if (submission.state === \"running\") {\n yield* sql`\n UPDATE effect_agent_submissions\n SET state = 'ready'\n WHERE submission_id = ${validated.submissionId}\n `.pipe(Effect.mapError(sqlFailure(operation)));\n }\n }),\n );\n yield* hitFailpoint(\"ledger:release:after\", operation);\n });\n\n const markInputApplied: SubmissionLedger[\"Service\"][\"markInputApplied\"] = Effect.fn(\n \"DoSubmissionLedger.markInputApplied\",\n )(function* (request: MarkInputAppliedRequest) {\n const operation = \"ledger mark input applied\";\n\n const validated = yield* Schema.decodeUnknownEffect(Schema.toType(MarkInputAppliedRequest))(\n request,\n ).pipe(Effect.mapError(internalFailure(operation)));\n\n yield* hitFailpoint(\"ledger:mark-input-applied:before\", operation);\n yield* inWriteTransaction(\n operation,\n Effect.gen(function* () {\n const submission = yield* requireSubmission(operation, validated.submissionId);\n\n yield* requireOwnership(operation, submission, validated.ownershipToken);\n if (submission.input_applied_record_id !== null) {\n if (\n submission.input_applied_record_id === validated.recordId &&\n submission.input_applied_sequence === validated.sequence\n ) {\n return;\n }\n\n return yield* corruptionFailure(\n operation,\n \"effect_agent_submissions\",\n validated.submissionId,\n \"A different canonical input marker is already recorded for this Submission.\",\n );\n }\n yield* sql`\n UPDATE effect_agent_submissions\n SET\n input_applied_record_id = ${validated.recordId},\n input_applied_sequence = ${validated.sequence},\n state = CASE\n WHEN state IN ('admitted', 'ready', 'running') THEN 'input-applied'\n ELSE state\n END\n WHERE submission_id = ${validated.submissionId}\n `.pipe(Effect.mapError(sqlFailure(operation)));\n }),\n );\n yield* hitFailpoint(\"ledger:mark-input-applied:after\", operation);\n });\n\n const reserveSettlement: SubmissionLedger[\"Service\"][\"reserveSettlement\"] = Effect.fn(\n \"DoSubmissionLedger.reserveSettlement\",\n )(function* (request: SettlementReservation) {\n const operation = \"ledger reserve settlement\";\n\n const validated = yield* Schema.decodeUnknownEffect(Schema.toType(SettlementReservation))(\n request,\n ).pipe(Effect.mapError(internalFailure(operation)));\n\n const recordJson = yield* encodeRecordEnvelopeText(validated.record).pipe(\n Effect.mapError(internalFailure(operation)),\n );\n\n // The reserved record is appended canonically later; refuse over-bound payloads typed\n // before the reservation row exists.\n yield* journal\n .checkValueBound(operation, recordJson)\n .pipe(Effect.mapError(internalFailure(operation)));\n yield* hitFailpoint(\"ledger:reserve-settlement:before\", operation);\n\n const reserved = yield* inWriteTransaction(\n operation,\n Effect.gen(function* () {\n const existing = yield* readReservation(operation, validated.submissionId);\n\n if (Option.isSome(existing)) {\n const identical =\n existing.value.settlement_id === validated.settlementId &&\n existing.value.outcome === validated.outcome &&\n existing.value.record_digest === validated.recordDigest &&\n existing.value.record_json === recordJson;\n\n if (!identical) {\n return yield* SettlementConflict.make({\n submissionId: validated.submissionId,\n existingOutcome: existing.value.outcome,\n });\n }\n\n const record = yield* decodeRecordEnvelopeText(existing.value.record_json).pipe(\n Effect.mapError((error) =>\n corruptionFailure(\n operation,\n \"effect_agent_settlement_reservations\",\n validated.submissionId,\n error.message,\n ),\n ),\n );\n\n return ReservedSettlement.make({\n submissionId: validated.submissionId,\n settlementId: validated.settlementId,\n outcome: validated.outcome,\n record,\n recordDigest: validated.recordDigest,\n replayed: true,\n });\n }\n\n const submission = yield* requireSubmission(operation, validated.submissionId);\n\n if (submission.state === \"settled\") {\n if (submission.settled_outcome === null) {\n return yield* corruptionFailure(\n operation,\n \"effect_agent_submissions\",\n validated.submissionId,\n \"A settled Submission carries no terminal outcome.\",\n );\n }\n\n return yield* SettlementConflict.make({\n submissionId: validated.submissionId,\n existingOutcome: submission.settled_outcome,\n });\n }\n // A `joined` Submission settles WITH its host (plan §2.5) and its lane is never\n // worker-claimable, so no ownership token can exist for it: the recorded host linkage\n // authorizes the reservation and the presented token is not consulted.\n if (!(submission.state === \"joined\" && submission.joined_host_submission_id !== null)) {\n // P7 §7(c): an aborted, never-claimed, still-queued Submission likewise has no live\n // ownership to fence against — its durable abort intent authorizes exactly its\n // ABORTED settlement (`terminalizing` is the same pass's crash replay). Every other\n // reservation stays fenced by the target lane's live ownership.\n let queuedAbortSettlement = false;\n\n if (\n validated.outcome === \"aborted\" &&\n (submission.state === \"ready\" || submission.state === \"terminalizing\")\n ) {\n const abortIntent = yield* readAbortIntent(operation, validated.submissionId);\n\n if (Option.isSome(abortIntent)) {\n const ownership = yield* readOwnership(operation, validated.submissionId);\n\n queuedAbortSettlement = Option.isNone(ownership);\n }\n }\n if (!queuedAbortSettlement) {\n yield* requireOwnership(operation, submission, validated.ownershipToken);\n }\n }\n const now = yield* currentInstant;\n\n yield* sql`\n INSERT INTO effect_agent_settlement_reservations (\n submission_id,\n settlement_id,\n outcome,\n record_id,\n record_json,\n record_digest,\n reserved_at\n ) VALUES (\n ${validated.submissionId},\n ${validated.settlementId},\n ${validated.outcome},\n ${validated.record.recordId},\n ${recordJson},\n ${validated.recordDigest},\n ${now.iso}\n )\n `.pipe(Effect.mapError(sqlFailure(operation)));\n yield* sql`\n UPDATE effect_agent_submissions\n SET state = 'terminalizing'\n WHERE submission_id = ${validated.submissionId}\n `.pipe(Effect.mapError(sqlFailure(operation)));\n\n return ReservedSettlement.make({\n submissionId: validated.submissionId,\n settlementId: validated.settlementId,\n outcome: validated.outcome,\n record: validated.record,\n recordDigest: validated.recordDigest,\n replayed: false,\n });\n }),\n );\n\n yield* hitFailpoint(\"ledger:reserve-settlement:after\", operation);\n\n return reserved;\n });\n\n const validateFinalization = Effect.fn(\"DoSubmissionLedger.validateFinalization\")(function* (\n validated: SettlementFinalization,\n reservation: Option.Option<ReservationRow>,\n ) {\n const operation = \"ledger finalize settlement\";\n\n if (Option.isNone(reservation)) {\n return yield* LedgerError.make({\n operation,\n message: `No settlement reservation exists for submission ${validated.submissionId}.`,\n });\n }\n if (reservation.value.settlement_id !== validated.settlementId) {\n return yield* SettlementConflict.make({\n submissionId: validated.submissionId,\n existingOutcome: reservation.value.outcome,\n });\n }\n\n const reservationRecord = yield* decodeRecordEnvelopeText(reservation.value.record_json).pipe(\n Effect.mapError((error) =>\n corruptionFailure(\n operation,\n \"effect_agent_settlement_reservations\",\n validated.submissionId,\n error.message,\n ),\n ),\n );\n\n const settlementFailure = settlementFailureFromRecord(reservationRecord);\n\n if ((reservation.value.outcome === \"failed\") !== (settlementFailure !== undefined)) {\n return yield* corruptionFailure(\n operation,\n \"effect_agent_settlement_reservations\",\n validated.submissionId,\n \"The reserved outcome and canonical failure diagnostic disagree.\",\n );\n }\n\n return { reservation: reservation.value, settlementFailure };\n });\n\n const replayFinalization = Effect.fn(\"DoSubmissionLedger.replayFinalization\")(function* (\n validated: SettlementFinalization,\n submission: SubmissionRow,\n { reservation, settlementFailure }: Effect.Success<ReturnType<typeof validateFinalization>>,\n ) {\n const operation = \"ledger finalize settlement\";\n\n if (reservation.finalized_at === null) {\n return yield* corruptionFailure(\n operation,\n \"effect_agent_settlement_reservations\",\n validated.submissionId,\n \"A settled Submission's reservation carries no finalization timestamp.\",\n );\n }\n\n return yield* decodeSettlement({\n submissionId: validated.submissionId,\n settlementId: validated.settlementId,\n receiptId: submission.receipt_id,\n outcome: reservation.outcome,\n ...(settlementFailure === undefined ? {} : { failure: settlementFailure }),\n settledAt: reservation.finalized_at,\n }).pipe(Effect.mapError(internalFailure(operation)));\n });\n\n const finalizeSettlement: SubmissionLedger[\"Service\"][\"finalizeSettlement\"] = Effect.fn(\n \"DoSubmissionLedger.finalizeSettlement\",\n )(function* (request: SettlementFinalization) {\n const operation = \"ledger finalize settlement\";\n\n const validated = yield* Schema.decodeUnknownEffect(Schema.toType(SettlementFinalization))(\n request,\n ).pipe(Effect.mapError(internalFailure(operation)));\n\n yield* hitFailpoint(\"ledger:finalize-settlement:before\", operation);\n\n // A single statement captures the settled row and its immutable reservation together.\n // A miss does not authorize finalization: the write path re-reads under its transaction.\n const replayRows = yield* sql<Record<string, unknown>>`\n SELECT submission.*, reservation.settlement_id, reservation.outcome,\n reservation.record_id, reservation.record_json, reservation.record_digest,\n reservation.reserved_at, reservation.finalized_at\n FROM effect_agent_submissions AS submission\n INNER JOIN effect_agent_settlement_reservations AS reservation\n ON reservation.submission_id = submission.submission_id\n WHERE submission.submission_id = ${validated.submissionId} AND submission.state = 'settled'\n `.pipe(Effect.mapError(sqlFailure(operation)));\n\n if (replayRows.length > 1) {\n return yield* corruptionFailure(\n operation,\n \"effect_agent_submissions\",\n validated.submissionId,\n \"A submission primary key returned more than one row.\",\n );\n }\n const replayRow = replayRows[0];\n\n if (replayRow !== undefined) {\n const reservations = yield* decodeRows(\n Schema.Array(ReservationRow),\n \"effect_agent_settlement_reservations\",\n validated.submissionId,\n replayRows,\n ).pipe(Effect.mapError(internalFailure(operation)));\n\n const state = yield* validateFinalization(validated, Option.fromUndefinedOr(reservations[0]));\n\n const submission = yield* Schema.decodeUnknownEffect(SubmissionRow)(replayRow).pipe(\n Effect.mapError((error) =>\n corruptionFailure(\n operation,\n \"effect_agent_submissions\",\n validated.submissionId,\n error.message,\n ),\n ),\n );\n\n const settlement = yield* replayFinalization(validated, submission, state);\n\n yield* hitFailpoint(\"ledger:finalize-settlement:after\", operation);\n\n return settlement;\n }\n\n const settlement = yield* inWriteTransaction(\n operation,\n Effect.gen(function* () {\n const state = yield* validateFinalization(\n validated,\n yield* readReservation(operation, validated.submissionId),\n );\n\n const { reservation, settlementFailure } = state;\n const submission = yield* requireSubmission(operation, validated.submissionId);\n\n if (submission.state === \"settled\")\n return yield* replayFinalization(validated, submission, state);\n const now = yield* currentInstant;\n\n yield* sql`\n UPDATE effect_agent_submissions\n SET state = 'settled', settled_outcome = ${reservation.outcome}\n WHERE submission_id = ${validated.submissionId}\n `.pipe(Effect.mapError(sqlFailure(operation)));\n yield* sql`\n UPDATE effect_agent_settlement_reservations\n SET finalized_at = ${now.iso}\n WHERE submission_id = ${validated.submissionId}\n `.pipe(Effect.mapError(sqlFailure(operation)));\n yield* sql`\n DELETE FROM effect_agent_submission_ownership\n WHERE submission_id = ${validated.submissionId}\n `.pipe(Effect.mapError(sqlFailure(operation)));\n\n return yield* decodeSettlement({\n submissionId: validated.submissionId,\n settlementId: validated.settlementId,\n receiptId: submission.receipt_id,\n outcome: reservation.outcome,\n ...(settlementFailure === undefined ? {} : { failure: settlementFailure }),\n settledAt: now.iso,\n }).pipe(Effect.mapError(internalFailure(operation)));\n }),\n );\n\n yield* hitFailpoint(\"ledger:finalize-settlement:after\", operation);\n\n return settlement;\n });\n\n const requestAbort: SubmissionLedger[\"Service\"][\"requestAbort\"] = Effect.fn(\n \"DoSubmissionLedger.requestAbort\",\n )(function* (request: AbortCommand) {\n const operation = \"ledger request abort\";\n\n const validated = yield* Schema.decodeUnknownEffect(Schema.toType(AbortCommand))(request).pipe(\n Effect.mapError(internalFailure(operation)),\n );\n\n yield* hitFailpoint(\"ledger:request-abort:before\", operation);\n\n const intent = yield* inWriteTransaction(\n operation,\n Effect.gen(function* () {\n const submission = yield* requireSubmission(operation, validated.submissionId);\n\n if (submission.state === \"settled\") {\n if (submission.settled_outcome === null) {\n return yield* corruptionFailure(\n operation,\n \"effect_agent_submissions\",\n validated.submissionId,\n \"A settled Submission carries no terminal outcome.\",\n );\n }\n\n return yield* SettlementConflict.make({\n submissionId: validated.submissionId,\n existingOutcome: submission.settled_outcome,\n });\n }\n // A joined Submission settles WITH its host; the abort target is the host (plan\n // §2.5). A joining Submission still records the intent: it is honored only if the\n // host has not consumed the input (revert-then-abort).\n if (submission.state === \"joined\") {\n if (submission.joined_host_submission_id === null) {\n return yield* corruptionFailure(\n operation,\n \"effect_agent_submissions\",\n validated.submissionId,\n \"A joined Submission carries no host linkage.\",\n );\n }\n\n const hostSubmissionId = yield* decodeSubmissionId(\n submission.joined_host_submission_id,\n ).pipe(Effect.mapError(internalFailure(operation)));\n\n return yield* JoinedToHost.make({\n submissionId: validated.submissionId,\n hostSubmissionId,\n });\n }\n const existing = yield* readAbortIntent(operation, validated.submissionId);\n\n if (Option.isSome(existing)) {\n return yield* abortIntentFromRow(\n operation,\n submission,\n validated.submissionId,\n existing.value,\n );\n }\n const now = yield* currentInstant;\n\n yield* sql`\n INSERT INTO effect_agent_abort_intents (\n submission_id,\n author,\n reason,\n requested_at\n ) VALUES (\n ${validated.submissionId},\n ${validated.author},\n ${validated.reason},\n ${now.iso}\n )\n `.pipe(Effect.mapError(sqlFailure(operation)));\n\n const canonicalRecordId = yield* canonicalAbortRecordId(\n operation,\n submission.thread_id,\n validated.submissionId,\n );\n\n return yield* decodeAbortIntent({\n submissionId: validated.submissionId,\n author: validated.author,\n reason: validated.reason,\n requestedAt: now.iso,\n ...(canonicalRecordId === undefined ? {} : { canonicalRecordId }),\n }).pipe(Effect.mapError(internalFailure(operation)));\n }),\n );\n\n yield* hitFailpoint(\"ledger:request-abort:after\", operation);\n\n return intent;\n });\n\n const claimJoining: SubmissionLedger[\"Service\"][\"claimJoining\"] = Effect.fn(\n \"DoSubmissionLedger.claimJoining\",\n )(function* (request: ClaimJoiningRequest) {\n const operation = \"ledger claim joining\";\n\n const validated = yield* Schema.decodeUnknownEffect(Schema.toType(ClaimJoiningRequest))(\n request,\n ).pipe(Effect.mapError(internalFailure(operation)));\n\n yield* hitFailpoint(\"ledger:claim-joining:before\", operation);\n\n const claims = yield* inWriteTransaction(\n operation,\n Effect.gen(function* () {\n const host = yield* requireSubmission(operation, validated.hostSubmissionId);\n\n if (host.thread_id !== validated.threadId) {\n return yield* LedgerError.make({\n operation,\n message: `Host submission ${validated.hostSubmissionId} does not belong to thread ${validated.threadId}.`,\n });\n }\n // The host Attempt already owns the lane; no epoch bump happens here (plan §2.5).\n yield* requireOwnership(operation, host, validated.ownershipToken);\n\n const laterRows = yield* sql<Record<string, unknown>>`\n SELECT ${sql.literal(SUBMISSION_COLUMNS)}\n FROM effect_agent_submissions\n WHERE thread_id = ${validated.threadId}\n AND queue_sequence > ${host.queue_sequence}\n ORDER BY queue_sequence ASC\n `.pipe(Effect.mapError(sqlFailure(operation)));\n\n const later = yield* decodeSubmissionRows(operation, validated.threadId, laterRows);\n const claimed: Array<JoiningClaim> = [];\n\n for (const row of later) {\n if (claimed.length >= validated.maxCount) break;\n // Rows already claimed by THIS host extend its contiguous prefix and are skipped;\n // the coordinator re-delivers already-joined input through the coverage rule.\n if (\n (row.state === \"joining\" || row.state === \"joined\") &&\n row.joined_host_submission_id === validated.hostSubmissionId\n ) {\n continue;\n }\n // P7 §7(c): an aborted-settled row is a CLOSED obligation, not a gap — recovery\n // settles aborted never-claimed queued work immediately, and settlement order of\n // never-run work is not execution order (DUR-004 bounds execution).\n if (row.state === \"settled\" && row.settled_outcome === \"aborted\") continue;\n // Any other non-ready row — an admitted-not-ready gap in particular — breaks the\n // contiguous ready prefix (plan §2.5); later ready work stays queued (DUR-004).\n if (row.state !== \"ready\") break;\n yield* sql`\n UPDATE effect_agent_submissions\n SET state = 'joining', joined_host_submission_id = ${validated.hostSubmissionId}\n WHERE submission_id = ${row.submission_id}\n `.pipe(Effect.mapError(sqlFailure(operation)));\n\n const inputPayload = yield* parseStoredJsonText(row.input_json).pipe(\n Effect.mapError((error) =>\n corruptionFailure(\n operation,\n \"effect_agent_submissions\",\n row.submission_id,\n error.message,\n ),\n ),\n );\n\n claimed.push(\n yield* decodeJoiningClaim({\n submissionId: row.submission_id,\n queueSequence: row.queue_sequence,\n inputPayload,\n }).pipe(Effect.mapError(internalFailure(operation))),\n );\n }\n\n return claimed;\n }),\n );\n\n yield* hitFailpoint(\"ledger:claim-joining:after\", operation);\n\n return claims;\n });\n\n const markJoined: SubmissionLedger[\"Service\"][\"markJoined\"] = Effect.fn(\n \"DoSubmissionLedger.markJoined\",\n )(function* (request: MarkJoinedRequest) {\n const operation = \"ledger mark joined\";\n\n const validated = yield* Schema.decodeUnknownEffect(Schema.toType(MarkJoinedRequest))(\n request,\n ).pipe(Effect.mapError(internalFailure(operation)));\n\n yield* hitFailpoint(\"ledger:mark-joined:before\", operation);\n yield* inWriteTransaction(\n operation,\n Effect.gen(function* () {\n const submission = yield* requireSubmission(operation, validated.submissionId);\n\n if (submission.joined_host_submission_id === null) {\n return yield* LedgerError.make({\n operation,\n message: `Submission ${validated.submissionId} was never claimed for joining.`,\n });\n }\n const host = yield* requireSubmission(operation, submission.joined_host_submission_id);\n\n // The lane is host-owned: the presented token must own the HOST's ownership period,\n // which also lets a later host Attempt repair a lost marker from history (DUR-016).\n yield* requireOwnership(operation, host, validated.ownershipToken);\n if (submission.input_applied_record_id !== null) {\n if (\n submission.input_applied_record_id === validated.recordId &&\n submission.input_applied_sequence === validated.sequence\n ) {\n return;\n }\n\n return yield* corruptionFailure(\n operation,\n \"effect_agent_submissions\",\n validated.submissionId,\n \"A different join marker is already recorded for this Submission.\",\n );\n }\n if (submission.state !== \"joining\" && submission.state !== \"joined\") {\n return yield* LedgerError.make({\n operation,\n message: `Cannot mark submission ${validated.submissionId} joined from state ${submission.state}.`,\n });\n }\n yield* sql`\n UPDATE effect_agent_submissions\n SET\n input_applied_record_id = ${validated.recordId},\n input_applied_sequence = ${validated.sequence},\n state = 'joined'\n WHERE submission_id = ${validated.submissionId}\n `.pipe(Effect.mapError(sqlFailure(operation)));\n }),\n );\n yield* hitFailpoint(\"ledger:mark-joined:after\", operation);\n });\n\n const revertJoining: SubmissionLedger[\"Service\"][\"revertJoining\"] = Effect.fn(\n \"DoSubmissionLedger.revertJoining\",\n )(function* (request: RevertJoiningRequest) {\n const operation = \"ledger revert joining\";\n\n const validated = yield* Schema.decodeUnknownEffect(Schema.toType(RevertJoiningRequest))(\n request,\n ).pipe(Effect.mapError(internalFailure(operation)));\n\n yield* hitFailpoint(\"ledger:revert-joining:before\", operation);\n yield* inWriteTransaction(\n operation,\n Effect.gen(function* () {\n const submission = yield* requireSubmission(operation, validated.submissionId);\n\n // Idempotent and recovery-only: only a still-`joining` Submission reverts; an\n // already-joined (or already-reverted) Submission is a no-op (DUR-016).\n if (submission.state !== \"joining\") return;\n yield* sql`\n UPDATE effect_agent_submissions\n SET state = 'ready', joined_host_submission_id = NULL\n WHERE submission_id = ${validated.submissionId}\n `.pipe(Effect.mapError(sqlFailure(operation)));\n }),\n );\n yield* hitFailpoint(\"ledger:revert-joining:after\", operation);\n });\n\n const suspend: SubmissionLedger[\"Service\"][\"suspend\"] = Effect.fn(\"DoSubmissionLedger.suspend\")(\n function* (request: SuspendRequest) {\n const operation = \"ledger suspend\";\n\n const validated = yield* Schema.decodeUnknownEffect(Schema.toType(SuspendRequest))(\n request,\n ).pipe(Effect.mapError(internalFailure(operation)));\n\n const reasonJson = yield* encodeSuspensionReasonText(validated.reason).pipe(\n Effect.mapError(internalFailure(operation)),\n );\n\n yield* hitFailpoint(\"ledger:suspend:before\", operation);\n\n const outcome = yield* inWriteTransaction(\n operation,\n Effect.gen(function* () {\n const submission = yield* requireSubmission(operation, validated.submissionId);\n\n if (submission.state === \"settled\") {\n if (submission.settled_outcome === null) {\n return yield* corruptionFailure(\n operation,\n \"effect_agent_submissions\",\n validated.submissionId,\n \"A settled Submission carries no terminal outcome.\",\n );\n }\n\n return yield* SettlementConflict.make({\n submissionId: validated.submissionId,\n existingOutcome: submission.settled_outcome,\n });\n }\n // An exact terminal outcome is already reserved (DUR-011); suspension would\n // contradict it, so the reservation wins.\n const reservation = yield* readReservation(operation, validated.submissionId);\n\n if (Option.isSome(reservation)) {\n return yield* SettlementConflict.make({\n submissionId: validated.submissionId,\n existingOutcome: reservation.value.outcome,\n });\n }\n yield* requireOwnership(operation, submission, validated.ownershipToken);\n // A covering event that raced ahead of the suspend transaction resumes the caller\n // immediately WITHOUT releasing the lane (plan §2.6, §12). For WaitingForChild the\n // covering evidence is EITHER a locally settled child row OR a durable cross-store\n // notification marker: parent and child Threads live in different Durable\n // Objects, and the port contract requires that a child settlement reported (via\n // `recordChildSettled` → marker) before this suspend commits is observed here.\n if (validated.reason._tag === \"ApprovalPending\") {\n const decisions = yield* readApprovalDecisions(operation, validated.submissionId);\n const decided = new Set(decisions.map((row) => row.tool_call_id));\n\n if (validated.reason.toolCallIds.every((toolCallId) => decided.has(toolCallId))) {\n return RESUME_IMMEDIATELY;\n }\n } else {\n const markers = yield* readChildSettlementMarkers(operation, validated.submissionId);\n const markerChildren = new Set(markers.map((row) => row.child_submission_id));\n let allSettled = true;\n\n for (const child of validated.reason.children) {\n const settled = yield* childProvablySettled(\n operation,\n markerChildren,\n child.childSubmissionId,\n );\n\n if (!settled) {\n allSettled = false;\n break;\n }\n }\n if (allSettled) {\n return RESUME_IMMEDIATELY;\n }\n }\n const now = yield* currentInstant;\n\n yield* sql`\n UPDATE effect_agent_submissions\n SET\n state = 'suspended',\n suspended_reason_json = ${reasonJson},\n suspended_at = ${now.iso}\n WHERE submission_id = ${validated.submissionId}\n `.pipe(Effect.mapError(sqlFailure(operation)));\n // Suspension ends the ownership period WITHOUT settling: the accepted-work\n // obligation stays owed while the lane consumes no worker permit (plan §2.6).\n yield* sql`\n DELETE FROM effect_agent_submission_ownership\n WHERE submission_id = ${validated.submissionId}\n `.pipe(Effect.mapError(sqlFailure(operation)));\n\n return SUSPENDED;\n }),\n );\n\n yield* hitFailpoint(\"ledger:suspend:after\", operation);\n\n return outcome;\n },\n );\n\n /**\n * Once every pending call of a recorded ApprovalPending suspension has a decision intent,\n * the lane wakes: suspended → input-applied, suspension cleared (plan §2.6). A\n * WaitingForChild suspension wakes only through recordChildSettled. Runs inside the caller's\n * write transaction.\n */\n const wakeSuspendedIfCovered = Effect.fn(\"DoSubmissionLedger.wakeSuspendedIfCovered\")(function* (\n operation: string,\n submission: SubmissionRow,\n ): Effect.fn.Return<void, LedgerError> {\n if (submission.state !== \"suspended\" || submission.suspended_reason_json === null) return;\n\n const reason = yield* Schema.decodeEffect(Schema.fromJsonString(SuspensionReason))(\n submission.suspended_reason_json,\n ).pipe(\n Effect.mapError((error) =>\n corruptionFailure(\n operation,\n \"effect_agent_submissions\",\n submission.submission_id,\n error.message,\n ),\n ),\n );\n\n if (reason._tag !== \"ApprovalPending\") return;\n const decisions = yield* readApprovalDecisions(operation, submission.submission_id);\n const decided = new Set(decisions.map((row) => row.tool_call_id));\n\n if (!reason.toolCallIds.every((toolCallId) => decided.has(toolCallId))) return;\n yield* sql`\n UPDATE effect_agent_submissions\n SET\n state = 'input-applied',\n suspended_reason_json = NULL,\n suspended_at = NULL\n WHERE submission_id = ${submission.submission_id}\n `.pipe(Effect.mapError(sqlFailure(operation)));\n });\n\n const recordApprovalDecision: SubmissionLedger[\"Service\"][\"recordApprovalDecision\"] = Effect.fn(\n \"DoSubmissionLedger.recordApprovalDecision\",\n )(function* (command: ApprovalDecisionCommand) {\n const operation = \"ledger record approval decision\";\n\n const validated = yield* Schema.decodeUnknownEffect(Schema.toType(ApprovalDecisionCommand))(\n command,\n ).pipe(Effect.mapError(internalFailure(operation)));\n\n yield* hitFailpoint(\"ledger:approval-decision:before\", operation);\n\n const intent = yield* inWriteTransaction(\n operation,\n Effect.gen(function* () {\n const submission = yield* requireSubmission(operation, validated.submissionId);\n\n if (submission.state === \"settled\") {\n if (submission.settled_outcome === null) {\n return yield* corruptionFailure(\n operation,\n \"effect_agent_submissions\",\n validated.submissionId,\n \"A settled Submission carries no terminal outcome.\",\n );\n }\n\n return yield* SettlementConflict.make({\n submissionId: validated.submissionId,\n existingOutcome: submission.settled_outcome,\n });\n }\n const decisions = yield* readApprovalDecisions(operation, validated.submissionId);\n const existing = decisions.find((row) => row.tool_call_id === validated.toolCallId);\n\n if (existing !== undefined) {\n // Idempotent per (submissionId, toolCallId): repeating the SAME decision replays\n // the recorded intent unchanged; a divergent re-decision conflicts.\n if (existing.decision !== validated.decision) {\n return yield* ApprovalConflict.make({\n submissionId: validated.submissionId,\n toolCallId: validated.toolCallId,\n existingDecision: existing.decision,\n });\n }\n\n return yield* approvalIntentFromRow(operation, existing);\n }\n const now = yield* currentInstant;\n\n yield* sql`\n INSERT INTO effect_agent_approval_decisions (\n submission_id,\n tool_call_id,\n decision,\n resolver,\n reason,\n decided_at\n ) VALUES (\n ${validated.submissionId},\n ${validated.toolCallId},\n ${validated.decision},\n ${validated.resolver},\n ${validated.reason},\n ${now.iso}\n )\n `.pipe(Effect.mapError(sqlFailure(operation)));\n yield* wakeSuspendedIfCovered(operation, submission);\n\n return yield* decodeApprovalDecisionIntent({\n submissionId: validated.submissionId,\n toolCallId: validated.toolCallId,\n decision: validated.decision,\n resolver: validated.resolver,\n reason: validated.reason,\n decidedAt: now.iso,\n }).pipe(Effect.mapError(internalFailure(operation)));\n }),\n );\n\n yield* hitFailpoint(\"ledger:approval-decision:after\", operation);\n\n return intent;\n });\n\n const markUnknown: SubmissionLedger[\"Service\"][\"markUnknown\"] = Effect.fn(\n \"DoSubmissionLedger.markUnknown\",\n )(function* (request: MarkUnknownRequest) {\n const operation = \"ledger mark unknown\";\n\n const validated = yield* Schema.decodeUnknownEffect(Schema.toType(MarkUnknownRequest))(\n request,\n ).pipe(Effect.mapError(internalFailure(operation)));\n\n yield* hitFailpoint(\"ledger:mark-unknown:before\", operation);\n yield* inWriteTransaction(\n operation,\n Effect.gen(function* () {\n const submission = yield* requireSubmission(operation, validated.submissionId);\n\n if (submission.state === \"settled\") {\n if (submission.settled_outcome === null) {\n return yield* corruptionFailure(\n operation,\n \"effect_agent_submissions\",\n validated.submissionId,\n \"A settled Submission carries no terminal outcome.\",\n );\n }\n\n return yield* SettlementConflict.make({\n submissionId: validated.submissionId,\n existingOutcome: submission.settled_outcome,\n });\n }\n // A reserved exact outcome wins over a late Unknown marking (DUR-011); the recovery\n // classifier orders reservation ahead of MarkUnknown for the same reason.\n const reservation = yield* readReservation(operation, validated.submissionId);\n\n if (Option.isSome(reservation)) {\n return yield* SettlementConflict.make({\n submissionId: validated.submissionId,\n existingOutcome: reservation.value.outcome,\n });\n }\n // Idempotent merge: repeating is a no-op; additional open calls extend the marked\n // set while the first recorded reason is kept.\n const existingIds = yield* storedUnknownToolCallIds(operation, submission);\n const known = new Set(existingIds);\n\n const merged = [\n ...existingIds,\n ...validated.toolCallIds.filter((toolCallId) => !known.has(toolCallId)),\n ];\n\n const idsJson = yield* encodeToolCallIdsText(merged).pipe(\n Effect.mapError(internalFailure(operation)),\n );\n\n yield* sql`\n UPDATE effect_agent_submissions\n SET\n state = 'unknown',\n unknown_reason = ${submission.unknown_reason ?? validated.reason},\n unknown_tool_call_ids_json = ${idsJson}\n WHERE submission_id = ${validated.submissionId}\n `.pipe(Effect.mapError(sqlFailure(operation)));\n }),\n );\n yield* hitFailpoint(\"ledger:mark-unknown:after\", operation);\n });\n\n const recordUnknownResolution: SubmissionLedger[\"Service\"][\"recordUnknownResolution\"] = Effect.fn(\n \"DoSubmissionLedger.recordUnknownResolution\",\n )(function* (command: UnknownResolutionCommand) {\n const operation = \"ledger record unknown resolution\";\n\n const validated = yield* Schema.decodeUnknownEffect(Schema.toType(UnknownResolutionCommand))(\n command,\n ).pipe(Effect.mapError(internalFailure(operation)));\n\n const resolutionJson = yield* encodeUnknownResolutionText(validated.resolution).pipe(\n Effect.mapError(internalFailure(operation)),\n );\n\n yield* hitFailpoint(\"ledger:unknown-resolution:before\", operation);\n\n const intent = yield* inWriteTransaction(\n operation,\n Effect.gen(function* () {\n const submission = yield* requireSubmission(operation, validated.submissionId);\n\n if (submission.state === \"settled\") {\n if (submission.settled_outcome === null) {\n return yield* corruptionFailure(\n operation,\n \"effect_agent_submissions\",\n validated.submissionId,\n \"A settled Submission carries no terminal outcome.\",\n );\n }\n\n return yield* SettlementConflict.make({\n submissionId: validated.submissionId,\n existingOutcome: submission.settled_outcome,\n });\n }\n const resolutions = yield* readUnknownResolutions(operation, validated.submissionId);\n const existing = resolutions.find((row) => row.tool_call_id === validated.toolCallId);\n\n const existingIntent =\n existing === undefined\n ? undefined\n : yield* unknownResolutionIntentFromRow(operation, existing);\n\n if (\n existingIntent !== undefined &&\n !equivalentUnknownResolution(existingIntent.resolution, validated.resolution)\n ) {\n return yield* UnknownResolutionConflict.make({\n submissionId: validated.submissionId,\n toolCallId: validated.toolCallId,\n });\n }\n let resolved: UnknownResolutionIntent;\n\n if (existingIntent !== undefined) {\n // Idempotent replay of the recorded intent (author/reason may differ; the stored\n // audit fields win, exactly like requestAbort).\n resolved = existingIntent;\n } else {\n const now = yield* currentInstant;\n\n yield* sql`\n INSERT INTO effect_agent_unknown_resolutions (\n submission_id,\n tool_call_id,\n author,\n reason,\n resolution_json,\n resolved_at\n ) VALUES (\n ${validated.submissionId},\n ${validated.toolCallId},\n ${validated.author},\n ${validated.reason},\n ${resolutionJson},\n ${now.iso}\n )\n `.pipe(Effect.mapError(sqlFailure(operation)));\n\n const resolution = yield* parseStoredJsonText(resolutionJson).pipe(\n Effect.mapError(internalFailure(operation)),\n );\n\n resolved = yield* decodeUnknownResolutionIntent({\n submissionId: validated.submissionId,\n toolCallId: validated.toolCallId,\n author: validated.author,\n reason: validated.reason,\n resolution,\n resolvedAt: now.iso,\n }).pipe(Effect.mapError(internalFailure(operation)));\n }\n // The lane reopens only when EVERY marked open call has a durable resolution intent:\n // unknown → input-applied (DUR-017). Replays re-run the coverage check so a\n // recovering caller can wake the lane idempotently.\n if (submission.state === \"unknown\" && submission.unknown_tool_call_ids_json !== null) {\n const markedIds = yield* storedUnknownToolCallIds(operation, submission);\n const covering = yield* readUnknownResolutions(operation, validated.submissionId);\n const coveredIds = new Set(covering.map((row) => row.tool_call_id));\n\n if (markedIds.every((toolCallId) => coveredIds.has(toolCallId))) {\n yield* sql`\n UPDATE effect_agent_submissions\n SET\n state = 'input-applied',\n unknown_reason = NULL,\n unknown_tool_call_ids_json = NULL\n WHERE submission_id = ${validated.submissionId}\n `.pipe(Effect.mapError(sqlFailure(operation)));\n }\n }\n\n return resolved;\n }),\n );\n\n yield* hitFailpoint(\"ledger:unknown-resolution:after\", operation);\n\n return intent;\n });\n\n const recordChildSettled: SubmissionLedger[\"Service\"][\"recordChildSettled\"] = Effect.fn(\n \"DoSubmissionLedger.recordChildSettled\",\n )(function* (request: ChildSettledNotification) {\n const operation = \"ledger record child settled\";\n\n const validated = yield* Schema.decodeUnknownEffect(Schema.toType(ChildSettledNotification))(\n request,\n ).pipe(Effect.mapError(internalFailure(operation)));\n\n yield* hitFailpoint(\"ledger:child-settled:before\", operation);\n\n const outcome = yield* inWriteTransaction(\n operation,\n Effect.gen(function* () {\n const parent = yield* requireSubmission(operation, validated.parentSubmissionId);\n // The child's canonical Settlement is the authority for this wake. When the child's\n // row lives in THIS store (single-store latitude, and every conformance lane), either a\n // finalized row or an exact terminalizing reservation admits the notification: the\n // runtime calls only after the canonical append and before ledger finalization. When the\n // row does not live here — the normal cross-DO case — the routed notification from the\n // child's owning Durable Object is the settlement evidence this store records durably.\n const child = yield* readSubmission(operation, validated.childSubmissionId);\n const childReservation = yield* readReservation(operation, validated.childSubmissionId);\n\n if (\n Option.isSome(child) &&\n child.value.state !== \"settled\" &&\n !(child.value.state === \"terminalizing\" && Option.isSome(childReservation))\n ) {\n return yield* LedgerError.make({\n operation,\n message: `Child submission ${validated.childSubmissionId} has no recorded settlement.`,\n });\n }\n // Record the durable notification marker FIRST and unconditionally (idempotent):\n // the port's cross-store race guarantee requires that a notification committed\n // before the parent's suspend transaction is observed by that suspend's covering\n // check, even when the parent is not (or not yet) suspended.\n const now = yield* currentInstant;\n\n yield* sql`\n INSERT INTO effect_agent_child_settlements (\n parent_submission_id,\n child_submission_id,\n child_outcome,\n recorded_at\n ) VALUES (\n ${validated.parentSubmissionId},\n ${validated.childSubmissionId},\n ${\n Option.isSome(child) && child.value.state === \"settled\"\n ? child.value.settled_outcome\n : Option.isSome(childReservation)\n ? childReservation.value.outcome\n : null\n },\n ${now.iso}\n )\n ON CONFLICT (parent_submission_id, child_submission_id) DO NOTHING\n `.pipe(Effect.mapError(sqlFailure(operation)));\n\n if (parent.state !== \"suspended\" || parent.suspended_reason_json === null) {\n return NOT_WAITING;\n }\n\n const reason = yield* Schema.decodeEffect(Schema.fromJsonString(SuspensionReason))(\n parent.suspended_reason_json,\n ).pipe(\n Effect.mapError((error) =>\n corruptionFailure(\n operation,\n \"effect_agent_submissions\",\n parent.submission_id,\n error.message,\n ),\n ),\n );\n\n if (reason._tag !== \"WaitingForChild\") {\n return NOT_WAITING;\n }\n if (\n !reason.children.some((entry) => entry.childSubmissionId === validated.childSubmissionId)\n ) {\n return NOT_WAITING;\n }\n // The parent wakes exactly when EVERY listed child is provably settled — from its\n // local row or a recorded marker (spec §12 step 10); replays re-run the coverage\n // check so a recovering caller wakes the lane idempotently.\n const markers = yield* readChildSettlementMarkers(operation, validated.parentSubmissionId);\n const markerChildren = new Set(markers.map((row) => row.child_submission_id));\n\n for (const entry of reason.children) {\n const settled = yield* childProvablySettled(\n operation,\n markerChildren,\n entry.childSubmissionId,\n );\n\n if (!settled) {\n return STILL_WAITING;\n }\n }\n yield* sql`\n UPDATE effect_agent_submissions\n SET\n state = 'input-applied',\n suspended_reason_json = NULL,\n suspended_at = NULL\n WHERE submission_id = ${validated.parentSubmissionId}\n `.pipe(Effect.mapError(sqlFailure(operation)));\n\n return WOKEN;\n }),\n );\n\n yield* hitFailpoint(\"ledger:child-settled:after\", operation);\n\n return outcome;\n });\n\n const reserveChildBudget: SubmissionLedger[\"Service\"][\"reserveChildBudget\"] = Effect.fn(\n \"DoSubmissionLedger.reserveChildBudget\",\n )(function* (request: ChildBudgetReservationRequest) {\n const operation = \"ledger reserve child budget\";\n\n const validated = yield* Schema.decodeUnknownEffect(\n Schema.toType(ChildBudgetReservationRequest),\n )(request).pipe(Effect.mapError(internalFailure(operation)));\n\n const allocationJson = yield* encodePersistedJsonText(validated.allocation).pipe(\n Effect.mapError(internalFailure(operation)),\n );\n\n yield* hitFailpoint(\"ledger:child-reservation:before\", operation);\n\n const reserved = yield* inWriteTransaction(\n operation,\n Effect.gen(function* () {\n const existing = yield* readChildReservation(operation, validated.reservationId);\n\n if (Option.isSome(existing)) {\n const existingSnapshot = yield* childReservationSnapshotFromRow(\n operation,\n existing.value,\n );\n\n // Identical replays short-circuit before the fence, mirroring reserveSettlement: a\n // replay creates nothing, so a recovering caller resumes rather than duplicates.\n const identical =\n existing.value.parent_submission_id === validated.parentSubmissionId &&\n existing.value.parent_tool_call_id === validated.parentToolCallId &&\n existing.value.allocation_digest === validated.allocationDigest &&\n equivalentPersistedJson(existingSnapshot.allocation, validated.allocation);\n\n if (!identical) {\n return yield* ChildReservationConflict.make({\n reservationId: validated.reservationId,\n status: existing.value.status,\n message:\n \"A reservation with this identity exists with a different parent Tool Call or allocation.\",\n });\n }\n\n return ReservedChildBudget.make({\n reservation: existingSnapshot,\n replayed: true,\n });\n }\n\n const collision = yield* readChildReservationForCall(\n operation,\n validated.parentSubmissionId,\n validated.parentToolCallId,\n );\n\n if (Option.isSome(collision)) {\n return yield* ChildReservationConflict.make({\n reservationId: validated.reservationId,\n status: collision.value.status,\n message: `Parent Tool Call ${validated.parentToolCallId} already owns reservation ${collision.value.reservation_id}.`,\n });\n }\n const parent = yield* requireSubmission(operation, validated.parentSubmissionId);\n\n // Creation is fenced by the parent lane's live ownership (spec §12 step 2): a stale\n // parent Attempt can never create new reservation state.\n yield* requireOwnership(operation, parent, validated.ownershipToken);\n const now = yield* currentInstant;\n\n yield* sql`\n INSERT INTO effect_agent_child_reservations (\n reservation_id,\n parent_submission_id,\n parent_tool_call_id,\n status,\n allocation_json,\n allocation_digest,\n reserved_at\n ) VALUES (\n ${validated.reservationId},\n ${validated.parentSubmissionId},\n ${validated.parentToolCallId},\n 'reserved',\n ${allocationJson},\n ${validated.allocationDigest},\n ${now.iso}\n )\n `.pipe(Effect.mapError(sqlFailure(operation)));\n const inserted = yield* readChildReservation(operation, validated.reservationId);\n\n if (Option.isNone(inserted)) {\n return yield* corruptionFailure(\n operation,\n \"effect_agent_child_reservations\",\n validated.reservationId,\n \"An inserted child reservation row is missing inside its own transaction.\",\n );\n }\n\n return ReservedChildBudget.make({\n reservation: yield* childReservationSnapshotFromRow(operation, inserted.value),\n replayed: false,\n });\n }),\n );\n\n yield* hitFailpoint(\"ledger:child-reservation:after\", operation);\n\n return reserved;\n });\n\n const attachChildToReservation: SubmissionLedger[\"Service\"][\"attachChildToReservation\"] =\n Effect.fn(\"DoSubmissionLedger.attachChildToReservation\")(function* (\n request: AttachChildToReservationRequest,\n ) {\n const operation = \"ledger attach child to reservation\";\n\n const validated = yield* Schema.decodeUnknownEffect(\n Schema.toType(AttachChildToReservationRequest),\n )(request).pipe(Effect.mapError(internalFailure(operation)));\n\n yield* hitFailpoint(\"ledger:child-attach:before\", operation);\n\n const attached = yield* inWriteTransaction(\n operation,\n Effect.gen(function* () {\n const existing = yield* readChildReservation(operation, validated.reservationId);\n\n if (Option.isNone(existing)) {\n return yield* LedgerError.make({\n operation,\n message: `Unknown child reservation ${validated.reservationId}.`,\n });\n }\n if (existing.value.child_submission_id !== null) {\n // Idempotent replay of the recorded attachment (unfenced — it mutates nothing).\n if (existing.value.child_submission_id === validated.childSubmissionId) {\n return yield* childReservationSnapshotFromRow(operation, existing.value);\n }\n\n return yield* ChildReservationConflict.make({\n reservationId: validated.reservationId,\n status: existing.value.status,\n message: `Reservation ${validated.reservationId} already records child ${existing.value.child_submission_id}.`,\n });\n }\n const parent = yield* requireSubmission(operation, existing.value.parent_submission_id);\n\n yield* requireOwnership(operation, parent, validated.ownershipToken);\n if (existing.value.status !== \"reserved\") {\n return yield* ChildReservationConflict.make({\n reservationId: validated.reservationId,\n status: existing.value.status,\n message: `Cannot attach a child to a ${existing.value.status} reservation.`,\n });\n }\n // Unlike the single-store Node adapter, the admitted child's row lives in ANOTHER\n // Durable Object, so no local existence check is possible here. The canonical\n // `SubagentStarted` record remains the attachment's repair authority (DUR-015),\n // and the coordinator only attaches after the child's admission committed.\n yield* sql`\n UPDATE effect_agent_child_reservations\n SET child_submission_id = ${validated.childSubmissionId}\n WHERE reservation_id = ${validated.reservationId}\n `.pipe(Effect.mapError(sqlFailure(operation)));\n const updated = yield* readChildReservation(operation, validated.reservationId);\n\n if (Option.isNone(updated)) {\n return yield* corruptionFailure(\n operation,\n \"effect_agent_child_reservations\",\n validated.reservationId,\n \"An updated child reservation row is missing inside its own transaction.\",\n );\n }\n\n return yield* childReservationSnapshotFromRow(operation, updated.value);\n }),\n );\n\n yield* hitFailpoint(\"ledger:child-attach:after\", operation);\n\n return attached;\n });\n\n const beginChildBudgetRelease: SubmissionLedger[\"Service\"][\"beginChildBudgetRelease\"] = Effect.fn(\n \"DoSubmissionLedger.beginChildBudgetRelease\",\n )(function* (request: BeginChildBudgetReleaseRequest) {\n const operation = \"ledger begin child budget release\";\n\n const validated = yield* Schema.decodeUnknownEffect(\n Schema.toType(BeginChildBudgetReleaseRequest),\n )(request).pipe(Effect.mapError(internalFailure(operation)));\n\n const accountingJson = yield* encodePersistedJsonText(validated.accounting).pipe(\n Effect.mapError(internalFailure(operation)),\n );\n\n yield* hitFailpoint(\"ledger:child-release-pending:before\", operation);\n\n const frozen = yield* inWriteTransaction(\n operation,\n Effect.gen(function* () {\n const existing = yield* readChildReservation(operation, validated.reservationId);\n\n if (Option.isNone(existing)) {\n return yield* LedgerError.make({\n operation,\n message: `Unknown child reservation ${validated.reservationId}.`,\n });\n }\n if (existing.value.status !== \"reserved\") {\n const existingSnapshot = yield* childReservationSnapshotFromRow(\n operation,\n existing.value,\n );\n\n // The accounting decision was already frozen exactly once; an identical replay is a\n // no-op and a divergent decision conflicts (spec §12 join step 6).\n if (\n existingSnapshot.accounting !== undefined &&\n equivalentPersistedJson(existingSnapshot.accounting, validated.accounting)\n ) {\n return existingSnapshot;\n }\n\n return yield* ChildReservationConflict.make({\n reservationId: validated.reservationId,\n status: existing.value.status,\n message: \"A different accounting decision is already frozen for this reservation.\",\n });\n }\n const now = yield* currentInstant;\n\n yield* sql`\n UPDATE effect_agent_child_reservations\n SET\n status = 'releasePending',\n accounting_json = ${accountingJson},\n release_began_at = ${now.iso}\n WHERE reservation_id = ${validated.reservationId}\n `.pipe(Effect.mapError(sqlFailure(operation)));\n const updated = yield* readChildReservation(operation, validated.reservationId);\n\n if (Option.isNone(updated)) {\n return yield* corruptionFailure(\n operation,\n \"effect_agent_child_reservations\",\n validated.reservationId,\n \"An updated child reservation row is missing inside its own transaction.\",\n );\n }\n\n return yield* childReservationSnapshotFromRow(operation, updated.value);\n }),\n );\n\n yield* hitFailpoint(\"ledger:child-release-pending:after\", operation);\n\n return frozen;\n });\n\n const releaseChildBudget: SubmissionLedger[\"Service\"][\"releaseChildBudget\"] = Effect.fn(\n \"DoSubmissionLedger.releaseChildBudget\",\n )(function* (request: ReleaseChildBudgetRequest) {\n const operation = \"ledger release child budget\";\n\n const validated = yield* Schema.decodeUnknownEffect(Schema.toType(ReleaseChildBudgetRequest))(\n request,\n ).pipe(Effect.mapError(internalFailure(operation)));\n\n yield* hitFailpoint(\"ledger:child-release:before\", operation);\n\n const released = yield* inWriteTransaction(\n operation,\n Effect.gen(function* () {\n const existing = yield* readChildReservation(operation, validated.reservationId);\n\n if (Option.isNone(existing)) {\n return yield* LedgerError.make({\n operation,\n message: `Unknown child reservation ${validated.reservationId}.`,\n });\n }\n // Applied exactly once: replaying a released reservation returns the stored row\n // unchanged (spec §12: \"never available twice\").\n if (existing.value.status === \"released\") {\n return yield* childReservationSnapshotFromRow(operation, existing.value);\n }\n if (existing.value.status !== \"releasePending\") {\n return yield* ChildReservationConflict.make({\n reservationId: validated.reservationId,\n status: existing.value.status,\n message: \"Cannot release a reservation whose accounting decision is not frozen.\",\n });\n }\n const now = yield* currentInstant;\n\n yield* sql`\n UPDATE effect_agent_child_reservations\n SET status = 'released', released_at = ${now.iso}\n WHERE reservation_id = ${validated.reservationId}\n `.pipe(Effect.mapError(sqlFailure(operation)));\n const updated = yield* readChildReservation(operation, validated.reservationId);\n\n if (Option.isNone(updated)) {\n return yield* corruptionFailure(\n operation,\n \"effect_agent_child_reservations\",\n validated.reservationId,\n \"An updated child reservation row is missing inside its own transaction.\",\n );\n }\n\n return yield* childReservationSnapshotFromRow(operation, updated.value);\n }),\n );\n\n yield* hitFailpoint(\"ledger:child-release:after\", operation);\n\n return released;\n });\n\n interface ScanCursor {\n readonly threadId: string;\n readonly queueSequence: number;\n }\n\n const scanPage = Effect.fn(\"DoSubmissionLedger.scanPage\")(function* (\n cursor: ScanCursor | undefined,\n ): Effect.fn.Return<\n readonly [ReadonlyArray<SubmissionSnapshot>, Option.Option<ScanCursor | undefined>],\n LedgerError\n > {\n const operation = \"ledger scan nonterminal\";\n\n const rows = yield* (\n cursor === undefined\n ? sql<Record<string, unknown>>`\n SELECT ${sql.literal(SUBMISSION_COLUMNS)}\n FROM effect_agent_submissions\n WHERE state <> 'settled'\n ORDER BY thread_id ASC, queue_sequence ASC\n LIMIT ${SCAN_PAGE_SIZE}\n `\n : sql<Record<string, unknown>>`\n SELECT ${sql.literal(SUBMISSION_COLUMNS)}\n FROM effect_agent_submissions\n WHERE state <> 'settled'\n AND (thread_id, queue_sequence) > (${cursor.threadId}, ${cursor.queueSequence})\n ORDER BY thread_id ASC, queue_sequence ASC\n LIMIT ${SCAN_PAGE_SIZE}\n `\n ).pipe(Effect.mapError(sqlFailure(operation)));\n\n const decoded = yield* decodeSubmissionRows(operation, \"nonterminal_scan\", rows);\n\n const snapshots = yield* Effect.forEach(decoded, (row) =>\n decodeSubmissionSnapshot(operation, row),\n );\n\n const last = decoded[decoded.length - 1];\n\n const next: Option.Option<ScanCursor | undefined> =\n last === undefined || decoded.length < SCAN_PAGE_SIZE\n ? Option.none()\n : Option.some({\n threadId: last.thread_id,\n queueSequence: last.queue_sequence,\n });\n\n return [snapshots, next] as const;\n });\n\n const scanNonterminal: Stream.Stream<SubmissionSnapshot, LedgerError> = Stream.paginate<\n ScanCursor | undefined,\n SubmissionSnapshot,\n LedgerError\n >(undefined, scanPage);\n\n const readAbortIntentForSubmission: SubmissionLedger[\"Service\"][\"readAbortIntent\"] = Effect.fn(\n \"DoSubmissionLedger.readAbortIntentForSubmission\",\n )(function* (request) {\n const operation = \"ledger read abort intent\";\n\n const validated = yield* Schema.decodeUnknownEffect(Schema.toType(AbortIntentRequest))(\n request,\n ).pipe(Effect.mapError(internalFailure(operation)));\n\n const recordId = submissionAbortRecordId(validated.submissionId);\n\n const rows = yield* sql<Record<string, unknown>>`\n SELECT\n submission.submission_id,\n abort.submission_id AS abort_submission_id,\n abort.author,\n abort.reason,\n abort.requested_at,\n canonical.record_id AS canonical_record_id\n FROM effect_agent_submissions AS submission\n LEFT JOIN effect_agent_abort_intents AS abort\n ON abort.submission_id = submission.submission_id\n LEFT JOIN effect_agent_canonical_records AS canonical\n ON canonical.thread_id = submission.thread_id\n AND canonical.record_id = ${recordId}\n WHERE submission.submission_id = ${validated.submissionId}\n `.pipe(Effect.mapError(sqlFailure(operation)));\n\n const decoded = yield* decodeRows(\n Schema.Array(AbortIntentLookupRow),\n \"effect_agent_abort_intents\",\n validated.submissionId,\n rows,\n ).pipe(Effect.mapError(internalFailure(operation)));\n\n if (decoded.length === 0) {\n return yield* LedgerError.make({\n operation,\n message: `Unknown submission ${validated.submissionId}.`,\n });\n }\n if (decoded.length !== 1) {\n return yield* corruptionFailure(\n operation,\n \"effect_agent_abort_intents\",\n validated.submissionId,\n \"An abort intent lookup returned more than one row.\",\n );\n }\n const row = decoded[0];\n\n if (row.abort_submission_id === null) return undefined;\n\n return yield* decodeAbortIntent({\n submissionId: row.abort_submission_id,\n author: row.author,\n reason: row.reason,\n requestedAt: row.requested_at,\n ...(row.canonical_record_id === null ? {} : { canonicalRecordId: row.canonical_record_id }),\n }).pipe(\n Effect.mapError((error) =>\n corruptionFailure(\n operation,\n \"effect_agent_abort_intents\",\n validated.submissionId,\n error.message,\n ),\n ),\n );\n });\n\n const loadRecoverySnapshot: SubmissionLedger[\"Service\"][\"loadRecoverySnapshot\"] = Effect.fn(\n \"DoSubmissionLedger.loadRecoverySnapshot\",\n )(function* (request: RecoverySnapshotRequest) {\n const operation = \"ledger load recovery snapshot\";\n\n const validated = yield* Schema.decodeUnknownEffect(Schema.toType(RecoverySnapshotRequest))(\n request,\n ).pipe(Effect.mapError(internalFailure(operation)));\n\n return yield* sql\n .withTransaction(\n Effect.gen(function* () {\n const submissionRow = yield* requireSubmission(operation, validated.submissionId);\n const submission = yield* decodeSubmissionSnapshot(operation, submissionRow);\n\n let ownership: OwnershipSnapshot | undefined;\n const ownershipRow = yield* readOwnership(operation, validated.submissionId);\n\n if (Option.isSome(ownershipRow)) {\n ownership = yield* decodeOwnershipSnapshot({\n attemptId: ownershipRow.value.attempt_id,\n ownerProducerId: ownershipRow.value.owner_producer_id,\n producerEpoch: ownershipRow.value.producer_epoch,\n leaseExpiresAt: ownershipRow.value.lease_expires_at,\n }).pipe(Effect.mapError(internalFailure(operation)));\n }\n\n let inputApplied: InputAppliedMarker | undefined;\n\n if (\n submissionRow.input_applied_record_id !== null &&\n submissionRow.input_applied_sequence !== null\n ) {\n inputApplied = yield* decodeInputAppliedMarker({\n recordId: submissionRow.input_applied_record_id,\n sequence: submissionRow.input_applied_sequence,\n }).pipe(Effect.mapError(internalFailure(operation)));\n }\n\n let reservation: SettlementReservationSnapshot | undefined;\n const reservationRow = yield* readReservation(operation, validated.submissionId);\n\n if (Option.isSome(reservationRow)) {\n const record = yield* decodeRecordEnvelopeText(reservationRow.value.record_json).pipe(\n Effect.mapError((error) =>\n corruptionFailure(\n operation,\n \"effect_agent_settlement_reservations\",\n validated.submissionId,\n error.message,\n ),\n ),\n );\n\n const settlementId = yield* Schema.decodeUnknownEffect(\n SettlementReservationSnapshot.fields.settlementId,\n )(reservationRow.value.settlement_id).pipe(Effect.mapError(internalFailure(operation)));\n\n reservation = SettlementReservationSnapshot.make({\n settlementId,\n outcome: reservationRow.value.outcome,\n record,\n recordDigest: reservationRow.value.record_digest,\n finalized: reservationRow.value.finalized_at !== null,\n });\n }\n\n let abortIntent: AbortIntent | undefined;\n const abortRow = yield* readAbortIntent(operation, validated.submissionId);\n\n if (Option.isSome(abortRow)) {\n abortIntent = yield* abortIntentFromRow(\n operation,\n submissionRow,\n validated.submissionId,\n abortRow.value,\n );\n }\n\n // Host-side view: every Submission whose host linkage points here, in queue order\n // (the terminalize loop settles them with the host outcome, DUR-002).\n const joinRows = yield* sql<Record<string, unknown>>`\n SELECT ${sql.literal(SUBMISSION_COLUMNS)}\n FROM effect_agent_submissions\n WHERE joined_host_submission_id = ${validated.submissionId}\n ORDER BY queue_sequence ASC\n `.pipe(Effect.mapError(sqlFailure(operation)));\n\n const joinSubmissions = yield* decodeSubmissionRows(\n operation,\n validated.submissionId,\n joinRows,\n );\n\n const joins = yield* Effect.forEach(joinSubmissions, (row) =>\n decodeJoinSnapshot({\n submissionId: row.submission_id,\n state: row.state,\n hostSubmissionId: validated.submissionId,\n }).pipe(Effect.mapError(internalFailure(operation))),\n );\n\n let hostSubmissionId: RecoverySnapshot[\"hostSubmissionId\"];\n\n if (submissionRow.joined_host_submission_id !== null) {\n hostSubmissionId = yield* decodeSubmissionId(\n submissionRow.joined_host_submission_id,\n ).pipe(Effect.mapError(internalFailure(operation)));\n }\n\n let suspension: SuspensionSnapshot | undefined;\n\n if (submissionRow.suspended_reason_json !== null && submissionRow.suspended_at !== null) {\n const reason = yield* parseStoredJsonText(submissionRow.suspended_reason_json).pipe(\n Effect.mapError((error) =>\n corruptionFailure(\n operation,\n \"effect_agent_submissions\",\n validated.submissionId,\n error.message,\n ),\n ),\n );\n\n suspension = yield* decodeSuspensionSnapshot({\n reason,\n suspendedAt: submissionRow.suspended_at,\n }).pipe(\n Effect.mapError((error) =>\n corruptionFailure(\n operation,\n \"effect_agent_submissions\",\n validated.submissionId,\n error.message,\n ),\n ),\n );\n }\n\n const decisionRows = yield* readApprovalDecisions(operation, validated.submissionId);\n\n const approvalDecisions = yield* Effect.forEach(decisionRows, (row) =>\n approvalIntentFromRow(operation, row),\n );\n\n const resolutionRows = yield* readUnknownResolutions(operation, validated.submissionId);\n\n const unknownResolutions = yield* Effect.forEach(resolutionRows, (row) =>\n unknownResolutionIntentFromRow(operation, row),\n );\n\n // Parent-side subagent view: this Submission's child budget reservations in parent\n // Tool Call order, plus each attached child's current lane state (a disposable\n // derived view; canonical records stay the recovery truth, DUR-015). The child's\n // state comes from its local row when this store holds it, and otherwise from the\n // durable cross-store settlement marker; a child that is neither local nor marked\n // settled is enriched by the routed per-child lookup one layer out (plan §1.3).\n const childReservationRows = yield* sql<Record<string, unknown>>`\n SELECT ${sql.literal(CHILD_RESERVATION_COLUMNS)}\n FROM effect_agent_child_reservations\n WHERE parent_submission_id = ${validated.submissionId}\n ORDER BY parent_tool_call_id ASC\n `.pipe(Effect.mapError(sqlFailure(operation)));\n\n const decodedChildReservations = yield* decodeChildReservationRows(\n operation,\n validated.submissionId,\n childReservationRows,\n );\n\n const childReservations = yield* Effect.forEach(decodedChildReservations, (row) =>\n childReservationSnapshotFromRow(operation, row),\n );\n\n const markers = yield* readChildSettlementMarkers(operation, validated.submissionId);\n const markersByChild = new Map(markers.map((row) => [row.child_submission_id, row]));\n const childAttachments: Array<ChildAttachmentSnapshot> = [];\n\n for (const row of decodedChildReservations) {\n if (row.child_submission_id === null) continue;\n const child = yield* readSubmission(operation, row.child_submission_id);\n\n if (Option.isSome(child)) {\n childAttachments.push(\n yield* decodeChildAttachmentSnapshot({\n toolCallId: row.parent_tool_call_id,\n childSubmissionId: row.child_submission_id,\n childState: child.value.state,\n ...(child.value.settled_outcome === null\n ? {}\n : { childOutcome: child.value.settled_outcome }),\n }).pipe(Effect.mapError(internalFailure(operation))),\n );\n continue;\n }\n const marker = markersByChild.get(row.child_submission_id);\n\n if (marker === undefined) continue;\n childAttachments.push(\n yield* decodeChildAttachmentSnapshot({\n toolCallId: row.parent_tool_call_id,\n childSubmissionId: row.child_submission_id,\n childState: \"settled\",\n ...(marker.child_outcome === null ? {} : { childOutcome: marker.child_outcome }),\n }).pipe(Effect.mapError(internalFailure(operation))),\n );\n }\n\n let parentLinkage: ParentLinkage | undefined;\n\n if (\n submissionRow.parent_submission_id !== null &&\n submissionRow.parent_tool_call_id !== null\n ) {\n parentLinkage = yield* decodeParentLinkage({\n parentSubmissionId: submissionRow.parent_submission_id,\n parentToolCallId: submissionRow.parent_tool_call_id,\n }).pipe(Effect.mapError(internalFailure(operation)));\n }\n\n return RecoverySnapshot.make({\n submission,\n joins,\n approvalDecisions,\n unknownResolutions,\n childReservations,\n childAttachments,\n ...(parentLinkage === undefined ? {} : { parentLinkage }),\n ...(hostSubmissionId === undefined ? {} : { hostSubmissionId }),\n ...(suspension === undefined ? {} : { suspension }),\n ...(ownership === undefined ? {} : { ownership }),\n ...(inputApplied === undefined ? {} : { inputApplied }),\n ...(reservation === undefined ? {} : { reservation }),\n ...(abortIntent === undefined ? {} : { abortIntent }),\n });\n }),\n )\n .pipe(Effect.catchTag(\"SqlError\", (error) => Effect.fail(sqlFailure(operation)(error))));\n });\n\n return Context.make(\n SubmissionLedger,\n SubmissionLedger.of({\n capabilities,\n admit,\n markReady,\n lookup,\n resolveAdmission,\n claim,\n renewOwnership,\n releaseOwnership,\n markInputApplied,\n reserveSettlement,\n finalizeSettlement,\n requestAbort,\n claimJoining,\n markJoined,\n revertJoining,\n suspend,\n recordApprovalDecision,\n markUnknown,\n recordUnknownResolution,\n recordChildSettled,\n reserveChildBudget,\n attachChildToReservation,\n beginChildBudgetRelease,\n releaseChildBudget,\n scanNonterminal,\n loadRecoverySnapshot,\n readAbortIntent: readAbortIntentForSubmission,\n }),\n );\n});\n\n/**\n * Durable Object SubmissionLedger implementation sharing the journal's private SQLite\n * database, storage-backed transaction discipline, and producer-epoch fencing substrate.\n * Configuration, failpoint, SQL, and Crypto authority stay visible in the input channel.\n */\nexport const submissionLedgerLayer: Layer.Layer<\n SubmissionLedger,\n DoStorageInitializationError,\n DoStorageConfig | DoStorageFailpoint | SqlClientService.SqlClient | Crypto.Crypto\n> = Layer.effectContext(makeServices());\n\n/**\n * A composition-root convenience Layer for the durable Submission Ledger. Point it at the\n * same `ctx.storage` as the ThreadStore so claims fence the same producer epochs.\n */\nexport const ledgerLayer = (\n options: DoStorageOptions,\n): Layer.Layer<SubmissionLedger, DoStorageInitializationError> =>\n Layer.unwrap(\n Effect.map(DoStorageConfig, (config) =>\n submissionLedgerLayer.pipe(\n Layer.provide(\n Layer.mergeAll(\n Layer.succeed(DoStorageConfig)(config),\n storageFailpointLayer(options),\n SqliteClient.layer({ storage: options.storage }),\n BrowserCrypto.layer,\n ),\n ),\n ),\n ),\n ).pipe(Layer.provide(storageConfigLayer(options)));\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;AAiHA,MAAM,oBAAoB,OAAO,OAAO,MAAM,OAAO,YAAY,GAAS,CAAC;AAC3E,MAAM,oBAAoB,OAAO,eAAe,MAAM,OAAO,YAAY,IAAI,CAAC;AAC9E,MAAM,mBAAmB,OAAO,eAAe,MAAM,OAAO,YAAY,GAAG,CAAC;AAE5E,MAAM,iBAAiB;AACvB,MAAM,aAAa,OAAO,WAAW,aAAa,CAAC,CAAC,CAAC;AACrD,MAAM,qBAAwC;AAC9C,MAAM,YAA+B;AACrC,MAAM,cAAmC;AACzC,MAAM,gBAAqC;AAC3C,MAAM,QAA6B;AACnC,MAAM,wBAAwB;AAE9B,IAAM,gBAAN,cAA4B,OAAO,MAAqB,eAAe,CAAC,CAAC;CACvE,eAAe;CACf,WAAW;CACX,gBAAgB;CAChB,WAAW;CACX,iBAAiB;CACjB,UAAU;CACV,oBAAoB;CACpB,eAAe;CACf,YAAY;CACZ,cAAc;CACd,YAAY;CACZ,OAAO;CACP,iBAAiB,OAAO,OAAO,iBAAiB;CAChD,YAAY;CACZ,UAAU,OAAO,OAAO,gBAAgB;CACxC,yBAAyB,OAAO,OAAO,iBAAiB;CACxD,wBAAwB,OAAO,OAAO,iBAAiB;CACvD,2BAA2B,OAAO,OAAO,iBAAiB;CAC1D,uBAAuB,OAAO,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C,MAAa,eACX,YAEA,MAAM,OACJ,OAAO,IAAI,kBAAkB,WAC3B,sBAAsB,KACpB,MAAM,QACJ,MAAM,SACJ,MAAM,QAAQ,eAAe,CAAC,CAAC,MAAM,GACrC,sBAAsB,OAAO,GAC7B,aAAa,MAAM,EAAE,SAAS,QAAQ,QAAQ,CAAC,GAC/C,cAAc,KAChB,CACF,CACF,CACF,CACF,CAAC,CAAC,KAAK,MAAM,QAAQ,mBAAmB,OAAO,CAAC,CAAC"}
|
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
import { Context, Effect, Layer } from "effect";
|
|
2
|
+
import * as SqlClientService from "effect/unstable/sql/SqlClient";
|
|
3
|
+
import { SourcePartition, SubscriptionError, SubscriptionFailpointError, SubscriptionStore } from "@effect-agent/thread/Subscription";
|
|
4
|
+
declare namespace DoSubscriptionStore_d_exports {
|
|
5
|
+
export { DoSubscriptionAlarmControl, DoSubscriptionAlarmReplacement, DoSubscriptionReplaceAlarm, DoSubscriptionTransaction, doSubscriptionStoreLayer };
|
|
6
|
+
}
|
|
7
|
+
interface DoSubscriptionAlarmReplacement {
|
|
8
|
+
readonly deadlineAtMillis: number | null;
|
|
9
|
+
readonly generation: number;
|
|
10
|
+
}
|
|
11
|
+
type DoSubscriptionReplaceAlarm = (replacement: DoSubscriptionAlarmReplacement) => Effect.Effect<void, SubscriptionError>;
|
|
12
|
+
declare const DoSubscriptionTransaction_base: Context.ServiceClass<DoSubscriptionTransaction, "@effect-agent/storage-cloudflare/DoSubscriptionTransaction", {
|
|
13
|
+
readonly run: <A, E, R>(body: (replaceAlarm: DoSubscriptionReplaceAlarm) => Effect.Effect<A, E, R>) => Effect.Effect<A, E | SubscriptionError, R>;
|
|
14
|
+
}>;
|
|
15
|
+
/** One Durable Object transaction combining subscription SQL and its single native alarm. */
|
|
16
|
+
declare class DoSubscriptionTransaction extends DoSubscriptionTransaction_base {}
|
|
17
|
+
declare const DoSubscriptionAlarmControl_base: Context.ServiceClass<DoSubscriptionAlarmControl, "@effect-agent/storage-cloudflare/DoSubscriptionAlarmControl", {
|
|
18
|
+
readonly prearm: (deadlineAtMillis: number) => Effect.Effect<void, SubscriptionError | SubscriptionFailpointError>;
|
|
19
|
+
readonly reconcile: Effect.Effect<void, SubscriptionError | SubscriptionFailpointError>;
|
|
20
|
+
}>;
|
|
21
|
+
declare class DoSubscriptionAlarmControl extends DoSubscriptionAlarmControl_base {}
|
|
22
|
+
declare const doSubscriptionStoreLayer: (partition: SourcePartition) => Layer.Layer<SubscriptionStore | DoSubscriptionAlarmControl, SubscriptionError, DoSubscriptionTransaction | SqlClientService.SqlClient>;
|
|
23
|
+
//#endregion
|
|
24
|
+
export { DoSubscriptionAlarmControl, DoSubscriptionAlarmReplacement, DoSubscriptionReplaceAlarm, DoSubscriptionTransaction, doSubscriptionStoreLayer, DoSubscriptionStore_d_exports as t };
|
|
25
|
+
//# sourceMappingURL=DoSubscriptionStore.d.mts.map
|