@effect-agent/storage-sqlite 0.1.0-beta.6 → 0.1.0-beta.60
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/SqliteActivityStore.d.mts +14 -0
- package/dist/SqliteActivityStore.mjs +310 -0
- package/dist/SqliteActivityStore.mjs.map +1 -0
- package/dist/SqliteMessageDeliveryStore.d.mts +14 -0
- package/dist/SqliteMessageDeliveryStore.mjs +24 -0
- package/dist/SqliteMessageDeliveryStore.mjs.map +1 -0
- package/dist/SqliteScheduleStore.d.mts +14 -0
- package/dist/SqliteScheduleStore.mjs +255 -0
- package/dist/SqliteScheduleStore.mjs.map +1 -0
- package/dist/SqliteStorageConfig.d.mts +34 -0
- package/dist/SqliteStorageConfig.mjs +39 -0
- package/dist/SqliteStorageConfig.mjs.map +1 -0
- package/dist/SqliteStorageError-CzKmwCLl.d.mts +86 -0
- package/dist/SqliteStorageError.d.mts +2 -0
- package/dist/SqliteStorageError.mjs +148 -0
- package/dist/SqliteStorageError.mjs.map +1 -0
- package/dist/SqliteStorageFailpoint.d.mts +17 -0
- package/dist/SqliteStorageFailpoint.mjs +14 -0
- package/dist/SqliteStorageFailpoint.mjs.map +1 -0
- package/dist/SqliteStorageFailpointTesting.d.mts +15 -0
- package/dist/SqliteStorageFailpointTesting.mjs +19 -0
- package/dist/SqliteStorageFailpointTesting.mjs.map +1 -0
- package/dist/SqliteStorageVersion-gA7_96xM.d.mts +9 -0
- package/dist/SqliteStorageVersion.d.mts +2 -0
- package/dist/SqliteStorageVersion.mjs +8 -0
- package/dist/SqliteStorageVersion.mjs.map +1 -0
- package/dist/SqliteSubmissionLedger.d.mts +23 -0
- package/dist/SqliteSubmissionLedger.mjs +1765 -0
- package/dist/SqliteSubmissionLedger.mjs.map +1 -0
- package/dist/SqliteSubscriptionStore.d.mts +13 -0
- package/dist/SqliteSubscriptionStore.mjs +28 -0
- package/dist/SqliteSubscriptionStore.mjs.map +1 -0
- package/dist/SqliteThreadStore.d.mts +49 -0
- package/dist/SqliteThreadStore.mjs +427 -0
- package/dist/SqliteThreadStore.mjs.map +1 -0
- package/dist/index.d.mts +11 -193
- package/dist/index.mjs +11 -3082
- package/dist/migrations-dnTR0RKq.mjs +326 -0
- package/dist/migrations-dnTR0RKq.mjs.map +1 -0
- package/dist/rolldown-runtime-D7D4PA-g.mjs +13 -0
- package/dist/sqlite-journal-lDduEakl.mjs +887 -0
- package/dist/sqlite-journal-lDduEakl.mjs.map +1 -0
- package/package.json +1 -41
- package/src/SqliteActivityStore.ts +556 -0
- package/src/SqliteMessageDeliveryStore.ts +42 -0
- package/src/SqliteScheduleStore.ts +404 -0
- package/src/{sqlite-storage-config.ts → SqliteStorageConfig.ts} +1 -1
- package/src/{errors.ts → SqliteStorageError.ts} +8 -3
- package/src/SqliteStorageFailpoint.ts +23 -0
- package/src/{sqlite-storage-failpoint.ts → SqliteStorageFailpointTesting.ts} +7 -18
- package/src/SqliteStorageVersion.ts +2 -0
- package/src/{sqlite-ledger.ts → SqliteSubmissionLedger.ts} +753 -118
- package/src/SqliteSubscriptionStore.ts +59 -0
- package/src/{sqlite-conversation-store.ts → SqliteThreadStore.ts} +372 -302
- package/src/index.ts +10 -6
- package/src/internal/message-delivery-schema.ts +24 -0
- package/src/{migrations.ts → internal/migrations.ts} +145 -79
- package/src/{sqlite-journal.ts → internal/sqlite-journal.ts} +534 -222
- package/dist/index.mjs.map +0 -1
package/dist/index.mjs.map
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"index.mjs","names":["BoundedStoredText","BoundedIdentifier","noFailpoint","makeServices","SqlClientService","SqlClientService"],"sources":["../src/errors.ts","../src/migrations.ts","../src/sqlite-journal.ts","../src/sqlite-storage-config.ts","../src/sqlite-storage-failpoint.ts","../src/sqlite-conversation-store.ts","../src/sqlite-ledger.ts"],"sourcesContent":["import { CanonicalSequence, ProducerEpoch } from \"@effect-agent/session\";\nimport { Schema } from \"effect\";\n\n/** The SQLite file uses a private-development format this adapter cannot read. */\nexport class SqliteStorageCompatibilityError extends Schema.TaggedError<SqliteStorageCompatibilityError>()(\n \"SqliteStorageCompatibilityError\",\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 SqliteStorageCorruptionError extends Schema.TaggedError<SqliteStorageCorruptionError>()(\n \"SqliteStorageCorruptionError\",\n {\n message: Schema.String,\n rowKey: Schema.String,\n table: Schema.String,\n },\n) {}\n\n/** SQLite infrastructure failed while opening or operating the store. */\nexport class SqliteStorageError extends Schema.TaggedError<SqliteStorageError>()(\n \"SqliteStorageError\",\n {\n cause: Schema.optionalKey(Schema.Defect()),\n message: Schema.String,\n operation: Schema.String,\n },\n) {}\n\n/**\n * SQLite infrastructure failed while operating the Submission Ledger. Surfaces at the\n * SubmissionLedger port as the typed `LedgerError` with this error preserved as its cause,\n * so the adapter-level tag is never erased.\n */\nexport class SqliteLedgerError extends Schema.TaggedError<SqliteLedgerError>()(\n \"SqliteLedgerError\",\n {\n cause: Schema.optionalKey(Schema.Defect()),\n message: Schema.String,\n operation: Schema.String,\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 SqliteAppendConflict extends Schema.TaggedError<SqliteAppendConflict>()(\n \"SqliteAppendConflict\",\n {\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/**\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 SqliteFenceRejected extends Schema.TaggedError<SqliteFenceRejected>()(\n \"SqliteFenceRejected\",\n {\n actualEpoch: ProducerEpoch,\n message: Schema.String,\n producerEpoch: ProducerEpoch,\n },\n) {}\n\n/**\n * A write transaction could not acquire the SQLite write lock within the configured busy\n * timeout (SQLITE_BUSY / SQLITE_LOCKED). Another transiently coexisting owner is writing;\n * the operation did not mutate canonical state and is safe to retry.\n */\nexport class SqliteWriteContention extends Schema.TaggedError<SqliteWriteContention>()(\n \"SqliteWriteContention\",\n {\n cause: Schema.optionalKey(Schema.Defect()),\n message: Schema.String,\n operation: Schema.String,\n },\n) {}\n\n/** A checkpoint conflicts with a previously stored checkpoint at the same offset. */\nexport class SqliteCheckpointConflict extends Schema.TaggedError<SqliteCheckpointConflict>()(\n \"SqliteCheckpointConflict\",\n {\n message: Schema.String,\n },\n) {}\n\nexport const SqliteStorageFailpointLocation = 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 SqliteStorageFailpointLocation = typeof SqliteStorageFailpointLocation.Type;\n\n/** Deterministic test-only fault or pause injected at a SQLite operation boundary. */\nexport class SqliteStorageFailpointError extends Schema.TaggedError<SqliteStorageFailpointError>()(\n \"SqliteStorageFailpointError\",\n {\n location: SqliteStorageFailpointLocation,\n },\n) {\n override get message() {\n return `Injected SQLite storage failure at ${this.location}.`;\n }\n}\n","import { SqliteMigrator } from \"@effect/sql-sqlite-node\";\nimport { Effect } from \"effect\";\nimport * as SqlClient from \"effect/unstable/sql/SqlClient\";\n\nexport const CurrentSqliteStorageVersion = 4;\n\nexport const sqliteMigrations = SqliteMigrator.fromRecord({\n \"1_current_persistent_conversation_foundation\": 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 yield* sql`PRAGMA user_version = 1`.withoutTransform;\n }),\n \"2_durable_submission_ledger\": Effect.gen(function* () {\n const sql = yield* SqlClient.SqlClient;\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 UNIQUE (conversation_id, principal, idempotency_key),\n UNIQUE (conversation_id, queue_sequence)\n )\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`PRAGMA user_version = 2`.withoutTransform;\n }),\n \"3_durable_tools_and_joined_input\": Effect.gen(function* () {\n const sql = yield* SqlClient.SqlClient;\n\n // Joined queued input (plan §2.5, DUR-016): a joining/joined Submission records which host\n // Run claimed it. The canonical input marker reuses input_applied_record_id/_sequence\n // because the joined input IS the Submission's own canonical `input:{sid}` record.\n yield* sql`\n ALTER TABLE effect_agent_submissions\n ADD COLUMN joined_host_submission_id TEXT\n `.withoutTransform;\n\n // Durable approval suspension (plan §2.6): the reason is the Schema-encoded\n // SuspensionReason union so later suspension families stay additive.\n yield* sql`\n ALTER TABLE effect_agent_submissions\n ADD COLUMN suspended_reason_json TEXT\n `.withoutTransform;\n yield* sql`\n ALTER TABLE effect_agent_submissions\n ADD COLUMN suspended_at TEXT\n `.withoutTransform;\n\n // Unknown Outcome marking (DUR-009/DUR-017): the marked open Tool Call identities are\n // stored so `recordUnknownResolution` can reopen the lane only when every marked call\n // has a durable resolution intent.\n yield* sql`\n ALTER TABLE effect_agent_submissions\n ADD COLUMN unknown_reason TEXT\n `.withoutTransform;\n yield* sql`\n ALTER TABLE effect_agent_submissions\n ADD COLUMN unknown_tool_call_ids_json TEXT\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 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`PRAGMA user_version = 3`.withoutTransform;\n }),\n \"4_durable_subagents\": Effect.gen(function* () {\n const sql = yield* SqlClient.SqlClient;\n\n // Durable attached children (spec §12, SUB-004): a child Submission records its immutable\n // parent linkage at admission; the parent-side index serves the recovery attachment view.\n yield* sql`\n ALTER TABLE effect_agent_submissions\n ADD COLUMN parent_submission_id TEXT\n `.withoutTransform;\n yield* sql`\n ALTER TABLE effect_agent_submissions\n ADD COLUMN parent_tool_call_id TEXT\n `.withoutTransform;\n yield* sql`\n CREATE INDEX effect_agent_submissions_parent\n ON effect_agent_submissions (parent_submission_id)\n `.withoutTransform;\n\n // Parent-owned child budget reservations (spec §12 steps 2 and 6, SUB-010): generic\n // opaque-payload state-machine rows (D8) — allocation and accounting are Schema-encoded\n // JSON documents the adapter never interprets; status moves\n // reserved → releasePending → released, applied exactly once.\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 yield* sql`PRAGMA user_version = 4`.withoutTransform;\n }),\n});\n","import { CanonicalSequence, ProducerEpoch } from \"@effect-agent/session\";\nimport { SqliteMigrator } from \"@effect/sql-sqlite-node\";\nimport { Effect, Exit, Schema } from \"effect\";\nimport * as SqlClient from \"effect/unstable/sql/SqlClient\";\nimport type { SqlError } from \"effect/unstable/sql/SqlError\";\n\nimport {\n SqliteAppendConflict,\n SqliteCheckpointConflict,\n SqliteFenceRejected,\n SqliteStorageCompatibilityError,\n SqliteStorageCorruptionError,\n SqliteStorageError,\n SqliteStorageFailpointError,\n SqliteWriteContention,\n type SqliteStorageFailpointLocation,\n} from \"./errors.ts\";\nimport { CurrentSqliteStorageVersion, sqliteMigrations } from \"./migrations.ts\";\n\nconst BoundedStoredText = Schema.String.check(Schema.isMaxLength(16 * 1024 * 1024));\nconst BoundedIdentifier = Schema.NonEmptyString.check(Schema.isMaxLength(1024));\nconst NonNegativeInt = Schema.Int.check(Schema.isGreaterThanOrEqualTo(0));\nconst MAX_RECORDS_PER_CONVERSATION = 65_536;\nconst MAX_STORED_TEXT_BYTES = 16 * 1024 * 1024;\nconst MAX_IDENTIFIER_LENGTH = 1_024;\n\nconst storedTextBytes = (value: string): number => new TextEncoder().encode(value).byteLength;\n\nclass SqliteVersionRow extends Schema.Class<SqliteVersionRow>(\"SqliteVersionRow\")({\n user_version: NonNegativeInt,\n}) {}\n\nclass SqliteJournalModeRow extends Schema.Class<SqliteJournalModeRow>(\"SqliteJournalModeRow\")({\n journal_mode: Schema.NonEmptyString.check(Schema.isMaxLength(32)),\n}) {}\n\nclass SqliteNameRow extends Schema.Class<SqliteNameRow>(\"SqliteNameRow\")({\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>(\"@effect-agent/storage-sqlite/RawRecord\")({\n recordId: BoundedIdentifier,\n recordJson: BoundedStoredText,\n}) {}\n\nexport class RawAppendRequest extends Schema.Class<RawAppendRequest>(\n \"@effect-agent/storage-sqlite/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-sqlite/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-sqlite/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-sqlite/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-sqlite/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 | SqliteAppendConflict\n | SqliteFenceRejected\n | SqliteStorageCorruptionError\n | SqliteStorageError\n | SqliteStorageFailpointError\n | SqliteWriteContention;\n\ntype CheckpointError =\n | SqliteCheckpointConflict\n | SqliteStorageCorruptionError\n | SqliteStorageError\n | SqliteWriteContention;\ntype SqliteJournalFailpoint = (\n location: SqliteStorageFailpointLocation,\n) => Effect.Effect<void, SqliteStorageFailpointError>;\n\nconst noFailpoint: SqliteJournalFailpoint = () => Effect.void;\n\nconst storageError =\n (operation: string) =>\n (error: SqlError): SqliteStorageError =>\n SqliteStorageError.make({\n cause: error,\n operation,\n message: error.message,\n });\n\n/** Decode raw SQLite rows against a Schema, reporting failures as typed corruption. */\nexport const decodeRows = Effect.fn(\"SqliteJournal.decodeRows\")(\n <A, I>(\n schema: Schema.Codec<ReadonlyArray<A>, ReadonlyArray<I>>,\n table: string,\n rowKey: string,\n rows: unknown,\n ): Effect.Effect<ReadonlyArray<A>, SqliteStorageCorruptionError> =>\n Schema.decodeUnknownEffect(schema)(rows).pipe(\n Effect.mapError((error) =>\n SqliteStorageCorruptionError.make({\n table,\n rowKey,\n message: String(error),\n }),\n ),\n ),\n);\n\n/** Decode exactly one raw SQLite row against a Schema, reporting failures as typed corruption. */\nexport const decodeSingleRow = Effect.fn(\"SqliteJournal.decodeSingleRow\")(\n <A, I>(\n schema: Schema.Codec<ReadonlyArray<A>, ReadonlyArray<I>>,\n table: string,\n rowKey: string,\n rows: unknown,\n ): Effect.Effect<A, SqliteStorageCorruptionError> =>\n decodeRows(schema, table, rowKey, rows).pipe(\n Effect.flatMap((decoded) =>\n decoded.length === 1\n ? Effect.succeed(decoded[0])\n : Effect.fail(\n SqliteStorageCorruptionError.make({\n table,\n rowKey,\n message: `Expected exactly one row but found ${decoded.length}.`,\n }),\n ),\n ),\n ),\n);\n\nconst ensureCurrentStorage = Effect.fn(\"SqliteJournal.ensureCurrentStorage\")(function* (\n sql: SqlClient.SqlClient,\n failpoint: SqliteJournalFailpoint = noFailpoint,\n busyTimeoutMillis = 5_000,\n) {\n yield* sql`PRAGMA foreign_keys = ON`.pipe(Effect.mapError(storageError(\"enable foreign keys\")));\n // PRAGMA statements do not accept bound parameters; the value is a schema-validated\n // non-negative integer, never caller-controlled text.\n yield* sql\n .unsafe(`PRAGMA busy_timeout = ${busyTimeoutMillis}`)\n .pipe(Effect.mapError(storageError(\"configure busy timeout\")));\n const journalModeRows = yield* sql<Record<string, unknown>>`PRAGMA journal_mode`.pipe(\n Effect.mapError(storageError(\"read journal mode\")),\n );\n const journalMode = yield* decodeSingleRow(\n Schema.Array(SqliteJournalModeRow),\n \"pragma_journal_mode\",\n \"singleton\",\n journalModeRows,\n );\n if (journalMode.journal_mode.toLowerCase() !== \"wal\") {\n return yield* SqliteStorageCompatibilityError.make({\n actualVersion: 0,\n supportedVersion: CurrentSqliteStorageVersion,\n message: `SQLite WAL mode is required; the database reported ${journalMode.journal_mode}.`,\n });\n }\n\n const versionRows = yield* sql<Record<string, unknown>>`PRAGMA user_version`.pipe(\n Effect.mapError(storageError(\"read storage version\")),\n );\n const version = yield* decodeSingleRow(\n Schema.Array(SqliteVersionRow),\n \"pragma_user_version\",\n \"singleton\",\n versionRows,\n );\n\n // D7: the storage version must match EXACTLY (or be 0 for a fresh file). Older\n // private-development versions fail closed with reset guidance rather than being\n // migrated, and newer versions fail closed rather than being decoded incorrectly.\n if (version.user_version !== 0 && version.user_version !== CurrentSqliteStorageVersion) {\n return yield* SqliteStorageCompatibilityError.make({\n actualVersion: version.user_version,\n supportedVersion: CurrentSqliteStorageVersion,\n message:\n `The SQLite file uses private-development storage version ${version.user_version}; ` +\n `this build supports exactly version ${CurrentSqliteStorageVersion}. ` +\n \"Reset the database file explicitly; automatic stored-data migrations are not provided during private development.\",\n });\n }\n\n if (version.user_version === 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(SqliteNameRow),\n \"sqlite_master\",\n \"effect_agent_%\",\n existingRows,\n );\n\n if (existing.length > 0) {\n return yield* SqliteStorageCompatibilityError.make({\n actualVersion: 0,\n supportedVersion: CurrentSqliteStorageVersion,\n message:\n \"The SQLite file contains unversioned Effect Agent tables. Reset it explicitly; refusing to mutate ambiguous stored data.\",\n });\n }\n\n yield* SqliteMigrator.run({ loader: sqliteMigrations }).pipe(\n // SqliteMigrator depends on the generic client supplied by this adapter.\n // The concrete Node client is kept at the outer Layer boundary.\n Effect.provideService(SqlClient.SqlClient, sql),\n Effect.mapError((error) =>\n SqliteStorageError.make({\n cause: error,\n operation: \"initialize current storage\",\n message: error.message,\n }),\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 (\n 'effect_agent_conversations',\n 'effect_agent_canonical_batches',\n 'effect_agent_canonical_records',\n 'effect_agent_checkpoints',\n 'effect_agent_submissions',\n 'effect_agent_submission_ownership',\n 'effect_agent_attempts',\n 'effect_agent_settlement_reservations',\n 'effect_agent_abort_intents',\n 'effect_agent_approval_decisions',\n 'effect_agent_unknown_resolutions'\n )\n ORDER BY name\n `.pipe(Effect.mapError(storageError(\"verify storage tables\")));\n const required = yield* decodeRows(\n Schema.Array(SqliteNameRow),\n \"sqlite_master\",\n \"required_tables\",\n requiredRows,\n );\n if (required.length !== 11) {\n return yield* SqliteStorageCompatibilityError.make({\n actualVersion: CurrentSqliteStorageVersion,\n supportedVersion: CurrentSqliteStorageVersion,\n message:\n \"The SQLite file claims the current format but is missing required tables. Reset the corrupt private-development data.\",\n });\n }\n\n return makeJournal(sql, failpoint);\n});\n\nconst makeJournal = (sql: SqlClient.SqlClient, failpoint: SqliteJournalFailpoint) => {\n const classifyWriteFailure =\n (operation: string) =>\n (error: SqlError): SqliteStorageError | SqliteWriteContention =>\n error.reason._tag === \"LockTimeoutError\"\n ? SqliteWriteContention.make({\n cause: error,\n operation,\n message: `Another producer holds the SQLite write lock; ${operation} is safe to retry.`,\n })\n : storageError(operation)(error);\n\n /**\n * Runs one journal write transaction under `BEGIN IMMEDIATE`. SQLite's deferred `BEGIN`\n * would let a read-then-write transaction start as a reader and fail with\n * SQLITE_BUSY_SNAPSHOT on upgrade, which `busy_timeout` never retries. Taking the write\n * lock up front keeps cross-owner contention inside the bounded busy retry; a lock\n * timeout is classified as the retryable SqliteWriteContention. A failed `BEGIN` leaves\n * no transaction, so no rollback is attempted for it.\n *\n * Journal write transactions are always top level. Nesting one inside another would\n * deadlock the single-connection client, so new journal operations must not wrap this\n * helper inside another transaction.\n */\n const withWriteTransaction =\n (operation: string) =>\n <A, E>(\n effect: Effect.Effect<A, E>,\n ): Effect.Effect<A, E | SqliteStorageError | SqliteWriteContention> =>\n Effect.uninterruptibleMask((restore) =>\n Effect.scoped(\n Effect.gen(function* () {\n const connection = yield* sql.reserve.pipe(\n Effect.mapError(classifyWriteFailure(operation)),\n );\n yield* connection\n .executeUnprepared(\"BEGIN IMMEDIATE\", [], undefined)\n .pipe(Effect.mapError(classifyWriteFailure(operation)));\n const exit = yield* restore(\n Effect.provideService(effect, sql.transactionService, [connection, 0] as const),\n ).pipe(Effect.exit);\n if (Exit.isSuccess(exit)) {\n yield* connection\n .executeUnprepared(\"COMMIT\", [], undefined)\n .pipe(Effect.mapError(classifyWriteFailure(operation)));\n return exit.value;\n }\n yield* Effect.orDie(connection.executeUnprepared(\"ROLLBACK\", [], undefined));\n return yield* exit;\n }),\n ).pipe(\n Effect.withSpan(\"SqliteJournal.withWriteTransaction\", { attributes: { operation } }),\n ),\n );\n\n /**\n * Runs a read-only snapshot under a deferred transaction. Effect's SQLite client now\n * starts every writable-client `withTransaction` with `BEGIN IMMEDIATE`, which is the\n * right default for mutations but would make exports take the write lock and block a\n * concurrent append. Reserving the connection and beginning explicitly preserves the\n * adapter's snapshot-with-concurrent-writer contract. As with the write helper, a failed\n * `BEGIN` is reported directly because there is no transaction to roll back.\n */\n const withReadTransaction =\n (operation: string) =>\n <A, E>(effect: Effect.Effect<A, E>): Effect.Effect<A, E | SqliteStorageError> =>\n Effect.uninterruptibleMask((restore) =>\n Effect.scoped(\n Effect.gen(function* () {\n const connection = yield* sql.reserve.pipe(Effect.mapError(storageError(operation)));\n yield* connection\n .executeUnprepared(\"BEGIN\", [], undefined)\n .pipe(Effect.mapError(storageError(operation)));\n const exit = yield* restore(\n Effect.provideService(effect, sql.transactionService, [connection, 0] as const),\n ).pipe(Effect.exit);\n if (Exit.isSuccess(exit)) {\n yield* connection\n .executeUnprepared(\"COMMIT\", [], undefined)\n .pipe(Effect.mapError(storageError(operation)));\n return exit.value;\n }\n yield* Effect.orDie(connection.executeUnprepared(\"ROLLBACK\", [], undefined));\n return yield* exit;\n }),\n ).pipe(Effect.withSpan(\"SqliteJournal.withReadTransaction\", { attributes: { operation } })),\n );\n\n const materialize = Effect.fn(\"SqliteJournal.materialize\")(function* (\n conversationId: string,\n createdAt: string,\n emptyTailDigest: string,\n producerEpoch: ProducerEpoch,\n ): Effect.fn.Return<\n void,\n SqliteFenceRejected | SqliteStorageCorruptionError | SqliteStorageError | SqliteWriteContention\n > {\n if (\n conversationId.length > MAX_IDENTIFIER_LENGTH ||\n storedTextBytes(emptyTailDigest) > MAX_STORED_TEXT_BYTES\n ) {\n return yield* SqliteStorageError.make({\n operation: \"materialize conversation\",\n message: \"Conversation identity or initial digest exceeds the SQLite storage bounds.\",\n });\n }\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* SqliteStorageCorruptionError.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* SqliteFenceRejected.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(\"SqliteJournal.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(\"SqliteJournal.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 storedTextBytes(request.batchJson) > MAX_STORED_TEXT_BYTES ||\n storedTextBytes(request.batchDigest) > MAX_STORED_TEXT_BYTES ||\n storedTextBytes(request.tailDigest) > MAX_STORED_TEXT_BYTES ||\n request.records.some(\n (record) =>\n record.recordId.length > MAX_IDENTIFIER_LENGTH ||\n storedTextBytes(record.recordJson) > MAX_STORED_TEXT_BYTES,\n )\n ) {\n return yield* SqliteStorageError.make({\n operation: \"append canonical batch\",\n message: \"Canonical identifiers or encoded JSON exceed the SQLite storage bounds.\",\n });\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* SqliteAppendConflict.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* SqliteFenceRejected.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* SqliteStorageCorruptionError.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* SqliteAppendConflict.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* SqliteAppendConflict.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* SqliteStorageError.make({\n operation: \"append canonical batch\",\n message: `Conversation record limit ${MAX_RECORDS_PER_CONVERSATION} would be exceeded.`,\n });\n }\n\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(recordIds)}\n ORDER BY sequence\n `.pipe(Effect.mapError(storageError(\"check canonical record identities\")));\n const existingRecords = yield* decodeRows(\n Schema.Array(RecordRow),\n \"effect_agent_canonical_records\",\n `${request.conversationId}/record_ids`,\n existingRecordRows,\n );\n if (existingRecords.length > 0) {\n return yield* SqliteAppendConflict.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 SqliteStorageError.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 SqliteStorageError.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(\"SqliteJournal.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(\"SqliteJournal.exportConversation\")(function* (\n conversationId: string,\n ) {\n return yield* withReadTransaction(\"export 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 = ${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 });\n\n const saveCheckpoint = Effect.fn(\"SqliteJournal.saveCheckpoint\")(function* (\n checkpoint: RawCheckpoint,\n ): Effect.fn.Return<void, CheckpointError> {\n if (\n checkpoint.conversationId.length > MAX_IDENTIFIER_LENGTH ||\n storedTextBytes(checkpoint.checkpointJson) > MAX_STORED_TEXT_BYTES\n ) {\n return yield* SqliteStorageError.make({\n operation: \"save checkpoint\",\n message: \"Checkpoint identity or encoded JSON exceeds the SQLite storage bounds.\",\n });\n }\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* SqliteCheckpointConflict.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* SqliteStorageCorruptionError.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* SqliteCheckpointConflict.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(\"SqliteJournal.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(\"SqliteJournal.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(\"SqliteJournal.scanStoredPayloads\")(function* () {\n return yield* withReadTransaction(\"startup scan transaction\")(\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 });\n\n return {\n append,\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 SqliteJournal = ReturnType<typeof makeJournal>;\n\nexport const initializeSqliteJournal = ensureCurrentStorage;\n","import { Context, Schema } from \"effect\";\n\nconst ObservationPollInterval = Schema.Int.check(Schema.isGreaterThanOrEqualTo(0));\nconst BusyTimeoutMillis = Schema.Int.check(Schema.isGreaterThanOrEqualTo(0));\nconst OwnershipLeaseMillis = Schema.Int.check(Schema.isGreaterThan(0));\n\n/**\n * Validated construction configuration consumed by the SQLite storage Layer. The database\n * identity itself belongs to the SqlClient Layer; duplicating it here could silently diverge\n * from the connection actually in use.\n */\nexport class SqliteStorageConfigValue extends Schema.Class<SqliteStorageConfigValue>(\n \"@effect-agent/storage-sqlite/SqliteStorageConfigValue\",\n)({\n observationPollInterval: ObservationPollInterval,\n /** Bounded SQLITE_BUSY retry window for write-lock acquisition, in milliseconds. */\n busyTimeout: BusyTimeoutMillis,\n /**\n * Submission ownership lease duration in milliseconds (D5). The lease is a liveness hint\n * that makes an abandoned claim reclaimable; correctness never depends on it because every\n * canonical append is fenced by producer epoch. Convenience layers default this to\n * `DEFAULT_OWNERSHIP_LEASE_DURATION` from `@effect-agent/session`.\n */\n ownershipLeaseDuration: OwnershipLeaseMillis,\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 SQLite storage configuration authority. */\nexport class SqliteStorageConfig extends Context.Service<\n SqliteStorageConfig,\n SqliteStorageConfigValue\n>()(\"@effect-agent/storage-sqlite/SqliteStorageConfig\") {}\n","import { Context, Effect, Layer, Ref } from \"effect\";\n\nimport { SqliteStorageFailpointError, type SqliteStorageFailpointLocation } from \"./errors.ts\";\n\nexport type SqliteStorageFailpointHandler = (\n location: SqliteStorageFailpointLocation,\n) => Effect.Effect<void, SqliteStorageFailpointError>;\n\nconst noFailpoint: SqliteStorageFailpointHandler = () => Effect.void;\n\n/** Test-only control for replacing the active SQLite failpoint handler. */\nexport class SqliteStorageFailpointTestControl extends Context.Service<\n SqliteStorageFailpointTestControl,\n {\n readonly clear: Effect.Effect<void>;\n readonly setHandler: (handler: SqliteStorageFailpointHandler) => Effect.Effect<void>;\n }\n>()(\"@effect-agent/storage-sqlite/SqliteStorageFailpointTestControl\") {}\n\n/** Explicit fault-injection authority used at SQLite operation boundaries. */\nexport class SqliteStorageFailpoint extends Context.Service<\n SqliteStorageFailpoint,\n {\n readonly hit: SqliteStorageFailpointHandler;\n }\n>()(\"@effect-agent/storage-sqlite/SqliteStorageFailpoint\") {\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<SqliteStorageFailpointHandler>(noFailpoint);\n return Context.make(\n SqliteStorageFailpoint,\n SqliteStorageFailpoint.of({\n hit: (location) => Ref.get(handler).pipe(Effect.flatMap((current) => current(location))),\n }),\n ).pipe(\n Context.add(\n SqliteStorageFailpointTestControl,\n SqliteStorageFailpointTestControl.of({\n clear: Ref.set(handler, noFailpoint),\n setHandler: (next) => Ref.set(handler, next),\n }),\n ),\n );\n }),\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 { NodeCrypto } from \"@effect/platform-node\";\nimport { SqliteClient } from \"@effect/sql-sqlite-node\";\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 SqliteAppendConflict,\n SqliteCheckpointConflict,\n SqliteFenceRejected,\n type SqliteStorageFailpointLocation,\n SqliteStorageCompatibilityError,\n SqliteStorageCorruptionError,\n SqliteStorageError,\n} from \"./errors.ts\";\nimport {\n initializeSqliteJournal,\n RawAppendRequest,\n RawCheckpoint,\n RawReadRequest,\n type SqliteJournal,\n} from \"./sqlite-journal.ts\";\nimport { SqliteStorageConfig, SqliteStorageConfigValue } from \"./sqlite-storage-config.ts\";\nimport {\n SqliteStorageFailpoint,\n type SqliteStorageFailpointHandler,\n} from \"./sqlite-storage-failpoint.ts\";\n\nexport interface SqliteStorageOptions {\n readonly filename: string;\n readonly observationPollInterval?: number | undefined;\n /** Bounded SQLITE_BUSY retry window for write-lock acquisition, in milliseconds. */\n readonly busyTimeout?: 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 * 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?: SqliteStorageFailpointHandler | undefined;\n}\n\nexport type SqliteStorageInitializationError =\n | SqliteStorageCompatibilityError\n | SqliteStorageCorruptionError\n | SqliteStorageError;\n\nconst OffsetText = Schema.String.check(Schema.isMaxLength(4 * 1024));\nconst SQLITE_OFFSET_PREFIX = \"effect-agent-sqlite@1:\";\nconst ZERO_CANONICAL_SEQUENCE = Schema.decodeSync(CanonicalSequence)(0);\nconst isDigest = Schema.is(Digest);\n\nconst storeError = (operation: string, error: { readonly message: string }) =>\n ConversationStoreError.make({\n cause: error,\n operation,\n message: error.message,\n });\n\nconst schemaStoreError = (operation: string, error: { readonly message: string }) =>\n ConversationStoreError.make({\n cause: error,\n operation,\n message: error.message,\n });\n\nconst makeOffset = Effect.fn(\"SqliteConversationStore.makeOffset\")(function* (\n conversationId: ConversationMaterialization[\"conversationId\"],\n sequence: number,\n): Effect.fn.Return<ObservationOffset, ConversationStoreError> {\n return yield* Schema.decodeUnknownEffect(CanonicalSequence)(sequence).pipe(\n Effect.flatMap((validatedSequence) =>\n Schema.decodeUnknownEffect(ObservationOffset)(\n `${SQLITE_OFFSET_PREFIX}${encodeURIComponent(conversationId)}:${validatedSequence}`,\n ),\n ),\n Effect.mapError((error) => schemaStoreError(\"encode observation offset\", error)),\n );\n});\n\nconst parseOffset = Effect.fn(\"SqliteConversationStore.parseOffset\")(function* (\n conversationId: ConversationMaterialization[\"conversationId\"],\n offset: ObservationOffset | undefined,\n): Effect.fn.Return<CanonicalSequence, ConversationStoreError> {\n if (offset === undefined) return ZERO_CANONICAL_SEQUENCE;\n const text = yield* Schema.decodeUnknownEffect(OffsetText)(offset).pipe(\n Effect.mapError((error) => schemaStoreError(\"decode observation offset\", error)),\n );\n const conversationPrefix = `${SQLITE_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: SqliteFenceRejected,\n) =>\n FenceRejected.make({\n conversationId,\n actualEpoch: error.actualEpoch,\n attemptedEpoch: error.producerEpoch,\n });\n\nconst encodeCanonicalRecord = Effect.fn(\"SqliteConversationStore.encodeCanonicalRecord\")(function* (\n record: CanonicalRecord,\n): Effect.fn.Return<string, ConversationStoreError> {\n return yield* Schema.encodeEffect(Schema.fromJsonString(CanonicalRecord))(record).pipe(\n Effect.mapError((error) => schemaStoreError(\"encode canonical record\", error)),\n );\n});\n\nconst encodeCanonicalBatch = Effect.fn(\"SqliteConversationStore.encodeCanonicalBatch\")(function* (\n batch: CanonicalBatch,\n): Effect.fn.Return<string, ConversationStoreError> {\n return yield* Schema.encodeEffect(Schema.fromJsonString(CanonicalBatch))(batch).pipe(\n Effect.mapError((error) => schemaStoreError(\"encode canonical batch\", error)),\n );\n});\n\nconst encodeCheckpoint = Effect.fn(\"SqliteConversationStore.encodeCheckpoint\")(function* (\n checkpoint: ConversationCheckpoint,\n): Effect.fn.Return<string, ConversationStoreError> {\n return yield* Schema.encodeEffect(Schema.fromJsonString(ConversationCheckpoint))(checkpoint).pipe(\n Effect.mapError((error) => schemaStoreError(\"encode checkpoint\", error)),\n );\n});\n\nconst decodeEnvelope = Effect.fn(\"SqliteConversationStore.decodeEnvelope\")(function* (row: {\n readonly batch_id: string;\n readonly conversation_id: string;\n readonly record_json: string;\n readonly sequence: CanonicalSequence;\n}) {\n const record = yield* Schema.decodeEffect(Schema.fromJsonString(CanonicalRecord))(\n row.record_json,\n ).pipe(\n Effect.mapError((error) =>\n ConversationStoreError.make({\n operation: \"decode canonical record\",\n message: error.message,\n }),\n ),\n );\n const conversationId = yield* Schema.decodeUnknownEffect(\n CanonicalRecordEnvelope.fields.conversationId,\n )(row.conversation_id).pipe(\n Effect.mapError((error) => schemaStoreError(\"decode conversation identity\", error)),\n );\n const offset = yield* makeOffset(conversationId, row.sequence);\n const batchId = yield* Schema.decodeUnknownEffect(CanonicalRecordEnvelope.fields.batchId)(\n row.batch_id,\n ).pipe(Effect.mapError((error) => schemaStoreError(\"decode batch identity\", error)));\n return CanonicalRecordEnvelope.make({\n conversationId,\n batchId,\n sequence: row.sequence,\n offset,\n record,\n });\n});\n\nconst decodeCheckpoint = Effect.fn(\"SqliteConversationStore.decodeCheckpoint\")(function* (\n checkpointJson: string,\n): Effect.fn.Return<ConversationCheckpoint, ConversationStoreError> {\n return yield* Schema.decodeEffect(Schema.fromJsonString(ConversationCheckpoint))(\n checkpointJson,\n ).pipe(Effect.mapError((error) => schemaStoreError(\"decode checkpoint\", error)));\n});\n\nconst requireConversation = Effect.fn(\"SqliteConversationStore.requireConversation\")(function* (\n journal: SqliteJournal,\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(\"SqliteConversationStore.tailDigestAt\")(function* (\n journal: SqliteJournal,\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(\"SqliteConversationStore.decodeStartupPayloads\")(function* (\n journal: SqliteJournal,\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 SqliteStorageCorruptionError.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 SqliteStorageCorruptionError.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 SqliteStorageCorruptionError.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* SqliteStorageCorruptionError.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 SqliteStorageCorruptionError.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* SqliteStorageCorruptionError.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* SqliteStorageCorruptionError.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 SqliteStorageCorruptionError.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 SqliteStorageCorruptionError.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* SqliteStorageCorruptionError.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* SqliteStorageCorruptionError.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* SqliteStorageCorruptionError.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* SqliteStorageCorruptionError.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(\"SqliteConversationStore.makeServices\")(function* () {\n const config = yield* SqliteStorageConfig;\n const failpoint = yield* SqliteStorageFailpoint;\n const sql = yield* SqlClientService.SqlClient;\n const crypto = yield* Crypto.Crypto;\n const journal = yield* initializeSqliteJournal(sql, failpoint.hit, config.busyTimeout);\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(\"SqliteConversationStore.hitFailpoint\")(\n (location: SqliteStorageFailpointLocation): 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 \"SqliteConversationStore.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 === \"SqliteFenceRejected\"\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(\n \"SqliteConversationStore.append\",\n )(function* (request: FencedAppendRequest) {\n const validated = yield* Schema.decodeUnknownEffect(Schema.toType(FencedAppendRequest))(\n request,\n ).pipe(Effect.mapError((error) => schemaStoreError(\"validate canonical append\", error)));\n yield* requireConversation(journal, validated.conversationId);\n const tailDigest = yield* provideCrypto(\n digestCanonicalBatch(validated.expectedTailDigest, validated.batch),\n ).pipe(Effect.mapError((error) => storeError(\"digest canonical append\", error)));\n const batchJson = yield* encodeCanonicalBatch(validated.batch);\n const rawRecords = yield* Effect.forEach(validated.batch.records, (record) =>\n encodeCanonicalRecord(record).pipe(\n Effect.map((recordJson) => ({\n recordId: record.recordId,\n recordJson,\n })),\n ),\n );\n const rawRequest = yield* Schema.decodeUnknownEffect(RawAppendRequest)({\n conversationId: validated.conversationId,\n batchId: validated.batch.batchId,\n batchDigest: tailDigest,\n batchJson,\n expectedTailSequence: validated.expectedTailSequence,\n expectedTailDigest: validated.expectedTailDigest,\n producerEpoch: validated.producerEpoch,\n records: rawRecords,\n tailDigest,\n }).pipe(Effect.mapError((error) => schemaStoreError(\"encode canonical append\", error)));\n yield* hitFailpoint(\"append:before\");\n const result = yield* journal.append(rawRequest).pipe(\n Effect.mapError((error) => {\n if (error instanceof SqliteFenceRejected) {\n return mapFence(validated.conversationId, error);\n }\n if (error instanceof SqliteAppendConflict) {\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 const loadRecords = Effect.fn(\"SqliteConversationStore.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(\"SqliteConversationStore.read\")(function* (\n request: ConversationRead,\n ) {\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(\"SqliteConversationStore.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(\"SqliteConversationStore.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 \"SqliteConversationStore.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 \"SqliteConversationStore.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 \"SqliteConversationStore.saveCheckpoint\",\n )(function* (request: SaveCheckpointRequest) {\n const validated = yield* Schema.decodeUnknownEffect(Schema.toType(SaveCheckpointRequest))(\n request,\n ).pipe(Effect.mapError((error) => schemaStoreError(\"validate checkpoint\", error)));\n const conversation = yield* requireConversation(journal, validated.checkpoint.conversationId);\n if (validated.checkpoint.throughSequence > conversation.tail_sequence) {\n return yield* CheckpointRejected.make({\n conversationId: validated.checkpoint.conversationId,\n reason: \"ahead-of-tail\",\n });\n }\n const canonicalDigest = yield* tailDigestAt(\n journal,\n validated.checkpoint.conversationId,\n validated.checkpoint.throughSequence,\n );\n if (canonicalDigest !== validated.checkpoint.tailDigest) {\n return yield* CheckpointRejected.make({\n conversationId: validated.checkpoint.conversationId,\n reason: \"digest-mismatch\",\n });\n }\n const checkpointJson = yield* encodeCheckpoint(validated.checkpoint);\n const raw = RawCheckpoint.make({\n conversationId: validated.checkpoint.conversationId,\n throughSequence: validated.checkpoint.throughSequence,\n tailDigest: validated.checkpoint.tailDigest,\n checkpointJson,\n });\n yield* hitFailpoint(\"save-checkpoint:before\");\n yield* journal.saveCheckpoint(raw).pipe(\n Effect.mapError((error) =>\n error instanceof SqliteCheckpointConflict\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 \"SqliteConversationStore.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 * SQLite Conversation Store implementation with configuration, failpoint, SQL, and Crypto\n * authority kept visible in its input channel.\n */\nexport const conversationStoreLayer: Layer.Layer<\n ConversationStore,\n SqliteStorageInitializationError,\n SqliteStorageConfig | SqliteStorageFailpoint | SqlClientService.SqlClient | Crypto.Crypto\n> = Layer.effectContext(makeServices());\n\n/**\n * Validated SQLite storage configuration Layer with the documented defaults applied. Shared\n * by the ConversationStore and SubmissionLedger convenience layers so their defaults cannot\n * drift.\n */\nexport const storageConfigLayer = (\n options: SqliteStorageOptions,\n): Layer.Layer<SqliteStorageConfig, SqliteStorageError> =>\n Layer.effect(SqliteStorageConfig)(\n Schema.decodeUnknownEffect(SqliteStorageConfigValue)({\n observationPollInterval: options.observationPollInterval ?? 25,\n busyTimeout: options.busyTimeout ?? 5_000,\n ownershipLeaseDuration:\n options.ownershipLeaseDuration ?? Duration.toMillis(DEFAULT_OWNERSHIP_LEASE_DURATION),\n verifyOnOpen: options.verifyOnOpen ?? false,\n }).pipe(\n Effect.mapError((error) =>\n SqliteStorageError.make({\n cause: error,\n operation: \"configure SQLite 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: SqliteStorageOptions,\n): Layer.Layer<SqliteStorageFailpoint> =>\n options.failpoint === undefined\n ? SqliteStorageFailpoint.layer\n : Layer.succeed(SqliteStorageFailpoint)({ hit: options.failpoint });\n\n/**\n * A composition-root convenience Layer for canonical Conversations. Durable accepted work is\n * served by the separate SubmissionLedger port.\n */\nexport const layer = (\n options: SqliteStorageOptions,\n): Layer.Layer<ConversationStore, SqliteStorageInitializationError> => {\n const sqlLayer = SqliteClient.layer({ filename: options.filename });\n return conversationStoreLayer.pipe(\n Layer.provide(\n Layer.mergeAll(\n storageConfigLayer(options),\n storageFailpointLayer(options),\n sqlLayer,\n NodeCrypto.layer,\n ),\n ),\n );\n};\n\n/** Create an adapter-owned resumable observation offset for a known canonical sequence. */\nexport const observationOffsetAt = makeOffset;\n","import {\n AbortCommand,\n AbortIntent,\n AdmissionAdmitted,\n AdmissionConflict,\n AdmissionNotAdmitted,\n AdmissionRequest,\n AdmissionResult,\n ApprovalConflict,\n ApprovalDecision,\n ApprovalDecisionCommand,\n ApprovalDecisionIntent,\n AttachChildToReservationRequest,\n BeginChildBudgetReleaseRequest,\n CanonicalSequence,\n ChildAttachmentSnapshot,\n ChildBudgetReservationRequest,\n ChildBudgetReservationSnapshot,\n ChildReservationConflict,\n ChildReservationStatus,\n ChildSettledNotification,\n Claim,\n ClaimJoiningRequest,\n ClaimRequest,\n DefinitionDigests,\n Digest,\n EMPTY_TAIL_DIGEST,\n InputAppliedMarker,\n JoinSnapshot,\n JoinedToHost,\n JoiningClaim,\n LedgerCapabilities,\n LedgerError,\n MarkInputAppliedRequest,\n MarkJoinedRequest,\n MarkReadyRequest,\n MarkUnknownRequest,\n OwnershipLost,\n OwnershipRenewal,\n OwnershipSnapshot,\n ParentLinkage,\n PersistedJson,\n ProducerEpoch,\n QueueSequence,\n RecordEnvelope,\n RecoverySnapshot,\n RecoverySnapshotRequest,\n ReleaseChildBudgetRequest,\n ReleaseOwnershipRequest,\n RenewOwnershipRequest,\n ReservedChildBudget,\n ReservedSettlement,\n RevertJoiningRequest,\n Settlement,\n SettlementConflict,\n SettlementFinalization,\n SettlementOutcome,\n SettlementReservation,\n SubmissionLedger,\n SubmissionLookup,\n SubmissionLookupByKey,\n SubmissionSnapshot,\n SubmissionState,\n SettlementReservationSnapshot,\n SuspendRequest,\n SuspensionReason,\n SuspensionSnapshot,\n UnknownResolution,\n UnknownResolutionCommand,\n UnknownResolutionConflict,\n UnknownResolutionIntent,\n submissionAbortRecordId,\n type ChildSettledOutcome,\n type SuspensionOutcome,\n} from \"@effect-agent/session\";\nimport { NodeCrypto } from \"@effect/platform-node\";\nimport { SqliteClient } from \"@effect/sql-sqlite-node\";\nimport { Clock, Context, Crypto, DateTime, Effect, Layer, Option, Schema, Stream } from \"effect\";\nimport * as SqlClientService from \"effect/unstable/sql/SqlClient\";\nimport type { SqlError } from \"effect/unstable/sql/SqlError\";\n\nimport {\n SqliteLedgerError,\n SqliteStorageCorruptionError,\n SqliteStorageError,\n SqliteWriteContention,\n type SqliteStorageFailpointLocation,\n} from \"./errors.ts\";\nimport {\n storageConfigLayer,\n storageFailpointLayer,\n type SqliteStorageInitializationError,\n type SqliteStorageOptions,\n} from \"./sqlite-conversation-store.ts\";\nimport { decodeRows, initializeSqliteJournal } from \"./sqlite-journal.ts\";\nimport { SqliteStorageConfig } from \"./sqlite-storage-config.ts\";\nimport { SqliteStorageFailpoint } from \"./sqlite-storage-failpoint.ts\";\n\ntype SubmissionId = SubmissionSnapshot[\"submissionId\"];\n\nconst BoundedStoredText = Schema.String.check(Schema.isMaxLength(16 * 1024 * 1024));\nconst BoundedIdentifier = Schema.NonEmptyString.check(Schema.isMaxLength(1024));\nconst BoundedTimestamp = Schema.NonEmptyString.check(Schema.isMaxLength(128));\n\nconst SCAN_PAGE_SIZE = 256;\nconst EPOCH_ZERO = Schema.decodeSync(ProducerEpoch)(0);\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 ApprovalDecisionRow extends Schema.Class<ApprovalDecisionRow>(\"ApprovalDecisionRow\")({\n submission_id: BoundedIdentifier,\n tool_call_id: BoundedIdentifier,\n decision: ApprovalDecision,\n resolver: BoundedIdentifier,\n reason: BoundedStoredText,\n decided_at: BoundedTimestamp,\n}) {}\n\nclass UnknownResolutionRow extends Schema.Class<UnknownResolutionRow>(\"UnknownResolutionRow\")({\n submission_id: BoundedIdentifier,\n tool_call_id: BoundedIdentifier,\n author: BoundedIdentifier,\n reason: BoundedStoredText,\n resolution_json: BoundedStoredText,\n resolved_at: BoundedTimestamp,\n}) {}\n\nclass OwnershipRow extends Schema.Class<OwnershipRow>(\"OwnershipRow\")({\n submission_id: BoundedIdentifier,\n attempt_id: BoundedIdentifier,\n ownership_token: BoundedIdentifier,\n producer_epoch: ProducerEpoch,\n owner_producer_id: BoundedIdentifier,\n lease_expires_at: BoundedTimestamp,\n}) {}\n\nclass ReservationRow extends Schema.Class<ReservationRow>(\"ReservationRow\")({\n submission_id: BoundedIdentifier,\n settlement_id: BoundedIdentifier,\n outcome: SettlementOutcome,\n record_id: BoundedIdentifier,\n record_json: BoundedStoredText,\n record_digest: Digest,\n reserved_at: BoundedTimestamp,\n finalized_at: Schema.NullOr(BoundedTimestamp),\n}) {}\n\nclass AbortIntentRow extends Schema.Class<AbortIntentRow>(\"AbortIntentRow\")({\n submission_id: BoundedIdentifier,\n author: BoundedIdentifier,\n reason: BoundedStoredText,\n requested_at: BoundedTimestamp,\n canonical_record_id: Schema.NullOr(BoundedIdentifier),\n}) {}\n\nclass MaxQueueSequenceRow extends Schema.Class<MaxQueueSequenceRow>(\"MaxQueueSequenceRow\")({\n max_queue_sequence: Schema.Int.check(Schema.isGreaterThanOrEqualTo(0)),\n}) {}\n\nclass CanonicalRecordIdRow extends Schema.Class<CanonicalRecordIdRow>(\"CanonicalRecordIdRow\")({\n record_id: BoundedIdentifier,\n}) {}\n\nconst SUBMISSION_COLUMNS = `\n submission_id,\n conversation_id,\n queue_sequence,\n principal,\n idempotency_key,\n agent_id,\n agent_digests_json,\n deployment_id,\n input_json,\n input_digest,\n receipt_id,\n state,\n settled_outcome,\n created_at,\n ready_at,\n input_applied_record_id,\n input_applied_sequence,\n joined_host_submission_id,\n suspended_reason_json,\n suspended_at,\n unknown_reason,\n unknown_tool_call_ids_json,\n parent_submission_id,\n parent_tool_call_id\n`;\n\nconst CHILD_RESERVATION_COLUMNS = `\n reservation_id,\n parent_submission_id,\n parent_tool_call_id,\n child_submission_id,\n status,\n allocation_json,\n allocation_digest,\n accounting_json,\n reserved_at,\n release_began_at,\n released_at\n`;\n\n/** The branded ToolCallId schema, reached through the session port so no core import is needed. */\nconst ToolCallIdSchema = ApprovalDecisionCommand.fields.toolCallId;\nconst ToolCallIdList = Schema.Array(ToolCallIdSchema);\n\nconst encodePersistedJsonText = Schema.encodeEffect(Schema.fromJsonString(PersistedJson));\nconst encodeDefinitionDigestsText = Schema.encodeEffect(Schema.fromJsonString(DefinitionDigests));\nconst encodeRecordEnvelopeText = Schema.encodeEffect(Schema.fromJsonString(RecordEnvelope));\nconst decodeRecordEnvelopeText = Schema.decodeEffect(Schema.fromJsonString(RecordEnvelope));\nconst encodeSuspensionReasonText = Schema.encodeEffect(Schema.fromJsonString(SuspensionReason));\nconst encodeUnknownResolutionText = Schema.encodeEffect(Schema.fromJsonString(UnknownResolution));\nconst encodeToolCallIdsText = Schema.encodeEffect(Schema.fromJsonString(ToolCallIdList));\nconst decodeToolCallIdsText = Schema.decodeEffect(Schema.fromJsonString(ToolCallIdList));\nconst parseStoredJsonText = Schema.decodeEffect(Schema.fromJsonString(Schema.Json));\nconst decodeAdmissionResult = Schema.decodeUnknownEffect(AdmissionResult);\nconst decodeClaim = Schema.decodeUnknownEffect(Claim);\nconst decodeOwnershipRenewal = Schema.decodeUnknownEffect(OwnershipRenewal);\nconst decodeSettlement = Schema.decodeUnknownEffect(Settlement);\nconst decodeAbortIntent = Schema.decodeUnknownEffect(AbortIntent);\nconst decodeOwnershipSnapshot = Schema.decodeUnknownEffect(OwnershipSnapshot);\nconst decodeInputAppliedMarker = Schema.decodeUnknownEffect(InputAppliedMarker);\nconst decodeSubmissionSnapshotUnknown = Schema.decodeUnknownEffect(SubmissionSnapshot);\nconst decodeSubmissionId = Schema.decodeUnknownEffect(SubmissionSnapshot.fields.submissionId);\nconst decodeQueueSequence = Schema.decodeUnknownEffect(QueueSequence);\nconst decodeUtcInstant = Schema.decodeUnknownEffect(Schema.DateTimeUtcFromString);\nconst decodeJoiningClaim = Schema.decodeUnknownEffect(JoiningClaim);\nconst decodeJoinSnapshot = Schema.decodeUnknownEffect(JoinSnapshot);\nconst decodeSuspensionSnapshot = Schema.decodeUnknownEffect(SuspensionSnapshot);\nconst decodeApprovalDecisionIntent = Schema.decodeUnknownEffect(ApprovalDecisionIntent);\nconst decodeUnknownResolutionIntent = Schema.decodeUnknownEffect(UnknownResolutionIntent);\nconst decodeParentLinkage = Schema.decodeUnknownEffect(ParentLinkage);\nconst decodeChildReservationSnapshotUnknown = Schema.decodeUnknownEffect(\n ChildBudgetReservationSnapshot,\n);\nconst decodeChildAttachmentSnapshot = Schema.decodeUnknownEffect(ChildAttachmentSnapshot);\n\n/** Wrap an adapter-internal failure into the port's LedgerError without erasing its tag. */\nconst internalFailure =\n (operation: string) =>\n (error: { readonly message: string }): LedgerError =>\n LedgerError.make({ operation, message: error.message, cause: error });\n\n/** Classify raw SQL failures: write-lock timeouts stay retryable typed contention. */\nconst sqlFailure =\n (operation: string) =>\n (error: SqlError): LedgerError => {\n const internal =\n error.reason._tag === \"LockTimeoutError\"\n ? SqliteWriteContention.make({\n cause: error,\n operation,\n message: `Another producer holds the SQLite write lock; ${operation} is safe to retry.`,\n })\n : SqliteLedgerError.make({\n cause: error,\n operation,\n message: error.message,\n });\n return internalFailure(operation)(internal);\n };\n\nconst corruptionFailure = (operation: string, table: string, rowKey: string, message: string) =>\n internalFailure(operation)(SqliteStorageCorruptionError.make({ table, rowKey, message }));\n\nconst makeServices = Effect.fn(\"SqliteSubmissionLedger.makeServices\")(function* () {\n const config = yield* SqliteStorageConfig;\n const failpoint = yield* SqliteStorageFailpoint;\n const sql = yield* SqlClientService.SqlClient;\n const crypto = yield* Crypto.Crypto;\n const journal = yield* initializeSqliteJournal(sql, failpoint.hit, config.busyTimeout);\n\n const hitFailpoint = (\n location: SqliteStorageFailpointLocation,\n operation: string,\n ): Effect.Effect<void, LedgerError> =>\n failpoint.hit(location).pipe(Effect.mapError((error) => internalFailure(operation)(error)));\n\n /**\n * Run one ledger mutation under the journal's `BEGIN IMMEDIATE` write transaction so\n * ownership-token and epoch checks are atomic with their writes (DUR-006). Transaction\n * acquisition failures surface as LedgerError carrying the typed retryable\n * SqliteWriteContention (or SqliteStorageError) as cause.\n */\n const inWriteTransaction = <\n A,\n E extends\n | AdmissionConflict\n | ApprovalConflict\n | ChildReservationConflict\n | JoinedToHost\n | OwnershipLost\n | SettlementConflict\n | UnknownResolutionConflict\n | LedgerError,\n >(\n operation: string,\n effect: Effect.Effect<A, E>,\n ): Effect.Effect<A, E | LedgerError> =>\n journal\n .withWriteTransaction(operation)(effect)\n .pipe(\n Effect.mapError((error) =>\n error instanceof SqliteStorageError || error instanceof SqliteWriteContention\n ? internalFailure(operation)(error)\n : error,\n ),\n );\n\n const mintIdentifier = (prefix: string, operation: string): Effect.Effect<string, LedgerError> =>\n crypto.randomUUIDv7.pipe(\n Effect.map((uuid) => `${prefix}-${uuid}`),\n Effect.mapError((error) => internalFailure(operation)(error)),\n );\n\n const currentInstant = Effect.map(Clock.currentTimeMillis, (millis) => ({\n millis,\n iso: new Date(millis).toISOString(),\n }));\n\n const timestampMillis = (operation: string, rowKey: string) => (timestamp: string) =>\n decodeUtcInstant(timestamp).pipe(\n Effect.map(DateTime.toEpochMillis),\n Effect.mapError((error) =>\n corruptionFailure(operation, \"effect_agent_submission_ownership\", rowKey, error.message),\n ),\n );\n\n const decodeSubmissionRows = (operation: string, rowKey: string, rows: unknown) =>\n decodeRows(Schema.Array(SubmissionRow), \"effect_agent_submissions\", rowKey, rows).pipe(\n Effect.mapError(internalFailure(operation)),\n );\n\n const readSubmission = Effect.fn(\"SqliteSubmissionLedger.readSubmission\")(function* (\n operation: string,\n submissionId: string,\n ): Effect.fn.Return<Option.Option<SubmissionRow>, LedgerError> {\n const rows = yield* sql<Record<string, unknown>>`\n SELECT ${sql.literal(SUBMISSION_COLUMNS)}\n FROM effect_agent_submissions\n WHERE submission_id = ${submissionId}\n `.pipe(Effect.mapError(sqlFailure(operation)));\n 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(\"SqliteSubmissionLedger.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(\"SqliteSubmissionLedger.readOwnership\")(function* (\n operation: string,\n submissionId: string,\n ): Effect.fn.Return<Option.Option<OwnershipRow>, LedgerError> {\n const rows = yield* sql<Record<string, unknown>>`\n SELECT\n submission_id,\n attempt_id,\n ownership_token,\n producer_epoch,\n owner_producer_id,\n lease_expires_at\n FROM effect_agent_submission_ownership\n WHERE submission_id = ${submissionId}\n `.pipe(Effect.mapError(sqlFailure(operation)));\n 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(\"SqliteSubmissionLedger.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(\"SqliteSubmissionLedger.requireOwnership\")(function* (\n operation: string,\n submission: SubmissionRow,\n ownershipToken: string,\n ): Effect.fn.Return<OwnershipRow, OwnershipLost | LedgerError> {\n const ownership = yield* readOwnership(operation, submission.submission_id);\n 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(\"SqliteSubmissionLedger.decodeSubmissionSnapshot\")(\n function* (\n operation: string,\n row: SubmissionRow,\n ): Effect.fn.Return<SubmissionSnapshot, LedgerError> {\n const agentDigests = yield* parseStoredJsonText(row.agent_digests_json).pipe(\n Effect.mapError((error) =>\n corruptionFailure(\n operation,\n \"effect_agent_submissions\",\n row.submission_id,\n error.message,\n ),\n ),\n );\n 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(\"SqliteSubmissionLedger.readReservation\")(function* (\n operation: string,\n submissionId: string,\n ): Effect.fn.Return<Option.Option<ReservationRow>, LedgerError> {\n const rows = yield* sql<Record<string, unknown>>`\n SELECT\n submission_id,\n settlement_id,\n outcome,\n record_id,\n record_json,\n record_digest,\n reserved_at,\n finalized_at\n FROM effect_agent_settlement_reservations\n WHERE submission_id = ${submissionId}\n `.pipe(Effect.mapError(sqlFailure(operation)));\n 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(\"SqliteSubmissionLedger.readAbortIntent\")(function* (\n operation: string,\n submissionId: string,\n ): Effect.fn.Return<Option.Option<AbortIntentRow>, LedgerError> {\n const rows = yield* sql<Record<string, unknown>>`\n SELECT\n submission_id,\n author,\n reason,\n requested_at,\n canonical_record_id\n FROM effect_agent_abort_intents\n WHERE submission_id = ${submissionId}\n `.pipe(Effect.mapError(sqlFailure(operation)));\n 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 const decodeChildReservationRows = (operation: string, rowKey: string, rows: unknown) =>\n decodeRows(\n Schema.Array(ChildReservationRow),\n \"effect_agent_child_reservations\",\n rowKey,\n rows,\n ).pipe(Effect.mapError(internalFailure(operation)));\n\n const readChildReservation = Effect.fn(\"SqliteSubmissionLedger.readChildReservation\")(function* (\n operation: string,\n reservationId: string,\n ): Effect.fn.Return<Option.Option<ChildReservationRow>, LedgerError> {\n const rows = yield* sql<Record<string, unknown>>`\n SELECT ${sql.literal(CHILD_RESERVATION_COLUMNS)}\n FROM effect_agent_child_reservations\n WHERE reservation_id = ${reservationId}\n `.pipe(Effect.mapError(sqlFailure(operation)));\n 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(\n \"SqliteSubmissionLedger.readChildReservationForCall\",\n )(function* (\n operation: string,\n parentSubmissionId: string,\n parentToolCallId: string,\n ): Effect.fn.Return<Option.Option<ChildReservationRow>, LedgerError> {\n const rows = yield* sql<Record<string, unknown>>`\n SELECT ${sql.literal(CHILD_RESERVATION_COLUMNS)}\n FROM effect_agent_child_reservations\n WHERE parent_submission_id = ${parentSubmissionId}\n AND parent_tool_call_id = ${parentToolCallId}\n `.pipe(Effect.mapError(sqlFailure(operation)));\n 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 const childReservationSnapshotFromRow = Effect.fn(\n \"SqliteSubmissionLedger.childReservationSnapshotFromRow\",\n )(function* (\n operation: string,\n row: ChildReservationRow,\n ): Effect.fn.Return<ChildBudgetReservationSnapshot, LedgerError> {\n const rowFailure = (error: { readonly message: string }) =>\n corruptionFailure(\n operation,\n \"effect_agent_child_reservations\",\n row.reservation_id,\n error.message,\n );\n 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(\"SqliteSubmissionLedger.readApprovalDecisions\")(\n function* (\n operation: string,\n submissionId: string,\n ): Effect.fn.Return<ReadonlyArray<ApprovalDecisionRow>, LedgerError> {\n const rows = yield* sql<Record<string, unknown>>`\n SELECT\n submission_id,\n tool_call_id,\n decision,\n resolver,\n reason,\n decided_at\n FROM effect_agent_approval_decisions\n WHERE submission_id = ${submissionId}\n ORDER BY tool_call_id ASC\n `.pipe(Effect.mapError(sqlFailure(operation)));\n return yield* decodeRows(\n Schema.Array(ApprovalDecisionRow),\n \"effect_agent_approval_decisions\",\n submissionId,\n rows,\n ).pipe(Effect.mapError(internalFailure(operation)));\n },\n );\n\n const approvalIntentFromRow = Effect.fn(\"SqliteSubmissionLedger.approvalIntentFromRow\")(\n function* (\n operation: string,\n row: ApprovalDecisionRow,\n ): Effect.fn.Return<ApprovalDecisionIntent, LedgerError> {\n return yield* decodeApprovalDecisionIntent({\n submissionId: row.submission_id,\n toolCallId: row.tool_call_id,\n decision: row.decision,\n resolver: row.resolver,\n reason: row.reason,\n decidedAt: row.decided_at,\n }).pipe(\n Effect.mapError((error) =>\n corruptionFailure(\n operation,\n \"effect_agent_approval_decisions\",\n `${row.submission_id}/${row.tool_call_id}`,\n error.message,\n ),\n ),\n );\n },\n );\n\n const readUnknownResolutions = Effect.fn(\"SqliteSubmissionLedger.readUnknownResolutions\")(\n function* (\n operation: string,\n submissionId: string,\n ): Effect.fn.Return<ReadonlyArray<UnknownResolutionRow>, LedgerError> {\n const rows = yield* sql<Record<string, unknown>>`\n SELECT\n submission_id,\n tool_call_id,\n author,\n reason,\n resolution_json,\n resolved_at\n FROM effect_agent_unknown_resolutions\n WHERE submission_id = ${submissionId}\n ORDER BY tool_call_id ASC\n `.pipe(Effect.mapError(sqlFailure(operation)));\n return yield* decodeRows(\n Schema.Array(UnknownResolutionRow),\n \"effect_agent_unknown_resolutions\",\n submissionId,\n rows,\n ).pipe(Effect.mapError(internalFailure(operation)));\n },\n );\n\n const unknownResolutionIntentFromRow = Effect.fn(\n \"SqliteSubmissionLedger.unknownResolutionIntentFromRow\",\n )(function* (\n operation: string,\n row: UnknownResolutionRow,\n ): Effect.fn.Return<UnknownResolutionIntent, LedgerError> {\n const resolution = yield* parseStoredJsonText(row.resolution_json).pipe(\n Effect.mapError((error) =>\n corruptionFailure(\n operation,\n \"effect_agent_unknown_resolutions\",\n `${row.submission_id}/${row.tool_call_id}`,\n error.message,\n ),\n ),\n );\n return yield* decodeUnknownResolutionIntent({\n submissionId: row.submission_id,\n toolCallId: row.tool_call_id,\n author: row.author,\n reason: row.reason,\n resolution,\n resolvedAt: row.resolved_at,\n }).pipe(\n Effect.mapError((error) =>\n corruptionFailure(\n operation,\n \"effect_agent_unknown_resolutions\",\n `${row.submission_id}/${row.tool_call_id}`,\n error.message,\n ),\n ),\n );\n });\n\n /** The Submission's marked-unknown open Tool Call identities, empty when never marked. */\n const storedUnknownToolCallIds = Effect.fn(\"SqliteSubmissionLedger.storedUnknownToolCallIds\")(\n function* (\n operation: string,\n submission: SubmissionRow,\n ): Effect.fn.Return<ReadonlyArray<typeof ToolCallIdSchema.Type>, LedgerError> {\n if (submission.unknown_tool_call_ids_json === null) return [];\n return yield* decodeToolCallIdsText(submission.unknown_tool_call_ids_json).pipe(\n Effect.mapError((error) =>\n corruptionFailure(\n operation,\n \"effect_agent_submissions\",\n submission.submission_id,\n error.message,\n ),\n ),\n );\n },\n );\n\n /**\n * Canonical history is the abort authority (DUR-015): the intent's canonicalRecordId is\n * derived from the shared canonical-records table using the deterministic abort record\n * identity, never from a cached ledger marker.\n */\n const canonicalAbortRecordId = Effect.fn(\"SqliteSubmissionLedger.canonicalAbortRecordId\")(\n function* (\n operation: string,\n 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\n const abortIntentFromRow = Effect.fn(\"SqliteSubmissionLedger.abortIntentFromRow\")(function* (\n operation: string,\n submission: SubmissionRow,\n submissionId: SubmissionId,\n row: AbortIntentRow,\n ): Effect.fn.Return<AbortIntent, LedgerError> {\n const canonicalRecordId = yield* canonicalAbortRecordId(\n operation,\n submission.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 const capabilities = Effect.succeed(LedgerCapabilities.make({ durability: \"durable-node\" }));\n\n const admit: SubmissionLedger[\"Service\"][\"admit\"] = Effect.fn(\"SqliteSubmissionLedger.admit\")(\n function* (request: AdmissionRequest) {\n const operation = \"ledger admit\";\n 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 const agentDigestsJson = yield* encodeDefinitionDigestsText(validated.agentDigests).pipe(\n Effect.mapError(internalFailure(operation)),\n );\n const mintedSubmissionId = yield* mintIdentifier(\"submission\", operation);\n const mintedReceiptId = yield* mintIdentifier(\"receipt\", 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 \"SqliteSubmissionLedger.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(\"SqliteSubmissionLedger.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 // A single strongly consistent SQLite file always answers authoritatively (SUB-031): the\n // key-scoped read IS the admission truth, so the tri-state degenerates to NotAdmitted or\n // Admitted here — Indeterminate exists for adapters that can fail to reach the owner.\n const resolveAdmission: SubmissionLedger[\"Service\"][\"resolveAdmission\"] = Effect.fn(\n \"SqliteSubmissionLedger.resolveAdmission\",\n )(function* (request: SubmissionLookupByKey) {\n const operation = \"ledger resolve admission\";\n 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(\"SqliteSubmissionLedger.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 = yield* mintIdentifier(\"attempt\", operation);\n const ownershipToken = yield* mintIdentifier(\"owner\", operation);\n yield* hitFailpoint(\"ledger:claim:before\", operation);\n const claimed = yield* inWriteTransaction(\n operation,\n Effect.gen(function* () {\n const headRows = yield* sql<Record<string, unknown>>`\n SELECT ${sql.literal(SUBMISSION_COLUMNS)}\n FROM effect_agent_submissions\n WHERE conversation_id = ${validated.conversationId}\n AND state <> 'settled'\n ORDER BY queue_sequence ASC\n LIMIT 1\n `.pipe(Effect.mapError(sqlFailure(operation)));\n const heads = yield* decodeSubmissionRows(operation, validated.conversationId, headRows);\n if (heads.length === 0) return Option.none<Claim>();\n const head = heads[0];\n\n // A joining/joined head is host-owned and a suspended/unknown head is durably\n // blocked (DUR-017); the lane produces no claim and later ready work is never\n // skipped past the blocked head (DUR-004).\n if (\n head.state === \"joining\" ||\n head.state === \"joined\" ||\n head.state === \"suspended\" ||\n head.state === \"unknown\"\n ) {\n return Option.none<Claim>();\n }\n\n const now = yield* currentInstant;\n const ownership = yield* readOwnership(operation, head.submission_id);\n if (Option.isSome(ownership)) {\n const expiresAt = yield* timestampMillis(\n operation,\n head.submission_id,\n )(ownership.value.lease_expires_at);\n // A live lease blocks every new claim; expiry alone only revokes the liveness\n // assumption — correctness stays with producer-epoch fencing (D5).\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 (crash between admission and materialization) is created here\n // 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 \"SqliteSubmissionLedger.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 \"SqliteSubmissionLedger.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 \"SqliteSubmissionLedger.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 \"SqliteSubmissionLedger.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 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 \"SqliteSubmissionLedger.finalizeSettlement\",\n )(function* (request: SettlementFinalization) {\n const operation = \"ledger finalize settlement\";\n const validated = yield* Schema.decodeUnknownEffect(Schema.toType(SettlementFinalization))(\n request,\n ).pipe(Effect.mapError(internalFailure(operation)));\n yield* hitFailpoint(\"ledger:finalize-settlement:before\", operation);\n const settlement = yield* inWriteTransaction(\n operation,\n Effect.gen(function* () {\n const reservation = yield* readReservation(operation, validated.submissionId);\n if (Option.isNone(reservation)) {\n return yield* LedgerError.make({\n operation,\n message: `No settlement reservation exists for submission ${validated.submissionId}.`,\n });\n }\n if (reservation.value.settlement_id !== validated.settlementId) {\n return yield* SettlementConflict.make({\n submissionId: validated.submissionId,\n existingOutcome: reservation.value.outcome,\n });\n }\n const submission = yield* requireSubmission(operation, validated.submissionId);\n if (submission.state === \"settled\") {\n if (reservation.value.finalized_at === null) {\n return yield* corruptionFailure(\n operation,\n \"effect_agent_settlement_reservations\",\n validated.submissionId,\n \"A settled Submission's reservation carries no finalization timestamp.\",\n );\n }\n return yield* decodeSettlement({\n submissionId: validated.submissionId,\n settlementId: validated.settlementId,\n receiptId: submission.receipt_id,\n outcome: reservation.value.outcome,\n settledAt: reservation.value.finalized_at,\n }).pipe(Effect.mapError(internalFailure(operation)));\n }\n const now = yield* currentInstant;\n yield* sql`\n UPDATE effect_agent_submissions\n SET state = 'settled', settled_outcome = ${reservation.value.outcome}\n WHERE submission_id = ${validated.submissionId}\n `.pipe(Effect.mapError(sqlFailure(operation)));\n yield* sql`\n UPDATE effect_agent_settlement_reservations\n SET finalized_at = ${now.iso}\n WHERE submission_id = ${validated.submissionId}\n `.pipe(Effect.mapError(sqlFailure(operation)));\n yield* sql`\n DELETE FROM effect_agent_submission_ownership\n WHERE submission_id = ${validated.submissionId}\n `.pipe(Effect.mapError(sqlFailure(operation)));\n return yield* decodeSettlement({\n submissionId: validated.submissionId,\n settlementId: validated.settlementId,\n receiptId: submission.receipt_id,\n outcome: reservation.value.outcome,\n settledAt: now.iso,\n }).pipe(Effect.mapError(internalFailure(operation)));\n }),\n );\n yield* hitFailpoint(\"ledger:finalize-settlement:after\", operation);\n return settlement;\n });\n\n const requestAbort: SubmissionLedger[\"Service\"][\"requestAbort\"] = Effect.fn(\n \"SqliteSubmissionLedger.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 \"SqliteSubmissionLedger.claimJoining\",\n )(function* (request: ClaimJoiningRequest) {\n const operation = \"ledger claim joining\";\n const validated = yield* Schema.decodeUnknownEffect(Schema.toType(ClaimJoiningRequest))(\n request,\n ).pipe(Effect.mapError(internalFailure(operation)));\n yield* hitFailpoint(\"ledger:claim-joining:before\", operation);\n const claims = yield* inWriteTransaction(\n operation,\n Effect.gen(function* () {\n const host = yield* requireSubmission(operation, validated.hostSubmissionId);\n if (host.conversation_id !== validated.conversationId) {\n return yield* LedgerError.make({\n operation,\n message: `Host submission ${validated.hostSubmissionId} does not belong to conversation ${validated.conversationId}.`,\n });\n }\n // The host Attempt already owns the lane; no epoch bump happens here (plan §2.5).\n yield* requireOwnership(operation, host, validated.ownershipToken);\n const laterRows = yield* sql<Record<string, unknown>>`\n SELECT ${sql.literal(SUBMISSION_COLUMNS)}\n FROM effect_agent_submissions\n WHERE conversation_id = ${validated.conversationId}\n AND queue_sequence > ${host.queue_sequence}\n ORDER BY queue_sequence ASC\n `.pipe(Effect.mapError(sqlFailure(operation)));\n const later = yield* decodeSubmissionRows(operation, validated.conversationId, laterRows);\n const claimed: Array<JoiningClaim> = [];\n for (const row of later) {\n if (claimed.length >= validated.maxCount) break;\n // Rows already claimed by THIS host extend its contiguous prefix and are skipped;\n // the coordinator re-delivers already-joined input through the coverage rule.\n if (\n (row.state === \"joining\" || row.state === \"joined\") &&\n row.joined_host_submission_id === validated.hostSubmissionId\n ) {\n continue;\n }\n // P7 §7(c): an aborted-settled row is a CLOSED obligation, not a gap — recovery\n // settles aborted never-claimed queued work immediately, and settlement order of\n // never-run work is not execution order (DUR-004 bounds execution).\n if (row.state === \"settled\" && row.settled_outcome === \"aborted\") continue;\n // Any other non-ready row — an admitted-not-ready gap in particular — breaks the\n // contiguous ready prefix (plan §2.5); later ready work stays queued (DUR-004).\n if (row.state !== \"ready\") break;\n yield* sql`\n UPDATE effect_agent_submissions\n SET state = 'joining', joined_host_submission_id = ${validated.hostSubmissionId}\n WHERE submission_id = ${row.submission_id}\n `.pipe(Effect.mapError(sqlFailure(operation)));\n const inputPayload = yield* parseStoredJsonText(row.input_json).pipe(\n Effect.mapError((error) =>\n corruptionFailure(\n operation,\n \"effect_agent_submissions\",\n row.submission_id,\n error.message,\n ),\n ),\n );\n claimed.push(\n yield* decodeJoiningClaim({\n submissionId: row.submission_id,\n queueSequence: row.queue_sequence,\n inputPayload,\n }).pipe(Effect.mapError(internalFailure(operation))),\n );\n }\n return claimed as ReadonlyArray<JoiningClaim>;\n }),\n );\n yield* hitFailpoint(\"ledger:claim-joining:after\", operation);\n return claims;\n });\n\n const markJoined: SubmissionLedger[\"Service\"][\"markJoined\"] = Effect.fn(\n \"SqliteSubmissionLedger.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 \"SqliteSubmissionLedger.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(\n \"SqliteSubmissionLedger.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 (an approval decision,\n // or a child settlement observed directly from the child's row in this single-store\n // file) resumes the caller immediately WITHOUT releasing the lane (plan §2.6, §12).\n if (validated.reason._tag === \"ApprovalPending\") {\n const decisions = yield* readApprovalDecisions(operation, validated.submissionId);\n const decided = new Set(decisions.map((row) => row.tool_call_id));\n if (validated.reason.toolCallIds.every((toolCallId) => decided.has(toolCallId))) {\n return \"resume-immediately\" as SuspensionOutcome;\n }\n } else {\n let allSettled = true;\n for (const child of validated.reason.children) {\n const childRow = yield* readSubmission(operation, child.childSubmissionId);\n if (Option.isNone(childRow) || childRow.value.state !== \"settled\") {\n allSettled = false;\n break;\n }\n }\n if (allSettled) {\n return \"resume-immediately\" as SuspensionOutcome;\n }\n }\n const now = yield* currentInstant;\n yield* sql`\n UPDATE effect_agent_submissions\n SET\n state = 'suspended',\n suspended_reason_json = ${reasonJson},\n suspended_at = ${now.iso}\n WHERE submission_id = ${validated.submissionId}\n `.pipe(Effect.mapError(sqlFailure(operation)));\n // Suspension ends the ownership period WITHOUT settling: the accepted-work\n // obligation stays owed while the lane consumes no worker permit (plan §2.6).\n yield* sql`\n DELETE FROM effect_agent_submission_ownership\n WHERE submission_id = ${validated.submissionId}\n `.pipe(Effect.mapError(sqlFailure(operation)));\n return \"suspended\" as SuspensionOutcome;\n }),\n );\n yield* hitFailpoint(\"ledger:suspend:after\", operation);\n return outcome;\n });\n\n /**\n * Once every pending call of a recorded ApprovalPending suspension has a decision intent,\n * the lane wakes: suspended → input-applied, suspension cleared (plan §2.6). A\n * WaitingForChild suspension wakes only through recordChildSettled. Runs inside the caller's\n * write transaction.\n */\n const wakeSuspendedIfCovered = Effect.fn(\"SqliteSubmissionLedger.wakeSuspendedIfCovered\")(\n function* (operation: string, submission: SubmissionRow): Effect.fn.Return<void, LedgerError> {\n if (submission.state !== \"suspended\" || submission.suspended_reason_json === null) return;\n 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\n const recordApprovalDecision: SubmissionLedger[\"Service\"][\"recordApprovalDecision\"] = Effect.fn(\n \"SqliteSubmissionLedger.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 \"SqliteSubmissionLedger.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 \"SqliteSubmissionLedger.recordUnknownResolution\",\n )(function* (command: UnknownResolutionCommand) {\n const operation = \"ledger record unknown resolution\";\n const validated = yield* Schema.decodeUnknownEffect(Schema.toType(UnknownResolutionCommand))(\n command,\n ).pipe(Effect.mapError(internalFailure(operation)));\n const resolutionJson = yield* encodeUnknownResolutionText(validated.resolution).pipe(\n Effect.mapError(internalFailure(operation)),\n );\n yield* hitFailpoint(\"ledger:unknown-resolution:before\", operation);\n const intent = yield* inWriteTransaction(\n operation,\n Effect.gen(function* () {\n const submission = yield* requireSubmission(operation, validated.submissionId);\n if (submission.state === \"settled\") {\n if (submission.settled_outcome === null) {\n return yield* corruptionFailure(\n operation,\n \"effect_agent_submissions\",\n validated.submissionId,\n \"A settled Submission carries no terminal outcome.\",\n );\n }\n return yield* SettlementConflict.make({\n submissionId: validated.submissionId,\n existingOutcome: submission.settled_outcome,\n });\n }\n const resolutions = yield* readUnknownResolutions(operation, validated.submissionId);\n const existing = resolutions.find((row) => row.tool_call_id === validated.toolCallId);\n if (existing !== undefined && existing.resolution_json !== resolutionJson) {\n return yield* UnknownResolutionConflict.make({\n submissionId: validated.submissionId,\n toolCallId: validated.toolCallId,\n });\n }\n let resolved: UnknownResolutionIntent;\n if (existing !== undefined) {\n // Idempotent replay of the recorded intent (author/reason may differ; the stored\n // audit fields win, exactly like requestAbort).\n resolved = yield* unknownResolutionIntentFromRow(operation, existing);\n } else {\n const now = yield* currentInstant;\n yield* sql`\n INSERT INTO effect_agent_unknown_resolutions (\n submission_id,\n tool_call_id,\n author,\n reason,\n resolution_json,\n resolved_at\n ) VALUES (\n ${validated.submissionId},\n ${validated.toolCallId},\n ${validated.author},\n ${validated.reason},\n ${resolutionJson},\n ${now.iso}\n )\n `.pipe(Effect.mapError(sqlFailure(operation)));\n const resolution = yield* parseStoredJsonText(resolutionJson).pipe(\n Effect.mapError(internalFailure(operation)),\n );\n resolved = yield* decodeUnknownResolutionIntent({\n submissionId: validated.submissionId,\n toolCallId: validated.toolCallId,\n author: validated.author,\n reason: validated.reason,\n resolution,\n resolvedAt: now.iso,\n }).pipe(Effect.mapError(internalFailure(operation)));\n }\n // The lane reopens only when EVERY marked open call has a durable resolution intent:\n // unknown → input-applied (DUR-017). Replays re-run the coverage check so a\n // recovering caller can wake the lane idempotently.\n if (submission.state === \"unknown\" && submission.unknown_tool_call_ids_json !== null) {\n const markedIds = yield* storedUnknownToolCallIds(operation, submission);\n const covering = yield* readUnknownResolutions(operation, validated.submissionId);\n const coveredIds = new Set(covering.map((row) => row.tool_call_id));\n if (markedIds.every((toolCallId) => coveredIds.has(toolCallId))) {\n yield* sql`\n UPDATE effect_agent_submissions\n SET\n state = 'input-applied',\n unknown_reason = NULL,\n unknown_tool_call_ids_json = NULL\n WHERE submission_id = ${validated.submissionId}\n `.pipe(Effect.mapError(sqlFailure(operation)));\n }\n }\n return resolved;\n }),\n );\n yield* hitFailpoint(\"ledger:unknown-resolution:after\", operation);\n return intent;\n });\n\n const recordChildSettled: SubmissionLedger[\"Service\"][\"recordChildSettled\"] = Effect.fn(\n \"SqliteSubmissionLedger.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; a notification for\n // an unsettled (or unknown) child is a caller error in a single-store adapter.\n const child = yield* readSubmission(operation, validated.childSubmissionId);\n if (Option.isNone(child) || child.value.state !== \"settled\") {\n return yield* LedgerError.make({\n operation,\n message: `Child submission ${validated.childSubmissionId} has no recorded settlement.`,\n });\n }\n if (parent.state !== \"suspended\" || parent.suspended_reason_json === null) {\n return \"not-waiting\" as ChildSettledOutcome;\n }\n const reason = yield* Schema.decodeEffect(Schema.fromJsonString(SuspensionReason))(\n parent.suspended_reason_json,\n ).pipe(\n Effect.mapError((error) =>\n corruptionFailure(\n operation,\n \"effect_agent_submissions\",\n parent.submission_id,\n error.message,\n ),\n ),\n );\n if (reason._tag !== \"WaitingForChild\") {\n return \"not-waiting\" as ChildSettledOutcome;\n }\n if (\n !reason.children.some((entry) => entry.childSubmissionId === validated.childSubmissionId)\n ) {\n return \"not-waiting\" as ChildSettledOutcome;\n }\n // The parent wakes exactly when EVERY listed child is settled (spec §12 step 10);\n // replays re-run the coverage check so a recovering caller wakes the lane idempotently.\n for (const entry of reason.children) {\n const listed = yield* readSubmission(operation, entry.childSubmissionId);\n if (Option.isNone(listed) || listed.value.state !== \"settled\") {\n return \"still-waiting\" as ChildSettledOutcome;\n }\n }\n yield* sql`\n UPDATE effect_agent_submissions\n SET\n state = 'input-applied',\n suspended_reason_json = NULL,\n suspended_at = NULL\n WHERE submission_id = ${validated.parentSubmissionId}\n `.pipe(Effect.mapError(sqlFailure(operation)));\n return \"woken\" as ChildSettledOutcome;\n }),\n );\n yield* hitFailpoint(\"ledger:child-settled:after\", operation);\n return outcome;\n });\n\n const reserveChildBudget: SubmissionLedger[\"Service\"][\"reserveChildBudget\"] = Effect.fn(\n \"SqliteSubmissionLedger.reserveChildBudget\",\n )(function* (request: ChildBudgetReservationRequest) {\n const operation = \"ledger reserve child budget\";\n const validated = yield* Schema.decodeUnknownEffect(\n Schema.toType(ChildBudgetReservationRequest),\n )(request).pipe(Effect.mapError(internalFailure(operation)));\n const allocationJson = yield* encodePersistedJsonText(validated.allocation).pipe(\n Effect.mapError(internalFailure(operation)),\n );\n yield* hitFailpoint(\"ledger:child-reservation:before\", operation);\n const reserved = yield* inWriteTransaction(\n operation,\n Effect.gen(function* () {\n const existing = yield* readChildReservation(operation, validated.reservationId);\n if (Option.isSome(existing)) {\n // Identical replays short-circuit before the fence, mirroring reserveSettlement: a\n // replay creates nothing, so a recovering caller resumes rather than duplicates.\n const identical =\n existing.value.parent_submission_id === validated.parentSubmissionId &&\n existing.value.parent_tool_call_id === validated.parentToolCallId &&\n existing.value.allocation_digest === validated.allocationDigest &&\n existing.value.allocation_json === allocationJson;\n if (!identical) {\n return yield* ChildReservationConflict.make({\n reservationId: validated.reservationId,\n status: existing.value.status,\n message:\n \"A reservation with this identity exists with a different parent Tool Call or allocation.\",\n });\n }\n return ReservedChildBudget.make({\n reservation: yield* childReservationSnapshotFromRow(operation, existing.value),\n replayed: true,\n });\n }\n const collision = yield* readChildReservationForCall(\n operation,\n validated.parentSubmissionId,\n validated.parentToolCallId,\n );\n if (Option.isSome(collision)) {\n return yield* ChildReservationConflict.make({\n reservationId: validated.reservationId,\n status: collision.value.status,\n message: `Parent Tool Call ${validated.parentToolCallId} already owns reservation ${collision.value.reservation_id}.`,\n });\n }\n const parent = yield* requireSubmission(operation, validated.parentSubmissionId);\n // Creation is fenced by the parent lane's live ownership (spec §12 step 2): a stale\n // parent Attempt can never create new reservation state.\n yield* requireOwnership(operation, parent, validated.ownershipToken);\n const now = yield* currentInstant;\n yield* sql`\n INSERT INTO effect_agent_child_reservations (\n reservation_id,\n parent_submission_id,\n parent_tool_call_id,\n status,\n allocation_json,\n allocation_digest,\n reserved_at\n ) VALUES (\n ${validated.reservationId},\n ${validated.parentSubmissionId},\n ${validated.parentToolCallId},\n 'reserved',\n ${allocationJson},\n ${validated.allocationDigest},\n ${now.iso}\n )\n `.pipe(Effect.mapError(sqlFailure(operation)));\n const inserted = yield* readChildReservation(operation, validated.reservationId);\n if (Option.isNone(inserted)) {\n return yield* corruptionFailure(\n operation,\n \"effect_agent_child_reservations\",\n validated.reservationId,\n \"An inserted child reservation row is missing inside its own transaction.\",\n );\n }\n return ReservedChildBudget.make({\n reservation: yield* childReservationSnapshotFromRow(operation, inserted.value),\n replayed: false,\n });\n }),\n );\n yield* hitFailpoint(\"ledger:child-reservation:after\", operation);\n return reserved;\n });\n\n const attachChildToReservation: SubmissionLedger[\"Service\"][\"attachChildToReservation\"] =\n Effect.fn(\"SqliteSubmissionLedger.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 // Single-store latitude: the admitted child must exist here, so a dangling\n // attachment can never enter the recovery view.\n const child = yield* readSubmission(operation, validated.childSubmissionId);\n if (Option.isNone(child)) {\n return yield* LedgerError.make({\n operation,\n message: `Unknown child submission ${validated.childSubmissionId}.`,\n });\n }\n yield* sql`\n UPDATE effect_agent_child_reservations\n SET child_submission_id = ${validated.childSubmissionId}\n WHERE reservation_id = ${validated.reservationId}\n `.pipe(Effect.mapError(sqlFailure(operation)));\n const updated = yield* readChildReservation(operation, validated.reservationId);\n 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 \"SqliteSubmissionLedger.beginChildBudgetRelease\",\n )(function* (request: BeginChildBudgetReleaseRequest) {\n const operation = \"ledger begin child budget release\";\n const validated = yield* Schema.decodeUnknownEffect(\n Schema.toType(BeginChildBudgetReleaseRequest),\n )(request).pipe(Effect.mapError(internalFailure(operation)));\n const accountingJson = yield* encodePersistedJsonText(validated.accounting).pipe(\n Effect.mapError(internalFailure(operation)),\n );\n yield* hitFailpoint(\"ledger:child-release-pending:before\", operation);\n const frozen = yield* inWriteTransaction(\n operation,\n Effect.gen(function* () {\n const existing = yield* readChildReservation(operation, validated.reservationId);\n if (Option.isNone(existing)) {\n return yield* LedgerError.make({\n operation,\n message: `Unknown child reservation ${validated.reservationId}.`,\n });\n }\n if (existing.value.status !== \"reserved\") {\n // The accounting decision was already frozen exactly once; an identical replay is a\n // no-op and a divergent decision conflicts (spec §12 join step 6).\n if (existing.value.accounting_json === accountingJson) {\n return yield* childReservationSnapshotFromRow(operation, existing.value);\n }\n return yield* ChildReservationConflict.make({\n reservationId: validated.reservationId,\n status: existing.value.status,\n message: \"A different accounting decision is already frozen for this reservation.\",\n });\n }\n const now = yield* currentInstant;\n yield* sql`\n UPDATE effect_agent_child_reservations\n SET\n status = 'releasePending',\n accounting_json = ${accountingJson},\n release_began_at = ${now.iso}\n WHERE reservation_id = ${validated.reservationId}\n `.pipe(Effect.mapError(sqlFailure(operation)));\n const updated = yield* readChildReservation(operation, validated.reservationId);\n if (Option.isNone(updated)) {\n return yield* corruptionFailure(\n operation,\n \"effect_agent_child_reservations\",\n validated.reservationId,\n \"An updated child reservation row is missing inside its own transaction.\",\n );\n }\n return yield* childReservationSnapshotFromRow(operation, updated.value);\n }),\n );\n yield* hitFailpoint(\"ledger:child-release-pending:after\", operation);\n return frozen;\n });\n\n const releaseChildBudget: SubmissionLedger[\"Service\"][\"releaseChildBudget\"] = Effect.fn(\n \"SqliteSubmissionLedger.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(\"SqliteSubmissionLedger.scanPage\")(function* (\n cursor: ScanCursor | undefined,\n ): Effect.fn.Return<\n readonly [ReadonlyArray<SubmissionSnapshot>, Option.Option<ScanCursor | undefined>],\n LedgerError\n > {\n const operation = \"ledger scan nonterminal\";\n const rows = yield* (\n cursor === undefined\n ? sql<Record<string, unknown>>`\n SELECT ${sql.literal(SUBMISSION_COLUMNS)}\n FROM effect_agent_submissions\n WHERE state <> 'settled'\n ORDER BY conversation_id ASC, queue_sequence ASC\n LIMIT ${SCAN_PAGE_SIZE}\n `\n : sql<Record<string, unknown>>`\n SELECT ${sql.literal(SUBMISSION_COLUMNS)}\n FROM effect_agent_submissions\n WHERE state <> 'settled'\n AND (\n conversation_id > ${cursor.conversationId}\n OR (\n conversation_id = ${cursor.conversationId}\n AND queue_sequence > ${cursor.queueSequence}\n )\n )\n ORDER BY conversation_id ASC, queue_sequence ASC\n LIMIT ${SCAN_PAGE_SIZE}\n `\n ).pipe(Effect.mapError(sqlFailure(operation)));\n const decoded = yield* decodeSubmissionRows(operation, \"nonterminal_scan\", rows);\n const snapshots = yield* Effect.forEach(decoded, (row) =>\n decodeSubmissionSnapshot(operation, row),\n );\n const last = decoded[decoded.length - 1];\n const next: Option.Option<ScanCursor | undefined> =\n last === undefined || decoded.length < SCAN_PAGE_SIZE\n ? Option.none()\n : Option.some({\n conversationId: last.conversation_id,\n queueSequence: last.queue_sequence,\n });\n return [snapshots, next] as const;\n });\n\n const scanNonterminal: Stream.Stream<SubmissionSnapshot, LedgerError> = Stream.paginate(\n undefined as ScanCursor | undefined,\n scanPage,\n );\n\n const loadRecoverySnapshot: SubmissionLedger[\"Service\"][\"loadRecoverySnapshot\"] = Effect.fn(\n \"SqliteSubmissionLedger.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).\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 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.isNone(child)) continue;\n childAttachments.push(\n yield* decodeChildAttachmentSnapshot({\n toolCallId: row.parent_tool_call_id,\n childSubmissionId: row.child_submission_id,\n childState: child.value.state,\n ...(child.value.settled_outcome === null\n ? {}\n : { childOutcome: child.value.settled_outcome }),\n }).pipe(Effect.mapError(internalFailure(operation))),\n );\n }\n\n let parentLinkage: ParentLinkage | undefined;\n 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 * SQLite SubmissionLedger implementation sharing the journal's database file, write\n * transaction discipline, and producer-epoch fencing substrate. Configuration, failpoint,\n * SQL, and Crypto authority stay visible in the input channel.\n */\nexport const submissionLedgerLayer: Layer.Layer<\n SubmissionLedger,\n SqliteStorageInitializationError,\n SqliteStorageConfig | SqliteStorageFailpoint | SqlClientService.SqlClient | Crypto.Crypto\n> = Layer.effectContext(makeServices());\n\n/**\n * A composition-root convenience Layer for the durable Submission Ledger. Point it at the\n * same database file as the ConversationStore so claims fence the same producer epochs.\n */\nexport const ledgerLayer = (\n options: SqliteStorageOptions,\n): Layer.Layer<SubmissionLedger, SqliteStorageInitializationError> =>\n submissionLedgerLayer.pipe(\n Layer.provide(\n Layer.mergeAll(\n storageConfigLayer(options),\n storageFailpointLayer(options),\n SqliteClient.layer({ filename: options.filename }),\n NodeCrypto.layer,\n ),\n ),\n );\n"],"mappings":";;;;;;;AAIA,IAAa,kCAAb,cAAqD,OAAO,YAA6C,CAAC,CACxG,mCACA;CACE,eAAe,OAAO;CACtB,SAAS,OAAO;CAChB,kBAAkB,OAAO;AAC3B,CACF,CAAC,CAAC,CAAC;;AAGH,IAAa,+BAAb,cAAkD,OAAO,YAA0C,CAAC,CAClG,gCACA;CACE,SAAS,OAAO;CAChB,QAAQ,OAAO;CACf,OAAO,OAAO;AAChB,CACF,CAAC,CAAC,CAAC;;AAGH,IAAa,qBAAb,cAAwC,OAAO,YAAgC,CAAC,CAC9E,sBACA;CACE,OAAO,OAAO,YAAY,OAAO,OAAO,CAAC;CACzC,SAAS,OAAO;CAChB,WAAW,OAAO;AACpB,CACF,CAAC,CAAC,CAAC;;;;;;AAOH,IAAa,oBAAb,cAAuC,OAAO,YAA+B,CAAC,CAC5E,qBACA;CACE,OAAO,OAAO,YAAY,OAAO,OAAO,CAAC;CACzC,SAAS,OAAO;CAChB,WAAW,OAAO;AACpB,CACF,CAAC,CAAC,CAAC;;;;;AAMH,IAAa,uBAAb,cAA0C,OAAO,YAAkC,CAAC,CAClF,wBACA;CACE,SAAS,OAAO;CAChB,QAAQ,OAAO,SAAS;EAAC;EAAgB;EAAmB;CAAM,CAAC;CACnE,oBAAoB,OAAO,YAAY,iBAAiB;CACxD,kBAAkB,OAAO,YAAY,OAAO,MAAM;AACpD,CACF,CAAC,CAAC,CAAC;;;;;;AAOH,IAAa,sBAAb,cAAyC,OAAO,YAAiC,CAAC,CAChF,uBACA;CACE,aAAa;CACb,SAAS,OAAO;CAChB,eAAe;AACjB,CACF,CAAC,CAAC,CAAC;;;;;;AAOH,IAAa,wBAAb,cAA2C,OAAO,YAAmC,CAAC,CACpF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