@effect-agent/storage-cloudflare 0.1.0-beta.37 → 0.1.0-beta.39
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/do-storage-failpoint-9XB9tuif.d.mts +107 -0
- package/dist/do-storage-failpoint-C-Qtchs7.mjs +12 -0
- package/dist/do-storage-failpoint-C-Qtchs7.mjs.map +1 -0
- package/dist/index.d.mts +160 -242
- package/dist/index.mjs +1199 -522
- package/dist/index.mjs.map +1 -1
- package/dist/testing.d.mts +33 -0
- package/dist/testing.mjs +35 -0
- package/dist/testing.mjs.map +1 -0
- package/package.json +12 -5
- package/src/do-journal.ts +148 -157
- package/src/do-ledger.ts +66 -66
- package/src/do-schedule-store.ts +7 -3
- package/src/do-storage-failpoint-testing.ts +73 -0
- package/src/do-storage-failpoint.ts +1 -68
- package/src/do-subscription-store.ts +1122 -0
- package/src/{do-conversation-store.ts → do-thread-store.ts} +313 -334
- package/src/errors.ts +3 -3
- package/src/index.ts +9 -8
- package/src/migrations.ts +26 -26
- package/src/port-protocol.ts +29 -29
- package/src/routing.ts +146 -188
- package/src/testing.ts +2 -0
package/dist/index.mjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.mjs","names":["BoundedStoredText","BoundedIdentifier","MAX_IDENTIFIER_LENGTH","noFailpoint","decodeRows","makeServices","SqlClientService","makeServices","SqlClientService","decodeRows","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/do-schedule-store.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 type DoStorageFailpointError,\n DoAppendConflict,\n DoCheckpointConflict,\n DoFenceRejected,\n DoStorageCompatibilityError,\n DoStorageCorruptionError,\n DoStorageError,\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;\nconst isSqlError = Schema.is(SqlError);\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(\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(\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) => (isSqlError(error) ? storageError(operation)(error) : error)),\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 type { DoStorageFailpointError, 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 type DoStorageCompatibilityError,\n DoAppendConflict,\n DoCheckpointConflict,\n DoFenceRejected,\n type DoStorageFailpointLocation,\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);\nconst isDoFenceRejected = Schema.is(DoFenceRejected);\nconst isDoAppendConflict = Schema.is(DoAppendConflict);\nconst isDoCheckpointConflict = Schema.is(DoCheckpointConflict);\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(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(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(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(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(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(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(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(\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 (isDoFenceRejected(error)) {\n return mapFence(validated.conversationId, error);\n }\n if (isDoAppendConflict(error)) {\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 isDoCheckpointConflict(error)\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 Layer.unwrap(\n Effect.map(DoStorageConfig, (config) =>\n conversationStoreLayer.pipe(\n Layer.provide(\n Layer.mergeAll(\n Layer.succeed(DoStorageConfig)(config),\n storageFailpointLayer(options),\n SqliteClient.layer({ storage: options.storage }),\n BrowserCrypto.layer,\n ),\n ),\n ),\n ),\n ).pipe(Layer.provide(storageConfigLayer(options)));\n\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 settlementFailureFromRecord,\n SuspendRequest,\n SuspensionReason,\n SuspensionSnapshot,\n UnknownResolution,\n UnknownResolutionCommand,\n UnknownResolutionConflict,\n UnknownResolutionIntent,\n submissionAbortRecordId,\n type ChildSettledOutcome,\n type SuspensionOutcome,\n} from \"@effect-agent/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 RESUME_IMMEDIATELY: SuspensionOutcome = \"resume-immediately\";\nconst SUSPENDED: SuspensionOutcome = \"suspended\";\nconst NOT_WAITING: ChildSettledOutcome = \"not-waiting\";\nconst STILL_WAITING: ChildSettledOutcome = \"still-waiting\";\nconst WOKEN: ChildSettledOutcome = \"woken\";\nconst MAX_IDENTIFIER_LENGTH = 1_024;\n\nclass SubmissionRow extends Schema.Class<SubmissionRow>(\"SubmissionRow\")({\n submission_id: BoundedIdentifier,\n 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);\nconst equivalentPersistedJson = Schema.toEquivalence(PersistedJson);\nconst equivalentUnknownResolution = Schema.toEquivalence(UnknownResolution);\nconst isDoStorageError = Schema.is(DoStorageError);\n\n/** Wrap an adapter-internal failure into the port's LedgerError without erasing its tag. */\nconst internalFailure =\n (operation: string) =>\n (error: { readonly message: string }): LedgerError =>\n LedgerError.make({ operation, message: error.message, cause: error });\n\n/**\n * Classify raw SQL failures. Within one Durable Object there is exactly one writer, so the\n * Node adapter's retryable `SqliteWriteContention` classification has no analogue: every raw\n * failure is a `DoLedgerError` preserved as the LedgerError's cause.\n */\nconst sqlFailure =\n (operation: string) =>\n (error: SqlError): LedgerError =>\n internalFailure(operation)(\n DoLedgerError.make({\n cause: error,\n operation,\n message: error.message,\n }),\n );\n\nconst corruptionFailure = (operation: string, table: string, rowKey: string, message: string) =>\n internalFailure(operation)(DoStorageCorruptionError.make({ table, rowKey, message }));\n\nconst makeServices = Effect.fn(\"DoSubmissionLedger.makeServices\")(function* () {\n const config = yield* DoStorageConfig;\n const failpoint = yield* DoStorageFailpoint;\n const sql = yield* SqlClientService.SqlClient;\n const crypto = yield* Crypto.Crypto;\n const 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 isDoStorageError(error) ? internalFailure(operation)(error) : error,\n ),\n );\n\n const mintUuid = (operation: string): Effect.Effect<string, LedgerError> =>\n crypto.randomUUIDv7.pipe(Effect.mapError((error) => internalFailure(operation)(error)));\n\n const currentInstant = Effect.map(Clock.currentTimeMillis, (millis) => ({\n millis,\n iso: new Date(millis).toISOString(),\n }));\n\n const timestampMillis = (operation: string, rowKey: string) => (timestamp: string) =>\n decodeUtcInstant(timestamp).pipe(\n Effect.map(DateTime.toEpochMillis),\n Effect.mapError((error) =>\n corruptionFailure(operation, \"effect_agent_submission_ownership\", rowKey, error.message),\n ),\n );\n\n const decodeSubmissionRows = (operation: string, rowKey: string, rows: unknown) =>\n decodeRows(Schema.Array(SubmissionRow), \"effect_agent_submissions\", rowKey, rows).pipe(\n Effect.mapError(internalFailure(operation)),\n );\n\n const readSubmission = Effect.fn(\"DoSubmissionLedger.readSubmission\")(function* (\n operation: string,\n submissionId: string,\n ): Effect.fn.Return<Option.Option<SubmissionRow>, LedgerError> {\n const rows = yield* sql<Record<string, unknown>>`\n SELECT ${sql.literal(SUBMISSION_COLUMNS)}\n FROM effect_agent_submissions\n WHERE submission_id = ${submissionId}\n `.pipe(Effect.mapError(sqlFailure(operation)));\n 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 // Unknown work is claimable only for a durably requested abort: the coordinator\n // cleans up children and settles without replaying ordinary Tools. Read the intent\n // in this claim transaction; retain uncertainty evidence and all ownership fencing.\n if (\n head.state === \"joining\" ||\n head.state === \"joined\" ||\n head.state === \"suspended\" ||\n (head.state === \"unknown\" &&\n Option.isNone(yield* readAbortIntent(operation, head.submission_id)))\n ) {\n return Option.none<Claim>();\n }\n\n const now = yield* currentInstant;\n const ownership = yield* readOwnership(operation, head.submission_id);\n 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 reservationRecord = yield* decodeRecordEnvelopeText(\n reservation.value.record_json,\n ).pipe(\n Effect.mapError((error) =>\n corruptionFailure(\n operation,\n \"effect_agent_settlement_reservations\",\n validated.submissionId,\n error.message,\n ),\n ),\n );\n const settlementFailure = settlementFailureFromRecord(reservationRecord);\n if ((reservation.value.outcome === \"failed\") !== (settlementFailure !== undefined)) {\n return yield* corruptionFailure(\n operation,\n \"effect_agent_settlement_reservations\",\n validated.submissionId,\n \"The reserved outcome and canonical failure diagnostic disagree.\",\n );\n }\n const submission = yield* requireSubmission(operation, validated.submissionId);\n 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 ...(settlementFailure === undefined ? {} : { failure: settlementFailure }),\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 ...(settlementFailure === undefined ? {} : { failure: settlementFailure }),\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;\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;\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;\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;\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 const existingIntent =\n existing === undefined\n ? undefined\n : yield* unknownResolutionIntentFromRow(operation, existing);\n if (\n existingIntent !== undefined &&\n !equivalentUnknownResolution(existingIntent.resolution, validated.resolution)\n ) {\n return yield* UnknownResolutionConflict.make({\n submissionId: validated.submissionId,\n toolCallId: validated.toolCallId,\n });\n }\n let resolved: UnknownResolutionIntent;\n if (existingIntent !== undefined) {\n // Idempotent replay of the recorded intent (author/reason may differ; the stored\n // audit fields win, exactly like requestAbort).\n resolved = existingIntent;\n } else {\n const now = yield* currentInstant;\n 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), either a\n // finalized row or an exact terminalizing reservation admits the notification: the\n // runtime calls only after the canonical append and before ledger finalization. When the\n // row does not live here — the normal cross-DO case — the routed notification from the\n // child's owning Durable Object is the settlement evidence this store records durably.\n const child = yield* readSubmission(operation, validated.childSubmissionId);\n const childReservation = yield* readReservation(operation, validated.childSubmissionId);\n if (\n Option.isSome(child) &&\n child.value.state !== \"settled\" &&\n !(child.value.state === \"terminalizing\" && Option.isSome(childReservation))\n ) {\n return yield* LedgerError.make({\n operation,\n message: `Child submission ${validated.childSubmissionId} has no recorded settlement.`,\n });\n }\n // Record the durable notification marker FIRST and unconditionally (idempotent):\n // the port's cross-store race guarantee requires that a notification committed\n // before the parent's suspend transaction is observed by that suspend's covering\n // check, even when the parent is not (or not yet) suspended.\n const now = yield* currentInstant;\n yield* sql`\n INSERT INTO effect_agent_child_settlements (\n parent_submission_id,\n child_submission_id,\n child_outcome,\n recorded_at\n ) VALUES (\n ${validated.parentSubmissionId},\n ${validated.childSubmissionId},\n ${\n Option.isSome(child) && child.value.state === \"settled\"\n ? child.value.settled_outcome\n : Option.isSome(childReservation)\n ? childReservation.value.outcome\n : null\n },\n ${now.iso}\n )\n ON CONFLICT (parent_submission_id, child_submission_id) DO NOTHING\n `.pipe(Effect.mapError(sqlFailure(operation)));\n\n if (parent.state !== \"suspended\" || parent.suspended_reason_json === null) {\n return NOT_WAITING;\n }\n 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;\n }\n if (\n !reason.children.some((entry) => entry.childSubmissionId === validated.childSubmissionId)\n ) {\n return NOT_WAITING;\n }\n // The parent wakes exactly when EVERY listed child is provably settled — from its\n // local row or a recorded marker (spec §12 step 10); replays re-run the coverage\n // check so a recovering caller wakes the lane idempotently.\n const markers = yield* readChildSettlementMarkers(operation, validated.parentSubmissionId);\n const markerChildren = new Set(markers.map((row) => row.child_submission_id));\n 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;\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;\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 const existingSnapshot = yield* childReservationSnapshotFromRow(\n operation,\n existing.value,\n );\n // Identical replays short-circuit before the fence, mirroring reserveSettlement: a\n // replay creates nothing, so a recovering caller resumes rather than duplicates.\n const identical =\n existing.value.parent_submission_id === validated.parentSubmissionId &&\n existing.value.parent_tool_call_id === validated.parentToolCallId &&\n existing.value.allocation_digest === validated.allocationDigest &&\n equivalentPersistedJson(existingSnapshot.allocation, validated.allocation);\n 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: existingSnapshot,\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 const existingSnapshot = yield* childReservationSnapshotFromRow(\n operation,\n existing.value,\n );\n // The accounting decision was already frozen exactly once; an identical replay is a\n // no-op and a divergent decision conflicts (spec §12 join step 6).\n if (\n existingSnapshot.accounting !== undefined &&\n equivalentPersistedJson(existingSnapshot.accounting, validated.accounting)\n ) {\n return existingSnapshot;\n }\n 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 ScanCursor | undefined,\n SubmissionSnapshot,\n LedgerError\n >(undefined, scanPage);\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 Layer.unwrap(\n Effect.map(DoStorageConfig, (config) =>\n submissionLedgerLayer.pipe(\n Layer.provide(\n Layer.mergeAll(\n Layer.succeed(DoStorageConfig)(config),\n storageFailpointLayer(options),\n SqliteClient.layer({ storage: options.storage }),\n BrowserCrypto.layer,\n ),\n ),\n ),\n ),\n ).pipe(Layer.provide(storageConfigLayer(options)));\n","import {\n applyScheduleChange,\n ScheduleCapacityError,\n ScheduleDueCursor,\n defaultSchedulingLimits,\n scheduleUsesCapacity,\n ScheduleChange,\n ScheduleConflict,\n scheduleDeadline,\n ScheduleFailpoint,\n type ScheduleFailpointError,\n ScheduleKey,\n ScheduleId,\n ScheduleInstant,\n ScheduleNotFound,\n ScheduleOwner,\n type SchedulePage,\n SchedulePageRequest,\n ScheduleRecord,\n ScheduleStorageError,\n ScheduleStore,\n} from \"@effect-agent/session\";\nimport { Context, Effect, Layer, Result, Schema } from \"effect\";\nimport * as SqlClientService from \"effect/unstable/sql/SqlClient\";\n\nconst CURRENT_SCHEDULE_STORE_VERSION = 1;\nconst MAX_STORED_SCHEDULE_BYTES = 1_900_000;\n\nconst StoredScheduleJson = Schema.String.check(Schema.isMaxLength(MAX_STORED_SCHEDULE_BYTES));\nconst StoredDeadline = Schema.NullOr(ScheduleInstant);\n\nclass ScheduleRow extends Schema.Class<ScheduleRow>(\"@effect-agent/storage-cloudflare/ScheduleRow\")(\n {\n tenant_id: ScheduleOwner.fields.tenantId,\n owner_id: ScheduleOwner.fields.ownerId,\n schedule_id: ScheduleId,\n deadline_at_millis: StoredDeadline,\n record_json: StoredScheduleJson,\n },\n) {}\n\nconst ScheduleDueRow = Schema.Struct({\n tenant_id: ScheduleOwner.fields.tenantId,\n owner_id: ScheduleOwner.fields.ownerId,\n schedule_id: ScheduleId,\n deadline_at_millis: ScheduleInstant,\n});\n\nclass ScheduleCountRow extends Schema.Class<ScheduleCountRow>(\n \"@effect-agent/storage-cloudflare/ScheduleCountRow\",\n)({\n schedule_count: Schema.Int.check(Schema.isGreaterThanOrEqualTo(0)),\n}) {}\n\nclass ScheduleDeadlineRow extends Schema.Class<ScheduleDeadlineRow>(\n \"@effect-agent/storage-cloudflare/ScheduleDeadlineRow\",\n)({\n deadline_at_millis: StoredDeadline,\n}) {}\n\nclass ScheduleStoreStateRow extends Schema.Class<ScheduleStoreStateRow>(\n \"@effect-agent/storage-cloudflare/ScheduleStoreStateRow\",\n)({\n storage_version: Schema.Int.check(Schema.isGreaterThan(0)),\n alarm_generation: Schema.Int.check(Schema.isGreaterThanOrEqualTo(0)),\n}) {}\n\nclass ScheduleTableNameRow extends Schema.Class<ScheduleTableNameRow>(\n \"@effect-agent/storage-cloudflare/ScheduleTableNameRow\",\n)({\n name: Schema.String,\n}) {}\n\nexport interface DoScheduleAlarmReplacement {\n readonly deadlineAtMillis: number | null;\n /** Included in every logical alarm payload so equal-time replacement stays distinguishable. */\n readonly generation: number;\n}\n\nexport type DoScheduleReplaceAlarm = (\n replacement: DoScheduleAlarmReplacement,\n) => Effect.Effect<void, ScheduleStorageError>;\n\n/**\n * Platform-owned transaction boundary for schedule SQL and logical alarm mutation. The callback\n * and its `replaceAlarm` capability belong to one fiber and must not escape or fork.\n */\nexport class DoScheduleTransaction extends Context.Service<\n DoScheduleTransaction,\n {\n readonly run: <A, E, R>(\n body: (replaceAlarm: DoScheduleReplaceAlarm) => Effect.Effect<A, E, R>,\n ) => Effect.Effect<A, E | ScheduleStorageError, R>;\n }\n>()(\"@effect-agent/storage-cloudflare/DoScheduleTransaction\") {}\n\n/** Platform driver operations that use the same schedule-state and alarm transaction. */\nexport class DoScheduleAlarmControl extends Context.Service<\n DoScheduleAlarmControl,\n {\n /** Establish a future recovery wake before cross-Object admission starts. */\n readonly prearm: (\n deadlineAtMillis: number,\n ) => Effect.Effect<void, ScheduleStorageError | ScheduleFailpointError>;\n /** Replace or cancel the wake from the object's authoritative indexed deadline. */\n readonly reconcile: Effect.Effect<void, ScheduleStorageError | ScheduleFailpointError>;\n }\n>()(\"@effect-agent/storage-cloudflare/DoScheduleAlarmControl\") {}\n\nconst unavailable = (operation: string): ScheduleStorageError =>\n ScheduleStorageError.make({ operation, reason: \"unavailable\" });\n\nconst corrupt = (operation: string): ScheduleStorageError =>\n ScheduleStorageError.make({ operation, reason: \"corrupt\" });\n\nconst decodeRows = Effect.fn(\"DoScheduleStore.decodeRows\")(function* <A, I, R>(\n schema: Schema.Codec<A, I, R>,\n rows: ReadonlyArray<unknown>,\n operation: string,\n): Effect.fn.Return<A, ScheduleStorageError, R> {\n return yield* Schema.decodeUnknownEffect(schema)(rows).pipe(\n Effect.mapError(() => corrupt(operation)),\n );\n});\n\nconst decodeBoundary = <A, I, R>(\n schema: Schema.Codec<A, I, R>,\n value: unknown,\n operation: string,\n): Effect.Effect<A, ScheduleStorageError, R> =>\n Schema.decodeUnknownEffect(schema)(value).pipe(Effect.mapError(() => corrupt(operation)));\n\nconst decodeRecord = Effect.fn(\"DoScheduleStore.decodeRecord\")(function* (\n row: ScheduleRow,\n): Effect.fn.Return<ScheduleRecord, ScheduleStorageError> {\n const record = yield* Schema.decodeEffect(Schema.fromJsonString(ScheduleRecord))(\n row.record_json,\n ).pipe(Effect.mapError(() => corrupt(\"decode schedule\")));\n if (\n record.owner.tenantId !== row.tenant_id ||\n record.owner.ownerId !== row.owner_id ||\n record.scheduleId !== row.schedule_id ||\n scheduleDeadline(record) !== row.deadline_at_millis\n ) {\n return yield* corrupt(\"decode schedule index\");\n }\n return record;\n});\n\nconst encodeRecord = Effect.fn(\"DoScheduleStore.encodeRecord\")(function* (\n record: ScheduleRecord,\n): Effect.fn.Return<string, ScheduleStorageError> {\n const encoded = yield* Schema.encodeEffect(Schema.fromJsonString(ScheduleRecord))(record).pipe(\n Effect.mapError(() => corrupt(\"encode schedule\")),\n );\n return yield* Schema.decodeUnknownEffect(StoredScheduleJson)(encoded).pipe(\n Effect.mapError(() => corrupt(\"encode schedule bounds\")),\n );\n});\n\nconst initializeScheduleStore = Effect.fn(\"DoScheduleStore.initialize\")(function* () {\n const sql = yield* SqlClientService.SqlClient;\n const operation = \"initialize schedule store\";\n const rawTables = yield* sql<Record<string, unknown>>`\n SELECT name\n FROM sqlite_master\n WHERE type = 'table'\n AND name IN (\n 'effect_agent_schedule_store_state',\n 'effect_agent_schedules'\n )\n ORDER BY name\n `.pipe(Effect.mapError(() => unavailable(operation)));\n const tables = yield* decodeRows(Schema.Array(ScheduleTableNameRow), rawTables, operation);\n const hasState = tables.some((row) => row.name === \"effect_agent_schedule_store_state\");\n const hasSchedules = tables.some((row) => row.name === \"effect_agent_schedules\");\n\n if (!hasState) {\n if (hasSchedules) return yield* corrupt(operation);\n yield* sql\n .withTransaction(\n Effect.gen(function* () {\n yield* sql`\n CREATE TABLE effect_agent_schedule_store_state (\n singleton INTEGER PRIMARY KEY NOT NULL CHECK (singleton = 1),\n storage_version INTEGER NOT NULL,\n alarm_generation INTEGER NOT NULL\n )\n `.withoutTransform;\n yield* sql`\n CREATE TABLE effect_agent_schedules (\n tenant_id TEXT NOT NULL,\n owner_id TEXT NOT NULL,\n schedule_id TEXT NOT NULL,\n deadline_at_millis INTEGER,\n record_json TEXT NOT NULL,\n PRIMARY KEY (tenant_id, owner_id, schedule_id)\n )\n `.withoutTransform;\n yield* sql`\n CREATE INDEX effect_agent_schedules_deadline\n ON effect_agent_schedules (deadline_at_millis, tenant_id, owner_id, schedule_id)\n WHERE deadline_at_millis IS NOT NULL\n `.withoutTransform;\n yield* sql`\n CREATE INDEX effect_agent_schedules_owner_deadline\n ON effect_agent_schedules (tenant_id, owner_id, deadline_at_millis, schedule_id)\n WHERE deadline_at_millis IS NOT NULL\n `.withoutTransform;\n yield* sql`\n INSERT INTO effect_agent_schedule_store_state (\n singleton, storage_version, alarm_generation\n ) VALUES (1, ${CURRENT_SCHEDULE_STORE_VERSION}, 0)\n `.withoutTransform;\n }),\n )\n .pipe(Effect.mapError(() => unavailable(operation)));\n return;\n }\n\n if (!hasSchedules) return yield* corrupt(operation);\n const rawState = yield* sql<Record<string, unknown>>`\n SELECT storage_version, alarm_generation\n FROM effect_agent_schedule_store_state\n WHERE singleton = 1\n `.pipe(Effect.mapError(() => unavailable(operation)));\n const state = yield* decodeRows(Schema.Array(ScheduleStoreStateRow), rawState, operation);\n if (state.length !== 1 || state[0].storage_version !== CURRENT_SCHEDULE_STORE_VERSION) {\n return yield* corrupt(operation);\n }\n});\n\nconst makeServices = Effect.gen(function* () {\n const sql = yield* SqlClientService.SqlClient;\n const transactions = yield* DoScheduleTransaction;\n const scheduleFailpoint = yield* ScheduleFailpoint;\n\n yield* initializeScheduleStore();\n\n const readRows = Effect.fn(\"DoScheduleStore.readRows\")(function* (\n key: ScheduleKey,\n operation: string,\n ): Effect.fn.Return<ReadonlyArray<ScheduleRow>, ScheduleStorageError> {\n const rows = yield* sql<Record<string, unknown>>`\n SELECT tenant_id, owner_id, schedule_id, deadline_at_millis, record_json\n FROM effect_agent_schedules\n WHERE tenant_id = ${key.owner.tenantId}\n AND owner_id = ${key.owner.ownerId}\n AND schedule_id = ${key.scheduleId}\n `.pipe(Effect.mapError(() => unavailable(operation)));\n return yield* decodeRows(Schema.Array(ScheduleRow), rows, operation);\n });\n\n const readOne = Effect.fn(\"DoScheduleStore.readOne\")(function* (\n key: ScheduleKey,\n operation: string,\n ): Effect.fn.Return<ScheduleRecord | null, ScheduleStorageError> {\n const rows = yield* readRows(key, operation);\n if (rows.length === 0) return null;\n if (rows.length !== 1) return yield* corrupt(operation);\n return yield* decodeRecord(rows[0]);\n });\n\n const readNextDeadline = Effect.fn(\"DoScheduleStore.readNextDeadline\")(function* (\n owner: ScheduleOwner | undefined,\n operation: string,\n ): Effect.fn.Return<number | null, ScheduleStorageError> {\n const rows =\n owner === undefined\n ? yield* sql<Record<string, unknown>>`\n SELECT MIN(deadline_at_millis) AS deadline_at_millis\n FROM effect_agent_schedules\n WHERE deadline_at_millis IS NOT NULL\n `.pipe(Effect.mapError(() => unavailable(operation)))\n : yield* sql<Record<string, unknown>>`\n SELECT MIN(deadline_at_millis) AS deadline_at_millis\n FROM effect_agent_schedules\n WHERE tenant_id = ${owner.tenantId}\n AND owner_id = ${owner.ownerId}\n AND deadline_at_millis IS NOT NULL\n `.pipe(Effect.mapError(() => unavailable(operation)));\n const decoded = yield* decodeRows(Schema.Array(ScheduleDeadlineRow), rows, operation);\n if (decoded.length !== 1) return yield* corrupt(operation);\n return decoded[0].deadline_at_millis;\n });\n\n const replaceAlarm = Effect.fn(\"DoScheduleStore.replaceAlarm\")(function* (\n replace: DoScheduleReplaceAlarm,\n deadlineAtMillis: number | null,\n operation: string,\n ) {\n const rawState = yield* sql<Record<string, unknown>>`\n UPDATE effect_agent_schedule_store_state\n SET alarm_generation = alarm_generation + 1\n WHERE singleton = 1\n RETURNING storage_version, alarm_generation\n `.pipe(Effect.mapError(() => unavailable(operation)));\n const state = yield* decodeRows(Schema.Array(ScheduleStoreStateRow), rawState, operation);\n if (state.length !== 1 || state[0].storage_version !== CURRENT_SCHEDULE_STORE_VERSION) {\n return yield* corrupt(operation);\n }\n yield* scheduleFailpoint.hit(\"schedule:alarm:before\");\n yield* replace({ deadlineAtMillis, generation: state[0].alarm_generation });\n yield* scheduleFailpoint.hit(\"schedule:alarm:after\");\n });\n\n const insert: ScheduleStore[\"Service\"][\"insert\"] = Effect.fn(\"DoScheduleStore.insert\")(\n function* (record, ownerLimit) {\n const operation = \"insert schedule\";\n const canonical = yield* decodeBoundary(ScheduleRecord, record, operation);\n const recordJson = yield* encodeRecord(canonical);\n const result = yield* transactions.run((replace) =>\n Effect.gen(function* () {\n const existing = yield* readOne(canonical, operation);\n if (existing !== null) {\n if (existing.creationFingerprint === canonical.creationFingerprint) {\n return { record: existing, inserted: false } as const;\n }\n return yield* ScheduleConflict.make({ reason: \"creation\", key: canonical });\n }\n const rawCounts = yield* sql<Record<string, unknown>>`\n SELECT COUNT(*) AS schedule_count\n FROM effect_agent_schedules\n WHERE tenant_id = ${canonical.owner.tenantId}\n AND owner_id = ${canonical.owner.ownerId}\n AND (json_extract(record_json, '$.pending') IS NOT NULL OR\n (json_extract(record_json, '$.state') != 'cancelled' AND json_extract(record_json, '$.nextAtMillis') IS NOT NULL))\n `.pipe(Effect.mapError(() => unavailable(operation)));\n const counts = yield* decodeRows(Schema.Array(ScheduleCountRow), rawCounts, operation);\n if (counts.length !== 1) return yield* corrupt(operation);\n if (counts[0].schedule_count >= ownerLimit) {\n return yield* ScheduleCapacityError.make({ limit: ownerLimit });\n }\n yield* scheduleFailpoint.hit(\"schedule:insert:before\");\n yield* sql`\n INSERT INTO effect_agent_schedules (\n tenant_id, owner_id, schedule_id, deadline_at_millis, record_json\n ) VALUES (\n ${canonical.owner.tenantId},\n ${canonical.owner.ownerId},\n ${canonical.scheduleId},\n ${scheduleDeadline(canonical)},\n ${recordJson}\n )\n `.pipe(Effect.mapError(() => unavailable(operation)));\n const deadline = yield* readNextDeadline(undefined, operation);\n yield* replaceAlarm(replace, deadline, operation);\n return { record: canonical, inserted: true } as const;\n }),\n );\n if (result.inserted) yield* scheduleFailpoint.hit(\"schedule:insert:after\");\n return result.record;\n },\n );\n\n const get: ScheduleStore[\"Service\"][\"get\"] = Effect.fn(\"DoScheduleStore.get\")(function* (key) {\n const canonical = yield* decodeBoundary(ScheduleKey, key, \"get schedule\");\n return yield* readOne(canonical, \"get schedule\");\n });\n\n const list: ScheduleStore[\"Service\"][\"list\"] = Effect.fn(\"DoScheduleStore.list\")(function* (\n requestValue: SchedulePageRequest,\n ): Effect.fn.Return<SchedulePage, ScheduleStorageError> {\n const operation = \"list schedules\";\n const request = yield* decodeBoundary(SchedulePageRequest, requestValue, operation);\n const rows =\n request.after === undefined\n ? yield* sql<Record<string, unknown>>`\n SELECT tenant_id, owner_id, schedule_id, deadline_at_millis, record_json\n FROM effect_agent_schedules\n WHERE tenant_id = ${request.owner.tenantId}\n AND owner_id = ${request.owner.ownerId}\n ORDER BY schedule_id\n LIMIT ${request.limit + 1}\n `.pipe(Effect.mapError(() => unavailable(operation)))\n : yield* sql<Record<string, unknown>>`\n SELECT tenant_id, owner_id, schedule_id, deadline_at_millis, record_json\n FROM effect_agent_schedules\n WHERE tenant_id = ${request.owner.tenantId}\n AND owner_id = ${request.owner.ownerId}\n AND schedule_id > ${request.after}\n ORDER BY schedule_id\n LIMIT ${request.limit + 1}\n `.pipe(Effect.mapError(() => unavailable(operation)));\n const decoded = yield* decodeRows(Schema.Array(ScheduleRow), rows, operation);\n const records = yield* Effect.forEach(decoded, decodeRecord);\n const hasNext = records.length > request.limit;\n const items = hasNext ? records.slice(0, request.limit) : records;\n return { items, next: hasNext ? (items.at(-1)?.scheduleId ?? null) : null };\n });\n\n const change: ScheduleStore[\"Service\"][\"change\"] = Effect.fn(\"DoScheduleStore.change\")(function* (\n key,\n change,\n ownerLimit = defaultSchedulingLimits.maxSchedulesPerOwner,\n ) {\n const operation = \"change schedule\";\n const canonicalKey = yield* decodeBoundary(ScheduleKey, key, operation);\n const canonicalChange = yield* decodeBoundary(ScheduleChange, change, operation);\n const result = yield* transactions.run((replace) =>\n Effect.gen(function* () {\n const current = yield* readOne(canonicalKey, operation);\n if (current === null) return yield* ScheduleNotFound.make({ key: canonicalKey });\n const transition = applyScheduleChange(current, canonicalChange);\n if (Result.isFailure(transition)) return yield* transition.failure;\n const next = transition.success;\n if (!scheduleUsesCapacity(current) && scheduleUsesCapacity(next)) {\n const rawCounts = yield* sql<Record<string, unknown>>`\n SELECT COUNT(*) AS schedule_count FROM effect_agent_schedules\n WHERE tenant_id = ${key.owner.tenantId} AND owner_id = ${key.owner.ownerId}\n AND (json_extract(record_json, '$.pending') IS NOT NULL OR\n (json_extract(record_json, '$.state') != 'cancelled' AND json_extract(record_json, '$.nextAtMillis') IS NOT NULL))\n `.pipe(Effect.mapError(() => unavailable(operation)));\n const counts = yield* decodeRows(Schema.Array(ScheduleCountRow), rawCounts, operation);\n if (counts.length !== 1) return yield* corrupt(operation);\n if (counts[0].schedule_count >= ownerLimit)\n return yield* ScheduleCapacityError.make({ limit: ownerLimit });\n }\n if (next === current) return { record: current, changed: false } as const;\n const recordJson = yield* encodeRecord(next);\n yield* scheduleFailpoint.hit(`schedule:${canonicalChange._tag.toLowerCase()}:before`);\n yield* sql`\n UPDATE effect_agent_schedules\n SET deadline_at_millis = ${scheduleDeadline(next)}, record_json = ${recordJson}\n WHERE tenant_id = ${canonicalKey.owner.tenantId}\n AND owner_id = ${canonicalKey.owner.ownerId}\n AND schedule_id = ${canonicalKey.scheduleId}\n `.pipe(Effect.mapError(() => unavailable(operation)));\n const deadline = yield* readNextDeadline(undefined, operation);\n yield* replaceAlarm(replace, deadline, operation);\n return { record: next, changed: true } as const;\n }),\n );\n if (result.changed) {\n yield* scheduleFailpoint.hit(`schedule:${canonicalChange._tag.toLowerCase()}:after`);\n }\n return result.record;\n });\n\n const due: ScheduleStore[\"Service\"][\"due\"] = Effect.fn(\"DoScheduleStore.due\")(function* (\n nowMillis,\n limit,\n owner?: ScheduleOwner,\n after?: ScheduleDueCursor,\n ) {\n const operation = \"query due schedules\";\n const cursor =\n after === undefined\n ? undefined\n : yield* Schema.decodeUnknownEffect(ScheduleDueCursor)(after).pipe(\n Effect.mapError(() => corrupt(operation)),\n );\n const continuation =\n cursor === undefined\n ? sql`1 = 1`\n : sql`\n (deadline_at_millis, tenant_id, owner_id, schedule_id) >\n (${cursor.deadlineAtMillis}, ${cursor.owner.tenantId}, ${cursor.owner.ownerId}, ${cursor.scheduleId})`;\n const rows =\n owner === undefined\n ? yield* sql<Record<string, unknown>>`\n SELECT tenant_id, owner_id, schedule_id, deadline_at_millis\n FROM effect_agent_schedules\n WHERE deadline_at_millis <= ${nowMillis} AND ${continuation}\n ORDER BY deadline_at_millis, tenant_id, owner_id, schedule_id\n LIMIT ${limit}\n `.pipe(Effect.mapError(() => unavailable(operation)))\n : yield* sql<Record<string, unknown>>`\n SELECT tenant_id, owner_id, schedule_id, deadline_at_millis\n FROM effect_agent_schedules\n WHERE tenant_id = ${owner.tenantId}\n AND owner_id = ${owner.ownerId}\n AND deadline_at_millis <= ${nowMillis} AND ${continuation}\n ORDER BY deadline_at_millis, schedule_id\n LIMIT ${limit}\n `.pipe(Effect.mapError(() => unavailable(operation)));\n const decoded = yield* decodeRows(Schema.Array(ScheduleDueRow), rows, operation);\n return decoded.map((row) => ({\n owner: { tenantId: row.tenant_id, ownerId: row.owner_id },\n scheduleId: row.schedule_id,\n deadlineAtMillis: row.deadline_at_millis,\n }));\n });\n\n const nextDeadline: ScheduleStore[\"Service\"][\"nextDeadline\"] = Effect.fn(\n \"DoScheduleStore.nextDeadline\",\n )(function* (owner?: ScheduleOwner) {\n const operation = \"query next schedule deadline\";\n return yield* readNextDeadline(owner, operation);\n });\n\n const prearm = Effect.fn(\"DoScheduleStore.prearm\")(function* (\n deadlineAtMillis: number,\n ): Effect.fn.Return<void, ScheduleStorageError | ScheduleFailpointError> {\n yield* decodeBoundary(ScheduleInstant, deadlineAtMillis, \"pre-arm schedule recovery\");\n yield* transactions.run((replace) =>\n replaceAlarm(replace, deadlineAtMillis, \"pre-arm schedule recovery\"),\n );\n yield* scheduleFailpoint.hit(\"schedule:prearm:after\");\n });\n\n const reconcile = Effect.gen(function* () {\n yield* transactions.run((replace) =>\n Effect.gen(function* () {\n const deadline = yield* readNextDeadline(undefined, \"reconcile schedule alarm\");\n yield* replaceAlarm(replace, deadline, \"reconcile schedule alarm\");\n }),\n );\n yield* scheduleFailpoint.hit(\"schedule:reconcile:after\");\n });\n\n return Context.make(ScheduleStore, {\n insert,\n get,\n list,\n change,\n due,\n nextDeadline,\n }).pipe(Context.add(DoScheduleAlarmControl, { prearm, reconcile }));\n});\n\n/**\n * Durable Object SQLite ScheduleStore. Platform code supplies the one transaction owner that\n * combines these SQL mutations with its logical and native alarm lifecycle.\n */\nexport const scheduleStoreLayer: Layer.Layer<\n ScheduleStore | DoScheduleAlarmControl,\n ScheduleStorageError,\n SqlClientService.SqlClient | DoScheduleTransaction\n> = Layer.effectContext(makeServices);\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 AdmissionConflict,\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 SubmissionLookupByKey,\n type SubmissionSnapshot,\n} from \"@effect-agent/session\";\nimport { Context, Effect, Layer, Option, Predicate, 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\nconst safeTransportDiagnostic = (cause: unknown): string => {\n try {\n const message = cause instanceof Error ? cause.message : cause;\n return boundPortDiagnostic(typeof message === \"string\" ? message : String(message));\n } catch {\n return \"[unavailable transport diagnostic]\";\n }\n};\n\nconst transportRetryableSignal = (cause: unknown): boolean | undefined => {\n if (!Predicate.isObjectKeyword(cause)) return undefined;\n try {\n const signal = Reflect.get(cause, \"retryable\");\n return typeof signal === \"boolean\" ? signal : undefined;\n } catch {\n return undefined;\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 retryable = transportRetryableSignal(cause);\n return PortTransportError.make({\n target,\n message: safeTransportDiagnostic(cause),\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 NoAdditionalPortFailure = Schema.Never;\nconst AbortPortFailure = Schema.Union([SettlementConflict, JoinedToHost]);\nconst AppendPortFailure = Schema.Union([\n ConversationNotMaterialized,\n AppendConflict,\n FenceRejected,\n]);\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 = <ResultSchema extends Schema.Top, FailureSchema extends Schema.Top>(\n operation: string,\n target: ConversationId,\n call: PortRequest,\n resultSchema: ResultSchema,\n failureSchema: FailureSchema,\n ): Effect.Effect<ResultSchema[\"Type\"], FailureSchema[\"Type\"] | LedgerError> => {\n const isExpectedResult = Schema.is(resultSchema);\n const isExpectedFailure = Schema.is(failureSchema);\n return transportCall(target, call).pipe(\n Effect.mapError(routeFailure(operation, target)),\n Effect.flatMap(\n (response): Effect.Effect<ResultSchema[\"Type\"], FailureSchema[\"Type\"] | LedgerError> => {\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 (!isExpectedResult(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}.`,\n }),\n );\n }\n return Effect.succeed(result);\n },\n ),\n Effect.withSpan(\"DoPortRouting.foreignLedgerCall\", {\n attributes: { operation, target },\n }),\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 NoAdditionalPortFailure,\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 AdmissionConflict,\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 NoAdditionalPortFailure,\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 NoAdditionalPortFailure,\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 AbortPortFailure,\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 NoAdditionalPortFailure,\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 = <ResultSchema extends Schema.Top, FailureSchema extends Schema.Top>(\n operation: string,\n target: ConversationId,\n call: PortRequest,\n resultSchema: ResultSchema,\n failureSchema: FailureSchema,\n ): Effect.Effect<ResultSchema[\"Type\"], FailureSchema[\"Type\"] | ConversationStoreError> => {\n const isExpectedResult = Schema.is(resultSchema);\n const isExpectedFailure = Schema.is(failureSchema);\n return transportCall(target, call).pipe(\n Effect.mapError(routeFailure(operation, target)),\n Effect.flatMap(\n (\n response,\n ): Effect.Effect<ResultSchema[\"Type\"], FailureSchema[\"Type\"] | ConversationStoreError> => {\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 (!isExpectedResult(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}.`,\n }),\n );\n }\n return Effect.succeed(result);\n },\n ),\n Effect.withSpan(\"DoPortRouting.foreignStoreCall\", {\n attributes: { operation, target },\n }),\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 FenceRejected,\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 AppendPortFailure,\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 ConversationNotMaterialized,\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 ConversationNotMaterialized,\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 ConversationNotMaterialized,\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,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C,GAAG,OAAO,EAAE,CAAC,CAAC,CAC7E,CACF;EACF;EACA,KAAK,oBAAoB;GACvB,MAAM,QAAQ,OAAO;GACrB,OAAO,OAAO,QACZ,MACG,YAAY,QAAQ,OAAO,CAAC,CAC5B,KAAK,OAAO,KAAK,SAAS,uBAAuB,KAAK,EAAE,KAAK,CAAC,CAAC,CAAC,CACrE;EACF;EACA,KAAK,eAAe;GAClB,MAAM,QAAQ,OAAO;GACrB,OAAO,OAAO,QACZ,MACG,OAAO,QAAQ,OAAO,CAAC,CACvB,KACC,OAAO,KAAK,uBACV,kBAAkB,KAAK,EAAE,QAAQ,mBAAmB,CAAC,CACvD,CACF,CACJ;EACF;CACF;AACF,CAAC;;;;;;AAOD,MAAM,0BAA0B,aAA8B;CAC5D,MAAM;CACN,SAAS;EAAE,MAAM;EAAqB,SAAS,oBAAoB,OAAO;CAAE;AAC9E;;;;;;;;AASA,MAAa,2BAA2B,OAAO,GAAG,wCAAwC,CAAC,CACzF,WACE,SACwE;CAexE,OAAO,OAAO,mBAAmB,OAdT,kBAAkB,OAAO,CAAC,CAAC,KACjD,OAAO,QAAQ,kBAAkB,GACjC,OAAO,OAAO,UACZ,OAAO,QACL,WAAW,KAAK,EACd,SAAS,kBAAkB,KAAK,EAC9B,SAAS,oBACP,0CAA0C,MAAM,SAClD,EACF,CAAC,EACH,CAAC,CACH,CACF,CACF,CACyC,CAAC,CAAC,KACzC,OAAO,OAAO,UACZ,OAAO,QACL,uBAAuB,2CAA2C,MAAM,SAAS,CACnF,CACF,CACF;AACF,CACF"}
|
|
1
|
+
{"version":3,"file":"index.mjs","names":["BoundedStoredText","BoundedIdentifier","MAX_IDENTIFIER_LENGTH","decodeRows","makeServices","SqlClientService","makeServices","SqlClientService","decodeRows","unavailable","corrupt","decodeRows","SqlClientService","SqlClientService"],"sources":["../src/errors.ts","../src/migrations.ts","../src/do-journal.ts","../src/do-storage-config.ts","../src/do-thread-store.ts","../src/do-ledger.ts","../src/do-schedule-store.ts","../src/do-subscription-store.ts","../src/port-protocol.ts","../src/routing.ts"],"sourcesContent":["import { CanonicalSequence, ProducerEpoch } from \"@effect-agent/thread\";\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 Thread'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-thread-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 = 2;\n\n/**\n * The Thread 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 Threads\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_thread_object\": Effect.gen(function* () {\n const sql = yield* SqlClient.SqlClient;\n\n yield* sql`\n CREATE TABLE effect_agent_threads (\n thread_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 thread_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 (thread_id, batch_id),\n FOREIGN KEY (thread_id)\n REFERENCES effect_agent_threads(thread_id)\n ON DELETE RESTRICT\n )\n `.withoutTransform;\n\n yield* sql`\n CREATE TABLE effect_agent_canonical_records (\n thread_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 (thread_id, sequence),\n UNIQUE (thread_id, record_id),\n FOREIGN KEY (thread_id, batch_id)\n REFERENCES effect_agent_canonical_batches(thread_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 (thread_id, batch_id, sequence)\n `.withoutTransform;\n\n yield* sql`\n CREATE TABLE effect_agent_checkpoints (\n thread_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 (thread_id, through_sequence),\n FOREIGN KEY (thread_id)\n REFERENCES effect_agent_threads(thread_id)\n ON DELETE RESTRICT\n )\n `.withoutTransform;\n\n // Admission rows exist before Thread materialization (durability §4), so\n // thread_id intentionally carries no foreign key into effect_agent_threads.\n yield* sql`\n CREATE TABLE effect_agent_submissions (\n submission_id TEXT PRIMARY KEY NOT NULL,\n thread_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 (thread_id, principal, idempotency_key),\n UNIQUE (thread_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 thread_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/thread\";\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 type DoStorageFailpointError,\n DoAppendConflict,\n DoCheckpointConflict,\n DoFenceRejected,\n DoStorageCompatibilityError,\n DoStorageCorruptionError,\n DoStorageError,\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_THREAD = 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;\nconst isSqlError = Schema.is(SqlError);\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 ThreadRow extends Schema.Class<ThreadRow>(\"ThreadRow\")({\n thread_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 thread_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 thread_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 thread_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 threadId: 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 threadId: 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 threadId: BoundedIdentifier,\n tailDigest: BoundedStoredText,\n throughSequence: CanonicalSequence,\n}) {}\n\nexport class RawThreadExport extends Schema.Class<RawThreadExport>(\n \"@effect-agent/storage-cloudflare/RawThreadExport\",\n)({\n batches: Schema.Array(BatchRow),\n checkpoints: Schema.Array(CheckpointRow),\n thread: ThreadRow,\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(\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(\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_threads\",\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) => (isSqlError(error) ? storageError(operation)(error) : error)),\n Effect.withSpan(\"DoJournal.withWriteTransaction\", { attributes: { operation } }),\n );\n\n const materialize = Effect.fn(\"DoJournal.materialize\")(function* (\n threadId: string,\n createdAt: string,\n emptyTailDigest: string,\n producerEpoch: ProducerEpoch,\n ): Effect.fn.Return<\n void,\n DoFenceRejected | DoStorageCorruptionError | DoStorageError | DoValueBoundExceeded\n > {\n if (threadId.length > MAX_IDENTIFIER_LENGTH) {\n return yield* DoStorageError.make({\n operation: \"materialize thread\",\n message: \"Thread identity exceeds the Durable Object storage bounds.\",\n });\n }\n yield* checkValueBound(\"materialize thread\", emptyTailDigest);\n yield* withWriteTransaction(\"materialize transaction\")(\n Effect.gen(function* () {\n const existingRows = yield* sql<Record<string, unknown>>`\n SELECT\n thread_id,\n created_at,\n tail_sequence,\n tail_digest,\n producer_epoch\n FROM effect_agent_threads\n WHERE thread_id = ${threadId}\n `.pipe(Effect.mapError(storageError(\"read materialized thread\")));\n const existing = yield* decodeRows(\n Schema.Array(ThreadRow),\n \"effect_agent_threads\",\n threadId,\n existingRows,\n );\n if (existing.length > 1) {\n return yield* DoStorageCorruptionError.make({\n table: \"effect_agent_threads\",\n rowKey: threadId,\n message: \"A thread primary key returned more than one row.\",\n });\n }\n if (existing.length === 0) {\n yield* sql`\n INSERT INTO effect_agent_threads (\n thread_id,\n created_at,\n tail_sequence,\n tail_digest,\n producer_epoch\n ) VALUES (\n ${threadId},\n ${createdAt},\n 0,\n ${emptyTailDigest},\n ${producerEpoch}\n )\n `.pipe(Effect.mapError(storageError(\"materialize thread\")));\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_threads\n SET producer_epoch = ${producerEpoch}\n WHERE thread_id = ${threadId}\n `.pipe(Effect.mapError(storageError(\"advance materialization epoch\")));\n }\n }),\n );\n });\n\n const getThread = Effect.fn(\"DoJournal.getThread\")(function* (threadId: string) {\n const rows = yield* sql<Record<string, unknown>>`\n SELECT\n thread_id,\n created_at,\n tail_sequence,\n tail_digest,\n producer_epoch\n FROM effect_agent_threads\n WHERE thread_id = ${threadId}\n `.pipe(Effect.mapError(storageError(\"read thread\")));\n return yield* decodeRows(Schema.Array(ThreadRow), \"effect_agent_threads\", threadId, rows);\n });\n\n const append = Effect.fn(\"DoJournal.append\")(function* (\n request: RawAppendRequest,\n ): Effect.fn.Return<RawAppendResult, AppendError> {\n if (\n request.threadId.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 threadRows = yield* sql<Record<string, unknown>>`\n SELECT\n thread_id,\n created_at,\n tail_sequence,\n tail_digest,\n producer_epoch\n FROM effect_agent_threads\n WHERE thread_id = ${request.threadId}\n `.pipe(Effect.mapError(storageError(\"read append tail\")));\n const thread = yield* decodeSingleRow(\n Schema.Array(ThreadRow),\n \"effect_agent_threads\",\n request.threadId,\n threadRows,\n );\n\n if (request.producerEpoch !== thread.producer_epoch) {\n return yield* DoFenceRejected.make({\n producerEpoch: request.producerEpoch,\n actualEpoch: thread.producer_epoch,\n message: `Producer epoch ${request.producerEpoch} is not the current epoch ${thread.producer_epoch}.`,\n });\n }\n\n const batchRows = yield* sql<Record<string, unknown>>`\n SELECT\n thread_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 thread_id = ${request.threadId}\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.threadId}/${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.threadId}/${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 !== thread.tail_sequence ||\n request.expectedTailDigest !== thread.tail_digest\n ) {\n return yield* DoAppendConflict.make({\n message:\n `Expected tail ${request.expectedTailSequence}/${request.expectedTailDigest} ` +\n `but found ${thread.tail_sequence}/${thread.tail_digest}.`,\n reason: \"tail\",\n actualTailSequence: thread.tail_sequence,\n actualTailDigest: thread.tail_digest,\n });\n }\n if (thread.tail_sequence + request.records.length > MAX_RECORDS_PER_THREAD) {\n return yield* DoStorageError.make({\n operation: \"append canonical batch\",\n message: `Thread record limit ${MAX_RECORDS_PER_THREAD} 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 thread_id,\n sequence,\n record_id,\n batch_id,\n record_json\n FROM effect_agent_canonical_records\n WHERE thread_id = ${request.threadId}\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.threadId}/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 thread.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 thread_id,\n batch_id,\n first_sequence,\n last_sequence,\n batch_digest,\n tail_digest,\n batch_json\n ) VALUES (\n ${request.threadId},\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 thread_id,\n sequence,\n record_id,\n batch_id,\n record_json\n ) VALUES (\n ${request.threadId},\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_threads\n SET\n tail_sequence = ${lastSequence},\n tail_digest = ${request.tailDigest},\n producer_epoch = ${request.producerEpoch}\n WHERE thread_id = ${request.threadId}\n `.pipe(Effect.mapError(storageError(\"advance thread 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 thread_id,\n sequence,\n record_id,\n batch_id,\n record_json\n FROM effect_agent_canonical_records\n WHERE thread_id = ${request.threadId}\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.threadId}>${request.fromSequenceExclusive}`,\n rows,\n );\n });\n\n const exportThread = Effect.fn(\"DoJournal.exportThread\")(function* (threadId: string) {\n return yield* sql\n .withTransaction(\n Effect.gen(function* () {\n const threadRows = yield* sql<Record<string, unknown>>`\n SELECT\n thread_id,\n created_at,\n tail_sequence,\n tail_digest,\n producer_epoch\n FROM effect_agent_threads\n WHERE thread_id = ${threadId}\n `.pipe(Effect.mapError(storageError(\"export thread\")));\n const thread = yield* decodeSingleRow(\n Schema.Array(ThreadRow),\n \"effect_agent_threads\",\n threadId,\n threadRows,\n );\n yield* failpoint(\"export:after-thread-read\");\n const batchRows = yield* sql<Record<string, unknown>>`\n SELECT\n thread_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 thread_id = ${threadId}\n ORDER BY first_sequence\n `.pipe(Effect.mapError(storageError(\"export canonical batches\")));\n const recordRows = yield* sql<Record<string, unknown>>`\n SELECT\n thread_id,\n sequence,\n record_id,\n batch_id,\n record_json\n FROM effect_agent_canonical_records\n WHERE thread_id = ${threadId}\n ORDER BY sequence\n `.pipe(Effect.mapError(storageError(\"export canonical records\")));\n const checkpointRows = yield* sql<Record<string, unknown>>`\n SELECT\n thread_id,\n through_sequence,\n tail_digest,\n checkpoint_json\n FROM effect_agent_checkpoints\n WHERE thread_id = ${threadId}\n ORDER BY through_sequence\n `.pipe(Effect.mapError(storageError(\"export checkpoints\")));\n\n return RawThreadExport.make({\n thread,\n batches: yield* decodeRows(\n Schema.Array(BatchRow),\n \"effect_agent_canonical_batches\",\n threadId,\n batchRows,\n ),\n records: yield* decodeRows(\n Schema.Array(RecordRow),\n \"effect_agent_canonical_records\",\n threadId,\n recordRows,\n ),\n checkpoints: yield* decodeRows(\n Schema.Array(CheckpointRow),\n \"effect_agent_checkpoints\",\n threadId,\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.threadId.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 threadRows = yield* sql<Record<string, unknown>>`\n SELECT\n thread_id,\n created_at,\n tail_sequence,\n tail_digest,\n producer_epoch\n FROM effect_agent_threads\n WHERE thread_id = ${checkpoint.threadId}\n `.pipe(Effect.mapError(storageError(\"read checkpoint tail\")));\n const thread = yield* decodeSingleRow(\n Schema.Array(ThreadRow),\n \"effect_agent_threads\",\n checkpoint.threadId,\n threadRows,\n );\n if (checkpoint.throughSequence > thread.tail_sequence) {\n return yield* DoCheckpointConflict.make({\n message:\n `Checkpoint sequence ${checkpoint.throughSequence} is after canonical tail ` +\n `${thread.tail_sequence}.`,\n });\n }\n\n const checkpointRows = yield* sql<Record<string, unknown>>`\n SELECT\n thread_id,\n through_sequence,\n tail_digest,\n checkpoint_json\n FROM effect_agent_checkpoints\n WHERE thread_id = ${checkpoint.threadId}\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.threadId}/${checkpoint.throughSequence}`,\n checkpointRows,\n );\n if (existing.length > 1) {\n return yield* DoStorageCorruptionError.make({\n table: \"effect_agent_checkpoints\",\n rowKey: `${checkpoint.threadId}/${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 thread_id,\n through_sequence,\n tail_digest,\n checkpoint_json\n ) VALUES (\n ${checkpoint.threadId},\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 threadId: string,\n atOrBeforeSequence: CanonicalSequence,\n ) {\n const rows = yield* sql<Record<string, unknown>>`\n SELECT\n thread_id,\n through_sequence,\n tail_digest,\n checkpoint_json\n FROM effect_agent_checkpoints\n WHERE thread_id = ${threadId}\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 `${threadId}<=${atOrBeforeSequence}`,\n rows,\n );\n });\n\n const getTailDigestAt = Effect.fn(\"DoJournal.getTailDigestAt\")(function* (\n threadId: string,\n sequence: CanonicalSequence,\n ) {\n if (sequence === 0) {\n const threads = yield* getThread(threadId);\n return threads.length === 0\n ? []\n : [threads[0].tail_sequence === 0 ? threads[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 thread_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 thread_id = ${threadId}\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 `${threadId}/${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 threads = yield* sql<Record<string, unknown>>`\n SELECT\n thread_id,\n created_at,\n tail_sequence,\n tail_digest,\n producer_epoch\n FROM effect_agent_threads\n ORDER BY thread_id\n `.pipe(Effect.mapError(storageError(\"scan threads\")));\n const batches = yield* sql<Record<string, unknown>>`\n SELECT\n thread_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 thread_id, first_sequence\n `.pipe(Effect.mapError(storageError(\"scan canonical batches\")));\n const records = yield* sql<Record<string, unknown>>`\n SELECT\n thread_id,\n sequence,\n record_id,\n batch_id,\n record_json\n FROM effect_agent_canonical_records\n ORDER BY thread_id, sequence\n `.pipe(Effect.mapError(storageError(\"scan canonical records\")));\n const checkpoints = yield* sql<Record<string, unknown>>`\n SELECT\n thread_id,\n through_sequence,\n tail_digest,\n checkpoint_json\n FROM effect_agent_checkpoints\n ORDER BY thread_id, through_sequence\n `.pipe(Effect.mapError(storageError(\"scan checkpoints\")));\n return {\n threads: yield* decodeRows(\n Schema.Array(ThreadRow),\n \"effect_agent_threads\",\n \"startup_scan\",\n threads,\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 exportThread,\n getThread,\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 {\n AppendConflict,\n AppendResult,\n CanonicalBatch,\n CanonicalRecord,\n CanonicalRecordEnvelope,\n CanonicalSequence,\n CheckpointRejected,\n ThreadCheckpoint,\n ThreadExport,\n ThreadExportRequest,\n ThreadMaterialization,\n ThreadNotMaterialized,\n ThreadObservation,\n ThreadRead,\n ThreadStore,\n type ThreadCheckpoints,\n ThreadStoreError,\n ThreadTail,\n ThreadTailRequest,\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/thread\";\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 type DoStorageCompatibilityError,\n DoAppendConflict,\n DoCheckpointConflict,\n DoFenceRejected,\n type DoStorageFailpointLocation,\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/thread`.\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);\nconst isDoFenceRejected = Schema.is(DoFenceRejected);\nconst isDoAppendConflict = Schema.is(DoAppendConflict);\nconst isDoCheckpointConflict = Schema.is(DoCheckpointConflict);\n\nconst storeError = (operation: string, error: { readonly message: string }) =>\n ThreadStoreError.make({\n cause: error,\n operation,\n message: error.message,\n });\n\nconst schemaStoreError = (operation: string, error: { readonly message: string }) =>\n ThreadStoreError.make({\n cause: error,\n operation,\n message: error.message,\n });\n\nconst makeOffset = Effect.fn(function* (\n threadId: ThreadMaterialization[\"threadId\"],\n sequence: number,\n): Effect.fn.Return<ObservationOffset, ThreadStoreError> {\n return yield* Schema.decodeUnknownEffect(CanonicalSequence)(sequence).pipe(\n Effect.flatMap((validatedSequence) =>\n Schema.decodeUnknownEffect(ObservationOffset)(\n `${DO_OFFSET_PREFIX}${encodeURIComponent(threadId)}:${validatedSequence}`,\n ),\n ),\n Effect.mapError((error) => schemaStoreError(\"encode observation offset\", error)),\n );\n});\n\nconst parseOffset = Effect.fn(function* (\n threadId: ThreadMaterialization[\"threadId\"],\n offset: ObservationOffset | undefined,\n): Effect.fn.Return<CanonicalSequence, ThreadStoreError> {\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 threadPrefix = `${DO_OFFSET_PREFIX}${encodeURIComponent(threadId)}:`;\n if (!text.startsWith(threadPrefix)) {\n return yield* ThreadStoreError.make({\n operation: \"decode observation offset\",\n message: \"The observation offset belongs to a different adapter, storage version, or Thread.\",\n });\n }\n const sequenceText = text.slice(threadPrefix.length);\n if (!/^(0|[1-9][0-9]*)$/.test(sequenceText)) {\n return yield* ThreadStoreError.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 = (threadId: ThreadMaterialization[\"threadId\"], error: DoFenceRejected) =>\n FenceRejected.make({\n threadId,\n actualEpoch: error.actualEpoch,\n attemptedEpoch: error.producerEpoch,\n });\n\nconst encodeCanonicalRecord = Effect.fn(function* (\n record: CanonicalRecord,\n): Effect.fn.Return<string, ThreadStoreError> {\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(function* (\n batch: CanonicalBatch,\n): Effect.fn.Return<string, ThreadStoreError> {\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(function* (\n checkpoint: ThreadCheckpoint,\n): Effect.fn.Return<string, ThreadStoreError> {\n return yield* Schema.encodeEffect(Schema.fromJsonString(ThreadCheckpoint))(checkpoint).pipe(\n Effect.mapError((error) => schemaStoreError(\"encode checkpoint\", error)),\n );\n});\n\nconst decodeEnvelope = Effect.fn(function* (row: {\n readonly batch_id: string;\n readonly thread_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 ThreadStoreError.make({\n operation: \"decode canonical record\",\n message: error.message,\n }),\n ),\n );\n const threadId = yield* Schema.decodeUnknownEffect(CanonicalRecordEnvelope.fields.threadId)(\n row.thread_id,\n ).pipe(Effect.mapError((error) => schemaStoreError(\"decode thread identity\", error)));\n const offset = yield* makeOffset(threadId, 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 threadId,\n batchId,\n sequence: row.sequence,\n offset,\n record,\n });\n});\n\nconst decodeCheckpoint = Effect.fn(function* (\n checkpointJson: string,\n): Effect.fn.Return<ThreadCheckpoint, ThreadStoreError> {\n return yield* Schema.decodeEffect(Schema.fromJsonString(ThreadCheckpoint))(checkpointJson).pipe(\n Effect.mapError((error) => schemaStoreError(\"decode checkpoint\", error)),\n );\n});\n\nconst requireThread = Effect.fn(\"DoThreadStore.requireThread\")(function* (\n journal: DoJournal,\n threadId: ThreadMaterialization[\"threadId\"],\n) {\n const rows = yield* journal\n .getThread(threadId)\n .pipe(Effect.mapError((error) => storeError(\"read thread\", error)));\n if (rows.length === 0) {\n return yield* ThreadNotMaterialized.make({ threadId });\n }\n return rows[0];\n});\n\nconst tailDigestAt = Effect.fn(\"DoThreadStore.tailDigestAt\")(function* (\n journal: DoJournal,\n threadId: ThreadMaterialization[\"threadId\"],\n sequence: CanonicalSequence,\n) {\n if (sequence === 0) return EMPTY_TAIL_DIGEST;\n const digests = yield* journal\n .getTailDigestAt(threadId, sequence)\n .pipe(Effect.mapError((error) => storeError(\"read checkpoint digest\", error)));\n if (digests.length !== 1) {\n return yield* CheckpointRejected.make({\n threadId,\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(\"DoThreadStore.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.thread_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.thread_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(ThreadCheckpoint))(checkpoint.checkpoint_json).pipe(\n Effect.map((decoded) => ({ decoded, row: checkpoint })),\n Effect.mapError((error) =>\n DoStorageCorruptionError.make({\n table: \"effect_agent_checkpoints\",\n rowKey: `${checkpoint.thread_id}/${checkpoint.through_sequence}`,\n message: error.message,\n }),\n ),\n ),\n );\n\n const batchesByThread = groupByKey(batches, ({ row }) => row.thread_id);\n const recordsByThread = groupByKey(records, ({ row }) => row.thread_id);\n const checkpointsByThread = groupByKey(checkpoints, ({ row }) => row.thread_id);\n const materializedIds = new Set(stored.threads.map((thread) => thread.thread_id));\n\n for (const thread of stored.threads) {\n const threadBatches = batchesByThread.get(thread.thread_id) ?? [];\n const threadRecords = recordsByThread.get(thread.thread_id) ?? [];\n const threadCheckpoints = checkpointsByThread.get(thread.thread_id) ?? [];\n const recordsByBatch = groupByKey(threadRecords, ({ 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 threadBatches) {\n const key = `${batchRow.thread_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 threadRecords.length !== thread.tail_sequence ||\n thread.tail_sequence !== expectedSequence - 1 ||\n thread.tail_digest !== previousDigest\n ) {\n return yield* DoStorageCorruptionError.make({\n table: \"effect_agent_threads\",\n rowKey: thread.thread_id,\n message: \"Thread tail does not match its canonical batch chain.\",\n });\n }\n\n for (const checkpoint of threadCheckpoints) {\n if (\n checkpoint.decoded.threadId !== thread.thread_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: `${thread.thread_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.thread_id)) ||\n records.some(({ row }) => !materializedIds.has(row.thread_id)) ||\n checkpoints.some(({ row }) => !materializedIds.has(row.thread_id))\n ) {\n return yield* DoStorageCorruptionError.make({\n table: \"effect_agent_threads\",\n rowKey: \"startup_scan\",\n message: \"Canonical rows exist without a materialized Thread.\",\n });\n }\n});\n\nconst makeServices = Effect.fn(\"DoThreadStore.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(\n (location: DoStorageFailpointLocation): Effect.Effect<void, ThreadStoreError> =>\n failpoint\n .hit(location)\n .pipe(Effect.mapError((error) => storeError(`storage failpoint ${location}`, error))),\n );\n\n const materialize: ThreadStore[\"Service\"][\"materialize\"] = Effect.fn(\"DoThreadStore.materialize\")(\n function* (request: ThreadMaterialization) {\n const validated = yield* Schema.decodeUnknownEffect(Schema.toType(ThreadMaterialization))(\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.threadId,\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.threadId, error)\n : storeError(\"materialize thread\", error),\n ),\n );\n yield* hitFailpoint(\"materialize:after\");\n },\n );\n\n const append: ThreadStore[\"Service\"][\"append\"] = Effect.fn(\"DoThreadStore.append\")(function* (\n request: FencedAppendRequest,\n ) {\n const validated = yield* Schema.decodeUnknownEffect(Schema.toType(FencedAppendRequest))(\n request,\n ).pipe(Effect.mapError((error) => schemaStoreError(\"validate canonical append\", error)));\n yield* requireThread(journal, validated.threadId);\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 threadId: validated.threadId,\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 (isDoFenceRejected(error)) {\n return mapFence(validated.threadId, error);\n }\n if (isDoAppendConflict(error)) {\n return error.actualTailSequence !== undefined && isDigest(error.actualTailDigest)\n ? AppendConflict.make({\n threadId: validated.threadId,\n batchId: validated.batch.batchId,\n reason: error.reason,\n actualTailSequence: error.actualTailSequence,\n actualTailDigest: error.actualTailDigest,\n })\n : AppendConflict.make({\n threadId: validated.threadId,\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 const loadRecords = Effect.fn(\"DoThreadStore.loadRecords\")(function* (request: RawReadRequest) {\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(\"DoThreadStore.read\")(function* (request: ThreadRead) {\n const validated = yield* Schema.decodeUnknownEffect(Schema.toType(ThreadRead))(request).pipe(\n Effect.mapError((error) => schemaStoreError(\"validate thread read\", error)),\n );\n yield* requireThread(journal, validated.threadId);\n const records = yield* loadRecords(\n RawReadRequest.make({\n threadId: validated.threadId,\n fromSequenceExclusive: validated.afterSequence ?? ZERO_CANONICAL_SEQUENCE,\n limit: validated.limit,\n }),\n );\n return Stream.fromIterable(records);\n });\n const read: ThreadStore[\"Service\"][\"read\"] = (request) => Stream.unwrap(readEffect(request));\n\n const observeEffect = Effect.fn(\"DoThreadStore.observe\")(function* (request: ThreadObservation) {\n const validated = yield* Schema.decodeUnknownEffect(Schema.toType(ThreadObservation))(\n request,\n ).pipe(Effect.mapError((error) => schemaStoreError(\"validate thread observation\", error)));\n yield* requireThread(journal, validated.threadId);\n const initialSequence = yield* parseOffset(validated.threadId, validated.afterOffset);\n const cursor = yield* Ref.make(initialSequence);\n const poll = Effect.fn(\"DoThreadStore.observePoll\")(function* () {\n const fromSequenceExclusive = yield* Ref.get(cursor);\n const records = yield* loadRecords(\n RawReadRequest.make({\n threadId: validated.threadId,\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: ThreadStore[\"Service\"][\"observe\"] = (request) =>\n Stream.unwrap(observeEffect(request));\n\n const exportThread: ThreadStore[\"Service\"][\"export\"] = Effect.fn(\"DoThreadStore.export\")(\n function* (request: ThreadExportRequest) {\n const validated = yield* Schema.decodeUnknownEffect(Schema.toType(ThreadExportRequest))(\n request,\n ).pipe(Effect.mapError((error) => schemaStoreError(\"validate thread export\", error)));\n yield* requireThread(journal, validated.threadId);\n const exported = yield* journal\n .exportThread(validated.threadId)\n .pipe(Effect.mapError((error) => storeError(\"export thread\", error)));\n const records = yield* Effect.forEach(exported.records, decodeEnvelope);\n if (records.length > 65_536) {\n return yield* ThreadStoreError.make({\n operation: \"decode thread export\",\n message: \"The thread exceeds the current export record limit.\",\n });\n }\n const tailDigest = yield* Schema.decodeUnknownEffect(Digest)(\n exported.thread.tail_digest,\n ).pipe(Effect.mapError((error) => schemaStoreError(\"decode export tail digest\", error)));\n return ThreadExport.make({\n format: \"effect-agent/thread@1\",\n threadId: validated.threadId,\n tailSequence: exported.thread.tail_sequence,\n tailDigest,\n records,\n });\n },\n );\n\n const inspectTail: ThreadStore[\"Service\"][\"inspectTail\"] = Effect.fn(\"DoThreadStore.inspectTail\")(\n function* (request: ThreadTailRequest) {\n const validated = yield* Schema.decodeUnknownEffect(Schema.toType(ThreadTailRequest))(\n request,\n ).pipe(Effect.mapError((error) => schemaStoreError(\"validate tail inspection\", error)));\n const thread = yield* requireThread(journal, validated.threadId);\n const tailDigest = yield* Schema.decodeUnknownEffect(Digest)(thread.tail_digest).pipe(\n Effect.mapError((error) => schemaStoreError(\"decode tail digest\", error)),\n );\n return ThreadTail.make({\n threadId: validated.threadId,\n tailSequence: thread.tail_sequence,\n tailDigest,\n producerEpoch: thread.producer_epoch,\n });\n },\n );\n\n const saveCheckpoint: ThreadCheckpoints[\"save\"] = Effect.fn(\"DoThreadStore.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 thread = yield* requireThread(journal, validated.checkpoint.threadId);\n if (validated.checkpoint.throughSequence > thread.tail_sequence) {\n return yield* CheckpointRejected.make({\n threadId: validated.checkpoint.threadId,\n reason: \"ahead-of-tail\",\n });\n }\n const canonicalDigest = yield* tailDigestAt(\n journal,\n validated.checkpoint.threadId,\n validated.checkpoint.throughSequence,\n );\n if (canonicalDigest !== validated.checkpoint.tailDigest) {\n return yield* CheckpointRejected.make({\n threadId: validated.checkpoint.threadId,\n reason: \"digest-mismatch\",\n });\n }\n const checkpointJson = yield* encodeCheckpoint(validated.checkpoint);\n const raw = RawCheckpoint.make({\n threadId: validated.checkpoint.threadId,\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 isDoCheckpointConflict(error)\n ? CheckpointRejected.make({\n threadId: validated.checkpoint.threadId,\n reason: \"digest-mismatch\",\n })\n : storeError(\"save checkpoint\", error),\n ),\n );\n yield* hitFailpoint(\"save-checkpoint:after\");\n },\n );\n\n const loadCheckpoint: ThreadCheckpoints[\"load\"] = Effect.fn(\"DoThreadStore.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 thread = yield* requireThread(journal, validated.threadId);\n const rows = yield* journal\n .loadCheckpoint(validated.threadId, validated.atOrBeforeSequence ?? thread.tail_sequence)\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* ThreadStoreError.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.threadId,\n checkpoint.throughSequence,\n );\n if (canonicalDigest !== checkpoint.tailDigest) {\n return yield* CheckpointRejected.make({\n threadId: checkpoint.threadId,\n reason: \"digest-mismatch\",\n });\n }\n return Option.some(checkpoint);\n },\n );\n\n const threadStore = ThreadStore.of({\n append,\n export: exportThread,\n inspectTail,\n materialize,\n observe,\n read,\n checkpoints: { save: saveCheckpoint, load: loadCheckpoint },\n });\n\n return Context.make(ThreadStore, threadStore);\n});\n\n/**\n * Durable Object Thread Store implementation with configuration, failpoint, SQL, and\n * Crypto authority kept visible in its input channel.\n */\nexport const threadStoreLayer: Layer.Layer<\n ThreadStore,\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 ThreadStore 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 Threads 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<ThreadStore, DoStorageInitializationError> =>\n Layer.unwrap(\n Effect.map(DoStorageConfig, (config) =>\n threadStoreLayer.pipe(\n Layer.provide(\n Layer.mergeAll(\n Layer.succeed(DoStorageConfig)(config),\n storageFailpointLayer(options),\n SqliteClient.layer({ storage: options.storage }),\n BrowserCrypto.layer,\n ),\n ),\n ),\n ),\n ).pipe(Layer.provide(storageConfigLayer(options)));\n\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 settlementFailureFromRecord,\n SuspendRequest,\n SuspensionReason,\n SuspensionSnapshot,\n UnknownResolution,\n UnknownResolutionCommand,\n UnknownResolutionConflict,\n UnknownResolutionIntent,\n submissionAbortRecordId,\n type ChildSettledOutcome,\n type SuspensionOutcome,\n} from \"@effect-agent/thread\";\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 { decodeRows, initializeDoJournal } from \"./do-journal.ts\";\nimport { DoStorageConfig } from \"./do-storage-config.ts\";\nimport { DoStorageFailpoint } from \"./do-storage-failpoint.ts\";\nimport {\n storageConfigLayer,\n storageFailpointLayer,\n type DoStorageInitializationError,\n type DoStorageOptions,\n} from \"./do-thread-store.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 RESUME_IMMEDIATELY: SuspensionOutcome = \"resume-immediately\";\nconst SUSPENDED: SuspensionOutcome = \"suspended\";\nconst NOT_WAITING: ChildSettledOutcome = \"not-waiting\";\nconst STILL_WAITING: ChildSettledOutcome = \"still-waiting\";\nconst WOKEN: ChildSettledOutcome = \"woken\";\nconst MAX_IDENTIFIER_LENGTH = 1_024;\n\nclass SubmissionRow extends Schema.Class<SubmissionRow>(\"SubmissionRow\")({\n submission_id: BoundedIdentifier,\n thread_id: BoundedIdentifier,\n queue_sequence: QueueSequence,\n principal: BoundedIdentifier,\n idempotency_key: BoundedIdentifier,\n agent_id: BoundedIdentifier,\n agent_digests_json: BoundedStoredText,\n deployment_id: BoundedIdentifier,\n input_json: BoundedStoredText,\n input_digest: Digest,\n receipt_id: BoundedIdentifier,\n state: SubmissionState,\n settled_outcome: Schema.NullOr(SettlementOutcome),\n created_at: BoundedTimestamp,\n ready_at: Schema.NullOr(BoundedTimestamp),\n input_applied_record_id: Schema.NullOr(BoundedIdentifier),\n input_applied_sequence: Schema.NullOr(CanonicalSequence),\n joined_host_submission_id: Schema.NullOr(BoundedIdentifier),\n suspended_reason_json: Schema.NullOr(BoundedStoredText),\n suspended_at: Schema.NullOr(BoundedTimestamp),\n unknown_reason: Schema.NullOr(BoundedStoredText),\n unknown_tool_call_ids_json: Schema.NullOr(BoundedStoredText),\n parent_submission_id: Schema.NullOr(BoundedIdentifier),\n parent_tool_call_id: Schema.NullOr(BoundedIdentifier),\n}) {}\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 thread_id,\n queue_sequence,\n principal,\n idempotency_key,\n agent_id,\n agent_digests_json,\n deployment_id,\n input_json,\n input_digest,\n receipt_id,\n state,\n settled_outcome,\n created_at,\n ready_at,\n input_applied_record_id,\n input_applied_sequence,\n joined_host_submission_id,\n suspended_reason_json,\n suspended_at,\n unknown_reason,\n unknown_tool_call_ids_json,\n parent_submission_id,\n parent_tool_call_id\n`;\n\nconst CHILD_RESERVATION_COLUMNS = `\n reservation_id,\n parent_submission_id,\n parent_tool_call_id,\n child_submission_id,\n status,\n allocation_json,\n allocation_digest,\n accounting_json,\n reserved_at,\n release_began_at,\n released_at\n`;\n\n/** The branded ToolCallId schema, reached through the thread port so no core import is needed. */\nconst ToolCallIdSchema = ApprovalDecisionCommand.fields.toolCallId;\nconst ToolCallIdList = Schema.Array(ToolCallIdSchema);\n\nconst encodePersistedJsonText = Schema.encodeEffect(Schema.fromJsonString(PersistedJson));\nconst encodeDefinitionDigestsText = Schema.encodeEffect(Schema.fromJsonString(DefinitionDigests));\nconst encodeRecordEnvelopeText = Schema.encodeEffect(Schema.fromJsonString(RecordEnvelope));\nconst decodeRecordEnvelopeText = Schema.decodeEffect(Schema.fromJsonString(RecordEnvelope));\nconst encodeSuspensionReasonText = Schema.encodeEffect(Schema.fromJsonString(SuspensionReason));\nconst encodeUnknownResolutionText = Schema.encodeEffect(Schema.fromJsonString(UnknownResolution));\nconst encodeToolCallIdsText = Schema.encodeEffect(Schema.fromJsonString(ToolCallIdList));\nconst decodeToolCallIdsText = Schema.decodeEffect(Schema.fromJsonString(ToolCallIdList));\nconst parseStoredJsonText = Schema.decodeEffect(Schema.fromJsonString(Schema.Json));\nconst decodeAdmissionResult = Schema.decodeUnknownEffect(AdmissionResult);\nconst decodeClaim = Schema.decodeUnknownEffect(Claim);\nconst decodeOwnershipRenewal = Schema.decodeUnknownEffect(OwnershipRenewal);\nconst decodeSettlement = Schema.decodeUnknownEffect(Settlement);\nconst decodeAbortIntent = Schema.decodeUnknownEffect(AbortIntent);\nconst decodeOwnershipSnapshot = Schema.decodeUnknownEffect(OwnershipSnapshot);\nconst decodeInputAppliedMarker = Schema.decodeUnknownEffect(InputAppliedMarker);\nconst decodeSubmissionSnapshotUnknown = Schema.decodeUnknownEffect(SubmissionSnapshot);\nconst decodeSubmissionId = Schema.decodeUnknownEffect(SubmissionSnapshot.fields.submissionId);\nconst decodeQueueSequence = Schema.decodeUnknownEffect(QueueSequence);\nconst decodeUtcInstant = Schema.decodeUnknownEffect(Schema.DateTimeUtcFromString);\nconst decodeJoiningClaim = Schema.decodeUnknownEffect(JoiningClaim);\nconst decodeJoinSnapshot = Schema.decodeUnknownEffect(JoinSnapshot);\nconst decodeSuspensionSnapshot = Schema.decodeUnknownEffect(SuspensionSnapshot);\nconst decodeApprovalDecisionIntent = Schema.decodeUnknownEffect(ApprovalDecisionIntent);\nconst decodeUnknownResolutionIntent = Schema.decodeUnknownEffect(UnknownResolutionIntent);\nconst decodeParentLinkage = Schema.decodeUnknownEffect(ParentLinkage);\nconst decodeChildReservationSnapshotUnknown = Schema.decodeUnknownEffect(\n ChildBudgetReservationSnapshot,\n);\nconst decodeChildAttachmentSnapshot = Schema.decodeUnknownEffect(ChildAttachmentSnapshot);\nconst equivalentPersistedJson = Schema.toEquivalence(PersistedJson);\nconst equivalentUnknownResolution = Schema.toEquivalence(UnknownResolution);\nconst isDoStorageError = Schema.is(DoStorageError);\n\n/** Wrap an adapter-internal failure into the port's LedgerError without erasing its tag. */\nconst internalFailure =\n (operation: string) =>\n (error: { readonly message: string }): LedgerError =>\n LedgerError.make({ operation, message: error.message, cause: error });\n\n/**\n * Classify raw SQL failures. Within one Durable Object there is exactly one writer, so the\n * Node adapter's retryable `SqliteWriteContention` classification has no analogue: every raw\n * failure is a `DoLedgerError` preserved as the LedgerError's cause.\n */\nconst sqlFailure =\n (operation: string) =>\n (error: SqlError): LedgerError =>\n internalFailure(operation)(\n DoLedgerError.make({\n cause: error,\n operation,\n message: error.message,\n }),\n );\n\nconst corruptionFailure = (operation: string, table: string, rowKey: string, message: string) =>\n internalFailure(operation)(DoStorageCorruptionError.make({ table, rowKey, message }));\n\nconst makeServices = Effect.fn(\"DoSubmissionLedger.makeServices\")(function* () {\n const config = yield* DoStorageConfig;\n const failpoint = yield* DoStorageFailpoint;\n const sql = yield* SqlClientService.SqlClient;\n const crypto = yield* Crypto.Crypto;\n const 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 isDoStorageError(error) ? internalFailure(operation)(error) : error,\n ),\n );\n\n const mintUuid = (operation: string): Effect.Effect<string, LedgerError> =>\n crypto.randomUUIDv7.pipe(Effect.mapError((error) => internalFailure(operation)(error)));\n\n const currentInstant = Effect.map(Clock.currentTimeMillis, (millis) => ({\n millis,\n iso: new Date(millis).toISOString(),\n }));\n\n const timestampMillis = (operation: string, rowKey: string) => (timestamp: string) =>\n decodeUtcInstant(timestamp).pipe(\n Effect.map(DateTime.toEpochMillis),\n Effect.mapError((error) =>\n corruptionFailure(operation, \"effect_agent_submission_ownership\", rowKey, error.message),\n ),\n );\n\n const decodeSubmissionRows = (operation: string, rowKey: string, rows: unknown) =>\n decodeRows(Schema.Array(SubmissionRow), \"effect_agent_submissions\", rowKey, rows).pipe(\n Effect.mapError(internalFailure(operation)),\n );\n\n const readSubmission = Effect.fn(\"DoSubmissionLedger.readSubmission\")(function* (\n operation: string,\n submissionId: string,\n ): Effect.fn.Return<Option.Option<SubmissionRow>, LedgerError> {\n const rows = yield* sql<Record<string, unknown>>`\n SELECT ${sql.literal(SUBMISSION_COLUMNS)}\n FROM effect_agent_submissions\n WHERE submission_id = ${submissionId}\n `.pipe(Effect.mapError(sqlFailure(operation)));\n 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 threadEpoch = Effect.fn(\"DoSubmissionLedger.threadEpoch\")(function* (\n operation: string,\n threadId: string,\n ): Effect.fn.Return<ProducerEpoch, LedgerError> {\n const threads = yield* journal\n .getThread(threadId)\n .pipe(Effect.mapError(internalFailure(operation)));\n return threads.length === 0 ? EPOCH_ZERO : threads[0].producer_epoch;\n });\n\n /**\n * Verify inside the surrounding write transaction that the presented token still owns the\n * Submission's lane; a superseded or missing token fails with OwnershipLost carrying the\n * Thread's current producer epoch (DUR-006).\n */\n const requireOwnership = Effect.fn(\"DoSubmissionLedger.requireOwnership\")(function* (\n operation: string,\n submission: SubmissionRow,\n ownershipToken: string,\n ): Effect.fn.Return<OwnershipRow, OwnershipLost | LedgerError> {\n const ownership = yield* readOwnership(operation, submission.submission_id);\n if (Option.isNone(ownership) || ownership.value.ownership_token !== ownershipToken) {\n const actualEpoch = yield* threadEpoch(operation, submission.thread_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 threadId: row.thread_id,\n queueSequence: row.queue_sequence,\n principal: row.principal,\n idempotencyKey: row.idempotency_key,\n agentId: row.agent_id,\n agentDigests,\n deploymentId: row.deployment_id,\n inputPayload,\n inputDigest: row.input_digest,\n receiptId: row.receipt_id,\n state: row.state,\n createdAt: row.created_at,\n ...(row.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 threadId: 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 thread_id = ${threadId}\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 `${threadId}/${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.thread_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}:{threadId}`. The cross-DO\n // routing layer parses ITS OWN minted format (split at the first \":\") to address\n // submissionId-only operations to the owning Thread Object; the id stays opaque\n // to every other component, exactly like DN's `submission-{uuid}` prefix.\n const mintedSubmissionId = `${yield* mintUuid(operation)}:${validated.threadId}`;\n if (mintedSubmissionId.length > MAX_IDENTIFIER_LENGTH) {\n return yield* LedgerError.make({\n operation,\n message:\n `A routable Submission identity of ${mintedSubmissionId.length} characters exceeds ` +\n `the ${MAX_IDENTIFIER_LENGTH}-character ledger row bound; shorten the Thread identity.`,\n });\n }\n const mintedReceiptId = `receipt-${yield* mintUuid(operation)}`;\n yield* hitFailpoint(\"ledger:admit:before\", operation);\n const result = yield* inWriteTransaction(\n operation,\n Effect.gen(function* () {\n const keyRowKey = `${validated.threadId}/${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 thread_id = ${validated.threadId}\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 threadId: validated.threadId,\n principal: validated.principal,\n idempotencyKey: validated.idempotencyKey,\n existingInputDigest: existing[0].input_digest,\n attemptedInputDigest: validated.inputDigest,\n });\n }\n return yield* decodeAdmissionResult({\n submissionId: existing[0].submission_id,\n receiptId: existing[0].receipt_id,\n queueSequence: existing[0].queue_sequence,\n state: existing[0].state,\n replayed: true,\n }).pipe(Effect.mapError(internalFailure(operation)));\n }\n\n const maxRows = yield* sql<Record<string, unknown>>`\n SELECT COALESCE(MAX(queue_sequence), 0) AS max_queue_sequence\n FROM effect_agent_submissions\n WHERE thread_id = ${validated.threadId}\n `.pipe(Effect.mapError(sqlFailure(operation)));\n const decodedMax = yield* decodeRows(\n Schema.Array(MaxQueueSequenceRow),\n \"effect_agent_submissions\",\n validated.threadId,\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 thread_id,\n queue_sequence,\n principal,\n idempotency_key,\n agent_id,\n agent_digests_json,\n deployment_id,\n input_json,\n input_digest,\n receipt_id,\n state,\n created_at,\n parent_submission_id,\n parent_tool_call_id\n ) VALUES (\n ${mintedSubmissionId},\n ${validated.threadId},\n ${queueSequence},\n ${validated.principal},\n ${validated.idempotencyKey},\n ${validated.agentId},\n ${agentDigestsJson},\n ${validated.deploymentId},\n ${inputJson},\n ${validated.inputDigest},\n ${mintedReceiptId},\n 'admitted',\n ${now.iso},\n ${validated.parentLinkage?.parentSubmissionId ?? null},\n ${validated.parentLinkage?.parentToolCallId ?? null}\n )\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 thread_id = ${validated.threadId}\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.threadId}/${validated.principal}/${validated.idempotencyKey}`,\n rows,\n );\n if (decoded.length > 1) {\n return yield* corruptionFailure(\n operation,\n \"effect_agent_submissions\",\n `${validated.threadId}/${validated.principal}/${validated.idempotencyKey}`,\n \"An admission idempotency key returned more than one row.\",\n );\n }\n if (decoded.length === 0) return Option.none();\n return Option.some(yield* decodeSubmissionSnapshot(operation, decoded[0]));\n },\n );\n\n // This LOCAL facet is the authoritative owner of every Thread stored in this Durable\n // Object, so the key-scoped read IS the admission truth and the tri-state degenerates to\n // NotAdmitted or Admitted (SUB-031). `AdmissionIndeterminate` becomes real one layer out:\n // the WP2 routed decorator answers it when the OWNING Durable Object is unreachable.\n const resolveAdmission: SubmissionLedger[\"Service\"][\"resolveAdmission\"] = Effect.fn(\n \"DoSubmissionLedger.resolveAdmission\",\n )(function* (request: SubmissionLookupByKey) {\n const operation = \"ledger resolve admission\";\n 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 thread_id = ${validated.threadId}\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.threadId}/${validated.principal}/${validated.idempotencyKey}`,\n rows,\n );\n if (decoded.length > 1) {\n return yield* corruptionFailure(\n operation,\n \"effect_agent_submissions\",\n `${validated.threadId}/${validated.principal}/${validated.idempotencyKey}`,\n \"An admission idempotency key returned more than one row.\",\n );\n }\n if (decoded.length === 0) return AdmissionNotAdmitted.make();\n 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 thread_id = ${validated.threadId}\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.threadId, headRows);\n if (heads.length === 0) return Option.none<Claim>();\n const head = heads[0];\n\n // Unknown work is claimable only for a durably requested abort: the coordinator\n // cleans up children and settles without replaying ordinary Tools. Read the intent\n // in this claim transaction; retain uncertainty evidence and all ownership fencing.\n if (\n head.state === \"joining\" ||\n head.state === \"joined\" ||\n head.state === \"suspended\" ||\n (head.state === \"unknown\" &&\n Option.isNone(yield* readAbortIntent(operation, head.submission_id)))\n ) {\n return Option.none<Claim>();\n }\n\n const now = yield* currentInstant;\n const ownership = yield* readOwnership(operation, head.submission_id);\n 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 Thread's producer epoch atomically with the claim so every stale\n // Attempt is fenced out of canonical appends (DUR-006). A Thread that was\n // never materialized (eviction between admission and materialization) is created\n // here so recovery can claim first and re-materialize idempotently at this epoch.\n const threads = yield* journal\n .getThread(head.thread_id)\n .pipe(Effect.mapError(internalFailure(operation)));\n let producerEpoch: number;\n if (threads.length === 0) {\n producerEpoch = 1;\n yield* sql`\n INSERT INTO effect_agent_threads (\n thread_id,\n created_at,\n tail_sequence,\n tail_digest,\n producer_epoch\n ) VALUES (\n ${head.thread_id},\n ${now.iso},\n 0,\n ${EMPTY_TAIL_DIGEST},\n ${producerEpoch}\n )\n `.pipe(Effect.mapError(sqlFailure(operation)));\n } else {\n producerEpoch = threads[0].producer_epoch + 1;\n yield* sql`\n UPDATE effect_agent_threads\n SET producer_epoch = ${producerEpoch}\n WHERE thread_id = ${head.thread_id}\n `.pipe(Effect.mapError(sqlFailure(operation)));\n }\n\n const leaseExpiresAt = new Date(now.millis + config.ownershipLeaseDuration).toISOString();\n yield* sql`\n INSERT INTO effect_agent_submission_ownership (\n submission_id,\n attempt_id,\n ownership_token,\n producer_epoch,\n owner_producer_id,\n lease_expires_at\n ) VALUES (\n ${head.submission_id},\n ${attemptId},\n ${ownershipToken},\n ${producerEpoch},\n ${validated.producerId},\n ${leaseExpiresAt}\n )\n ON CONFLICT (submission_id) DO UPDATE SET\n attempt_id = excluded.attempt_id,\n ownership_token = excluded.ownership_token,\n producer_epoch = excluded.producer_epoch,\n owner_producer_id = excluded.owner_producer_id,\n lease_expires_at = excluded.lease_expires_at\n `.pipe(Effect.mapError(sqlFailure(operation)));\n\n yield* sql`\n INSERT INTO effect_agent_attempts (\n attempt_id,\n submission_id,\n thread_id,\n owner_producer_id,\n producer_epoch,\n claimed_at\n ) VALUES (\n ${attemptId},\n ${head.submission_id},\n ${head.thread_id},\n ${validated.producerId},\n ${producerEpoch},\n ${now.iso}\n )\n `.pipe(Effect.mapError(sqlFailure(operation)));\n\n if (head.state === \"ready\") {\n yield* sql`\n UPDATE effect_agent_submissions\n SET state = 'running'\n WHERE submission_id = ${head.submission_id}\n `.pipe(Effect.mapError(sqlFailure(operation)));\n }\n\n const inputPayload = yield* parseStoredJsonText(head.input_json).pipe(\n Effect.mapError((error) =>\n corruptionFailure(\n operation,\n \"effect_agent_submissions\",\n head.submission_id,\n error.message,\n ),\n ),\n );\n 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 reservationRecord = yield* decodeRecordEnvelopeText(\n reservation.value.record_json,\n ).pipe(\n Effect.mapError((error) =>\n corruptionFailure(\n operation,\n \"effect_agent_settlement_reservations\",\n validated.submissionId,\n error.message,\n ),\n ),\n );\n const settlementFailure = settlementFailureFromRecord(reservationRecord);\n if ((reservation.value.outcome === \"failed\") !== (settlementFailure !== undefined)) {\n return yield* corruptionFailure(\n operation,\n \"effect_agent_settlement_reservations\",\n validated.submissionId,\n \"The reserved outcome and canonical failure diagnostic disagree.\",\n );\n }\n const submission = yield* requireSubmission(operation, validated.submissionId);\n 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 ...(settlementFailure === undefined ? {} : { failure: settlementFailure }),\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 ...(settlementFailure === undefined ? {} : { failure: settlementFailure }),\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.thread_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.thread_id !== validated.threadId) {\n return yield* LedgerError.make({\n operation,\n message: `Host submission ${validated.hostSubmissionId} does not belong to thread ${validated.threadId}.`,\n });\n }\n // The host Attempt already owns the lane; no epoch bump happens here (plan §2.5).\n yield* requireOwnership(operation, host, validated.ownershipToken);\n const laterRows = yield* sql<Record<string, unknown>>`\n SELECT ${sql.literal(SUBMISSION_COLUMNS)}\n FROM effect_agent_submissions\n WHERE thread_id = ${validated.threadId}\n AND queue_sequence > ${host.queue_sequence}\n ORDER BY queue_sequence ASC\n `.pipe(Effect.mapError(sqlFailure(operation)));\n const later = yield* decodeSubmissionRows(operation, validated.threadId, 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;\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 Threads live in different Durable\n // Objects, and the port contract requires that a child settlement reported (via\n // `recordChildSettled` → marker) before this suspend commits is observed here.\n if (validated.reason._tag === \"ApprovalPending\") {\n const decisions = yield* readApprovalDecisions(operation, validated.submissionId);\n const decided = new Set(decisions.map((row) => row.tool_call_id));\n if (validated.reason.toolCallIds.every((toolCallId) => decided.has(toolCallId))) {\n return RESUME_IMMEDIATELY;\n }\n } else {\n const markers = yield* readChildSettlementMarkers(operation, validated.submissionId);\n const markerChildren = new Set(markers.map((row) => row.child_submission_id));\n let allSettled = true;\n 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;\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;\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 const existingIntent =\n existing === undefined\n ? undefined\n : yield* unknownResolutionIntentFromRow(operation, existing);\n if (\n existingIntent !== undefined &&\n !equivalentUnknownResolution(existingIntent.resolution, validated.resolution)\n ) {\n return yield* UnknownResolutionConflict.make({\n submissionId: validated.submissionId,\n toolCallId: validated.toolCallId,\n });\n }\n let resolved: UnknownResolutionIntent;\n if (existingIntent !== undefined) {\n // Idempotent replay of the recorded intent (author/reason may differ; the stored\n // audit fields win, exactly like requestAbort).\n resolved = existingIntent;\n } else {\n const now = yield* currentInstant;\n 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), either a\n // finalized row or an exact terminalizing reservation admits the notification: the\n // runtime calls only after the canonical append and before ledger finalization. When the\n // row does not live here — the normal cross-DO case — the routed notification from the\n // child's owning Durable Object is the settlement evidence this store records durably.\n const child = yield* readSubmission(operation, validated.childSubmissionId);\n const childReservation = yield* readReservation(operation, validated.childSubmissionId);\n if (\n Option.isSome(child) &&\n child.value.state !== \"settled\" &&\n !(child.value.state === \"terminalizing\" && Option.isSome(childReservation))\n ) {\n return yield* LedgerError.make({\n operation,\n message: `Child submission ${validated.childSubmissionId} has no recorded settlement.`,\n });\n }\n // Record the durable notification marker FIRST and unconditionally (idempotent):\n // the port's cross-store race guarantee requires that a notification committed\n // before the parent's suspend transaction is observed by that suspend's covering\n // check, even when the parent is not (or not yet) suspended.\n const now = yield* currentInstant;\n yield* sql`\n INSERT INTO effect_agent_child_settlements (\n parent_submission_id,\n child_submission_id,\n child_outcome,\n recorded_at\n ) VALUES (\n ${validated.parentSubmissionId},\n ${validated.childSubmissionId},\n ${\n Option.isSome(child) && child.value.state === \"settled\"\n ? child.value.settled_outcome\n : Option.isSome(childReservation)\n ? childReservation.value.outcome\n : null\n },\n ${now.iso}\n )\n ON CONFLICT (parent_submission_id, child_submission_id) DO NOTHING\n `.pipe(Effect.mapError(sqlFailure(operation)));\n\n if (parent.state !== \"suspended\" || parent.suspended_reason_json === null) {\n return NOT_WAITING;\n }\n 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;\n }\n if (\n !reason.children.some((entry) => entry.childSubmissionId === validated.childSubmissionId)\n ) {\n return NOT_WAITING;\n }\n // The parent wakes exactly when EVERY listed child is provably settled — from its\n // local row or a recorded marker (spec §12 step 10); replays re-run the coverage\n // check so a recovering caller wakes the lane idempotently.\n const markers = yield* readChildSettlementMarkers(operation, validated.parentSubmissionId);\n const markerChildren = new Set(markers.map((row) => row.child_submission_id));\n 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;\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;\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 const existingSnapshot = yield* childReservationSnapshotFromRow(\n operation,\n existing.value,\n );\n // Identical replays short-circuit before the fence, mirroring reserveSettlement: a\n // replay creates nothing, so a recovering caller resumes rather than duplicates.\n const identical =\n existing.value.parent_submission_id === validated.parentSubmissionId &&\n existing.value.parent_tool_call_id === validated.parentToolCallId &&\n existing.value.allocation_digest === validated.allocationDigest &&\n equivalentPersistedJson(existingSnapshot.allocation, validated.allocation);\n 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: existingSnapshot,\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 const existingSnapshot = yield* childReservationSnapshotFromRow(\n operation,\n existing.value,\n );\n // The accounting decision was already frozen exactly once; an identical replay is a\n // no-op and a divergent decision conflicts (spec §12 join step 6).\n if (\n existingSnapshot.accounting !== undefined &&\n equivalentPersistedJson(existingSnapshot.accounting, validated.accounting)\n ) {\n return existingSnapshot;\n }\n 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 threadId: string;\n readonly queueSequence: number;\n }\n\n const scanPage = Effect.fn(\"DoSubmissionLedger.scanPage\")(function* (\n cursor: ScanCursor | undefined,\n ): Effect.fn.Return<\n readonly [ReadonlyArray<SubmissionSnapshot>, Option.Option<ScanCursor | undefined>],\n LedgerError\n > {\n const operation = \"ledger scan nonterminal\";\n const rows = yield* (\n cursor === undefined\n ? sql<Record<string, unknown>>`\n SELECT ${sql.literal(SUBMISSION_COLUMNS)}\n FROM effect_agent_submissions\n WHERE state <> 'settled'\n ORDER BY thread_id ASC, queue_sequence ASC\n LIMIT ${SCAN_PAGE_SIZE}\n `\n : sql<Record<string, unknown>>`\n SELECT ${sql.literal(SUBMISSION_COLUMNS)}\n FROM effect_agent_submissions\n WHERE state <> 'settled'\n AND (\n thread_id > ${cursor.threadId}\n OR (\n thread_id = ${cursor.threadId}\n AND queue_sequence > ${cursor.queueSequence}\n )\n )\n ORDER BY thread_id ASC, queue_sequence ASC\n LIMIT ${SCAN_PAGE_SIZE}\n `\n ).pipe(Effect.mapError(sqlFailure(operation)));\n 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 threadId: last.thread_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 ScanCursor | undefined,\n SubmissionSnapshot,\n LedgerError\n >(undefined, scanPage);\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 ThreadStore so claims fence the same producer epochs.\n */\nexport const ledgerLayer = (\n options: DoStorageOptions,\n): Layer.Layer<SubmissionLedger, DoStorageInitializationError> =>\n Layer.unwrap(\n Effect.map(DoStorageConfig, (config) =>\n submissionLedgerLayer.pipe(\n Layer.provide(\n Layer.mergeAll(\n Layer.succeed(DoStorageConfig)(config),\n storageFailpointLayer(options),\n SqliteClient.layer({ storage: options.storage }),\n BrowserCrypto.layer,\n ),\n ),\n ),\n ),\n ).pipe(Layer.provide(storageConfigLayer(options)));\n","import {\n applyScheduleChange,\n ScheduleCapacityError,\n ScheduleDueCursor,\n defaultSchedulingLimits,\n scheduleUsesCapacity,\n ScheduleChange,\n ScheduleConflict,\n scheduleDeadline,\n ScheduleFailpoint,\n type ScheduleFailpointError,\n ScheduleKey,\n ScheduleId,\n ScheduleInstant,\n ScheduleNotFound,\n ScheduleOwner,\n type SchedulePage,\n SchedulePageRequest,\n ScheduleRecord,\n ScheduleStorageError,\n ScheduleStore,\n} from \"@effect-agent/thread\";\nimport { Context, Effect, Layer, Result, Schema } from \"effect\";\nimport * as SqlClientService from \"effect/unstable/sql/SqlClient\";\n\nconst CURRENT_SCHEDULE_STORE_VERSION = 2;\nconst MAX_STORED_SCHEDULE_BYTES = 1_900_000;\n\nconst StoredScheduleJson = Schema.String.check(Schema.isMaxLength(MAX_STORED_SCHEDULE_BYTES));\nconst StoredDeadline = Schema.NullOr(ScheduleInstant);\n\nclass ScheduleRow extends Schema.Class<ScheduleRow>(\"@effect-agent/storage-cloudflare/ScheduleRow\")(\n {\n tenant_id: ScheduleOwner.fields.tenantId,\n owner_id: ScheduleOwner.fields.ownerId,\n schedule_id: ScheduleId,\n deadline_at_millis: StoredDeadline,\n record_json: StoredScheduleJson,\n },\n) {}\n\nconst ScheduleDueRow = Schema.Struct({\n tenant_id: ScheduleOwner.fields.tenantId,\n owner_id: ScheduleOwner.fields.ownerId,\n schedule_id: ScheduleId,\n deadline_at_millis: ScheduleInstant,\n});\n\nclass ScheduleCountRow extends Schema.Class<ScheduleCountRow>(\n \"@effect-agent/storage-cloudflare/ScheduleCountRow\",\n)({\n schedule_count: Schema.Int.check(Schema.isGreaterThanOrEqualTo(0)),\n}) {}\n\nclass ScheduleDeadlineRow extends Schema.Class<ScheduleDeadlineRow>(\n \"@effect-agent/storage-cloudflare/ScheduleDeadlineRow\",\n)({\n deadline_at_millis: StoredDeadline,\n}) {}\n\nclass ScheduleStoreStateRow extends Schema.Class<ScheduleStoreStateRow>(\n \"@effect-agent/storage-cloudflare/ScheduleStoreStateRow\",\n)({\n storage_version: Schema.Int.check(Schema.isGreaterThan(0)),\n alarm_generation: Schema.Int.check(Schema.isGreaterThanOrEqualTo(0)),\n}) {}\n\nclass ScheduleTableNameRow extends Schema.Class<ScheduleTableNameRow>(\n \"@effect-agent/storage-cloudflare/ScheduleTableNameRow\",\n)({\n name: Schema.String,\n}) {}\n\nexport interface DoScheduleAlarmReplacement {\n readonly deadlineAtMillis: number | null;\n /** Included in every logical alarm payload so equal-time replacement stays distinguishable. */\n readonly generation: number;\n}\n\nexport type DoScheduleReplaceAlarm = (\n replacement: DoScheduleAlarmReplacement,\n) => Effect.Effect<void, ScheduleStorageError>;\n\n/**\n * Platform-owned transaction boundary for schedule SQL and logical alarm mutation. The callback\n * and its `replaceAlarm` capability belong to one fiber and must not escape or fork.\n */\nexport class DoScheduleTransaction extends Context.Service<\n DoScheduleTransaction,\n {\n readonly run: <A, E, R>(\n body: (replaceAlarm: DoScheduleReplaceAlarm) => Effect.Effect<A, E, R>,\n ) => Effect.Effect<A, E | ScheduleStorageError, R>;\n }\n>()(\"@effect-agent/storage-cloudflare/DoScheduleTransaction\") {}\n\n/** Platform driver operations that use the same schedule-state and alarm transaction. */\nexport class DoScheduleAlarmControl extends Context.Service<\n DoScheduleAlarmControl,\n {\n /** Establish a future recovery wake before cross-Object admission starts. */\n readonly prearm: (\n deadlineAtMillis: number,\n ) => Effect.Effect<void, ScheduleStorageError | ScheduleFailpointError>;\n /** Replace or cancel the wake from the object's authoritative indexed deadline. */\n readonly reconcile: Effect.Effect<void, ScheduleStorageError | ScheduleFailpointError>;\n }\n>()(\"@effect-agent/storage-cloudflare/DoScheduleAlarmControl\") {}\n\nconst unavailable = (operation: string): ScheduleStorageError =>\n ScheduleStorageError.make({ operation, reason: \"unavailable\" });\n\nconst corrupt = (operation: string): ScheduleStorageError =>\n ScheduleStorageError.make({ operation, reason: \"corrupt\" });\n\nconst decodeRows = Effect.fn(\"DoScheduleStore.decodeRows\")(function* <A, I, R>(\n schema: Schema.Codec<A, I, R>,\n rows: ReadonlyArray<unknown>,\n operation: string,\n): Effect.fn.Return<A, ScheduleStorageError, R> {\n return yield* Schema.decodeUnknownEffect(schema)(rows).pipe(\n Effect.mapError(() => corrupt(operation)),\n );\n});\n\nconst decodeBoundary = <A, I, R>(\n schema: Schema.Codec<A, I, R>,\n value: unknown,\n operation: string,\n): Effect.Effect<A, ScheduleStorageError, R> =>\n Schema.decodeUnknownEffect(schema)(value).pipe(Effect.mapError(() => corrupt(operation)));\n\nconst decodeRecord = Effect.fn(\"DoScheduleStore.decodeRecord\")(function* (\n row: ScheduleRow,\n): Effect.fn.Return<ScheduleRecord, ScheduleStorageError> {\n const record = yield* Schema.decodeEffect(Schema.fromJsonString(ScheduleRecord))(\n row.record_json,\n ).pipe(Effect.mapError(() => corrupt(\"decode schedule\")));\n if (\n record.owner.tenantId !== row.tenant_id ||\n record.owner.ownerId !== row.owner_id ||\n record.scheduleId !== row.schedule_id ||\n scheduleDeadline(record) !== row.deadline_at_millis\n ) {\n return yield* corrupt(\"decode schedule index\");\n }\n return record;\n});\n\nconst encodeRecord = Effect.fn(\"DoScheduleStore.encodeRecord\")(function* (\n record: ScheduleRecord,\n): Effect.fn.Return<string, ScheduleStorageError> {\n const encoded = yield* Schema.encodeEffect(Schema.fromJsonString(ScheduleRecord))(record).pipe(\n Effect.mapError(() => corrupt(\"encode schedule\")),\n );\n return yield* Schema.decodeUnknownEffect(StoredScheduleJson)(encoded).pipe(\n Effect.mapError(() => corrupt(\"encode schedule bounds\")),\n );\n});\n\nconst initializeScheduleStore = Effect.fn(\"DoScheduleStore.initialize\")(function* () {\n const sql = yield* SqlClientService.SqlClient;\n const operation = \"initialize schedule store\";\n const rawTables = yield* sql<Record<string, unknown>>`\n SELECT name\n FROM sqlite_master\n WHERE type = 'table'\n AND name IN (\n 'effect_agent_schedule_store_state',\n 'effect_agent_schedules'\n )\n ORDER BY name\n `.pipe(Effect.mapError(() => unavailable(operation)));\n const tables = yield* decodeRows(Schema.Array(ScheduleTableNameRow), rawTables, operation);\n const hasState = tables.some((row) => row.name === \"effect_agent_schedule_store_state\");\n const hasSchedules = tables.some((row) => row.name === \"effect_agent_schedules\");\n\n if (!hasState) {\n if (hasSchedules) return yield* corrupt(operation);\n yield* sql\n .withTransaction(\n Effect.gen(function* () {\n yield* sql`\n CREATE TABLE effect_agent_schedule_store_state (\n singleton INTEGER PRIMARY KEY NOT NULL CHECK (singleton = 1),\n storage_version INTEGER NOT NULL,\n alarm_generation INTEGER NOT NULL\n )\n `.withoutTransform;\n yield* sql`\n CREATE TABLE effect_agent_schedules (\n tenant_id TEXT NOT NULL,\n owner_id TEXT NOT NULL,\n schedule_id TEXT NOT NULL,\n deadline_at_millis INTEGER,\n record_json TEXT NOT NULL,\n PRIMARY KEY (tenant_id, owner_id, schedule_id)\n )\n `.withoutTransform;\n yield* sql`\n CREATE INDEX effect_agent_schedules_deadline\n ON effect_agent_schedules (deadline_at_millis, tenant_id, owner_id, schedule_id)\n WHERE deadline_at_millis IS NOT NULL\n `.withoutTransform;\n yield* sql`\n CREATE INDEX effect_agent_schedules_owner_deadline\n ON effect_agent_schedules (tenant_id, owner_id, deadline_at_millis, schedule_id)\n WHERE deadline_at_millis IS NOT NULL\n `.withoutTransform;\n yield* sql`\n INSERT INTO effect_agent_schedule_store_state (\n singleton, storage_version, alarm_generation\n ) VALUES (1, ${CURRENT_SCHEDULE_STORE_VERSION}, 0)\n `.withoutTransform;\n }),\n )\n .pipe(Effect.mapError(() => unavailable(operation)));\n return;\n }\n\n if (!hasSchedules) return yield* corrupt(operation);\n const rawState = yield* sql<Record<string, unknown>>`\n SELECT storage_version, alarm_generation\n FROM effect_agent_schedule_store_state\n WHERE singleton = 1\n `.pipe(Effect.mapError(() => unavailable(operation)));\n const state = yield* decodeRows(Schema.Array(ScheduleStoreStateRow), rawState, operation);\n if (state.length !== 1 || state[0].storage_version !== CURRENT_SCHEDULE_STORE_VERSION) {\n return yield* corrupt(\n state.length === 1\n ? `${operation}: incompatible storage version ${state[0].storage_version}; expected ${CURRENT_SCHEDULE_STORE_VERSION}`\n : `${operation}: invalid storage version row`,\n );\n }\n});\n\nconst makeServices = Effect.gen(function* () {\n const sql = yield* SqlClientService.SqlClient;\n const transactions = yield* DoScheduleTransaction;\n const scheduleFailpoint = yield* ScheduleFailpoint;\n\n yield* initializeScheduleStore();\n\n const readRows = Effect.fn(\"DoScheduleStore.readRows\")(function* (\n key: ScheduleKey,\n operation: string,\n ): Effect.fn.Return<ReadonlyArray<ScheduleRow>, ScheduleStorageError> {\n const rows = yield* sql<Record<string, unknown>>`\n SELECT tenant_id, owner_id, schedule_id, deadline_at_millis, record_json\n FROM effect_agent_schedules\n WHERE tenant_id = ${key.owner.tenantId}\n AND owner_id = ${key.owner.ownerId}\n AND schedule_id = ${key.scheduleId}\n `.pipe(Effect.mapError(() => unavailable(operation)));\n return yield* decodeRows(Schema.Array(ScheduleRow), rows, operation);\n });\n\n const readOne = Effect.fn(\"DoScheduleStore.readOne\")(function* (\n key: ScheduleKey,\n operation: string,\n ): Effect.fn.Return<ScheduleRecord | null, ScheduleStorageError> {\n const rows = yield* readRows(key, operation);\n if (rows.length === 0) return null;\n if (rows.length !== 1) return yield* corrupt(operation);\n return yield* decodeRecord(rows[0]);\n });\n\n const readNextDeadline = Effect.fn(\"DoScheduleStore.readNextDeadline\")(function* (\n owner: ScheduleOwner | undefined,\n operation: string,\n ): Effect.fn.Return<number | null, ScheduleStorageError> {\n const rows =\n owner === undefined\n ? yield* sql<Record<string, unknown>>`\n SELECT MIN(deadline_at_millis) AS deadline_at_millis\n FROM effect_agent_schedules\n WHERE deadline_at_millis IS NOT NULL\n `.pipe(Effect.mapError(() => unavailable(operation)))\n : yield* sql<Record<string, unknown>>`\n SELECT MIN(deadline_at_millis) AS deadline_at_millis\n FROM effect_agent_schedules\n WHERE tenant_id = ${owner.tenantId}\n AND owner_id = ${owner.ownerId}\n AND deadline_at_millis IS NOT NULL\n `.pipe(Effect.mapError(() => unavailable(operation)));\n const decoded = yield* decodeRows(Schema.Array(ScheduleDeadlineRow), rows, operation);\n if (decoded.length !== 1) return yield* corrupt(operation);\n return decoded[0].deadline_at_millis;\n });\n\n const replaceAlarm = Effect.fn(\"DoScheduleStore.replaceAlarm\")(function* (\n replace: DoScheduleReplaceAlarm,\n deadlineAtMillis: number | null,\n operation: string,\n ) {\n const rawState = yield* sql<Record<string, unknown>>`\n UPDATE effect_agent_schedule_store_state\n SET alarm_generation = alarm_generation + 1\n WHERE singleton = 1\n RETURNING storage_version, alarm_generation\n `.pipe(Effect.mapError(() => unavailable(operation)));\n const state = yield* decodeRows(Schema.Array(ScheduleStoreStateRow), rawState, operation);\n if (state.length !== 1 || state[0].storage_version !== CURRENT_SCHEDULE_STORE_VERSION) {\n return yield* corrupt(operation);\n }\n yield* scheduleFailpoint.hit(\"schedule:alarm:before\");\n yield* replace({ deadlineAtMillis, generation: state[0].alarm_generation });\n yield* scheduleFailpoint.hit(\"schedule:alarm:after\");\n });\n\n const insert: ScheduleStore[\"Service\"][\"insert\"] = Effect.fn(\"DoScheduleStore.insert\")(\n function* (record, ownerLimit) {\n const operation = \"insert schedule\";\n const canonical = yield* decodeBoundary(ScheduleRecord, record, operation);\n const recordJson = yield* encodeRecord(canonical);\n const result = yield* transactions.run((replace) =>\n Effect.gen(function* () {\n const existing = yield* readOne(canonical, operation);\n if (existing !== null) {\n if (existing.creationFingerprint === canonical.creationFingerprint) {\n return { record: existing, inserted: false } as const;\n }\n return yield* ScheduleConflict.make({ reason: \"creation\", key: canonical });\n }\n const rawCounts = yield* sql<Record<string, unknown>>`\n SELECT COUNT(*) AS schedule_count\n FROM effect_agent_schedules\n WHERE tenant_id = ${canonical.owner.tenantId}\n AND owner_id = ${canonical.owner.ownerId}\n AND (json_extract(record_json, '$.pending') IS NOT NULL OR\n (json_extract(record_json, '$.state') != 'cancelled' AND json_extract(record_json, '$.nextAtMillis') IS NOT NULL))\n `.pipe(Effect.mapError(() => unavailable(operation)));\n const counts = yield* decodeRows(Schema.Array(ScheduleCountRow), rawCounts, operation);\n if (counts.length !== 1) return yield* corrupt(operation);\n if (counts[0].schedule_count >= ownerLimit) {\n return yield* ScheduleCapacityError.make({ limit: ownerLimit });\n }\n yield* scheduleFailpoint.hit(\"schedule:insert:before\");\n yield* sql`\n INSERT INTO effect_agent_schedules (\n tenant_id, owner_id, schedule_id, deadline_at_millis, record_json\n ) VALUES (\n ${canonical.owner.tenantId},\n ${canonical.owner.ownerId},\n ${canonical.scheduleId},\n ${scheduleDeadline(canonical)},\n ${recordJson}\n )\n `.pipe(Effect.mapError(() => unavailable(operation)));\n const deadline = yield* readNextDeadline(undefined, operation);\n yield* replaceAlarm(replace, deadline, operation);\n return { record: canonical, inserted: true } as const;\n }),\n );\n if (result.inserted) yield* scheduleFailpoint.hit(\"schedule:insert:after\");\n return result.record;\n },\n );\n\n const get: ScheduleStore[\"Service\"][\"get\"] = Effect.fn(\"DoScheduleStore.get\")(function* (key) {\n const canonical = yield* decodeBoundary(ScheduleKey, key, \"get schedule\");\n return yield* readOne(canonical, \"get schedule\");\n });\n\n const list: ScheduleStore[\"Service\"][\"list\"] = Effect.fn(\"DoScheduleStore.list\")(function* (\n requestValue: SchedulePageRequest,\n ): Effect.fn.Return<SchedulePage, ScheduleStorageError> {\n const operation = \"list schedules\";\n const request = yield* decodeBoundary(SchedulePageRequest, requestValue, operation);\n const rows =\n request.after === undefined\n ? yield* sql<Record<string, unknown>>`\n SELECT tenant_id, owner_id, schedule_id, deadline_at_millis, record_json\n FROM effect_agent_schedules\n WHERE tenant_id = ${request.owner.tenantId}\n AND owner_id = ${request.owner.ownerId}\n ORDER BY schedule_id\n LIMIT ${request.limit + 1}\n `.pipe(Effect.mapError(() => unavailable(operation)))\n : yield* sql<Record<string, unknown>>`\n SELECT tenant_id, owner_id, schedule_id, deadline_at_millis, record_json\n FROM effect_agent_schedules\n WHERE tenant_id = ${request.owner.tenantId}\n AND owner_id = ${request.owner.ownerId}\n AND schedule_id > ${request.after}\n ORDER BY schedule_id\n LIMIT ${request.limit + 1}\n `.pipe(Effect.mapError(() => unavailable(operation)));\n const decoded = yield* decodeRows(Schema.Array(ScheduleRow), rows, operation);\n const records = yield* Effect.forEach(decoded, decodeRecord);\n const hasNext = records.length > request.limit;\n const items = hasNext ? records.slice(0, request.limit) : records;\n return { items, next: hasNext ? (items.at(-1)?.scheduleId ?? null) : null };\n });\n\n const change: ScheduleStore[\"Service\"][\"change\"] = Effect.fn(\"DoScheduleStore.change\")(function* (\n key,\n change,\n ownerLimit = defaultSchedulingLimits.maxSchedulesPerOwner,\n ) {\n const operation = \"change schedule\";\n const canonicalKey = yield* decodeBoundary(ScheduleKey, key, operation);\n const canonicalChange = yield* decodeBoundary(ScheduleChange, change, operation);\n const result = yield* transactions.run((replace) =>\n Effect.gen(function* () {\n const current = yield* readOne(canonicalKey, operation);\n if (current === null) return yield* ScheduleNotFound.make({ key: canonicalKey });\n const transition = applyScheduleChange(current, canonicalChange);\n if (Result.isFailure(transition)) return yield* transition.failure;\n const next = transition.success;\n if (!scheduleUsesCapacity(current) && scheduleUsesCapacity(next)) {\n const rawCounts = yield* sql<Record<string, unknown>>`\n SELECT COUNT(*) AS schedule_count FROM effect_agent_schedules\n WHERE tenant_id = ${key.owner.tenantId} AND owner_id = ${key.owner.ownerId}\n AND (json_extract(record_json, '$.pending') IS NOT NULL OR\n (json_extract(record_json, '$.state') != 'cancelled' AND json_extract(record_json, '$.nextAtMillis') IS NOT NULL))\n `.pipe(Effect.mapError(() => unavailable(operation)));\n const counts = yield* decodeRows(Schema.Array(ScheduleCountRow), rawCounts, operation);\n if (counts.length !== 1) return yield* corrupt(operation);\n if (counts[0].schedule_count >= ownerLimit)\n return yield* ScheduleCapacityError.make({ limit: ownerLimit });\n }\n if (next === current) return { record: current, changed: false } as const;\n const recordJson = yield* encodeRecord(next);\n yield* scheduleFailpoint.hit(`schedule:${canonicalChange._tag.toLowerCase()}:before`);\n yield* sql`\n UPDATE effect_agent_schedules\n SET deadline_at_millis = ${scheduleDeadline(next)}, record_json = ${recordJson}\n WHERE tenant_id = ${canonicalKey.owner.tenantId}\n AND owner_id = ${canonicalKey.owner.ownerId}\n AND schedule_id = ${canonicalKey.scheduleId}\n `.pipe(Effect.mapError(() => unavailable(operation)));\n const deadline = yield* readNextDeadline(undefined, operation);\n yield* replaceAlarm(replace, deadline, operation);\n return { record: next, changed: true } as const;\n }),\n );\n if (result.changed) {\n yield* scheduleFailpoint.hit(`schedule:${canonicalChange._tag.toLowerCase()}:after`);\n }\n return result.record;\n });\n\n const due: ScheduleStore[\"Service\"][\"due\"] = Effect.fn(\"DoScheduleStore.due\")(function* (\n nowMillis,\n limit,\n owner?: ScheduleOwner,\n after?: ScheduleDueCursor,\n ) {\n const operation = \"query due schedules\";\n const cursor =\n after === undefined\n ? undefined\n : yield* Schema.decodeUnknownEffect(ScheduleDueCursor)(after).pipe(\n Effect.mapError(() => corrupt(operation)),\n );\n const continuation =\n cursor === undefined\n ? sql`1 = 1`\n : sql`\n (deadline_at_millis, tenant_id, owner_id, schedule_id) >\n (${cursor.deadlineAtMillis}, ${cursor.owner.tenantId}, ${cursor.owner.ownerId}, ${cursor.scheduleId})`;\n const rows =\n owner === undefined\n ? yield* sql<Record<string, unknown>>`\n SELECT tenant_id, owner_id, schedule_id, deadline_at_millis\n FROM effect_agent_schedules\n WHERE deadline_at_millis <= ${nowMillis} AND ${continuation}\n ORDER BY deadline_at_millis, tenant_id, owner_id, schedule_id\n LIMIT ${limit}\n `.pipe(Effect.mapError(() => unavailable(operation)))\n : yield* sql<Record<string, unknown>>`\n SELECT tenant_id, owner_id, schedule_id, deadline_at_millis\n FROM effect_agent_schedules\n WHERE tenant_id = ${owner.tenantId}\n AND owner_id = ${owner.ownerId}\n AND deadline_at_millis <= ${nowMillis} AND ${continuation}\n ORDER BY deadline_at_millis, schedule_id\n LIMIT ${limit}\n `.pipe(Effect.mapError(() => unavailable(operation)));\n const decoded = yield* decodeRows(Schema.Array(ScheduleDueRow), rows, operation);\n return decoded.map((row) => ({\n owner: { tenantId: row.tenant_id, ownerId: row.owner_id },\n scheduleId: row.schedule_id,\n deadlineAtMillis: row.deadline_at_millis,\n }));\n });\n\n const nextDeadline: ScheduleStore[\"Service\"][\"nextDeadline\"] = Effect.fn(\n \"DoScheduleStore.nextDeadline\",\n )(function* (owner?: ScheduleOwner) {\n const operation = \"query next schedule deadline\";\n return yield* readNextDeadline(owner, operation);\n });\n\n const prearm = Effect.fn(\"DoScheduleStore.prearm\")(function* (\n deadlineAtMillis: number,\n ): Effect.fn.Return<void, ScheduleStorageError | ScheduleFailpointError> {\n yield* decodeBoundary(ScheduleInstant, deadlineAtMillis, \"pre-arm schedule recovery\");\n yield* transactions.run((replace) =>\n replaceAlarm(replace, deadlineAtMillis, \"pre-arm schedule recovery\"),\n );\n yield* scheduleFailpoint.hit(\"schedule:prearm:after\");\n });\n\n const reconcile = Effect.gen(function* () {\n yield* transactions.run((replace) =>\n Effect.gen(function* () {\n const deadline = yield* readNextDeadline(undefined, \"reconcile schedule alarm\");\n yield* replaceAlarm(replace, deadline, \"reconcile schedule alarm\");\n }),\n );\n yield* scheduleFailpoint.hit(\"schedule:reconcile:after\");\n });\n\n return Context.make(ScheduleStore, {\n insert,\n get,\n list,\n change,\n due,\n nextDeadline,\n }).pipe(Context.add(DoScheduleAlarmControl, { prearm, reconcile }));\n});\n\n/**\n * Durable Object SQLite ScheduleStore. Platform code supplies the one transaction owner that\n * combines these SQL mutations with its logical and native alarm lifecycle.\n */\nexport const scheduleStoreLayer: Layer.Layer<\n ScheduleStore | DoScheduleAlarmControl,\n ScheduleStorageError,\n SqlClientService.SqlClient | DoScheduleTransaction\n> = Layer.effectContext(makeServices);\n","import type { SubscriptionFailpointError } from \"@effect-agent/thread\";\nimport {\n AcceptedEvent,\n applySubscriptionDeliveryChange,\n DeliveryChange,\n Digest,\n sameAcceptedEventIdentity,\n sameSourcePartition,\n SourcePartition,\n subscriptionCanSelect,\n subscriptionDeliveryCanSelect,\n SubscriptionDelivery,\n SubscriptionDeliveryKey,\n SubscriptionError,\n SubscriptionFailpoint,\n SubscriptionKey,\n SubscriptionLimits,\n SubscriptionName,\n SubscriptionRecord,\n SubscriptionScanCursors,\n SubscriptionStore,\n subscriptionDeliveryKeyString,\n} from \"@effect-agent/thread\";\nimport { Clock, Context, Effect, Layer, Result, Schema } from \"effect\";\nimport * as SqlClientService from \"effect/unstable/sql/SqlClient\";\nimport type { SqlError } from \"effect/unstable/sql/SqlError\";\n\nconst CURRENT_SUBSCRIPTION_STORE_VERSION = 2;\nconst StoredJson = Schema.String.check(Schema.isMaxLength(1_900_000));\nconst CountRow = Schema.Struct({ count: Schema.Int.check(Schema.isGreaterThanOrEqualTo(0)) });\nconst SequenceRow = Schema.Struct({ sequence: Schema.Natural });\nconst ScanRow = Schema.Struct({\n event_scan_cursor: Schema.String,\n delivery_scan_cursor: Schema.String,\n recovery_scan_cursor: Schema.Natural,\n});\nconst JsonRow = Schema.Struct({ record_json: StoredJson });\nconst RegistrationRow = Schema.Struct({\n owner_id: Schema.String,\n subscription_id: Schema.String,\n ordinal: Schema.Natural,\n source_name: Schema.String,\n source_version: Schema.String,\n matching_key: Schema.String,\n state: SubscriptionRecord.fields.state,\n expires_at_millis: Schema.Number,\n recovery_at_millis: Schema.NullOr(Schema.Number),\n record_json: StoredJson,\n});\nconst EventRow = Schema.Struct({\n event_id: Schema.String,\n source_name: Schema.String,\n source_version: Schema.String,\n matching_key: Schema.String,\n payload_digest: Digest,\n cutoff: Schema.Natural,\n cursor: Schema.Natural,\n routing_complete: Schema.Number,\n next_attempt_at_millis: Schema.Number,\n record_json: StoredJson,\n});\nconst DeliveryRow = Schema.Struct({\n owner_id: Schema.String,\n subscription_id: Schema.String,\n event_id: Schema.String,\n delivery_key: Schema.String,\n state: SubscriptionDelivery.fields.state,\n next_attempt_at_millis: Schema.Number,\n record_json: StoredJson,\n});\nconst StoreStateRow = Schema.Struct({\n storage_version: Schema.Int,\n alarm_generation: Schema.Natural,\n});\n\nexport interface DoSubscriptionAlarmReplacement {\n readonly deadlineAtMillis: number | null;\n readonly generation: number;\n}\nexport type DoSubscriptionReplaceAlarm = (\n replacement: DoSubscriptionAlarmReplacement,\n) => Effect.Effect<void, SubscriptionError>;\n\n/** One Durable Object transaction combining subscription SQL and its single native alarm. */\nexport class DoSubscriptionTransaction extends Context.Service<\n DoSubscriptionTransaction,\n {\n readonly run: <A, E, R>(\n body: (replaceAlarm: DoSubscriptionReplaceAlarm) => Effect.Effect<A, E, R>,\n ) => Effect.Effect<A, E | SubscriptionError, R>;\n }\n>()(\"@effect-agent/storage-cloudflare/DoSubscriptionTransaction\") {}\n\nexport class DoSubscriptionAlarmControl extends Context.Service<\n DoSubscriptionAlarmControl,\n {\n readonly prearm: (\n deadlineAtMillis: number,\n ) => Effect.Effect<void, SubscriptionError | SubscriptionFailpointError>;\n readonly reconcile: Effect.Effect<void, SubscriptionError | SubscriptionFailpointError>;\n }\n>()(\"@effect-agent/storage-cloudflare/DoSubscriptionAlarmControl\") {}\n\nconst error = (reason: SubscriptionError[\"reason\"], code: string) =>\n SubscriptionError.make({ reason, code });\nconst unavailable = (operation: string) => error(\"storage\", operation);\nconst corrupt = (operation: string) => error(\"corrupt\", operation);\nconst bytes = (value: unknown) => new TextEncoder().encode(JSON.stringify(value)).byteLength;\n\nconst validate = <A, I>(schema: Schema.Codec<A, I>, value: unknown, code: string) =>\n Schema.decodeUnknownEffect(schema)(value).pipe(Effect.mapError(() => error(\"validation\", code)));\n\nconst encode = <A, I>(schema: Schema.Codec<A, I>, value: A, code: string) =>\n Schema.encodeEffect(Schema.fromJsonString(schema))(value).pipe(\n Effect.mapError(() => corrupt(code)),\n );\n\nconst decode = <A, I>(schema: Schema.Codec<A, I>, value: string, code: string) =>\n Schema.decodeEffect(Schema.fromJsonString(schema))(value).pipe(\n Effect.mapError(() => corrupt(code)),\n );\n\nconst decodeRows = <A, I>(schema: Schema.Codec<A, I>, rows: unknown, code: string) =>\n Schema.decodeUnknownEffect(Schema.Array(schema))(rows).pipe(Effect.mapError(() => corrupt(code)));\n\nconst sameDeliveryIdentity = (left: SubscriptionDelivery, right: SubscriptionDelivery): boolean =>\n subscriptionDeliveryKeyString(left.key) === subscriptionDeliveryKeyString(right.key) &&\n left.deliveryId === right.deliveryId &&\n left.source.name === right.source.name &&\n left.source.version === right.source.version &&\n left.threadId === right.threadId &&\n left.admissionKey === right.admissionKey &&\n left.subscriptionFingerprint === right.subscriptionFingerprint &&\n left.eventDigest === right.eventDigest;\n\nconst initializeDoSubscriptionStore = Effect.fn(\"DoSubscriptionStore.initialize\")(function* () {\n const sql = yield* SqlClientService.SqlClient;\n const names = yield* sql<Record<string, unknown>>`\n SELECT name FROM sqlite_master WHERE type='table' AND name LIKE 'effect_agent_subscription_%'\n `.pipe(Effect.mapError(() => unavailable(\"inspect subscription storage\")));\n const decodedNames = yield* decodeRows(\n Schema.Struct({ name: Schema.String }),\n names,\n \"inspect subscription storage\",\n );\n const expected = new Set([\n \"effect_agent_subscription_store_state\",\n \"effect_agent_subscription_sequences\",\n \"effect_agent_subscriptions\",\n \"effect_agent_subscription_events\",\n \"effect_agent_subscription_deliveries\",\n ]);\n const hasState = decodedNames.some(\n ({ name }) => name === \"effect_agent_subscription_store_state\",\n );\n if (!hasState && decodedNames.length > 0) return yield* corrupt(\"partial subscription storage\");\n if (!hasState) {\n yield* sql\n .withTransaction(\n Effect.gen(function* () {\n yield* sql`CREATE TABLE effect_agent_subscription_store_state (\n singleton INTEGER PRIMARY KEY NOT NULL CHECK(singleton=1), storage_version INTEGER NOT NULL, alarm_generation INTEGER NOT NULL\n )`.withoutTransform;\n yield* sql`CREATE TABLE effect_agent_subscription_sequences (\n tenant_id TEXT NOT NULL, source_address TEXT NOT NULL, sequence INTEGER NOT NULL,\n event_scan_cursor TEXT NOT NULL, delivery_scan_cursor TEXT NOT NULL, recovery_scan_cursor INTEGER NOT NULL,\n PRIMARY KEY (tenant_id, source_address)\n )`.withoutTransform;\n yield* sql`CREATE TABLE effect_agent_subscriptions (\n tenant_id TEXT NOT NULL, source_address TEXT NOT NULL, owner_id TEXT NOT NULL, subscription_id TEXT NOT NULL,\n ordinal INTEGER NOT NULL, source_name TEXT NOT NULL, source_version TEXT NOT NULL, matching_key TEXT NOT NULL,\n state TEXT NOT NULL, expires_at_millis INTEGER NOT NULL, recovery_at_millis INTEGER, record_json TEXT NOT NULL,\n PRIMARY KEY (tenant_id, source_address, owner_id, subscription_id), UNIQUE (tenant_id, source_address, ordinal)\n )`.withoutTransform;\n yield* sql`CREATE INDEX effect_agent_subscriptions_owner ON effect_agent_subscriptions (tenant_id, source_address, owner_id, ordinal)`\n .withoutTransform;\n yield* sql`CREATE INDEX effect_agent_subscriptions_candidates ON effect_agent_subscriptions (tenant_id, source_address, source_name, source_version, matching_key, ordinal)`\n .withoutTransform;\n yield* sql`CREATE INDEX effect_agent_subscriptions_recovery ON effect_agent_subscriptions (tenant_id, source_address, recovery_at_millis, ordinal) WHERE recovery_at_millis IS NOT NULL`\n .withoutTransform;\n yield* sql`CREATE TABLE effect_agent_subscription_events (\n tenant_id TEXT NOT NULL, source_address TEXT NOT NULL, event_id TEXT NOT NULL, source_name TEXT NOT NULL,\n source_version TEXT NOT NULL, matching_key TEXT NOT NULL, payload_digest TEXT NOT NULL, cutoff INTEGER NOT NULL,\n cursor INTEGER NOT NULL, routing_complete INTEGER NOT NULL, next_attempt_at_millis INTEGER NOT NULL, record_json TEXT NOT NULL,\n PRIMARY KEY (tenant_id, source_address, event_id)\n )`.withoutTransform;\n yield* sql`CREATE INDEX effect_agent_subscription_events_pending ON effect_agent_subscription_events (tenant_id, source_address, routing_complete, next_attempt_at_millis, event_id)`\n .withoutTransform;\n yield* sql`CREATE TABLE effect_agent_subscription_deliveries (\n tenant_id TEXT NOT NULL, source_address TEXT NOT NULL, owner_id TEXT NOT NULL, subscription_id TEXT NOT NULL,\n event_id TEXT NOT NULL, delivery_key TEXT NOT NULL, state TEXT NOT NULL, next_attempt_at_millis INTEGER NOT NULL,\n record_json TEXT NOT NULL, PRIMARY KEY (tenant_id, source_address, owner_id, subscription_id, event_id),\n UNIQUE (tenant_id, source_address, delivery_key)\n )`.withoutTransform;\n yield* sql`CREATE INDEX effect_agent_subscription_deliveries_pending ON effect_agent_subscription_deliveries (tenant_id, source_address, state, next_attempt_at_millis, delivery_key)`\n .withoutTransform;\n yield* sql`CREATE INDEX effect_agent_subscription_deliveries_registration ON effect_agent_subscription_deliveries (tenant_id, source_address, owner_id, subscription_id, delivery_key)`\n .withoutTransform;\n yield* sql`INSERT INTO effect_agent_subscription_store_state (singleton, storage_version, alarm_generation)\n VALUES (1, ${CURRENT_SUBSCRIPTION_STORE_VERSION}, 0)`.withoutTransform;\n }),\n )\n .pipe(Effect.mapError(() => unavailable(\"initialize subscription storage\")));\n return;\n }\n if (decodedNames.length !== expected.size || decodedNames.some(({ name }) => !expected.has(name)))\n return yield* corrupt(\"subscription storage tables\");\n const rows = yield* sql<\n Record<string, unknown>\n >`SELECT storage_version, alarm_generation FROM effect_agent_subscription_store_state WHERE singleton=1`.pipe(\n Effect.mapError(() => unavailable(\"read subscription storage version\")),\n );\n const state = yield* decodeRows(StoreStateRow, rows, \"read subscription storage version\");\n if (state.length !== 1 || state[0].storage_version !== CURRENT_SUBSCRIPTION_STORE_VERSION)\n return yield* corrupt(\n state.length === 1\n ? `incompatible subscription storage version ${state[0].storage_version}; expected ${CURRENT_SUBSCRIPTION_STORE_VERSION}`\n : \"invalid subscription storage version row\",\n );\n});\n\nconst makeSubscriptionStore = Effect.fn(\"SqliteSubscriptionStore.make\")(function* (\n owned: SourcePartition,\n) {\n const partition = yield* validate(SourcePartition, owned, \"partition\");\n const sql = yield* SqlClientService.SqlClient;\n const failpoint = yield* SubscriptionFailpoint;\n const transactions = yield* DoSubscriptionTransaction;\n yield* initializeDoSubscriptionStore();\n yield* sql`\n INSERT INTO effect_agent_subscription_sequences (\n tenant_id, source_address, sequence, event_scan_cursor, delivery_scan_cursor, recovery_scan_cursor\n ) VALUES (${partition.tenantId}, ${partition.address}, 0, '', '', 0) ON CONFLICT DO NOTHING\n `.pipe(Effect.mapError(() => unavailable(\"initialize subscription partition\")));\n\n const query = <A extends object>(\n effect: Effect.Effect<ReadonlyArray<A>, SqlError>,\n code: string,\n ) => effect.pipe(Effect.mapError(() => unavailable(code)));\n const readIndexedDeadline = Effect.fn(\"DoSubscriptionStore.readIndexedDeadline\")(function* () {\n const scanRows = yield* query(\n sql<Record<string, unknown>>`\n SELECT event_scan_cursor, delivery_scan_cursor, recovery_scan_cursor FROM effect_agent_subscription_sequences\n WHERE tenant_id=${partition.tenantId} AND source_address=${partition.address}\n `,\n \"read scan cursor deadline\",\n );\n const scans = yield* decodeRows(ScanRow, scanRows, \"read scan cursor deadline\");\n if (scans.length !== 1) return yield* corrupt(\"scan cursor deadline\");\n if (\n scans[0].event_scan_cursor !== \"\" ||\n scans[0].delivery_scan_cursor !== \"\" ||\n scans[0].recovery_scan_cursor !== 0\n )\n return 0;\n const rows = yield* query(\n sql<Record<string, unknown>>`\n SELECT MIN(deadline) AS deadline FROM (\n SELECT next_attempt_at_millis AS deadline FROM effect_agent_subscription_events\n WHERE tenant_id=${partition.tenantId} AND source_address=${partition.address} AND routing_complete=0\n UNION ALL SELECT next_attempt_at_millis FROM effect_agent_subscription_deliveries\n WHERE tenant_id=${partition.tenantId} AND source_address=${partition.address} AND state NOT IN ('delivered','refused')\n UNION ALL SELECT recovery_at_millis FROM effect_agent_subscriptions\n WHERE tenant_id=${partition.tenantId} AND source_address=${partition.address} AND state='active' AND recovery_at_millis IS NOT NULL\n )\n `,\n \"read subscription deadline\",\n );\n const decoded = yield* decodeRows(\n Schema.Struct({ deadline: Schema.NullOr(Schema.Number) }),\n rows,\n \"read subscription deadline\",\n );\n if (decoded.length !== 1) return yield* corrupt(\"subscription deadline\");\n return decoded[0].deadline;\n });\n const replaceAlarm = Effect.fn(\"DoSubscriptionStore.replaceAlarm\")(function* (\n replace: DoSubscriptionReplaceAlarm,\n deadlineAtMillis: number | null,\n ) {\n const rows = yield* query(\n sql<Record<string, unknown>>`\n UPDATE effect_agent_subscription_store_state SET alarm_generation=alarm_generation+1\n WHERE singleton=1 RETURNING storage_version, alarm_generation\n `,\n \"advance subscription alarm generation\",\n );\n const state = yield* decodeRows(StoreStateRow, rows, \"advance subscription alarm generation\");\n if (state.length !== 1 || state[0].storage_version !== CURRENT_SUBSCRIPTION_STORE_VERSION)\n return yield* corrupt(\"subscription alarm state\");\n yield* failpoint.hit(\"subscription:alarm:before\");\n yield* replace({ deadlineAtMillis, generation: state[0].alarm_generation });\n yield* failpoint.hit(\"subscription:alarm:after\");\n });\n const transact = <A>(effect: Effect.Effect<A, SubscriptionError | SubscriptionFailpointError>) =>\n transactions.run((replace) =>\n Effect.gen(function* () {\n const value = yield* effect;\n yield* replaceAlarm(replace, yield* readIndexedDeadline());\n return value;\n }),\n );\n const requirePartition = (candidate: SourcePartition, code: string) =>\n sameSourcePartition(candidate, partition)\n ? Effect.void\n : Effect.fail(error(\"validation\", code));\n const requireKey = Effect.fn(\"SqliteSubscriptionStore.requireKey\")(function* (\n input: SubscriptionKey,\n code: string,\n ) {\n const key = yield* validate(SubscriptionKey, input, code);\n yield* requirePartition(key.partition, code);\n return key;\n });\n const readRegistration = Effect.fn(\"SqliteSubscriptionStore.readRegistration\")(function* (\n key: SubscriptionKey,\n code: string,\n ) {\n const rows = yield* query(\n sql<Record<string, unknown>>`\n SELECT owner_id, subscription_id, ordinal, source_name, source_version, matching_key, state,\n expires_at_millis, recovery_at_millis, record_json FROM effect_agent_subscriptions\n WHERE tenant_id=${partition.tenantId} AND source_address=${partition.address}\n AND owner_id=${key.ownerId} AND subscription_id=${key.subscriptionId}\n `,\n code,\n );\n const decodedRows = yield* decodeRows(RegistrationRow, rows, code);\n if (decodedRows.length > 1) return yield* corrupt(code);\n const row = decodedRows[0];\n if (row === undefined) return null;\n const record = yield* decode(SubscriptionRecord, row.record_json, code);\n if (\n !sameSourcePartition(record.key.partition, partition) ||\n record.key.ownerId !== row.owner_id ||\n record.key.subscriptionId !== row.subscription_id ||\n record.ordinal !== row.ordinal ||\n record.configuration.source.name !== row.source_name ||\n record.configuration.source.version !== row.source_version ||\n record.configuration.matchingKey !== row.matching_key ||\n record.state !== row.state ||\n record.configuration.expiresAtMillis !== row.expires_at_millis ||\n (record.recovery?.nextAttemptAtMillis ?? null) !== row.recovery_at_millis\n )\n return yield* corrupt(`${code}-projection`);\n return record;\n });\n const readEvent = Effect.fn(\"SqliteSubscriptionStore.readEvent\")(function* (\n eventId: string,\n code: string,\n ) {\n const rows = yield* query(\n sql<Record<string, unknown>>`\n SELECT event_id, source_name, source_version, matching_key, payload_digest, cutoff, cursor,\n routing_complete, next_attempt_at_millis, record_json FROM effect_agent_subscription_events\n WHERE tenant_id=${partition.tenantId} AND source_address=${partition.address} AND event_id=${eventId}\n `,\n code,\n );\n const decodedRows = yield* decodeRows(EventRow, rows, code);\n if (decodedRows.length > 1) return yield* corrupt(code);\n const row = decodedRows[0];\n if (row === undefined) return null;\n const event = yield* decode(AcceptedEvent, row.record_json, code);\n if (\n !sameSourcePartition(event.partition, partition) ||\n event.eventId !== row.event_id ||\n event.source.name !== row.source_name ||\n event.source.version !== row.source_version ||\n event.matchingKey !== row.matching_key ||\n event.payloadDigest !== row.payload_digest ||\n event.cutoff !== row.cutoff ||\n event.cursor !== row.cursor ||\n (event.routingComplete ? 1 : 0) !== row.routing_complete ||\n event.nextAttemptAtMillis !== row.next_attempt_at_millis\n )\n return yield* corrupt(`${code}-projection`);\n return event;\n });\n const readDelivery = Effect.fn(\"SqliteSubscriptionStore.readDelivery\")(function* (\n key: SubscriptionDeliveryKey,\n code: string,\n ) {\n const rows = yield* query(\n sql<Record<string, unknown>>`\n SELECT owner_id, subscription_id, event_id, delivery_key, state, next_attempt_at_millis, record_json\n FROM effect_agent_subscription_deliveries\n WHERE tenant_id=${partition.tenantId} AND source_address=${partition.address}\n AND owner_id=${key.subscription.ownerId} AND subscription_id=${key.subscription.subscriptionId}\n AND event_id=${key.eventId}\n `,\n code,\n );\n const decodedRows = yield* decodeRows(DeliveryRow, rows, code);\n if (decodedRows.length > 1) return yield* corrupt(code);\n const row = decodedRows[0];\n if (row === undefined) return null;\n const delivery = yield* decode(SubscriptionDelivery, row.record_json, code);\n if (\n !sameSourcePartition(delivery.key.subscription.partition, partition) ||\n delivery.key.subscription.ownerId !== row.owner_id ||\n delivery.key.subscription.subscriptionId !== row.subscription_id ||\n delivery.key.eventId !== row.event_id ||\n subscriptionDeliveryKeyString(delivery.key) !== row.delivery_key ||\n delivery.state !== row.state ||\n delivery.retry.nextAttemptAtMillis !== row.next_attempt_at_millis\n )\n return yield* corrupt(`${code}-projection`);\n return delivery;\n });\n const count = Effect.fn(\"SqliteSubscriptionStore.count\")(function* (\n statement: Effect.Effect<ReadonlyArray<Record<string, unknown>>, SqlError>,\n code: string,\n ) {\n const rows = yield* query(statement, code);\n const decoded = yield* decodeRows(CountRow, rows, code);\n if (decoded.length !== 1) return yield* corrupt(code);\n return decoded[0].count;\n });\n const nextSequence = Effect.fn(\"SqliteSubscriptionStore.nextSequence\")(function* () {\n const rows = yield* query(\n sql<Record<string, unknown>>`\n UPDATE effect_agent_subscription_sequences SET sequence=sequence+1\n WHERE tenant_id=${partition.tenantId} AND source_address=${partition.address}\n RETURNING sequence\n `,\n \"advance subscription sequence\",\n );\n const decoded = yield* decodeRows(SequenceRow, rows, \"advance subscription sequence\");\n if (decoded.length !== 1) return yield* corrupt(\"subscription sequence\");\n return decoded[0].sequence;\n });\n const writeRegistration = Effect.fn(\"SqliteSubscriptionStore.writeRegistration\")(function* (\n record: SubscriptionRecord,\n ) {\n const json = yield* encode(SubscriptionRecord, record, \"encode subscription\");\n yield* query(\n sql<Record<string, unknown>>`\n UPDATE effect_agent_subscriptions SET state=${record.state}, expires_at_millis=${record.configuration.expiresAtMillis},\n recovery_at_millis=${record.recovery?.nextAttemptAtMillis ?? null}, record_json=${json}\n WHERE tenant_id=${partition.tenantId} AND source_address=${partition.address}\n AND owner_id=${record.key.ownerId} AND subscription_id=${record.key.subscriptionId}\n `,\n \"write subscription\",\n );\n });\n const writeEvent = Effect.fn(\"SqliteSubscriptionStore.writeEvent\")(function* (\n event: AcceptedEvent,\n ) {\n const json = yield* encode(AcceptedEvent, event, \"encode event\");\n yield* query(\n sql<Record<string, unknown>>`\n UPDATE effect_agent_subscription_events SET cursor=${event.cursor}, routing_complete=${event.routingComplete ? 1 : 0},\n next_attempt_at_millis=${event.nextAttemptAtMillis}, record_json=${json}\n WHERE tenant_id=${partition.tenantId} AND source_address=${partition.address} AND event_id=${event.eventId}\n `,\n \"write event\",\n );\n });\n const writeDelivery = Effect.fn(\"SqliteSubscriptionStore.writeDelivery\")(function* (\n delivery: SubscriptionDelivery,\n ) {\n const json = yield* encode(SubscriptionDelivery, delivery, \"encode delivery\");\n yield* query(\n sql<Record<string, unknown>>`\n UPDATE effect_agent_subscription_deliveries SET state=${delivery.state},\n next_attempt_at_millis=${delivery.retry.nextAttemptAtMillis}, record_json=${json}\n WHERE tenant_id=${partition.tenantId} AND source_address=${partition.address}\n AND owner_id=${delivery.key.subscription.ownerId} AND subscription_id=${delivery.key.subscription.subscriptionId}\n AND event_id=${delivery.key.eventId}\n `,\n \"write delivery\",\n );\n });\n\n const register: SubscriptionStore[\"Service\"][\"register\"] = Effect.fn(\n \"SqliteSubscriptionStore.register\",\n )(function* (input, inputLimits) {\n const record = yield* validate(SubscriptionRecord, input, \"register-record\");\n const limits = yield* validate(SubscriptionLimits, inputLimits, \"register-limits\");\n yield* requirePartition(record.key.partition, \"register-partition\");\n const result = yield* transact(\n Effect.gen(function* () {\n const existing = yield* readRegistration(record.key, \"register-existing\");\n if (existing !== null) {\n if (existing.creationFingerprint !== record.creationFingerprint)\n return yield* error(\"conflict\", \"registration-identity\");\n return { value: existing, changed: false } as const;\n }\n if (bytes(record.configuration.context) > limits.maxContextBytes)\n return yield* error(\"capacity\", \"context-bytes\");\n if (bytes(record.configuration.parameters) > limits.maxPayloadBytes)\n return yield* error(\"capacity\", \"parameters-bytes\");\n if (\n record.configuration.expiresAtMillis - record.createdAtMillis >\n limits.maxLifetimeMillis\n )\n return yield* error(\"capacity\", \"lifetime\");\n if (\n (yield* count(\n sql<\n Record<string, unknown>\n >`SELECT COUNT(*) AS count FROM effect_agent_subscriptions WHERE tenant_id=${partition.tenantId} AND source_address=${partition.address}`,\n \"count registrations\",\n )) >= limits.maxRegistrations\n )\n return yield* error(\"capacity\", \"registrations\");\n if (\n (yield* count(\n sql<\n Record<string, unknown>\n >`SELECT COUNT(*) AS count FROM effect_agent_subscriptions WHERE tenant_id=${partition.tenantId} AND source_address=${partition.address} AND owner_id=${record.key.ownerId}`,\n \"count owner registrations\",\n )) >= limits.maxRegistrationsPerOwner\n )\n return yield* error(\"capacity\", \"owner-registrations\");\n const assigned = { ...record, ordinal: yield* nextSequence() };\n const json = yield* encode(SubscriptionRecord, assigned, \"encode registration\");\n yield* failpoint.hit(\"subscription:register:before\");\n yield* query(\n sql<Record<string, unknown>>`\n INSERT INTO effect_agent_subscriptions (tenant_id, source_address, owner_id, subscription_id, ordinal,\n source_name, source_version, matching_key, state, expires_at_millis, recovery_at_millis, record_json)\n VALUES (${partition.tenantId}, ${partition.address}, ${assigned.key.ownerId}, ${assigned.key.subscriptionId}, ${assigned.ordinal},\n ${assigned.configuration.source.name}, ${assigned.configuration.source.version}, ${assigned.configuration.matchingKey}, ${assigned.state},\n ${assigned.configuration.expiresAtMillis}, ${assigned.recovery?.nextAttemptAtMillis ?? null}, ${json})\n `,\n \"insert registration\",\n );\n return { value: assigned, changed: true } as const;\n }),\n );\n if (result.changed) yield* failpoint.hit(\"subscription:register:after\");\n return result.value;\n });\n\n const get: SubscriptionStore[\"Service\"][\"get\"] = Effect.fn(\"SqliteSubscriptionStore.get\")(\n function* (input) {\n return yield* readRegistration(yield* requireKey(input, \"get-key\"), \"get subscription\");\n },\n );\n\n const list: SubscriptionStore[\"Service\"][\"list\"] = Effect.fn(\"SqliteSubscriptionStore.list\")(\n function* (ownerId, after, limit) {\n const rows = yield* query(\n sql<Record<string, unknown>>`\n SELECT owner_id, subscription_id, ordinal FROM effect_agent_subscriptions WHERE tenant_id=${partition.tenantId} AND source_address=${partition.address}\n AND owner_id=${ownerId} AND ordinal>${after} ORDER BY ordinal LIMIT ${limit}\n `,\n \"list subscriptions\",\n );\n const decoded = yield* decodeRows(\n Schema.Struct({\n owner_id: Schema.String,\n subscription_id: Schema.String,\n ordinal: Schema.Natural,\n }),\n rows,\n \"list subscriptions\",\n );\n return yield* Effect.forEach(\n decoded,\n Effect.fn(\"SqliteSubscriptionStore.listRecord\")(function* (row) {\n const record = yield* readRegistration(\n { partition, ownerId: row.owner_id, subscriptionId: row.subscription_id },\n \"list subscription\",\n );\n if (record === null || record.ordinal !== row.ordinal)\n return yield* corrupt(\"list subscription projection\");\n return record;\n }),\n );\n },\n );\n\n const cancel: SubscriptionStore[\"Service\"][\"cancel\"] = Effect.fn(\n \"SqliteSubscriptionStore.cancel\",\n )(function* (input) {\n const key = yield* requireKey(input, \"cancel-key\");\n const result = yield* transact(\n Effect.gen(function* () {\n const current = yield* readRegistration(key, \"cancel subscription\");\n if (current === null) return yield* error(\"not-found\", \"subscription\");\n if (current.state === \"cancelled\") return { value: current, changed: false } as const;\n const updated = { ...current, state: \"cancelled\" as const, recovery: null };\n yield* failpoint.hit(\"subscription:cancel:before\");\n yield* writeRegistration(updated);\n return { value: updated, changed: true } as const;\n }),\n );\n if (result.changed) yield* failpoint.hit(\"subscription:cancel:after\");\n return result.value;\n });\n\n const accept: SubscriptionStore[\"Service\"][\"accept\"] = Effect.fn(\n \"SqliteSubscriptionStore.accept\",\n )(function* (input, inputLimits) {\n const event = yield* validate(AcceptedEvent, input, \"accept-event\");\n const limits = yield* validate(SubscriptionLimits, inputLimits, \"accept-limits\");\n yield* requirePartition(event.partition, \"accept-partition\");\n const result = yield* transact(\n Effect.gen(function* () {\n const existing = yield* readEvent(event.eventId, \"accept event\");\n if (existing !== null) {\n if (!sameAcceptedEventIdentity(existing, event))\n return yield* error(\"conflict\", \"event-identity\");\n return { value: existing, changed: false } as const;\n }\n if (bytes(event.payload) > limits.maxPayloadBytes)\n return yield* error(\"capacity\", \"payload-bytes\");\n if (\n (yield* count(\n sql<\n Record<string, unknown>\n >`SELECT COUNT(*) AS count FROM effect_agent_subscription_events WHERE tenant_id=${partition.tenantId} AND source_address=${partition.address}`,\n \"count events\",\n )) >= limits.maxEvents\n )\n return yield* error(\"capacity\", \"events\");\n const accepted: AcceptedEvent = {\n ...event,\n cutoff: yield* nextSequence(),\n cursor: 0,\n routingComplete: false,\n routingFailure: null,\n };\n const json = yield* encode(AcceptedEvent, accepted, \"encode accepted event\");\n yield* failpoint.hit(\"subscription:accept:before\");\n yield* query(\n sql<Record<string, unknown>>`\n INSERT INTO effect_agent_subscription_events (tenant_id, source_address, event_id, source_name, source_version,\n matching_key, payload_digest, cutoff, cursor, routing_complete, next_attempt_at_millis, record_json)\n VALUES (${partition.tenantId}, ${partition.address}, ${accepted.eventId}, ${accepted.source.name}, ${accepted.source.version},\n ${accepted.matchingKey}, ${accepted.payloadDigest}, ${accepted.cutoff}, ${accepted.cursor}, 0, ${accepted.nextAttemptAtMillis}, ${json})\n `,\n \"insert event\",\n );\n return { value: accepted, changed: true } as const;\n }),\n );\n if (result.changed) yield* failpoint.hit(\"subscription:accept:after\");\n return result.value;\n });\n\n const event: SubscriptionStore[\"Service\"][\"event\"] = Effect.fn(\"SqliteSubscriptionStore.event\")(\n (eventId) => readEvent(eventId, \"get event\"),\n );\n\n const pendingEvents: SubscriptionStore[\"Service\"][\"pendingEvents\"] = Effect.fn(\n \"SqliteSubscriptionStore.pendingEvents\",\n )(function* (nowMillis, after, limit) {\n const rows = yield* query(\n sql<Record<string, unknown>>`\n SELECT event_id FROM effect_agent_subscription_events WHERE tenant_id=${partition.tenantId} AND source_address=${partition.address}\n AND routing_complete=0 AND next_attempt_at_millis<=${nowMillis} AND event_id>${after} ORDER BY event_id LIMIT ${limit}\n `,\n \"pending events\",\n );\n return yield* decodeRows(\n Schema.Struct({ event_id: Schema.String }),\n rows,\n \"pending event keys\",\n ).pipe(Effect.map((items) => items.map((item) => item.event_id)));\n });\n\n const candidates: SubscriptionStore[\"Service\"][\"candidates\"] = Effect.fn(\n \"SqliteSubscriptionStore.candidates\",\n )(function* (input, limit) {\n const supplied = yield* validate(AcceptedEvent, input, \"candidates-event\");\n yield* requirePartition(supplied.partition, \"candidates-partition\");\n const stored = yield* readEvent(supplied.eventId, \"candidates event\");\n if (stored === null) return yield* error(\"not-found\", \"event\");\n if (!sameAcceptedEventIdentity(stored, supplied)) return yield* error(\"conflict\", \"event\");\n const rows = yield* query(\n sql<Record<string, unknown>>`\n SELECT owner_id, subscription_id, ordinal FROM effect_agent_subscriptions WHERE tenant_id=${partition.tenantId} AND source_address=${partition.address}\n AND source_name=${stored.source.name} AND source_version=${stored.source.version} AND matching_key=${stored.matchingKey}\n AND ordinal>${stored.cursor} AND ordinal<=${stored.cutoff} ORDER BY ordinal LIMIT ${limit}\n `,\n \"subscription candidates\",\n );\n const decoded = yield* decodeRows(\n Schema.Struct({\n owner_id: Schema.String,\n subscription_id: Schema.String,\n ordinal: Schema.Natural,\n }),\n rows,\n \"subscription candidates\",\n );\n return yield* Effect.forEach(\n decoded,\n Effect.fn(\"SqliteSubscriptionStore.candidateRecord\")(function* (row) {\n const record = yield* readRegistration(\n { partition, ownerId: row.owner_id, subscriptionId: row.subscription_id },\n \"subscription candidate\",\n );\n if (record === null || record.ordinal !== row.ordinal)\n return yield* corrupt(\"subscription candidate projection\");\n return record;\n }),\n );\n });\n\n const insertDelivery = Effect.fn(\"SqliteSubscriptionStore.insertDelivery\")(function* (\n delivery: SubscriptionDelivery,\n ) {\n const json = yield* encode(SubscriptionDelivery, delivery, \"encode selected delivery\");\n yield* query(\n sql<Record<string, unknown>>`\n INSERT INTO effect_agent_subscription_deliveries (tenant_id, source_address, owner_id, subscription_id, event_id,\n delivery_key, state, next_attempt_at_millis, record_json)\n VALUES (${partition.tenantId}, ${partition.address}, ${delivery.key.subscription.ownerId}, ${delivery.key.subscription.subscriptionId},\n ${delivery.key.eventId}, ${subscriptionDeliveryKeyString(delivery.key)}, ${delivery.state}, ${delivery.retry.nextAttemptAtMillis}, ${json})\n `,\n \"insert delivery\",\n );\n });\n\n const select: SubscriptionStore[\"Service\"][\"select\"] = Effect.fn(\n \"SqliteSubscriptionStore.select\",\n )(function* (inputEvent, inputDeliveries, cursor, complete, nowMillis, inputLimits) {\n const supplied = yield* validate(AcceptedEvent, inputEvent, \"select-event\");\n const deliveries = yield* validate(\n Schema.Array(SubscriptionDelivery),\n inputDeliveries,\n \"select-deliveries\",\n );\n const limits = yield* validate(SubscriptionLimits, inputLimits, \"select-limits\");\n yield* requirePartition(supplied.partition, \"select-partition\");\n for (const candidate of deliveries)\n yield* requirePartition(candidate.key.subscription.partition, \"select-delivery-partition\");\n const changed = yield* transact(\n Effect.gen(function* () {\n const accepted = yield* readEvent(supplied.eventId, \"select event\");\n if (accepted === null) return yield* error(\"not-found\", \"event\");\n if (!sameAcceptedEventIdentity(accepted, supplied) || accepted.cursor !== supplied.cursor)\n return yield* error(\"conflict\", \"event-cursor\");\n if (accepted.routingComplete) return false;\n if (!Number.isSafeInteger(cursor) || cursor < accepted.cursor || cursor > accepted.cutoff)\n return yield* error(\"validation\", \"cursor\");\n yield* failpoint.hit(\"subscription:select:before\");\n const effectiveNowMillis = Math.max(nowMillis, yield* Clock.currentTimeMillis);\n const additions: Array<{ delivery: SubscriptionDelivery; record: SubscriptionRecord }> = [];\n for (const delivery of deliveries) {\n const record = yield* readRegistration(delivery.key.subscription, \"select registration\");\n if (record === null) return yield* error(\"not-found\", \"subscription\");\n if (\n !subscriptionDeliveryCanSelect(delivery, record, accepted) ||\n delivery.key.eventId !== accepted.eventId ||\n delivery.source.name !== accepted.source.name ||\n delivery.source.version !== accepted.source.version ||\n record.ordinal <= accepted.cursor ||\n record.ordinal > cursor\n )\n return yield* error(\"conflict\", \"selection\");\n const existing = yield* readDelivery(delivery.key, \"select existing delivery\");\n if (existing !== null) {\n if (!sameDeliveryIdentity(existing, delivery))\n return yield* error(\"conflict\", \"delivery-identity\");\n continue;\n }\n if (!subscriptionCanSelect(record, accepted, effectiveNowMillis, false)) continue;\n additions.push({ delivery, record });\n }\n const total = yield* count(\n sql<\n Record<string, unknown>\n >`SELECT COUNT(*) AS count FROM effect_agent_subscription_deliveries WHERE tenant_id=${partition.tenantId} AND source_address=${partition.address}`,\n \"count deliveries\",\n );\n if (total + additions.length > limits.maxDeliveries)\n return yield* error(\"capacity\", \"deliveries\");\n for (const ownerId of new Set(additions.map(({ record }) => record.key.ownerId))) {\n const existing = yield* count(\n sql<\n Record<string, unknown>\n >`SELECT COUNT(*) AS count FROM effect_agent_subscription_deliveries WHERE tenant_id=${partition.tenantId} AND source_address=${partition.address} AND owner_id=${ownerId}`,\n \"count owner deliveries\",\n );\n if (\n existing + additions.filter(({ record }) => record.key.ownerId === ownerId).length >\n limits.maxDeliveriesPerOwner\n )\n return yield* error(\"capacity\", \"owner-deliveries\");\n }\n for (const addition of additions) {\n yield* insertDelivery(addition.delivery);\n if (addition.record.configuration.mode === \"once\")\n yield* writeRegistration({ ...addition.record, state: \"consumed\", recovery: null });\n }\n yield* writeEvent({ ...accepted, cursor, routingComplete: complete, routingFailure: null });\n return true;\n }),\n );\n if (changed) yield* failpoint.hit(\"subscription:select:after\");\n });\n\n const catchUp: SubscriptionStore[\"Service\"][\"catchUp\"] = Effect.fn(\n \"SqliteSubscriptionStore.catchUp\",\n )(function* (inputEvent, inputDelivery, nowMillis, inputLimits) {\n const supplied = yield* validate(AcceptedEvent, inputEvent, \"catch-up-event\");\n const delivery = yield* validate(SubscriptionDelivery, inputDelivery, \"catch-up-delivery\");\n const limits = yield* validate(SubscriptionLimits, inputLimits, \"catch-up-limits\");\n yield* requirePartition(supplied.partition, \"catch-up-partition\");\n yield* requirePartition(delivery.key.subscription.partition, \"catch-up-delivery-partition\");\n const changed = yield* transact(\n Effect.gen(function* () {\n const accepted = yield* readEvent(supplied.eventId, \"catch-up event\");\n const record = yield* readRegistration(delivery.key.subscription, \"catch-up subscription\");\n if (accepted === null || record === null)\n return yield* error(\"not-found\", accepted === null ? \"event\" : \"subscription\");\n if (\n !sameAcceptedEventIdentity(accepted, supplied) ||\n !subscriptionDeliveryCanSelect(delivery, record, accepted) ||\n delivery.key.eventId !== accepted.eventId ||\n delivery.source.name !== accepted.source.name ||\n delivery.source.version !== accepted.source.version ||\n record.configuration.mode !== \"once\"\n )\n return yield* error(\"conflict\", \"catch-up-identity\");\n const existing = yield* readDelivery(delivery.key, \"catch-up existing delivery\");\n if (existing !== null) {\n if (!sameDeliveryIdentity(existing, delivery))\n return yield* error(\"conflict\", \"delivery-identity\");\n return false;\n }\n yield* failpoint.hit(\"subscription:catch-up:before\");\n const effectiveNowMillis = Math.max(nowMillis, yield* Clock.currentTimeMillis);\n if (!subscriptionCanSelect(record, accepted, effectiveNowMillis, true))\n return yield* error(\"conflict\", \"catch-up-eligibility\");\n if (\n (yield* count(\n sql<\n Record<string, unknown>\n >`SELECT COUNT(*) AS count FROM effect_agent_subscription_deliveries WHERE tenant_id=${partition.tenantId} AND source_address=${partition.address}`,\n \"count deliveries\",\n )) >= limits.maxDeliveries\n )\n return yield* error(\"capacity\", \"deliveries\");\n if (\n (yield* count(\n sql<\n Record<string, unknown>\n >`SELECT COUNT(*) AS count FROM effect_agent_subscription_deliveries WHERE tenant_id=${partition.tenantId} AND source_address=${partition.address} AND owner_id=${record.key.ownerId}`,\n \"count owner deliveries\",\n )) >= limits.maxDeliveriesPerOwner\n )\n return yield* error(\"capacity\", \"owner-deliveries\");\n yield* insertDelivery(delivery);\n yield* writeRegistration({ ...record, state: \"consumed\", recovery: null });\n return true;\n }),\n );\n if (changed) yield* failpoint.hit(\"subscription:catch-up:after\");\n });\n\n const deferEvent: SubscriptionStore[\"Service\"][\"deferEvent\"] = Effect.fn(\n \"SqliteSubscriptionStore.deferEvent\",\n )(function* (eventId, nextAttemptAtMillis, code) {\n const routingFailure =\n code === undefined\n ? \"routing-failed\"\n : yield* validate(SubscriptionName, code, \"routing-failure\");\n yield* transact(\n Effect.gen(function* () {\n const accepted = yield* readEvent(eventId, \"defer event\");\n if (accepted === null) return yield* error(\"not-found\", \"event\");\n yield* failpoint.hit(\"subscription:defer-event:before\");\n yield* writeEvent({ ...accepted, nextAttemptAtMillis, routingFailure });\n }),\n );\n yield* failpoint.hit(\"subscription:defer-event:after\");\n });\n\n const delivery: SubscriptionStore[\"Service\"][\"delivery\"] = Effect.fn(\n \"SqliteSubscriptionStore.delivery\",\n )(function* (input) {\n const key = yield* validate(SubscriptionDeliveryKey, input, \"delivery-key\");\n yield* requirePartition(key.subscription.partition, \"delivery-partition\");\n return yield* readDelivery(key, \"get delivery\");\n });\n\n const pendingDeliveries: SubscriptionStore[\"Service\"][\"pendingDeliveries\"] = Effect.fn(\n \"SqliteSubscriptionStore.pendingDeliveries\",\n )(function* (nowMillis, after, limit) {\n const rows = yield* query(\n sql<Record<string, unknown>>`\n SELECT owner_id, subscription_id, event_id FROM effect_agent_subscription_deliveries\n WHERE tenant_id=${partition.tenantId} AND source_address=${partition.address} AND state NOT IN ('delivered','refused')\n AND next_attempt_at_millis<=${nowMillis} AND delivery_key>${after} ORDER BY delivery_key LIMIT ${limit}\n `,\n \"pending deliveries\",\n );\n const rowSchema = Schema.Struct({\n owner_id: Schema.String,\n subscription_id: Schema.String,\n event_id: Schema.String,\n });\n return yield* decodeRows(rowSchema, rows, \"pending delivery keys\").pipe(\n Effect.map((items) =>\n items.map((item) => ({\n subscription: { partition, ownerId: item.owner_id, subscriptionId: item.subscription_id },\n eventId: item.event_id,\n })),\n ),\n );\n });\n\n const listDeliveries: SubscriptionStore[\"Service\"][\"listDeliveries\"] = Effect.fn(\n \"SqliteSubscriptionStore.listDeliveries\",\n )(function* (input, after, limit) {\n const key = yield* requireKey(input, \"list-deliveries-key\");\n const rows = yield* query(\n sql<Record<string, unknown>>`\n SELECT record_json FROM effect_agent_subscription_deliveries WHERE tenant_id=${partition.tenantId} AND source_address=${partition.address}\n AND owner_id=${key.ownerId} AND subscription_id=${key.subscriptionId} AND delivery_key>${after} ORDER BY delivery_key LIMIT ${limit}\n `,\n \"list deliveries\",\n );\n const decoded = yield* decodeRows(JsonRow, rows, \"list deliveries\");\n return yield* Effect.forEach(decoded, (row) =>\n decode(SubscriptionDelivery, row.record_json, \"list delivery\"),\n );\n });\n\n const changeDelivery: SubscriptionStore[\"Service\"][\"changeDelivery\"] = Effect.fn(\n \"SqliteSubscriptionStore.changeDelivery\",\n )(function* (inputKey, inputDeliveryId, inputChange) {\n const key = yield* validate(SubscriptionDeliveryKey, inputKey, \"change-delivery-key\");\n const deliveryId = yield* validate(Digest, inputDeliveryId, \"change-delivery-id\");\n const change = yield* validate(DeliveryChange, inputChange, \"change-delivery-change\");\n yield* requirePartition(key.subscription.partition, \"change-delivery-partition\");\n const result = yield* transact(\n Effect.gen(function* () {\n const existing = yield* readDelivery(key, \"change delivery\");\n const record = yield* readRegistration(key.subscription, \"change delivery subscription\");\n if (existing === null || record === null)\n return yield* error(\"not-found\", existing === null ? \"delivery\" : \"subscription\");\n yield* failpoint.hit(`subscription:delivery-${change._tag.toLowerCase()}:before`);\n const effectiveChange =\n change._tag === \"Prepare\"\n ? { ...change, nowMillis: Math.max(change.nowMillis, yield* Clock.currentTimeMillis) }\n : change;\n const transition = applySubscriptionDeliveryChange(\n existing,\n record,\n deliveryId,\n effectiveChange,\n );\n if (Result.isFailure(transition)) return yield* transition.failure;\n if (transition.success === existing) return { value: existing, changed: false } as const;\n yield* writeDelivery(transition.success);\n return { value: transition.success, changed: true } as const;\n }),\n );\n if (result.changed)\n yield* failpoint.hit(`subscription:delivery-${change._tag.toLowerCase()}:after`);\n return result.value;\n });\n\n const recovering: SubscriptionStore[\"Service\"][\"recovering\"] = Effect.fn(\n \"SqliteSubscriptionStore.recovering\",\n )(function* (nowMillis, after, limit) {\n const rows = yield* query(\n sql<Record<string, unknown>>`\n SELECT owner_id, subscription_id, ordinal FROM effect_agent_subscriptions\n WHERE tenant_id=${partition.tenantId} AND source_address=${partition.address} AND state='active'\n AND recovery_at_millis IS NOT NULL AND recovery_at_millis<=${nowMillis} AND ordinal>${after}\n ORDER BY ordinal LIMIT ${limit}\n `,\n \"recovering subscriptions\",\n );\n const rowSchema = Schema.Struct({\n owner_id: Schema.String,\n subscription_id: Schema.String,\n ordinal: Schema.Natural,\n });\n return yield* decodeRows(rowSchema, rows, \"recovering subscription keys\").pipe(\n Effect.map((items) =>\n items.map((item) => ({\n key: { partition, ownerId: item.owner_id, subscriptionId: item.subscription_id },\n ordinal: item.ordinal,\n })),\n ),\n );\n });\n\n const deferRecovery: SubscriptionStore[\"Service\"][\"deferRecovery\"] = Effect.fn(\n \"SqliteSubscriptionStore.deferRecovery\",\n )(function* (input, recovery) {\n const key = yield* requireKey(input, \"defer-recovery-key\");\n yield* transact(\n Effect.gen(function* () {\n const record = yield* readRegistration(key, \"defer recovery\");\n if (record === null) return yield* error(\"not-found\", \"subscription\");\n yield* failpoint.hit(\"subscription:defer-recovery:before\");\n yield* writeRegistration({\n ...record,\n recovery: record.state === \"active\" ? recovery : null,\n });\n }),\n );\n yield* failpoint.hit(\"subscription:defer-recovery:after\");\n });\n\n const readScanCursors: SubscriptionStore[\"Service\"][\"readScanCursors\"] = Effect.gen(function* () {\n const rows = yield* query(\n sql<Record<string, unknown>>`\n SELECT event_scan_cursor, delivery_scan_cursor, recovery_scan_cursor\n FROM effect_agent_subscription_sequences\n WHERE tenant_id=${partition.tenantId} AND source_address=${partition.address}\n `,\n \"read subscription scan cursors\",\n );\n const decoded = yield* decodeRows(ScanRow, rows, \"read subscription scan cursors\");\n if (decoded.length !== 1) return yield* corrupt(\"subscription scan cursors\");\n return {\n events: decoded[0].event_scan_cursor,\n deliveries: decoded[0].delivery_scan_cursor,\n recovery: decoded[0].recovery_scan_cursor,\n };\n });\n\n const advanceScanCursors: SubscriptionStore[\"Service\"][\"advanceScanCursors\"] = Effect.fn(\n \"SqliteSubscriptionStore.advanceScanCursors\",\n )(function* (input) {\n const cursors = yield* validate(SubscriptionScanCursors, input, \"scan-cursors\");\n yield* transact(\n Effect.gen(function* () {\n yield* failpoint.hit(\"subscription:advance-scan-cursors:before\");\n yield* query(\n sql<Record<string, unknown>>`\n UPDATE effect_agent_subscription_sequences\n SET event_scan_cursor=${cursors.events}, delivery_scan_cursor=${cursors.deliveries}, recovery_scan_cursor=${cursors.recovery}\n WHERE tenant_id=${partition.tenantId} AND source_address=${partition.address}\n `,\n \"advance subscription scan cursors\",\n );\n }),\n );\n yield* failpoint.hit(\"subscription:advance-scan-cursors:after\");\n });\n\n const indexedDeadline = query(\n sql<Record<string, unknown>>`\n SELECT MIN(deadline) AS deadline FROM (\n SELECT next_attempt_at_millis AS deadline FROM effect_agent_subscription_events\n WHERE tenant_id=${partition.tenantId} AND source_address=${partition.address} AND routing_complete=0\n UNION ALL SELECT next_attempt_at_millis FROM effect_agent_subscription_deliveries\n WHERE tenant_id=${partition.tenantId} AND source_address=${partition.address} AND state NOT IN ('delivered','refused')\n UNION ALL SELECT recovery_at_millis FROM effect_agent_subscriptions\n WHERE tenant_id=${partition.tenantId} AND source_address=${partition.address} AND state='active' AND recovery_at_millis IS NOT NULL\n )\n `,\n \"next subscription deadline\",\n ).pipe(\n Effect.flatMap((rows) =>\n decodeRows(\n Schema.Struct({ deadline: Schema.NullOr(Schema.Number) }),\n rows,\n \"next subscription deadline\",\n ),\n ),\n Effect.flatMap((rows) =>\n rows.length === 1\n ? Effect.succeed(rows[0].deadline)\n : Effect.fail(corrupt(\"next subscription deadline\")),\n ),\n );\n\n const nextDeadline = Effect.gen(function* () {\n const cursors = yield* readScanCursors;\n if (cursors.events !== \"\" || cursors.deliveries !== \"\" || cursors.recovery !== 0) return 0;\n return yield* indexedDeadline;\n });\n\n const prearm = Effect.fn(\"DoSubscriptionStore.prearm\")(function* (deadlineAtMillis: number) {\n yield* transactions.run((replace) => replaceAlarm(replace, deadlineAtMillis));\n yield* failpoint.hit(\"subscription:prearm:after\");\n });\n const reconcile = Effect.gen(function* () {\n yield* transactions.run((replace) =>\n Effect.gen(function* () {\n yield* replaceAlarm(replace, yield* readIndexedDeadline());\n }),\n );\n yield* failpoint.hit(\"subscription:reconcile:after\");\n });\n\n return Context.make(SubscriptionStore, {\n partition,\n register,\n get,\n list,\n cancel,\n accept,\n event,\n pendingEvents,\n candidates,\n select,\n catchUp,\n deferEvent,\n delivery,\n pendingDeliveries,\n listDeliveries,\n changeDelivery,\n recovering,\n deferRecovery,\n readScanCursors,\n advanceScanCursors,\n nextDeadline,\n }).pipe(Context.add(DoSubscriptionAlarmControl, { prearm, reconcile }));\n});\n\nexport const doSubscriptionStoreLayer = (\n partition: SourcePartition,\n): Layer.Layer<\n SubscriptionStore | DoSubscriptionAlarmControl,\n SubscriptionError,\n DoSubscriptionTransaction | SqlClientService.SqlClient\n> => Layer.effectContext(makeSubscriptionStore(partition));\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 ThreadExport,\n ThreadExportRequest,\n ThreadMaterialization,\n ThreadNotMaterialized,\n ThreadRead,\n ThreadStoreError,\n ThreadTail,\n ThreadTailRequest,\n FenceRejected,\n FencedAppendRequest,\n JoinedToHost,\n LedgerError,\n MarkReadyRequest,\n SettlementConflict,\n SubmissionLookup,\n SubmissionLookupByKey,\n SubmissionSnapshot,\n} from \"@effect-agent/thread\";\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 thread ports. One Thread's\n * Durable Object executes another Thread'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 Thread (parent/child establishment, status checks, abort propagation,\n * child-settlement notification, and the child-thread 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`/`ThreadStoreError` 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`/`ThreadStoreError`),\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 `ThreadStore.materialize` against the owning Object. */\nexport class StoreMaterializeCall extends Schema.TaggedClass<StoreMaterializeCall>(\n \"@effect-agent/storage-cloudflare/StoreMaterializeCall\",\n)(\"StoreMaterialize\", {\n request: ThreadMaterialization,\n}) {}\n\n/** Routed `ThreadStore.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 `ThreadStore.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: ThreadRead,\n}) {}\n\n/** Routed `ThreadStore.inspectTail` against the owning Object. */\nexport class StoreInspectTailCall extends Schema.TaggedClass<StoreInspectTailCall>(\n \"@effect-agent/storage-cloudflare/StoreInspectTailCall\",\n)(\"StoreInspectTail\", {\n request: ThreadTailRequest,\n}) {}\n\n/** Routed `ThreadStore.export` against the owning Object. */\nexport class StoreExportCall extends Schema.TaggedClass<StoreExportCall>(\n \"@effect-agent/storage-cloudflare/StoreExportCall\",\n)(\"StoreExport\", {\n request: ThreadExportRequest,\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: ThreadTail,\n}) {}\n\nexport class StoreExportResult extends Schema.TaggedClass<StoreExportResult>(\n \"@effect-agent/storage-cloudflare/StoreExportResult\",\n)(\"StoreExportResult\", {\n export: ThreadExport,\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 * thread 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 ThreadStoreError,\n ThreadNotMaterialized,\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 AdmissionConflict,\n AppendConflict,\n ChildAttachmentSnapshot,\n ThreadMaterialization,\n ThreadNotMaterialized,\n ThreadStore,\n ThreadStoreError,\n FenceRejected,\n JoinedToHost,\n LedgerError,\n RecoverySnapshot,\n SettlementConflict,\n SubmissionLedger,\n SubmissionLookupById,\n type SubmissionLookupByKey,\n type SubmissionSnapshot,\n} from \"@effect-agent/thread\";\nimport { Context, Effect, Layer, Option, Predicate, 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 ThreadId = ThreadMaterialization[\"threadId\"];\ntype SubmissionId = SubmissionSnapshot[\"submissionId\"];\n\nconst ThreadIdSchema = ThreadMaterialization.fields.threadId;\nconst decodeThreadId = Schema.decodeUnknownEffect(ThreadIdSchema);\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 * Thread'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\nconst safeTransportDiagnostic = (cause: unknown): string => {\n try {\n const message = cause instanceof Error ? cause.message : cause;\n return boundPortDiagnostic(typeof message === \"string\" ? message : String(message));\n } catch {\n return \"[unavailable transport diagnostic]\";\n }\n};\n\nconst transportRetryableSignal = (cause: unknown): boolean | undefined => {\n if (!Predicate.isObjectKeyword(cause)) return undefined;\n try {\n const signal = Reflect.get(cause, \"retryable\");\n return typeof signal === \"boolean\" ? signal : undefined;\n } catch {\n return undefined;\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 retryable = transportRetryableSignal(cause);\n return PortTransportError.make({\n target,\n message: safeTransportDiagnostic(cause),\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 * Thread (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(threadId)`; 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 ThreadPortTransport extends Context.Service<\n ThreadPortTransport,\n {\n readonly call: (\n threadId: ThreadId,\n request: PortRequestEnvelope,\n ) => Effect.Effect<unknown, PortTransportError>;\n }\n>()(\"@effect-agent/storage-cloudflare/ThreadPortTransport\") {}\n\n/** Construction options shared by both routed port Layers. */\nexport interface RoutedPortOptions {\n /**\n * The Thread this Durable Object owns (the Object identity rule is\n * `namespace.idFromName(threadId)`). Requests addressed here execute on the local\n * facet; requests addressed anywhere else route through the transport or fail fast typed.\n */\n readonly localThreadId: ThreadId;\n}\n\n/** Where one port request must execute. */\ntype RouteTarget =\n | { readonly _tag: \"local\" }\n | { readonly _tag: \"foreign\"; readonly threadId: ThreadId };\n\nconst LOCAL: RouteTarget = { _tag: \"local\" };\n\n/**\n * Parse a DC-minted routable Submission identity — `{uuidv7}:{threadId}`, split at the\n * FIRST `:` because the Thread 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 localThreadId: ThreadId,\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 === localThreadId) return LOCAL;\n return yield* decodeThreadId(tail).pipe(\n Effect.map((threadId): RouteTarget => ({ _tag: \"foreign\", threadId })),\n Effect.orElseSucceed(() => LOCAL),\n );\n });\n\nconst NoAdditionalPortFailure = Schema.Never;\nconst AbortPortFailure = Schema.Union([SettlementConflict, JoinedToHost]);\nconst AppendPortFailure = Schema.Union([ThreadNotMaterialized, AppendConflict, FenceRejected]);\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 crossThreadLedgerError = (operation: string, target: string): LedgerError =>\n LedgerError.make({\n operation,\n message:\n `${operation} addressed to foreign Thread ${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 Thread's Durable Object.\",\n });\n\nconst crossThreadStoreError = (operation: string, target: string): ThreadStoreError =>\n ThreadStoreError.make({\n operation,\n message:\n `${operation} addressed to foreign Thread ${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 Thread's Durable Object.\",\n });\n\nconst makeTransportCall = (transport: ThreadPortTransport[\"Service\"]) =>\n Effect.fn(\"DoPortRouting.transportCall\")(function* (target: ThreadId, 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* ThreadPortTransport;\n const transportCall: TransportCall = makeTransportCall(transport);\n const submissionTarget = routableSubmissionTarget(options.localThreadId);\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 Thread 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 = <ResultSchema extends Schema.Top, FailureSchema extends Schema.Top>(\n operation: string,\n target: ThreadId,\n call: PortRequest,\n resultSchema: ResultSchema,\n failureSchema: FailureSchema,\n ): Effect.Effect<ResultSchema[\"Type\"], FailureSchema[\"Type\"] | LedgerError> => {\n const isExpectedResult = Schema.is(resultSchema);\n const isExpectedFailure = Schema.is(failureSchema);\n return transportCall(target, call).pipe(\n Effect.mapError(routeFailure(operation, target)),\n Effect.flatMap(\n (response): Effect.Effect<ResultSchema[\"Type\"], FailureSchema[\"Type\"] | LedgerError> => {\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 Thread 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 (!isExpectedResult(result)) {\n return Effect.fail(\n LedgerError.make({\n operation,\n message:\n `The Thread Object owning ${target} answered ${operation} with the ` +\n `mismatched result ${result._tag}.`,\n }),\n );\n }\n return Effect.succeed(result);\n },\n ),\n Effect.withSpan(\"DoPortRouting.foreignLedgerCall\", {\n attributes: { operation, target },\n }),\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: ThreadId,\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 Thread 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 Thread 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 Thread 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 Thread 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: ThreadId,\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 NoAdditionalPortFailure,\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.threadId, 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.threadId === options.localThreadId\n ? local.admit(request)\n : foreignLedgerCall(\n \"ledger admit\",\n request.threadId,\n LedgerAdmitCall.make({ request }),\n LedgerAdmitResult,\n AdmissionConflict,\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.threadId,\n LedgerMarkReadyCall.make({ request }),\n LedgerMarkReadyResult,\n NoAdditionalPortFailure,\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.threadId, request.submissionId),\n ),\n )\n : request.threadId === options.localThreadId\n ? local.lookup(request)\n : foreignLedgerCall(\n \"ledger lookup\",\n request.threadId,\n LedgerLookupCall.make({ request }),\n LedgerLookupResult,\n NoAdditionalPortFailure,\n ).pipe(\n Effect.map((result) =>\n result.submission === undefined ? Option.none() : Option.some(result.submission),\n ),\n ),\n\n resolveAdmission: (request) =>\n request.threadId === options.localThreadId\n ? local.resolveAdmission(request)\n : resolveForeignAdmission(request.threadId, 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.threadId,\n LedgerRequestAbortCall.make({ request }),\n LedgerRequestAbortResult,\n AbortPortFailure,\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.threadId,\n LedgerRecordChildSettledCall.make({ request }),\n LedgerRecordChildSettledResult,\n NoAdditionalPortFailure,\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.threadId === options.localThreadId\n ? local.claim(request)\n : Effect.fail(crossThreadLedgerError(\"ledger claim\", request.threadId)),\n\n claimJoining: (request) =>\n request.threadId === options.localThreadId\n ? local.claimJoining(request)\n : Effect.fail(crossThreadLedgerError(\"ledger claim joining\", request.threadId)),\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(crossThreadLedgerError(\"ledger renew ownership\", target.threadId)),\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(crossThreadLedgerError(\"ledger release ownership\", target.threadId)),\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(crossThreadLedgerError(\"ledger mark input applied\", target.threadId)),\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(crossThreadLedgerError(\"ledger reserve settlement\", target.threadId)),\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(crossThreadLedgerError(\"ledger finalize settlement\", target.threadId)),\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(crossThreadLedgerError(\"ledger mark joined\", target.threadId)),\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(crossThreadLedgerError(\"ledger revert joining\", target.threadId)),\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(crossThreadLedgerError(\"ledger suspend\", target.threadId)),\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 crossThreadLedgerError(\"ledger record approval decision\", target.threadId),\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(crossThreadLedgerError(\"ledger mark unknown\", target.threadId)),\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 crossThreadLedgerError(\"ledger record unknown resolution\", target.threadId),\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(crossThreadLedgerError(\"ledger reserve child budget\", target.threadId)),\n ),\n ),\n\n // Reservation identities carry no Thread 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 Thread 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(crossThreadLedgerError(\"ledger load recovery snapshot\", target.threadId)),\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* ThreadStore;\n const checkpoints = local.checkpoints;\n const transport = yield* ThreadPortTransport;\n const transportCall: TransportCall = makeTransportCall(transport);\n\n const routeFailure =\n (operation: string, target: string) =>\n (error: PortTransportError | PortProtocolError): ThreadStoreError =>\n ThreadStoreError.make({\n operation,\n message: boundPortDiagnostic(\n `Routed ${operation} to the Thread Object owning ${target} failed: ${error.message}`,\n ),\n cause: error,\n });\n\n /** The store twin of `foreignLedgerCall` with `ThreadStoreError` as the base error. */\n const foreignStoreCall = <ResultSchema extends Schema.Top, FailureSchema extends Schema.Top>(\n operation: string,\n target: ThreadId,\n call: PortRequest,\n resultSchema: ResultSchema,\n failureSchema: FailureSchema,\n ): Effect.Effect<ResultSchema[\"Type\"], FailureSchema[\"Type\"] | ThreadStoreError> => {\n const isExpectedResult = Schema.is(resultSchema);\n const isExpectedFailure = Schema.is(failureSchema);\n return transportCall(target, call).pipe(\n Effect.mapError(routeFailure(operation, target)),\n Effect.flatMap(\n (\n response,\n ): Effect.Effect<ResultSchema[\"Type\"], FailureSchema[\"Type\"] | ThreadStoreError> => {\n if (response._tag === \"PortFailed\") {\n const failure = response.failure;\n if (isExpectedFailure(failure)) return Effect.fail(failure);\n if (failure._tag === \"ThreadStoreError\") return Effect.fail(failure);\n return Effect.fail(\n ThreadStoreError.make({\n operation,\n message: boundPortDiagnostic(\n `The Thread 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 (!isExpectedResult(result)) {\n return Effect.fail(\n ThreadStoreError.make({\n operation,\n message:\n `The Thread Object owning ${target} answered ${operation} with the ` +\n `mismatched result ${result._tag}.`,\n }),\n );\n }\n return Effect.succeed(result);\n },\n ),\n Effect.withSpan(\"DoPortRouting.foreignStoreCall\", {\n attributes: { operation, target },\n }),\n );\n };\n\n const routed = ThreadStore.of({\n materialize: (request) =>\n request.threadId === options.localThreadId\n ? local.materialize(request)\n : foreignStoreCall(\n \"thread materialize\",\n request.threadId,\n StoreMaterializeCall.make({ request }),\n StoreMaterializeResult,\n FenceRejected,\n ).pipe(Effect.asVoid),\n\n append: (request) =>\n request.threadId === options.localThreadId\n ? local.append(request)\n : foreignStoreCall(\n \"thread append\",\n request.threadId,\n StoreAppendCall.make({ request }),\n StoreAppendResult,\n AppendPortFailure,\n ).pipe(Effect.map((reply) => reply.result)),\n\n read: (request) =>\n request.threadId === options.localThreadId\n ? local.read(request)\n : Stream.unwrap(\n foreignStoreCall(\n \"thread read\",\n request.threadId,\n StoreReadPageCall.make({ request }),\n StoreReadPageResult,\n ThreadNotMaterialized,\n ).pipe(Effect.map((reply) => Stream.fromIterable(reply.records))),\n ),\n\n inspectTail: (request) =>\n request.threadId === options.localThreadId\n ? local.inspectTail(request)\n : foreignStoreCall(\n \"thread inspect tail\",\n request.threadId,\n StoreInspectTailCall.make({ request }),\n StoreInspectTailResult,\n ThreadNotMaterialized,\n ).pipe(Effect.map((reply) => reply.tail)),\n\n export: (request) =>\n request.threadId === options.localThreadId\n ? local.export(request)\n : foreignStoreCall(\n \"thread export\",\n request.threadId,\n StoreExportCall.make({ request }),\n StoreExportResult,\n ThreadNotMaterialized,\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.threadId === options.localThreadId\n ? local.observe(request)\n : Stream.unwrap(Effect.fail(crossThreadStoreError(\"thread observe\", request.threadId))),\n\n ...(checkpoints === undefined\n ? {}\n : {\n checkpoints: {\n save: (request) =>\n request.checkpoint.threadId === options.localThreadId\n ? checkpoints.save(request)\n : Effect.fail(\n crossThreadStoreError(\"thread save checkpoint\", request.checkpoint.threadId),\n ),\n load: (request) =>\n request.threadId === options.localThreadId\n ? checkpoints.load(request)\n : Effect.fail(crossThreadStoreError(\"thread load checkpoint\", request.threadId)),\n },\n }),\n });\n\n return Context.make(ThreadStore, routed);\n});\n\n/**\n * Routing decorator over the LOCAL `SubmissionLedger` facet (plan §1.3): a request addressing\n * this Object's Thread executes locally; a route-capable request addressing another\n * Thread is Schema-encoded onto the `ThreadPortTransport` 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 | ThreadPortTransport> =>\n Layer.effectContext(makeRoutedLedgerServices(options));\n\n/**\n * Routing decorator over the LOCAL `ThreadStore` facet (plan §1.3): this-thread\n * requests execute locally; foreign materialize/append/read/inspectTail/export travel the\n * transport; foreign observation and checkpoints fail fast typed.\n */\nexport const routedThreadStoreLayer = (\n options: RoutedPortOptions,\n): Layer.Layer<ThreadStore, never, ThreadStore | ThreadPortTransport> =>\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 Thread, 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 | ThreadStore> {\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* ThreadStore;\n return yield* capture(\n store.materialize(request.request).pipe(Effect.map(() => StoreMaterializeResult.make({}))),\n );\n }\n case \"StoreAppend\": {\n const store = yield* ThreadStore;\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* ThreadStore;\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* ThreadStore;\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* ThreadStore;\n return yield* capture(\n store\n .export(request.request)\n .pipe(Effect.map((threadExport) => StoreExportResult.make({ export: threadExport }))),\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* (encoded: unknown): Effect.fn.Return<unknown, never, SubmissionLedger | ThreadStore> {\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,cAAmC,OAAO,YAA2B,CAAC,CAAC,iBAAiB;CACtF,OAAO,O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