@effect-agent/storage-cloudflare 0.1.0-beta.8 → 0.1.0-beta.81
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/DoMemoryStore.d.mts +29 -0
- package/dist/DoMemoryStore.mjs +55 -0
- package/dist/DoMemoryStore.mjs.map +1 -0
- package/dist/DoMessageDeliveryStore.d.mts +17 -0
- package/dist/DoMessageDeliveryStore.mjs +32 -0
- package/dist/DoMessageDeliveryStore.mjs.map +1 -0
- package/dist/DoScheduleStore.d.mts +36 -0
- package/dist/DoScheduleStore.mjs +388 -0
- package/dist/DoScheduleStore.mjs.map +1 -0
- package/dist/DoStorageConfig.d.mts +45 -0
- package/dist/DoStorageConfig.mjs +52 -0
- package/dist/DoStorageConfig.mjs.map +1 -0
- package/dist/DoStorageError-Cmhvl4TQ.d.mts +98 -0
- package/dist/DoStorageError.d.mts +2 -0
- package/dist/DoStorageError.mjs +164 -0
- package/dist/DoStorageError.mjs.map +1 -0
- package/dist/DoStorageFailpoint.d.mts +17 -0
- package/dist/DoStorageFailpoint.mjs +14 -0
- package/dist/DoStorageFailpoint.mjs.map +1 -0
- package/dist/DoStorageFailpointTesting.d.mts +34 -0
- package/dist/DoStorageFailpointTesting.mjs +35 -0
- package/dist/DoStorageFailpointTesting.mjs.map +1 -0
- package/dist/DoStorageVersion-x5OOurvZ.d.mts +12 -0
- package/dist/DoStorageVersion.d.mts +2 -0
- package/dist/DoStorageVersion.mjs +8 -0
- package/dist/DoStorageVersion.mjs.map +1 -0
- package/dist/DoSubmissionLedger.d.mts +23 -0
- package/dist/DoSubmissionLedger.mjs +1849 -0
- package/dist/DoSubmissionLedger.mjs.map +1 -0
- package/dist/DoSubscriptionStore.d.mts +25 -0
- package/dist/DoSubscriptionStore.mjs +183 -0
- package/dist/DoSubscriptionStore.mjs.map +1 -0
- package/dist/DoThreadStore.d.mts +59 -0
- package/dist/DoThreadStore.mjs +465 -0
- package/dist/DoThreadStore.mjs.map +1 -0
- package/dist/MemoryProtocol.d.mts +38160 -0
- package/dist/MemoryProtocol.mjs +219 -0
- package/dist/MemoryProtocol.mjs.map +1 -0
- package/dist/PortProtocol.d.mts +3207 -0
- package/dist/PortProtocol.mjs +176 -0
- package/dist/PortProtocol.mjs.map +1 -0
- package/dist/PortRouting.d.mts +83 -0
- package/dist/PortRouting.mjs +410 -0
- package/dist/PortRouting.mjs.map +1 -0
- package/dist/do-journal-DHqCQeBU.mjs +991 -0
- package/dist/do-journal-DHqCQeBU.mjs.map +1 -0
- package/dist/index.d.mts +14 -1521
- package/dist/index.mjs +14 -3695
- package/dist/migrations-Ba_kOrSx.mjs +287 -0
- package/dist/migrations-Ba_kOrSx.mjs.map +1 -0
- package/dist/rolldown-runtime-D7D4PA-g.mjs +13 -0
- package/package.json +1 -45
- package/src/DoMemoryStore.ts +59 -0
- package/src/DoMessageDeliveryStore.ts +53 -0
- package/src/DoScheduleStore.ts +622 -0
- package/src/{errors.ts → DoStorageError.ts} +10 -3
- package/src/DoStorageFailpoint.ts +20 -0
- package/src/{do-storage-failpoint.ts → DoStorageFailpointTesting.ts} +5 -18
- package/src/DoStorageVersion.ts +2 -0
- package/src/{do-ledger.ts → DoSubmissionLedger.ts} +862 -163
- package/src/DoSubscriptionStore.ts +329 -0
- package/src/DoThreadStore.ts +1014 -0
- package/src/MemoryProtocol.ts +355 -0
- package/src/{port-protocol.ts → PortProtocol.ts} +44 -37
- package/src/{routing.ts → PortRouting.ts} +292 -264
- package/src/index.ts +13 -32
- package/src/{do-journal.ts → internal/do-journal.ts} +716 -232
- package/src/internal/message-delivery-schema.ts +24 -0
- package/src/{migrations.ts → internal/migrations.ts} +51 -35
- package/src/internal/recovery-checkpoint-schema.ts +17 -0
- package/dist/index.mjs.map +0 -1
- package/src/do-conversation-store.ts +0 -850
- /package/src/{do-storage-config.ts → DoStorageConfig.ts} +0 -0
package/dist/index.mjs.map
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"index.mjs","names":["BoundedStoredText","BoundedIdentifier","MAX_IDENTIFIER_LENGTH","noFailpoint","makeServices","SqlClientService","SqlClientService"],"sources":["../src/errors.ts","../src/migrations.ts","../src/do-journal.ts","../src/do-storage-config.ts","../src/do-storage-failpoint.ts","../src/do-conversation-store.ts","../src/do-ledger.ts","../src/port-protocol.ts","../src/routing.ts"],"sourcesContent":["import { CanonicalSequence, ProducerEpoch } from \"@effect-agent/session\";\nimport { Schema } from \"effect\";\n\n/** The Durable Object's SQLite storage uses a private-development format this adapter cannot read. */\nexport class DoStorageCompatibilityError extends Schema.TaggedError<DoStorageCompatibilityError>()(\n \"DoStorageCompatibilityError\",\n {\n actualVersion: Schema.Int,\n message: Schema.String,\n supportedVersion: Schema.Int,\n },\n) {}\n\n/** Stored bytes failed the current Schema and cannot be used as recovery truth. */\nexport class DoStorageCorruptionError extends Schema.TaggedError<DoStorageCorruptionError>()(\n \"DoStorageCorruptionError\",\n {\n message: Schema.String,\n rowKey: Schema.String,\n table: Schema.String,\n },\n) {}\n\n/** Durable Object SQLite infrastructure failed while opening or operating the store. */\nexport class DoStorageError extends Schema.TaggedError<DoStorageError>()(\"DoStorageError\", {\n cause: Schema.optionalKey(Schema.Defect()),\n message: Schema.String,\n operation: Schema.String,\n}) {}\n\n/**\n * Durable Object SQLite infrastructure failed while operating the Submission Ledger. Surfaces\n * at the SubmissionLedger port as the typed `LedgerError` with this error preserved as its\n * cause, so the adapter-level tag is never erased.\n */\nexport class DoLedgerError extends Schema.TaggedError<DoLedgerError>()(\"DoLedgerError\", {\n cause: Schema.optionalKey(Schema.Defect()),\n message: Schema.String,\n operation: Schema.String,\n}) {}\n\n/**\n * A value to be stored exceeds the configured Durable Object per-value bound\n * (`DoStorageConfigValue.maxStoredValueBytes`, kept under the platform's 2 MB SQLite value\n * limit). The refusal happens typed BEFORE any durable mutation; no partial state is written.\n * Payloads of this size are the designed overflow case for a future R2-backed AttachmentStore\n * (deployment spec §3.1, deferred until a real attachment requirement exists).\n */\nexport class DoValueBoundExceeded extends Schema.TaggedError<DoValueBoundExceeded>()(\n \"DoValueBoundExceeded\",\n {\n actualBytes: Schema.Int,\n maxBytes: Schema.Int,\n operation: Schema.String,\n },\n) {\n override get message() {\n return (\n `A stored value of ${this.actualBytes} bytes exceeds the Durable Object per-value bound ` +\n `of ${this.maxBytes} bytes during ${this.operation}. Nothing was written. Values of this ` +\n \"size are the designed R2 AttachmentStore overflow path (deferred, deployment spec §3.1).\"\n );\n }\n}\n\n/**\n * A canonical batch retry conflicts with existing append state. Tail conflicts carry the\n * actual committed tail as a diagnostic resume hint.\n */\nexport class DoAppendConflict extends Schema.TaggedError<DoAppendConflict>()(\"DoAppendConflict\", {\n message: Schema.String,\n reason: Schema.Literals([\"batch-digest\", \"record-identity\", \"tail\"]),\n actualTailSequence: Schema.optionalKey(CanonicalSequence),\n actualTailDigest: Schema.optionalKey(Schema.String),\n}) {}\n\n/**\n * A producer epoch does not match the Conversation's current writer registration. Appends\n * require the exact registered epoch, so both older and newer unregistered epochs are fenced;\n * a newer epoch takes over by materializing first.\n */\nexport class DoFenceRejected extends Schema.TaggedError<DoFenceRejected>()(\"DoFenceRejected\", {\n actualEpoch: ProducerEpoch,\n message: Schema.String,\n producerEpoch: ProducerEpoch,\n}) {}\n\n/** A checkpoint conflicts with a previously stored checkpoint at the same offset. */\nexport class DoCheckpointConflict extends Schema.TaggedError<DoCheckpointConflict>()(\n \"DoCheckpointConflict\",\n {\n message: Schema.String,\n },\n) {}\n\n/**\n * Deterministic fault-injection locations at Durable Object storage operation boundaries.\n *\n * The string list is copied VERBATIM from `SqliteStorageFailpointLocation`\n * (`packages/storage-sqlite/src/errors.ts`) so every crash-matrix row keeps the same name on\n * both platforms — the DN process-kill evidence and the DC eviction evidence address identical\n * locations. There is intentionally no Cloudflare-only location.\n */\nexport const DoStorageFailpointLocation = Schema.Literals([\n \"materialize:before\",\n \"materialize:after\",\n \"append:before\",\n \"append:after-batch-insert\",\n \"append:after-record-insert\",\n \"append:after-tail-update\",\n \"append:after\",\n \"export:after-conversation-read\",\n \"save-checkpoint:before\",\n \"save-checkpoint:after\",\n \"ledger:admit:before\",\n \"ledger:admit:after\",\n \"ledger:mark-ready:before\",\n \"ledger:mark-ready:after\",\n \"ledger:claim:before\",\n \"ledger:claim:after\",\n \"ledger:mark-input-applied:before\",\n \"ledger:mark-input-applied:after\",\n \"ledger:renew:before\",\n \"ledger:renew:after\",\n \"ledger:reserve-settlement:before\",\n \"ledger:reserve-settlement:after\",\n \"ledger:finalize-settlement:before\",\n \"ledger:finalize-settlement:after\",\n \"ledger:request-abort:before\",\n \"ledger:request-abort:after\",\n \"ledger:release:before\",\n \"ledger:release:after\",\n \"ledger:claim-joining:before\",\n \"ledger:claim-joining:after\",\n \"ledger:mark-joined:before\",\n \"ledger:mark-joined:after\",\n \"ledger:revert-joining:before\",\n \"ledger:revert-joining:after\",\n \"ledger:suspend:before\",\n \"ledger:suspend:after\",\n \"ledger:approval-decision:before\",\n \"ledger:approval-decision:after\",\n \"ledger:mark-unknown:before\",\n \"ledger:mark-unknown:after\",\n \"ledger:unknown-resolution:before\",\n \"ledger:unknown-resolution:after\",\n \"ledger:child-reservation:before\",\n \"ledger:child-reservation:after\",\n \"ledger:child-attach:before\",\n \"ledger:child-attach:after\",\n \"ledger:child-release-pending:before\",\n \"ledger:child-release-pending:after\",\n \"ledger:child-release:before\",\n \"ledger:child-release:after\",\n \"ledger:child-settled:before\",\n \"ledger:child-settled:after\",\n]);\nexport type DoStorageFailpointLocation = typeof DoStorageFailpointLocation.Type;\n\n/** Deterministic test-only fault or pause injected at a Durable Object storage boundary. */\nexport class DoStorageFailpointError extends Schema.TaggedError<DoStorageFailpointError>()(\n \"DoStorageFailpointError\",\n {\n location: DoStorageFailpointLocation,\n },\n) {\n override get message() {\n return `Injected Durable Object storage failure at ${this.location}.`;\n }\n}\n","import { SqliteMigrator } from \"@effect/sql-sqlite-do\";\nimport { Effect } from \"effect\";\nimport * as SqlClient from \"effect/unstable/sql/SqlClient\";\n\n/**\n * The exact-or-fresh storage version recorded in `effect_agent_meta`. Cloudflare is a fresh\n * platform, so there is exactly ONE migration carrying the complete current schema — no\n * v1→v4 history to replay (deployment spec §9: no rolling data-version promise during\n * private development).\n */\nexport const CurrentDoStorageVersion = 1;\n\n/**\n * The Conversation Durable Object schema. Table names and columns mirror the Node/SQLite v4\n * schema byte-for-byte (`packages/storage-sqlite/src/migrations.ts`, migrations 1–4 collapsed\n * into their final shape) so the shared conformance suites and crash-matrix rows address\n * identical durable state. Two DC-specific additions:\n *\n * 1. `effect_agent_meta` replaces `PRAGMA user_version` as the exact-or-fresh version gate —\n * a meta table is portable regardless of which PRAGMAs Durable Object SQL storage allows.\n * 2. `effect_agent_child_settlements` is the durable cross-store notification marker the\n * SubmissionLedger port contract mandates for cross-store adapters (`suspend`'s covering\n * check and `recordChildSettled`'s wake both consult it): parent and child Conversations\n * live in different Durable Objects, so a child settlement reported before the parent's\n * suspend commits must be observable from the PARENT's own storage.\n */\nexport const doMigrations = SqliteMigrator.fromRecord({\n \"1_current_cloudflare_conversation_object\": Effect.gen(function* () {\n const sql = yield* SqlClient.SqlClient;\n\n yield* sql`\n CREATE TABLE effect_agent_conversations (\n conversation_id TEXT PRIMARY KEY NOT NULL,\n created_at TEXT NOT NULL,\n tail_sequence INTEGER NOT NULL,\n tail_digest TEXT NOT NULL,\n producer_epoch INTEGER NOT NULL\n )\n `.withoutTransform;\n\n yield* sql`\n CREATE TABLE effect_agent_canonical_batches (\n conversation_id TEXT NOT NULL,\n batch_id TEXT NOT NULL,\n first_sequence INTEGER NOT NULL,\n last_sequence INTEGER NOT NULL,\n batch_digest TEXT NOT NULL,\n tail_digest TEXT NOT NULL,\n batch_json TEXT NOT NULL,\n PRIMARY KEY (conversation_id, batch_id),\n FOREIGN KEY (conversation_id)\n REFERENCES effect_agent_conversations(conversation_id)\n ON DELETE RESTRICT\n )\n `.withoutTransform;\n\n yield* sql`\n CREATE TABLE effect_agent_canonical_records (\n conversation_id TEXT NOT NULL,\n sequence INTEGER NOT NULL,\n record_id TEXT NOT NULL,\n batch_id TEXT NOT NULL,\n record_json TEXT NOT NULL,\n PRIMARY KEY (conversation_id, sequence),\n UNIQUE (conversation_id, record_id),\n FOREIGN KEY (conversation_id, batch_id)\n REFERENCES effect_agent_canonical_batches(conversation_id, batch_id)\n ON DELETE RESTRICT\n )\n `.withoutTransform;\n\n yield* sql`\n CREATE INDEX effect_agent_canonical_records_batch\n ON effect_agent_canonical_records (conversation_id, batch_id, sequence)\n `.withoutTransform;\n\n yield* sql`\n CREATE TABLE effect_agent_checkpoints (\n conversation_id TEXT NOT NULL,\n through_sequence INTEGER NOT NULL,\n tail_digest TEXT NOT NULL,\n checkpoint_json TEXT NOT NULL,\n PRIMARY KEY (conversation_id, through_sequence),\n FOREIGN KEY (conversation_id)\n REFERENCES effect_agent_conversations(conversation_id)\n ON DELETE RESTRICT\n )\n `.withoutTransform;\n\n // Admission rows exist before Conversation materialization (durability §4), so\n // conversation_id intentionally carries no foreign key into effect_agent_conversations.\n yield* sql`\n CREATE TABLE effect_agent_submissions (\n submission_id TEXT PRIMARY KEY NOT NULL,\n conversation_id TEXT NOT NULL,\n queue_sequence INTEGER NOT NULL,\n principal TEXT NOT NULL,\n idempotency_key TEXT NOT NULL,\n agent_id TEXT NOT NULL,\n agent_digests_json TEXT NOT NULL,\n deployment_id TEXT NOT NULL,\n input_json TEXT NOT NULL,\n input_digest TEXT NOT NULL,\n receipt_id TEXT NOT NULL,\n state TEXT NOT NULL,\n settled_outcome TEXT,\n created_at TEXT NOT NULL,\n ready_at TEXT,\n input_applied_record_id TEXT,\n input_applied_sequence INTEGER,\n joined_host_submission_id TEXT,\n suspended_reason_json TEXT,\n suspended_at TEXT,\n unknown_reason TEXT,\n unknown_tool_call_ids_json TEXT,\n parent_submission_id TEXT,\n parent_tool_call_id TEXT,\n UNIQUE (conversation_id, principal, idempotency_key),\n UNIQUE (conversation_id, queue_sequence)\n )\n `.withoutTransform;\n\n yield* sql`\n CREATE INDEX effect_agent_submissions_joined_host\n ON effect_agent_submissions (joined_host_submission_id)\n `.withoutTransform;\n\n yield* sql`\n CREATE INDEX effect_agent_submissions_parent\n ON effect_agent_submissions (parent_submission_id)\n `.withoutTransform;\n\n yield* sql`\n CREATE TABLE effect_agent_submission_ownership (\n submission_id TEXT PRIMARY KEY NOT NULL,\n attempt_id TEXT NOT NULL,\n ownership_token TEXT NOT NULL,\n producer_epoch INTEGER NOT NULL,\n owner_producer_id TEXT NOT NULL,\n lease_expires_at TEXT NOT NULL,\n FOREIGN KEY (submission_id)\n REFERENCES effect_agent_submissions(submission_id)\n ON DELETE RESTRICT\n )\n `.withoutTransform;\n\n yield* sql`\n CREATE TABLE effect_agent_attempts (\n attempt_id TEXT PRIMARY KEY NOT NULL,\n submission_id TEXT NOT NULL,\n conversation_id TEXT NOT NULL,\n owner_producer_id TEXT NOT NULL,\n producer_epoch INTEGER NOT NULL,\n claimed_at TEXT NOT NULL,\n FOREIGN KEY (submission_id)\n REFERENCES effect_agent_submissions(submission_id)\n ON DELETE RESTRICT\n )\n `.withoutTransform;\n\n yield* sql`\n CREATE TABLE effect_agent_settlement_reservations (\n submission_id TEXT PRIMARY KEY NOT NULL,\n settlement_id TEXT NOT NULL,\n outcome TEXT NOT NULL,\n record_id TEXT NOT NULL,\n record_json TEXT NOT NULL,\n record_digest TEXT NOT NULL,\n reserved_at TEXT NOT NULL,\n finalized_at TEXT,\n FOREIGN KEY (submission_id)\n REFERENCES effect_agent_submissions(submission_id)\n ON DELETE RESTRICT\n )\n `.withoutTransform;\n\n yield* sql`\n CREATE TABLE effect_agent_abort_intents (\n submission_id TEXT PRIMARY KEY NOT NULL,\n author TEXT NOT NULL,\n reason TEXT NOT NULL,\n requested_at TEXT NOT NULL,\n canonical_record_id TEXT,\n FOREIGN KEY (submission_id)\n REFERENCES effect_agent_submissions(submission_id)\n ON DELETE RESTRICT\n )\n `.withoutTransform;\n\n yield* sql`\n CREATE TABLE effect_agent_approval_decisions (\n submission_id TEXT NOT NULL,\n tool_call_id TEXT NOT NULL,\n decision TEXT NOT NULL,\n resolver TEXT NOT NULL,\n reason TEXT NOT NULL,\n decided_at TEXT NOT NULL,\n PRIMARY KEY (submission_id, tool_call_id),\n FOREIGN KEY (submission_id)\n REFERENCES effect_agent_submissions(submission_id)\n ON DELETE RESTRICT\n )\n `.withoutTransform;\n\n yield* sql`\n CREATE TABLE effect_agent_unknown_resolutions (\n submission_id TEXT NOT NULL,\n tool_call_id TEXT NOT NULL,\n author TEXT NOT NULL,\n reason TEXT NOT NULL,\n resolution_json TEXT NOT NULL,\n resolved_at TEXT NOT NULL,\n PRIMARY KEY (submission_id, tool_call_id),\n FOREIGN KEY (submission_id)\n REFERENCES effect_agent_submissions(submission_id)\n ON DELETE RESTRICT\n )\n `.withoutTransform;\n\n yield* sql`\n CREATE TABLE effect_agent_child_reservations (\n reservation_id TEXT PRIMARY KEY NOT NULL,\n parent_submission_id TEXT NOT NULL,\n parent_tool_call_id TEXT NOT NULL,\n child_submission_id TEXT,\n status TEXT NOT NULL,\n allocation_json TEXT NOT NULL,\n allocation_digest TEXT NOT NULL,\n accounting_json TEXT,\n reserved_at TEXT NOT NULL,\n release_began_at TEXT,\n released_at TEXT,\n UNIQUE (parent_submission_id, parent_tool_call_id),\n FOREIGN KEY (parent_submission_id)\n REFERENCES effect_agent_submissions(submission_id)\n ON DELETE RESTRICT\n )\n `.withoutTransform;\n\n // Durable cross-store child-settlement notification marker (parent-side; the child's row\n // lives in ANOTHER Durable Object). child_outcome is nullable: the notification command\n // carries identities only, and the child's canonical Settlement stays the outcome\n // authority (DUR-015). No foreign keys: the parent row is checked by the operation, and\n // the child row is intentionally foreign.\n yield* sql`\n CREATE TABLE effect_agent_child_settlements (\n parent_submission_id TEXT NOT NULL,\n child_submission_id TEXT NOT NULL,\n child_outcome TEXT,\n recorded_at TEXT NOT NULL,\n PRIMARY KEY (parent_submission_id, child_submission_id)\n )\n `.withoutTransform;\n\n yield* sql`\n CREATE TABLE effect_agent_meta (\n key TEXT PRIMARY KEY NOT NULL,\n value TEXT NOT NULL\n )\n `.withoutTransform;\n\n yield* sql`\n INSERT INTO effect_agent_meta (key, value)\n VALUES ('storage_version', ${String(CurrentDoStorageVersion)})\n `.withoutTransform;\n }),\n});\n","import { CanonicalSequence, ProducerEpoch } from \"@effect-agent/session\";\nimport { SqliteMigrator } from \"@effect/sql-sqlite-do\";\nimport { Effect, Schema } from \"effect\";\nimport * as SqlClient from \"effect/unstable/sql/SqlClient\";\nimport { SqlError } from \"effect/unstable/sql/SqlError\";\n\nimport {\n DoAppendConflict,\n DoCheckpointConflict,\n DoFenceRejected,\n DoStorageCompatibilityError,\n DoStorageCorruptionError,\n DoStorageError,\n DoStorageFailpointError,\n DoValueBoundExceeded,\n type DoStorageFailpointLocation,\n} from \"./errors.ts\";\nimport { CurrentDoStorageVersion, doMigrations } from \"./migrations.ts\";\n\n/**\n * Static schema ceiling for stored text columns. Writes are bounded in BYTES by the\n * configured `maxStoredValueBytes` (always ≤ 2,000,000); UTF-8 byte length is never smaller\n * than UTF-16 string length, so any value that passed the byte bound also passes this\n * decode-side character ceiling.\n */\nconst BoundedStoredText = Schema.String.check(Schema.isMaxLength(2_000_000));\nconst BoundedIdentifier = Schema.NonEmptyString.check(Schema.isMaxLength(1024));\nconst MAX_RECORDS_PER_CONVERSATION = 65_536;\nconst MAX_IDENTIFIER_LENGTH = 1_024;\n/** Durable Object SQL storage allows at most 100 bound parameters per statement. */\nconst MAX_BOUND_PARAMETERS = 100;\n\nconst storedTextBytes = (value: string): number => new TextEncoder().encode(value).byteLength;\n\nconst chunked = <A>(values: ReadonlyArray<A>, size: number): Array<ReadonlyArray<A>> => {\n const chunks: Array<ReadonlyArray<A>> = [];\n for (let index = 0; index < values.length; index += size) {\n chunks.push(values.slice(index, index + size));\n }\n return chunks;\n};\n\nclass DoMetaRow extends Schema.Class<DoMetaRow>(\"DoMetaRow\")({\n value: Schema.NonEmptyString.check(Schema.isMaxLength(128)),\n}) {}\n\nclass DoNameRow extends Schema.Class<DoNameRow>(\"DoNameRow\")({\n name: BoundedIdentifier,\n}) {}\n\nclass ConversationRow extends Schema.Class<ConversationRow>(\"ConversationRow\")({\n conversation_id: BoundedIdentifier,\n created_at: Schema.NonEmptyString.check(Schema.isMaxLength(128)),\n producer_epoch: ProducerEpoch,\n tail_digest: BoundedStoredText,\n tail_sequence: CanonicalSequence,\n}) {}\n\nclass BatchRow extends Schema.Class<BatchRow>(\"BatchRow\")({\n batch_digest: BoundedStoredText,\n batch_id: BoundedIdentifier,\n batch_json: BoundedStoredText,\n conversation_id: BoundedIdentifier,\n first_sequence: CanonicalSequence,\n last_sequence: CanonicalSequence,\n tail_digest: BoundedStoredText,\n}) {}\n\nclass RecordRow extends Schema.Class<RecordRow>(\"RecordRow\")({\n batch_id: BoundedIdentifier,\n conversation_id: BoundedIdentifier,\n record_id: BoundedIdentifier,\n record_json: BoundedStoredText,\n sequence: CanonicalSequence,\n}) {}\n\nclass CheckpointRow extends Schema.Class<CheckpointRow>(\"CheckpointRow\")({\n checkpoint_json: BoundedStoredText,\n conversation_id: BoundedIdentifier,\n tail_digest: BoundedStoredText,\n through_sequence: CanonicalSequence,\n}) {}\n\nexport class RawRecord extends Schema.Class<RawRecord>(\n \"@effect-agent/storage-cloudflare/RawRecord\",\n)({\n recordId: BoundedIdentifier,\n recordJson: BoundedStoredText,\n}) {}\n\nexport class RawAppendRequest extends Schema.Class<RawAppendRequest>(\n \"@effect-agent/storage-cloudflare/RawAppendRequest\",\n)({\n batchDigest: BoundedStoredText,\n batchId: BoundedIdentifier,\n batchJson: BoundedStoredText,\n conversationId: BoundedIdentifier,\n expectedTailDigest: BoundedStoredText,\n expectedTailSequence: CanonicalSequence,\n producerEpoch: ProducerEpoch,\n records: Schema.NonEmptyArray(RawRecord).check(Schema.isMaxLength(256)),\n tailDigest: BoundedStoredText,\n}) {}\n\nexport class RawAppendResult extends Schema.Class<RawAppendResult>(\n \"@effect-agent/storage-cloudflare/RawAppendResult\",\n)({\n firstSequence: CanonicalSequence,\n lastSequence: CanonicalSequence,\n replayed: Schema.Boolean,\n tailDigest: BoundedStoredText,\n}) {}\n\nexport class RawReadRequest extends Schema.Class<RawReadRequest>(\n \"@effect-agent/storage-cloudflare/RawReadRequest\",\n)({\n conversationId: BoundedIdentifier,\n fromSequenceExclusive: CanonicalSequence,\n limit: Schema.Int.check(Schema.isGreaterThan(0), Schema.isLessThanOrEqualTo(1_024)),\n}) {}\n\nexport class RawCheckpoint extends Schema.Class<RawCheckpoint>(\n \"@effect-agent/storage-cloudflare/RawCheckpoint\",\n)({\n checkpointJson: BoundedStoredText,\n conversationId: BoundedIdentifier,\n tailDigest: BoundedStoredText,\n throughSequence: CanonicalSequence,\n}) {}\n\nexport class RawConversationExport extends Schema.Class<RawConversationExport>(\n \"@effect-agent/storage-cloudflare/RawConversationExport\",\n)({\n batches: Schema.Array(BatchRow),\n checkpoints: Schema.Array(CheckpointRow),\n conversation: ConversationRow,\n records: Schema.Array(RecordRow),\n}) {}\n\ntype AppendError =\n | DoAppendConflict\n | DoFenceRejected\n | DoStorageCorruptionError\n | DoStorageError\n | DoStorageFailpointError\n | DoValueBoundExceeded;\n\ntype CheckpointError =\n | DoCheckpointConflict\n | DoStorageCorruptionError\n | DoStorageError\n | DoValueBoundExceeded;\n\ntype DoJournalFailpoint = (\n location: DoStorageFailpointLocation,\n) => Effect.Effect<void, DoStorageFailpointError>;\n\nconst noFailpoint: DoJournalFailpoint = () => Effect.void;\n\nconst storageError =\n (operation: string) =>\n (error: SqlError): DoStorageError =>\n DoStorageError.make({\n cause: error,\n operation,\n message: error.message,\n });\n\n/** Decode raw Durable Object SQLite rows against a Schema, reporting failures as typed corruption. */\nexport const decodeRows = Effect.fn(\"DoJournal.decodeRows\")(\n <A, I>(\n schema: Schema.Codec<ReadonlyArray<A>, ReadonlyArray<I>>,\n table: string,\n rowKey: string,\n rows: unknown,\n ): Effect.Effect<ReadonlyArray<A>, DoStorageCorruptionError> =>\n Schema.decodeUnknownEffect(schema)(rows).pipe(\n Effect.mapError((error) =>\n DoStorageCorruptionError.make({\n table,\n rowKey,\n message: String(error),\n }),\n ),\n ),\n);\n\n/** Decode exactly one raw row against a Schema, reporting failures as typed corruption. */\nexport const decodeSingleRow = Effect.fn(\"DoJournal.decodeSingleRow\")(\n <A, I>(\n schema: Schema.Codec<ReadonlyArray<A>, ReadonlyArray<I>>,\n table: string,\n rowKey: string,\n rows: unknown,\n ): Effect.Effect<A, DoStorageCorruptionError> =>\n decodeRows(schema, table, rowKey, rows).pipe(\n Effect.flatMap((decoded) =>\n decoded.length === 1\n ? Effect.succeed(decoded[0])\n : Effect.fail(\n DoStorageCorruptionError.make({\n table,\n rowKey,\n message: `Expected exactly one row but found ${decoded.length}.`,\n }),\n ),\n ),\n ),\n);\n\nconst REQUIRED_TABLES = [\n \"effect_agent_abort_intents\",\n \"effect_agent_approval_decisions\",\n \"effect_agent_attempts\",\n \"effect_agent_canonical_batches\",\n \"effect_agent_canonical_records\",\n \"effect_agent_checkpoints\",\n \"effect_agent_child_reservations\",\n \"effect_agent_child_settlements\",\n \"effect_agent_conversations\",\n \"effect_agent_meta\",\n \"effect_agent_settlement_reservations\",\n \"effect_agent_submission_ownership\",\n \"effect_agent_submissions\",\n \"effect_agent_unknown_resolutions\",\n] as const;\n\n/**\n * Exact-or-fresh storage gate (DEPLOY-008) over `effect_agent_meta` instead of\n * `PRAGMA user_version` (unverified on Durable Object SQL storage; a meta table is portable\n * regardless). No WAL check (Durable Object storage owns durability and confirms writes\n * through output gates) and no busy timeout (a Durable Object has exactly one writer): the\n * Node machinery those served has no DC analogue and is deliberately absent.\n */\nconst ensureCurrentStorage = Effect.fn(\"DoJournal.ensureCurrentStorage\")(function* (\n sql: SqlClient.SqlClient,\n failpoint: DoJournalFailpoint = noFailpoint,\n maxStoredValueBytes: number,\n) {\n const metaTableRows = yield* sql<Record<string, unknown>>`\n SELECT name\n FROM sqlite_master\n WHERE type = 'table'\n AND name = 'effect_agent_meta'\n `.pipe(Effect.mapError(storageError(\"read storage version table\")));\n const metaTables = yield* decodeRows(\n Schema.Array(DoNameRow),\n \"sqlite_master\",\n \"effect_agent_meta\",\n metaTableRows,\n );\n\n if (metaTables.length === 0) {\n const existingRows = yield* sql<Record<string, unknown>>`\n SELECT name\n FROM sqlite_master\n WHERE type = 'table'\n AND name LIKE 'effect_agent_%'\n ORDER BY name\n `.pipe(Effect.mapError(storageError(\"inspect unversioned storage\")));\n const existing = yield* decodeRows(\n Schema.Array(DoNameRow),\n \"sqlite_master\",\n \"effect_agent_%\",\n existingRows,\n );\n\n if (existing.length > 0) {\n return yield* DoStorageCompatibilityError.make({\n actualVersion: 0,\n supportedVersion: CurrentDoStorageVersion,\n message:\n \"The Durable Object contains unversioned Effect Agent tables. Reset the development namespace explicitly; refusing to mutate ambiguous stored data.\",\n });\n }\n\n yield* SqliteMigrator.run({ loader: doMigrations }).pipe(\n // SqliteMigrator depends on the generic client supplied by this adapter. The concrete\n // Durable Object client is kept at the outer Layer boundary.\n Effect.provideService(SqlClient.SqlClient, sql),\n Effect.mapError((error) =>\n DoStorageError.make({\n cause: error,\n operation: \"initialize current storage\",\n message: error.message,\n }),\n ),\n );\n } else {\n const versionRows = yield* sql<Record<string, unknown>>`\n SELECT value\n FROM effect_agent_meta\n WHERE key = 'storage_version'\n `.pipe(Effect.mapError(storageError(\"read storage version\")));\n const version = yield* decodeSingleRow(\n Schema.Array(DoMetaRow),\n \"effect_agent_meta\",\n \"storage_version\",\n versionRows,\n );\n\n // The storage version must match EXACTLY. Older private-development versions fail\n // closed with reset guidance rather than being migrated, and newer versions fail closed\n // rather than being decoded incorrectly (DEPLOY-008).\n if (version.value !== String(CurrentDoStorageVersion)) {\n const actualVersion = Number.parseInt(version.value, 10);\n return yield* DoStorageCompatibilityError.make({\n actualVersion: Number.isSafeInteger(actualVersion) ? actualVersion : -1,\n supportedVersion: CurrentDoStorageVersion,\n message:\n `The Durable Object uses private-development storage version ${version.value}; ` +\n `this build supports exactly version ${CurrentDoStorageVersion}. ` +\n \"Replace the development namespace explicitly; automatic stored-data migrations are not provided during private development.\",\n });\n }\n }\n\n const requiredRows = yield* sql<Record<string, unknown>>`\n SELECT name\n FROM sqlite_master\n WHERE type = 'table'\n AND name IN ${sql.in([...REQUIRED_TABLES])}\n ORDER BY name\n `.pipe(Effect.mapError(storageError(\"verify storage tables\")));\n const required = yield* decodeRows(\n Schema.Array(DoNameRow),\n \"sqlite_master\",\n \"required_tables\",\n requiredRows,\n );\n if (required.length !== REQUIRED_TABLES.length) {\n return yield* DoStorageCompatibilityError.make({\n actualVersion: CurrentDoStorageVersion,\n supportedVersion: CurrentDoStorageVersion,\n message:\n \"The Durable Object claims the current format but is missing required tables. Reset the corrupt private-development data.\",\n });\n }\n\n return makeJournal(sql, failpoint, maxStoredValueBytes);\n});\n\nconst makeJournal = (\n sql: SqlClient.SqlClient,\n failpoint: DoJournalFailpoint,\n maxStoredValueBytes: number,\n) => {\n /** Typed pre-write refusal for any single value over the configured byte bound. */\n const checkValueBound = (\n operation: string,\n value: string,\n ): Effect.Effect<void, DoValueBoundExceeded> => {\n const actualBytes = storedTextBytes(value);\n return actualBytes > maxStoredValueBytes\n ? Effect.fail(\n DoValueBoundExceeded.make({\n actualBytes,\n maxBytes: maxStoredValueBytes,\n operation,\n }),\n )\n : Effect.void;\n };\n\n /**\n * Runs one journal write transaction on the Durable Object storage-backed\n * `withTransaction` (`ctx.storage.transaction()` under the hood). Within one Durable\n * Object there is exactly ONE writer, so the Node `BEGIN IMMEDIATE` + busy-retry +\n * `SqliteWriteContention` machinery has no analogue here and is deliberately absent.\n * Ownership-token and epoch checks still run INSIDE the transaction, so fencing atomicity\n * (DUR-006) is preserved identically.\n *\n * Journal write transactions are always top level: the Durable Object client rejects\n * nested transactions, so new journal operations must not wrap this helper inside another\n * transaction.\n */\n const withWriteTransaction =\n (operation: string) =>\n <A, E>(effect: Effect.Effect<A, E>): Effect.Effect<A, E | DoStorageError> =>\n sql.withTransaction(effect).pipe(\n Effect.mapError((error) =>\n error instanceof SqlError ? storageError(operation)(error) : error,\n ),\n Effect.withSpan(\"DoJournal.withWriteTransaction\", { attributes: { operation } }),\n );\n\n const materialize = Effect.fn(\"DoJournal.materialize\")(function* (\n conversationId: string,\n createdAt: string,\n emptyTailDigest: string,\n producerEpoch: ProducerEpoch,\n ): Effect.fn.Return<\n void,\n DoFenceRejected | DoStorageCorruptionError | DoStorageError | DoValueBoundExceeded\n > {\n if (conversationId.length > MAX_IDENTIFIER_LENGTH) {\n return yield* DoStorageError.make({\n operation: \"materialize conversation\",\n message: \"Conversation identity exceeds the Durable Object storage bounds.\",\n });\n }\n yield* checkValueBound(\"materialize conversation\", emptyTailDigest);\n yield* withWriteTransaction(\"materialize transaction\")(\n Effect.gen(function* () {\n const existingRows = yield* sql<Record<string, unknown>>`\n SELECT\n conversation_id,\n created_at,\n tail_sequence,\n tail_digest,\n producer_epoch\n FROM effect_agent_conversations\n WHERE conversation_id = ${conversationId}\n `.pipe(Effect.mapError(storageError(\"read materialized conversation\")));\n const existing = yield* decodeRows(\n Schema.Array(ConversationRow),\n \"effect_agent_conversations\",\n conversationId,\n existingRows,\n );\n if (existing.length > 1) {\n return yield* DoStorageCorruptionError.make({\n table: \"effect_agent_conversations\",\n rowKey: conversationId,\n message: \"A conversation primary key returned more than one row.\",\n });\n }\n if (existing.length === 0) {\n yield* sql`\n INSERT INTO effect_agent_conversations (\n conversation_id,\n created_at,\n tail_sequence,\n tail_digest,\n producer_epoch\n ) VALUES (\n ${conversationId},\n ${createdAt},\n 0,\n ${emptyTailDigest},\n ${producerEpoch}\n )\n `.pipe(Effect.mapError(storageError(\"materialize conversation\")));\n return;\n }\n if (producerEpoch < existing[0].producer_epoch) {\n return yield* DoFenceRejected.make({\n producerEpoch,\n actualEpoch: existing[0].producer_epoch,\n message: `Producer epoch ${producerEpoch} is stale; current epoch is ${existing[0].producer_epoch}.`,\n });\n }\n if (producerEpoch > existing[0].producer_epoch) {\n yield* sql`\n UPDATE effect_agent_conversations\n SET producer_epoch = ${producerEpoch}\n WHERE conversation_id = ${conversationId}\n `.pipe(Effect.mapError(storageError(\"advance materialization epoch\")));\n }\n }),\n );\n });\n\n const getConversation = Effect.fn(\"DoJournal.getConversation\")(function* (\n conversationId: string,\n ) {\n const rows = yield* sql<Record<string, unknown>>`\n SELECT\n conversation_id,\n created_at,\n tail_sequence,\n tail_digest,\n producer_epoch\n FROM effect_agent_conversations\n WHERE conversation_id = ${conversationId}\n `.pipe(Effect.mapError(storageError(\"read conversation\")));\n return yield* decodeRows(\n Schema.Array(ConversationRow),\n \"effect_agent_conversations\",\n conversationId,\n rows,\n );\n });\n\n const append = Effect.fn(\"DoJournal.append\")(function* (\n request: RawAppendRequest,\n ): Effect.fn.Return<RawAppendResult, AppendError> {\n if (\n request.conversationId.length > MAX_IDENTIFIER_LENGTH ||\n request.batchId.length > MAX_IDENTIFIER_LENGTH ||\n request.records.some((record) => record.recordId.length > MAX_IDENTIFIER_LENGTH)\n ) {\n return yield* DoStorageError.make({\n operation: \"append canonical batch\",\n message: \"Canonical identifiers exceed the Durable Object storage bounds.\",\n });\n }\n // The platform's ~2 MB per-value limit, enforced typed BEFORE any write (plan §1.2).\n yield* checkValueBound(\"append canonical batch\", request.batchJson);\n yield* checkValueBound(\"append canonical batch\", request.batchDigest);\n yield* checkValueBound(\"append canonical batch\", request.tailDigest);\n yield* Effect.forEach(\n request.records,\n (record) => checkValueBound(\"append canonical record\", record.recordJson),\n { discard: true },\n );\n return yield* withWriteTransaction(\"append transaction\")(\n Effect.gen(function* () {\n const recordIds = request.records.map((record) => record.recordId);\n if (new Set(recordIds).size !== recordIds.length) {\n return yield* DoAppendConflict.make({\n message: `Batch ${request.batchId} contains duplicate canonical record IDs.`,\n reason: \"record-identity\",\n });\n }\n\n const conversationRows = yield* sql<Record<string, unknown>>`\n SELECT\n conversation_id,\n created_at,\n tail_sequence,\n tail_digest,\n producer_epoch\n FROM effect_agent_conversations\n WHERE conversation_id = ${request.conversationId}\n `.pipe(Effect.mapError(storageError(\"read append tail\")));\n const conversation = yield* decodeSingleRow(\n Schema.Array(ConversationRow),\n \"effect_agent_conversations\",\n request.conversationId,\n conversationRows,\n );\n\n if (request.producerEpoch !== conversation.producer_epoch) {\n return yield* DoFenceRejected.make({\n producerEpoch: request.producerEpoch,\n actualEpoch: conversation.producer_epoch,\n message: `Producer epoch ${request.producerEpoch} is not the current epoch ${conversation.producer_epoch}.`,\n });\n }\n\n const batchRows = yield* sql<Record<string, unknown>>`\n SELECT\n conversation_id,\n batch_id,\n first_sequence,\n last_sequence,\n batch_digest,\n tail_digest,\n batch_json\n FROM effect_agent_canonical_batches\n WHERE conversation_id = ${request.conversationId}\n AND batch_id = ${request.batchId}\n `.pipe(Effect.mapError(storageError(\"read idempotent batch\")));\n const batches = yield* decodeRows(\n Schema.Array(BatchRow),\n \"effect_agent_canonical_batches\",\n `${request.conversationId}/${request.batchId}`,\n batchRows,\n );\n\n if (batches.length > 1) {\n return yield* DoStorageCorruptionError.make({\n table: \"effect_agent_canonical_batches\",\n rowKey: `${request.conversationId}/${request.batchId}`,\n message: \"A canonical batch primary key returned more than one row.\",\n });\n }\n if (batches.length === 1) {\n const existing = batches[0];\n if (existing.batch_digest !== request.batchDigest) {\n return yield* DoAppendConflict.make({\n message: `Batch ${request.batchId} already exists with different canonical content.`,\n reason: \"batch-digest\",\n });\n }\n return RawAppendResult.make({\n firstSequence: existing.first_sequence,\n lastSequence: existing.last_sequence,\n replayed: true,\n tailDigest: existing.tail_digest,\n });\n }\n\n if (\n request.expectedTailSequence !== conversation.tail_sequence ||\n request.expectedTailDigest !== conversation.tail_digest\n ) {\n return yield* DoAppendConflict.make({\n message:\n `Expected tail ${request.expectedTailSequence}/${request.expectedTailDigest} ` +\n `but found ${conversation.tail_sequence}/${conversation.tail_digest}.`,\n reason: \"tail\",\n actualTailSequence: conversation.tail_sequence,\n actualTailDigest: conversation.tail_digest,\n });\n }\n if (conversation.tail_sequence + request.records.length > MAX_RECORDS_PER_CONVERSATION) {\n return yield* DoStorageError.make({\n operation: \"append canonical batch\",\n message: `Conversation record limit ${MAX_RECORDS_PER_CONVERSATION} would be exceeded.`,\n });\n }\n\n // Chunked to respect the Durable Object platform's 100-bound-parameter statement\n // limit: a batch may carry up to 256 records.\n const existingRecords: Array<RecordRow> = [];\n for (const chunk of chunked(recordIds, MAX_BOUND_PARAMETERS - 10)) {\n const existingRecordRows = yield* sql<Record<string, unknown>>`\n SELECT\n conversation_id,\n sequence,\n record_id,\n batch_id,\n record_json\n FROM effect_agent_canonical_records\n WHERE conversation_id = ${request.conversationId}\n AND record_id IN ${sql.in([...chunk])}\n ORDER BY sequence\n `.pipe(Effect.mapError(storageError(\"check canonical record identities\")));\n existingRecords.push(\n ...(yield* decodeRows(\n Schema.Array(RecordRow),\n \"effect_agent_canonical_records\",\n `${request.conversationId}/record_ids`,\n existingRecordRows,\n )),\n );\n }\n if (existingRecords.length > 0) {\n return yield* DoAppendConflict.make({\n message: `Canonical record ID ${existingRecords[0].record_id} already exists.`,\n reason: \"record-identity\",\n });\n }\n\n const firstSequence = yield* Schema.decodeUnknownEffect(CanonicalSequence)(\n conversation.tail_sequence + 1,\n ).pipe(\n Effect.mapError((error) =>\n DoStorageError.make({\n cause: error,\n operation: \"append canonical batch\",\n message: error.message,\n }),\n ),\n );\n const lastSequence = yield* Schema.decodeUnknownEffect(CanonicalSequence)(\n firstSequence + request.records.length - 1,\n ).pipe(\n Effect.mapError((error) =>\n DoStorageError.make({\n cause: error,\n operation: \"append canonical batch\",\n message: error.message,\n }),\n ),\n );\n\n yield* sql`\n INSERT INTO effect_agent_canonical_batches (\n conversation_id,\n batch_id,\n first_sequence,\n last_sequence,\n batch_digest,\n tail_digest,\n batch_json\n ) VALUES (\n ${request.conversationId},\n ${request.batchId},\n ${firstSequence},\n ${lastSequence},\n ${request.batchDigest},\n ${request.tailDigest},\n ${request.batchJson}\n )\n `.pipe(Effect.mapError(storageError(\"insert canonical batch\")));\n yield* failpoint(\"append:after-batch-insert\");\n\n yield* Effect.forEach(\n request.records,\n (record, index) =>\n Effect.gen(function* () {\n yield* sql`\n INSERT INTO effect_agent_canonical_records (\n conversation_id,\n sequence,\n record_id,\n batch_id,\n record_json\n ) VALUES (\n ${request.conversationId},\n ${firstSequence + index},\n ${record.recordId},\n ${request.batchId},\n ${record.recordJson}\n )\n `.pipe(Effect.mapError(storageError(\"insert canonical record\")));\n yield* failpoint(\"append:after-record-insert\");\n }),\n { discard: true },\n );\n\n yield* sql`\n UPDATE effect_agent_conversations\n SET\n tail_sequence = ${lastSequence},\n tail_digest = ${request.tailDigest},\n producer_epoch = ${request.producerEpoch}\n WHERE conversation_id = ${request.conversationId}\n `.pipe(Effect.mapError(storageError(\"advance conversation tail\")));\n yield* failpoint(\"append:after-tail-update\");\n\n return RawAppendResult.make({\n firstSequence,\n lastSequence,\n replayed: false,\n tailDigest: request.tailDigest,\n });\n }),\n );\n });\n\n const read = Effect.fn(\"DoJournal.read\")(function* (request: RawReadRequest) {\n const rows = yield* sql<Record<string, unknown>>`\n SELECT\n conversation_id,\n sequence,\n record_id,\n batch_id,\n record_json\n FROM effect_agent_canonical_records\n WHERE conversation_id = ${request.conversationId}\n AND sequence > ${request.fromSequenceExclusive}\n ORDER BY sequence\n LIMIT ${request.limit}\n `.pipe(Effect.mapError(storageError(\"read canonical records\")));\n return yield* decodeRows(\n Schema.Array(RecordRow),\n \"effect_agent_canonical_records\",\n `${request.conversationId}>${request.fromSequenceExclusive}`,\n rows,\n );\n });\n\n const exportConversation = Effect.fn(\"DoJournal.exportConversation\")(function* (\n conversationId: string,\n ) {\n return yield* sql\n .withTransaction(\n Effect.gen(function* () {\n const conversationRows = yield* sql<Record<string, unknown>>`\n SELECT\n conversation_id,\n created_at,\n tail_sequence,\n tail_digest,\n producer_epoch\n FROM effect_agent_conversations\n WHERE conversation_id = ${conversationId}\n `.pipe(Effect.mapError(storageError(\"export conversation\")));\n const conversation = yield* decodeSingleRow(\n Schema.Array(ConversationRow),\n \"effect_agent_conversations\",\n conversationId,\n conversationRows,\n );\n yield* failpoint(\"export:after-conversation-read\");\n const batchRows = yield* sql<Record<string, unknown>>`\n SELECT\n conversation_id,\n batch_id,\n first_sequence,\n last_sequence,\n batch_digest,\n tail_digest,\n batch_json\n FROM effect_agent_canonical_batches\n WHERE conversation_id = ${conversationId}\n ORDER BY first_sequence\n `.pipe(Effect.mapError(storageError(\"export canonical batches\")));\n const recordRows = yield* sql<Record<string, unknown>>`\n SELECT\n conversation_id,\n sequence,\n record_id,\n batch_id,\n record_json\n FROM effect_agent_canonical_records\n WHERE conversation_id = ${conversationId}\n ORDER BY sequence\n `.pipe(Effect.mapError(storageError(\"export canonical records\")));\n const checkpointRows = yield* sql<Record<string, unknown>>`\n SELECT\n conversation_id,\n through_sequence,\n tail_digest,\n checkpoint_json\n FROM effect_agent_checkpoints\n WHERE conversation_id = ${conversationId}\n ORDER BY through_sequence\n `.pipe(Effect.mapError(storageError(\"export checkpoints\")));\n\n return RawConversationExport.make({\n conversation,\n batches: yield* decodeRows(\n Schema.Array(BatchRow),\n \"effect_agent_canonical_batches\",\n conversationId,\n batchRows,\n ),\n records: yield* decodeRows(\n Schema.Array(RecordRow),\n \"effect_agent_canonical_records\",\n conversationId,\n recordRows,\n ),\n checkpoints: yield* decodeRows(\n Schema.Array(CheckpointRow),\n \"effect_agent_checkpoints\",\n conversationId,\n checkpointRows,\n ),\n });\n }),\n )\n .pipe(\n Effect.catchTag(\"SqlError\", (error) =>\n Effect.fail(storageError(\"export transaction\")(error)),\n ),\n );\n });\n\n const saveCheckpoint = Effect.fn(\"DoJournal.saveCheckpoint\")(function* (\n checkpoint: RawCheckpoint,\n ): Effect.fn.Return<void, CheckpointError> {\n if (checkpoint.conversationId.length > MAX_IDENTIFIER_LENGTH) {\n return yield* DoStorageError.make({\n operation: \"save checkpoint\",\n message: \"Checkpoint identity exceeds the Durable Object storage bounds.\",\n });\n }\n yield* checkValueBound(\"save checkpoint\", checkpoint.checkpointJson);\n yield* withWriteTransaction(\"checkpoint transaction\")(\n Effect.gen(function* () {\n const conversationRows = yield* sql<Record<string, unknown>>`\n SELECT\n conversation_id,\n created_at,\n tail_sequence,\n tail_digest,\n producer_epoch\n FROM effect_agent_conversations\n WHERE conversation_id = ${checkpoint.conversationId}\n `.pipe(Effect.mapError(storageError(\"read checkpoint tail\")));\n const conversation = yield* decodeSingleRow(\n Schema.Array(ConversationRow),\n \"effect_agent_conversations\",\n checkpoint.conversationId,\n conversationRows,\n );\n if (checkpoint.throughSequence > conversation.tail_sequence) {\n return yield* DoCheckpointConflict.make({\n message:\n `Checkpoint sequence ${checkpoint.throughSequence} is after canonical tail ` +\n `${conversation.tail_sequence}.`,\n });\n }\n\n const checkpointRows = yield* sql<Record<string, unknown>>`\n SELECT\n conversation_id,\n through_sequence,\n tail_digest,\n checkpoint_json\n FROM effect_agent_checkpoints\n WHERE conversation_id = ${checkpoint.conversationId}\n AND through_sequence = ${checkpoint.throughSequence}\n `.pipe(Effect.mapError(storageError(\"read idempotent checkpoint\")));\n const existing = yield* decodeRows(\n Schema.Array(CheckpointRow),\n \"effect_agent_checkpoints\",\n `${checkpoint.conversationId}/${checkpoint.throughSequence}`,\n checkpointRows,\n );\n if (existing.length > 1) {\n return yield* DoStorageCorruptionError.make({\n table: \"effect_agent_checkpoints\",\n rowKey: `${checkpoint.conversationId}/${checkpoint.throughSequence}`,\n message: \"A checkpoint primary key returned more than one row.\",\n });\n }\n if (existing.length === 1) {\n if (\n existing[0].tail_digest !== checkpoint.tailDigest ||\n existing[0].checkpoint_json !== checkpoint.checkpointJson\n ) {\n return yield* DoCheckpointConflict.make({\n message: \"A different checkpoint already exists at this canonical sequence.\",\n });\n }\n return;\n }\n\n yield* sql`\n INSERT INTO effect_agent_checkpoints (\n conversation_id,\n through_sequence,\n tail_digest,\n checkpoint_json\n ) VALUES (\n ${checkpoint.conversationId},\n ${checkpoint.throughSequence},\n ${checkpoint.tailDigest},\n ${checkpoint.checkpointJson}\n )\n `.pipe(Effect.mapError(storageError(\"insert checkpoint\")));\n }),\n );\n });\n\n const loadCheckpoint = Effect.fn(\"DoJournal.loadCheckpoint\")(function* (\n conversationId: string,\n atOrBeforeSequence: CanonicalSequence,\n ) {\n const rows = yield* sql<Record<string, unknown>>`\n SELECT\n conversation_id,\n through_sequence,\n tail_digest,\n checkpoint_json\n FROM effect_agent_checkpoints\n WHERE conversation_id = ${conversationId}\n AND through_sequence <= ${atOrBeforeSequence}\n ORDER BY through_sequence DESC\n LIMIT 1\n `.pipe(Effect.mapError(storageError(\"load checkpoint\")));\n return yield* decodeRows(\n Schema.Array(CheckpointRow),\n \"effect_agent_checkpoints\",\n `${conversationId}<=${atOrBeforeSequence}`,\n rows,\n );\n });\n\n const getTailDigestAt = Effect.fn(\"DoJournal.getTailDigestAt\")(function* (\n conversationId: string,\n sequence: CanonicalSequence,\n ) {\n if (sequence === 0) {\n const conversations = yield* getConversation(conversationId);\n return conversations.length === 0\n ? []\n : [conversations[0].tail_sequence === 0 ? conversations[0].tail_digest : undefined].filter(\n (value): value is string => value !== undefined,\n );\n }\n const rows = yield* sql<Record<string, unknown>>`\n SELECT\n conversation_id,\n batch_id,\n first_sequence,\n last_sequence,\n batch_digest,\n tail_digest,\n batch_json\n FROM effect_agent_canonical_batches\n WHERE conversation_id = ${conversationId}\n AND last_sequence = ${sequence}\n `.pipe(Effect.mapError(storageError(\"read canonical digest at sequence\")));\n const batches = yield* decodeRows(\n Schema.Array(BatchRow),\n \"effect_agent_canonical_batches\",\n `${conversationId}/${sequence}`,\n rows,\n );\n return batches.map((batch) => batch.tail_digest);\n });\n\n const scanStoredPayloads = Effect.fn(\"DoJournal.scanStoredPayloads\")(function* () {\n return yield* sql\n .withTransaction(\n Effect.gen(function* () {\n const conversations = yield* sql<Record<string, unknown>>`\n SELECT\n conversation_id,\n created_at,\n tail_sequence,\n tail_digest,\n producer_epoch\n FROM effect_agent_conversations\n ORDER BY conversation_id\n `.pipe(Effect.mapError(storageError(\"scan conversations\")));\n const batches = yield* sql<Record<string, unknown>>`\n SELECT\n conversation_id,\n batch_id,\n first_sequence,\n last_sequence,\n batch_digest,\n tail_digest,\n batch_json\n FROM effect_agent_canonical_batches\n ORDER BY conversation_id, first_sequence\n `.pipe(Effect.mapError(storageError(\"scan canonical batches\")));\n const records = yield* sql<Record<string, unknown>>`\n SELECT\n conversation_id,\n sequence,\n record_id,\n batch_id,\n record_json\n FROM effect_agent_canonical_records\n ORDER BY conversation_id, sequence\n `.pipe(Effect.mapError(storageError(\"scan canonical records\")));\n const checkpoints = yield* sql<Record<string, unknown>>`\n SELECT\n conversation_id,\n through_sequence,\n tail_digest,\n checkpoint_json\n FROM effect_agent_checkpoints\n ORDER BY conversation_id, through_sequence\n `.pipe(Effect.mapError(storageError(\"scan checkpoints\")));\n return {\n conversations: yield* decodeRows(\n Schema.Array(ConversationRow),\n \"effect_agent_conversations\",\n \"startup_scan\",\n conversations,\n ),\n batches: yield* decodeRows(\n Schema.Array(BatchRow),\n \"effect_agent_canonical_batches\",\n \"startup_scan\",\n batches,\n ),\n records: yield* decodeRows(\n Schema.Array(RecordRow),\n \"effect_agent_canonical_records\",\n \"startup_scan\",\n records,\n ),\n checkpoints: yield* decodeRows(\n Schema.Array(CheckpointRow),\n \"effect_agent_checkpoints\",\n \"startup_scan\",\n checkpoints,\n ),\n };\n }),\n )\n .pipe(\n Effect.catchTag(\"SqlError\", (error) =>\n Effect.fail(storageError(\"startup scan transaction\")(error)),\n ),\n );\n });\n\n return {\n append,\n checkValueBound,\n exportConversation,\n getConversation,\n getTailDigestAt,\n loadCheckpoint,\n materialize,\n read,\n saveCheckpoint,\n scanStoredPayloads,\n withWriteTransaction,\n } as const;\n};\n\nexport type DoJournal = ReturnType<typeof makeJournal>;\n\nexport const initializeDoJournal = ensureCurrentStorage;\n","import { Context, Schema } from \"effect\";\n\nconst ObservationPollInterval = Schema.Int.check(Schema.isGreaterThanOrEqualTo(0));\nconst OwnershipLeaseMillis = Schema.Int.check(Schema.isGreaterThan(0));\n\n/**\n * Default per-value byte bound, kept under the Durable Object platform's 2 MB SQLite value\n * limit with a safety margin. This is the DC analogue of Node's 16 MB `BoundedStoredText`\n * bound: both fail typed before mutating, only the threshold differs (a documented DN/DC\n * behavioral difference; Travel Planner payloads sit orders of magnitude below both).\n */\nexport const DEFAULT_MAX_STORED_VALUE_BYTES = 1_900_000;\n\n/** The hard schema ceiling for the configurable bound: never at or above the platform limit. */\nconst MaxStoredValueBytes = Schema.Int.check(\n Schema.isGreaterThan(0),\n Schema.isLessThanOrEqualTo(2_000_000),\n);\n\n/**\n * Validated construction configuration consumed by the Durable Object storage Layers. The\n * storage identity itself belongs to the SqlClient Layer (built from `ctx.storage`);\n * duplicating it here could silently diverge from the handle actually in use.\n */\nexport class DoStorageConfigValue extends Schema.Class<DoStorageConfigValue>(\n \"@effect-agent/storage-cloudflare/DoStorageConfigValue\",\n)({\n observationPollInterval: ObservationPollInterval,\n /**\n * Submission ownership lease duration in milliseconds (D5). Inside one Durable Object the\n * object itself is the serialized owner, so the lease's primary DC role is fencing work\n * across DO incarnations (an evicted incarnation's claim becomes reclaimable); correctness\n * never depends on it because every canonical append is fenced by producer epoch.\n */\n ownershipLeaseDuration: OwnershipLeaseMillis,\n /**\n * Maximum bytes for any single stored text value (canonical batch/record JSON, admission\n * input payload, checkpoint JSON). Enforced typed BEFORE any write; must stay under the\n * platform's 2 MB per-value limit.\n */\n maxStoredValueBytes: MaxStoredValueBytes,\n /**\n * Re-verify every stored payload and digest chain while opening the store. Per-operation\n * Schema decoding and the digest chain already fail clearly on corrupt rows, so the full\n * scan is an explicit opt-in integrity audit rather than a startup requirement.\n */\n verifyOnOpen: Schema.Boolean,\n}) {}\n\n/** Explicit Durable Object storage configuration authority. */\nexport class DoStorageConfig extends Context.Service<DoStorageConfig, DoStorageConfigValue>()(\n \"@effect-agent/storage-cloudflare/DoStorageConfig\",\n) {}\n","import { Context, Effect, Layer, Ref } from \"effect\";\n\nimport { DoStorageFailpointError, type DoStorageFailpointLocation } from \"./errors.ts\";\n\nexport type DoStorageFailpointHandler = (\n location: DoStorageFailpointLocation,\n) => Effect.Effect<void, DoStorageFailpointError>;\n\nconst noFailpoint: DoStorageFailpointHandler = () => Effect.void;\n\n/** Test-only control for replacing the active Durable Object failpoint handler. */\nexport class DoStorageFailpointTestControl extends Context.Service<\n DoStorageFailpointTestControl,\n {\n readonly clear: Effect.Effect<void>;\n readonly setHandler: (handler: DoStorageFailpointHandler) => Effect.Effect<void>;\n }\n>()(\"@effect-agent/storage-cloudflare/DoStorageFailpointTestControl\") {}\n\n/** Explicit fault-injection authority used at Durable Object storage operation boundaries. */\nexport class DoStorageFailpoint extends Context.Service<\n DoStorageFailpoint,\n {\n readonly hit: DoStorageFailpointHandler;\n }\n>()(\"@effect-agent/storage-cloudflare/DoStorageFailpoint\") {\n /** Production default: no fault injection. */\n static readonly layer = Layer.succeed(this)({ hit: noFailpoint });\n\n /** Reusable test Layer with a control service backed by the same handler Ref. */\n static readonly layerTest = Layer.effectContext(\n Effect.gen(function* () {\n const handler = yield* Ref.make<DoStorageFailpointHandler>(noFailpoint);\n return Context.make(\n DoStorageFailpoint,\n DoStorageFailpoint.of({\n hit: (location) => Ref.get(handler).pipe(Effect.flatMap((current) => current(location))),\n }),\n ).pipe(\n Context.add(\n DoStorageFailpointTestControl,\n DoStorageFailpointTestControl.of({\n clear: Ref.set(handler, noFailpoint),\n setHandler: (next) => Ref.set(handler, next),\n }),\n ),\n );\n }),\n );\n}\n\n/**\n * The DC-specific eviction failpoint mode: instead of failing typed, an armed hit evicts the\n * Durable Object through an injected `evict` thunk — in production-shaped harnesses that thunk\n * is `() => ctx.abort()`, the platform's real failure mode. `ctx.abort()` never returns (it\n * throws while destroying the in-memory instance and every in-flight implicit or explicit\n * storage transaction rolls back), so an armed hit ends the current Attempt exactly like an\n * unannounced platform eviction; DO storage — the only correctness-critical state — survives\n * for the next incarnation, which the persisted alarm wakes without any incoming request.\n *\n * The handles stay injected: this package never imports `cloudflare:workers`, so the harness\n * that owns a `DurableObjectState` supplies the thunk.\n */\nexport const evictionFailpointHandler =\n (options: {\n readonly isArmed: (location: DoStorageFailpointLocation) => Effect.Effect<boolean>;\n /** Kills the incarnation — e.g. `() => ctx.abort()`. Typed `void` because the platform\n * declares `abort` as returning, but it throws while destroying the instance. */\n readonly evict: (location: DoStorageFailpointLocation) => void;\n }): DoStorageFailpointHandler =>\n (location) =>\n options.isArmed(location).pipe(\n Effect.flatMap((armed) =>\n armed\n ? // `ctx.abort()` throws while destroying the instance; that throw surfaces as a\n // defect in the (already dying) incarnation. The defensive throw below keeps the\n // guarantee — nothing after an armed hit may observe in-memory state — even if a\n // harness supplies an evict thunk that returns.\n Effect.sync((): never => {\n options.evict(location);\n throw new Error(\n `Durable Object eviction did not interrupt execution at ${location}.`,\n );\n })\n : Effect.void,\n ),\n );\n","import {\n AppendConflict,\n AppendResult,\n CanonicalBatch,\n CanonicalRecord,\n CanonicalRecordEnvelope,\n CanonicalSequence,\n CheckpointRejected,\n ConversationCheckpoint,\n ConversationExport,\n ConversationExportRequest,\n ConversationMaterialization,\n ConversationNotMaterialized,\n ConversationObservation,\n ConversationRead,\n ConversationStore,\n ConversationStoreError,\n ConversationTail,\n ConversationTailRequest,\n DEFAULT_OWNERSHIP_LEASE_DURATION,\n digestCanonicalBatch,\n Digest,\n EMPTY_TAIL_DIGEST,\n FenceRejected,\n FencedAppendRequest,\n LoadCheckpointRequest,\n ObservationOffset,\n SaveCheckpointRequest,\n} from \"@effect-agent/session\";\nimport { BrowserCrypto } from \"@effect/platform-browser\";\nimport { SqliteClient } from \"@effect/sql-sqlite-do\";\nimport {\n Clock,\n Context,\n Crypto,\n Duration,\n Effect,\n Layer,\n Option,\n Ref,\n Schema,\n Stream,\n} from \"effect\";\nimport * as SqlClientService from \"effect/unstable/sql/SqlClient\";\n\nimport {\n initializeDoJournal,\n RawAppendRequest,\n RawCheckpoint,\n RawReadRequest,\n type DoJournal,\n} from \"./do-journal.ts\";\nimport {\n DEFAULT_MAX_STORED_VALUE_BYTES,\n DoStorageConfig,\n DoStorageConfigValue,\n} from \"./do-storage-config.ts\";\nimport { DoStorageFailpoint, type DoStorageFailpointHandler } from \"./do-storage-failpoint.ts\";\nimport {\n DoAppendConflict,\n DoCheckpointConflict,\n DoFenceRejected,\n type DoStorageFailpointLocation,\n DoStorageCompatibilityError,\n DoStorageCorruptionError,\n DoStorageError,\n} from \"./errors.ts\";\n\n/**\n * Convenience-layer construction options. `storage` is the Durable Object's own\n * `ctx.storage` handle, injected as a value (DEPLOY-010: platform bindings enter only\n * through Layers; this package never imports `cloudflare:workers`).\n */\nexport interface DoStorageOptions {\n readonly storage: DurableObjectStorage;\n readonly observationPollInterval?: number | undefined;\n /**\n * Submission ownership lease duration in milliseconds (D5). Defaults to\n * `DEFAULT_OWNERSHIP_LEASE_DURATION` from `@effect-agent/session`.\n */\n readonly ownershipLeaseDuration?: number | undefined;\n /**\n * Maximum bytes for any single stored value; must stay under the platform's 2 MB\n * per-value limit. Defaults to `DEFAULT_MAX_STORED_VALUE_BYTES`.\n */\n readonly maxStoredValueBytes?: number | undefined;\n /**\n * Re-verify every stored payload and digest chain while opening the store. Defaults to\n * off: per-operation Schema decoding and the digest chain already fail clearly on corrupt\n * rows without scanning the whole database on every open.\n */\n readonly verifyOnOpen?: boolean | undefined;\n readonly failpoint?: DoStorageFailpointHandler | undefined;\n}\n\nexport type DoStorageInitializationError =\n | DoStorageCompatibilityError\n | DoStorageCorruptionError\n | DoStorageError;\n\nconst OffsetText = Schema.String.check(Schema.isMaxLength(4 * 1024));\nconst DO_OFFSET_PREFIX = \"effect-agent-do@1:\";\nconst ZERO_CANONICAL_SEQUENCE = Schema.decodeSync(CanonicalSequence)(0);\nconst isDigest = Schema.is(Digest);\n\nconst storeError = (operation: string, error: { readonly message: string }) =>\n ConversationStoreError.make({\n cause: error,\n operation,\n message: error.message,\n });\n\nconst schemaStoreError = (operation: string, error: { readonly message: string }) =>\n ConversationStoreError.make({\n cause: error,\n operation,\n message: error.message,\n });\n\nconst makeOffset = Effect.fn(\"DoConversationStore.makeOffset\")(function* (\n conversationId: ConversationMaterialization[\"conversationId\"],\n sequence: number,\n): Effect.fn.Return<ObservationOffset, ConversationStoreError> {\n return yield* Schema.decodeUnknownEffect(CanonicalSequence)(sequence).pipe(\n Effect.flatMap((validatedSequence) =>\n Schema.decodeUnknownEffect(ObservationOffset)(\n `${DO_OFFSET_PREFIX}${encodeURIComponent(conversationId)}:${validatedSequence}`,\n ),\n ),\n Effect.mapError((error) => schemaStoreError(\"encode observation offset\", error)),\n );\n});\n\nconst parseOffset = Effect.fn(\"DoConversationStore.parseOffset\")(function* (\n conversationId: ConversationMaterialization[\"conversationId\"],\n offset: ObservationOffset | undefined,\n): Effect.fn.Return<CanonicalSequence, ConversationStoreError> {\n if (offset === undefined) return ZERO_CANONICAL_SEQUENCE;\n const text = yield* Schema.decodeUnknownEffect(OffsetText)(offset).pipe(\n Effect.mapError((error) => schemaStoreError(\"decode observation offset\", error)),\n );\n const conversationPrefix = `${DO_OFFSET_PREFIX}${encodeURIComponent(conversationId)}:`;\n if (!text.startsWith(conversationPrefix)) {\n return yield* ConversationStoreError.make({\n operation: \"decode observation offset\",\n message:\n \"The observation offset belongs to a different adapter, storage version, or Conversation.\",\n });\n }\n const sequenceText = text.slice(conversationPrefix.length);\n if (!/^(0|[1-9][0-9]*)$/.test(sequenceText)) {\n return yield* ConversationStoreError.make({\n operation: \"decode observation offset\",\n message: \"The observation offset is malformed.\",\n });\n }\n return yield* Schema.decodeUnknownEffect(CanonicalSequence)(Number(sequenceText)).pipe(\n Effect.mapError((error) => schemaStoreError(\"decode observation offset\", error)),\n );\n});\n\nconst mapFence = (\n conversationId: ConversationMaterialization[\"conversationId\"],\n error: DoFenceRejected,\n) =>\n FenceRejected.make({\n conversationId,\n actualEpoch: error.actualEpoch,\n attemptedEpoch: error.producerEpoch,\n });\n\nconst encodeCanonicalRecord = Effect.fn(\"DoConversationStore.encodeCanonicalRecord\")(function* (\n record: CanonicalRecord,\n): Effect.fn.Return<string, ConversationStoreError> {\n return yield* Schema.encodeEffect(Schema.fromJsonString(CanonicalRecord))(record).pipe(\n Effect.mapError((error) => schemaStoreError(\"encode canonical record\", error)),\n );\n});\n\nconst encodeCanonicalBatch = Effect.fn(\"DoConversationStore.encodeCanonicalBatch\")(function* (\n batch: CanonicalBatch,\n): Effect.fn.Return<string, ConversationStoreError> {\n return yield* Schema.encodeEffect(Schema.fromJsonString(CanonicalBatch))(batch).pipe(\n Effect.mapError((error) => schemaStoreError(\"encode canonical batch\", error)),\n );\n});\n\nconst encodeCheckpoint = Effect.fn(\"DoConversationStore.encodeCheckpoint\")(function* (\n checkpoint: ConversationCheckpoint,\n): Effect.fn.Return<string, ConversationStoreError> {\n return yield* Schema.encodeEffect(Schema.fromJsonString(ConversationCheckpoint))(checkpoint).pipe(\n Effect.mapError((error) => schemaStoreError(\"encode checkpoint\", error)),\n );\n});\n\nconst decodeEnvelope = Effect.fn(\"DoConversationStore.decodeEnvelope\")(function* (row: {\n readonly batch_id: string;\n readonly conversation_id: string;\n readonly record_json: string;\n readonly sequence: CanonicalSequence;\n}) {\n const record = yield* Schema.decodeEffect(Schema.fromJsonString(CanonicalRecord))(\n row.record_json,\n ).pipe(\n Effect.mapError((error) =>\n ConversationStoreError.make({\n operation: \"decode canonical record\",\n message: error.message,\n }),\n ),\n );\n const conversationId = yield* Schema.decodeUnknownEffect(\n CanonicalRecordEnvelope.fields.conversationId,\n )(row.conversation_id).pipe(\n Effect.mapError((error) => schemaStoreError(\"decode conversation identity\", error)),\n );\n const offset = yield* makeOffset(conversationId, row.sequence);\n const batchId = yield* Schema.decodeUnknownEffect(CanonicalRecordEnvelope.fields.batchId)(\n row.batch_id,\n ).pipe(Effect.mapError((error) => schemaStoreError(\"decode batch identity\", error)));\n return CanonicalRecordEnvelope.make({\n conversationId,\n batchId,\n sequence: row.sequence,\n offset,\n record,\n });\n});\n\nconst decodeCheckpoint = Effect.fn(\"DoConversationStore.decodeCheckpoint\")(function* (\n checkpointJson: string,\n): Effect.fn.Return<ConversationCheckpoint, ConversationStoreError> {\n return yield* Schema.decodeEffect(Schema.fromJsonString(ConversationCheckpoint))(\n checkpointJson,\n ).pipe(Effect.mapError((error) => schemaStoreError(\"decode checkpoint\", error)));\n});\n\nconst requireConversation = Effect.fn(\"DoConversationStore.requireConversation\")(function* (\n journal: DoJournal,\n conversationId: ConversationMaterialization[\"conversationId\"],\n) {\n const rows = yield* journal\n .getConversation(conversationId)\n .pipe(Effect.mapError((error) => storeError(\"read conversation\", error)));\n if (rows.length === 0) {\n return yield* ConversationNotMaterialized.make({ conversationId });\n }\n return rows[0];\n});\n\nconst tailDigestAt = Effect.fn(\"DoConversationStore.tailDigestAt\")(function* (\n journal: DoJournal,\n conversationId: ConversationMaterialization[\"conversationId\"],\n sequence: CanonicalSequence,\n) {\n if (sequence === 0) return EMPTY_TAIL_DIGEST;\n const digests = yield* journal\n .getTailDigestAt(conversationId, sequence)\n .pipe(Effect.mapError((error) => storeError(\"read checkpoint digest\", error)));\n if (digests.length !== 1) {\n return yield* CheckpointRejected.make({\n conversationId,\n reason: \"digest-mismatch\",\n });\n }\n return yield* Schema.decodeUnknownEffect(Digest)(digests[0]).pipe(\n Effect.mapError((error) => schemaStoreError(\"decode checkpoint digest\", error)),\n );\n});\n\nconst groupByKey = <A>(\n rows: ReadonlyArray<A>,\n key: (row: A) => string,\n): ReadonlyMap<string, ReadonlyArray<A>> => {\n const grouped = new Map<string, Array<A>>();\n for (const row of rows) {\n const existing = grouped.get(key(row));\n if (existing === undefined) {\n grouped.set(key(row), [row]);\n } else {\n existing.push(row);\n }\n }\n return grouped;\n};\n\n/**\n * Opt-in full integrity audit (`verifyOnOpen`). Every stored payload is decoded, re-encoded,\n * and re-digested against the canonical chain. Routine opens skip this scan: per-operation\n * Schema decoding plus the digest chain already fail clearly on corrupt rows.\n */\nconst decodeStartupPayloads = Effect.fn(\"DoConversationStore.decodeStartupPayloads\")(function* (\n journal: DoJournal,\n crypto: Crypto.Crypto,\n) {\n const stored = yield* journal.scanStoredPayloads();\n const batches = yield* Effect.forEach(stored.batches, (batch) =>\n Schema.decodeEffect(Schema.fromJsonString(CanonicalBatch))(batch.batch_json).pipe(\n Effect.map((decoded) => ({ decoded, row: batch })),\n Effect.mapError((error) =>\n DoStorageCorruptionError.make({\n table: \"effect_agent_canonical_batches\",\n rowKey: `${batch.conversation_id}/${batch.batch_id}`,\n message: error.message,\n }),\n ),\n ),\n );\n const records = yield* Effect.forEach(stored.records, (record) =>\n Schema.decodeEffect(Schema.fromJsonString(CanonicalRecord))(record.record_json).pipe(\n Effect.map((decoded) => ({ decoded, row: record })),\n Effect.mapError((error) =>\n DoStorageCorruptionError.make({\n table: \"effect_agent_canonical_records\",\n rowKey: `${record.conversation_id}/${record.sequence}`,\n message: error.message,\n }),\n ),\n ),\n );\n const checkpoints = yield* Effect.forEach(stored.checkpoints, (checkpoint) =>\n Schema.decodeEffect(Schema.fromJsonString(ConversationCheckpoint))(\n checkpoint.checkpoint_json,\n ).pipe(\n Effect.map((decoded) => ({ decoded, row: checkpoint })),\n Effect.mapError((error) =>\n DoStorageCorruptionError.make({\n table: \"effect_agent_checkpoints\",\n rowKey: `${checkpoint.conversation_id}/${checkpoint.through_sequence}`,\n message: error.message,\n }),\n ),\n ),\n );\n\n const batchesByConversation = groupByKey(batches, ({ row }) => row.conversation_id);\n const recordsByConversation = groupByKey(records, ({ row }) => row.conversation_id);\n const checkpointsByConversation = groupByKey(checkpoints, ({ row }) => row.conversation_id);\n const materializedIds = new Set(\n stored.conversations.map((conversation) => conversation.conversation_id),\n );\n\n for (const conversation of stored.conversations) {\n const conversationBatches = batchesByConversation.get(conversation.conversation_id) ?? [];\n const conversationRecords = recordsByConversation.get(conversation.conversation_id) ?? [];\n const conversationCheckpoints =\n checkpointsByConversation.get(conversation.conversation_id) ?? [];\n const recordsByBatch = groupByKey(conversationRecords, ({ row }) => row.batch_id);\n let previousDigest = EMPTY_TAIL_DIGEST;\n let expectedSequence = 1;\n const tailDigests = new Map<number, string>([[0, EMPTY_TAIL_DIGEST]]);\n\n for (const { decoded: canonicalBatch, row: batchRow } of conversationBatches) {\n const key = `${batchRow.conversation_id}/${batchRow.batch_id}`;\n if (\n canonicalBatch.batchId !== batchRow.batch_id ||\n batchRow.first_sequence !== expectedSequence ||\n batchRow.last_sequence !== batchRow.first_sequence + canonicalBatch.records.length - 1\n ) {\n return yield* DoStorageCorruptionError.make({\n table: \"effect_agent_canonical_batches\",\n rowKey: key,\n message: \"Canonical batch identity, sequence, or record count is inconsistent.\",\n });\n }\n\n const digest = yield* digestCanonicalBatch(previousDigest, canonicalBatch).pipe(\n Effect.provideService(Crypto.Crypto, crypto),\n Effect.mapError((error) =>\n DoStorageCorruptionError.make({\n table: \"effect_agent_canonical_batches\",\n rowKey: key,\n message: error.message,\n }),\n ),\n );\n if (batchRow.batch_digest !== digest || batchRow.tail_digest !== digest) {\n return yield* DoStorageCorruptionError.make({\n table: \"effect_agent_canonical_batches\",\n rowKey: key,\n message: \"Canonical batch digest does not match its decoded content and prior tail.\",\n });\n }\n\n const batchRecords = recordsByBatch.get(batchRow.batch_id) ?? [];\n if (batchRecords.length !== canonicalBatch.records.length) {\n return yield* DoStorageCorruptionError.make({\n table: \"effect_agent_canonical_records\",\n rowKey: key,\n message: \"Canonical batch and record-table counts differ.\",\n });\n }\n for (let index = 0; index < canonicalBatch.records.length; index++) {\n const expectedRecord = canonicalBatch.records[index];\n const storedRecord = batchRecords[index];\n const expectedJson = yield* Schema.encodeEffect(Schema.fromJsonString(CanonicalRecord))(\n expectedRecord,\n ).pipe(\n Effect.mapError((error) =>\n DoStorageCorruptionError.make({\n table: \"effect_agent_canonical_batches\",\n rowKey: key,\n message: error.message,\n }),\n ),\n );\n const storedJson = yield* Schema.encodeEffect(Schema.fromJsonString(CanonicalRecord))(\n storedRecord.decoded,\n ).pipe(\n Effect.mapError((error) =>\n DoStorageCorruptionError.make({\n table: \"effect_agent_canonical_records\",\n rowKey: `${key}/${storedRecord.row.sequence}`,\n message: error.message,\n }),\n ),\n );\n if (\n storedRecord.row.sequence !== batchRow.first_sequence + index ||\n storedRecord.row.record_id !== expectedRecord.recordId ||\n expectedJson !== storedJson\n ) {\n return yield* DoStorageCorruptionError.make({\n table: \"effect_agent_canonical_records\",\n rowKey: `${key}/${storedRecord.row.sequence}`,\n message: \"Canonical record identity, sequence, or payload differs from its batch.\",\n });\n }\n }\n\n previousDigest = digest;\n expectedSequence = batchRow.last_sequence + 1;\n tailDigests.set(batchRow.last_sequence, digest);\n }\n\n if (\n conversationRecords.length !== conversation.tail_sequence ||\n conversation.tail_sequence !== expectedSequence - 1 ||\n conversation.tail_digest !== previousDigest\n ) {\n return yield* DoStorageCorruptionError.make({\n table: \"effect_agent_conversations\",\n rowKey: conversation.conversation_id,\n message: \"Conversation tail does not match its canonical batch chain.\",\n });\n }\n\n for (const checkpoint of conversationCheckpoints) {\n if (\n checkpoint.decoded.conversationId !== conversation.conversation_id ||\n checkpoint.decoded.throughSequence !== checkpoint.row.through_sequence ||\n checkpoint.decoded.tailDigest !== checkpoint.row.tail_digest ||\n tailDigests.get(checkpoint.row.through_sequence) !== checkpoint.row.tail_digest\n ) {\n return yield* DoStorageCorruptionError.make({\n table: \"effect_agent_checkpoints\",\n rowKey: `${conversation.conversation_id}/${checkpoint.row.through_sequence}`,\n message: \"Checkpoint identity or digest is not bound to a canonical batch tail.\",\n });\n }\n }\n }\n\n if (\n batches.some(({ row }) => !materializedIds.has(row.conversation_id)) ||\n records.some(({ row }) => !materializedIds.has(row.conversation_id)) ||\n checkpoints.some(({ row }) => !materializedIds.has(row.conversation_id))\n ) {\n return yield* DoStorageCorruptionError.make({\n table: \"effect_agent_conversations\",\n rowKey: \"startup_scan\",\n message: \"Canonical rows exist without a materialized Conversation.\",\n });\n }\n});\n\nconst makeServices = Effect.fn(\"DoConversationStore.makeServices\")(function* () {\n const config = yield* DoStorageConfig;\n const failpoint = yield* DoStorageFailpoint;\n const sql = yield* SqlClientService.SqlClient;\n const crypto = yield* Crypto.Crypto;\n const journal = yield* initializeDoJournal(sql, failpoint.hit, config.maxStoredValueBytes);\n if (config.verifyOnOpen) {\n yield* decodeStartupPayloads(journal, crypto);\n }\n\n const provideCrypto = <A, E>(effect: Effect.Effect<A, E, Crypto.Crypto>) =>\n Effect.provideService(effect, Crypto.Crypto, crypto);\n const hitFailpoint = Effect.fn(\"DoConversationStore.hitFailpoint\")(\n (location: DoStorageFailpointLocation): Effect.Effect<void, ConversationStoreError> =>\n failpoint\n .hit(location)\n .pipe(Effect.mapError((error) => storeError(`storage failpoint ${location}`, error))),\n );\n\n const materialize: ConversationStore[\"Service\"][\"materialize\"] = Effect.fn(\n \"DoConversationStore.materialize\",\n )(function* (request: ConversationMaterialization) {\n const validated = yield* Schema.decodeUnknownEffect(Schema.toType(ConversationMaterialization))(\n request,\n ).pipe(Effect.mapError((error) => schemaStoreError(\"validate materialization\", error)));\n const now = yield* Clock.currentTimeMillis;\n yield* hitFailpoint(\"materialize:before\");\n yield* journal\n .materialize(\n validated.conversationId,\n new Date(now).toISOString(),\n EMPTY_TAIL_DIGEST,\n validated.producerEpoch,\n )\n .pipe(\n Effect.mapError((error) =>\n error._tag === \"DoFenceRejected\"\n ? mapFence(validated.conversationId, error)\n : storeError(\"materialize conversation\", error),\n ),\n );\n yield* hitFailpoint(\"materialize:after\");\n });\n\n const append: ConversationStore[\"Service\"][\"append\"] = Effect.fn(\"DoConversationStore.append\")(\n function* (request: FencedAppendRequest) {\n const validated = yield* Schema.decodeUnknownEffect(Schema.toType(FencedAppendRequest))(\n request,\n ).pipe(Effect.mapError((error) => schemaStoreError(\"validate canonical append\", error)));\n yield* requireConversation(journal, validated.conversationId);\n const tailDigest = yield* provideCrypto(\n digestCanonicalBatch(validated.expectedTailDigest, validated.batch),\n ).pipe(Effect.mapError((error) => storeError(\"digest canonical append\", error)));\n const batchJson = yield* encodeCanonicalBatch(validated.batch);\n const rawRecords = yield* Effect.forEach(validated.batch.records, (record) =>\n encodeCanonicalRecord(record).pipe(\n Effect.map((recordJson) => ({\n recordId: record.recordId,\n recordJson,\n })),\n ),\n );\n const rawRequest = yield* Schema.decodeUnknownEffect(RawAppendRequest)({\n conversationId: validated.conversationId,\n batchId: validated.batch.batchId,\n batchDigest: tailDigest,\n batchJson,\n expectedTailSequence: validated.expectedTailSequence,\n expectedTailDigest: validated.expectedTailDigest,\n producerEpoch: validated.producerEpoch,\n records: rawRecords,\n tailDigest,\n }).pipe(Effect.mapError((error) => schemaStoreError(\"encode canonical append\", error)));\n yield* hitFailpoint(\"append:before\");\n const result = yield* journal.append(rawRequest).pipe(\n Effect.mapError((error) => {\n if (error instanceof DoFenceRejected) {\n return mapFence(validated.conversationId, error);\n }\n if (error instanceof DoAppendConflict) {\n return error.actualTailSequence !== undefined && isDigest(error.actualTailDigest)\n ? AppendConflict.make({\n conversationId: validated.conversationId,\n batchId: validated.batch.batchId,\n reason: error.reason,\n actualTailSequence: error.actualTailSequence,\n actualTailDigest: error.actualTailDigest,\n })\n : AppendConflict.make({\n conversationId: validated.conversationId,\n batchId: validated.batch.batchId,\n reason: error.reason,\n });\n }\n return storeError(\"append canonical batch\", error);\n }),\n Effect.flatMap((result) =>\n Schema.decodeUnknownEffect(AppendResult)(result).pipe(\n Effect.mapError((error) => schemaStoreError(\"decode append result\", error)),\n ),\n ),\n );\n yield* hitFailpoint(\"append:after\");\n return result;\n },\n );\n\n const loadRecords = Effect.fn(\"DoConversationStore.loadRecords\")(function* (\n request: RawReadRequest,\n ) {\n const rows = yield* journal\n .read(request)\n .pipe(Effect.mapError((error) => storeError(\"read canonical records\", error)));\n return yield* Effect.forEach(rows, decodeEnvelope);\n });\n\n const readEffect = Effect.fn(\"DoConversationStore.read\")(function* (request: ConversationRead) {\n const validated = yield* Schema.decodeUnknownEffect(Schema.toType(ConversationRead))(\n request,\n ).pipe(Effect.mapError((error) => schemaStoreError(\"validate conversation read\", error)));\n yield* requireConversation(journal, validated.conversationId);\n const records = yield* loadRecords(\n RawReadRequest.make({\n conversationId: validated.conversationId,\n fromSequenceExclusive: validated.afterSequence ?? ZERO_CANONICAL_SEQUENCE,\n limit: validated.limit,\n }),\n );\n return Stream.fromIterable(records);\n });\n const read: ConversationStore[\"Service\"][\"read\"] = (request) =>\n Stream.unwrap(readEffect(request));\n\n const observeEffect = Effect.fn(\"DoConversationStore.observe\")(function* (\n request: ConversationObservation,\n ) {\n const validated = yield* Schema.decodeUnknownEffect(Schema.toType(ConversationObservation))(\n request,\n ).pipe(\n Effect.mapError((error) => schemaStoreError(\"validate conversation observation\", error)),\n );\n yield* requireConversation(journal, validated.conversationId);\n const initialSequence = yield* parseOffset(validated.conversationId, validated.afterOffset);\n const cursor = yield* Ref.make(initialSequence);\n const poll = Effect.fn(\"DoConversationStore.observePoll\")(function* () {\n const fromSequenceExclusive = yield* Ref.get(cursor);\n const records = yield* loadRecords(\n RawReadRequest.make({\n conversationId: validated.conversationId,\n fromSequenceExclusive,\n limit: 1_024,\n }),\n );\n if (records.length === 0) {\n yield* Effect.sleep(config.observationPollInterval);\n return [];\n }\n yield* Ref.set(cursor, records[records.length - 1].sequence);\n return records;\n });\n return Stream.fromIterableEffectRepeat(poll());\n });\n const observe: ConversationStore[\"Service\"][\"observe\"] = (request) =>\n Stream.unwrap(observeEffect(request));\n\n const exportConversation: ConversationStore[\"Service\"][\"export\"] = Effect.fn(\n \"DoConversationStore.export\",\n )(function* (request: ConversationExportRequest) {\n const validated = yield* Schema.decodeUnknownEffect(Schema.toType(ConversationExportRequest))(\n request,\n ).pipe(Effect.mapError((error) => schemaStoreError(\"validate conversation export\", error)));\n yield* requireConversation(journal, validated.conversationId);\n const exported = yield* journal\n .exportConversation(validated.conversationId)\n .pipe(Effect.mapError((error) => storeError(\"export conversation\", error)));\n const records = yield* Effect.forEach(exported.records, decodeEnvelope);\n if (records.length > 65_536) {\n return yield* ConversationStoreError.make({\n operation: \"decode conversation export\",\n message: \"The conversation exceeds the current export record limit.\",\n });\n }\n const tailDigest = yield* Schema.decodeUnknownEffect(Digest)(\n exported.conversation.tail_digest,\n ).pipe(Effect.mapError((error) => schemaStoreError(\"decode export tail digest\", error)));\n return ConversationExport.make({\n format: \"effect-agent/conversation@1\",\n conversationId: validated.conversationId,\n tailSequence: exported.conversation.tail_sequence,\n tailDigest,\n records,\n });\n });\n\n const inspectTail: ConversationStore[\"Service\"][\"inspectTail\"] = Effect.fn(\n \"DoConversationStore.inspectTail\",\n )(function* (request: ConversationTailRequest) {\n const validated = yield* Schema.decodeUnknownEffect(Schema.toType(ConversationTailRequest))(\n request,\n ).pipe(Effect.mapError((error) => schemaStoreError(\"validate tail inspection\", error)));\n const conversation = yield* requireConversation(journal, validated.conversationId);\n const tailDigest = yield* Schema.decodeUnknownEffect(Digest)(conversation.tail_digest).pipe(\n Effect.mapError((error) => schemaStoreError(\"decode tail digest\", error)),\n );\n return ConversationTail.make({\n conversationId: validated.conversationId,\n tailSequence: conversation.tail_sequence,\n tailDigest,\n producerEpoch: conversation.producer_epoch,\n });\n });\n\n const saveCheckpoint: ConversationStore[\"Service\"][\"saveCheckpoint\"] = Effect.fn(\n \"DoConversationStore.saveCheckpoint\",\n )(function* (request: SaveCheckpointRequest) {\n const validated = yield* Schema.decodeUnknownEffect(Schema.toType(SaveCheckpointRequest))(\n request,\n ).pipe(Effect.mapError((error) => schemaStoreError(\"validate checkpoint\", error)));\n const conversation = yield* requireConversation(journal, validated.checkpoint.conversationId);\n if (validated.checkpoint.throughSequence > conversation.tail_sequence) {\n return yield* CheckpointRejected.make({\n conversationId: validated.checkpoint.conversationId,\n reason: \"ahead-of-tail\",\n });\n }\n const canonicalDigest = yield* tailDigestAt(\n journal,\n validated.checkpoint.conversationId,\n validated.checkpoint.throughSequence,\n );\n if (canonicalDigest !== validated.checkpoint.tailDigest) {\n return yield* CheckpointRejected.make({\n conversationId: validated.checkpoint.conversationId,\n reason: \"digest-mismatch\",\n });\n }\n const checkpointJson = yield* encodeCheckpoint(validated.checkpoint);\n const raw = RawCheckpoint.make({\n conversationId: validated.checkpoint.conversationId,\n throughSequence: validated.checkpoint.throughSequence,\n tailDigest: validated.checkpoint.tailDigest,\n checkpointJson,\n });\n yield* hitFailpoint(\"save-checkpoint:before\");\n yield* journal.saveCheckpoint(raw).pipe(\n Effect.mapError((error) =>\n error instanceof DoCheckpointConflict\n ? CheckpointRejected.make({\n conversationId: validated.checkpoint.conversationId,\n reason: \"digest-mismatch\",\n })\n : storeError(\"save checkpoint\", error),\n ),\n );\n yield* hitFailpoint(\"save-checkpoint:after\");\n });\n\n const loadCheckpoint: ConversationStore[\"Service\"][\"loadCheckpoint\"] = Effect.fn(\n \"DoConversationStore.loadCheckpoint\",\n )(function* (request: LoadCheckpointRequest) {\n const validated = yield* Schema.decodeUnknownEffect(Schema.toType(LoadCheckpointRequest))(\n request,\n ).pipe(Effect.mapError((error) => schemaStoreError(\"validate checkpoint lookup\", error)));\n const conversation = yield* requireConversation(journal, validated.conversationId);\n const rows = yield* journal\n .loadCheckpoint(\n validated.conversationId,\n validated.atOrBeforeSequence ?? conversation.tail_sequence,\n )\n .pipe(Effect.mapError((error) => storeError(\"load checkpoint\", error)));\n if (rows.length === 0) return Option.none();\n if (rows.length !== 1) {\n return yield* ConversationStoreError.make({\n operation: \"load checkpoint\",\n message: `Expected at most one checkpoint row but found ${rows.length}.`,\n });\n }\n const checkpoint = yield* decodeCheckpoint(rows[0].checkpoint_json);\n const canonicalDigest = yield* tailDigestAt(\n journal,\n checkpoint.conversationId,\n checkpoint.throughSequence,\n );\n if (canonicalDigest !== checkpoint.tailDigest) {\n return yield* CheckpointRejected.make({\n conversationId: checkpoint.conversationId,\n reason: \"digest-mismatch\",\n });\n }\n return Option.some(checkpoint);\n });\n\n const conversationStore = ConversationStore.of({\n append,\n export: exportConversation,\n inspectTail,\n loadCheckpoint,\n materialize,\n observe,\n read,\n saveCheckpoint,\n });\n\n return Context.make(ConversationStore, conversationStore);\n});\n\n/**\n * Durable Object Conversation Store implementation with configuration, failpoint, SQL, and\n * Crypto authority kept visible in its input channel.\n */\nexport const conversationStoreLayer: Layer.Layer<\n ConversationStore,\n DoStorageInitializationError,\n DoStorageConfig | DoStorageFailpoint | SqlClientService.SqlClient | Crypto.Crypto\n> = Layer.effectContext(makeServices());\n\n/**\n * Validated Durable Object storage configuration Layer with the documented defaults applied.\n * Shared by the ConversationStore and SubmissionLedger convenience layers so their defaults\n * cannot drift.\n */\nexport const storageConfigLayer = (\n options: DoStorageOptions,\n): Layer.Layer<DoStorageConfig, DoStorageError> =>\n Layer.effect(DoStorageConfig)(\n Schema.decodeUnknownEffect(DoStorageConfigValue)({\n observationPollInterval: options.observationPollInterval ?? 25,\n ownershipLeaseDuration:\n options.ownershipLeaseDuration ?? Duration.toMillis(DEFAULT_OWNERSHIP_LEASE_DURATION),\n maxStoredValueBytes: options.maxStoredValueBytes ?? DEFAULT_MAX_STORED_VALUE_BYTES,\n verifyOnOpen: options.verifyOnOpen ?? false,\n }).pipe(\n Effect.mapError((error) =>\n DoStorageError.make({\n cause: error,\n operation: \"configure Durable Object storage\",\n message: error.message,\n }),\n ),\n ),\n );\n\n/** The failpoint Layer selected by convenience options: explicit handler or the no-op default. */\nexport const storageFailpointLayer = (\n options: DoStorageOptions,\n): Layer.Layer<DoStorageFailpoint> =>\n options.failpoint === undefined\n ? DoStorageFailpoint.layer\n : Layer.succeed(DoStorageFailpoint)({ hit: options.failpoint });\n\n/**\n * A composition-root convenience Layer for canonical Conversations inside one Durable Object,\n * built over `ctx.storage`. Durable accepted work is served by the separate SubmissionLedger\n * port; point both at the SAME `ctx.storage` so claims fence the same producer epochs\n * (ADR-0011 D7's \"same file\" rule, transposed to one object's private database).\n */\nexport const layer = (\n options: DoStorageOptions,\n): Layer.Layer<ConversationStore, DoStorageInitializationError> => {\n const sqlLayer = SqliteClient.layer({ storage: options.storage });\n return conversationStoreLayer.pipe(\n Layer.provide(\n Layer.mergeAll(\n storageConfigLayer(options),\n storageFailpointLayer(options),\n sqlLayer,\n BrowserCrypto.layer,\n ),\n ),\n );\n};\n\n/** Create an adapter-owned resumable observation offset for a known canonical sequence. */\nexport const observationOffsetAt = makeOffset;\n","import {\n AbortCommand,\n AbortIntent,\n AdmissionAdmitted,\n AdmissionConflict,\n AdmissionNotAdmitted,\n AdmissionRequest,\n AdmissionResult,\n ApprovalConflict,\n ApprovalDecision,\n ApprovalDecisionCommand,\n ApprovalDecisionIntent,\n AttachChildToReservationRequest,\n BeginChildBudgetReleaseRequest,\n CanonicalSequence,\n ChildAttachmentSnapshot,\n ChildBudgetReservationRequest,\n ChildBudgetReservationSnapshot,\n ChildReservationConflict,\n ChildReservationStatus,\n ChildSettledNotification,\n Claim,\n ClaimJoiningRequest,\n ClaimRequest,\n DefinitionDigests,\n Digest,\n EMPTY_TAIL_DIGEST,\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 PersistedJson,\n ProducerEpoch,\n QueueSequence,\n RecordEnvelope,\n RecoverySnapshot,\n RecoverySnapshotRequest,\n ReleaseChildBudgetRequest,\n ReleaseOwnershipRequest,\n RenewOwnershipRequest,\n ReservedChildBudget,\n ReservedSettlement,\n RevertJoiningRequest,\n Settlement,\n SettlementConflict,\n SettlementFinalization,\n SettlementOutcome,\n SettlementReservation,\n SubmissionLedger,\n SubmissionLookup,\n SubmissionLookupByKey,\n SubmissionSnapshot,\n SubmissionState,\n SettlementReservationSnapshot,\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/session\";\nimport { BrowserCrypto } from \"@effect/platform-browser\";\nimport { SqliteClient } from \"@effect/sql-sqlite-do\";\nimport { Clock, Context, Crypto, DateTime, Effect, Layer, Option, Schema, Stream } from \"effect\";\nimport * as SqlClientService from \"effect/unstable/sql/SqlClient\";\nimport type { SqlError } from \"effect/unstable/sql/SqlError\";\n\nimport {\n storageConfigLayer,\n storageFailpointLayer,\n type DoStorageInitializationError,\n type DoStorageOptions,\n} from \"./do-conversation-store.ts\";\nimport { decodeRows, initializeDoJournal } from \"./do-journal.ts\";\nimport { DoStorageConfig } from \"./do-storage-config.ts\";\nimport { DoStorageFailpoint } from \"./do-storage-failpoint.ts\";\nimport {\n DoLedgerError,\n DoStorageCorruptionError,\n DoStorageError,\n type DoStorageFailpointLocation,\n} from \"./errors.ts\";\n\ntype SubmissionId = SubmissionSnapshot[\"submissionId\"];\n\n/**\n * Static decode-side ceiling; writes are bounded in bytes by the configured\n * `maxStoredValueBytes` (see do-journal.ts).\n */\nconst BoundedStoredText = Schema.String.check(Schema.isMaxLength(2_000_000));\nconst BoundedIdentifier = Schema.NonEmptyString.check(Schema.isMaxLength(1024));\nconst BoundedTimestamp = Schema.NonEmptyString.check(Schema.isMaxLength(128));\n\nconst SCAN_PAGE_SIZE = 256;\nconst EPOCH_ZERO = Schema.decodeSync(ProducerEpoch)(0);\nconst MAX_IDENTIFIER_LENGTH = 1_024;\n\nclass SubmissionRow extends Schema.Class<SubmissionRow>(\"SubmissionRow\")({\n submission_id: BoundedIdentifier,\n conversation_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}) {}\n\nclass ChildReservationRow extends Schema.Class<ChildReservationRow>(\"ChildReservationRow\")({\n reservation_id: BoundedIdentifier,\n parent_submission_id: BoundedIdentifier,\n parent_tool_call_id: BoundedIdentifier,\n child_submission_id: Schema.NullOr(BoundedIdentifier),\n status: ChildReservationStatus,\n allocation_json: BoundedStoredText,\n allocation_digest: Digest,\n accounting_json: Schema.NullOr(BoundedStoredText),\n reserved_at: BoundedTimestamp,\n release_began_at: Schema.NullOr(BoundedTimestamp),\n released_at: Schema.NullOr(BoundedTimestamp),\n}) {}\n\nclass ChildSettlementMarkerRow extends Schema.Class<ChildSettlementMarkerRow>(\n \"ChildSettlementMarkerRow\",\n)({\n parent_submission_id: BoundedIdentifier,\n child_submission_id: BoundedIdentifier,\n child_outcome: Schema.NullOr(SettlementOutcome),\n recorded_at: BoundedTimestamp,\n}) {}\n\nclass ApprovalDecisionRow extends Schema.Class<ApprovalDecisionRow>(\"ApprovalDecisionRow\")({\n submission_id: BoundedIdentifier,\n tool_call_id: BoundedIdentifier,\n decision: ApprovalDecision,\n resolver: BoundedIdentifier,\n reason: BoundedStoredText,\n decided_at: BoundedTimestamp,\n}) {}\n\nclass UnknownResolutionRow extends Schema.Class<UnknownResolutionRow>(\"UnknownResolutionRow\")({\n submission_id: BoundedIdentifier,\n tool_call_id: BoundedIdentifier,\n author: BoundedIdentifier,\n reason: BoundedStoredText,\n resolution_json: BoundedStoredText,\n resolved_at: BoundedTimestamp,\n}) {}\n\nclass OwnershipRow extends Schema.Class<OwnershipRow>(\"OwnershipRow\")({\n submission_id: BoundedIdentifier,\n attempt_id: BoundedIdentifier,\n ownership_token: BoundedIdentifier,\n producer_epoch: ProducerEpoch,\n owner_producer_id: BoundedIdentifier,\n lease_expires_at: BoundedTimestamp,\n}) {}\n\nclass ReservationRow extends Schema.Class<ReservationRow>(\"ReservationRow\")({\n submission_id: BoundedIdentifier,\n settlement_id: BoundedIdentifier,\n outcome: SettlementOutcome,\n record_id: BoundedIdentifier,\n record_json: BoundedStoredText,\n record_digest: Digest,\n reserved_at: BoundedTimestamp,\n finalized_at: Schema.NullOr(BoundedTimestamp),\n}) {}\n\nclass AbortIntentRow extends Schema.Class<AbortIntentRow>(\"AbortIntentRow\")({\n submission_id: BoundedIdentifier,\n author: BoundedIdentifier,\n reason: BoundedStoredText,\n requested_at: BoundedTimestamp,\n canonical_record_id: Schema.NullOr(BoundedIdentifier),\n}) {}\n\nclass MaxQueueSequenceRow extends Schema.Class<MaxQueueSequenceRow>(\"MaxQueueSequenceRow\")({\n max_queue_sequence: Schema.Int.check(Schema.isGreaterThanOrEqualTo(0)),\n}) {}\n\nclass CanonicalRecordIdRow extends Schema.Class<CanonicalRecordIdRow>(\"CanonicalRecordIdRow\")({\n record_id: BoundedIdentifier,\n}) {}\n\nconst SUBMISSION_COLUMNS = `\n submission_id,\n conversation_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`;\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 session 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);\nconst decodeChildReservationSnapshotUnknown = Schema.decodeUnknownEffect(\n ChildBudgetReservationSnapshot,\n);\nconst decodeChildAttachmentSnapshot = Schema.decodeUnknownEffect(ChildAttachmentSnapshot);\n\n/** Wrap an adapter-internal failure into the port's LedgerError without erasing its tag. */\nconst internalFailure =\n (operation: string) =>\n (error: { readonly message: string }): LedgerError =>\n LedgerError.make({ operation, message: error.message, cause: error });\n\n/**\n * Classify raw SQL failures. Within one Durable Object there is exactly one writer, so the\n * Node adapter's retryable `SqliteWriteContention` classification has no analogue: every raw\n * failure is a `DoLedgerError` preserved as the LedgerError's cause.\n */\nconst sqlFailure =\n (operation: string) =>\n (error: SqlError): LedgerError =>\n internalFailure(operation)(\n DoLedgerError.make({\n cause: error,\n operation,\n message: error.message,\n }),\n );\n\nconst corruptionFailure = (operation: string, table: string, rowKey: string, message: string) =>\n internalFailure(operation)(DoStorageCorruptionError.make({ table, rowKey, message }));\n\nconst makeServices = Effect.fn(\"DoSubmissionLedger.makeServices\")(function* () {\n const config = yield* DoStorageConfig;\n const failpoint = yield* DoStorageFailpoint;\n const sql = yield* SqlClientService.SqlClient;\n const crypto = yield* Crypto.Crypto;\n const journal = yield* initializeDoJournal(sql, failpoint.hit, config.maxStoredValueBytes);\n\n const hitFailpoint = (\n location: DoStorageFailpointLocation,\n operation: string,\n ): Effect.Effect<void, LedgerError> =>\n failpoint.hit(location).pipe(Effect.mapError((error) => internalFailure(operation)(error)));\n\n /**\n * Run one ledger mutation under the journal's Durable Object storage-backed transaction so\n * ownership-token and epoch checks are atomic with their writes (DUR-006). Transaction\n * failures surface as LedgerError carrying the typed `DoStorageError` as cause.\n */\n const inWriteTransaction = <\n A,\n E extends\n | AdmissionConflict\n | 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 error instanceof DoStorageError ? internalFailure(operation)(error) : error,\n ),\n );\n\n const mintUuid = (operation: string): Effect.Effect<string, LedgerError> =>\n crypto.randomUUIDv7.pipe(Effect.mapError((error) => internalFailure(operation)(error)));\n\n const currentInstant = Effect.map(Clock.currentTimeMillis, (millis) => ({\n millis,\n iso: new Date(millis).toISOString(),\n }));\n\n const timestampMillis = (operation: string, rowKey: string) => (timestamp: string) =>\n decodeUtcInstant(timestamp).pipe(\n Effect.map(DateTime.toEpochMillis),\n Effect.mapError((error) =>\n corruptionFailure(operation, \"effect_agent_submission_ownership\", rowKey, error.message),\n ),\n );\n\n const decodeSubmissionRows = (operation: string, rowKey: string, rows: unknown) =>\n decodeRows(Schema.Array(SubmissionRow), \"effect_agent_submissions\", rowKey, rows).pipe(\n Effect.mapError(internalFailure(operation)),\n );\n\n const readSubmission = Effect.fn(\"DoSubmissionLedger.readSubmission\")(function* (\n operation: string,\n submissionId: string,\n ): Effect.fn.Return<Option.Option<SubmissionRow>, LedgerError> {\n const rows = yield* sql<Record<string, unknown>>`\n SELECT ${sql.literal(SUBMISSION_COLUMNS)}\n FROM effect_agent_submissions\n WHERE submission_id = ${submissionId}\n `.pipe(Effect.mapError(sqlFailure(operation)));\n const decoded = yield* decodeSubmissionRows(operation, submissionId, rows);\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 return decoded.length === 0 ? Option.none() : Option.some(decoded[0]);\n });\n\n const requireSubmission = Effect.fn(\"DoSubmissionLedger.requireSubmission\")(function* (\n operation: string,\n submissionId: string,\n ): Effect.fn.Return<SubmissionRow, LedgerError> {\n const submission = yield* readSubmission(operation, submissionId);\n if (Option.isNone(submission)) {\n return yield* LedgerError.make({\n operation,\n message: `Unknown submission ${submissionId}.`,\n });\n }\n return submission.value;\n });\n\n const readOwnership = Effect.fn(\"DoSubmissionLedger.readOwnership\")(function* (\n operation: string,\n submissionId: string,\n ): Effect.fn.Return<Option.Option<OwnershipRow>, LedgerError> {\n const rows = yield* sql<Record<string, unknown>>`\n SELECT\n submission_id,\n attempt_id,\n ownership_token,\n producer_epoch,\n owner_producer_id,\n lease_expires_at\n FROM effect_agent_submission_ownership\n WHERE submission_id = ${submissionId}\n `.pipe(Effect.mapError(sqlFailure(operation)));\n const decoded = yield* decodeRows(\n Schema.Array(OwnershipRow),\n \"effect_agent_submission_ownership\",\n submissionId,\n rows,\n ).pipe(Effect.mapError(internalFailure(operation)));\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 return decoded.length === 0 ? Option.none() : Option.some(decoded[0]);\n });\n\n const conversationEpoch = Effect.fn(\"DoSubmissionLedger.conversationEpoch\")(function* (\n operation: string,\n conversationId: string,\n ): Effect.fn.Return<ProducerEpoch, LedgerError> {\n const conversations = yield* journal\n .getConversation(conversationId)\n .pipe(Effect.mapError(internalFailure(operation)));\n return conversations.length === 0 ? EPOCH_ZERO : conversations[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 * Conversation's current producer epoch (DUR-006).\n */\n const requireOwnership = Effect.fn(\"DoSubmissionLedger.requireOwnership\")(function* (\n operation: string,\n submission: SubmissionRow,\n ownershipToken: string,\n ): Effect.fn.Return<OwnershipRow, OwnershipLost | LedgerError> {\n const ownership = yield* readOwnership(operation, submission.submission_id);\n if (Option.isNone(ownership) || ownership.value.ownership_token !== ownershipToken) {\n const actualEpoch = yield* conversationEpoch(operation, submission.conversation_id);\n const submissionId = yield* Schema.decodeUnknownEffect(\n SubmissionSnapshot.fields.submissionId,\n )(submission.submission_id).pipe(Effect.mapError(internalFailure(operation)));\n return yield* OwnershipLost.make({ submissionId, actualEpoch });\n }\n return ownership.value;\n });\n\n const decodeSubmissionSnapshot = Effect.fn(\"DoSubmissionLedger.decodeSubmissionSnapshot\")(\n function* (\n operation: string,\n row: SubmissionRow,\n ): Effect.fn.Return<SubmissionSnapshot, LedgerError> {\n const agentDigests = yield* parseStoredJsonText(row.agent_digests_json).pipe(\n Effect.mapError((error) =>\n corruptionFailure(\n operation,\n \"effect_agent_submissions\",\n row.submission_id,\n error.message,\n ),\n ),\n );\n 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 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 return yield* decodeSubmissionSnapshotUnknown({\n submissionId: row.submission_id,\n conversationId: row.conversation_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.settled_outcome === null ? {} : { settledOutcome: row.settled_outcome }),\n ...(row.ready_at === null ? {} : { readyAt: row.ready_at }),\n ...(row.parent_submission_id === null || row.parent_tool_call_id === null\n ? {}\n : {\n parentLinkage: {\n parentSubmissionId: row.parent_submission_id,\n parentToolCallId: row.parent_tool_call_id,\n },\n }),\n }).pipe(\n Effect.mapError((error) =>\n corruptionFailure(\n operation,\n \"effect_agent_submissions\",\n row.submission_id,\n error.message,\n ),\n ),\n );\n },\n );\n\n const readReservation = Effect.fn(\"DoSubmissionLedger.readReservation\")(function* (\n operation: string,\n submissionId: string,\n ): Effect.fn.Return<Option.Option<ReservationRow>, LedgerError> {\n const rows = yield* sql<Record<string, unknown>>`\n SELECT\n submission_id,\n settlement_id,\n outcome,\n record_id,\n record_json,\n record_digest,\n reserved_at,\n finalized_at\n FROM effect_agent_settlement_reservations\n WHERE submission_id = ${submissionId}\n `.pipe(Effect.mapError(sqlFailure(operation)));\n const decoded = yield* decodeRows(\n Schema.Array(ReservationRow),\n \"effect_agent_settlement_reservations\",\n submissionId,\n rows,\n ).pipe(Effect.mapError(internalFailure(operation)));\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 return decoded.length === 0 ? Option.none() : Option.some(decoded[0]);\n });\n\n const readAbortIntent = Effect.fn(\"DoSubmissionLedger.readAbortIntent\")(function* (\n operation: string,\n submissionId: string,\n ): Effect.fn.Return<Option.Option<AbortIntentRow>, LedgerError> {\n const rows = yield* sql<Record<string, unknown>>`\n SELECT\n submission_id,\n author,\n reason,\n requested_at,\n canonical_record_id\n FROM effect_agent_abort_intents\n WHERE submission_id = ${submissionId}\n `.pipe(Effect.mapError(sqlFailure(operation)));\n const decoded = yield* decodeRows(\n Schema.Array(AbortIntentRow),\n \"effect_agent_abort_intents\",\n submissionId,\n rows,\n ).pipe(Effect.mapError(internalFailure(operation)));\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 return decoded.length === 0 ? Option.none() : Option.some(decoded[0]);\n });\n\n /**\n * Read the durable cross-store child-settlement markers recorded against one parent\n * Submission (the DC realization of the port's \"cross-store adapters record a durable\n * notification marker\" contract).\n */\n const readChildSettlementMarkers = Effect.fn(\"DoSubmissionLedger.readChildSettlementMarkers\")(\n function* (\n operation: string,\n parentSubmissionId: string,\n ): Effect.fn.Return<ReadonlyArray<ChildSettlementMarkerRow>, LedgerError> {\n const rows = yield* sql<Record<string, unknown>>`\n SELECT\n parent_submission_id,\n child_submission_id,\n child_outcome,\n recorded_at\n FROM effect_agent_child_settlements\n WHERE parent_submission_id = ${parentSubmissionId}\n ORDER BY child_submission_id ASC\n `.pipe(Effect.mapError(sqlFailure(operation)));\n return yield* decodeRows(\n Schema.Array(ChildSettlementMarkerRow),\n \"effect_agent_child_settlements\",\n parentSubmissionId,\n rows,\n ).pipe(Effect.mapError(internalFailure(operation)));\n },\n );\n\n /**\n * Whether one listed child is provably settled from THIS store: either its own row lives\n * here and is settled (single-store evidence, identical to the Node adapter), or a durable\n * cross-store notification marker was recorded for it (the child's row lives in another\n * Durable Object and its owner reported the settlement through `recordChildSettled`).\n */\n const childProvablySettled = Effect.fn(\"DoSubmissionLedger.childProvablySettled\")(function* (\n operation: string,\n markerChildren: ReadonlySet<string>,\n childSubmissionId: string,\n ): Effect.fn.Return<boolean, LedgerError> {\n if (markerChildren.has(childSubmissionId)) return true;\n const childRow = yield* readSubmission(operation, childSubmissionId);\n return Option.isSome(childRow) && childRow.value.state === \"settled\";\n });\n\n const decodeChildReservationRows = (operation: string, rowKey: string, rows: unknown) =>\n decodeRows(\n Schema.Array(ChildReservationRow),\n \"effect_agent_child_reservations\",\n rowKey,\n rows,\n ).pipe(Effect.mapError(internalFailure(operation)));\n\n const readChildReservation = Effect.fn(\"DoSubmissionLedger.readChildReservation\")(function* (\n operation: string,\n reservationId: string,\n ): Effect.fn.Return<Option.Option<ChildReservationRow>, LedgerError> {\n const rows = yield* sql<Record<string, unknown>>`\n SELECT ${sql.literal(CHILD_RESERVATION_COLUMNS)}\n FROM effect_agent_child_reservations\n WHERE reservation_id = ${reservationId}\n `.pipe(Effect.mapError(sqlFailure(operation)));\n const decoded = yield* decodeChildReservationRows(operation, reservationId, rows);\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 return decoded.length === 0 ? Option.none() : Option.some(decoded[0]);\n });\n\n const readChildReservationForCall = Effect.fn(\"DoSubmissionLedger.readChildReservationForCall\")(\n function* (\n operation: string,\n parentSubmissionId: string,\n parentToolCallId: string,\n ): Effect.fn.Return<Option.Option<ChildReservationRow>, LedgerError> {\n const rows = yield* sql<Record<string, unknown>>`\n SELECT ${sql.literal(CHILD_RESERVATION_COLUMNS)}\n FROM effect_agent_child_reservations\n WHERE parent_submission_id = ${parentSubmissionId}\n AND parent_tool_call_id = ${parentToolCallId}\n `.pipe(Effect.mapError(sqlFailure(operation)));\n const decoded = yield* decodeChildReservationRows(\n operation,\n `${parentSubmissionId}/${parentToolCallId}`,\n rows,\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 return decoded.length === 0 ? Option.none() : Option.some(decoded[0]);\n },\n );\n\n const childReservationSnapshotFromRow = Effect.fn(\n \"DoSubmissionLedger.childReservationSnapshotFromRow\",\n )(function* (\n operation: string,\n row: ChildReservationRow,\n ): Effect.fn.Return<ChildBudgetReservationSnapshot, LedgerError> {\n const rowFailure = (error: { readonly message: string }) =>\n corruptionFailure(\n operation,\n \"effect_agent_child_reservations\",\n row.reservation_id,\n error.message,\n );\n const allocation = yield* parseStoredJsonText(row.allocation_json).pipe(\n Effect.mapError(rowFailure),\n );\n const accounting =\n row.accounting_json === null\n ? undefined\n : yield* parseStoredJsonText(row.accounting_json).pipe(Effect.mapError(rowFailure));\n return yield* decodeChildReservationSnapshotUnknown({\n reservationId: row.reservation_id,\n parentSubmissionId: row.parent_submission_id,\n parentToolCallId: row.parent_tool_call_id,\n status: row.status,\n allocation,\n allocationDigest: row.allocation_digest,\n reservedAt: row.reserved_at,\n ...(row.child_submission_id === null ? {} : { childSubmissionId: row.child_submission_id }),\n ...(accounting === undefined ? {} : { accounting }),\n ...(row.release_began_at === null ? {} : { releaseBeganAt: row.release_began_at }),\n ...(row.released_at === null ? {} : { releasedAt: row.released_at }),\n }).pipe(Effect.mapError(rowFailure));\n });\n\n const readApprovalDecisions = Effect.fn(\"DoSubmissionLedger.readApprovalDecisions\")(function* (\n operation: string,\n submissionId: string,\n ): Effect.fn.Return<ReadonlyArray<ApprovalDecisionRow>, LedgerError> {\n const rows = yield* sql<Record<string, unknown>>`\n SELECT\n submission_id,\n tool_call_id,\n decision,\n resolver,\n reason,\n decided_at\n FROM effect_agent_approval_decisions\n WHERE submission_id = ${submissionId}\n ORDER BY tool_call_id ASC\n `.pipe(Effect.mapError(sqlFailure(operation)));\n return yield* decodeRows(\n Schema.Array(ApprovalDecisionRow),\n \"effect_agent_approval_decisions\",\n submissionId,\n rows,\n ).pipe(Effect.mapError(internalFailure(operation)));\n });\n\n const approvalIntentFromRow = Effect.fn(\"DoSubmissionLedger.approvalIntentFromRow\")(function* (\n operation: string,\n row: ApprovalDecisionRow,\n ): Effect.fn.Return<ApprovalDecisionIntent, LedgerError> {\n return yield* decodeApprovalDecisionIntent({\n submissionId: row.submission_id,\n toolCallId: row.tool_call_id,\n decision: row.decision,\n resolver: row.resolver,\n reason: row.reason,\n decidedAt: row.decided_at,\n }).pipe(\n Effect.mapError((error) =>\n corruptionFailure(\n operation,\n \"effect_agent_approval_decisions\",\n `${row.submission_id}/${row.tool_call_id}`,\n error.message,\n ),\n ),\n );\n });\n\n const readUnknownResolutions = Effect.fn(\"DoSubmissionLedger.readUnknownResolutions\")(function* (\n operation: string,\n submissionId: string,\n ): Effect.fn.Return<ReadonlyArray<UnknownResolutionRow>, LedgerError> {\n const rows = yield* sql<Record<string, unknown>>`\n SELECT\n submission_id,\n tool_call_id,\n author,\n reason,\n resolution_json,\n resolved_at\n FROM effect_agent_unknown_resolutions\n WHERE submission_id = ${submissionId}\n ORDER BY tool_call_id ASC\n `.pipe(Effect.mapError(sqlFailure(operation)));\n return yield* decodeRows(\n Schema.Array(UnknownResolutionRow),\n \"effect_agent_unknown_resolutions\",\n submissionId,\n rows,\n ).pipe(Effect.mapError(internalFailure(operation)));\n });\n\n const unknownResolutionIntentFromRow = Effect.fn(\n \"DoSubmissionLedger.unknownResolutionIntentFromRow\",\n )(function* (\n operation: string,\n row: UnknownResolutionRow,\n ): Effect.fn.Return<UnknownResolutionIntent, LedgerError> {\n const resolution = yield* parseStoredJsonText(row.resolution_json).pipe(\n Effect.mapError((error) =>\n corruptionFailure(\n operation,\n \"effect_agent_unknown_resolutions\",\n `${row.submission_id}/${row.tool_call_id}`,\n error.message,\n ),\n ),\n );\n return yield* decodeUnknownResolutionIntent({\n submissionId: row.submission_id,\n toolCallId: row.tool_call_id,\n author: row.author,\n reason: row.reason,\n resolution,\n resolvedAt: row.resolved_at,\n }).pipe(\n Effect.mapError((error) =>\n corruptionFailure(\n operation,\n \"effect_agent_unknown_resolutions\",\n `${row.submission_id}/${row.tool_call_id}`,\n error.message,\n ),\n ),\n );\n });\n\n /** The Submission's marked-unknown open Tool Call identities, empty when never marked. */\n const storedUnknownToolCallIds = Effect.fn(\"DoSubmissionLedger.storedUnknownToolCallIds\")(\n function* (\n operation: string,\n submission: SubmissionRow,\n ): Effect.fn.Return<ReadonlyArray<typeof ToolCallIdSchema.Type>, LedgerError> {\n if (submission.unknown_tool_call_ids_json === null) return [];\n return yield* decodeToolCallIdsText(submission.unknown_tool_call_ids_json).pipe(\n Effect.mapError((error) =>\n corruptionFailure(\n operation,\n \"effect_agent_submissions\",\n submission.submission_id,\n error.message,\n ),\n ),\n );\n },\n );\n\n /**\n * Canonical history is the abort authority (DUR-015): the intent's canonicalRecordId is\n * derived from the shared canonical-records table using the deterministic abort record\n * identity, never from a cached ledger marker.\n */\n const canonicalAbortRecordId = Effect.fn(\"DoSubmissionLedger.canonicalAbortRecordId\")(function* (\n operation: string,\n conversationId: string,\n submissionId: SubmissionId,\n ): Effect.fn.Return<string | undefined, LedgerError> {\n const recordId = submissionAbortRecordId(submissionId);\n const rows = yield* sql<Record<string, unknown>>`\n SELECT record_id\n FROM effect_agent_canonical_records\n WHERE conversation_id = ${conversationId}\n AND record_id = ${recordId}\n `.pipe(Effect.mapError(sqlFailure(operation)));\n const decoded = yield* decodeRows(\n Schema.Array(CanonicalRecordIdRow),\n \"effect_agent_canonical_records\",\n `${conversationId}/${recordId}`,\n rows,\n ).pipe(Effect.mapError(internalFailure(operation)));\n return decoded.length === 0 ? undefined : recordId;\n });\n\n const abortIntentFromRow = Effect.fn(\"DoSubmissionLedger.abortIntentFromRow\")(function* (\n operation: string,\n submission: SubmissionRow,\n submissionId: SubmissionId,\n row: AbortIntentRow,\n ): Effect.fn.Return<AbortIntent, LedgerError> {\n const canonicalRecordId = yield* canonicalAbortRecordId(\n operation,\n submission.conversation_id,\n submissionId,\n );\n return yield* decodeAbortIntent({\n submissionId: row.submission_id,\n author: row.author,\n reason: row.reason,\n requestedAt: row.requested_at,\n ...(canonicalRecordId === undefined ? {} : { canonicalRecordId }),\n }).pipe(\n Effect.mapError((error) =>\n corruptionFailure(\n operation,\n \"effect_agent_abort_intents\",\n row.submission_id,\n error.message,\n ),\n ),\n );\n });\n\n // Durable Object storage is the single serialized owner: writes confirm through output\n // gates before any response is observable, which is exactly the single-owner crash\n // durability this adapter claims — under its own honest label (P7 WP0).\n const capabilities = Effect.succeed(\n LedgerCapabilities.make({ durability: \"durable-cloudflare\" }),\n );\n\n const admit: SubmissionLedger[\"Service\"][\"admit\"] = Effect.fn(\"DoSubmissionLedger.admit\")(\n function* (request: AdmissionRequest) {\n const operation = \"ledger admit\";\n const validated = yield* Schema.decodeUnknownEffect(Schema.toType(AdmissionRequest))(\n request,\n ).pipe(Effect.mapError(internalFailure(operation)));\n const inputJson = yield* encodePersistedJsonText(validated.inputPayload).pipe(\n Effect.mapError(internalFailure(operation)),\n );\n // The platform's ~2 MB per-value bound, refused typed BEFORE any durable mutation\n // (resource-limits gate; oversized payloads are the designed R2 overflow path).\n yield* journal\n .checkValueBound(operation, inputJson)\n .pipe(Effect.mapError(internalFailure(operation)));\n const agentDigestsJson = yield* encodeDefinitionDigestsText(validated.agentDigests).pipe(\n Effect.mapError(internalFailure(operation)),\n );\n // Routable Submission identity (D-P6-5): `{uuidv7}:{conversationId}`. The cross-DO\n // routing layer parses ITS OWN minted format (split at the first \":\") to address\n // submissionId-only operations to the owning Conversation Object; the id stays opaque\n // to every other component, exactly like DN's `submission-{uuid}` prefix.\n const mintedSubmissionId = `${yield* mintUuid(operation)}:${validated.conversationId}`;\n if (mintedSubmissionId.length > MAX_IDENTIFIER_LENGTH) {\n return yield* LedgerError.make({\n operation,\n message:\n `A routable Submission identity of ${mintedSubmissionId.length} characters exceeds ` +\n `the ${MAX_IDENTIFIER_LENGTH}-character ledger row bound; shorten the Conversation identity.`,\n });\n }\n const mintedReceiptId = `receipt-${yield* mintUuid(operation)}`;\n yield* hitFailpoint(\"ledger:admit:before\", operation);\n const result = yield* inWriteTransaction(\n operation,\n Effect.gen(function* () {\n const keyRowKey = `${validated.conversationId}/${validated.principal}/${validated.idempotencyKey}`;\n const existingRows = yield* sql<Record<string, unknown>>`\n SELECT ${sql.literal(SUBMISSION_COLUMNS)}\n FROM effect_agent_submissions\n WHERE conversation_id = ${validated.conversationId}\n AND principal = ${validated.principal}\n AND idempotency_key = ${validated.idempotencyKey}\n `.pipe(Effect.mapError(sqlFailure(operation)));\n const existing = yield* decodeSubmissionRows(operation, keyRowKey, existingRows);\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 if (existing[0].input_digest !== validated.inputDigest || !sameLinkage) {\n return yield* AdmissionConflict.make({\n conversationId: validated.conversationId,\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 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 conversation_id = ${validated.conversationId}\n `.pipe(Effect.mapError(sqlFailure(operation)));\n const decodedMax = yield* decodeRows(\n Schema.Array(MaxQueueSequenceRow),\n \"effect_agent_submissions\",\n validated.conversationId,\n maxRows,\n ).pipe(Effect.mapError(internalFailure(operation)));\n const queueSequence = yield* decodeQueueSequence(\n (decodedMax[0]?.max_queue_sequence ?? 0) + 1,\n ).pipe(Effect.mapError(internalFailure(operation)));\n const now = yield* currentInstant;\n\n yield* sql`\n INSERT INTO effect_agent_submissions (\n submission_id,\n conversation_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 ) VALUES (\n ${mintedSubmissionId},\n ${validated.conversationId},\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 )\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 yield* hitFailpoint(\"ledger:admit:after\", operation);\n return result;\n },\n );\n\n const markReady: SubmissionLedger[\"Service\"][\"markReady\"] = Effect.fn(\n \"DoSubmissionLedger.markReady\",\n )(function* (request: MarkReadyRequest) {\n const operation = \"ledger mark ready\";\n const validated = yield* Schema.decodeUnknownEffect(Schema.toType(MarkReadyRequest))(\n request,\n ).pipe(Effect.mapError(internalFailure(operation)));\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 if (submission.state !== \"admitted\") return;\n const now = yield* currentInstant;\n yield* sql`\n UPDATE effect_agent_submissions\n SET state = 'ready', ready_at = ${now.iso}\n WHERE submission_id = ${validated.submissionId}\n `.pipe(Effect.mapError(sqlFailure(operation)));\n }),\n );\n yield* hitFailpoint(\"ledger:mark-ready:after\", operation);\n });\n\n const lookup: SubmissionLedger[\"Service\"][\"lookup\"] = Effect.fn(\"DoSubmissionLedger.lookup\")(\n function* (request: SubmissionLookup) {\n const operation = \"ledger lookup\";\n const validated = yield* Schema.decodeUnknownEffect(Schema.toType(SubmissionLookup))(\n request,\n ).pipe(Effect.mapError(internalFailure(operation)));\n if (validated._tag === \"SubmissionLookupById\") {\n const row = yield* readSubmission(operation, validated.submissionId);\n if (Option.isNone(row)) return Option.none();\n return Option.some(yield* decodeSubmissionSnapshot(operation, row.value));\n }\n const rows = yield* sql<Record<string, unknown>>`\n SELECT ${sql.literal(SUBMISSION_COLUMNS)}\n FROM effect_agent_submissions\n WHERE conversation_id = ${validated.conversationId}\n AND principal = ${validated.principal}\n AND idempotency_key = ${validated.idempotencyKey}\n `.pipe(Effect.mapError(sqlFailure(operation)));\n const decoded = yield* decodeSubmissionRows(\n operation,\n `${validated.conversationId}/${validated.principal}/${validated.idempotencyKey}`,\n rows,\n );\n if (decoded.length > 1) {\n return yield* corruptionFailure(\n operation,\n \"effect_agent_submissions\",\n `${validated.conversationId}/${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 return Option.some(yield* decodeSubmissionSnapshot(operation, decoded[0]));\n },\n );\n\n // This LOCAL facet is the authoritative owner of every Conversation stored in this Durable\n // Object, so the key-scoped read IS the admission truth and the tri-state degenerates to\n // NotAdmitted or Admitted (SUB-031). `AdmissionIndeterminate` becomes real one layer out:\n // the WP2 routed decorator answers it when the OWNING Durable Object is unreachable.\n const resolveAdmission: SubmissionLedger[\"Service\"][\"resolveAdmission\"] = Effect.fn(\n \"DoSubmissionLedger.resolveAdmission\",\n )(function* (request: SubmissionLookupByKey) {\n const operation = \"ledger resolve admission\";\n const validated = yield* Schema.decodeUnknownEffect(Schema.toType(SubmissionLookupByKey))(\n request,\n ).pipe(Effect.mapError(internalFailure(operation)));\n const rows = yield* sql<Record<string, unknown>>`\n SELECT ${sql.literal(SUBMISSION_COLUMNS)}\n FROM effect_agent_submissions\n WHERE conversation_id = ${validated.conversationId}\n AND principal = ${validated.principal}\n AND idempotency_key = ${validated.idempotencyKey}\n `.pipe(Effect.mapError(sqlFailure(operation)));\n const decoded = yield* decodeSubmissionRows(\n operation,\n `${validated.conversationId}/${validated.principal}/${validated.idempotencyKey}`,\n rows,\n );\n if (decoded.length > 1) {\n return yield* corruptionFailure(\n operation,\n \"effect_agent_submissions\",\n `${validated.conversationId}/${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 return AdmissionAdmitted.make({\n submission: yield* decodeSubmissionSnapshot(operation, decoded[0]),\n });\n });\n\n const claim: SubmissionLedger[\"Service\"][\"claim\"] = Effect.fn(\"DoSubmissionLedger.claim\")(\n function* (request: ClaimRequest) {\n const operation = \"ledger claim\";\n const validated = yield* Schema.decodeUnknownEffect(Schema.toType(ClaimRequest))(\n request,\n ).pipe(Effect.mapError(internalFailure(operation)));\n const attemptId = `attempt-${yield* mintUuid(operation)}`;\n const ownershipToken = `owner-${yield* mintUuid(operation)}`;\n yield* hitFailpoint(\"ledger:claim:before\", operation);\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 conversation_id = ${validated.conversationId}\n AND state <> 'settled'\n ORDER BY queue_sequence ASC\n LIMIT 1\n `.pipe(Effect.mapError(sqlFailure(operation)));\n const heads = yield* decodeSubmissionRows(operation, validated.conversationId, headRows);\n if (heads.length === 0) return Option.none<Claim>();\n const head = heads[0];\n\n // A joining/joined head is host-owned and a suspended/unknown head is durably\n // blocked (DUR-017); the lane produces no claim and later ready work is never\n // skipped past the blocked head (DUR-004).\n if (\n head.state === \"joining\" ||\n head.state === \"joined\" ||\n head.state === \"suspended\" ||\n head.state === \"unknown\"\n ) {\n return Option.none<Claim>();\n }\n\n const now = yield* currentInstant;\n const ownership = yield* readOwnership(operation, head.submission_id);\n if (Option.isSome(ownership)) {\n const expiresAt = yield* timestampMillis(\n operation,\n head.submission_id,\n )(ownership.value.lease_expires_at);\n // A live lease blocks every new claim; expiry alone only revokes the liveness\n // assumption — correctness stays with producer-epoch fencing (D5). In DC a live\n // lease under another token can only come from an evicted incarnation.\n if (expiresAt > now.millis) return Option.none<Claim>();\n }\n\n // Bump the Conversation's producer epoch atomically with the claim so every stale\n // Attempt is fenced out of canonical appends (DUR-006). A Conversation that was\n // never materialized (eviction between admission and materialization) is created\n // here so recovery can claim first and re-materialize idempotently at this epoch.\n const conversations = yield* journal\n .getConversation(head.conversation_id)\n .pipe(Effect.mapError(internalFailure(operation)));\n let producerEpoch: number;\n if (conversations.length === 0) {\n producerEpoch = 1;\n yield* sql`\n INSERT INTO effect_agent_conversations (\n conversation_id,\n created_at,\n tail_sequence,\n tail_digest,\n producer_epoch\n ) VALUES (\n ${head.conversation_id},\n ${now.iso},\n 0,\n ${EMPTY_TAIL_DIGEST},\n ${producerEpoch}\n )\n `.pipe(Effect.mapError(sqlFailure(operation)));\n } else {\n producerEpoch = conversations[0].producer_epoch + 1;\n yield* sql`\n UPDATE effect_agent_conversations\n SET producer_epoch = ${producerEpoch}\n WHERE conversation_id = ${head.conversation_id}\n `.pipe(Effect.mapError(sqlFailure(operation)));\n }\n\n const leaseExpiresAt = new Date(now.millis + config.ownershipLeaseDuration).toISOString();\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 conversation_id,\n owner_producer_id,\n producer_epoch,\n claimed_at\n ) VALUES (\n ${attemptId},\n ${head.submission_id},\n ${head.conversation_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 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 yield* hitFailpoint(\"ledger:claim:after\", operation);\n return claimed;\n },\n );\n\n const renewOwnership: SubmissionLedger[\"Service\"][\"renewOwnership\"] = Effect.fn(\n \"DoSubmissionLedger.renewOwnership\",\n )(function* (request: RenewOwnershipRequest) {\n const operation = \"ledger renew ownership\";\n const validated = yield* Schema.decodeUnknownEffect(Schema.toType(RenewOwnershipRequest))(\n request,\n ).pipe(Effect.mapError(internalFailure(operation)));\n yield* hitFailpoint(\"ledger:renew:before\", operation);\n const renewal = yield* inWriteTransaction(\n operation,\n Effect.gen(function* () {\n const submission = yield* requireSubmission(operation, validated.submissionId);\n yield* requireOwnership(operation, submission, validated.ownershipToken);\n const now = yield* currentInstant;\n const leaseExpiresAt = new Date(now.millis + config.ownershipLeaseDuration).toISOString();\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 return yield* decodeOwnershipRenewal({\n ownershipToken: validated.ownershipToken,\n leaseExpiresAt,\n }).pipe(Effect.mapError(internalFailure(operation)));\n }),\n );\n yield* hitFailpoint(\"ledger:renew:after\", operation);\n return renewal;\n });\n\n const releaseOwnership: SubmissionLedger[\"Service\"][\"releaseOwnership\"] = Effect.fn(\n \"DoSubmissionLedger.releaseOwnership\",\n )(function* (request: ReleaseOwnershipRequest) {\n const operation = \"ledger release ownership\";\n const validated = yield* Schema.decodeUnknownEffect(Schema.toType(ReleaseOwnershipRequest))(\n request,\n ).pipe(Effect.mapError(internalFailure(operation)));\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 yield* requireOwnership(operation, submission, validated.ownershipToken);\n yield* sql`\n DELETE FROM effect_agent_submission_ownership\n WHERE submission_id = ${validated.submissionId}\n `.pipe(Effect.mapError(sqlFailure(operation)));\n if (submission.state === \"running\") {\n yield* sql`\n UPDATE effect_agent_submissions\n SET state = 'ready'\n WHERE submission_id = ${validated.submissionId}\n `.pipe(Effect.mapError(sqlFailure(operation)));\n }\n }),\n );\n yield* hitFailpoint(\"ledger:release:after\", operation);\n });\n\n const markInputApplied: SubmissionLedger[\"Service\"][\"markInputApplied\"] = Effect.fn(\n \"DoSubmissionLedger.markInputApplied\",\n )(function* (request: MarkInputAppliedRequest) {\n const operation = \"ledger mark input applied\";\n const validated = yield* Schema.decodeUnknownEffect(Schema.toType(MarkInputAppliedRequest))(\n request,\n ).pipe(Effect.mapError(internalFailure(operation)));\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 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 return yield* corruptionFailure(\n operation,\n \"effect_agent_submissions\",\n validated.submissionId,\n \"A different canonical input marker is already recorded for this Submission.\",\n );\n }\n yield* sql`\n UPDATE effect_agent_submissions\n SET\n input_applied_record_id = ${validated.recordId},\n input_applied_sequence = ${validated.sequence},\n state = CASE\n WHEN state IN ('admitted', 'ready', 'running') THEN 'input-applied'\n ELSE state\n END\n WHERE submission_id = ${validated.submissionId}\n `.pipe(Effect.mapError(sqlFailure(operation)));\n }),\n );\n yield* hitFailpoint(\"ledger:mark-input-applied:after\", operation);\n });\n\n const reserveSettlement: SubmissionLedger[\"Service\"][\"reserveSettlement\"] = Effect.fn(\n \"DoSubmissionLedger.reserveSettlement\",\n )(function* (request: SettlementReservation) {\n const operation = \"ledger reserve settlement\";\n const validated = yield* Schema.decodeUnknownEffect(Schema.toType(SettlementReservation))(\n request,\n ).pipe(Effect.mapError(internalFailure(operation)));\n const recordJson = yield* encodeRecordEnvelopeText(validated.record).pipe(\n Effect.mapError(internalFailure(operation)),\n );\n // The reserved record is appended canonically later; refuse over-bound payloads typed\n // before the reservation row exists.\n yield* journal\n .checkValueBound(operation, recordJson)\n .pipe(Effect.mapError(internalFailure(operation)));\n yield* hitFailpoint(\"ledger:reserve-settlement:before\", operation);\n const reserved = yield* inWriteTransaction(\n operation,\n Effect.gen(function* () {\n const existing = yield* readReservation(operation, validated.submissionId);\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 if (!identical) {\n return yield* SettlementConflict.make({\n submissionId: validated.submissionId,\n existingOutcome: existing.value.outcome,\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 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 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 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 if (\n validated.outcome === \"aborted\" &&\n (submission.state === \"ready\" || submission.state === \"terminalizing\")\n ) {\n const abortIntent = yield* readAbortIntent(operation, validated.submissionId);\n if (Option.isSome(abortIntent)) {\n const ownership = yield* readOwnership(operation, validated.submissionId);\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 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 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 yield* hitFailpoint(\"ledger:reserve-settlement:after\", operation);\n return reserved;\n });\n\n const finalizeSettlement: SubmissionLedger[\"Service\"][\"finalizeSettlement\"] = Effect.fn(\n \"DoSubmissionLedger.finalizeSettlement\",\n )(function* (request: SettlementFinalization) {\n const operation = \"ledger finalize settlement\";\n const validated = yield* Schema.decodeUnknownEffect(Schema.toType(SettlementFinalization))(\n request,\n ).pipe(Effect.mapError(internalFailure(operation)));\n yield* hitFailpoint(\"ledger:finalize-settlement:before\", operation);\n const settlement = yield* inWriteTransaction(\n operation,\n Effect.gen(function* () {\n const reservation = yield* readReservation(operation, validated.submissionId);\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 const submission = yield* requireSubmission(operation, validated.submissionId);\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 return yield* decodeSettlement({\n submissionId: validated.submissionId,\n settlementId: validated.settlementId,\n receiptId: submission.receipt_id,\n outcome: reservation.value.outcome,\n settledAt: reservation.value.finalized_at,\n }).pipe(Effect.mapError(internalFailure(operation)));\n }\n const now = yield* currentInstant;\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 return yield* decodeSettlement({\n submissionId: validated.submissionId,\n settlementId: validated.settlementId,\n receiptId: submission.receipt_id,\n outcome: reservation.value.outcome,\n settledAt: now.iso,\n }).pipe(Effect.mapError(internalFailure(operation)));\n }),\n );\n yield* hitFailpoint(\"ledger:finalize-settlement:after\", operation);\n return settlement;\n });\n\n const requestAbort: SubmissionLedger[\"Service\"][\"requestAbort\"] = Effect.fn(\n \"DoSubmissionLedger.requestAbort\",\n )(function* (request: AbortCommand) {\n const operation = \"ledger request abort\";\n const validated = yield* Schema.decodeUnknownEffect(Schema.toType(AbortCommand))(request).pipe(\n Effect.mapError(internalFailure(operation)),\n );\n yield* hitFailpoint(\"ledger:request-abort:before\", operation);\n const intent = yield* inWriteTransaction(\n operation,\n Effect.gen(function* () {\n const submission = yield* requireSubmission(operation, validated.submissionId);\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 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 const hostSubmissionId = yield* decodeSubmissionId(\n submission.joined_host_submission_id,\n ).pipe(Effect.mapError(internalFailure(operation)));\n return yield* JoinedToHost.make({\n submissionId: validated.submissionId,\n hostSubmissionId,\n });\n }\n const existing = yield* readAbortIntent(operation, validated.submissionId);\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 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 const canonicalRecordId = yield* canonicalAbortRecordId(\n operation,\n submission.conversation_id,\n validated.submissionId,\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 yield* hitFailpoint(\"ledger:request-abort:after\", operation);\n return intent;\n });\n\n const claimJoining: SubmissionLedger[\"Service\"][\"claimJoining\"] = Effect.fn(\n \"DoSubmissionLedger.claimJoining\",\n )(function* (request: ClaimJoiningRequest) {\n const operation = \"ledger claim joining\";\n const validated = yield* Schema.decodeUnknownEffect(Schema.toType(ClaimJoiningRequest))(\n request,\n ).pipe(Effect.mapError(internalFailure(operation)));\n yield* hitFailpoint(\"ledger:claim-joining:before\", operation);\n const claims = yield* inWriteTransaction(\n operation,\n Effect.gen(function* () {\n const host = yield* requireSubmission(operation, validated.hostSubmissionId);\n if (host.conversation_id !== validated.conversationId) {\n return yield* LedgerError.make({\n operation,\n message: `Host submission ${validated.hostSubmissionId} does not belong to conversation ${validated.conversationId}.`,\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 const laterRows = yield* sql<Record<string, unknown>>`\n SELECT ${sql.literal(SUBMISSION_COLUMNS)}\n FROM effect_agent_submissions\n WHERE conversation_id = ${validated.conversationId}\n AND queue_sequence > ${host.queue_sequence}\n ORDER BY queue_sequence ASC\n `.pipe(Effect.mapError(sqlFailure(operation)));\n const later = yield* decodeSubmissionRows(operation, validated.conversationId, laterRows);\n const claimed: Array<JoiningClaim> = [];\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 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 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 return claimed as ReadonlyArray<JoiningClaim>;\n }),\n );\n yield* hitFailpoint(\"ledger:claim-joining:after\", operation);\n return claims;\n });\n\n const markJoined: SubmissionLedger[\"Service\"][\"markJoined\"] = Effect.fn(\n \"DoSubmissionLedger.markJoined\",\n )(function* (request: MarkJoinedRequest) {\n const operation = \"ledger mark joined\";\n const validated = yield* Schema.decodeUnknownEffect(Schema.toType(MarkJoinedRequest))(\n request,\n ).pipe(Effect.mapError(internalFailure(operation)));\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 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 // 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 return yield* corruptionFailure(\n operation,\n \"effect_agent_submissions\",\n validated.submissionId,\n \"A different join marker is already recorded for this Submission.\",\n );\n }\n if (submission.state !== \"joining\" && submission.state !== \"joined\") {\n return yield* LedgerError.make({\n operation,\n message: `Cannot mark submission ${validated.submissionId} joined from state ${submission.state}.`,\n });\n }\n yield* sql`\n UPDATE effect_agent_submissions\n SET\n input_applied_record_id = ${validated.recordId},\n input_applied_sequence = ${validated.sequence},\n state = 'joined'\n WHERE submission_id = ${validated.submissionId}\n `.pipe(Effect.mapError(sqlFailure(operation)));\n }),\n );\n yield* hitFailpoint(\"ledger:mark-joined:after\", operation);\n });\n\n const revertJoining: SubmissionLedger[\"Service\"][\"revertJoining\"] = Effect.fn(\n \"DoSubmissionLedger.revertJoining\",\n )(function* (request: RevertJoiningRequest) {\n const operation = \"ledger revert joining\";\n const validated = yield* Schema.decodeUnknownEffect(Schema.toType(RevertJoiningRequest))(\n request,\n ).pipe(Effect.mapError(internalFailure(operation)));\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 // Idempotent and recovery-only: only a still-`joining` Submission reverts; an\n // already-joined (or already-reverted) Submission is a no-op (DUR-016).\n if (submission.state !== \"joining\") return;\n yield* sql`\n UPDATE effect_agent_submissions\n SET state = 'ready', joined_host_submission_id = NULL\n WHERE submission_id = ${validated.submissionId}\n `.pipe(Effect.mapError(sqlFailure(operation)));\n }),\n );\n yield* hitFailpoint(\"ledger:revert-joining:after\", operation);\n });\n\n const suspend: SubmissionLedger[\"Service\"][\"suspend\"] = Effect.fn(\"DoSubmissionLedger.suspend\")(\n function* (request: SuspendRequest) {\n const operation = \"ledger suspend\";\n const validated = yield* Schema.decodeUnknownEffect(Schema.toType(SuspendRequest))(\n request,\n ).pipe(Effect.mapError(internalFailure(operation)));\n const reasonJson = yield* encodeSuspensionReasonText(validated.reason).pipe(\n Effect.mapError(internalFailure(operation)),\n );\n yield* hitFailpoint(\"ledger:suspend:before\", operation);\n const outcome = yield* inWriteTransaction(\n operation,\n Effect.gen(function* () {\n const submission = yield* requireSubmission(operation, validated.submissionId);\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 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 if (Option.isSome(reservation)) {\n return yield* SettlementConflict.make({\n submissionId: validated.submissionId,\n existingOutcome: reservation.value.outcome,\n });\n }\n yield* requireOwnership(operation, submission, validated.ownershipToken);\n // A covering event that raced ahead of the suspend transaction resumes the caller\n // immediately WITHOUT releasing the lane (plan §2.6, §12). For WaitingForChild the\n // covering evidence is EITHER a locally settled child row OR a durable cross-store\n // notification marker: parent and child Conversations live in different Durable\n // Objects, and the port contract requires that a child settlement reported (via\n // `recordChildSettled` → marker) before this suspend commits is observed here.\n if (validated.reason._tag === \"ApprovalPending\") {\n const decisions = yield* readApprovalDecisions(operation, validated.submissionId);\n const decided = new Set(decisions.map((row) => row.tool_call_id));\n if (validated.reason.toolCallIds.every((toolCallId) => decided.has(toolCallId))) {\n return \"resume-immediately\" as SuspensionOutcome;\n }\n } else {\n const markers = yield* readChildSettlementMarkers(operation, validated.submissionId);\n const markerChildren = new Set(markers.map((row) => row.child_submission_id));\n let allSettled = true;\n for (const child of validated.reason.children) {\n const settled = yield* childProvablySettled(\n operation,\n markerChildren,\n child.childSubmissionId,\n );\n if (!settled) {\n allSettled = false;\n break;\n }\n }\n if (allSettled) {\n return \"resume-immediately\" as SuspensionOutcome;\n }\n }\n const now = yield* currentInstant;\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 return \"suspended\" as SuspensionOutcome;\n }),\n );\n yield* hitFailpoint(\"ledger:suspend:after\", operation);\n return outcome;\n },\n );\n\n /**\n * Once every pending call of a recorded ApprovalPending suspension has a decision intent,\n * the lane wakes: suspended → input-applied, suspension cleared (plan §2.6). A\n * WaitingForChild suspension wakes only through recordChildSettled. Runs inside the caller's\n * write transaction.\n */\n const wakeSuspendedIfCovered = Effect.fn(\"DoSubmissionLedger.wakeSuspendedIfCovered\")(function* (\n operation: string,\n submission: SubmissionRow,\n ): Effect.fn.Return<void, LedgerError> {\n if (submission.state !== \"suspended\" || submission.suspended_reason_json === null) return;\n 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 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 if (!reason.toolCallIds.every((toolCallId) => decided.has(toolCallId))) return;\n yield* sql`\n UPDATE effect_agent_submissions\n SET\n state = 'input-applied',\n suspended_reason_json = NULL,\n suspended_at = NULL\n WHERE submission_id = ${submission.submission_id}\n `.pipe(Effect.mapError(sqlFailure(operation)));\n });\n\n const recordApprovalDecision: SubmissionLedger[\"Service\"][\"recordApprovalDecision\"] = Effect.fn(\n \"DoSubmissionLedger.recordApprovalDecision\",\n )(function* (command: ApprovalDecisionCommand) {\n const operation = \"ledger record approval decision\";\n const validated = yield* Schema.decodeUnknownEffect(Schema.toType(ApprovalDecisionCommand))(\n command,\n ).pipe(Effect.mapError(internalFailure(operation)));\n yield* hitFailpoint(\"ledger:approval-decision:before\", operation);\n const intent = yield* inWriteTransaction(\n operation,\n Effect.gen(function* () {\n const submission = yield* requireSubmission(operation, validated.submissionId);\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 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 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 return yield* approvalIntentFromRow(operation, existing);\n }\n const now = yield* currentInstant;\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 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 yield* hitFailpoint(\"ledger:approval-decision:after\", operation);\n return intent;\n });\n\n const markUnknown: SubmissionLedger[\"Service\"][\"markUnknown\"] = Effect.fn(\n \"DoSubmissionLedger.markUnknown\",\n )(function* (request: MarkUnknownRequest) {\n const operation = \"ledger mark unknown\";\n const validated = yield* Schema.decodeUnknownEffect(Schema.toType(MarkUnknownRequest))(\n request,\n ).pipe(Effect.mapError(internalFailure(operation)));\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 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 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 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 const merged = [\n ...existingIds,\n ...validated.toolCallIds.filter((toolCallId) => !known.has(toolCallId)),\n ];\n const idsJson = yield* encodeToolCallIdsText(merged).pipe(\n Effect.mapError(internalFailure(operation)),\n );\n yield* sql`\n UPDATE effect_agent_submissions\n SET\n state = 'unknown',\n unknown_reason = ${submission.unknown_reason ?? validated.reason},\n unknown_tool_call_ids_json = ${idsJson}\n WHERE submission_id = ${validated.submissionId}\n `.pipe(Effect.mapError(sqlFailure(operation)));\n }),\n );\n yield* hitFailpoint(\"ledger:mark-unknown:after\", operation);\n });\n\n const recordUnknownResolution: SubmissionLedger[\"Service\"][\"recordUnknownResolution\"] = Effect.fn(\n \"DoSubmissionLedger.recordUnknownResolution\",\n )(function* (command: UnknownResolutionCommand) {\n const operation = \"ledger record unknown resolution\";\n const validated = yield* Schema.decodeUnknownEffect(Schema.toType(UnknownResolutionCommand))(\n command,\n ).pipe(Effect.mapError(internalFailure(operation)));\n const resolutionJson = yield* encodeUnknownResolutionText(validated.resolution).pipe(\n Effect.mapError(internalFailure(operation)),\n );\n yield* hitFailpoint(\"ledger:unknown-resolution:before\", operation);\n const intent = yield* inWriteTransaction(\n operation,\n Effect.gen(function* () {\n const submission = yield* requireSubmission(operation, validated.submissionId);\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 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 if (existing !== undefined && existing.resolution_json !== resolutionJson) {\n return yield* UnknownResolutionConflict.make({\n submissionId: validated.submissionId,\n toolCallId: validated.toolCallId,\n });\n }\n let resolved: UnknownResolutionIntent;\n if (existing !== undefined) {\n // Idempotent replay of the recorded intent (author/reason may differ; the stored\n // audit fields win, exactly like requestAbort).\n resolved = yield* unknownResolutionIntentFromRow(operation, existing);\n } else {\n const now = yield* currentInstant;\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 const resolution = yield* parseStoredJsonText(resolutionJson).pipe(\n Effect.mapError(internalFailure(operation)),\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 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 return resolved;\n }),\n );\n yield* hitFailpoint(\"ledger:unknown-resolution:after\", operation);\n return intent;\n });\n\n const recordChildSettled: SubmissionLedger[\"Service\"][\"recordChildSettled\"] = Effect.fn(\n \"DoSubmissionLedger.recordChildSettled\",\n )(function* (request: ChildSettledNotification) {\n const operation = \"ledger record child settled\";\n const validated = yield* Schema.decodeUnknownEffect(Schema.toType(ChildSettledNotification))(\n request,\n ).pipe(Effect.mapError(internalFailure(operation)));\n yield* hitFailpoint(\"ledger:child-settled:before\", operation);\n const outcome = yield* inWriteTransaction(\n operation,\n Effect.gen(function* () {\n const parent = yield* requireSubmission(operation, validated.parentSubmissionId);\n // The child's canonical Settlement is the authority for this wake. When the child's\n // row lives in THIS store (single-store latitude, and every conformance lane), an\n // unsettled child makes the notification a caller error exactly as on Node. When it\n // does not — the normal cross-DO case — the routed notification from the child's\n // owning Durable Object is the settlement evidence this store records durably.\n const child = yield* readSubmission(operation, validated.childSubmissionId);\n if (Option.isSome(child) && child.value.state !== \"settled\") {\n return yield* LedgerError.make({\n operation,\n message: `Child submission ${validated.childSubmissionId} has no recorded settlement.`,\n });\n }\n // Record the durable notification marker FIRST and unconditionally (idempotent):\n // the port's cross-store race guarantee requires that a notification committed\n // before the parent's suspend transaction is observed by that suspend's covering\n // check, even when the parent is not (or not yet) suspended.\n const now = yield* currentInstant;\n yield* sql`\n INSERT INTO effect_agent_child_settlements (\n parent_submission_id,\n child_submission_id,\n child_outcome,\n recorded_at\n ) VALUES (\n ${validated.parentSubmissionId},\n ${validated.childSubmissionId},\n ${Option.isSome(child) ? child.value.settled_outcome : null},\n ${now.iso}\n )\n ON CONFLICT (parent_submission_id, child_submission_id) DO NOTHING\n `.pipe(Effect.mapError(sqlFailure(operation)));\n\n if (parent.state !== \"suspended\" || parent.suspended_reason_json === null) {\n return \"not-waiting\" as ChildSettledOutcome;\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 if (reason._tag !== \"WaitingForChild\") {\n return \"not-waiting\" as ChildSettledOutcome;\n }\n if (\n !reason.children.some((entry) => entry.childSubmissionId === validated.childSubmissionId)\n ) {\n return \"not-waiting\" as ChildSettledOutcome;\n }\n // The parent wakes exactly when EVERY listed child is provably settled — from its\n // local row or a recorded marker (spec §12 step 10); replays re-run the coverage\n // check so a recovering caller wakes the lane idempotently.\n const markers = yield* readChildSettlementMarkers(operation, validated.parentSubmissionId);\n const markerChildren = new Set(markers.map((row) => row.child_submission_id));\n for (const entry of reason.children) {\n const settled = yield* childProvablySettled(\n operation,\n markerChildren,\n entry.childSubmissionId,\n );\n if (!settled) {\n return \"still-waiting\" as ChildSettledOutcome;\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 return \"woken\" as ChildSettledOutcome;\n }),\n );\n yield* hitFailpoint(\"ledger:child-settled:after\", operation);\n return outcome;\n });\n\n const reserveChildBudget: SubmissionLedger[\"Service\"][\"reserveChildBudget\"] = Effect.fn(\n \"DoSubmissionLedger.reserveChildBudget\",\n )(function* (request: ChildBudgetReservationRequest) {\n const operation = \"ledger reserve child budget\";\n const validated = yield* Schema.decodeUnknownEffect(\n Schema.toType(ChildBudgetReservationRequest),\n )(request).pipe(Effect.mapError(internalFailure(operation)));\n const allocationJson = yield* encodePersistedJsonText(validated.allocation).pipe(\n Effect.mapError(internalFailure(operation)),\n );\n yield* hitFailpoint(\"ledger:child-reservation:before\", operation);\n const reserved = yield* inWriteTransaction(\n operation,\n Effect.gen(function* () {\n const existing = yield* readChildReservation(operation, validated.reservationId);\n if (Option.isSome(existing)) {\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 existing.value.allocation_json === allocationJson;\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 return ReservedChildBudget.make({\n reservation: yield* childReservationSnapshotFromRow(operation, existing.value),\n replayed: true,\n });\n }\n const collision = yield* readChildReservationForCall(\n operation,\n validated.parentSubmissionId,\n validated.parentToolCallId,\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 // 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 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 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 return ReservedChildBudget.make({\n reservation: yield* childReservationSnapshotFromRow(operation, inserted.value),\n replayed: false,\n });\n }),\n );\n yield* hitFailpoint(\"ledger:child-reservation:after\", operation);\n return reserved;\n });\n\n const attachChildToReservation: SubmissionLedger[\"Service\"][\"attachChildToReservation\"] =\n Effect.fn(\"DoSubmissionLedger.attachChildToReservation\")(function* (\n request: AttachChildToReservationRequest,\n ) {\n const operation = \"ledger attach child to reservation\";\n const validated = yield* Schema.decodeUnknownEffect(\n Schema.toType(AttachChildToReservationRequest),\n )(request).pipe(Effect.mapError(internalFailure(operation)));\n yield* hitFailpoint(\"ledger:child-attach:before\", operation);\n const attached = yield* inWriteTransaction(\n operation,\n Effect.gen(function* () {\n const existing = yield* readChildReservation(operation, validated.reservationId);\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 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 yield* requireOwnership(operation, parent, validated.ownershipToken);\n if (existing.value.status !== \"reserved\") {\n return yield* ChildReservationConflict.make({\n reservationId: validated.reservationId,\n status: existing.value.status,\n message: `Cannot attach a child to a ${existing.value.status} reservation.`,\n });\n }\n // Unlike the single-store Node adapter, the admitted child's row lives in ANOTHER\n // Durable Object, so no local existence check is possible here. The canonical\n // `SubagentStarted` record remains the attachment's repair authority (DUR-015),\n // and the coordinator only attaches after the child's admission committed.\n yield* sql`\n UPDATE effect_agent_child_reservations\n SET child_submission_id = ${validated.childSubmissionId}\n WHERE reservation_id = ${validated.reservationId}\n `.pipe(Effect.mapError(sqlFailure(operation)));\n const updated = yield* readChildReservation(operation, validated.reservationId);\n 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 return yield* childReservationSnapshotFromRow(operation, updated.value);\n }),\n );\n yield* hitFailpoint(\"ledger:child-attach:after\", operation);\n return attached;\n });\n\n const beginChildBudgetRelease: SubmissionLedger[\"Service\"][\"beginChildBudgetRelease\"] = Effect.fn(\n \"DoSubmissionLedger.beginChildBudgetRelease\",\n )(function* (request: BeginChildBudgetReleaseRequest) {\n const operation = \"ledger begin child budget release\";\n const validated = yield* Schema.decodeUnknownEffect(\n Schema.toType(BeginChildBudgetReleaseRequest),\n )(request).pipe(Effect.mapError(internalFailure(operation)));\n const accountingJson = yield* encodePersistedJsonText(validated.accounting).pipe(\n Effect.mapError(internalFailure(operation)),\n );\n yield* hitFailpoint(\"ledger:child-release-pending:before\", operation);\n const frozen = yield* inWriteTransaction(\n operation,\n Effect.gen(function* () {\n const existing = yield* readChildReservation(operation, validated.reservationId);\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 // 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 (existing.value.accounting_json === accountingJson) {\n return yield* childReservationSnapshotFromRow(operation, existing.value);\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 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 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 return yield* childReservationSnapshotFromRow(operation, updated.value);\n }),\n );\n yield* hitFailpoint(\"ledger:child-release-pending:after\", operation);\n return frozen;\n });\n\n const releaseChildBudget: SubmissionLedger[\"Service\"][\"releaseChildBudget\"] = Effect.fn(\n \"DoSubmissionLedger.releaseChildBudget\",\n )(function* (request: ReleaseChildBudgetRequest) {\n const operation = \"ledger release child budget\";\n const validated = yield* Schema.decodeUnknownEffect(Schema.toType(ReleaseChildBudgetRequest))(\n request,\n ).pipe(Effect.mapError(internalFailure(operation)));\n yield* hitFailpoint(\"ledger:child-release:before\", operation);\n const released = yield* inWriteTransaction(\n operation,\n Effect.gen(function* () {\n const existing = yield* readChildReservation(operation, validated.reservationId);\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 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 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 return yield* childReservationSnapshotFromRow(operation, updated.value);\n }),\n );\n yield* hitFailpoint(\"ledger:child-release:after\", operation);\n return released;\n });\n\n interface ScanCursor {\n readonly conversationId: string;\n readonly queueSequence: number;\n }\n\n const scanPage = Effect.fn(\"DoSubmissionLedger.scanPage\")(function* (\n cursor: ScanCursor | undefined,\n ): Effect.fn.Return<\n readonly [ReadonlyArray<SubmissionSnapshot>, Option.Option<ScanCursor | undefined>],\n LedgerError\n > {\n const operation = \"ledger scan nonterminal\";\n 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 conversation_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 conversation_id > ${cursor.conversationId}\n OR (\n conversation_id = ${cursor.conversationId}\n AND queue_sequence > ${cursor.queueSequence}\n )\n )\n ORDER BY conversation_id ASC, queue_sequence ASC\n LIMIT ${SCAN_PAGE_SIZE}\n `\n ).pipe(Effect.mapError(sqlFailure(operation)));\n const decoded = yield* decodeSubmissionRows(operation, \"nonterminal_scan\", rows);\n const snapshots = yield* Effect.forEach(decoded, (row) =>\n decodeSubmissionSnapshot(operation, row),\n );\n const last = decoded[decoded.length - 1];\n const next: Option.Option<ScanCursor | undefined> =\n last === undefined || decoded.length < SCAN_PAGE_SIZE\n ? Option.none()\n : Option.some({\n conversationId: last.conversation_id,\n queueSequence: last.queue_sequence,\n });\n return [snapshots, next] as const;\n });\n\n const scanNonterminal: Stream.Stream<SubmissionSnapshot, LedgerError> = Stream.paginate(\n undefined as ScanCursor | undefined,\n scanPage,\n );\n\n const loadRecoverySnapshot: SubmissionLedger[\"Service\"][\"loadRecoverySnapshot\"] = Effect.fn(\n \"DoSubmissionLedger.loadRecoverySnapshot\",\n )(function* (request: RecoverySnapshotRequest) {\n const operation = \"ledger load recovery snapshot\";\n const validated = yield* Schema.decodeUnknownEffect(Schema.toType(RecoverySnapshotRequest))(\n request,\n ).pipe(Effect.mapError(internalFailure(operation)));\n return yield* sql\n .withTransaction(\n Effect.gen(function* () {\n const submissionRow = yield* requireSubmission(operation, validated.submissionId);\n const submission = yield* decodeSubmissionSnapshot(operation, submissionRow);\n\n let ownership: OwnershipSnapshot | undefined;\n const ownershipRow = yield* readOwnership(operation, validated.submissionId);\n 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 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 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 const settlementId = yield* Schema.decodeUnknownEffect(\n SettlementReservationSnapshot.fields.settlementId,\n )(reservationRow.value.settlement_id).pipe(Effect.mapError(internalFailure(operation)));\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 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 const joinSubmissions = yield* decodeSubmissionRows(\n operation,\n validated.submissionId,\n joinRows,\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 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 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 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 const approvalDecisions = yield* Effect.forEach(decisionRows, (row) =>\n approvalIntentFromRow(operation, row),\n );\n\n const resolutionRows = yield* readUnknownResolutions(operation, validated.submissionId);\n const unknownResolutions = yield* Effect.forEach(resolutionRows, (row) =>\n unknownResolutionIntentFromRow(operation, row),\n );\n\n // Parent-side subagent view: this Submission's child budget reservations in parent\n // Tool Call order, plus each attached child's current lane state (a disposable\n // derived view; canonical records stay the recovery truth, DUR-015). The child's\n // state comes from its local row when this store holds it, and otherwise from the\n // durable cross-store settlement marker; a child that is neither local nor marked\n // settled is enriched by the routed per-child lookup one layer out (plan §1.3).\n const childReservationRows = yield* sql<Record<string, unknown>>`\n SELECT ${sql.literal(CHILD_RESERVATION_COLUMNS)}\n FROM effect_agent_child_reservations\n WHERE parent_submission_id = ${validated.submissionId}\n ORDER BY parent_tool_call_id ASC\n `.pipe(Effect.mapError(sqlFailure(operation)));\n const decodedChildReservations = yield* decodeChildReservationRows(\n operation,\n validated.submissionId,\n childReservationRows,\n );\n const childReservations = yield* Effect.forEach(decodedChildReservations, (row) =>\n childReservationSnapshotFromRow(operation, row),\n );\n const markers = yield* readChildSettlementMarkers(operation, validated.submissionId);\n const markersByChild = new Map(markers.map((row) => [row.child_submission_id, row]));\n const childAttachments: Array<ChildAttachmentSnapshot> = [];\n for (const row of decodedChildReservations) {\n if (row.child_submission_id === null) continue;\n const child = yield* readSubmission(operation, row.child_submission_id);\n if (Option.isSome(child)) {\n childAttachments.push(\n yield* decodeChildAttachmentSnapshot({\n toolCallId: row.parent_tool_call_id,\n childSubmissionId: row.child_submission_id,\n childState: child.value.state,\n ...(child.value.settled_outcome === null\n ? {}\n : { childOutcome: child.value.settled_outcome }),\n }).pipe(Effect.mapError(internalFailure(operation))),\n );\n continue;\n }\n const marker = markersByChild.get(row.child_submission_id);\n if (marker === undefined) continue;\n childAttachments.push(\n yield* decodeChildAttachmentSnapshot({\n toolCallId: row.parent_tool_call_id,\n childSubmissionId: row.child_submission_id,\n childState: \"settled\",\n ...(marker.child_outcome === null ? {} : { childOutcome: marker.child_outcome }),\n }).pipe(Effect.mapError(internalFailure(operation))),\n );\n }\n\n let parentLinkage: ParentLinkage | undefined;\n if (\n submissionRow.parent_submission_id !== null &&\n submissionRow.parent_tool_call_id !== null\n ) {\n parentLinkage = yield* decodeParentLinkage({\n parentSubmissionId: submissionRow.parent_submission_id,\n parentToolCallId: submissionRow.parent_tool_call_id,\n }).pipe(Effect.mapError(internalFailure(operation)));\n }\n\n return RecoverySnapshot.make({\n submission,\n joins,\n approvalDecisions,\n unknownResolutions,\n childReservations,\n childAttachments,\n ...(parentLinkage === undefined ? {} : { parentLinkage }),\n ...(hostSubmissionId === undefined ? {} : { hostSubmissionId }),\n ...(suspension === undefined ? {} : { suspension }),\n ...(ownership === undefined ? {} : { ownership }),\n ...(inputApplied === undefined ? {} : { inputApplied }),\n ...(reservation === undefined ? {} : { reservation }),\n ...(abortIntent === undefined ? {} : { abortIntent }),\n });\n }),\n )\n .pipe(Effect.catchTag(\"SqlError\", (error) => Effect.fail(sqlFailure(operation)(error))));\n });\n\n return Context.make(\n SubmissionLedger,\n SubmissionLedger.of({\n capabilities,\n admit,\n markReady,\n lookup,\n resolveAdmission,\n claim,\n renewOwnership,\n releaseOwnership,\n markInputApplied,\n reserveSettlement,\n finalizeSettlement,\n requestAbort,\n claimJoining,\n markJoined,\n revertJoining,\n suspend,\n recordApprovalDecision,\n markUnknown,\n recordUnknownResolution,\n recordChildSettled,\n reserveChildBudget,\n attachChildToReservation,\n beginChildBudgetRelease,\n releaseChildBudget,\n scanNonterminal,\n loadRecoverySnapshot,\n }),\n );\n});\n\n/**\n * Durable Object SubmissionLedger implementation sharing the journal's private SQLite\n * database, storage-backed transaction discipline, and producer-epoch fencing substrate.\n * Configuration, failpoint, SQL, and Crypto authority stay visible in the input channel.\n */\nexport const submissionLedgerLayer: Layer.Layer<\n SubmissionLedger,\n DoStorageInitializationError,\n DoStorageConfig | DoStorageFailpoint | SqlClientService.SqlClient | Crypto.Crypto\n> = Layer.effectContext(makeServices());\n\n/**\n * A composition-root convenience Layer for the durable Submission Ledger. Point it at the\n * same `ctx.storage` as the ConversationStore so claims fence the same producer epochs.\n */\nexport const ledgerLayer = (\n options: DoStorageOptions,\n): Layer.Layer<SubmissionLedger, DoStorageInitializationError> =>\n submissionLedgerLayer.pipe(\n Layer.provide(\n Layer.mergeAll(\n storageConfigLayer(options),\n storageFailpointLayer(options),\n SqliteClient.layer({ storage: options.storage }),\n BrowserCrypto.layer,\n ),\n ),\n );\n","import {\n AbortCommand,\n AbortIntent,\n AdmissionConflict,\n AdmissionRequest,\n AdmissionResolution,\n AdmissionResult,\n AppendConflict,\n AppendResult,\n CanonicalRecordEnvelope,\n ChildSettledNotification,\n ChildSettledOutcome,\n ConversationExport,\n ConversationExportRequest,\n ConversationMaterialization,\n ConversationNotMaterialized,\n ConversationRead,\n ConversationStoreError,\n ConversationTail,\n ConversationTailRequest,\n FenceRejected,\n FencedAppendRequest,\n JoinedToHost,\n LedgerError,\n MarkReadyRequest,\n SettlementConflict,\n SubmissionLookup,\n SubmissionLookupByKey,\n SubmissionSnapshot,\n} from \"@effect-agent/session\";\nimport { Schema } from \"effect\";\n\n/**\n * The cross-Durable-Object port protocol (plan §1.3, D-P6-3): Schema request/response/error\n * envelopes for the CLOSED route-capable subset of the session ports. One Conversation's\n * Durable Object executes another Conversation's request against its OWN local facets; the\n * envelopes here are the only values that cross the Object boundary, and they are\n * transport-agnostic — native Durable Object JS RPC is the shipped carrier, fetch-with-JSON\n * the documented fallback, and both move the same Schema-encoded JSON.\n *\n * The closed subset is exactly the set of operations the durable coordinator performs against\n * a FOREIGN Conversation (parent/child establishment, status checks, abort propagation,\n * child-settlement notification, and the child-conversation store operations used by\n * establishment, `verifySettledChild`, and result projection):\n *\n * - ledger: `admit`, `markReady`, `lookup`, `resolveAdmission`, `requestAbort`,\n * `recordChildSettled`;\n * - store: `materialize`, `append`, `read` (one page), `inspectTail`, `export`.\n *\n * Every other port operation is lane-local by construction and is NOT given an envelope:\n * honesty over accidental distribution — the routing layer fails such calls fast and typed\n * instead of quietly widening the distributed surface.\n *\n * Failures cross the boundary as the `PortFailure` union and re-decode on the caller side to\n * the SAME tagged error types the local facet would have produced, so routed calls keep\n * error-tag fidelity. `cause` chains inside `LedgerError`/`ConversationStoreError` travel as\n * Schema defects and do not claim instance fidelity across Objects (plan §2.8).\n */\n\n/** Ceiling for protocol diagnostic strings; matches `AdmissionIndeterminate.reason`. */\nexport const MAX_PORT_DIAGNOSTIC_LENGTH = 4_096;\n\nconst BoundedDiagnostic = Schema.String.check(Schema.isMaxLength(MAX_PORT_DIAGNOSTIC_LENGTH));\n\n/** Truncate a diagnostic string to the protocol's bounded diagnostic length. */\nexport const boundPortDiagnostic = (value: string): string =>\n value.length > MAX_PORT_DIAGNOSTIC_LENGTH\n ? `${value.slice(0, MAX_PORT_DIAGNOSTIC_LENGTH - 3)}...`\n : value;\n\n/**\n * The envelope itself could not be honored: the receiving Object could not decode the\n * request, or a response could not be encoded/decoded. It never carries port semantics —\n * callers fold it into the operation's base error (`LedgerError`/`ConversationStoreError`),\n * except `resolveAdmission`, which folds it into `AdmissionIndeterminate` because a\n * non-answer is never proof of absence (SUB-031).\n */\nexport class PortProtocolError extends Schema.TaggedError<PortProtocolError>()(\n \"PortProtocolError\",\n {\n message: BoundedDiagnostic,\n },\n) {}\n\n// ---------------------------------------------------------------------------\n// Requests\n// ---------------------------------------------------------------------------\n\n/** Routed `SubmissionLedger.admit` — child establishment admits INTO the owning Object. */\nexport class LedgerAdmitCall extends Schema.TaggedClass<LedgerAdmitCall>(\n \"@effect-agent/storage-cloudflare/LedgerAdmitCall\",\n)(\"LedgerAdmit\", {\n request: AdmissionRequest,\n}) {}\n\n/** Routed `SubmissionLedger.markReady` for a Submission owned by another Object. */\nexport class LedgerMarkReadyCall extends Schema.TaggedClass<LedgerMarkReadyCall>(\n \"@effect-agent/storage-cloudflare/LedgerMarkReadyCall\",\n)(\"LedgerMarkReady\", {\n request: MarkReadyRequest,\n}) {}\n\n/** Routed `SubmissionLedger.lookup` (by identity or scoped idempotency key). */\nexport class LedgerLookupCall extends Schema.TaggedClass<LedgerLookupCall>(\n \"@effect-agent/storage-cloudflare/LedgerLookupCall\",\n)(\"LedgerLookup\", {\n request: SubmissionLookup,\n}) {}\n\n/** Routed `SubmissionLedger.resolveAdmission` — the SUB-031 tri-state authority call. */\nexport class LedgerResolveAdmissionCall extends Schema.TaggedClass<LedgerResolveAdmissionCall>(\n \"@effect-agent/storage-cloudflare/LedgerResolveAdmissionCall\",\n)(\"LedgerResolveAdmission\", {\n request: SubmissionLookupByKey,\n}) {}\n\n/** Routed `SubmissionLedger.requestAbort` — abort propagation across Objects. */\nexport class LedgerRequestAbortCall extends Schema.TaggedClass<LedgerRequestAbortCall>(\n \"@effect-agent/storage-cloudflare/LedgerRequestAbortCall\",\n)(\"LedgerRequestAbort\", {\n request: AbortCommand,\n}) {}\n\n/** Routed `SubmissionLedger.recordChildSettled` — the child→parent durable notification. */\nexport class LedgerRecordChildSettledCall extends Schema.TaggedClass<LedgerRecordChildSettledCall>(\n \"@effect-agent/storage-cloudflare/LedgerRecordChildSettledCall\",\n)(\"LedgerRecordChildSettled\", {\n request: ChildSettledNotification,\n}) {}\n\n/** Routed `ConversationStore.materialize` against the owning Object. */\nexport class StoreMaterializeCall extends Schema.TaggedClass<StoreMaterializeCall>(\n \"@effect-agent/storage-cloudflare/StoreMaterializeCall\",\n)(\"StoreMaterialize\", {\n request: ConversationMaterialization,\n}) {}\n\n/** Routed `ConversationStore.append` against the owning Object. */\nexport class StoreAppendCall extends Schema.TaggedClass<StoreAppendCall>(\n \"@effect-agent/storage-cloudflare/StoreAppendCall\",\n)(\"StoreAppend\", {\n request: FencedAppendRequest,\n}) {}\n\n/** Routed one-page `ConversationStore.read`; the page bound is the request's own `limit`. */\nexport class StoreReadPageCall extends Schema.TaggedClass<StoreReadPageCall>(\n \"@effect-agent/storage-cloudflare/StoreReadPageCall\",\n)(\"StoreReadPage\", {\n request: ConversationRead,\n}) {}\n\n/** Routed `ConversationStore.inspectTail` against the owning Object. */\nexport class StoreInspectTailCall extends Schema.TaggedClass<StoreInspectTailCall>(\n \"@effect-agent/storage-cloudflare/StoreInspectTailCall\",\n)(\"StoreInspectTail\", {\n request: ConversationTailRequest,\n}) {}\n\n/** Routed `ConversationStore.export` against the owning Object. */\nexport class StoreExportCall extends Schema.TaggedClass<StoreExportCall>(\n \"@effect-agent/storage-cloudflare/StoreExportCall\",\n)(\"StoreExport\", {\n request: ConversationExportRequest,\n}) {}\n\n/** Every request that may cross a Durable Object boundary — the CLOSED route-capable subset. */\nexport const PortRequest = Schema.Union([\n LedgerAdmitCall,\n LedgerMarkReadyCall,\n LedgerLookupCall,\n LedgerResolveAdmissionCall,\n LedgerRequestAbortCall,\n LedgerRecordChildSettledCall,\n StoreMaterializeCall,\n StoreAppendCall,\n StoreReadPageCall,\n StoreInspectTailCall,\n StoreExportCall,\n]);\nexport type PortRequest = typeof PortRequest.Type;\n\n/** The wire form of one port request (what a transport actually carries). */\nexport type PortRequestEnvelope = typeof PortRequest.Encoded;\n\n// ---------------------------------------------------------------------------\n// Results\n// ---------------------------------------------------------------------------\n\nexport class LedgerAdmitResult extends Schema.TaggedClass<LedgerAdmitResult>(\n \"@effect-agent/storage-cloudflare/LedgerAdmitResult\",\n)(\"LedgerAdmitResult\", {\n result: AdmissionResult,\n}) {}\n\nexport class LedgerMarkReadyResult extends Schema.TaggedClass<LedgerMarkReadyResult>(\n \"@effect-agent/storage-cloudflare/LedgerMarkReadyResult\",\n)(\"LedgerMarkReadyResult\", {}) {}\n\n/** `submission` is absent exactly when the lookup answered `Option.none`. */\nexport class LedgerLookupResult extends Schema.TaggedClass<LedgerLookupResult>(\n \"@effect-agent/storage-cloudflare/LedgerLookupResult\",\n)(\"LedgerLookupResult\", {\n submission: Schema.optionalKey(SubmissionSnapshot),\n}) {}\n\nexport class LedgerResolveAdmissionResult extends Schema.TaggedClass<LedgerResolveAdmissionResult>(\n \"@effect-agent/storage-cloudflare/LedgerResolveAdmissionResult\",\n)(\"LedgerResolveAdmissionResult\", {\n resolution: AdmissionResolution,\n}) {}\n\nexport class LedgerRequestAbortResult extends Schema.TaggedClass<LedgerRequestAbortResult>(\n \"@effect-agent/storage-cloudflare/LedgerRequestAbortResult\",\n)(\"LedgerRequestAbortResult\", {\n intent: AbortIntent,\n}) {}\n\nexport class LedgerRecordChildSettledResult extends Schema.TaggedClass<LedgerRecordChildSettledResult>(\n \"@effect-agent/storage-cloudflare/LedgerRecordChildSettledResult\",\n)(\"LedgerRecordChildSettledResult\", {\n outcome: ChildSettledOutcome,\n}) {}\n\nexport class StoreMaterializeResult extends Schema.TaggedClass<StoreMaterializeResult>(\n \"@effect-agent/storage-cloudflare/StoreMaterializeResult\",\n)(\"StoreMaterializeResult\", {}) {}\n\nexport class StoreAppendResult extends Schema.TaggedClass<StoreAppendResult>(\n \"@effect-agent/storage-cloudflare/StoreAppendResult\",\n)(\"StoreAppendResult\", {\n result: AppendResult,\n}) {}\n\n/** One page of canonical records, bounded by the request's `limit` (≤ 1,024). */\nexport class StoreReadPageResult extends Schema.TaggedClass<StoreReadPageResult>(\n \"@effect-agent/storage-cloudflare/StoreReadPageResult\",\n)(\"StoreReadPageResult\", {\n records: Schema.Array(CanonicalRecordEnvelope).check(Schema.isMaxLength(1_024)),\n}) {}\n\nexport class StoreInspectTailResult extends Schema.TaggedClass<StoreInspectTailResult>(\n \"@effect-agent/storage-cloudflare/StoreInspectTailResult\",\n)(\"StoreInspectTailResult\", {\n tail: ConversationTail,\n}) {}\n\nexport class StoreExportResult extends Schema.TaggedClass<StoreExportResult>(\n \"@effect-agent/storage-cloudflare/StoreExportResult\",\n)(\"StoreExportResult\", {\n export: ConversationExport,\n}) {}\n\n/** Every successful routed result. Callers narrow by the tag their request implies. */\nexport const PortResult = Schema.Union([\n LedgerAdmitResult,\n LedgerMarkReadyResult,\n LedgerLookupResult,\n LedgerResolveAdmissionResult,\n LedgerRequestAbortResult,\n LedgerRecordChildSettledResult,\n StoreMaterializeResult,\n StoreAppendResult,\n StoreReadPageResult,\n StoreInspectTailResult,\n StoreExportResult,\n]);\nexport type PortResult = typeof PortResult.Type;\n\n// ---------------------------------------------------------------------------\n// Failures and the response envelope\n// ---------------------------------------------------------------------------\n\n/**\n * Every typed failure a route-capable operation can produce on its owning Object, plus the\n * protocol's own `PortProtocolError`. Members re-decode to the SAME tagged classes the\n * session ports declare, so a routed caller observes identical error tags and fields.\n */\nexport const PortFailure = Schema.Union([\n AdmissionConflict,\n SettlementConflict,\n JoinedToHost,\n LedgerError,\n ConversationStoreError,\n ConversationNotMaterialized,\n AppendConflict,\n FenceRejected,\n PortProtocolError,\n]);\nexport type PortFailure = typeof PortFailure.Type;\n\n/** The routed operation succeeded on its owning Object. */\nexport class PortSucceeded extends Schema.TaggedClass<PortSucceeded>(\n \"@effect-agent/storage-cloudflare/PortSucceeded\",\n)(\"PortSucceeded\", {\n result: PortResult,\n}) {}\n\n/** The routed operation failed TYPED on its owning Object; the failure re-decodes verbatim. */\nexport class PortFailed extends Schema.TaggedClass<PortFailed>(\n \"@effect-agent/storage-cloudflare/PortFailed\",\n)(\"PortFailed\", {\n failure: PortFailure,\n}) {}\n\n/** The uniform answer of one `portCall`: op-specific success or a re-decodable typed failure. */\nexport const PortResponse = Schema.Union([PortSucceeded, PortFailed]);\nexport type PortResponse = typeof PortResponse.Type;\n\n/** The wire form of one port response (what a transport actually carries). */\nexport type PortResponseEnvelope = typeof PortResponse.Encoded;\n\n// ---------------------------------------------------------------------------\n// Codecs\n// ---------------------------------------------------------------------------\n\nexport const encodePortRequest = Schema.encodeEffect(PortRequest);\nexport const decodePortRequest = Schema.decodeUnknownEffect(PortRequest);\nexport const encodePortResponse = Schema.encodeEffect(PortResponse);\nexport const decodePortResponse = Schema.decodeUnknownEffect(PortResponse);\n","import {\n AdmissionIndeterminate,\n AppendConflict,\n ChildAttachmentSnapshot,\n ConversationMaterialization,\n ConversationNotMaterialized,\n ConversationStore,\n ConversationStoreError,\n FenceRejected,\n JoinedToHost,\n LedgerError,\n RecoverySnapshot,\n SettlementConflict,\n SubmissionLedger,\n SubmissionLookupById,\n type AdmissionConflict,\n type SubmissionLookupByKey,\n type SubmissionSnapshot,\n} from \"@effect-agent/session\";\nimport { Context, Effect, Layer, Option, Schema, Stream } from \"effect\";\n\nimport {\n boundPortDiagnostic,\n decodePortRequest,\n decodePortResponse,\n encodePortRequest,\n encodePortResponse,\n LedgerAdmitCall,\n LedgerAdmitResult,\n LedgerLookupCall,\n LedgerLookupResult,\n LedgerMarkReadyCall,\n LedgerMarkReadyResult,\n LedgerRecordChildSettledCall,\n LedgerRecordChildSettledResult,\n LedgerRequestAbortCall,\n LedgerRequestAbortResult,\n LedgerResolveAdmissionCall,\n LedgerResolveAdmissionResult,\n PortFailed,\n PortProtocolError,\n PortSucceeded,\n StoreAppendCall,\n StoreAppendResult,\n StoreExportCall,\n StoreExportResult,\n StoreInspectTailCall,\n StoreInspectTailResult,\n StoreMaterializeCall,\n StoreMaterializeResult,\n StoreReadPageCall,\n StoreReadPageResult,\n type PortFailure,\n type PortRequest,\n type PortRequestEnvelope,\n type PortResponse,\n type PortResult,\n} from \"./port-protocol.ts\";\n\ntype ConversationId = ConversationMaterialization[\"conversationId\"];\ntype SubmissionId = SubmissionSnapshot[\"submissionId\"];\n\nconst ConversationIdSchema = ConversationMaterialization.fields.conversationId;\nconst decodeConversationId = Schema.decodeUnknownEffect(ConversationIdSchema);\n\n/**\n * The ledger row bound routable Submission identities must respect (mirrors the local\n * facet's `MAX_IDENTIFIER_LENGTH`; the minting side already refuses longer identities typed\n * at admission, so a longer identity presented here cannot name any stored row).\n */\nconst MAX_ROUTABLE_SUBMISSION_ID_LENGTH = 1_024;\n\n/** The `{uuidv7}` head of a DC-minted routable Submission identity. */\nconst UUID_HEAD_PATTERN =\n /^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$/;\n\n/**\n * A transport could not deliver a port request to (or an answer from) the owning\n * Conversation's Durable Object. `retryable` carries the platform's own stub signal when one\n * exists. This error never crosses the wire — it is the CALLER-side evidence that the\n * authority was unreachable, which is exactly the case `AdmissionIndeterminate` was\n * specified for (SUB-031).\n */\nexport class PortTransportError extends Schema.TaggedError<PortTransportError>()(\n \"PortTransportError\",\n {\n target: Schema.String,\n message: Schema.String,\n retryable: Schema.optionalKey(Schema.Boolean),\n cause: Schema.optionalKey(Schema.Defect()),\n },\n) {}\n\n/**\n * Build a `PortTransportError` from an arbitrary thrown transport cause, preserving the\n * platform stub's own `retryable` signal when present.\n */\nexport const portTransportFailure = (target: string, cause: unknown): PortTransportError => {\n const message = cause instanceof Error ? cause.message : String(cause);\n let retryable: boolean | undefined;\n if (typeof cause === \"object\" && cause !== null && \"retryable\" in cause) {\n const signal = cause.retryable;\n if (typeof signal === \"boolean\") retryable = signal;\n }\n return PortTransportError.make({\n target,\n message: boundPortDiagnostic(message),\n ...(retryable === undefined ? {} : { retryable }),\n cause,\n });\n};\n\n/**\n * Delivery of Schema-encoded port envelopes to the Durable Object that owns a FOREIGN\n * Conversation (plan §1.3, D-P6-3). The shipped implementation (platform-cloudflare, WP3)\n * calls the owner's `portCall` over native Durable Object JS RPC via\n * `namespace.idFromName(conversationId)`; the protocol is transport-agnostic and any carrier\n * that moves the encoded envelopes verbatim satisfies this service. Implementations MUST\n * surface every delivery problem as `PortTransportError` and must never fabricate an answer.\n */\nexport class ConversationPortTransport extends Context.Service<\n ConversationPortTransport,\n {\n readonly call: (\n conversationId: ConversationId,\n request: PortRequestEnvelope,\n ) => Effect.Effect<unknown, PortTransportError>;\n }\n>()(\"@effect-agent/storage-cloudflare/ConversationPortTransport\") {}\n\n/** Construction options shared by both routed port Layers. */\nexport interface RoutedPortOptions {\n /**\n * The Conversation this Durable Object owns (the Object identity rule is\n * `namespace.idFromName(conversationId)`). Requests addressed here execute on the local\n * facet; requests addressed anywhere else route through the transport or fail fast typed.\n */\n readonly localConversationId: ConversationId;\n}\n\n/** Where one port request must execute. */\ntype RouteTarget =\n | { readonly _tag: \"local\" }\n | { readonly _tag: \"foreign\"; readonly conversationId: ConversationId };\n\nconst LOCAL: RouteTarget = { _tag: \"local\" };\n\n/**\n * Parse a DC-minted routable Submission identity — `{uuidv7}:{conversationId}`, split at the\n * FIRST `:` because the Conversation tail may itself contain colons (D-P6-5). This adapter\n * minted the format at admission and is the ONLY component that parses it; identities that do\n * not carry the minted shape (no separator, non-UUID head, empty tail) fall back to the local\n * facet, which is the only authority this Object can consult without inventing an owner.\n * Identities beyond the ledger's 1,024-character row bound fail typed: the minting side\n * refused them at admission, so they cannot name any stored row anywhere.\n */\nconst routableSubmissionTarget = (\n localConversationId: ConversationId,\n): ((operation: string, submissionId: string) => Effect.Effect<RouteTarget, LedgerError>) =>\n Effect.fn(\"DoPortRouting.routableSubmissionTarget\")(function* (\n operation: string,\n submissionId: string,\n ): Effect.fn.Return<RouteTarget, LedgerError> {\n if (submissionId.length > MAX_ROUTABLE_SUBMISSION_ID_LENGTH) {\n return yield* LedgerError.make({\n operation,\n message:\n `A Submission identity of ${submissionId.length} characters exceeds the ` +\n `${MAX_ROUTABLE_SUBMISSION_ID_LENGTH}-character routable identity bound; admission ` +\n \"refuses such identities, so it cannot name any stored row.\",\n });\n }\n const separator = submissionId.indexOf(\":\");\n if (separator === -1) return LOCAL;\n if (!UUID_HEAD_PATTERN.test(submissionId.slice(0, separator))) return LOCAL;\n const tail = submissionId.slice(separator + 1);\n if (tail === localConversationId) return LOCAL;\n return yield* decodeConversationId(tail).pipe(\n Effect.map((conversationId): RouteTarget => ({ _tag: \"foreign\", conversationId })),\n Effect.orElseSucceed(() => LOCAL),\n );\n });\n\nconst isResultTag =\n <Tag extends PortResult[\"_tag\"]>(tag: Tag) =>\n (result: PortResult): result is Extract<PortResult, { readonly _tag: Tag }> =>\n result._tag === tag;\n\nconst isAdmitConflict = (failure: PortFailure): failure is AdmissionConflict =>\n failure._tag === \"AdmissionConflict\";\nconst isAbortConflict = (failure: PortFailure): failure is SettlementConflict | JoinedToHost =>\n failure._tag === \"SettlementConflict\" || failure._tag === \"JoinedToHost\";\nconst noExtraFailure = (_failure: PortFailure): _failure is never => false;\nconst isFenceRejected = (failure: PortFailure): failure is FenceRejected =>\n failure._tag === \"FenceRejected\";\nconst isAppendFailure = (\n failure: PortFailure,\n): failure is ConversationNotMaterialized | AppendConflict | FenceRejected =>\n failure._tag === \"ConversationNotMaterialized\" ||\n failure._tag === \"AppendConflict\" ||\n failure._tag === \"FenceRejected\";\nconst isNotMaterialized = (failure: PortFailure): failure is ConversationNotMaterialized =>\n failure._tag === \"ConversationNotMaterialized\";\n\n/**\n * The fail-fast refusal for any foreign operation OUTSIDE the closed route-capable subset\n * (plan §1.3): honesty over accidental distribution.\n */\nconst crossConversationLedgerError = (operation: string, target: string): LedgerError =>\n LedgerError.make({\n operation,\n message:\n `${operation} addressed to foreign Conversation ${target} is not route-capable; the ` +\n \"closed cross-Object subset is admit, markReady, lookup, resolveAdmission, \" +\n \"requestAbort, and recordChildSettled. Every other ledger operation is lane-local by \" +\n \"construction and must execute inside the owning Conversation's Durable Object.\",\n });\n\nconst crossConversationStoreError = (operation: string, target: string): ConversationStoreError =>\n ConversationStoreError.make({\n operation,\n message:\n `${operation} addressed to foreign Conversation ${target} is not route-capable; the ` +\n \"closed cross-Object subset is materialize, append, read (paged), inspectTail, and \" +\n \"export. Observation and checkpoints are lane-local by construction and must execute \" +\n \"inside the owning Conversation's Durable Object.\",\n });\n\nconst makeTransportCall = (transport: ConversationPortTransport[\"Service\"]) =>\n Effect.fn(\"DoPortRouting.transportCall\")(function* (target: ConversationId, call: PortRequest) {\n const encoded = yield* encodePortRequest(call).pipe(\n Effect.mapError((error) =>\n PortProtocolError.make({\n message: boundPortDiagnostic(`The port request could not be encoded: ${error.message}`),\n }),\n ),\n );\n const raw = yield* transport.call(target, encoded);\n return yield* decodePortResponse(raw).pipe(\n Effect.mapError((error) =>\n PortProtocolError.make({\n message: boundPortDiagnostic(`The port response could not be decoded: ${error.message}`),\n }),\n ),\n );\n });\n\ntype TransportCall = ReturnType<typeof makeTransportCall>;\n\nconst makeRoutedLedgerServices = Effect.fn(\"DoPortRouting.makeRoutedLedgerServices\")(function* (\n options: RoutedPortOptions,\n) {\n const local = yield* SubmissionLedger;\n const transport = yield* ConversationPortTransport;\n const transportCall: TransportCall = makeTransportCall(transport);\n const submissionTarget = routableSubmissionTarget(options.localConversationId);\n\n const routeFailure =\n (operation: string, target: string) =>\n (error: PortTransportError | PortProtocolError): LedgerError =>\n LedgerError.make({\n operation,\n message: boundPortDiagnostic(\n `Routed ${operation} to the Conversation Object owning ${target} failed: ${error.message}`,\n ),\n cause: error,\n });\n\n /**\n * One routed ledger call: encode, deliver, decode, then narrow the uniform envelope to the\n * operation's own result and failure surface. A foreign `LedgerError` is always in-channel;\n * any failure outside the operation's declared surface — including protocol anomalies — is\n * folded into a `LedgerError` naming the anomaly instead of being erased or re-thrown raw.\n */\n const foreignLedgerCall = <Tag extends PortResult[\"_tag\"], ExpectedFailure extends PortFailure>(\n operation: string,\n target: ConversationId,\n call: PortRequest,\n resultTag: Tag,\n isExpectedFailure: (failure: PortFailure) => failure is ExpectedFailure,\n ): Effect.Effect<Extract<PortResult, { readonly _tag: Tag }>, ExpectedFailure | LedgerError> =>\n transportCall(target, call).pipe(\n Effect.mapError(routeFailure(operation, target)),\n Effect.flatMap(\n (\n response,\n ): Effect.Effect<\n Extract<PortResult, { readonly _tag: Tag }>,\n ExpectedFailure | LedgerError\n > => {\n if (response._tag === \"PortFailed\") {\n const failure = response.failure;\n if (isExpectedFailure(failure)) return Effect.fail(failure);\n if (failure._tag === \"LedgerError\") return Effect.fail(failure);\n return Effect.fail(\n LedgerError.make({\n operation,\n message: boundPortDiagnostic(\n `The Conversation Object owning ${target} answered ${operation} with the ` +\n `out-of-contract failure ${failure._tag}: ${failure.message}`,\n ),\n cause: failure,\n }),\n );\n }\n const result = response.result;\n if (!isResultTag(resultTag)(result)) {\n return Effect.fail(\n LedgerError.make({\n operation,\n message:\n `The Conversation Object owning ${target} answered ${operation} with the ` +\n `mismatched result ${result._tag}; expected ${resultTag}.`,\n }),\n );\n }\n return Effect.succeed(result);\n },\n ),\n Effect.withSpan(\"DoPortRouting.foreignLedgerCall\", {\n attributes: { operation, target },\n }),\n );\n\n /**\n * Routed `resolveAdmission` — where the S2 tri-state becomes real (plan §1.3): when the\n * owning Object cannot be reached, or its answer cannot be understood, the routed adapter\n * answers `AdmissionIndeterminate{reason}` and NEVER `NotAdmitted` — an unreachable\n * authority proves nothing, and only `NotAdmitted` permits an admission attempt (SUB-031).\n * A typed `LedgerError` answered BY the authority still fails typed: the authority was\n * reached and reported its own storage failure.\n */\n const resolveForeignAdmission = (\n target: ConversationId,\n request: SubmissionLookupByKey,\n ): Effect.Effect<\n | AdmissionIndeterminate\n | Extract<PortResult, { readonly _tag: \"LedgerResolveAdmissionResult\" }>[\"resolution\"],\n LedgerError\n > =>\n transportCall(target, LedgerResolveAdmissionCall.make({ request })).pipe(\n Effect.flatMap((response) => {\n if (response._tag === \"PortFailed\") {\n if (response.failure._tag === \"LedgerError\") return Effect.fail(response.failure);\n return Effect.succeed(\n AdmissionIndeterminate.make({\n reason: boundPortDiagnostic(\n `The Conversation Object owning ${target} answered resolveAdmission with the ` +\n `out-of-contract failure ${response.failure._tag}: ${response.failure.message}`,\n ),\n }),\n );\n }\n if (response.result._tag !== \"LedgerResolveAdmissionResult\") {\n return Effect.succeed(\n AdmissionIndeterminate.make({\n reason: boundPortDiagnostic(\n `The Conversation Object owning ${target} answered resolveAdmission with the ` +\n `mismatched result ${response.result._tag}.`,\n ),\n }),\n );\n }\n return Effect.succeed(response.result.resolution);\n }),\n Effect.catchTags({\n PortTransportError: (error) =>\n Effect.succeed(\n AdmissionIndeterminate.make({\n reason: boundPortDiagnostic(\n `The Conversation Object owning ${target} is unreachable: ${error.message}`,\n ),\n }),\n ),\n PortProtocolError: (error) =>\n Effect.succeed(\n AdmissionIndeterminate.make({\n reason: boundPortDiagnostic(\n `The answer of the Conversation Object owning ${target} could not be ` +\n `understood: ${error.message}`,\n ),\n }),\n ),\n }),\n Effect.withSpan(\"DoPortRouting.resolveForeignAdmission\", { attributes: { target } }),\n );\n\n const foreignLookupById = (\n operation: string,\n target: ConversationId,\n submissionId: SubmissionId,\n ): Effect.Effect<Option.Option<SubmissionSnapshot>, LedgerError> =>\n foreignLedgerCall(\n operation,\n target,\n LedgerLookupCall.make({ request: SubmissionLookupById.make({ submissionId }) }),\n \"LedgerLookupResult\",\n noExtraFailure,\n ).pipe(\n Effect.map((result) =>\n result.submission === undefined ? Option.none() : Option.some(result.submission),\n ),\n );\n\n /**\n * Enrich a LOCAL parent's recovery snapshot with the lane state of attached children whose\n * rows live in other Durable Objects (plan §1.3): markers first (the local facet already\n * consulted them), then a routed per-child `lookup` for any attached child that is neither\n * local nor marker-settled. A transport failure surfaces as `LedgerError` so the alarm\n * pass retries; the child's canonical Settlement remains the only authority (DUR-015).\n */\n const enrichChildAttachments = Effect.fn(\"DoPortRouting.enrichChildAttachments\")(function* (\n snapshot: RecoverySnapshot,\n ): Effect.fn.Return<RecoverySnapshot, LedgerError> {\n const operation = \"ledger load recovery snapshot\";\n const attachments = new Map(\n snapshot.childAttachments.map((attachment) => [attachment.childSubmissionId, attachment]),\n );\n let enriched = false;\n for (const reservation of snapshot.childReservations) {\n const childSubmissionId = reservation.childSubmissionId;\n if (childSubmissionId === undefined || attachments.has(childSubmissionId)) continue;\n const target = yield* submissionTarget(operation, childSubmissionId);\n // A local or opaque child identity was already answered authoritatively by the local\n // facet; absence there means the child admission never committed.\n if (target._tag !== \"foreign\") continue;\n const child = yield* foreignLookupById(operation, target.conversationId, childSubmissionId);\n if (Option.isNone(child)) continue;\n attachments.set(\n childSubmissionId,\n ChildAttachmentSnapshot.make({\n toolCallId: reservation.parentToolCallId,\n childSubmissionId,\n childState: child.value.state,\n ...(child.value.settledOutcome === undefined\n ? {}\n : { childOutcome: child.value.settledOutcome }),\n }),\n );\n enriched = true;\n }\n if (!enriched) return snapshot;\n // Rebuild in reservation (parent Tool Call) order, the order the local facet documents.\n const ordered: Array<ChildAttachmentSnapshot> = [];\n for (const reservation of snapshot.childReservations) {\n if (reservation.childSubmissionId === undefined) continue;\n const attachment = attachments.get(reservation.childSubmissionId);\n if (attachment !== undefined) ordered.push(attachment);\n }\n return RecoverySnapshot.make({ ...snapshot, childAttachments: ordered });\n });\n\n const routed = SubmissionLedger.of({\n capabilities: local.capabilities,\n\n admit: (request) =>\n request.conversationId === options.localConversationId\n ? local.admit(request)\n : foreignLedgerCall(\n \"ledger admit\",\n request.conversationId,\n LedgerAdmitCall.make({ request }),\n \"LedgerAdmitResult\",\n isAdmitConflict,\n ).pipe(Effect.map((reply) => reply.result)),\n\n markReady: (request) =>\n submissionTarget(\"ledger mark ready\", request.submissionId).pipe(\n Effect.flatMap((target) =>\n target._tag === \"local\"\n ? local.markReady(request)\n : foreignLedgerCall(\n \"ledger mark ready\",\n target.conversationId,\n LedgerMarkReadyCall.make({ request }),\n \"LedgerMarkReadyResult\",\n noExtraFailure,\n ).pipe(Effect.asVoid),\n ),\n ),\n\n lookup: (request) =>\n request._tag === \"SubmissionLookupById\"\n ? submissionTarget(\"ledger lookup\", request.submissionId).pipe(\n Effect.flatMap((target) =>\n target._tag === \"local\"\n ? local.lookup(request)\n : foreignLookupById(\"ledger lookup\", target.conversationId, request.submissionId),\n ),\n )\n : request.conversationId === options.localConversationId\n ? local.lookup(request)\n : foreignLedgerCall(\n \"ledger lookup\",\n request.conversationId,\n LedgerLookupCall.make({ request }),\n \"LedgerLookupResult\",\n noExtraFailure,\n ).pipe(\n Effect.map((result) =>\n result.submission === undefined ? Option.none() : Option.some(result.submission),\n ),\n ),\n\n resolveAdmission: (request) =>\n request.conversationId === options.localConversationId\n ? local.resolveAdmission(request)\n : resolveForeignAdmission(request.conversationId, request),\n\n requestAbort: (request) =>\n submissionTarget(\"ledger request abort\", request.submissionId).pipe(\n Effect.flatMap((target) =>\n target._tag === \"local\"\n ? local.requestAbort(request)\n : foreignLedgerCall(\n \"ledger request abort\",\n target.conversationId,\n LedgerRequestAbortCall.make({ request }),\n \"LedgerRequestAbortResult\",\n isAbortConflict,\n ).pipe(Effect.map((reply) => reply.intent)),\n ),\n ),\n\n recordChildSettled: (request) =>\n submissionTarget(\"ledger record child settled\", request.parentSubmissionId).pipe(\n Effect.flatMap((target) =>\n target._tag === \"local\"\n ? local.recordChildSettled(request)\n : foreignLedgerCall(\n \"ledger record child settled\",\n target.conversationId,\n LedgerRecordChildSettledCall.make({ request }),\n \"LedgerRecordChildSettledResult\",\n noExtraFailure,\n ).pipe(Effect.map((reply) => reply.outcome)),\n ),\n ),\n\n // Every operation below is lane-local by construction (plan §1.3): a foreign address is\n // an out-of-contract call and fails fast typed instead of being quietly distributed.\n claim: (request) =>\n request.conversationId === options.localConversationId\n ? local.claim(request)\n : Effect.fail(crossConversationLedgerError(\"ledger claim\", request.conversationId)),\n\n claimJoining: (request) =>\n request.conversationId === options.localConversationId\n ? local.claimJoining(request)\n : Effect.fail(crossConversationLedgerError(\"ledger claim joining\", request.conversationId)),\n\n renewOwnership: (request) =>\n submissionTarget(\"ledger renew ownership\", request.submissionId).pipe(\n Effect.flatMap((target) =>\n target._tag === \"local\"\n ? local.renewOwnership(request)\n : Effect.fail(\n crossConversationLedgerError(\"ledger renew ownership\", target.conversationId),\n ),\n ),\n ),\n\n releaseOwnership: (request) =>\n submissionTarget(\"ledger release ownership\", request.submissionId).pipe(\n Effect.flatMap((target) =>\n target._tag === \"local\"\n ? local.releaseOwnership(request)\n : Effect.fail(\n crossConversationLedgerError(\"ledger release ownership\", target.conversationId),\n ),\n ),\n ),\n\n markInputApplied: (request) =>\n submissionTarget(\"ledger mark input applied\", request.submissionId).pipe(\n Effect.flatMap((target) =>\n target._tag === \"local\"\n ? local.markInputApplied(request)\n : Effect.fail(\n crossConversationLedgerError(\"ledger mark input applied\", target.conversationId),\n ),\n ),\n ),\n\n reserveSettlement: (request) =>\n submissionTarget(\"ledger reserve settlement\", request.submissionId).pipe(\n Effect.flatMap((target) =>\n target._tag === \"local\"\n ? local.reserveSettlement(request)\n : Effect.fail(\n crossConversationLedgerError(\"ledger reserve settlement\", target.conversationId),\n ),\n ),\n ),\n\n finalizeSettlement: (request) =>\n submissionTarget(\"ledger finalize settlement\", request.submissionId).pipe(\n Effect.flatMap((target) =>\n target._tag === \"local\"\n ? local.finalizeSettlement(request)\n : Effect.fail(\n crossConversationLedgerError(\"ledger finalize settlement\", target.conversationId),\n ),\n ),\n ),\n\n markJoined: (request) =>\n submissionTarget(\"ledger mark joined\", request.submissionId).pipe(\n Effect.flatMap((target) =>\n target._tag === \"local\"\n ? local.markJoined(request)\n : Effect.fail(\n crossConversationLedgerError(\"ledger mark joined\", target.conversationId),\n ),\n ),\n ),\n\n revertJoining: (request) =>\n submissionTarget(\"ledger revert joining\", request.submissionId).pipe(\n Effect.flatMap((target) =>\n target._tag === \"local\"\n ? local.revertJoining(request)\n : Effect.fail(\n crossConversationLedgerError(\"ledger revert joining\", target.conversationId),\n ),\n ),\n ),\n\n suspend: (request) =>\n submissionTarget(\"ledger suspend\", request.submissionId).pipe(\n Effect.flatMap((target) =>\n target._tag === \"local\"\n ? local.suspend(request)\n : Effect.fail(crossConversationLedgerError(\"ledger suspend\", target.conversationId)),\n ),\n ),\n\n recordApprovalDecision: (command) =>\n submissionTarget(\"ledger record approval decision\", command.submissionId).pipe(\n Effect.flatMap((target) =>\n target._tag === \"local\"\n ? local.recordApprovalDecision(command)\n : Effect.fail(\n crossConversationLedgerError(\n \"ledger record approval decision\",\n target.conversationId,\n ),\n ),\n ),\n ),\n\n markUnknown: (request) =>\n submissionTarget(\"ledger mark unknown\", request.submissionId).pipe(\n Effect.flatMap((target) =>\n target._tag === \"local\"\n ? local.markUnknown(request)\n : Effect.fail(\n crossConversationLedgerError(\"ledger mark unknown\", target.conversationId),\n ),\n ),\n ),\n\n recordUnknownResolution: (command) =>\n submissionTarget(\"ledger record unknown resolution\", command.submissionId).pipe(\n Effect.flatMap((target) =>\n target._tag === \"local\"\n ? local.recordUnknownResolution(command)\n : Effect.fail(\n crossConversationLedgerError(\n \"ledger record unknown resolution\",\n target.conversationId,\n ),\n ),\n ),\n ),\n\n reserveChildBudget: (request) =>\n submissionTarget(\"ledger reserve child budget\", request.parentSubmissionId).pipe(\n Effect.flatMap((target) =>\n target._tag === \"local\"\n ? local.reserveChildBudget(request)\n : Effect.fail(\n crossConversationLedgerError(\"ledger reserve child budget\", target.conversationId),\n ),\n ),\n ),\n\n // Reservation identities carry no Conversation address; the reservation row lives in the\n // parent's own Object and these transitions are parent-lane-local by construction, so\n // they always execute on the local facet (which fails typed for an unknown row).\n attachChildToReservation: local.attachChildToReservation,\n beginChildBudgetRelease: local.beginChildBudgetRelease,\n releaseChildBudget: local.releaseChildBudget,\n\n // The local scan IS the whole worklist: one Conversation per Object (durability §5).\n scanNonterminal: local.scanNonterminal,\n\n loadRecoverySnapshot: (request) =>\n submissionTarget(\"ledger load recovery snapshot\", request.submissionId).pipe(\n Effect.flatMap((target) =>\n target._tag === \"local\"\n ? local.loadRecoverySnapshot(request).pipe(Effect.flatMap(enrichChildAttachments))\n : Effect.fail(\n crossConversationLedgerError(\n \"ledger load recovery snapshot\",\n target.conversationId,\n ),\n ),\n ),\n ),\n });\n\n return Context.make(SubmissionLedger, routed);\n});\n\nconst makeRoutedStoreServices = Effect.fn(\"DoPortRouting.makeRoutedStoreServices\")(function* (\n options: RoutedPortOptions,\n) {\n const local = yield* ConversationStore;\n const transport = yield* ConversationPortTransport;\n const transportCall: TransportCall = makeTransportCall(transport);\n\n const routeFailure =\n (operation: string, target: string) =>\n (error: PortTransportError | PortProtocolError): ConversationStoreError =>\n ConversationStoreError.make({\n operation,\n message: boundPortDiagnostic(\n `Routed ${operation} to the Conversation Object owning ${target} failed: ${error.message}`,\n ),\n cause: error,\n });\n\n /** The store twin of `foreignLedgerCall` with `ConversationStoreError` as the base error. */\n const foreignStoreCall = <Tag extends PortResult[\"_tag\"], ExpectedFailure extends PortFailure>(\n operation: string,\n target: ConversationId,\n call: PortRequest,\n resultTag: Tag,\n isExpectedFailure: (failure: PortFailure) => failure is ExpectedFailure,\n ): Effect.Effect<\n Extract<PortResult, { readonly _tag: Tag }>,\n ExpectedFailure | ConversationStoreError\n > =>\n transportCall(target, call).pipe(\n Effect.mapError(routeFailure(operation, target)),\n Effect.flatMap(\n (\n response,\n ): Effect.Effect<\n Extract<PortResult, { readonly _tag: Tag }>,\n ExpectedFailure | ConversationStoreError\n > => {\n if (response._tag === \"PortFailed\") {\n const failure = response.failure;\n if (isExpectedFailure(failure)) return Effect.fail(failure);\n if (failure._tag === \"ConversationStoreError\") return Effect.fail(failure);\n return Effect.fail(\n ConversationStoreError.make({\n operation,\n message: boundPortDiagnostic(\n `The Conversation Object owning ${target} answered ${operation} with the ` +\n `out-of-contract failure ${failure._tag}: ${failure.message}`,\n ),\n cause: failure,\n }),\n );\n }\n const result = response.result;\n if (!isResultTag(resultTag)(result)) {\n return Effect.fail(\n ConversationStoreError.make({\n operation,\n message:\n `The Conversation Object owning ${target} answered ${operation} with the ` +\n `mismatched result ${result._tag}; expected ${resultTag}.`,\n }),\n );\n }\n return Effect.succeed(result);\n },\n ),\n Effect.withSpan(\"DoPortRouting.foreignStoreCall\", {\n attributes: { operation, target },\n }),\n );\n\n const routed = ConversationStore.of({\n materialize: (request) =>\n request.conversationId === options.localConversationId\n ? local.materialize(request)\n : foreignStoreCall(\n \"conversation materialize\",\n request.conversationId,\n StoreMaterializeCall.make({ request }),\n \"StoreMaterializeResult\",\n isFenceRejected,\n ).pipe(Effect.asVoid),\n\n append: (request) =>\n request.conversationId === options.localConversationId\n ? local.append(request)\n : foreignStoreCall(\n \"conversation append\",\n request.conversationId,\n StoreAppendCall.make({ request }),\n \"StoreAppendResult\",\n isAppendFailure,\n ).pipe(Effect.map((reply) => reply.result)),\n\n read: (request) =>\n request.conversationId === options.localConversationId\n ? local.read(request)\n : Stream.unwrap(\n foreignStoreCall(\n \"conversation read\",\n request.conversationId,\n StoreReadPageCall.make({ request }),\n \"StoreReadPageResult\",\n isNotMaterialized,\n ).pipe(Effect.map((reply) => Stream.fromIterable(reply.records))),\n ),\n\n inspectTail: (request) =>\n request.conversationId === options.localConversationId\n ? local.inspectTail(request)\n : foreignStoreCall(\n \"conversation inspect tail\",\n request.conversationId,\n StoreInspectTailCall.make({ request }),\n \"StoreInspectTailResult\",\n isNotMaterialized,\n ).pipe(Effect.map((reply) => reply.tail)),\n\n export: (request) =>\n request.conversationId === options.localConversationId\n ? local.export(request)\n : foreignStoreCall(\n \"conversation export\",\n request.conversationId,\n StoreExportCall.make({ request }),\n \"StoreExportResult\",\n isNotMaterialized,\n ).pipe(Effect.map((reply) => reply.export)),\n\n // Observation and checkpoints are lane-local by construction (plan §1.3): the closed\n // route-capable store subset is materialize/append/read/inspectTail/export, and a\n // foreign address on anything else fails fast typed.\n observe: (request) =>\n request.conversationId === options.localConversationId\n ? local.observe(request)\n : Stream.unwrap(\n Effect.fail(\n crossConversationStoreError(\"conversation observe\", request.conversationId),\n ),\n ),\n\n saveCheckpoint: (request) =>\n request.checkpoint.conversationId === options.localConversationId\n ? local.saveCheckpoint(request)\n : Effect.fail(\n crossConversationStoreError(\n \"conversation save checkpoint\",\n request.checkpoint.conversationId,\n ),\n ),\n\n loadCheckpoint: (request) =>\n request.conversationId === options.localConversationId\n ? local.loadCheckpoint(request)\n : Effect.fail(\n crossConversationStoreError(\"conversation load checkpoint\", request.conversationId),\n ),\n });\n\n return Context.make(ConversationStore, routed);\n});\n\n/**\n * Routing decorator over the LOCAL `SubmissionLedger` facet (plan §1.3): a request addressing\n * this Object's Conversation executes locally; a route-capable request addressing another\n * Conversation is Schema-encoded onto the `ConversationPortTransport` and executed by the\n * owning Object's local facet; any other foreign request fails fast typed. Provide the WP1\n * local facet (`submissionLedgerLayer`/`ledgerLayer`) and a transport to close it.\n */\nexport const routedSubmissionLedgerLayer = (\n options: RoutedPortOptions,\n): Layer.Layer<SubmissionLedger, never, SubmissionLedger | ConversationPortTransport> =>\n Layer.effectContext(makeRoutedLedgerServices(options));\n\n/**\n * Routing decorator over the LOCAL `ConversationStore` facet (plan §1.3): this-conversation\n * requests execute locally; foreign materialize/append/read/inspectTail/export travel the\n * transport; foreign observation and checkpoints fail fast typed.\n */\nexport const routedConversationStoreLayer = (\n options: RoutedPortOptions,\n): Layer.Layer<ConversationStore, never, ConversationStore | ConversationPortTransport> =>\n Layer.effectContext(makeRoutedStoreServices(options));\n\n// ---------------------------------------------------------------------------\n// Owner-side execution\n// ---------------------------------------------------------------------------\n\n/** Fold one port operation's typed failures into the uniform response envelope. */\nconst capture = <Failure extends PortFailure>(\n effect: Effect.Effect<PortResult, Failure>,\n): Effect.Effect<PortResponse> =>\n effect.pipe(\n Effect.map((result): PortResponse => PortSucceeded.make({ result })),\n Effect.catch((failure) => Effect.succeed<PortResponse>(PortFailed.make({ failure }))),\n );\n\n/**\n * Execute one decoded port request against THIS Object's LOCAL facets — the owner-side half\n * of the routed ports (plan §1.3). Callers must provide the WP1 local facets, never the\n * routed decorators: the routing layer already established that this Object owns the\n * addressed Conversation, and re-routing here could bounce a request between Objects.\n * Failures never escape — every typed port failure becomes a `PortFailed` envelope that\n * re-decodes on the caller side.\n */\nexport const executePortRequest = Effect.fn(\"DoPortRouting.executePortRequest\")(function* (\n request: PortRequest,\n): Effect.fn.Return<PortResponse, never, SubmissionLedger | ConversationStore> {\n switch (request._tag) {\n case \"LedgerAdmit\": {\n const ledger = yield* SubmissionLedger;\n return yield* capture(\n ledger\n .admit(request.request)\n .pipe(Effect.map((result) => LedgerAdmitResult.make({ result }))),\n );\n }\n case \"LedgerMarkReady\": {\n const ledger = yield* SubmissionLedger;\n return yield* capture(\n ledger.markReady(request.request).pipe(Effect.map(() => LedgerMarkReadyResult.make({}))),\n );\n }\n case \"LedgerLookup\": {\n const ledger = yield* SubmissionLedger;\n return yield* capture(\n ledger\n .lookup(request.request)\n .pipe(\n Effect.map((submission) =>\n Option.isSome(submission)\n ? LedgerLookupResult.make({ submission: submission.value })\n : LedgerLookupResult.make({}),\n ),\n ),\n );\n }\n case \"LedgerResolveAdmission\": {\n const ledger = yield* SubmissionLedger;\n return yield* capture(\n ledger\n .resolveAdmission(request.request)\n .pipe(Effect.map((resolution) => LedgerResolveAdmissionResult.make({ resolution }))),\n );\n }\n case \"LedgerRequestAbort\": {\n const ledger = yield* SubmissionLedger;\n return yield* capture(\n ledger\n .requestAbort(request.request)\n .pipe(Effect.map((intent) => LedgerRequestAbortResult.make({ intent }))),\n );\n }\n case \"LedgerRecordChildSettled\": {\n const ledger = yield* SubmissionLedger;\n return yield* capture(\n ledger\n .recordChildSettled(request.request)\n .pipe(Effect.map((outcome) => LedgerRecordChildSettledResult.make({ outcome }))),\n );\n }\n case \"StoreMaterialize\": {\n const store = yield* ConversationStore;\n return yield* capture(\n store.materialize(request.request).pipe(Effect.map(() => StoreMaterializeResult.make({}))),\n );\n }\n case \"StoreAppend\": {\n const store = yield* ConversationStore;\n return yield* capture(\n store\n .append(request.request)\n .pipe(Effect.map((result) => StoreAppendResult.make({ result }))),\n );\n }\n case \"StoreReadPage\": {\n const store = yield* ConversationStore;\n return yield* capture(\n store.read(request.request).pipe(\n Stream.runCollect,\n Effect.map((records) => StoreReadPageResult.make({ records: [...records] })),\n ),\n );\n }\n case \"StoreInspectTail\": {\n const store = yield* ConversationStore;\n return yield* capture(\n store\n .inspectTail(request.request)\n .pipe(Effect.map((tail) => StoreInspectTailResult.make({ tail }))),\n );\n }\n case \"StoreExport\": {\n const store = yield* ConversationStore;\n return yield* capture(\n store\n .export(request.request)\n .pipe(\n Effect.map((conversationExport) =>\n StoreExportResult.make({ export: conversationExport }),\n ),\n ),\n );\n }\n }\n});\n\n/**\n * The last-resort wire fallback when even encoding a response fails: the literal encoded\n * form of `PortFailed(PortProtocolError)` — tagged classes of bounded strings encode to\n * exactly this shape, so no Schema round trip is needed to produce it.\n */\nconst encodedProtocolFailure = (message: string): unknown => ({\n _tag: \"PortFailed\",\n failure: { _tag: \"PortProtocolError\", message: boundPortDiagnostic(message) },\n});\n\n/**\n * The complete owner-side endpoint body for `portCall` (D-P6-3): decode the wire request,\n * execute it against this Object's LOCAL facets, and answer with the encoded response\n * envelope. Total by construction — a request that cannot be decoded, or a response that\n * cannot be encoded, answers `PortFailed(PortProtocolError)` instead of throwing, so the\n * transport never has to interpret exceptions as protocol answers.\n */\nexport const handleEncodedPortRequest = Effect.fn(\"DoPortRouting.handleEncodedPortRequest\")(\n function* (\n encoded: unknown,\n ): Effect.fn.Return<unknown, never, SubmissionLedger | ConversationStore> {\n const response = yield* decodePortRequest(encoded).pipe(\n Effect.flatMap(executePortRequest),\n Effect.catch((error) =>\n Effect.succeed<PortResponse>(\n PortFailed.make({\n failure: PortProtocolError.make({\n message: boundPortDiagnostic(\n `The port request could not be decoded: ${error.message}`,\n ),\n }),\n }),\n ),\n ),\n );\n return yield* encodePortResponse(response).pipe(\n Effect.catch((error) =>\n Effect.succeed(\n encodedProtocolFailure(`The port response could not be encoded: ${error.message}`),\n ),\n ),\n );\n },\n);\n"],"mappings":";;;;;;;;AAIA,IAAa,8BAAb,cAAiD,OAAO,YAAyC,CAAC,CAChG,+BACA;CACE,eAAe,OAAO;CACtB,SAAS,OAAO;CAChB,kBAAkB,OAAO;AAC3B,CACF,CAAC,CAAC,CAAC;;AAGH,IAAa,2BAAb,cAA8C,OAAO,YAAsC,CAAC,CAC1F,4BACA;CACE,SAAS,OAAO;CAChB,QAAQ,OAAO;CACf,OAAO,OAAO;AAChB,CACF,CAAC,CAAC,CAAC;;AAGH,IAAa,iBAAb,cAAoC,OAAO,YAA4B,CAAC,CAAC,kBAAkB;CACzF,OAAO,OAAO,YAAY,OAAO,OAAO,CAAC;CACzC,SAAS,OAAO;CAChB,WAAW,OAAO;AACpB,CAAC,CAAC,CAAC,CAAC;;;;;;AAOJ,IAAa,gBAAb,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