@effect-agent/storage-sqlite 0.1.0-beta.69 → 0.1.0-beta.70

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.
@@ -1 +1 @@
1
- {"version":3,"file":"SqliteSubmissionLedger.mjs","names":[],"sources":["../src/SqliteSubmissionLedger.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 { NodeCrypto } from \"@effect/platform-node\";\nimport { SqliteClient } from \"@effect/sql-sqlite-node\";\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 { decodeRows, initializeSqliteJournal } from \"./internal/sqlite-journal.ts\";\nimport { SqliteStorageConfig } from \"./SqliteStorageConfig.ts\";\nimport {\n SqliteLedgerError,\n SqliteStorageCorruptionError,\n SqliteStorageError,\n SqliteWriteContention,\n type SqliteStorageFailpointLocation,\n} from \"./SqliteStorageError.ts\";\nimport { SqliteStorageFailpoint } from \"./SqliteStorageFailpoint.ts\";\nimport {\n storageConfigLayer,\n storageFailpointLayer,\n type SqliteStorageInitializationError,\n type SqliteStorageOptions,\n} from \"./SqliteThreadStore.ts\";\n\ntype SubmissionId = SubmissionSnapshot[\"submissionId\"];\n\nconst BoundedStoredText = Schema.String.check(Schema.isMaxLength(16 * 1024 * 1024));\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\";\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 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);\n\nconst isSqliteTransactionFailure = Schema.is(\n Schema.Union([SqliteStorageError, SqliteWriteContention]),\n);\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/** Classify raw SQL failures: write-lock timeouts stay retryable typed contention. */\nconst sqlFailure =\n (operation: string) =>\n (error: SqlError): LedgerError => {\n const internal =\n error.reason._tag === \"LockTimeoutError\"\n ? SqliteWriteContention.make({\n cause: error,\n operation,\n message: `Another producer holds the SQLite write lock; ${operation} is safe to retry.`,\n })\n : SqliteLedgerError.make({\n cause: error,\n operation,\n message: error.message,\n });\n\n return internalFailure(operation)(internal);\n };\n\nconst corruptionFailure = (operation: string, table: string, rowKey: string, message: string) =>\n internalFailure(operation)(SqliteStorageCorruptionError.make({ table, rowKey, message }));\n\nconst makeServices = Effect.fn(\"SqliteSubmissionLedger.makeServices\")(function* () {\n const config = yield* SqliteStorageConfig;\n const failpoint = yield* SqliteStorageFailpoint;\n const sql = yield* SqlClientService.SqlClient;\n const crypto = yield* Crypto.Crypto;\n const admissionFence = yield* SubmissionAdmissionFence;\n const journal = yield* initializeSqliteJournal();\n\n const hitFailpoint = (\n location: SqliteStorageFailpointLocation,\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 `BEGIN IMMEDIATE` write transaction so\n * ownership-token and epoch checks are atomic with their writes (DUR-006). Transaction\n * acquisition failures surface as LedgerError carrying the typed retryable\n * SqliteWriteContention (or SqliteStorageError) 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 isSqliteTransactionFailure(error) ? internalFailure(operation)(error) : error,\n ),\n );\n\n const mintIdentifier = (prefix: string, operation: string): Effect.Effect<string, LedgerError> =>\n crypto.randomUUIDv7.pipe(\n Effect.map((uuid) => `${prefix}-${uuid}`),\n Effect.mapError((error) => internalFailure(operation)(error)),\n );\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(\"SqliteSubmissionLedger.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(\"SqliteSubmissionLedger.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(\"SqliteSubmissionLedger.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(\"SqliteSubmissionLedger.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(\"SqliteSubmissionLedger.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(\"SqliteSubmissionLedger.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(\"SqliteSubmissionLedger.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(\"SqliteSubmissionLedger.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 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(\"SqliteSubmissionLedger.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(\n \"SqliteSubmissionLedger.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 const childReservationSnapshotFromRow = Effect.fn(\n \"SqliteSubmissionLedger.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(\"SqliteSubmissionLedger.readApprovalDecisions\")(\n 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\n const approvalIntentFromRow = Effect.fn(\"SqliteSubmissionLedger.approvalIntentFromRow\")(\n 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\n const readUnknownResolutions = Effect.fn(\"SqliteSubmissionLedger.readUnknownResolutions\")(\n 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\n const unknownResolutionIntentFromRow = Effect.fn(\n \"SqliteSubmissionLedger.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(\"SqliteSubmissionLedger.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(\"SqliteSubmissionLedger.canonicalAbortRecordId\")(\n 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\n const abortIntentFromRow = Effect.fn(\"SqliteSubmissionLedger.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 const capabilities = Effect.succeed(LedgerCapabilities.make({ durability: \"durable-node\" }));\n\n const admit: SubmissionLedger[\"Service\"][\"admit\"] = Effect.fn(\"SqliteSubmissionLedger.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 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 > 16 * 1024 * 1024\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 > 16 * 1024 * 1024\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 const mintedSubmissionId = yield* mintIdentifier(\"submission\", operation);\n const mintedReceiptId = yield* mintIdentifier(\"receipt\", 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 \"SqliteSubmissionLedger.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(\"SqliteSubmissionLedger.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 // A single strongly consistent SQLite file always answers authoritatively (SUB-031): the\n // key-scoped read IS the admission truth, so the tri-state degenerates to NotAdmitted or\n // Admitted here — Indeterminate exists for adapters that can fail to reach the owner.\n const resolveAdmission: SubmissionLedger[\"Service\"][\"resolveAdmission\"] = Effect.fn(\n \"SqliteSubmissionLedger.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(\"SqliteSubmissionLedger.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 = yield* mintIdentifier(\"attempt\", operation);\n const ownershipToken = yield* mintIdentifier(\"owner\", 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).\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 (crash between admission and materialization) is created here\n // 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 \"SqliteSubmissionLedger.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 \"SqliteSubmissionLedger.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 \"SqliteSubmissionLedger.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 \"SqliteSubmissionLedger.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 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 finalizeSettlement: SubmissionLedger[\"Service\"][\"finalizeSettlement\"] = Effect.fn(\n \"SqliteSubmissionLedger.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 const settlement = yield* inWriteTransaction(\n operation,\n Effect.gen(function* () {\n const reservation = yield* readReservation(operation, validated.submissionId);\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(\n reservation.value.record_json,\n ).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 const submission = yield* requireSubmission(operation, validated.submissionId);\n\n if (submission.state === \"settled\") {\n if (reservation.value.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.value.outcome,\n ...(settlementFailure === undefined ? {} : { failure: settlementFailure }),\n settledAt: reservation.value.finalized_at,\n }).pipe(Effect.mapError(internalFailure(operation)));\n }\n const now = yield* currentInstant;\n\n yield* sql`\n UPDATE effect_agent_submissions\n SET state = 'settled', settled_outcome = ${reservation.value.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.value.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 \"SqliteSubmissionLedger.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 \"SqliteSubmissionLedger.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 \"SqliteSubmissionLedger.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 \"SqliteSubmissionLedger.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(\n \"SqliteSubmissionLedger.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 (an approval decision,\n // or a child settlement observed directly from the child's row in this single-store\n // file) resumes the caller immediately WITHOUT releasing the lane (plan §2.6, §12).\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 let allSettled = true;\n\n for (const child of validated.reason.children) {\n const childRow = yield* readSubmission(operation, child.childSubmissionId);\n\n if (Option.isNone(childRow) || childRow.value.state !== \"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 * 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(\"SqliteSubmissionLedger.wakeSuspendedIfCovered\")(\n function* (operation: string, submission: SubmissionRow): 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\n const recordApprovalDecision: SubmissionLedger[\"Service\"][\"recordApprovalDecision\"] = Effect.fn(\n \"SqliteSubmissionLedger.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 \"SqliteSubmissionLedger.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 \"SqliteSubmissionLedger.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 \"SqliteSubmissionLedger.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 caller may notify after the canonical Settlement append but before ledger\n // finalization. An exact reservation plus `terminalizing` is the narrow durable prefix\n // that makes that ordering admissible; earlier states remain a caller error.\n const child = yield* readSubmission(operation, validated.childSubmissionId);\n const childReservation = yield* readReservation(operation, validated.childSubmissionId);\n\n const announced =\n Option.isSome(child) &&\n (child.value.state === \"settled\" ||\n (child.value.state === \"terminalizing\" && Option.isSome(childReservation)));\n\n if (!announced) {\n return yield* LedgerError.make({\n operation,\n message: `Child submission ${validated.childSubmissionId} has no recorded settlement.`,\n });\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 // Every listed child must be either finalized or canonically announced from the exact\n // terminalizing reservation. Replays re-run this coverage check idempotently.\n for (const entry of reason.children) {\n const listed = yield* readSubmission(operation, entry.childSubmissionId);\n const reservation = yield* readReservation(operation, entry.childSubmissionId);\n\n const covered =\n Option.isSome(listed) &&\n (listed.value.state === \"settled\" ||\n (listed.value.state === \"terminalizing\" && Option.isSome(reservation)));\n\n if (!covered) {\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 \"SqliteSubmissionLedger.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(\"SqliteSubmissionLedger.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 // Single-store latitude: the admitted child must exist here, so a dangling\n // attachment can never enter the recovery view.\n const child = yield* readSubmission(operation, validated.childSubmissionId);\n\n if (Option.isNone(child)) {\n return yield* LedgerError.make({\n operation,\n message: `Unknown child submission ${validated.childSubmissionId}.`,\n });\n }\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 \"SqliteSubmissionLedger.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 \"SqliteSubmissionLedger.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(\"SqliteSubmissionLedger.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 (\n thread_id > ${cursor.threadId}\n OR (\n thread_id = ${cursor.threadId}\n AND queue_sequence > ${cursor.queueSequence}\n )\n )\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 \"SqliteSubmissionLedger.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 \"SqliteSubmissionLedger.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* journal\n .withReadTransaction(operation)(\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).\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 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.isNone(child)) continue;\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 }\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(\n Effect.catchTag(\"SqliteStorageError\", (error) =>\n Effect.fail(internalFailure(operation)(error)),\n ),\n );\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 * SQLite SubmissionLedger implementation sharing the journal's database file, write\n * transaction discipline, and producer-epoch fencing substrate. Configuration, failpoint,\n * SQL, and Crypto authority stay visible in the input channel.\n */\nexport const submissionLedgerLayer: Layer.Layer<\n SubmissionLedger,\n SqliteStorageInitializationError,\n SqliteStorageConfig | SqliteStorageFailpoint | 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 database file as the ThreadStore so claims fence the same producer epochs.\n */\nexport const ledgerLayer = (\n options: SqliteStorageOptions,\n): Layer.Layer<SubmissionLedger, SqliteStorageInitializationError> =>\n Layer.unwrap(\n Effect.map(SqliteStorageConfig, (config) =>\n submissionLedgerLayer.pipe(\n Layer.provide(\n Layer.mergeAll(\n Layer.succeed(SqliteStorageConfig)(config),\n storageFailpointLayer(options),\n SqliteClient.layer({ filename: options.filename }),\n NodeCrypto.layer,\n ),\n ),\n ),\n ),\n ).pipe(Layer.provide(storageConfigLayer(options)));\n"],"mappings":";;;;;;;;;;;;;;;;;;;AA8GA,MAAM,oBAAoB,OAAO,OAAO,MAAM,OAAO,YAAY,QAAgB,CAAC;AAClF,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;AAEnC,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,OAAO,iBAAiB;CACtD,cAAc,OAAO,OAAO,gBAAgB;CAC5C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A,MAAM,OACJ,OAAO,IAAI,sBAAsB,WAC/B,sBAAsB,KACpB,MAAM,QACJ,MAAM,SACJ,MAAM,QAAQ,mBAAmB,CAAC,CAAC,MAAM,GACzC,sBAAsB,OAAO,GAC7B,aAAa,MAAM,EAAE,UAAU,QAAQ,SAAS,CAAC,GACjD,WAAW,KACb,CACF,CACF,CACF,CACF,CAAC,CAAC,KAAK,MAAM,QAAQ,mBAAmB,OAAO,CAAC,CAAC"}
1
+ {"version":3,"file":"SqliteSubmissionLedger.mjs","names":[],"sources":["../src/SqliteSubmissionLedger.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 { NodeCrypto } from \"@effect/platform-node\";\nimport { SqliteClient } from \"@effect/sql-sqlite-node\";\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 { decodeRows, initializeSqliteJournal } from \"./internal/sqlite-journal.ts\";\nimport { SqliteStorageConfig } from \"./SqliteStorageConfig.ts\";\nimport {\n SqliteLedgerError,\n SqliteStorageCorruptionError,\n SqliteStorageError,\n SqliteWriteContention,\n type SqliteStorageFailpointLocation,\n} from \"./SqliteStorageError.ts\";\nimport { SqliteStorageFailpoint } from \"./SqliteStorageFailpoint.ts\";\nimport {\n storageConfigLayer,\n storageFailpointLayer,\n type SqliteStorageInitializationError,\n type SqliteStorageOptions,\n} from \"./SqliteThreadStore.ts\";\n\ntype SubmissionId = SubmissionSnapshot[\"submissionId\"];\n\nconst BoundedStoredText = Schema.String.check(Schema.isMaxLength(16 * 1024 * 1024));\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\";\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 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);\n\nconst isSqliteTransactionFailure = Schema.is(\n Schema.Union([SqliteStorageError, SqliteWriteContention]),\n);\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/** Classify raw SQL failures: write-lock timeouts stay retryable typed contention. */\nconst sqlFailure =\n (operation: string) =>\n (error: SqlError): LedgerError => {\n const internal =\n error.reason._tag === \"LockTimeoutError\"\n ? SqliteWriteContention.make({\n cause: error,\n operation,\n message: `Another producer holds the SQLite write lock; ${operation} is safe to retry.`,\n })\n : SqliteLedgerError.make({\n cause: error,\n operation,\n message: error.message,\n });\n\n return internalFailure(operation)(internal);\n };\n\nconst corruptionFailure = (operation: string, table: string, rowKey: string, message: string) =>\n internalFailure(operation)(SqliteStorageCorruptionError.make({ table, rowKey, message }));\n\nconst makeServices = Effect.fn(\"SqliteSubmissionLedger.makeServices\")(function* () {\n const config = yield* SqliteStorageConfig;\n const failpoint = yield* SqliteStorageFailpoint;\n const sql = yield* SqlClientService.SqlClient;\n const crypto = yield* Crypto.Crypto;\n const admissionFence = yield* SubmissionAdmissionFence;\n const journal = yield* initializeSqliteJournal();\n\n const hitFailpoint = (\n location: SqliteStorageFailpointLocation,\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 `BEGIN IMMEDIATE` write transaction so\n * ownership-token and epoch checks are atomic with their writes (DUR-006). Transaction\n * acquisition failures surface as LedgerError carrying the typed retryable\n * SqliteWriteContention (or SqliteStorageError) 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 isSqliteTransactionFailure(error) ? internalFailure(operation)(error) : error,\n ),\n );\n\n const mintIdentifier = (prefix: string, operation: string): Effect.Effect<string, LedgerError> =>\n crypto.randomUUIDv7.pipe(\n Effect.map((uuid) => `${prefix}-${uuid}`),\n Effect.mapError((error) => internalFailure(operation)(error)),\n );\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(\"SqliteSubmissionLedger.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(\"SqliteSubmissionLedger.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(\"SqliteSubmissionLedger.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(\"SqliteSubmissionLedger.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(\"SqliteSubmissionLedger.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(\"SqliteSubmissionLedger.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(\"SqliteSubmissionLedger.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(\"SqliteSubmissionLedger.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 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(\"SqliteSubmissionLedger.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(\n \"SqliteSubmissionLedger.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 const childReservationSnapshotFromRow = Effect.fn(\n \"SqliteSubmissionLedger.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(\"SqliteSubmissionLedger.readApprovalDecisions\")(\n 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\n const approvalIntentFromRow = Effect.fn(\"SqliteSubmissionLedger.approvalIntentFromRow\")(\n 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\n const readUnknownResolutions = Effect.fn(\"SqliteSubmissionLedger.readUnknownResolutions\")(\n 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\n const unknownResolutionIntentFromRow = Effect.fn(\n \"SqliteSubmissionLedger.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(\"SqliteSubmissionLedger.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(\"SqliteSubmissionLedger.canonicalAbortRecordId\")(\n 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\n const abortIntentFromRow = Effect.fn(\"SqliteSubmissionLedger.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 const capabilities = Effect.succeed(LedgerCapabilities.make({ durability: \"durable-node\" }));\n\n const admit: SubmissionLedger[\"Service\"][\"admit\"] = Effect.fn(\"SqliteSubmissionLedger.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 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 > 16 * 1024 * 1024\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 > 16 * 1024 * 1024\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 const mintedSubmissionId = yield* mintIdentifier(\"submission\", operation);\n const mintedReceiptId = yield* mintIdentifier(\"receipt\", 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 \"SqliteSubmissionLedger.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(\"SqliteSubmissionLedger.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 // A single strongly consistent SQLite file always answers authoritatively (SUB-031): the\n // key-scoped read IS the admission truth, so the tri-state degenerates to NotAdmitted or\n // Admitted here — Indeterminate exists for adapters that can fail to reach the owner.\n const resolveAdmission: SubmissionLedger[\"Service\"][\"resolveAdmission\"] = Effect.fn(\n \"SqliteSubmissionLedger.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(\"SqliteSubmissionLedger.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 = yield* mintIdentifier(\"attempt\", operation);\n const ownershipToken = yield* mintIdentifier(\"owner\", 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).\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 (crash between admission and materialization) is created here\n // 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 \"SqliteSubmissionLedger.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 \"SqliteSubmissionLedger.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 \"SqliteSubmissionLedger.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 \"SqliteSubmissionLedger.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 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(\"SqliteSubmissionLedger.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(\"SqliteSubmissionLedger.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 \"SqliteSubmissionLedger.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 \"SqliteSubmissionLedger.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 \"SqliteSubmissionLedger.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 \"SqliteSubmissionLedger.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 \"SqliteSubmissionLedger.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(\n \"SqliteSubmissionLedger.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 (an approval decision,\n // or a child settlement observed directly from the child's row in this single-store\n // file) resumes the caller immediately WITHOUT releasing the lane (plan §2.6, §12).\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 let allSettled = true;\n\n for (const child of validated.reason.children) {\n const childRow = yield* readSubmission(operation, child.childSubmissionId);\n\n if (Option.isNone(childRow) || childRow.value.state !== \"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 * 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(\"SqliteSubmissionLedger.wakeSuspendedIfCovered\")(\n function* (operation: string, submission: SubmissionRow): 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\n const recordApprovalDecision: SubmissionLedger[\"Service\"][\"recordApprovalDecision\"] = Effect.fn(\n \"SqliteSubmissionLedger.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 \"SqliteSubmissionLedger.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 \"SqliteSubmissionLedger.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 \"SqliteSubmissionLedger.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 caller may notify after the canonical Settlement append but before ledger\n // finalization. An exact reservation plus `terminalizing` is the narrow durable prefix\n // that makes that ordering admissible; earlier states remain a caller error.\n const child = yield* readSubmission(operation, validated.childSubmissionId);\n const childReservation = yield* readReservation(operation, validated.childSubmissionId);\n\n const announced =\n Option.isSome(child) &&\n (child.value.state === \"settled\" ||\n (child.value.state === \"terminalizing\" && Option.isSome(childReservation)));\n\n if (!announced) {\n return yield* LedgerError.make({\n operation,\n message: `Child submission ${validated.childSubmissionId} has no recorded settlement.`,\n });\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 // Every listed child must be either finalized or canonically announced from the exact\n // terminalizing reservation. Replays re-run this coverage check idempotently.\n for (const entry of reason.children) {\n const listed = yield* readSubmission(operation, entry.childSubmissionId);\n const reservation = yield* readReservation(operation, entry.childSubmissionId);\n\n const covered =\n Option.isSome(listed) &&\n (listed.value.state === \"settled\" ||\n (listed.value.state === \"terminalizing\" && Option.isSome(reservation)));\n\n if (!covered) {\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 \"SqliteSubmissionLedger.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(\"SqliteSubmissionLedger.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 // Single-store latitude: the admitted child must exist here, so a dangling\n // attachment can never enter the recovery view.\n const child = yield* readSubmission(operation, validated.childSubmissionId);\n\n if (Option.isNone(child)) {\n return yield* LedgerError.make({\n operation,\n message: `Unknown child submission ${validated.childSubmissionId}.`,\n });\n }\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 \"SqliteSubmissionLedger.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 \"SqliteSubmissionLedger.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(\"SqliteSubmissionLedger.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 \"SqliteSubmissionLedger.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 \"SqliteSubmissionLedger.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* journal\n .withReadTransaction(operation)(\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).\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 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.isNone(child)) continue;\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 }\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(\n Effect.catchTag(\"SqliteStorageError\", (error) =>\n Effect.fail(internalFailure(operation)(error)),\n ),\n );\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 * SQLite SubmissionLedger implementation sharing the journal's database file, write\n * transaction discipline, and producer-epoch fencing substrate. Configuration, failpoint,\n * SQL, and Crypto authority stay visible in the input channel.\n */\nexport const submissionLedgerLayer: Layer.Layer<\n SubmissionLedger,\n SqliteStorageInitializationError,\n SqliteStorageConfig | SqliteStorageFailpoint | 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 database file as the ThreadStore so claims fence the same producer epochs.\n */\nexport const ledgerLayer = (\n options: SqliteStorageOptions,\n): Layer.Layer<SubmissionLedger, SqliteStorageInitializationError> =>\n Layer.unwrap(\n Effect.map(SqliteStorageConfig, (config) =>\n submissionLedgerLayer.pipe(\n Layer.provide(\n Layer.mergeAll(\n Layer.succeed(SqliteStorageConfig)(config),\n storageFailpointLayer(options),\n SqliteClient.layer({ filename: options.filename }),\n NodeCrypto.layer,\n ),\n ),\n ),\n ),\n ).pipe(Layer.provide(storageConfigLayer(options)));\n"],"mappings":";;;;;;;;;;;;;;;;;;;AA8GA,MAAM,oBAAoB,OAAO,OAAO,MAAM,OAAO,YAAY,QAAgB,CAAC;AAClF,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;AAEnC,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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