@effect-agent/storage-sqlite 0.0.1-beta.0

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/index.mjs ADDED
@@ -0,0 +1,3063 @@
1
+ import { AbortCommand, AbortIntent, AdmissionAdmitted, AdmissionConflict, AdmissionNotAdmitted, AdmissionRequest, AdmissionResult, AppendConflict, AppendResult, ApprovalConflict, ApprovalDecision, ApprovalDecisionCommand, ApprovalDecisionIntent, AttachChildToReservationRequest, BeginChildBudgetReleaseRequest, CanonicalBatch, CanonicalRecord, CanonicalRecordEnvelope, CanonicalSequence, CheckpointRejected, ChildAttachmentSnapshot, ChildBudgetReservationRequest, ChildBudgetReservationSnapshot, ChildReservationConflict, ChildReservationStatus, ChildSettledNotification, Claim, ClaimJoiningRequest, ClaimRequest, ConversationCheckpoint, ConversationExport, ConversationExportRequest, ConversationMaterialization, ConversationNotMaterialized, ConversationObservation, ConversationRead, ConversationStore, ConversationStoreError, ConversationTail, ConversationTailRequest, DEFAULT_OWNERSHIP_LEASE_DURATION, DefinitionDigests, Digest, EMPTY_TAIL_DIGEST, FenceRejected, FencedAppendRequest, InputAppliedMarker, JoinSnapshot, JoinedToHost, JoiningClaim, LedgerCapabilities, LedgerError, LoadCheckpointRequest, MarkInputAppliedRequest, MarkJoinedRequest, MarkReadyRequest, MarkUnknownRequest, ObservationOffset, OwnershipLost, OwnershipRenewal, OwnershipSnapshot, ParentLinkage, PersistedJson, ProducerEpoch, QueueSequence, RecordEnvelope, RecoverySnapshot, RecoverySnapshotRequest, ReleaseChildBudgetRequest, ReleaseOwnershipRequest, RenewOwnershipRequest, ReservedChildBudget, ReservedSettlement, RevertJoiningRequest, SaveCheckpointRequest, Settlement, SettlementConflict, SettlementFinalization, SettlementOutcome, SettlementReservation, SettlementReservationSnapshot, SubmissionLedger, SubmissionLookup, SubmissionLookupByKey, SubmissionSnapshot, SubmissionState, SuspendRequest, SuspensionReason, SuspensionSnapshot, UnknownResolution, UnknownResolutionCommand, UnknownResolutionConflict, UnknownResolutionIntent, digestCanonicalBatch, submissionAbortRecordId } from "@effect-agent/session";
2
+ import { Clock, Context, Crypto, DateTime, Duration, Effect, Exit, Layer, Option, Ref, Schema, Stream } from "effect";
3
+ import { SqliteClient, SqliteMigrator } from "@effect/sql-sqlite-node";
4
+ import * as SqlClient from "effect/unstable/sql/SqlClient";
5
+ import { NodeCrypto } from "@effect/platform-node";
6
+ //#region src/errors.ts
7
+ /** The SQLite file uses a private-development format this adapter cannot read. */
8
+ var SqliteStorageCompatibilityError = class extends Schema.TaggedErrorClass()("SqliteStorageCompatibilityError", {
9
+ actualVersion: Schema.Int,
10
+ message: Schema.String,
11
+ supportedVersion: Schema.Int
12
+ }) {};
13
+ /** Stored bytes failed the current Schema and cannot be used as recovery truth. */
14
+ var SqliteStorageCorruptionError = class extends Schema.TaggedErrorClass()("SqliteStorageCorruptionError", {
15
+ message: Schema.String,
16
+ rowKey: Schema.String,
17
+ table: Schema.String
18
+ }) {};
19
+ /** SQLite infrastructure failed while opening or operating the store. */
20
+ var SqliteStorageError = class extends Schema.TaggedErrorClass()("SqliteStorageError", {
21
+ cause: Schema.optionalKey(Schema.Defect()),
22
+ message: Schema.String,
23
+ operation: Schema.String
24
+ }) {};
25
+ /**
26
+ * SQLite infrastructure failed while operating the Submission Ledger. Surfaces at the
27
+ * SubmissionLedger port as the typed `LedgerError` with this error preserved as its cause,
28
+ * so the adapter-level tag is never erased.
29
+ */
30
+ var SqliteLedgerError = class extends Schema.TaggedErrorClass()("SqliteLedgerError", {
31
+ cause: Schema.optionalKey(Schema.Defect()),
32
+ message: Schema.String,
33
+ operation: Schema.String
34
+ }) {};
35
+ /**
36
+ * A canonical batch retry conflicts with existing append state. Tail conflicts carry the
37
+ * actual committed tail as a diagnostic resume hint.
38
+ */
39
+ var SqliteAppendConflict = class extends Schema.TaggedErrorClass()("SqliteAppendConflict", {
40
+ message: Schema.String,
41
+ reason: Schema.Literals([
42
+ "batch-digest",
43
+ "record-identity",
44
+ "tail"
45
+ ]),
46
+ actualTailSequence: Schema.optionalKey(CanonicalSequence),
47
+ actualTailDigest: Schema.optionalKey(Schema.String)
48
+ }) {};
49
+ /**
50
+ * A producer epoch does not match the Conversation's current writer registration. Appends
51
+ * require the exact registered epoch, so both older and newer unregistered epochs are fenced;
52
+ * a newer epoch takes over by materializing first.
53
+ */
54
+ var SqliteFenceRejected = class extends Schema.TaggedErrorClass()("SqliteFenceRejected", {
55
+ actualEpoch: ProducerEpoch,
56
+ message: Schema.String,
57
+ producerEpoch: ProducerEpoch
58
+ }) {};
59
+ /**
60
+ * A write transaction could not acquire the SQLite write lock within the configured busy
61
+ * timeout (SQLITE_BUSY / SQLITE_LOCKED). Another transiently coexisting owner is writing;
62
+ * the operation did not mutate canonical state and is safe to retry.
63
+ */
64
+ var SqliteWriteContention = class extends Schema.TaggedErrorClass()("SqliteWriteContention", {
65
+ cause: Schema.optionalKey(Schema.Defect()),
66
+ message: Schema.String,
67
+ operation: Schema.String
68
+ }) {};
69
+ /** A checkpoint conflicts with a previously stored checkpoint at the same offset. */
70
+ var SqliteCheckpointConflict = class extends Schema.TaggedErrorClass()("SqliteCheckpointConflict", { message: Schema.String }) {};
71
+ const SqliteStorageFailpointLocation = Schema.Literals([
72
+ "materialize:before",
73
+ "materialize:after",
74
+ "append:before",
75
+ "append:after-batch-insert",
76
+ "append:after-record-insert",
77
+ "append:after-tail-update",
78
+ "append:after",
79
+ "export:after-conversation-read",
80
+ "save-checkpoint:before",
81
+ "save-checkpoint:after",
82
+ "ledger:admit:before",
83
+ "ledger:admit:after",
84
+ "ledger:mark-ready:before",
85
+ "ledger:mark-ready:after",
86
+ "ledger:claim:before",
87
+ "ledger:claim:after",
88
+ "ledger:mark-input-applied:before",
89
+ "ledger:mark-input-applied:after",
90
+ "ledger:renew:before",
91
+ "ledger:renew:after",
92
+ "ledger:reserve-settlement:before",
93
+ "ledger:reserve-settlement:after",
94
+ "ledger:finalize-settlement:before",
95
+ "ledger:finalize-settlement:after",
96
+ "ledger:request-abort:before",
97
+ "ledger:request-abort:after",
98
+ "ledger:release:before",
99
+ "ledger:release:after",
100
+ "ledger:claim-joining:before",
101
+ "ledger:claim-joining:after",
102
+ "ledger:mark-joined:before",
103
+ "ledger:mark-joined:after",
104
+ "ledger:revert-joining:before",
105
+ "ledger:revert-joining:after",
106
+ "ledger:suspend:before",
107
+ "ledger:suspend:after",
108
+ "ledger:approval-decision:before",
109
+ "ledger:approval-decision:after",
110
+ "ledger:mark-unknown:before",
111
+ "ledger:mark-unknown:after",
112
+ "ledger:unknown-resolution:before",
113
+ "ledger:unknown-resolution:after",
114
+ "ledger:child-reservation:before",
115
+ "ledger:child-reservation:after",
116
+ "ledger:child-attach:before",
117
+ "ledger:child-attach:after",
118
+ "ledger:child-release-pending:before",
119
+ "ledger:child-release-pending:after",
120
+ "ledger:child-release:before",
121
+ "ledger:child-release:after",
122
+ "ledger:child-settled:before",
123
+ "ledger:child-settled:after"
124
+ ]);
125
+ /** Deterministic test-only fault or pause injected at a SQLite operation boundary. */
126
+ var SqliteStorageFailpointError = class extends Schema.TaggedErrorClass()("SqliteStorageFailpointError", { location: SqliteStorageFailpointLocation }) {
127
+ get message() {
128
+ return `Injected SQLite storage failure at ${this.location}.`;
129
+ }
130
+ };
131
+ //#endregion
132
+ //#region src/migrations.ts
133
+ const CurrentSqliteStorageVersion = 4;
134
+ const sqliteMigrations = SqliteMigrator.fromRecord({
135
+ "1_current_persistent_conversation_foundation": Effect.gen(function* () {
136
+ const sql = yield* SqlClient.SqlClient;
137
+ yield* sql`
138
+ CREATE TABLE effect_agent_conversations (
139
+ conversation_id TEXT PRIMARY KEY NOT NULL,
140
+ created_at TEXT NOT NULL,
141
+ tail_sequence INTEGER NOT NULL,
142
+ tail_digest TEXT NOT NULL,
143
+ producer_epoch INTEGER NOT NULL
144
+ )
145
+ `.withoutTransform;
146
+ yield* sql`
147
+ CREATE TABLE effect_agent_canonical_batches (
148
+ conversation_id TEXT NOT NULL,
149
+ batch_id TEXT NOT NULL,
150
+ first_sequence INTEGER NOT NULL,
151
+ last_sequence INTEGER NOT NULL,
152
+ batch_digest TEXT NOT NULL,
153
+ tail_digest TEXT NOT NULL,
154
+ batch_json TEXT NOT NULL,
155
+ PRIMARY KEY (conversation_id, batch_id),
156
+ FOREIGN KEY (conversation_id)
157
+ REFERENCES effect_agent_conversations(conversation_id)
158
+ ON DELETE RESTRICT
159
+ )
160
+ `.withoutTransform;
161
+ yield* sql`
162
+ CREATE TABLE effect_agent_canonical_records (
163
+ conversation_id TEXT NOT NULL,
164
+ sequence INTEGER NOT NULL,
165
+ record_id TEXT NOT NULL,
166
+ batch_id TEXT NOT NULL,
167
+ record_json TEXT NOT NULL,
168
+ PRIMARY KEY (conversation_id, sequence),
169
+ UNIQUE (conversation_id, record_id),
170
+ FOREIGN KEY (conversation_id, batch_id)
171
+ REFERENCES effect_agent_canonical_batches(conversation_id, batch_id)
172
+ ON DELETE RESTRICT
173
+ )
174
+ `.withoutTransform;
175
+ yield* sql`
176
+ CREATE INDEX effect_agent_canonical_records_batch
177
+ ON effect_agent_canonical_records (conversation_id, batch_id, sequence)
178
+ `.withoutTransform;
179
+ yield* sql`
180
+ CREATE TABLE effect_agent_checkpoints (
181
+ conversation_id TEXT NOT NULL,
182
+ through_sequence INTEGER NOT NULL,
183
+ tail_digest TEXT NOT NULL,
184
+ checkpoint_json TEXT NOT NULL,
185
+ PRIMARY KEY (conversation_id, through_sequence),
186
+ FOREIGN KEY (conversation_id)
187
+ REFERENCES effect_agent_conversations(conversation_id)
188
+ ON DELETE RESTRICT
189
+ )
190
+ `.withoutTransform;
191
+ yield* sql`PRAGMA user_version = 1`.withoutTransform;
192
+ }),
193
+ "2_durable_submission_ledger": Effect.gen(function* () {
194
+ const sql = yield* SqlClient.SqlClient;
195
+ yield* sql`
196
+ CREATE TABLE effect_agent_submissions (
197
+ submission_id TEXT PRIMARY KEY NOT NULL,
198
+ conversation_id TEXT NOT NULL,
199
+ queue_sequence INTEGER NOT NULL,
200
+ principal TEXT NOT NULL,
201
+ idempotency_key TEXT NOT NULL,
202
+ agent_id TEXT NOT NULL,
203
+ agent_digests_json TEXT NOT NULL,
204
+ deployment_id TEXT NOT NULL,
205
+ input_json TEXT NOT NULL,
206
+ input_digest TEXT NOT NULL,
207
+ receipt_id TEXT NOT NULL,
208
+ state TEXT NOT NULL,
209
+ settled_outcome TEXT,
210
+ created_at TEXT NOT NULL,
211
+ ready_at TEXT,
212
+ input_applied_record_id TEXT,
213
+ input_applied_sequence INTEGER,
214
+ UNIQUE (conversation_id, principal, idempotency_key),
215
+ UNIQUE (conversation_id, queue_sequence)
216
+ )
217
+ `.withoutTransform;
218
+ yield* sql`
219
+ CREATE TABLE effect_agent_submission_ownership (
220
+ submission_id TEXT PRIMARY KEY NOT NULL,
221
+ attempt_id TEXT NOT NULL,
222
+ ownership_token TEXT NOT NULL,
223
+ producer_epoch INTEGER NOT NULL,
224
+ owner_producer_id TEXT NOT NULL,
225
+ lease_expires_at TEXT NOT NULL,
226
+ FOREIGN KEY (submission_id)
227
+ REFERENCES effect_agent_submissions(submission_id)
228
+ ON DELETE RESTRICT
229
+ )
230
+ `.withoutTransform;
231
+ yield* sql`
232
+ CREATE TABLE effect_agent_attempts (
233
+ attempt_id TEXT PRIMARY KEY NOT NULL,
234
+ submission_id TEXT NOT NULL,
235
+ conversation_id TEXT NOT NULL,
236
+ owner_producer_id TEXT NOT NULL,
237
+ producer_epoch INTEGER NOT NULL,
238
+ claimed_at TEXT NOT NULL,
239
+ FOREIGN KEY (submission_id)
240
+ REFERENCES effect_agent_submissions(submission_id)
241
+ ON DELETE RESTRICT
242
+ )
243
+ `.withoutTransform;
244
+ yield* sql`
245
+ CREATE TABLE effect_agent_settlement_reservations (
246
+ submission_id TEXT PRIMARY KEY NOT NULL,
247
+ settlement_id TEXT NOT NULL,
248
+ outcome TEXT NOT NULL,
249
+ record_id TEXT NOT NULL,
250
+ record_json TEXT NOT NULL,
251
+ record_digest TEXT NOT NULL,
252
+ reserved_at TEXT NOT NULL,
253
+ finalized_at TEXT,
254
+ FOREIGN KEY (submission_id)
255
+ REFERENCES effect_agent_submissions(submission_id)
256
+ ON DELETE RESTRICT
257
+ )
258
+ `.withoutTransform;
259
+ yield* sql`
260
+ CREATE TABLE effect_agent_abort_intents (
261
+ submission_id TEXT PRIMARY KEY NOT NULL,
262
+ author TEXT NOT NULL,
263
+ reason TEXT NOT NULL,
264
+ requested_at TEXT NOT NULL,
265
+ canonical_record_id TEXT,
266
+ FOREIGN KEY (submission_id)
267
+ REFERENCES effect_agent_submissions(submission_id)
268
+ ON DELETE RESTRICT
269
+ )
270
+ `.withoutTransform;
271
+ yield* sql`PRAGMA user_version = 2`.withoutTransform;
272
+ }),
273
+ "3_durable_tools_and_joined_input": Effect.gen(function* () {
274
+ const sql = yield* SqlClient.SqlClient;
275
+ yield* sql`
276
+ ALTER TABLE effect_agent_submissions
277
+ ADD COLUMN joined_host_submission_id TEXT
278
+ `.withoutTransform;
279
+ yield* sql`
280
+ ALTER TABLE effect_agent_submissions
281
+ ADD COLUMN suspended_reason_json TEXT
282
+ `.withoutTransform;
283
+ yield* sql`
284
+ ALTER TABLE effect_agent_submissions
285
+ ADD COLUMN suspended_at TEXT
286
+ `.withoutTransform;
287
+ yield* sql`
288
+ ALTER TABLE effect_agent_submissions
289
+ ADD COLUMN unknown_reason TEXT
290
+ `.withoutTransform;
291
+ yield* sql`
292
+ ALTER TABLE effect_agent_submissions
293
+ ADD COLUMN unknown_tool_call_ids_json TEXT
294
+ `.withoutTransform;
295
+ yield* sql`
296
+ CREATE INDEX effect_agent_submissions_joined_host
297
+ ON effect_agent_submissions (joined_host_submission_id)
298
+ `.withoutTransform;
299
+ yield* sql`
300
+ CREATE TABLE effect_agent_approval_decisions (
301
+ submission_id TEXT NOT NULL,
302
+ tool_call_id TEXT NOT NULL,
303
+ decision TEXT NOT NULL,
304
+ resolver TEXT NOT NULL,
305
+ reason TEXT NOT NULL,
306
+ decided_at TEXT NOT NULL,
307
+ PRIMARY KEY (submission_id, tool_call_id),
308
+ FOREIGN KEY (submission_id)
309
+ REFERENCES effect_agent_submissions(submission_id)
310
+ ON DELETE RESTRICT
311
+ )
312
+ `.withoutTransform;
313
+ yield* sql`
314
+ CREATE TABLE effect_agent_unknown_resolutions (
315
+ submission_id TEXT NOT NULL,
316
+ tool_call_id TEXT NOT NULL,
317
+ author TEXT NOT NULL,
318
+ reason TEXT NOT NULL,
319
+ resolution_json TEXT NOT NULL,
320
+ resolved_at TEXT NOT NULL,
321
+ PRIMARY KEY (submission_id, tool_call_id),
322
+ FOREIGN KEY (submission_id)
323
+ REFERENCES effect_agent_submissions(submission_id)
324
+ ON DELETE RESTRICT
325
+ )
326
+ `.withoutTransform;
327
+ yield* sql`PRAGMA user_version = 3`.withoutTransform;
328
+ }),
329
+ "4_durable_subagents": Effect.gen(function* () {
330
+ const sql = yield* SqlClient.SqlClient;
331
+ yield* sql`
332
+ ALTER TABLE effect_agent_submissions
333
+ ADD COLUMN parent_submission_id TEXT
334
+ `.withoutTransform;
335
+ yield* sql`
336
+ ALTER TABLE effect_agent_submissions
337
+ ADD COLUMN parent_tool_call_id TEXT
338
+ `.withoutTransform;
339
+ yield* sql`
340
+ CREATE INDEX effect_agent_submissions_parent
341
+ ON effect_agent_submissions (parent_submission_id)
342
+ `.withoutTransform;
343
+ yield* sql`
344
+ CREATE TABLE effect_agent_child_reservations (
345
+ reservation_id TEXT PRIMARY KEY NOT NULL,
346
+ parent_submission_id TEXT NOT NULL,
347
+ parent_tool_call_id TEXT NOT NULL,
348
+ child_submission_id TEXT,
349
+ status TEXT NOT NULL,
350
+ allocation_json TEXT NOT NULL,
351
+ allocation_digest TEXT NOT NULL,
352
+ accounting_json TEXT,
353
+ reserved_at TEXT NOT NULL,
354
+ release_began_at TEXT,
355
+ released_at TEXT,
356
+ UNIQUE (parent_submission_id, parent_tool_call_id),
357
+ FOREIGN KEY (parent_submission_id)
358
+ REFERENCES effect_agent_submissions(submission_id)
359
+ ON DELETE RESTRICT
360
+ )
361
+ `.withoutTransform;
362
+ yield* sql`PRAGMA user_version = 4`.withoutTransform;
363
+ })
364
+ });
365
+ //#endregion
366
+ //#region src/sqlite-journal.ts
367
+ const BoundedStoredText$1 = Schema.String.check(Schema.isMaxLength(16 * 1024 * 1024));
368
+ const BoundedIdentifier$1 = Schema.NonEmptyString.check(Schema.isMaxLength(1024));
369
+ const NonNegativeInt = Schema.Int.check(Schema.isGreaterThanOrEqualTo(0));
370
+ const MAX_RECORDS_PER_CONVERSATION = 65536;
371
+ const MAX_STORED_TEXT_BYTES = 16 * 1024 * 1024;
372
+ const MAX_IDENTIFIER_LENGTH = 1024;
373
+ const storedTextBytes = (value) => new TextEncoder().encode(value).byteLength;
374
+ var SqliteVersionRow = class extends Schema.Class("SqliteVersionRow")({ user_version: NonNegativeInt }) {};
375
+ var SqliteJournalModeRow = class extends Schema.Class("SqliteJournalModeRow")({ journal_mode: Schema.NonEmptyString.check(Schema.isMaxLength(32)) }) {};
376
+ var SqliteNameRow = class extends Schema.Class("SqliteNameRow")({ name: BoundedIdentifier$1 }) {};
377
+ var ConversationRow = class extends Schema.Class("ConversationRow")({
378
+ conversation_id: BoundedIdentifier$1,
379
+ created_at: Schema.NonEmptyString.check(Schema.isMaxLength(128)),
380
+ producer_epoch: ProducerEpoch,
381
+ tail_digest: BoundedStoredText$1,
382
+ tail_sequence: CanonicalSequence
383
+ }) {};
384
+ var BatchRow = class extends Schema.Class("BatchRow")({
385
+ batch_digest: BoundedStoredText$1,
386
+ batch_id: BoundedIdentifier$1,
387
+ batch_json: BoundedStoredText$1,
388
+ conversation_id: BoundedIdentifier$1,
389
+ first_sequence: CanonicalSequence,
390
+ last_sequence: CanonicalSequence,
391
+ tail_digest: BoundedStoredText$1
392
+ }) {};
393
+ var RecordRow = class extends Schema.Class("RecordRow")({
394
+ batch_id: BoundedIdentifier$1,
395
+ conversation_id: BoundedIdentifier$1,
396
+ record_id: BoundedIdentifier$1,
397
+ record_json: BoundedStoredText$1,
398
+ sequence: CanonicalSequence
399
+ }) {};
400
+ var CheckpointRow = class extends Schema.Class("CheckpointRow")({
401
+ checkpoint_json: BoundedStoredText$1,
402
+ conversation_id: BoundedIdentifier$1,
403
+ tail_digest: BoundedStoredText$1,
404
+ through_sequence: CanonicalSequence
405
+ }) {};
406
+ var RawRecord = class extends Schema.Class("@effect-agent/storage-sqlite/RawRecord")({
407
+ recordId: BoundedIdentifier$1,
408
+ recordJson: BoundedStoredText$1
409
+ }) {};
410
+ var RawAppendRequest = class extends Schema.Class("@effect-agent/storage-sqlite/RawAppendRequest")({
411
+ batchDigest: BoundedStoredText$1,
412
+ batchId: BoundedIdentifier$1,
413
+ batchJson: BoundedStoredText$1,
414
+ conversationId: BoundedIdentifier$1,
415
+ expectedTailDigest: BoundedStoredText$1,
416
+ expectedTailSequence: CanonicalSequence,
417
+ producerEpoch: ProducerEpoch,
418
+ records: Schema.NonEmptyArray(RawRecord).check(Schema.isMaxLength(256)),
419
+ tailDigest: BoundedStoredText$1
420
+ }) {};
421
+ var RawAppendResult = class extends Schema.Class("@effect-agent/storage-sqlite/RawAppendResult")({
422
+ firstSequence: CanonicalSequence,
423
+ lastSequence: CanonicalSequence,
424
+ replayed: Schema.Boolean,
425
+ tailDigest: BoundedStoredText$1
426
+ }) {};
427
+ var RawReadRequest = class extends Schema.Class("@effect-agent/storage-sqlite/RawReadRequest")({
428
+ conversationId: BoundedIdentifier$1,
429
+ fromSequenceExclusive: CanonicalSequence,
430
+ limit: Schema.Int.check(Schema.isGreaterThan(0), Schema.isLessThanOrEqualTo(1024))
431
+ }) {};
432
+ var RawCheckpoint = class extends Schema.Class("@effect-agent/storage-sqlite/RawCheckpoint")({
433
+ checkpointJson: BoundedStoredText$1,
434
+ conversationId: BoundedIdentifier$1,
435
+ tailDigest: BoundedStoredText$1,
436
+ throughSequence: CanonicalSequence
437
+ }) {};
438
+ var RawConversationExport = class extends Schema.Class("@effect-agent/storage-sqlite/RawConversationExport")({
439
+ batches: Schema.Array(BatchRow),
440
+ checkpoints: Schema.Array(CheckpointRow),
441
+ conversation: ConversationRow,
442
+ records: Schema.Array(RecordRow)
443
+ }) {};
444
+ const noFailpoint$1 = () => Effect.void;
445
+ const storageError = (operation) => (error) => SqliteStorageError.make({
446
+ cause: error,
447
+ operation,
448
+ message: error.message
449
+ });
450
+ /** Decode raw SQLite rows against a Schema, reporting failures as typed corruption. */
451
+ const decodeRows = Effect.fn("SqliteJournal.decodeRows")((schema, table, rowKey, rows) => Schema.decodeUnknownEffect(schema)(rows).pipe(Effect.mapError((error) => SqliteStorageCorruptionError.make({
452
+ table,
453
+ rowKey,
454
+ message: String(error)
455
+ }))));
456
+ /** Decode exactly one raw SQLite row against a Schema, reporting failures as typed corruption. */
457
+ const decodeSingleRow = Effect.fn("SqliteJournal.decodeSingleRow")((schema, table, rowKey, rows) => decodeRows(schema, table, rowKey, rows).pipe(Effect.flatMap((decoded) => decoded.length === 1 ? Effect.succeed(decoded[0]) : Effect.fail(SqliteStorageCorruptionError.make({
458
+ table,
459
+ rowKey,
460
+ message: `Expected exactly one row but found ${decoded.length}.`
461
+ })))));
462
+ const ensureCurrentStorage = Effect.fn("SqliteJournal.ensureCurrentStorage")(function* (sql, failpoint = noFailpoint$1, busyTimeoutMillis = 5e3) {
463
+ yield* sql`PRAGMA foreign_keys = ON`.pipe(Effect.mapError(storageError("enable foreign keys")));
464
+ yield* sql.unsafe(`PRAGMA busy_timeout = ${busyTimeoutMillis}`).pipe(Effect.mapError(storageError("configure busy timeout")));
465
+ const journalModeRows = yield* sql`PRAGMA journal_mode`.pipe(Effect.mapError(storageError("read journal mode")));
466
+ const journalMode = yield* decodeSingleRow(Schema.Array(SqliteJournalModeRow), "pragma_journal_mode", "singleton", journalModeRows);
467
+ if (journalMode.journal_mode.toLowerCase() !== "wal") return yield* SqliteStorageCompatibilityError.make({
468
+ actualVersion: 0,
469
+ supportedVersion: 4,
470
+ message: `SQLite WAL mode is required; the database reported ${journalMode.journal_mode}.`
471
+ });
472
+ const versionRows = yield* sql`PRAGMA user_version`.pipe(Effect.mapError(storageError("read storage version")));
473
+ const version = yield* decodeSingleRow(Schema.Array(SqliteVersionRow), "pragma_user_version", "singleton", versionRows);
474
+ if (version.user_version !== 0 && version.user_version !== 4) return yield* SqliteStorageCompatibilityError.make({
475
+ actualVersion: version.user_version,
476
+ supportedVersion: 4,
477
+ message: `The SQLite file uses private-development storage version ${version.user_version}; this build supports exactly version 4. Reset the database file explicitly; automatic stored-data migrations are not provided during private development.`
478
+ });
479
+ if (version.user_version === 0) {
480
+ const existingRows = yield* sql`
481
+ SELECT name
482
+ FROM sqlite_master
483
+ WHERE type = 'table'
484
+ AND name LIKE 'effect_agent_%'
485
+ ORDER BY name
486
+ `.pipe(Effect.mapError(storageError("inspect unversioned storage")));
487
+ if ((yield* decodeRows(Schema.Array(SqliteNameRow), "sqlite_master", "effect_agent_%", existingRows)).length > 0) return yield* SqliteStorageCompatibilityError.make({
488
+ actualVersion: 0,
489
+ supportedVersion: 4,
490
+ message: "The SQLite file contains unversioned Effect Agent tables. Reset it explicitly; refusing to mutate ambiguous stored data."
491
+ });
492
+ yield* SqliteMigrator.run({ loader: sqliteMigrations }).pipe(Effect.provideService(SqlClient.SqlClient, sql), Effect.mapError((error) => SqliteStorageError.make({
493
+ cause: error,
494
+ operation: "initialize current storage",
495
+ message: error.message
496
+ })));
497
+ }
498
+ const requiredRows = yield* sql`
499
+ SELECT name
500
+ FROM sqlite_master
501
+ WHERE type = 'table'
502
+ AND name IN (
503
+ 'effect_agent_conversations',
504
+ 'effect_agent_canonical_batches',
505
+ 'effect_agent_canonical_records',
506
+ 'effect_agent_checkpoints',
507
+ 'effect_agent_submissions',
508
+ 'effect_agent_submission_ownership',
509
+ 'effect_agent_attempts',
510
+ 'effect_agent_settlement_reservations',
511
+ 'effect_agent_abort_intents',
512
+ 'effect_agent_approval_decisions',
513
+ 'effect_agent_unknown_resolutions'
514
+ )
515
+ ORDER BY name
516
+ `.pipe(Effect.mapError(storageError("verify storage tables")));
517
+ if ((yield* decodeRows(Schema.Array(SqliteNameRow), "sqlite_master", "required_tables", requiredRows)).length !== 11) return yield* SqliteStorageCompatibilityError.make({
518
+ actualVersion: 4,
519
+ supportedVersion: 4,
520
+ message: "The SQLite file claims the current format but is missing required tables. Reset the corrupt private-development data."
521
+ });
522
+ return makeJournal(sql, failpoint);
523
+ });
524
+ const makeJournal = (sql, failpoint) => {
525
+ const classifyWriteFailure = (operation) => (error) => error.reason._tag === "LockTimeoutError" ? SqliteWriteContention.make({
526
+ cause: error,
527
+ operation,
528
+ message: `Another producer holds the SQLite write lock; ${operation} is safe to retry.`
529
+ }) : storageError(operation)(error);
530
+ /**
531
+ * Runs one journal write transaction under `BEGIN IMMEDIATE`. SQLite's deferred `BEGIN`
532
+ * would let a read-then-write transaction start as a reader and fail with
533
+ * SQLITE_BUSY_SNAPSHOT on upgrade, which `busy_timeout` never retries. Taking the write
534
+ * lock up front keeps cross-owner contention inside the bounded busy retry; a lock
535
+ * timeout is classified as the retryable SqliteWriteContention. A failed `BEGIN` leaves
536
+ * no transaction, so no rollback is attempted for it.
537
+ *
538
+ * Journal write transactions are always top level. Nesting one inside another would
539
+ * deadlock the single-connection client, so new journal operations must not wrap this
540
+ * helper inside another transaction.
541
+ */
542
+ const withWriteTransaction = (operation) => (effect) => Effect.uninterruptibleMask((restore) => Effect.scoped(Effect.gen(function* () {
543
+ const connection = yield* sql.reserve.pipe(Effect.mapError(classifyWriteFailure(operation)));
544
+ yield* connection.executeUnprepared("BEGIN IMMEDIATE", [], void 0).pipe(Effect.mapError(classifyWriteFailure(operation)));
545
+ const exit = yield* restore(Effect.provideService(effect, sql.transactionService, [connection, 0])).pipe(Effect.exit);
546
+ if (Exit.isSuccess(exit)) {
547
+ yield* connection.executeUnprepared("COMMIT", [], void 0).pipe(Effect.mapError(classifyWriteFailure(operation)));
548
+ return exit.value;
549
+ }
550
+ yield* Effect.orDie(connection.executeUnprepared("ROLLBACK", [], void 0));
551
+ return yield* exit;
552
+ })).pipe(Effect.withSpan("SqliteJournal.withWriteTransaction", { attributes: { operation } })));
553
+ const materialize = Effect.fn("SqliteJournal.materialize")(function* (conversationId, createdAt, emptyTailDigest, producerEpoch) {
554
+ if (conversationId.length > MAX_IDENTIFIER_LENGTH || storedTextBytes(emptyTailDigest) > MAX_STORED_TEXT_BYTES) return yield* SqliteStorageError.make({
555
+ operation: "materialize conversation",
556
+ message: "Conversation identity or initial digest exceeds the SQLite storage bounds."
557
+ });
558
+ yield* withWriteTransaction("materialize transaction")(Effect.gen(function* () {
559
+ const existingRows = yield* sql`
560
+ SELECT
561
+ conversation_id,
562
+ created_at,
563
+ tail_sequence,
564
+ tail_digest,
565
+ producer_epoch
566
+ FROM effect_agent_conversations
567
+ WHERE conversation_id = ${conversationId}
568
+ `.pipe(Effect.mapError(storageError("read materialized conversation")));
569
+ const existing = yield* decodeRows(Schema.Array(ConversationRow), "effect_agent_conversations", conversationId, existingRows);
570
+ if (existing.length > 1) return yield* SqliteStorageCorruptionError.make({
571
+ table: "effect_agent_conversations",
572
+ rowKey: conversationId,
573
+ message: "A conversation primary key returned more than one row."
574
+ });
575
+ if (existing.length === 0) {
576
+ yield* sql`
577
+ INSERT INTO effect_agent_conversations (
578
+ conversation_id,
579
+ created_at,
580
+ tail_sequence,
581
+ tail_digest,
582
+ producer_epoch
583
+ ) VALUES (
584
+ ${conversationId},
585
+ ${createdAt},
586
+ 0,
587
+ ${emptyTailDigest},
588
+ ${producerEpoch}
589
+ )
590
+ `.pipe(Effect.mapError(storageError("materialize conversation")));
591
+ return;
592
+ }
593
+ if (producerEpoch < existing[0].producer_epoch) return yield* SqliteFenceRejected.make({
594
+ producerEpoch,
595
+ actualEpoch: existing[0].producer_epoch,
596
+ message: `Producer epoch ${producerEpoch} is stale; current epoch is ${existing[0].producer_epoch}.`
597
+ });
598
+ if (producerEpoch > existing[0].producer_epoch) yield* sql`
599
+ UPDATE effect_agent_conversations
600
+ SET producer_epoch = ${producerEpoch}
601
+ WHERE conversation_id = ${conversationId}
602
+ `.pipe(Effect.mapError(storageError("advance materialization epoch")));
603
+ }));
604
+ });
605
+ const getConversation = Effect.fn("SqliteJournal.getConversation")(function* (conversationId) {
606
+ const rows = yield* sql`
607
+ SELECT
608
+ conversation_id,
609
+ created_at,
610
+ tail_sequence,
611
+ tail_digest,
612
+ producer_epoch
613
+ FROM effect_agent_conversations
614
+ WHERE conversation_id = ${conversationId}
615
+ `.pipe(Effect.mapError(storageError("read conversation")));
616
+ return yield* decodeRows(Schema.Array(ConversationRow), "effect_agent_conversations", conversationId, rows);
617
+ });
618
+ const append = Effect.fn("SqliteJournal.append")(function* (request) {
619
+ if (request.conversationId.length > MAX_IDENTIFIER_LENGTH || request.batchId.length > MAX_IDENTIFIER_LENGTH || storedTextBytes(request.batchJson) > MAX_STORED_TEXT_BYTES || storedTextBytes(request.batchDigest) > MAX_STORED_TEXT_BYTES || storedTextBytes(request.tailDigest) > MAX_STORED_TEXT_BYTES || request.records.some((record) => record.recordId.length > MAX_IDENTIFIER_LENGTH || storedTextBytes(record.recordJson) > MAX_STORED_TEXT_BYTES)) return yield* SqliteStorageError.make({
620
+ operation: "append canonical batch",
621
+ message: "Canonical identifiers or encoded JSON exceed the SQLite storage bounds."
622
+ });
623
+ return yield* withWriteTransaction("append transaction")(Effect.gen(function* () {
624
+ const recordIds = request.records.map((record) => record.recordId);
625
+ if (new Set(recordIds).size !== recordIds.length) return yield* SqliteAppendConflict.make({
626
+ message: `Batch ${request.batchId} contains duplicate canonical record IDs.`,
627
+ reason: "record-identity"
628
+ });
629
+ const conversationRows = yield* sql`
630
+ SELECT
631
+ conversation_id,
632
+ created_at,
633
+ tail_sequence,
634
+ tail_digest,
635
+ producer_epoch
636
+ FROM effect_agent_conversations
637
+ WHERE conversation_id = ${request.conversationId}
638
+ `.pipe(Effect.mapError(storageError("read append tail")));
639
+ const conversation = yield* decodeSingleRow(Schema.Array(ConversationRow), "effect_agent_conversations", request.conversationId, conversationRows);
640
+ if (request.producerEpoch !== conversation.producer_epoch) return yield* SqliteFenceRejected.make({
641
+ producerEpoch: request.producerEpoch,
642
+ actualEpoch: conversation.producer_epoch,
643
+ message: `Producer epoch ${request.producerEpoch} is not the current epoch ${conversation.producer_epoch}.`
644
+ });
645
+ const batchRows = yield* sql`
646
+ SELECT
647
+ conversation_id,
648
+ batch_id,
649
+ first_sequence,
650
+ last_sequence,
651
+ batch_digest,
652
+ tail_digest,
653
+ batch_json
654
+ FROM effect_agent_canonical_batches
655
+ WHERE conversation_id = ${request.conversationId}
656
+ AND batch_id = ${request.batchId}
657
+ `.pipe(Effect.mapError(storageError("read idempotent batch")));
658
+ const batches = yield* decodeRows(Schema.Array(BatchRow), "effect_agent_canonical_batches", `${request.conversationId}/${request.batchId}`, batchRows);
659
+ if (batches.length > 1) return yield* SqliteStorageCorruptionError.make({
660
+ table: "effect_agent_canonical_batches",
661
+ rowKey: `${request.conversationId}/${request.batchId}`,
662
+ message: "A canonical batch primary key returned more than one row."
663
+ });
664
+ if (batches.length === 1) {
665
+ const existing = batches[0];
666
+ if (existing.batch_digest !== request.batchDigest) return yield* SqliteAppendConflict.make({
667
+ message: `Batch ${request.batchId} already exists with different canonical content.`,
668
+ reason: "batch-digest"
669
+ });
670
+ return RawAppendResult.make({
671
+ firstSequence: existing.first_sequence,
672
+ lastSequence: existing.last_sequence,
673
+ replayed: true,
674
+ tailDigest: existing.tail_digest
675
+ });
676
+ }
677
+ if (request.expectedTailSequence !== conversation.tail_sequence || request.expectedTailDigest !== conversation.tail_digest) return yield* SqliteAppendConflict.make({
678
+ message: `Expected tail ${request.expectedTailSequence}/${request.expectedTailDigest} but found ${conversation.tail_sequence}/${conversation.tail_digest}.`,
679
+ reason: "tail",
680
+ actualTailSequence: conversation.tail_sequence,
681
+ actualTailDigest: conversation.tail_digest
682
+ });
683
+ if (conversation.tail_sequence + request.records.length > MAX_RECORDS_PER_CONVERSATION) return yield* SqliteStorageError.make({
684
+ operation: "append canonical batch",
685
+ message: `Conversation record limit ${MAX_RECORDS_PER_CONVERSATION} would be exceeded.`
686
+ });
687
+ const existingRecordRows = yield* sql`
688
+ SELECT
689
+ conversation_id,
690
+ sequence,
691
+ record_id,
692
+ batch_id,
693
+ record_json
694
+ FROM effect_agent_canonical_records
695
+ WHERE conversation_id = ${request.conversationId}
696
+ AND record_id IN ${sql.in(recordIds)}
697
+ ORDER BY sequence
698
+ `.pipe(Effect.mapError(storageError("check canonical record identities")));
699
+ const existingRecords = yield* decodeRows(Schema.Array(RecordRow), "effect_agent_canonical_records", `${request.conversationId}/record_ids`, existingRecordRows);
700
+ if (existingRecords.length > 0) return yield* SqliteAppendConflict.make({
701
+ message: `Canonical record ID ${existingRecords[0].record_id} already exists.`,
702
+ reason: "record-identity"
703
+ });
704
+ const firstSequence = yield* Schema.decodeUnknownEffect(CanonicalSequence)(conversation.tail_sequence + 1).pipe(Effect.mapError((error) => SqliteStorageError.make({
705
+ cause: error,
706
+ operation: "append canonical batch",
707
+ message: error.message
708
+ })));
709
+ const lastSequence = yield* Schema.decodeUnknownEffect(CanonicalSequence)(firstSequence + request.records.length - 1).pipe(Effect.mapError((error) => SqliteStorageError.make({
710
+ cause: error,
711
+ operation: "append canonical batch",
712
+ message: error.message
713
+ })));
714
+ yield* sql`
715
+ INSERT INTO effect_agent_canonical_batches (
716
+ conversation_id,
717
+ batch_id,
718
+ first_sequence,
719
+ last_sequence,
720
+ batch_digest,
721
+ tail_digest,
722
+ batch_json
723
+ ) VALUES (
724
+ ${request.conversationId},
725
+ ${request.batchId},
726
+ ${firstSequence},
727
+ ${lastSequence},
728
+ ${request.batchDigest},
729
+ ${request.tailDigest},
730
+ ${request.batchJson}
731
+ )
732
+ `.pipe(Effect.mapError(storageError("insert canonical batch")));
733
+ yield* failpoint("append:after-batch-insert");
734
+ yield* Effect.forEach(request.records, (record, index) => Effect.gen(function* () {
735
+ yield* sql`
736
+ INSERT INTO effect_agent_canonical_records (
737
+ conversation_id,
738
+ sequence,
739
+ record_id,
740
+ batch_id,
741
+ record_json
742
+ ) VALUES (
743
+ ${request.conversationId},
744
+ ${firstSequence + index},
745
+ ${record.recordId},
746
+ ${request.batchId},
747
+ ${record.recordJson}
748
+ )
749
+ `.pipe(Effect.mapError(storageError("insert canonical record")));
750
+ yield* failpoint("append:after-record-insert");
751
+ }), { discard: true });
752
+ yield* sql`
753
+ UPDATE effect_agent_conversations
754
+ SET
755
+ tail_sequence = ${lastSequence},
756
+ tail_digest = ${request.tailDigest},
757
+ producer_epoch = ${request.producerEpoch}
758
+ WHERE conversation_id = ${request.conversationId}
759
+ `.pipe(Effect.mapError(storageError("advance conversation tail")));
760
+ yield* failpoint("append:after-tail-update");
761
+ return RawAppendResult.make({
762
+ firstSequence,
763
+ lastSequence,
764
+ replayed: false,
765
+ tailDigest: request.tailDigest
766
+ });
767
+ }));
768
+ });
769
+ const read = Effect.fn("SqliteJournal.read")(function* (request) {
770
+ const rows = yield* sql`
771
+ SELECT
772
+ conversation_id,
773
+ sequence,
774
+ record_id,
775
+ batch_id,
776
+ record_json
777
+ FROM effect_agent_canonical_records
778
+ WHERE conversation_id = ${request.conversationId}
779
+ AND sequence > ${request.fromSequenceExclusive}
780
+ ORDER BY sequence
781
+ LIMIT ${request.limit}
782
+ `.pipe(Effect.mapError(storageError("read canonical records")));
783
+ return yield* decodeRows(Schema.Array(RecordRow), "effect_agent_canonical_records", `${request.conversationId}>${request.fromSequenceExclusive}`, rows);
784
+ });
785
+ const exportConversation = Effect.fn("SqliteJournal.exportConversation")(function* (conversationId) {
786
+ return yield* sql.withTransaction(Effect.gen(function* () {
787
+ const conversationRows = yield* sql`
788
+ SELECT
789
+ conversation_id,
790
+ created_at,
791
+ tail_sequence,
792
+ tail_digest,
793
+ producer_epoch
794
+ FROM effect_agent_conversations
795
+ WHERE conversation_id = ${conversationId}
796
+ `.pipe(Effect.mapError(storageError("export conversation")));
797
+ const conversation = yield* decodeSingleRow(Schema.Array(ConversationRow), "effect_agent_conversations", conversationId, conversationRows);
798
+ yield* failpoint("export:after-conversation-read");
799
+ const batchRows = yield* sql`
800
+ SELECT
801
+ conversation_id,
802
+ batch_id,
803
+ first_sequence,
804
+ last_sequence,
805
+ batch_digest,
806
+ tail_digest,
807
+ batch_json
808
+ FROM effect_agent_canonical_batches
809
+ WHERE conversation_id = ${conversationId}
810
+ ORDER BY first_sequence
811
+ `.pipe(Effect.mapError(storageError("export canonical batches")));
812
+ const recordRows = yield* sql`
813
+ SELECT
814
+ conversation_id,
815
+ sequence,
816
+ record_id,
817
+ batch_id,
818
+ record_json
819
+ FROM effect_agent_canonical_records
820
+ WHERE conversation_id = ${conversationId}
821
+ ORDER BY sequence
822
+ `.pipe(Effect.mapError(storageError("export canonical records")));
823
+ const checkpointRows = yield* sql`
824
+ SELECT
825
+ conversation_id,
826
+ through_sequence,
827
+ tail_digest,
828
+ checkpoint_json
829
+ FROM effect_agent_checkpoints
830
+ WHERE conversation_id = ${conversationId}
831
+ ORDER BY through_sequence
832
+ `.pipe(Effect.mapError(storageError("export checkpoints")));
833
+ return RawConversationExport.make({
834
+ conversation,
835
+ batches: yield* decodeRows(Schema.Array(BatchRow), "effect_agent_canonical_batches", conversationId, batchRows),
836
+ records: yield* decodeRows(Schema.Array(RecordRow), "effect_agent_canonical_records", conversationId, recordRows),
837
+ checkpoints: yield* decodeRows(Schema.Array(CheckpointRow), "effect_agent_checkpoints", conversationId, checkpointRows)
838
+ });
839
+ })).pipe(Effect.catchTag("SqlError", (error) => Effect.fail(storageError("export transaction")(error))));
840
+ });
841
+ const saveCheckpoint = Effect.fn("SqliteJournal.saveCheckpoint")(function* (checkpoint) {
842
+ if (checkpoint.conversationId.length > MAX_IDENTIFIER_LENGTH || storedTextBytes(checkpoint.checkpointJson) > MAX_STORED_TEXT_BYTES) return yield* SqliteStorageError.make({
843
+ operation: "save checkpoint",
844
+ message: "Checkpoint identity or encoded JSON exceeds the SQLite storage bounds."
845
+ });
846
+ yield* withWriteTransaction("checkpoint transaction")(Effect.gen(function* () {
847
+ const conversationRows = yield* sql`
848
+ SELECT
849
+ conversation_id,
850
+ created_at,
851
+ tail_sequence,
852
+ tail_digest,
853
+ producer_epoch
854
+ FROM effect_agent_conversations
855
+ WHERE conversation_id = ${checkpoint.conversationId}
856
+ `.pipe(Effect.mapError(storageError("read checkpoint tail")));
857
+ const conversation = yield* decodeSingleRow(Schema.Array(ConversationRow), "effect_agent_conversations", checkpoint.conversationId, conversationRows);
858
+ if (checkpoint.throughSequence > conversation.tail_sequence) return yield* SqliteCheckpointConflict.make({ message: `Checkpoint sequence ${checkpoint.throughSequence} is after canonical tail ${conversation.tail_sequence}.` });
859
+ const checkpointRows = yield* sql`
860
+ SELECT
861
+ conversation_id,
862
+ through_sequence,
863
+ tail_digest,
864
+ checkpoint_json
865
+ FROM effect_agent_checkpoints
866
+ WHERE conversation_id = ${checkpoint.conversationId}
867
+ AND through_sequence = ${checkpoint.throughSequence}
868
+ `.pipe(Effect.mapError(storageError("read idempotent checkpoint")));
869
+ const existing = yield* decodeRows(Schema.Array(CheckpointRow), "effect_agent_checkpoints", `${checkpoint.conversationId}/${checkpoint.throughSequence}`, checkpointRows);
870
+ if (existing.length > 1) return yield* SqliteStorageCorruptionError.make({
871
+ table: "effect_agent_checkpoints",
872
+ rowKey: `${checkpoint.conversationId}/${checkpoint.throughSequence}`,
873
+ message: "A checkpoint primary key returned more than one row."
874
+ });
875
+ if (existing.length === 1) {
876
+ if (existing[0].tail_digest !== checkpoint.tailDigest || existing[0].checkpoint_json !== checkpoint.checkpointJson) return yield* SqliteCheckpointConflict.make({ message: "A different checkpoint already exists at this canonical sequence." });
877
+ return;
878
+ }
879
+ yield* sql`
880
+ INSERT INTO effect_agent_checkpoints (
881
+ conversation_id,
882
+ through_sequence,
883
+ tail_digest,
884
+ checkpoint_json
885
+ ) VALUES (
886
+ ${checkpoint.conversationId},
887
+ ${checkpoint.throughSequence},
888
+ ${checkpoint.tailDigest},
889
+ ${checkpoint.checkpointJson}
890
+ )
891
+ `.pipe(Effect.mapError(storageError("insert checkpoint")));
892
+ }));
893
+ });
894
+ const loadCheckpoint = Effect.fn("SqliteJournal.loadCheckpoint")(function* (conversationId, atOrBeforeSequence) {
895
+ const rows = yield* sql`
896
+ SELECT
897
+ conversation_id,
898
+ through_sequence,
899
+ tail_digest,
900
+ checkpoint_json
901
+ FROM effect_agent_checkpoints
902
+ WHERE conversation_id = ${conversationId}
903
+ AND through_sequence <= ${atOrBeforeSequence}
904
+ ORDER BY through_sequence DESC
905
+ LIMIT 1
906
+ `.pipe(Effect.mapError(storageError("load checkpoint")));
907
+ return yield* decodeRows(Schema.Array(CheckpointRow), "effect_agent_checkpoints", `${conversationId}<=${atOrBeforeSequence}`, rows);
908
+ });
909
+ return {
910
+ append,
911
+ exportConversation,
912
+ getConversation,
913
+ getTailDigestAt: Effect.fn("SqliteJournal.getTailDigestAt")(function* (conversationId, sequence) {
914
+ if (sequence === 0) {
915
+ const conversations = yield* getConversation(conversationId);
916
+ return conversations.length === 0 ? [] : [conversations[0].tail_sequence === 0 ? conversations[0].tail_digest : void 0].filter((value) => value !== void 0);
917
+ }
918
+ const rows = yield* sql`
919
+ SELECT
920
+ conversation_id,
921
+ batch_id,
922
+ first_sequence,
923
+ last_sequence,
924
+ batch_digest,
925
+ tail_digest,
926
+ batch_json
927
+ FROM effect_agent_canonical_batches
928
+ WHERE conversation_id = ${conversationId}
929
+ AND last_sequence = ${sequence}
930
+ `.pipe(Effect.mapError(storageError("read canonical digest at sequence")));
931
+ return (yield* decodeRows(Schema.Array(BatchRow), "effect_agent_canonical_batches", `${conversationId}/${sequence}`, rows)).map((batch) => batch.tail_digest);
932
+ }),
933
+ loadCheckpoint,
934
+ materialize,
935
+ read,
936
+ saveCheckpoint,
937
+ scanStoredPayloads: Effect.fn("SqliteJournal.scanStoredPayloads")(function* () {
938
+ return yield* sql.withTransaction(Effect.gen(function* () {
939
+ const conversations = yield* sql`
940
+ SELECT
941
+ conversation_id,
942
+ created_at,
943
+ tail_sequence,
944
+ tail_digest,
945
+ producer_epoch
946
+ FROM effect_agent_conversations
947
+ ORDER BY conversation_id
948
+ `.pipe(Effect.mapError(storageError("scan conversations")));
949
+ const batches = yield* sql`
950
+ SELECT
951
+ conversation_id,
952
+ batch_id,
953
+ first_sequence,
954
+ last_sequence,
955
+ batch_digest,
956
+ tail_digest,
957
+ batch_json
958
+ FROM effect_agent_canonical_batches
959
+ ORDER BY conversation_id, first_sequence
960
+ `.pipe(Effect.mapError(storageError("scan canonical batches")));
961
+ const records = yield* sql`
962
+ SELECT
963
+ conversation_id,
964
+ sequence,
965
+ record_id,
966
+ batch_id,
967
+ record_json
968
+ FROM effect_agent_canonical_records
969
+ ORDER BY conversation_id, sequence
970
+ `.pipe(Effect.mapError(storageError("scan canonical records")));
971
+ const checkpoints = yield* sql`
972
+ SELECT
973
+ conversation_id,
974
+ through_sequence,
975
+ tail_digest,
976
+ checkpoint_json
977
+ FROM effect_agent_checkpoints
978
+ ORDER BY conversation_id, through_sequence
979
+ `.pipe(Effect.mapError(storageError("scan checkpoints")));
980
+ return {
981
+ conversations: yield* decodeRows(Schema.Array(ConversationRow), "effect_agent_conversations", "startup_scan", conversations),
982
+ batches: yield* decodeRows(Schema.Array(BatchRow), "effect_agent_canonical_batches", "startup_scan", batches),
983
+ records: yield* decodeRows(Schema.Array(RecordRow), "effect_agent_canonical_records", "startup_scan", records),
984
+ checkpoints: yield* decodeRows(Schema.Array(CheckpointRow), "effect_agent_checkpoints", "startup_scan", checkpoints)
985
+ };
986
+ })).pipe(Effect.catchTag("SqlError", (error) => Effect.fail(storageError("startup scan transaction")(error))));
987
+ }),
988
+ withWriteTransaction
989
+ };
990
+ };
991
+ const initializeSqliteJournal = ensureCurrentStorage;
992
+ //#endregion
993
+ //#region src/sqlite-storage-config.ts
994
+ const ObservationPollInterval = Schema.Int.check(Schema.isGreaterThanOrEqualTo(0));
995
+ const BusyTimeoutMillis = Schema.Int.check(Schema.isGreaterThanOrEqualTo(0));
996
+ const OwnershipLeaseMillis = Schema.Int.check(Schema.isGreaterThan(0));
997
+ /**
998
+ * Validated construction configuration consumed by the SQLite storage Layer. The database
999
+ * identity itself belongs to the SqlClient Layer; duplicating it here could silently diverge
1000
+ * from the connection actually in use.
1001
+ */
1002
+ var SqliteStorageConfigValue = class extends Schema.Class("@effect-agent/storage-sqlite/SqliteStorageConfigValue")({
1003
+ observationPollInterval: ObservationPollInterval,
1004
+ /** Bounded SQLITE_BUSY retry window for write-lock acquisition, in milliseconds. */
1005
+ busyTimeout: BusyTimeoutMillis,
1006
+ /**
1007
+ * Submission ownership lease duration in milliseconds (D5). The lease is a liveness hint
1008
+ * that makes an abandoned claim reclaimable; correctness never depends on it because every
1009
+ * canonical append is fenced by producer epoch. Convenience layers default this to
1010
+ * `DEFAULT_OWNERSHIP_LEASE_DURATION` from `@effect-agent/session`.
1011
+ */
1012
+ ownershipLeaseDuration: OwnershipLeaseMillis,
1013
+ /**
1014
+ * Re-verify every stored payload and digest chain while opening the store. Per-operation
1015
+ * Schema decoding and the digest chain already fail clearly on corrupt rows, so the full
1016
+ * scan is an explicit opt-in integrity audit rather than a startup requirement.
1017
+ */
1018
+ verifyOnOpen: Schema.Boolean
1019
+ }) {};
1020
+ /** Explicit SQLite storage configuration authority. */
1021
+ var SqliteStorageConfig = class extends Context.Service()("@effect-agent/storage-sqlite/SqliteStorageConfig") {};
1022
+ //#endregion
1023
+ //#region src/sqlite-storage-failpoint.ts
1024
+ const noFailpoint = () => Effect.void;
1025
+ /** Test-only control for replacing the active SQLite failpoint handler. */
1026
+ var SqliteStorageFailpointTestControl = class extends Context.Service()("@effect-agent/storage-sqlite/SqliteStorageFailpointTestControl") {};
1027
+ /** Explicit fault-injection authority used at SQLite operation boundaries. */
1028
+ var SqliteStorageFailpoint = class SqliteStorageFailpoint extends Context.Service()("@effect-agent/storage-sqlite/SqliteStorageFailpoint") {
1029
+ /** Production default: no fault injection. */
1030
+ static layer = Layer.succeed(this)({ hit: noFailpoint });
1031
+ /** Reusable test Layer with a control service backed by the same handler Ref. */
1032
+ static layerTest = Layer.effectContext(Effect.gen(function* () {
1033
+ const handler = yield* Ref.make(noFailpoint);
1034
+ return Context.make(SqliteStorageFailpoint, SqliteStorageFailpoint.of({ hit: (location) => Ref.get(handler).pipe(Effect.flatMap((current) => current(location))) })).pipe(Context.add(SqliteStorageFailpointTestControl, SqliteStorageFailpointTestControl.of({
1035
+ clear: Ref.set(handler, noFailpoint),
1036
+ setHandler: (next) => Ref.set(handler, next)
1037
+ })));
1038
+ }));
1039
+ };
1040
+ //#endregion
1041
+ //#region src/sqlite-conversation-store.ts
1042
+ const OffsetText = Schema.String.check(Schema.isMaxLength(4 * 1024));
1043
+ const SQLITE_OFFSET_PREFIX = "effect-agent-sqlite@1:";
1044
+ const ZERO_CANONICAL_SEQUENCE = Schema.decodeSync(CanonicalSequence)(0);
1045
+ const isDigest = Schema.is(Digest);
1046
+ const storeError = (operation, error) => ConversationStoreError.make({
1047
+ cause: error,
1048
+ operation,
1049
+ message: error.message
1050
+ });
1051
+ const schemaStoreError = (operation, error) => ConversationStoreError.make({
1052
+ cause: error,
1053
+ operation,
1054
+ message: error.message
1055
+ });
1056
+ const makeOffset = Effect.fn("SqliteConversationStore.makeOffset")(function* (conversationId, sequence) {
1057
+ return yield* Schema.decodeUnknownEffect(CanonicalSequence)(sequence).pipe(Effect.flatMap((validatedSequence) => Schema.decodeUnknownEffect(ObservationOffset)(`${SQLITE_OFFSET_PREFIX}${encodeURIComponent(conversationId)}:${validatedSequence}`)), Effect.mapError((error) => schemaStoreError("encode observation offset", error)));
1058
+ });
1059
+ const parseOffset = Effect.fn("SqliteConversationStore.parseOffset")(function* (conversationId, offset) {
1060
+ if (offset === void 0) return ZERO_CANONICAL_SEQUENCE;
1061
+ const text = yield* Schema.decodeUnknownEffect(OffsetText)(offset).pipe(Effect.mapError((error) => schemaStoreError("decode observation offset", error)));
1062
+ const conversationPrefix = `${SQLITE_OFFSET_PREFIX}${encodeURIComponent(conversationId)}:`;
1063
+ if (!text.startsWith(conversationPrefix)) return yield* ConversationStoreError.make({
1064
+ operation: "decode observation offset",
1065
+ message: "The observation offset belongs to a different adapter, storage version, or Conversation."
1066
+ });
1067
+ const sequenceText = text.slice(conversationPrefix.length);
1068
+ if (!/^(0|[1-9][0-9]*)$/.test(sequenceText)) return yield* ConversationStoreError.make({
1069
+ operation: "decode observation offset",
1070
+ message: "The observation offset is malformed."
1071
+ });
1072
+ return yield* Schema.decodeUnknownEffect(CanonicalSequence)(Number(sequenceText)).pipe(Effect.mapError((error) => schemaStoreError("decode observation offset", error)));
1073
+ });
1074
+ const mapFence = (conversationId, error) => FenceRejected.make({
1075
+ conversationId,
1076
+ actualEpoch: error.actualEpoch,
1077
+ attemptedEpoch: error.producerEpoch
1078
+ });
1079
+ const encodeCanonicalRecord = Effect.fn("SqliteConversationStore.encodeCanonicalRecord")(function* (record) {
1080
+ return yield* Schema.encodeEffect(Schema.fromJsonString(CanonicalRecord))(record).pipe(Effect.mapError((error) => schemaStoreError("encode canonical record", error)));
1081
+ });
1082
+ const encodeCanonicalBatch = Effect.fn("SqliteConversationStore.encodeCanonicalBatch")(function* (batch) {
1083
+ return yield* Schema.encodeEffect(Schema.fromJsonString(CanonicalBatch))(batch).pipe(Effect.mapError((error) => schemaStoreError("encode canonical batch", error)));
1084
+ });
1085
+ const encodeCheckpoint = Effect.fn("SqliteConversationStore.encodeCheckpoint")(function* (checkpoint) {
1086
+ return yield* Schema.encodeEffect(Schema.fromJsonString(ConversationCheckpoint))(checkpoint).pipe(Effect.mapError((error) => schemaStoreError("encode checkpoint", error)));
1087
+ });
1088
+ const decodeEnvelope = Effect.fn("SqliteConversationStore.decodeEnvelope")(function* (row) {
1089
+ const record = yield* Schema.decodeEffect(Schema.fromJsonString(CanonicalRecord))(row.record_json).pipe(Effect.mapError((error) => ConversationStoreError.make({
1090
+ operation: "decode canonical record",
1091
+ message: error.message
1092
+ })));
1093
+ const conversationId = yield* Schema.decodeUnknownEffect(CanonicalRecordEnvelope.fields.conversationId)(row.conversation_id).pipe(Effect.mapError((error) => schemaStoreError("decode conversation identity", error)));
1094
+ const offset = yield* makeOffset(conversationId, row.sequence);
1095
+ const batchId = yield* Schema.decodeUnknownEffect(CanonicalRecordEnvelope.fields.batchId)(row.batch_id).pipe(Effect.mapError((error) => schemaStoreError("decode batch identity", error)));
1096
+ return CanonicalRecordEnvelope.make({
1097
+ conversationId,
1098
+ batchId,
1099
+ sequence: row.sequence,
1100
+ offset,
1101
+ record
1102
+ });
1103
+ });
1104
+ const decodeCheckpoint = Effect.fn("SqliteConversationStore.decodeCheckpoint")(function* (checkpointJson) {
1105
+ return yield* Schema.decodeEffect(Schema.fromJsonString(ConversationCheckpoint))(checkpointJson).pipe(Effect.mapError((error) => schemaStoreError("decode checkpoint", error)));
1106
+ });
1107
+ const requireConversation = Effect.fn("SqliteConversationStore.requireConversation")(function* (journal, conversationId) {
1108
+ const rows = yield* journal.getConversation(conversationId).pipe(Effect.mapError((error) => storeError("read conversation", error)));
1109
+ if (rows.length === 0) return yield* ConversationNotMaterialized.make({ conversationId });
1110
+ return rows[0];
1111
+ });
1112
+ const tailDigestAt = Effect.fn("SqliteConversationStore.tailDigestAt")(function* (journal, conversationId, sequence) {
1113
+ if (sequence === 0) return EMPTY_TAIL_DIGEST;
1114
+ const digests = yield* journal.getTailDigestAt(conversationId, sequence).pipe(Effect.mapError((error) => storeError("read checkpoint digest", error)));
1115
+ if (digests.length !== 1) return yield* CheckpointRejected.make({
1116
+ conversationId,
1117
+ reason: "digest-mismatch"
1118
+ });
1119
+ return yield* Schema.decodeUnknownEffect(Digest)(digests[0]).pipe(Effect.mapError((error) => schemaStoreError("decode checkpoint digest", error)));
1120
+ });
1121
+ const groupByKey = (rows, key) => {
1122
+ const grouped = /* @__PURE__ */ new Map();
1123
+ for (const row of rows) {
1124
+ const existing = grouped.get(key(row));
1125
+ if (existing === void 0) grouped.set(key(row), [row]);
1126
+ else existing.push(row);
1127
+ }
1128
+ return grouped;
1129
+ };
1130
+ /**
1131
+ * Opt-in full integrity audit (`verifyOnOpen`). Every stored payload is decoded, re-encoded,
1132
+ * and re-digested against the canonical chain. Routine opens skip this scan: per-operation
1133
+ * Schema decoding plus the digest chain already fail clearly on corrupt rows.
1134
+ */
1135
+ const decodeStartupPayloads = Effect.fn("SqliteConversationStore.decodeStartupPayloads")(function* (journal, crypto) {
1136
+ const stored = yield* journal.scanStoredPayloads();
1137
+ const batches = yield* Effect.forEach(stored.batches, (batch) => Schema.decodeEffect(Schema.fromJsonString(CanonicalBatch))(batch.batch_json).pipe(Effect.map((decoded) => ({
1138
+ decoded,
1139
+ row: batch
1140
+ })), Effect.mapError((error) => SqliteStorageCorruptionError.make({
1141
+ table: "effect_agent_canonical_batches",
1142
+ rowKey: `${batch.conversation_id}/${batch.batch_id}`,
1143
+ message: error.message
1144
+ }))));
1145
+ const records = yield* Effect.forEach(stored.records, (record) => Schema.decodeEffect(Schema.fromJsonString(CanonicalRecord))(record.record_json).pipe(Effect.map((decoded) => ({
1146
+ decoded,
1147
+ row: record
1148
+ })), Effect.mapError((error) => SqliteStorageCorruptionError.make({
1149
+ table: "effect_agent_canonical_records",
1150
+ rowKey: `${record.conversation_id}/${record.sequence}`,
1151
+ message: error.message
1152
+ }))));
1153
+ const checkpoints = yield* Effect.forEach(stored.checkpoints, (checkpoint) => Schema.decodeEffect(Schema.fromJsonString(ConversationCheckpoint))(checkpoint.checkpoint_json).pipe(Effect.map((decoded) => ({
1154
+ decoded,
1155
+ row: checkpoint
1156
+ })), Effect.mapError((error) => SqliteStorageCorruptionError.make({
1157
+ table: "effect_agent_checkpoints",
1158
+ rowKey: `${checkpoint.conversation_id}/${checkpoint.through_sequence}`,
1159
+ message: error.message
1160
+ }))));
1161
+ const batchesByConversation = groupByKey(batches, ({ row }) => row.conversation_id);
1162
+ const recordsByConversation = groupByKey(records, ({ row }) => row.conversation_id);
1163
+ const checkpointsByConversation = groupByKey(checkpoints, ({ row }) => row.conversation_id);
1164
+ const materializedIds = new Set(stored.conversations.map((conversation) => conversation.conversation_id));
1165
+ for (const conversation of stored.conversations) {
1166
+ const conversationBatches = batchesByConversation.get(conversation.conversation_id) ?? [];
1167
+ const conversationRecords = recordsByConversation.get(conversation.conversation_id) ?? [];
1168
+ const conversationCheckpoints = checkpointsByConversation.get(conversation.conversation_id) ?? [];
1169
+ const recordsByBatch = groupByKey(conversationRecords, ({ row }) => row.batch_id);
1170
+ let previousDigest = EMPTY_TAIL_DIGEST;
1171
+ let expectedSequence = 1;
1172
+ const tailDigests = /* @__PURE__ */ new Map([[0, EMPTY_TAIL_DIGEST]]);
1173
+ for (const { decoded: canonicalBatch, row: batchRow } of conversationBatches) {
1174
+ const key = `${batchRow.conversation_id}/${batchRow.batch_id}`;
1175
+ if (canonicalBatch.batchId !== batchRow.batch_id || batchRow.first_sequence !== expectedSequence || batchRow.last_sequence !== batchRow.first_sequence + canonicalBatch.records.length - 1) return yield* SqliteStorageCorruptionError.make({
1176
+ table: "effect_agent_canonical_batches",
1177
+ rowKey: key,
1178
+ message: "Canonical batch identity, sequence, or record count is inconsistent."
1179
+ });
1180
+ const digest = yield* digestCanonicalBatch(previousDigest, canonicalBatch).pipe(Effect.provideService(Crypto.Crypto, crypto), Effect.mapError((error) => SqliteStorageCorruptionError.make({
1181
+ table: "effect_agent_canonical_batches",
1182
+ rowKey: key,
1183
+ message: error.message
1184
+ })));
1185
+ if (batchRow.batch_digest !== digest || batchRow.tail_digest !== digest) return yield* SqliteStorageCorruptionError.make({
1186
+ table: "effect_agent_canonical_batches",
1187
+ rowKey: key,
1188
+ message: "Canonical batch digest does not match its decoded content and prior tail."
1189
+ });
1190
+ const batchRecords = recordsByBatch.get(batchRow.batch_id) ?? [];
1191
+ if (batchRecords.length !== canonicalBatch.records.length) return yield* SqliteStorageCorruptionError.make({
1192
+ table: "effect_agent_canonical_records",
1193
+ rowKey: key,
1194
+ message: "Canonical batch and record-table counts differ."
1195
+ });
1196
+ for (let index = 0; index < canonicalBatch.records.length; index++) {
1197
+ const expectedRecord = canonicalBatch.records[index];
1198
+ const storedRecord = batchRecords[index];
1199
+ const expectedJson = yield* Schema.encodeEffect(Schema.fromJsonString(CanonicalRecord))(expectedRecord).pipe(Effect.mapError((error) => SqliteStorageCorruptionError.make({
1200
+ table: "effect_agent_canonical_batches",
1201
+ rowKey: key,
1202
+ message: error.message
1203
+ })));
1204
+ const storedJson = yield* Schema.encodeEffect(Schema.fromJsonString(CanonicalRecord))(storedRecord.decoded).pipe(Effect.mapError((error) => SqliteStorageCorruptionError.make({
1205
+ table: "effect_agent_canonical_records",
1206
+ rowKey: `${key}/${storedRecord.row.sequence}`,
1207
+ message: error.message
1208
+ })));
1209
+ if (storedRecord.row.sequence !== batchRow.first_sequence + index || storedRecord.row.record_id !== expectedRecord.recordId || expectedJson !== storedJson) return yield* SqliteStorageCorruptionError.make({
1210
+ table: "effect_agent_canonical_records",
1211
+ rowKey: `${key}/${storedRecord.row.sequence}`,
1212
+ message: "Canonical record identity, sequence, or payload differs from its batch."
1213
+ });
1214
+ }
1215
+ previousDigest = digest;
1216
+ expectedSequence = batchRow.last_sequence + 1;
1217
+ tailDigests.set(batchRow.last_sequence, digest);
1218
+ }
1219
+ if (conversationRecords.length !== conversation.tail_sequence || conversation.tail_sequence !== expectedSequence - 1 || conversation.tail_digest !== previousDigest) return yield* SqliteStorageCorruptionError.make({
1220
+ table: "effect_agent_conversations",
1221
+ rowKey: conversation.conversation_id,
1222
+ message: "Conversation tail does not match its canonical batch chain."
1223
+ });
1224
+ for (const checkpoint of conversationCheckpoints) if (checkpoint.decoded.conversationId !== conversation.conversation_id || checkpoint.decoded.throughSequence !== checkpoint.row.through_sequence || checkpoint.decoded.tailDigest !== checkpoint.row.tail_digest || tailDigests.get(checkpoint.row.through_sequence) !== checkpoint.row.tail_digest) return yield* SqliteStorageCorruptionError.make({
1225
+ table: "effect_agent_checkpoints",
1226
+ rowKey: `${conversation.conversation_id}/${checkpoint.row.through_sequence}`,
1227
+ message: "Checkpoint identity or digest is not bound to a canonical batch tail."
1228
+ });
1229
+ }
1230
+ if (batches.some(({ row }) => !materializedIds.has(row.conversation_id)) || records.some(({ row }) => !materializedIds.has(row.conversation_id)) || checkpoints.some(({ row }) => !materializedIds.has(row.conversation_id))) return yield* SqliteStorageCorruptionError.make({
1231
+ table: "effect_agent_conversations",
1232
+ rowKey: "startup_scan",
1233
+ message: "Canonical rows exist without a materialized Conversation."
1234
+ });
1235
+ });
1236
+ const makeServices$1 = Effect.fn("SqliteConversationStore.makeServices")(function* () {
1237
+ const config = yield* SqliteStorageConfig;
1238
+ const failpoint = yield* SqliteStorageFailpoint;
1239
+ const sql = yield* SqlClient.SqlClient;
1240
+ const crypto = yield* Crypto.Crypto;
1241
+ const journal = yield* initializeSqliteJournal(sql, failpoint.hit, config.busyTimeout);
1242
+ if (config.verifyOnOpen) yield* decodeStartupPayloads(journal, crypto);
1243
+ const provideCrypto = (effect) => Effect.provideService(effect, Crypto.Crypto, crypto);
1244
+ const hitFailpoint = Effect.fn("SqliteConversationStore.hitFailpoint")((location) => failpoint.hit(location).pipe(Effect.mapError((error) => storeError(`storage failpoint ${location}`, error))));
1245
+ const materialize = Effect.fn("SqliteConversationStore.materialize")(function* (request) {
1246
+ const validated = yield* Schema.decodeUnknownEffect(Schema.toType(ConversationMaterialization))(request).pipe(Effect.mapError((error) => schemaStoreError("validate materialization", error)));
1247
+ const now = yield* Clock.currentTimeMillis;
1248
+ yield* hitFailpoint("materialize:before");
1249
+ yield* journal.materialize(validated.conversationId, new Date(now).toISOString(), EMPTY_TAIL_DIGEST, validated.producerEpoch).pipe(Effect.mapError((error) => error._tag === "SqliteFenceRejected" ? mapFence(validated.conversationId, error) : storeError("materialize conversation", error)));
1250
+ yield* hitFailpoint("materialize:after");
1251
+ });
1252
+ const append = Effect.fn("SqliteConversationStore.append")(function* (request) {
1253
+ const validated = yield* Schema.decodeUnknownEffect(Schema.toType(FencedAppendRequest))(request).pipe(Effect.mapError((error) => schemaStoreError("validate canonical append", error)));
1254
+ yield* requireConversation(journal, validated.conversationId);
1255
+ const tailDigest = yield* provideCrypto(digestCanonicalBatch(validated.expectedTailDigest, validated.batch)).pipe(Effect.mapError((error) => storeError("digest canonical append", error)));
1256
+ const batchJson = yield* encodeCanonicalBatch(validated.batch);
1257
+ const rawRecords = yield* Effect.forEach(validated.batch.records, (record) => encodeCanonicalRecord(record).pipe(Effect.map((recordJson) => ({
1258
+ recordId: record.recordId,
1259
+ recordJson
1260
+ }))));
1261
+ const rawRequest = yield* Schema.decodeUnknownEffect(RawAppendRequest)({
1262
+ conversationId: validated.conversationId,
1263
+ batchId: validated.batch.batchId,
1264
+ batchDigest: tailDigest,
1265
+ batchJson,
1266
+ expectedTailSequence: validated.expectedTailSequence,
1267
+ expectedTailDigest: validated.expectedTailDigest,
1268
+ producerEpoch: validated.producerEpoch,
1269
+ records: rawRecords,
1270
+ tailDigest
1271
+ }).pipe(Effect.mapError((error) => schemaStoreError("encode canonical append", error)));
1272
+ yield* hitFailpoint("append:before");
1273
+ const result = yield* journal.append(rawRequest).pipe(Effect.mapError((error) => {
1274
+ if (error instanceof SqliteFenceRejected) return mapFence(validated.conversationId, error);
1275
+ if (error instanceof SqliteAppendConflict) return error.actualTailSequence !== void 0 && isDigest(error.actualTailDigest) ? AppendConflict.make({
1276
+ conversationId: validated.conversationId,
1277
+ batchId: validated.batch.batchId,
1278
+ reason: error.reason,
1279
+ actualTailSequence: error.actualTailSequence,
1280
+ actualTailDigest: error.actualTailDigest
1281
+ }) : AppendConflict.make({
1282
+ conversationId: validated.conversationId,
1283
+ batchId: validated.batch.batchId,
1284
+ reason: error.reason
1285
+ });
1286
+ return storeError("append canonical batch", error);
1287
+ }), Effect.flatMap((result) => Schema.decodeUnknownEffect(AppendResult)(result).pipe(Effect.mapError((error) => schemaStoreError("decode append result", error)))));
1288
+ yield* hitFailpoint("append:after");
1289
+ return result;
1290
+ });
1291
+ const loadRecords = Effect.fn("SqliteConversationStore.loadRecords")(function* (request) {
1292
+ const rows = yield* journal.read(request).pipe(Effect.mapError((error) => storeError("read canonical records", error)));
1293
+ return yield* Effect.forEach(rows, decodeEnvelope);
1294
+ });
1295
+ const readEffect = Effect.fn("SqliteConversationStore.read")(function* (request) {
1296
+ const validated = yield* Schema.decodeUnknownEffect(Schema.toType(ConversationRead))(request).pipe(Effect.mapError((error) => schemaStoreError("validate conversation read", error)));
1297
+ yield* requireConversation(journal, validated.conversationId);
1298
+ const records = yield* loadRecords(RawReadRequest.make({
1299
+ conversationId: validated.conversationId,
1300
+ fromSequenceExclusive: validated.afterSequence ?? ZERO_CANONICAL_SEQUENCE,
1301
+ limit: validated.limit
1302
+ }));
1303
+ return Stream.fromIterable(records);
1304
+ });
1305
+ const read = (request) => Stream.unwrap(readEffect(request));
1306
+ const observeEffect = Effect.fn("SqliteConversationStore.observe")(function* (request) {
1307
+ const validated = yield* Schema.decodeUnknownEffect(Schema.toType(ConversationObservation))(request).pipe(Effect.mapError((error) => schemaStoreError("validate conversation observation", error)));
1308
+ yield* requireConversation(journal, validated.conversationId);
1309
+ const initialSequence = yield* parseOffset(validated.conversationId, validated.afterOffset);
1310
+ const cursor = yield* Ref.make(initialSequence);
1311
+ const poll = Effect.fn("SqliteConversationStore.observePoll")(function* () {
1312
+ const fromSequenceExclusive = yield* Ref.get(cursor);
1313
+ const records = yield* loadRecords(RawReadRequest.make({
1314
+ conversationId: validated.conversationId,
1315
+ fromSequenceExclusive,
1316
+ limit: 1024
1317
+ }));
1318
+ if (records.length === 0) {
1319
+ yield* Effect.sleep(config.observationPollInterval);
1320
+ return [];
1321
+ }
1322
+ yield* Ref.set(cursor, records[records.length - 1].sequence);
1323
+ return records;
1324
+ });
1325
+ return Stream.fromIterableEffectRepeat(poll());
1326
+ });
1327
+ const observe = (request) => Stream.unwrap(observeEffect(request));
1328
+ const exportConversation = Effect.fn("SqliteConversationStore.export")(function* (request) {
1329
+ const validated = yield* Schema.decodeUnknownEffect(Schema.toType(ConversationExportRequest))(request).pipe(Effect.mapError((error) => schemaStoreError("validate conversation export", error)));
1330
+ yield* requireConversation(journal, validated.conversationId);
1331
+ const exported = yield* journal.exportConversation(validated.conversationId).pipe(Effect.mapError((error) => storeError("export conversation", error)));
1332
+ const records = yield* Effect.forEach(exported.records, decodeEnvelope);
1333
+ if (records.length > 65536) return yield* ConversationStoreError.make({
1334
+ operation: "decode conversation export",
1335
+ message: "The conversation exceeds the current export record limit."
1336
+ });
1337
+ const tailDigest = yield* Schema.decodeUnknownEffect(Digest)(exported.conversation.tail_digest).pipe(Effect.mapError((error) => schemaStoreError("decode export tail digest", error)));
1338
+ return ConversationExport.make({
1339
+ format: "effect-agent/conversation@1",
1340
+ conversationId: validated.conversationId,
1341
+ tailSequence: exported.conversation.tail_sequence,
1342
+ tailDigest,
1343
+ records
1344
+ });
1345
+ });
1346
+ const inspectTail = Effect.fn("SqliteConversationStore.inspectTail")(function* (request) {
1347
+ const validated = yield* Schema.decodeUnknownEffect(Schema.toType(ConversationTailRequest))(request).pipe(Effect.mapError((error) => schemaStoreError("validate tail inspection", error)));
1348
+ const conversation = yield* requireConversation(journal, validated.conversationId);
1349
+ const tailDigest = yield* Schema.decodeUnknownEffect(Digest)(conversation.tail_digest).pipe(Effect.mapError((error) => schemaStoreError("decode tail digest", error)));
1350
+ return ConversationTail.make({
1351
+ conversationId: validated.conversationId,
1352
+ tailSequence: conversation.tail_sequence,
1353
+ tailDigest,
1354
+ producerEpoch: conversation.producer_epoch
1355
+ });
1356
+ });
1357
+ const saveCheckpoint = Effect.fn("SqliteConversationStore.saveCheckpoint")(function* (request) {
1358
+ const validated = yield* Schema.decodeUnknownEffect(Schema.toType(SaveCheckpointRequest))(request).pipe(Effect.mapError((error) => schemaStoreError("validate checkpoint", error)));
1359
+ const conversation = yield* requireConversation(journal, validated.checkpoint.conversationId);
1360
+ if (validated.checkpoint.throughSequence > conversation.tail_sequence) return yield* CheckpointRejected.make({
1361
+ conversationId: validated.checkpoint.conversationId,
1362
+ reason: "ahead-of-tail"
1363
+ });
1364
+ if ((yield* tailDigestAt(journal, validated.checkpoint.conversationId, validated.checkpoint.throughSequence)) !== validated.checkpoint.tailDigest) return yield* CheckpointRejected.make({
1365
+ conversationId: validated.checkpoint.conversationId,
1366
+ reason: "digest-mismatch"
1367
+ });
1368
+ const checkpointJson = yield* encodeCheckpoint(validated.checkpoint);
1369
+ const raw = RawCheckpoint.make({
1370
+ conversationId: validated.checkpoint.conversationId,
1371
+ throughSequence: validated.checkpoint.throughSequence,
1372
+ tailDigest: validated.checkpoint.tailDigest,
1373
+ checkpointJson
1374
+ });
1375
+ yield* hitFailpoint("save-checkpoint:before");
1376
+ yield* journal.saveCheckpoint(raw).pipe(Effect.mapError((error) => error instanceof SqliteCheckpointConflict ? CheckpointRejected.make({
1377
+ conversationId: validated.checkpoint.conversationId,
1378
+ reason: "digest-mismatch"
1379
+ }) : storeError("save checkpoint", error)));
1380
+ yield* hitFailpoint("save-checkpoint:after");
1381
+ });
1382
+ const loadCheckpoint = Effect.fn("SqliteConversationStore.loadCheckpoint")(function* (request) {
1383
+ const validated = yield* Schema.decodeUnknownEffect(Schema.toType(LoadCheckpointRequest))(request).pipe(Effect.mapError((error) => schemaStoreError("validate checkpoint lookup", error)));
1384
+ const conversation = yield* requireConversation(journal, validated.conversationId);
1385
+ const rows = yield* journal.loadCheckpoint(validated.conversationId, validated.atOrBeforeSequence ?? conversation.tail_sequence).pipe(Effect.mapError((error) => storeError("load checkpoint", error)));
1386
+ if (rows.length === 0) return Option.none();
1387
+ if (rows.length !== 1) return yield* ConversationStoreError.make({
1388
+ operation: "load checkpoint",
1389
+ message: `Expected at most one checkpoint row but found ${rows.length}.`
1390
+ });
1391
+ const checkpoint = yield* decodeCheckpoint(rows[0].checkpoint_json);
1392
+ if ((yield* tailDigestAt(journal, checkpoint.conversationId, checkpoint.throughSequence)) !== checkpoint.tailDigest) return yield* CheckpointRejected.make({
1393
+ conversationId: checkpoint.conversationId,
1394
+ reason: "digest-mismatch"
1395
+ });
1396
+ return Option.some(checkpoint);
1397
+ });
1398
+ const conversationStore = ConversationStore.of({
1399
+ append,
1400
+ export: exportConversation,
1401
+ inspectTail,
1402
+ loadCheckpoint,
1403
+ materialize,
1404
+ observe,
1405
+ read,
1406
+ saveCheckpoint
1407
+ });
1408
+ return Context.make(ConversationStore, conversationStore);
1409
+ });
1410
+ /**
1411
+ * SQLite Conversation Store implementation with configuration, failpoint, SQL, and Crypto
1412
+ * authority kept visible in its input channel.
1413
+ */
1414
+ const conversationStoreLayer = Layer.effectContext(makeServices$1());
1415
+ /**
1416
+ * Validated SQLite storage configuration Layer with the documented defaults applied. Shared
1417
+ * by the ConversationStore and SubmissionLedger convenience layers so their defaults cannot
1418
+ * drift.
1419
+ */
1420
+ const storageConfigLayer = (options) => Layer.effect(SqliteStorageConfig)(Schema.decodeUnknownEffect(SqliteStorageConfigValue)({
1421
+ observationPollInterval: options.observationPollInterval ?? 25,
1422
+ busyTimeout: options.busyTimeout ?? 5e3,
1423
+ ownershipLeaseDuration: options.ownershipLeaseDuration ?? Duration.toMillis(DEFAULT_OWNERSHIP_LEASE_DURATION),
1424
+ verifyOnOpen: options.verifyOnOpen ?? false
1425
+ }).pipe(Effect.mapError((error) => SqliteStorageError.make({
1426
+ cause: error,
1427
+ operation: "configure SQLite storage",
1428
+ message: error.message
1429
+ }))));
1430
+ /** The failpoint Layer selected by convenience options: explicit handler or the no-op default. */
1431
+ const storageFailpointLayer = (options) => options.failpoint === void 0 ? SqliteStorageFailpoint.layer : Layer.succeed(SqliteStorageFailpoint)({ hit: options.failpoint });
1432
+ /**
1433
+ * A composition-root convenience Layer for canonical Conversations. Durable accepted work is
1434
+ * served by the separate SubmissionLedger port.
1435
+ */
1436
+ const layer = (options) => {
1437
+ const sqlLayer = SqliteClient.layer({ filename: options.filename });
1438
+ return conversationStoreLayer.pipe(Layer.provide(Layer.mergeAll(storageConfigLayer(options), storageFailpointLayer(options), sqlLayer, NodeCrypto.layer)));
1439
+ };
1440
+ /** Create an adapter-owned resumable observation offset for a known canonical sequence. */
1441
+ const observationOffsetAt = makeOffset;
1442
+ //#endregion
1443
+ //#region src/sqlite-ledger.ts
1444
+ const BoundedStoredText = Schema.String.check(Schema.isMaxLength(16 * 1024 * 1024));
1445
+ const BoundedIdentifier = Schema.NonEmptyString.check(Schema.isMaxLength(1024));
1446
+ const BoundedTimestamp = Schema.NonEmptyString.check(Schema.isMaxLength(128));
1447
+ const SCAN_PAGE_SIZE = 256;
1448
+ const EPOCH_ZERO = Schema.decodeSync(ProducerEpoch)(0);
1449
+ var SubmissionRow = class extends Schema.Class("SubmissionRow")({
1450
+ submission_id: BoundedIdentifier,
1451
+ conversation_id: BoundedIdentifier,
1452
+ queue_sequence: QueueSequence,
1453
+ principal: BoundedIdentifier,
1454
+ idempotency_key: BoundedIdentifier,
1455
+ agent_id: BoundedIdentifier,
1456
+ agent_digests_json: BoundedStoredText,
1457
+ deployment_id: BoundedIdentifier,
1458
+ input_json: BoundedStoredText,
1459
+ input_digest: Digest,
1460
+ receipt_id: BoundedIdentifier,
1461
+ state: SubmissionState,
1462
+ settled_outcome: Schema.NullOr(SettlementOutcome),
1463
+ created_at: BoundedTimestamp,
1464
+ ready_at: Schema.NullOr(BoundedTimestamp),
1465
+ input_applied_record_id: Schema.NullOr(BoundedIdentifier),
1466
+ input_applied_sequence: Schema.NullOr(CanonicalSequence),
1467
+ joined_host_submission_id: Schema.NullOr(BoundedIdentifier),
1468
+ suspended_reason_json: Schema.NullOr(BoundedStoredText),
1469
+ suspended_at: Schema.NullOr(BoundedTimestamp),
1470
+ unknown_reason: Schema.NullOr(BoundedStoredText),
1471
+ unknown_tool_call_ids_json: Schema.NullOr(BoundedStoredText),
1472
+ parent_submission_id: Schema.NullOr(BoundedIdentifier),
1473
+ parent_tool_call_id: Schema.NullOr(BoundedIdentifier)
1474
+ }) {};
1475
+ var ChildReservationRow = class extends Schema.Class("ChildReservationRow")({
1476
+ reservation_id: BoundedIdentifier,
1477
+ parent_submission_id: BoundedIdentifier,
1478
+ parent_tool_call_id: BoundedIdentifier,
1479
+ child_submission_id: Schema.NullOr(BoundedIdentifier),
1480
+ status: ChildReservationStatus,
1481
+ allocation_json: BoundedStoredText,
1482
+ allocation_digest: Digest,
1483
+ accounting_json: Schema.NullOr(BoundedStoredText),
1484
+ reserved_at: BoundedTimestamp,
1485
+ release_began_at: Schema.NullOr(BoundedTimestamp),
1486
+ released_at: Schema.NullOr(BoundedTimestamp)
1487
+ }) {};
1488
+ var ApprovalDecisionRow = class extends Schema.Class("ApprovalDecisionRow")({
1489
+ submission_id: BoundedIdentifier,
1490
+ tool_call_id: BoundedIdentifier,
1491
+ decision: ApprovalDecision,
1492
+ resolver: BoundedIdentifier,
1493
+ reason: BoundedStoredText,
1494
+ decided_at: BoundedTimestamp
1495
+ }) {};
1496
+ var UnknownResolutionRow = class extends Schema.Class("UnknownResolutionRow")({
1497
+ submission_id: BoundedIdentifier,
1498
+ tool_call_id: BoundedIdentifier,
1499
+ author: BoundedIdentifier,
1500
+ reason: BoundedStoredText,
1501
+ resolution_json: BoundedStoredText,
1502
+ resolved_at: BoundedTimestamp
1503
+ }) {};
1504
+ var OwnershipRow = class extends Schema.Class("OwnershipRow")({
1505
+ submission_id: BoundedIdentifier,
1506
+ attempt_id: BoundedIdentifier,
1507
+ ownership_token: BoundedIdentifier,
1508
+ producer_epoch: ProducerEpoch,
1509
+ owner_producer_id: BoundedIdentifier,
1510
+ lease_expires_at: BoundedTimestamp
1511
+ }) {};
1512
+ var ReservationRow = class extends Schema.Class("ReservationRow")({
1513
+ submission_id: BoundedIdentifier,
1514
+ settlement_id: BoundedIdentifier,
1515
+ outcome: SettlementOutcome,
1516
+ record_id: BoundedIdentifier,
1517
+ record_json: BoundedStoredText,
1518
+ record_digest: Digest,
1519
+ reserved_at: BoundedTimestamp,
1520
+ finalized_at: Schema.NullOr(BoundedTimestamp)
1521
+ }) {};
1522
+ var AbortIntentRow = class extends Schema.Class("AbortIntentRow")({
1523
+ submission_id: BoundedIdentifier,
1524
+ author: BoundedIdentifier,
1525
+ reason: BoundedStoredText,
1526
+ requested_at: BoundedTimestamp,
1527
+ canonical_record_id: Schema.NullOr(BoundedIdentifier)
1528
+ }) {};
1529
+ var MaxQueueSequenceRow = class extends Schema.Class("MaxQueueSequenceRow")({ max_queue_sequence: Schema.Int.check(Schema.isGreaterThanOrEqualTo(0)) }) {};
1530
+ var CanonicalRecordIdRow = class extends Schema.Class("CanonicalRecordIdRow")({ record_id: BoundedIdentifier }) {};
1531
+ const SUBMISSION_COLUMNS = `
1532
+ submission_id,
1533
+ conversation_id,
1534
+ queue_sequence,
1535
+ principal,
1536
+ idempotency_key,
1537
+ agent_id,
1538
+ agent_digests_json,
1539
+ deployment_id,
1540
+ input_json,
1541
+ input_digest,
1542
+ receipt_id,
1543
+ state,
1544
+ settled_outcome,
1545
+ created_at,
1546
+ ready_at,
1547
+ input_applied_record_id,
1548
+ input_applied_sequence,
1549
+ joined_host_submission_id,
1550
+ suspended_reason_json,
1551
+ suspended_at,
1552
+ unknown_reason,
1553
+ unknown_tool_call_ids_json,
1554
+ parent_submission_id,
1555
+ parent_tool_call_id
1556
+ `;
1557
+ const CHILD_RESERVATION_COLUMNS = `
1558
+ reservation_id,
1559
+ parent_submission_id,
1560
+ parent_tool_call_id,
1561
+ child_submission_id,
1562
+ status,
1563
+ allocation_json,
1564
+ allocation_digest,
1565
+ accounting_json,
1566
+ reserved_at,
1567
+ release_began_at,
1568
+ released_at
1569
+ `;
1570
+ /** The branded ToolCallId schema, reached through the session port so no core import is needed. */
1571
+ const ToolCallIdSchema = ApprovalDecisionCommand.fields.toolCallId;
1572
+ const ToolCallIdList = Schema.Array(ToolCallIdSchema);
1573
+ const encodePersistedJsonText = Schema.encodeEffect(Schema.fromJsonString(PersistedJson));
1574
+ const encodeDefinitionDigestsText = Schema.encodeEffect(Schema.fromJsonString(DefinitionDigests));
1575
+ const encodeRecordEnvelopeText = Schema.encodeEffect(Schema.fromJsonString(RecordEnvelope));
1576
+ const decodeRecordEnvelopeText = Schema.decodeEffect(Schema.fromJsonString(RecordEnvelope));
1577
+ const encodeSuspensionReasonText = Schema.encodeEffect(Schema.fromJsonString(SuspensionReason));
1578
+ const encodeUnknownResolutionText = Schema.encodeEffect(Schema.fromJsonString(UnknownResolution));
1579
+ const encodeToolCallIdsText = Schema.encodeEffect(Schema.fromJsonString(ToolCallIdList));
1580
+ const decodeToolCallIdsText = Schema.decodeEffect(Schema.fromJsonString(ToolCallIdList));
1581
+ const parseStoredJsonText = Schema.decodeEffect(Schema.fromJsonString(Schema.Json));
1582
+ const decodeAdmissionResult = Schema.decodeUnknownEffect(AdmissionResult);
1583
+ const decodeClaim = Schema.decodeUnknownEffect(Claim);
1584
+ const decodeOwnershipRenewal = Schema.decodeUnknownEffect(OwnershipRenewal);
1585
+ const decodeSettlement = Schema.decodeUnknownEffect(Settlement);
1586
+ const decodeAbortIntent = Schema.decodeUnknownEffect(AbortIntent);
1587
+ const decodeOwnershipSnapshot = Schema.decodeUnknownEffect(OwnershipSnapshot);
1588
+ const decodeInputAppliedMarker = Schema.decodeUnknownEffect(InputAppliedMarker);
1589
+ const decodeSubmissionSnapshotUnknown = Schema.decodeUnknownEffect(SubmissionSnapshot);
1590
+ const decodeSubmissionId = Schema.decodeUnknownEffect(SubmissionSnapshot.fields.submissionId);
1591
+ const decodeQueueSequence = Schema.decodeUnknownEffect(QueueSequence);
1592
+ const decodeUtcInstant = Schema.decodeUnknownEffect(Schema.DateTimeUtcFromString);
1593
+ const decodeJoiningClaim = Schema.decodeUnknownEffect(JoiningClaim);
1594
+ const decodeJoinSnapshot = Schema.decodeUnknownEffect(JoinSnapshot);
1595
+ const decodeSuspensionSnapshot = Schema.decodeUnknownEffect(SuspensionSnapshot);
1596
+ const decodeApprovalDecisionIntent = Schema.decodeUnknownEffect(ApprovalDecisionIntent);
1597
+ const decodeUnknownResolutionIntent = Schema.decodeUnknownEffect(UnknownResolutionIntent);
1598
+ const decodeParentLinkage = Schema.decodeUnknownEffect(ParentLinkage);
1599
+ const decodeChildReservationSnapshotUnknown = Schema.decodeUnknownEffect(ChildBudgetReservationSnapshot);
1600
+ const decodeChildAttachmentSnapshot = Schema.decodeUnknownEffect(ChildAttachmentSnapshot);
1601
+ /** Wrap an adapter-internal failure into the port's LedgerError without erasing its tag. */
1602
+ const internalFailure = (operation) => (error) => LedgerError.make({
1603
+ operation,
1604
+ message: error.message,
1605
+ cause: error
1606
+ });
1607
+ /** Classify raw SQL failures: write-lock timeouts stay retryable typed contention. */
1608
+ const sqlFailure = (operation) => (error) => {
1609
+ const internal = error.reason._tag === "LockTimeoutError" ? SqliteWriteContention.make({
1610
+ cause: error,
1611
+ operation,
1612
+ message: `Another producer holds the SQLite write lock; ${operation} is safe to retry.`
1613
+ }) : SqliteLedgerError.make({
1614
+ cause: error,
1615
+ operation,
1616
+ message: error.message
1617
+ });
1618
+ return internalFailure(operation)(internal);
1619
+ };
1620
+ const corruptionFailure = (operation, table, rowKey, message) => internalFailure(operation)(SqliteStorageCorruptionError.make({
1621
+ table,
1622
+ rowKey,
1623
+ message
1624
+ }));
1625
+ const makeServices = Effect.fn("SqliteSubmissionLedger.makeServices")(function* () {
1626
+ const config = yield* SqliteStorageConfig;
1627
+ const failpoint = yield* SqliteStorageFailpoint;
1628
+ const sql = yield* SqlClient.SqlClient;
1629
+ const crypto = yield* Crypto.Crypto;
1630
+ const journal = yield* initializeSqliteJournal(sql, failpoint.hit, config.busyTimeout);
1631
+ const hitFailpoint = (location, operation) => failpoint.hit(location).pipe(Effect.mapError((error) => internalFailure(operation)(error)));
1632
+ /**
1633
+ * Run one ledger mutation under the journal's `BEGIN IMMEDIATE` write transaction so
1634
+ * ownership-token and epoch checks are atomic with their writes (DUR-006). Transaction
1635
+ * acquisition failures surface as LedgerError carrying the typed retryable
1636
+ * SqliteWriteContention (or SqliteStorageError) as cause.
1637
+ */
1638
+ const inWriteTransaction = (operation, effect) => journal.withWriteTransaction(operation)(effect).pipe(Effect.mapError((error) => error instanceof SqliteStorageError || error instanceof SqliteWriteContention ? internalFailure(operation)(error) : error));
1639
+ const mintIdentifier = (prefix, operation) => crypto.randomUUIDv7.pipe(Effect.map((uuid) => `${prefix}-${uuid}`), Effect.mapError((error) => internalFailure(operation)(error)));
1640
+ const currentInstant = Effect.map(Clock.currentTimeMillis, (millis) => ({
1641
+ millis,
1642
+ iso: new Date(millis).toISOString()
1643
+ }));
1644
+ const timestampMillis = (operation, rowKey) => (timestamp) => decodeUtcInstant(timestamp).pipe(Effect.map(DateTime.toEpochMillis), Effect.mapError((error) => corruptionFailure(operation, "effect_agent_submission_ownership", rowKey, error.message)));
1645
+ const decodeSubmissionRows = (operation, rowKey, rows) => decodeRows(Schema.Array(SubmissionRow), "effect_agent_submissions", rowKey, rows).pipe(Effect.mapError(internalFailure(operation)));
1646
+ const readSubmission = Effect.fn("SqliteSubmissionLedger.readSubmission")(function* (operation, submissionId) {
1647
+ const rows = yield* sql`
1648
+ SELECT ${sql.literal(SUBMISSION_COLUMNS)}
1649
+ FROM effect_agent_submissions
1650
+ WHERE submission_id = ${submissionId}
1651
+ `.pipe(Effect.mapError(sqlFailure(operation)));
1652
+ const decoded = yield* decodeSubmissionRows(operation, submissionId, rows);
1653
+ if (decoded.length > 1) return yield* corruptionFailure(operation, "effect_agent_submissions", submissionId, "A submission primary key returned more than one row.");
1654
+ return decoded.length === 0 ? Option.none() : Option.some(decoded[0]);
1655
+ });
1656
+ const requireSubmission = Effect.fn("SqliteSubmissionLedger.requireSubmission")(function* (operation, submissionId) {
1657
+ const submission = yield* readSubmission(operation, submissionId);
1658
+ if (Option.isNone(submission)) return yield* LedgerError.make({
1659
+ operation,
1660
+ message: `Unknown submission ${submissionId}.`
1661
+ });
1662
+ return submission.value;
1663
+ });
1664
+ const readOwnership = Effect.fn("SqliteSubmissionLedger.readOwnership")(function* (operation, submissionId) {
1665
+ const rows = yield* sql`
1666
+ SELECT
1667
+ submission_id,
1668
+ attempt_id,
1669
+ ownership_token,
1670
+ producer_epoch,
1671
+ owner_producer_id,
1672
+ lease_expires_at
1673
+ FROM effect_agent_submission_ownership
1674
+ WHERE submission_id = ${submissionId}
1675
+ `.pipe(Effect.mapError(sqlFailure(operation)));
1676
+ const decoded = yield* decodeRows(Schema.Array(OwnershipRow), "effect_agent_submission_ownership", submissionId, rows).pipe(Effect.mapError(internalFailure(operation)));
1677
+ if (decoded.length > 1) return yield* corruptionFailure(operation, "effect_agent_submission_ownership", submissionId, "An ownership primary key returned more than one row.");
1678
+ return decoded.length === 0 ? Option.none() : Option.some(decoded[0]);
1679
+ });
1680
+ const conversationEpoch = Effect.fn("SqliteSubmissionLedger.conversationEpoch")(function* (operation, conversationId) {
1681
+ const conversations = yield* journal.getConversation(conversationId).pipe(Effect.mapError(internalFailure(operation)));
1682
+ return conversations.length === 0 ? EPOCH_ZERO : conversations[0].producer_epoch;
1683
+ });
1684
+ /**
1685
+ * Verify inside the surrounding write transaction that the presented token still owns the
1686
+ * Submission's lane; a superseded or missing token fails with OwnershipLost carrying the
1687
+ * Conversation's current producer epoch (DUR-006).
1688
+ */
1689
+ const requireOwnership = Effect.fn("SqliteSubmissionLedger.requireOwnership")(function* (operation, submission, ownershipToken) {
1690
+ const ownership = yield* readOwnership(operation, submission.submission_id);
1691
+ if (Option.isNone(ownership) || ownership.value.ownership_token !== ownershipToken) {
1692
+ const actualEpoch = yield* conversationEpoch(operation, submission.conversation_id);
1693
+ const submissionId = yield* Schema.decodeUnknownEffect(SubmissionSnapshot.fields.submissionId)(submission.submission_id).pipe(Effect.mapError(internalFailure(operation)));
1694
+ return yield* OwnershipLost.make({
1695
+ submissionId,
1696
+ actualEpoch
1697
+ });
1698
+ }
1699
+ return ownership.value;
1700
+ });
1701
+ const decodeSubmissionSnapshot = Effect.fn("SqliteSubmissionLedger.decodeSubmissionSnapshot")(function* (operation, row) {
1702
+ const agentDigests = yield* parseStoredJsonText(row.agent_digests_json).pipe(Effect.mapError((error) => corruptionFailure(operation, "effect_agent_submissions", row.submission_id, error.message)));
1703
+ const inputPayload = yield* parseStoredJsonText(row.input_json).pipe(Effect.mapError((error) => corruptionFailure(operation, "effect_agent_submissions", row.submission_id, error.message)));
1704
+ if (row.parent_submission_id === null !== (row.parent_tool_call_id === null)) return yield* corruptionFailure(operation, "effect_agent_submissions", row.submission_id, "A parent linkage must record both the parent Submission and the parent Tool Call.");
1705
+ return yield* decodeSubmissionSnapshotUnknown({
1706
+ submissionId: row.submission_id,
1707
+ conversationId: row.conversation_id,
1708
+ queueSequence: row.queue_sequence,
1709
+ principal: row.principal,
1710
+ idempotencyKey: row.idempotency_key,
1711
+ agentId: row.agent_id,
1712
+ agentDigests,
1713
+ deploymentId: row.deployment_id,
1714
+ inputPayload,
1715
+ inputDigest: row.input_digest,
1716
+ receiptId: row.receipt_id,
1717
+ state: row.state,
1718
+ createdAt: row.created_at,
1719
+ ...row.settled_outcome === null ? {} : { settledOutcome: row.settled_outcome },
1720
+ ...row.ready_at === null ? {} : { readyAt: row.ready_at },
1721
+ ...row.parent_submission_id === null || row.parent_tool_call_id === null ? {} : { parentLinkage: {
1722
+ parentSubmissionId: row.parent_submission_id,
1723
+ parentToolCallId: row.parent_tool_call_id
1724
+ } }
1725
+ }).pipe(Effect.mapError((error) => corruptionFailure(operation, "effect_agent_submissions", row.submission_id, error.message)));
1726
+ });
1727
+ const readReservation = Effect.fn("SqliteSubmissionLedger.readReservation")(function* (operation, submissionId) {
1728
+ const rows = yield* sql`
1729
+ SELECT
1730
+ submission_id,
1731
+ settlement_id,
1732
+ outcome,
1733
+ record_id,
1734
+ record_json,
1735
+ record_digest,
1736
+ reserved_at,
1737
+ finalized_at
1738
+ FROM effect_agent_settlement_reservations
1739
+ WHERE submission_id = ${submissionId}
1740
+ `.pipe(Effect.mapError(sqlFailure(operation)));
1741
+ const decoded = yield* decodeRows(Schema.Array(ReservationRow), "effect_agent_settlement_reservations", submissionId, rows).pipe(Effect.mapError(internalFailure(operation)));
1742
+ if (decoded.length > 1) return yield* corruptionFailure(operation, "effect_agent_settlement_reservations", submissionId, "A settlement reservation primary key returned more than one row.");
1743
+ return decoded.length === 0 ? Option.none() : Option.some(decoded[0]);
1744
+ });
1745
+ const readAbortIntent = Effect.fn("SqliteSubmissionLedger.readAbortIntent")(function* (operation, submissionId) {
1746
+ const rows = yield* sql`
1747
+ SELECT
1748
+ submission_id,
1749
+ author,
1750
+ reason,
1751
+ requested_at,
1752
+ canonical_record_id
1753
+ FROM effect_agent_abort_intents
1754
+ WHERE submission_id = ${submissionId}
1755
+ `.pipe(Effect.mapError(sqlFailure(operation)));
1756
+ const decoded = yield* decodeRows(Schema.Array(AbortIntentRow), "effect_agent_abort_intents", submissionId, rows).pipe(Effect.mapError(internalFailure(operation)));
1757
+ if (decoded.length > 1) return yield* corruptionFailure(operation, "effect_agent_abort_intents", submissionId, "An abort intent primary key returned more than one row.");
1758
+ return decoded.length === 0 ? Option.none() : Option.some(decoded[0]);
1759
+ });
1760
+ const decodeChildReservationRows = (operation, rowKey, rows) => decodeRows(Schema.Array(ChildReservationRow), "effect_agent_child_reservations", rowKey, rows).pipe(Effect.mapError(internalFailure(operation)));
1761
+ const readChildReservation = Effect.fn("SqliteSubmissionLedger.readChildReservation")(function* (operation, reservationId) {
1762
+ const rows = yield* sql`
1763
+ SELECT ${sql.literal(CHILD_RESERVATION_COLUMNS)}
1764
+ FROM effect_agent_child_reservations
1765
+ WHERE reservation_id = ${reservationId}
1766
+ `.pipe(Effect.mapError(sqlFailure(operation)));
1767
+ const decoded = yield* decodeChildReservationRows(operation, reservationId, rows);
1768
+ if (decoded.length > 1) return yield* corruptionFailure(operation, "effect_agent_child_reservations", reservationId, "A child reservation primary key returned more than one row.");
1769
+ return decoded.length === 0 ? Option.none() : Option.some(decoded[0]);
1770
+ });
1771
+ const readChildReservationForCall = Effect.fn("SqliteSubmissionLedger.readChildReservationForCall")(function* (operation, parentSubmissionId, parentToolCallId) {
1772
+ const rows = yield* sql`
1773
+ SELECT ${sql.literal(CHILD_RESERVATION_COLUMNS)}
1774
+ FROM effect_agent_child_reservations
1775
+ WHERE parent_submission_id = ${parentSubmissionId}
1776
+ AND parent_tool_call_id = ${parentToolCallId}
1777
+ `.pipe(Effect.mapError(sqlFailure(operation)));
1778
+ const decoded = yield* decodeChildReservationRows(operation, `${parentSubmissionId}/${parentToolCallId}`, rows);
1779
+ if (decoded.length > 1) return yield* corruptionFailure(operation, "effect_agent_child_reservations", `${parentSubmissionId}/${parentToolCallId}`, "A parent Tool Call returned more than one child reservation.");
1780
+ return decoded.length === 0 ? Option.none() : Option.some(decoded[0]);
1781
+ });
1782
+ const childReservationSnapshotFromRow = Effect.fn("SqliteSubmissionLedger.childReservationSnapshotFromRow")(function* (operation, row) {
1783
+ const rowFailure = (error) => corruptionFailure(operation, "effect_agent_child_reservations", row.reservation_id, error.message);
1784
+ const allocation = yield* parseStoredJsonText(row.allocation_json).pipe(Effect.mapError(rowFailure));
1785
+ const accounting = row.accounting_json === null ? void 0 : yield* parseStoredJsonText(row.accounting_json).pipe(Effect.mapError(rowFailure));
1786
+ return yield* decodeChildReservationSnapshotUnknown({
1787
+ reservationId: row.reservation_id,
1788
+ parentSubmissionId: row.parent_submission_id,
1789
+ parentToolCallId: row.parent_tool_call_id,
1790
+ status: row.status,
1791
+ allocation,
1792
+ allocationDigest: row.allocation_digest,
1793
+ reservedAt: row.reserved_at,
1794
+ ...row.child_submission_id === null ? {} : { childSubmissionId: row.child_submission_id },
1795
+ ...accounting === void 0 ? {} : { accounting },
1796
+ ...row.release_began_at === null ? {} : { releaseBeganAt: row.release_began_at },
1797
+ ...row.released_at === null ? {} : { releasedAt: row.released_at }
1798
+ }).pipe(Effect.mapError(rowFailure));
1799
+ });
1800
+ const readApprovalDecisions = Effect.fn("SqliteSubmissionLedger.readApprovalDecisions")(function* (operation, submissionId) {
1801
+ const rows = yield* sql`
1802
+ SELECT
1803
+ submission_id,
1804
+ tool_call_id,
1805
+ decision,
1806
+ resolver,
1807
+ reason,
1808
+ decided_at
1809
+ FROM effect_agent_approval_decisions
1810
+ WHERE submission_id = ${submissionId}
1811
+ ORDER BY tool_call_id ASC
1812
+ `.pipe(Effect.mapError(sqlFailure(operation)));
1813
+ return yield* decodeRows(Schema.Array(ApprovalDecisionRow), "effect_agent_approval_decisions", submissionId, rows).pipe(Effect.mapError(internalFailure(operation)));
1814
+ });
1815
+ const approvalIntentFromRow = Effect.fn("SqliteSubmissionLedger.approvalIntentFromRow")(function* (operation, row) {
1816
+ return yield* decodeApprovalDecisionIntent({
1817
+ submissionId: row.submission_id,
1818
+ toolCallId: row.tool_call_id,
1819
+ decision: row.decision,
1820
+ resolver: row.resolver,
1821
+ reason: row.reason,
1822
+ decidedAt: row.decided_at
1823
+ }).pipe(Effect.mapError((error) => corruptionFailure(operation, "effect_agent_approval_decisions", `${row.submission_id}/${row.tool_call_id}`, error.message)));
1824
+ });
1825
+ const readUnknownResolutions = Effect.fn("SqliteSubmissionLedger.readUnknownResolutions")(function* (operation, submissionId) {
1826
+ const rows = yield* sql`
1827
+ SELECT
1828
+ submission_id,
1829
+ tool_call_id,
1830
+ author,
1831
+ reason,
1832
+ resolution_json,
1833
+ resolved_at
1834
+ FROM effect_agent_unknown_resolutions
1835
+ WHERE submission_id = ${submissionId}
1836
+ ORDER BY tool_call_id ASC
1837
+ `.pipe(Effect.mapError(sqlFailure(operation)));
1838
+ return yield* decodeRows(Schema.Array(UnknownResolutionRow), "effect_agent_unknown_resolutions", submissionId, rows).pipe(Effect.mapError(internalFailure(operation)));
1839
+ });
1840
+ const unknownResolutionIntentFromRow = Effect.fn("SqliteSubmissionLedger.unknownResolutionIntentFromRow")(function* (operation, row) {
1841
+ const resolution = yield* parseStoredJsonText(row.resolution_json).pipe(Effect.mapError((error) => corruptionFailure(operation, "effect_agent_unknown_resolutions", `${row.submission_id}/${row.tool_call_id}`, error.message)));
1842
+ return yield* decodeUnknownResolutionIntent({
1843
+ submissionId: row.submission_id,
1844
+ toolCallId: row.tool_call_id,
1845
+ author: row.author,
1846
+ reason: row.reason,
1847
+ resolution,
1848
+ resolvedAt: row.resolved_at
1849
+ }).pipe(Effect.mapError((error) => corruptionFailure(operation, "effect_agent_unknown_resolutions", `${row.submission_id}/${row.tool_call_id}`, error.message)));
1850
+ });
1851
+ /** The Submission's marked-unknown open Tool Call identities, empty when never marked. */
1852
+ const storedUnknownToolCallIds = Effect.fn("SqliteSubmissionLedger.storedUnknownToolCallIds")(function* (operation, submission) {
1853
+ if (submission.unknown_tool_call_ids_json === null) return [];
1854
+ return yield* decodeToolCallIdsText(submission.unknown_tool_call_ids_json).pipe(Effect.mapError((error) => corruptionFailure(operation, "effect_agent_submissions", submission.submission_id, error.message)));
1855
+ });
1856
+ /**
1857
+ * Canonical history is the abort authority (DUR-015): the intent's canonicalRecordId is
1858
+ * derived from the shared canonical-records table using the deterministic abort record
1859
+ * identity, never from a cached ledger marker.
1860
+ */
1861
+ const canonicalAbortRecordId = Effect.fn("SqliteSubmissionLedger.canonicalAbortRecordId")(function* (operation, conversationId, submissionId) {
1862
+ const recordId = submissionAbortRecordId(submissionId);
1863
+ const rows = yield* sql`
1864
+ SELECT record_id
1865
+ FROM effect_agent_canonical_records
1866
+ WHERE conversation_id = ${conversationId}
1867
+ AND record_id = ${recordId}
1868
+ `.pipe(Effect.mapError(sqlFailure(operation)));
1869
+ return (yield* decodeRows(Schema.Array(CanonicalRecordIdRow), "effect_agent_canonical_records", `${conversationId}/${recordId}`, rows).pipe(Effect.mapError(internalFailure(operation)))).length === 0 ? void 0 : recordId;
1870
+ });
1871
+ const abortIntentFromRow = Effect.fn("SqliteSubmissionLedger.abortIntentFromRow")(function* (operation, submission, submissionId, row) {
1872
+ const canonicalRecordId = yield* canonicalAbortRecordId(operation, submission.conversation_id, submissionId);
1873
+ return yield* decodeAbortIntent({
1874
+ submissionId: row.submission_id,
1875
+ author: row.author,
1876
+ reason: row.reason,
1877
+ requestedAt: row.requested_at,
1878
+ ...canonicalRecordId === void 0 ? {} : { canonicalRecordId }
1879
+ }).pipe(Effect.mapError((error) => corruptionFailure(operation, "effect_agent_abort_intents", row.submission_id, error.message)));
1880
+ });
1881
+ const capabilities = Effect.succeed(LedgerCapabilities.make({ durability: "durable-node" }));
1882
+ const admit = Effect.fn("SqliteSubmissionLedger.admit")(function* (request) {
1883
+ const operation = "ledger admit";
1884
+ const validated = yield* Schema.decodeUnknownEffect(Schema.toType(AdmissionRequest))(request).pipe(Effect.mapError(internalFailure(operation)));
1885
+ const inputJson = yield* encodePersistedJsonText(validated.inputPayload).pipe(Effect.mapError(internalFailure(operation)));
1886
+ const agentDigestsJson = yield* encodeDefinitionDigestsText(validated.agentDigests).pipe(Effect.mapError(internalFailure(operation)));
1887
+ const mintedSubmissionId = yield* mintIdentifier("submission", operation);
1888
+ const mintedReceiptId = yield* mintIdentifier("receipt", operation);
1889
+ yield* hitFailpoint("ledger:admit:before", operation);
1890
+ const result = yield* inWriteTransaction(operation, Effect.gen(function* () {
1891
+ const keyRowKey = `${validated.conversationId}/${validated.principal}/${validated.idempotencyKey}`;
1892
+ const existingRows = yield* sql`
1893
+ SELECT ${sql.literal(SUBMISSION_COLUMNS)}
1894
+ FROM effect_agent_submissions
1895
+ WHERE conversation_id = ${validated.conversationId}
1896
+ AND principal = ${validated.principal}
1897
+ AND idempotency_key = ${validated.idempotencyKey}
1898
+ `.pipe(Effect.mapError(sqlFailure(operation)));
1899
+ const existing = yield* decodeSubmissionRows(operation, keyRowKey, existingRows);
1900
+ if (existing.length > 1) return yield* corruptionFailure(operation, "effect_agent_submissions", keyRowKey, "An admission idempotency key returned more than one row.");
1901
+ if (existing.length === 1) {
1902
+ const sameLinkage = validated.parentLinkage === void 0 ? existing[0].parent_submission_id === null && existing[0].parent_tool_call_id === null : existing[0].parent_submission_id === validated.parentLinkage.parentSubmissionId && existing[0].parent_tool_call_id === validated.parentLinkage.parentToolCallId;
1903
+ if (existing[0].input_digest !== validated.inputDigest || !sameLinkage) return yield* AdmissionConflict.make({
1904
+ conversationId: validated.conversationId,
1905
+ principal: validated.principal,
1906
+ idempotencyKey: validated.idempotencyKey,
1907
+ existingInputDigest: existing[0].input_digest,
1908
+ attemptedInputDigest: validated.inputDigest
1909
+ });
1910
+ return yield* decodeAdmissionResult({
1911
+ submissionId: existing[0].submission_id,
1912
+ receiptId: existing[0].receipt_id,
1913
+ queueSequence: existing[0].queue_sequence,
1914
+ state: existing[0].state,
1915
+ replayed: true
1916
+ }).pipe(Effect.mapError(internalFailure(operation)));
1917
+ }
1918
+ const maxRows = yield* sql`
1919
+ SELECT COALESCE(MAX(queue_sequence), 0) AS max_queue_sequence
1920
+ FROM effect_agent_submissions
1921
+ WHERE conversation_id = ${validated.conversationId}
1922
+ `.pipe(Effect.mapError(sqlFailure(operation)));
1923
+ const decodedMax = yield* decodeRows(Schema.Array(MaxQueueSequenceRow), "effect_agent_submissions", validated.conversationId, maxRows).pipe(Effect.mapError(internalFailure(operation)));
1924
+ const queueSequence = yield* decodeQueueSequence((decodedMax[0]?.max_queue_sequence ?? 0) + 1).pipe(Effect.mapError(internalFailure(operation)));
1925
+ const now = yield* currentInstant;
1926
+ yield* sql`
1927
+ INSERT INTO effect_agent_submissions (
1928
+ submission_id,
1929
+ conversation_id,
1930
+ queue_sequence,
1931
+ principal,
1932
+ idempotency_key,
1933
+ agent_id,
1934
+ agent_digests_json,
1935
+ deployment_id,
1936
+ input_json,
1937
+ input_digest,
1938
+ receipt_id,
1939
+ state,
1940
+ created_at,
1941
+ parent_submission_id,
1942
+ parent_tool_call_id
1943
+ ) VALUES (
1944
+ ${mintedSubmissionId},
1945
+ ${validated.conversationId},
1946
+ ${queueSequence},
1947
+ ${validated.principal},
1948
+ ${validated.idempotencyKey},
1949
+ ${validated.agentId},
1950
+ ${agentDigestsJson},
1951
+ ${validated.deploymentId},
1952
+ ${inputJson},
1953
+ ${validated.inputDigest},
1954
+ ${mintedReceiptId},
1955
+ 'admitted',
1956
+ ${now.iso},
1957
+ ${validated.parentLinkage?.parentSubmissionId ?? null},
1958
+ ${validated.parentLinkage?.parentToolCallId ?? null}
1959
+ )
1960
+ `.pipe(Effect.mapError(sqlFailure(operation)));
1961
+ return yield* decodeAdmissionResult({
1962
+ submissionId: mintedSubmissionId,
1963
+ receiptId: mintedReceiptId,
1964
+ queueSequence,
1965
+ state: "admitted",
1966
+ replayed: false
1967
+ }).pipe(Effect.mapError(internalFailure(operation)));
1968
+ }));
1969
+ yield* hitFailpoint("ledger:admit:after", operation);
1970
+ return result;
1971
+ });
1972
+ const markReady = Effect.fn("SqliteSubmissionLedger.markReady")(function* (request) {
1973
+ const operation = "ledger mark ready";
1974
+ const validated = yield* Schema.decodeUnknownEffect(Schema.toType(MarkReadyRequest))(request).pipe(Effect.mapError(internalFailure(operation)));
1975
+ yield* hitFailpoint("ledger:mark-ready:before", operation);
1976
+ yield* inWriteTransaction(operation, Effect.gen(function* () {
1977
+ if ((yield* requireSubmission(operation, validated.submissionId)).state !== "admitted") return;
1978
+ const now = yield* currentInstant;
1979
+ yield* sql`
1980
+ UPDATE effect_agent_submissions
1981
+ SET state = 'ready', ready_at = ${now.iso}
1982
+ WHERE submission_id = ${validated.submissionId}
1983
+ `.pipe(Effect.mapError(sqlFailure(operation)));
1984
+ }));
1985
+ yield* hitFailpoint("ledger:mark-ready:after", operation);
1986
+ });
1987
+ const lookup = Effect.fn("SqliteSubmissionLedger.lookup")(function* (request) {
1988
+ const operation = "ledger lookup";
1989
+ const validated = yield* Schema.decodeUnknownEffect(Schema.toType(SubmissionLookup))(request).pipe(Effect.mapError(internalFailure(operation)));
1990
+ if (validated._tag === "SubmissionLookupById") {
1991
+ const row = yield* readSubmission(operation, validated.submissionId);
1992
+ if (Option.isNone(row)) return Option.none();
1993
+ return Option.some(yield* decodeSubmissionSnapshot(operation, row.value));
1994
+ }
1995
+ const rows = yield* sql`
1996
+ SELECT ${sql.literal(SUBMISSION_COLUMNS)}
1997
+ FROM effect_agent_submissions
1998
+ WHERE conversation_id = ${validated.conversationId}
1999
+ AND principal = ${validated.principal}
2000
+ AND idempotency_key = ${validated.idempotencyKey}
2001
+ `.pipe(Effect.mapError(sqlFailure(operation)));
2002
+ const decoded = yield* decodeSubmissionRows(operation, `${validated.conversationId}/${validated.principal}/${validated.idempotencyKey}`, rows);
2003
+ if (decoded.length > 1) return yield* corruptionFailure(operation, "effect_agent_submissions", `${validated.conversationId}/${validated.principal}/${validated.idempotencyKey}`, "An admission idempotency key returned more than one row.");
2004
+ if (decoded.length === 0) return Option.none();
2005
+ return Option.some(yield* decodeSubmissionSnapshot(operation, decoded[0]));
2006
+ });
2007
+ const resolveAdmission = Effect.fn("SqliteSubmissionLedger.resolveAdmission")(function* (request) {
2008
+ const operation = "ledger resolve admission";
2009
+ const validated = yield* Schema.decodeUnknownEffect(Schema.toType(SubmissionLookupByKey))(request).pipe(Effect.mapError(internalFailure(operation)));
2010
+ const rows = yield* sql`
2011
+ SELECT ${sql.literal(SUBMISSION_COLUMNS)}
2012
+ FROM effect_agent_submissions
2013
+ WHERE conversation_id = ${validated.conversationId}
2014
+ AND principal = ${validated.principal}
2015
+ AND idempotency_key = ${validated.idempotencyKey}
2016
+ `.pipe(Effect.mapError(sqlFailure(operation)));
2017
+ const decoded = yield* decodeSubmissionRows(operation, `${validated.conversationId}/${validated.principal}/${validated.idempotencyKey}`, rows);
2018
+ if (decoded.length > 1) return yield* corruptionFailure(operation, "effect_agent_submissions", `${validated.conversationId}/${validated.principal}/${validated.idempotencyKey}`, "An admission idempotency key returned more than one row.");
2019
+ if (decoded.length === 0) return AdmissionNotAdmitted.make();
2020
+ return AdmissionAdmitted.make({ submission: yield* decodeSubmissionSnapshot(operation, decoded[0]) });
2021
+ });
2022
+ const claim = Effect.fn("SqliteSubmissionLedger.claim")(function* (request) {
2023
+ const operation = "ledger claim";
2024
+ const validated = yield* Schema.decodeUnknownEffect(Schema.toType(ClaimRequest))(request).pipe(Effect.mapError(internalFailure(operation)));
2025
+ const attemptId = yield* mintIdentifier("attempt", operation);
2026
+ const ownershipToken = yield* mintIdentifier("owner", operation);
2027
+ yield* hitFailpoint("ledger:claim:before", operation);
2028
+ const claimed = yield* inWriteTransaction(operation, Effect.gen(function* () {
2029
+ const headRows = yield* sql`
2030
+ SELECT ${sql.literal(SUBMISSION_COLUMNS)}
2031
+ FROM effect_agent_submissions
2032
+ WHERE conversation_id = ${validated.conversationId}
2033
+ AND state <> 'settled'
2034
+ ORDER BY queue_sequence ASC
2035
+ LIMIT 1
2036
+ `.pipe(Effect.mapError(sqlFailure(operation)));
2037
+ const heads = yield* decodeSubmissionRows(operation, validated.conversationId, headRows);
2038
+ if (heads.length === 0) return Option.none();
2039
+ const head = heads[0];
2040
+ if (head.state === "joining" || head.state === "joined" || head.state === "suspended" || head.state === "unknown") return Option.none();
2041
+ const now = yield* currentInstant;
2042
+ const ownership = yield* readOwnership(operation, head.submission_id);
2043
+ if (Option.isSome(ownership)) {
2044
+ if ((yield* timestampMillis(operation, head.submission_id)(ownership.value.lease_expires_at)) > now.millis) return Option.none();
2045
+ }
2046
+ const conversations = yield* journal.getConversation(head.conversation_id).pipe(Effect.mapError(internalFailure(operation)));
2047
+ let producerEpoch;
2048
+ if (conversations.length === 0) {
2049
+ producerEpoch = 1;
2050
+ yield* sql`
2051
+ INSERT INTO effect_agent_conversations (
2052
+ conversation_id,
2053
+ created_at,
2054
+ tail_sequence,
2055
+ tail_digest,
2056
+ producer_epoch
2057
+ ) VALUES (
2058
+ ${head.conversation_id},
2059
+ ${now.iso},
2060
+ 0,
2061
+ ${EMPTY_TAIL_DIGEST},
2062
+ ${producerEpoch}
2063
+ )
2064
+ `.pipe(Effect.mapError(sqlFailure(operation)));
2065
+ } else {
2066
+ producerEpoch = conversations[0].producer_epoch + 1;
2067
+ yield* sql`
2068
+ UPDATE effect_agent_conversations
2069
+ SET producer_epoch = ${producerEpoch}
2070
+ WHERE conversation_id = ${head.conversation_id}
2071
+ `.pipe(Effect.mapError(sqlFailure(operation)));
2072
+ }
2073
+ const leaseExpiresAt = new Date(now.millis + config.ownershipLeaseDuration).toISOString();
2074
+ yield* sql`
2075
+ INSERT INTO effect_agent_submission_ownership (
2076
+ submission_id,
2077
+ attempt_id,
2078
+ ownership_token,
2079
+ producer_epoch,
2080
+ owner_producer_id,
2081
+ lease_expires_at
2082
+ ) VALUES (
2083
+ ${head.submission_id},
2084
+ ${attemptId},
2085
+ ${ownershipToken},
2086
+ ${producerEpoch},
2087
+ ${validated.producerId},
2088
+ ${leaseExpiresAt}
2089
+ )
2090
+ ON CONFLICT (submission_id) DO UPDATE SET
2091
+ attempt_id = excluded.attempt_id,
2092
+ ownership_token = excluded.ownership_token,
2093
+ producer_epoch = excluded.producer_epoch,
2094
+ owner_producer_id = excluded.owner_producer_id,
2095
+ lease_expires_at = excluded.lease_expires_at
2096
+ `.pipe(Effect.mapError(sqlFailure(operation)));
2097
+ yield* sql`
2098
+ INSERT INTO effect_agent_attempts (
2099
+ attempt_id,
2100
+ submission_id,
2101
+ conversation_id,
2102
+ owner_producer_id,
2103
+ producer_epoch,
2104
+ claimed_at
2105
+ ) VALUES (
2106
+ ${attemptId},
2107
+ ${head.submission_id},
2108
+ ${head.conversation_id},
2109
+ ${validated.producerId},
2110
+ ${producerEpoch},
2111
+ ${now.iso}
2112
+ )
2113
+ `.pipe(Effect.mapError(sqlFailure(operation)));
2114
+ if (head.state === "ready") yield* sql`
2115
+ UPDATE effect_agent_submissions
2116
+ SET state = 'running'
2117
+ WHERE submission_id = ${head.submission_id}
2118
+ `.pipe(Effect.mapError(sqlFailure(operation)));
2119
+ const inputPayload = yield* parseStoredJsonText(head.input_json).pipe(Effect.mapError((error) => corruptionFailure(operation, "effect_agent_submissions", head.submission_id, error.message)));
2120
+ return Option.some(yield* decodeClaim({
2121
+ submissionId: head.submission_id,
2122
+ attemptId,
2123
+ ownershipToken,
2124
+ producerEpoch,
2125
+ leaseExpiresAt,
2126
+ inputPayload
2127
+ }).pipe(Effect.mapError(internalFailure(operation))));
2128
+ }));
2129
+ yield* hitFailpoint("ledger:claim:after", operation);
2130
+ return claimed;
2131
+ });
2132
+ const renewOwnership = Effect.fn("SqliteSubmissionLedger.renewOwnership")(function* (request) {
2133
+ const operation = "ledger renew ownership";
2134
+ const validated = yield* Schema.decodeUnknownEffect(Schema.toType(RenewOwnershipRequest))(request).pipe(Effect.mapError(internalFailure(operation)));
2135
+ yield* hitFailpoint("ledger:renew:before", operation);
2136
+ const renewal = yield* inWriteTransaction(operation, Effect.gen(function* () {
2137
+ const submission = yield* requireSubmission(operation, validated.submissionId);
2138
+ yield* requireOwnership(operation, submission, validated.ownershipToken);
2139
+ const now = yield* currentInstant;
2140
+ const leaseExpiresAt = new Date(now.millis + config.ownershipLeaseDuration).toISOString();
2141
+ yield* sql`
2142
+ UPDATE effect_agent_submission_ownership
2143
+ SET lease_expires_at = ${leaseExpiresAt}
2144
+ WHERE submission_id = ${validated.submissionId}
2145
+ `.pipe(Effect.mapError(sqlFailure(operation)));
2146
+ return yield* decodeOwnershipRenewal({
2147
+ ownershipToken: validated.ownershipToken,
2148
+ leaseExpiresAt
2149
+ }).pipe(Effect.mapError(internalFailure(operation)));
2150
+ }));
2151
+ yield* hitFailpoint("ledger:renew:after", operation);
2152
+ return renewal;
2153
+ });
2154
+ const releaseOwnership = Effect.fn("SqliteSubmissionLedger.releaseOwnership")(function* (request) {
2155
+ const operation = "ledger release ownership";
2156
+ const validated = yield* Schema.decodeUnknownEffect(Schema.toType(ReleaseOwnershipRequest))(request).pipe(Effect.mapError(internalFailure(operation)));
2157
+ yield* hitFailpoint("ledger:release:before", operation);
2158
+ yield* inWriteTransaction(operation, Effect.gen(function* () {
2159
+ const submission = yield* requireSubmission(operation, validated.submissionId);
2160
+ yield* requireOwnership(operation, submission, validated.ownershipToken);
2161
+ yield* sql`
2162
+ DELETE FROM effect_agent_submission_ownership
2163
+ WHERE submission_id = ${validated.submissionId}
2164
+ `.pipe(Effect.mapError(sqlFailure(operation)));
2165
+ if (submission.state === "running") yield* sql`
2166
+ UPDATE effect_agent_submissions
2167
+ SET state = 'ready'
2168
+ WHERE submission_id = ${validated.submissionId}
2169
+ `.pipe(Effect.mapError(sqlFailure(operation)));
2170
+ }));
2171
+ yield* hitFailpoint("ledger:release:after", operation);
2172
+ });
2173
+ const markInputApplied = Effect.fn("SqliteSubmissionLedger.markInputApplied")(function* (request) {
2174
+ const operation = "ledger mark input applied";
2175
+ const validated = yield* Schema.decodeUnknownEffect(Schema.toType(MarkInputAppliedRequest))(request).pipe(Effect.mapError(internalFailure(operation)));
2176
+ yield* hitFailpoint("ledger:mark-input-applied:before", operation);
2177
+ yield* inWriteTransaction(operation, Effect.gen(function* () {
2178
+ const submission = yield* requireSubmission(operation, validated.submissionId);
2179
+ yield* requireOwnership(operation, submission, validated.ownershipToken);
2180
+ if (submission.input_applied_record_id !== null) {
2181
+ if (submission.input_applied_record_id === validated.recordId && submission.input_applied_sequence === validated.sequence) return;
2182
+ return yield* corruptionFailure(operation, "effect_agent_submissions", validated.submissionId, "A different canonical input marker is already recorded for this Submission.");
2183
+ }
2184
+ yield* sql`
2185
+ UPDATE effect_agent_submissions
2186
+ SET
2187
+ input_applied_record_id = ${validated.recordId},
2188
+ input_applied_sequence = ${validated.sequence},
2189
+ state = CASE
2190
+ WHEN state IN ('admitted', 'ready', 'running') THEN 'input-applied'
2191
+ ELSE state
2192
+ END
2193
+ WHERE submission_id = ${validated.submissionId}
2194
+ `.pipe(Effect.mapError(sqlFailure(operation)));
2195
+ }));
2196
+ yield* hitFailpoint("ledger:mark-input-applied:after", operation);
2197
+ });
2198
+ const reserveSettlement = Effect.fn("SqliteSubmissionLedger.reserveSettlement")(function* (request) {
2199
+ const operation = "ledger reserve settlement";
2200
+ const validated = yield* Schema.decodeUnknownEffect(Schema.toType(SettlementReservation))(request).pipe(Effect.mapError(internalFailure(operation)));
2201
+ const recordJson = yield* encodeRecordEnvelopeText(validated.record).pipe(Effect.mapError(internalFailure(operation)));
2202
+ yield* hitFailpoint("ledger:reserve-settlement:before", operation);
2203
+ const reserved = yield* inWriteTransaction(operation, Effect.gen(function* () {
2204
+ const existing = yield* readReservation(operation, validated.submissionId);
2205
+ if (Option.isSome(existing)) {
2206
+ if (!(existing.value.settlement_id === validated.settlementId && existing.value.outcome === validated.outcome && existing.value.record_digest === validated.recordDigest && existing.value.record_json === recordJson)) return yield* SettlementConflict.make({
2207
+ submissionId: validated.submissionId,
2208
+ existingOutcome: existing.value.outcome
2209
+ });
2210
+ const record = yield* decodeRecordEnvelopeText(existing.value.record_json).pipe(Effect.mapError((error) => corruptionFailure(operation, "effect_agent_settlement_reservations", validated.submissionId, error.message)));
2211
+ return ReservedSettlement.make({
2212
+ submissionId: validated.submissionId,
2213
+ settlementId: validated.settlementId,
2214
+ outcome: validated.outcome,
2215
+ record,
2216
+ recordDigest: validated.recordDigest,
2217
+ replayed: true
2218
+ });
2219
+ }
2220
+ const submission = yield* requireSubmission(operation, validated.submissionId);
2221
+ if (submission.state === "settled") {
2222
+ if (submission.settled_outcome === null) return yield* corruptionFailure(operation, "effect_agent_submissions", validated.submissionId, "A settled Submission carries no terminal outcome.");
2223
+ return yield* SettlementConflict.make({
2224
+ submissionId: validated.submissionId,
2225
+ existingOutcome: submission.settled_outcome
2226
+ });
2227
+ }
2228
+ if (!(submission.state === "joined" && submission.joined_host_submission_id !== null)) {
2229
+ let queuedAbortSettlement = false;
2230
+ if (validated.outcome === "aborted" && (submission.state === "ready" || submission.state === "terminalizing")) {
2231
+ const abortIntent = yield* readAbortIntent(operation, validated.submissionId);
2232
+ if (Option.isSome(abortIntent)) {
2233
+ const ownership = yield* readOwnership(operation, validated.submissionId);
2234
+ queuedAbortSettlement = Option.isNone(ownership);
2235
+ }
2236
+ }
2237
+ if (!queuedAbortSettlement) yield* requireOwnership(operation, submission, validated.ownershipToken);
2238
+ }
2239
+ const now = yield* currentInstant;
2240
+ yield* sql`
2241
+ INSERT INTO effect_agent_settlement_reservations (
2242
+ submission_id,
2243
+ settlement_id,
2244
+ outcome,
2245
+ record_id,
2246
+ record_json,
2247
+ record_digest,
2248
+ reserved_at
2249
+ ) VALUES (
2250
+ ${validated.submissionId},
2251
+ ${validated.settlementId},
2252
+ ${validated.outcome},
2253
+ ${validated.record.recordId},
2254
+ ${recordJson},
2255
+ ${validated.recordDigest},
2256
+ ${now.iso}
2257
+ )
2258
+ `.pipe(Effect.mapError(sqlFailure(operation)));
2259
+ yield* sql`
2260
+ UPDATE effect_agent_submissions
2261
+ SET state = 'terminalizing'
2262
+ WHERE submission_id = ${validated.submissionId}
2263
+ `.pipe(Effect.mapError(sqlFailure(operation)));
2264
+ return ReservedSettlement.make({
2265
+ submissionId: validated.submissionId,
2266
+ settlementId: validated.settlementId,
2267
+ outcome: validated.outcome,
2268
+ record: validated.record,
2269
+ recordDigest: validated.recordDigest,
2270
+ replayed: false
2271
+ });
2272
+ }));
2273
+ yield* hitFailpoint("ledger:reserve-settlement:after", operation);
2274
+ return reserved;
2275
+ });
2276
+ const finalizeSettlement = Effect.fn("SqliteSubmissionLedger.finalizeSettlement")(function* (request) {
2277
+ const operation = "ledger finalize settlement";
2278
+ const validated = yield* Schema.decodeUnknownEffect(Schema.toType(SettlementFinalization))(request).pipe(Effect.mapError(internalFailure(operation)));
2279
+ yield* hitFailpoint("ledger:finalize-settlement:before", operation);
2280
+ const settlement = yield* inWriteTransaction(operation, Effect.gen(function* () {
2281
+ const reservation = yield* readReservation(operation, validated.submissionId);
2282
+ if (Option.isNone(reservation)) return yield* LedgerError.make({
2283
+ operation,
2284
+ message: `No settlement reservation exists for submission ${validated.submissionId}.`
2285
+ });
2286
+ if (reservation.value.settlement_id !== validated.settlementId) return yield* SettlementConflict.make({
2287
+ submissionId: validated.submissionId,
2288
+ existingOutcome: reservation.value.outcome
2289
+ });
2290
+ const submission = yield* requireSubmission(operation, validated.submissionId);
2291
+ if (submission.state === "settled") {
2292
+ if (reservation.value.finalized_at === null) return yield* corruptionFailure(operation, "effect_agent_settlement_reservations", validated.submissionId, "A settled Submission's reservation carries no finalization timestamp.");
2293
+ return yield* decodeSettlement({
2294
+ submissionId: validated.submissionId,
2295
+ settlementId: validated.settlementId,
2296
+ receiptId: submission.receipt_id,
2297
+ outcome: reservation.value.outcome,
2298
+ settledAt: reservation.value.finalized_at
2299
+ }).pipe(Effect.mapError(internalFailure(operation)));
2300
+ }
2301
+ const now = yield* currentInstant;
2302
+ yield* sql`
2303
+ UPDATE effect_agent_submissions
2304
+ SET state = 'settled', settled_outcome = ${reservation.value.outcome}
2305
+ WHERE submission_id = ${validated.submissionId}
2306
+ `.pipe(Effect.mapError(sqlFailure(operation)));
2307
+ yield* sql`
2308
+ UPDATE effect_agent_settlement_reservations
2309
+ SET finalized_at = ${now.iso}
2310
+ WHERE submission_id = ${validated.submissionId}
2311
+ `.pipe(Effect.mapError(sqlFailure(operation)));
2312
+ yield* sql`
2313
+ DELETE FROM effect_agent_submission_ownership
2314
+ WHERE submission_id = ${validated.submissionId}
2315
+ `.pipe(Effect.mapError(sqlFailure(operation)));
2316
+ return yield* decodeSettlement({
2317
+ submissionId: validated.submissionId,
2318
+ settlementId: validated.settlementId,
2319
+ receiptId: submission.receipt_id,
2320
+ outcome: reservation.value.outcome,
2321
+ settledAt: now.iso
2322
+ }).pipe(Effect.mapError(internalFailure(operation)));
2323
+ }));
2324
+ yield* hitFailpoint("ledger:finalize-settlement:after", operation);
2325
+ return settlement;
2326
+ });
2327
+ const requestAbort = Effect.fn("SqliteSubmissionLedger.requestAbort")(function* (request) {
2328
+ const operation = "ledger request abort";
2329
+ const validated = yield* Schema.decodeUnknownEffect(Schema.toType(AbortCommand))(request).pipe(Effect.mapError(internalFailure(operation)));
2330
+ yield* hitFailpoint("ledger:request-abort:before", operation);
2331
+ const intent = yield* inWriteTransaction(operation, Effect.gen(function* () {
2332
+ const submission = yield* requireSubmission(operation, validated.submissionId);
2333
+ if (submission.state === "settled") {
2334
+ if (submission.settled_outcome === null) return yield* corruptionFailure(operation, "effect_agent_submissions", validated.submissionId, "A settled Submission carries no terminal outcome.");
2335
+ return yield* SettlementConflict.make({
2336
+ submissionId: validated.submissionId,
2337
+ existingOutcome: submission.settled_outcome
2338
+ });
2339
+ }
2340
+ if (submission.state === "joined") {
2341
+ if (submission.joined_host_submission_id === null) return yield* corruptionFailure(operation, "effect_agent_submissions", validated.submissionId, "A joined Submission carries no host linkage.");
2342
+ const hostSubmissionId = yield* decodeSubmissionId(submission.joined_host_submission_id).pipe(Effect.mapError(internalFailure(operation)));
2343
+ return yield* JoinedToHost.make({
2344
+ submissionId: validated.submissionId,
2345
+ hostSubmissionId
2346
+ });
2347
+ }
2348
+ const existing = yield* readAbortIntent(operation, validated.submissionId);
2349
+ if (Option.isSome(existing)) return yield* abortIntentFromRow(operation, submission, validated.submissionId, existing.value);
2350
+ const now = yield* currentInstant;
2351
+ yield* sql`
2352
+ INSERT INTO effect_agent_abort_intents (
2353
+ submission_id,
2354
+ author,
2355
+ reason,
2356
+ requested_at
2357
+ ) VALUES (
2358
+ ${validated.submissionId},
2359
+ ${validated.author},
2360
+ ${validated.reason},
2361
+ ${now.iso}
2362
+ )
2363
+ `.pipe(Effect.mapError(sqlFailure(operation)));
2364
+ const canonicalRecordId = yield* canonicalAbortRecordId(operation, submission.conversation_id, validated.submissionId);
2365
+ return yield* decodeAbortIntent({
2366
+ submissionId: validated.submissionId,
2367
+ author: validated.author,
2368
+ reason: validated.reason,
2369
+ requestedAt: now.iso,
2370
+ ...canonicalRecordId === void 0 ? {} : { canonicalRecordId }
2371
+ }).pipe(Effect.mapError(internalFailure(operation)));
2372
+ }));
2373
+ yield* hitFailpoint("ledger:request-abort:after", operation);
2374
+ return intent;
2375
+ });
2376
+ const claimJoining = Effect.fn("SqliteSubmissionLedger.claimJoining")(function* (request) {
2377
+ const operation = "ledger claim joining";
2378
+ const validated = yield* Schema.decodeUnknownEffect(Schema.toType(ClaimJoiningRequest))(request).pipe(Effect.mapError(internalFailure(operation)));
2379
+ yield* hitFailpoint("ledger:claim-joining:before", operation);
2380
+ const claims = yield* inWriteTransaction(operation, Effect.gen(function* () {
2381
+ const host = yield* requireSubmission(operation, validated.hostSubmissionId);
2382
+ if (host.conversation_id !== validated.conversationId) return yield* LedgerError.make({
2383
+ operation,
2384
+ message: `Host submission ${validated.hostSubmissionId} does not belong to conversation ${validated.conversationId}.`
2385
+ });
2386
+ yield* requireOwnership(operation, host, validated.ownershipToken);
2387
+ const laterRows = yield* sql`
2388
+ SELECT ${sql.literal(SUBMISSION_COLUMNS)}
2389
+ FROM effect_agent_submissions
2390
+ WHERE conversation_id = ${validated.conversationId}
2391
+ AND queue_sequence > ${host.queue_sequence}
2392
+ ORDER BY queue_sequence ASC
2393
+ `.pipe(Effect.mapError(sqlFailure(operation)));
2394
+ const later = yield* decodeSubmissionRows(operation, validated.conversationId, laterRows);
2395
+ const claimed = [];
2396
+ for (const row of later) {
2397
+ if (claimed.length >= validated.maxCount) break;
2398
+ if ((row.state === "joining" || row.state === "joined") && row.joined_host_submission_id === validated.hostSubmissionId) continue;
2399
+ if (row.state === "settled" && row.settled_outcome === "aborted") continue;
2400
+ if (row.state !== "ready") break;
2401
+ yield* sql`
2402
+ UPDATE effect_agent_submissions
2403
+ SET state = 'joining', joined_host_submission_id = ${validated.hostSubmissionId}
2404
+ WHERE submission_id = ${row.submission_id}
2405
+ `.pipe(Effect.mapError(sqlFailure(operation)));
2406
+ const inputPayload = yield* parseStoredJsonText(row.input_json).pipe(Effect.mapError((error) => corruptionFailure(operation, "effect_agent_submissions", row.submission_id, error.message)));
2407
+ claimed.push(yield* decodeJoiningClaim({
2408
+ submissionId: row.submission_id,
2409
+ queueSequence: row.queue_sequence,
2410
+ inputPayload
2411
+ }).pipe(Effect.mapError(internalFailure(operation))));
2412
+ }
2413
+ return claimed;
2414
+ }));
2415
+ yield* hitFailpoint("ledger:claim-joining:after", operation);
2416
+ return claims;
2417
+ });
2418
+ const markJoined = Effect.fn("SqliteSubmissionLedger.markJoined")(function* (request) {
2419
+ const operation = "ledger mark joined";
2420
+ const validated = yield* Schema.decodeUnknownEffect(Schema.toType(MarkJoinedRequest))(request).pipe(Effect.mapError(internalFailure(operation)));
2421
+ yield* hitFailpoint("ledger:mark-joined:before", operation);
2422
+ yield* inWriteTransaction(operation, Effect.gen(function* () {
2423
+ const submission = yield* requireSubmission(operation, validated.submissionId);
2424
+ if (submission.joined_host_submission_id === null) return yield* LedgerError.make({
2425
+ operation,
2426
+ message: `Submission ${validated.submissionId} was never claimed for joining.`
2427
+ });
2428
+ const host = yield* requireSubmission(operation, submission.joined_host_submission_id);
2429
+ yield* requireOwnership(operation, host, validated.ownershipToken);
2430
+ if (submission.input_applied_record_id !== null) {
2431
+ if (submission.input_applied_record_id === validated.recordId && submission.input_applied_sequence === validated.sequence) return;
2432
+ return yield* corruptionFailure(operation, "effect_agent_submissions", validated.submissionId, "A different join marker is already recorded for this Submission.");
2433
+ }
2434
+ if (submission.state !== "joining" && submission.state !== "joined") return yield* LedgerError.make({
2435
+ operation,
2436
+ message: `Cannot mark submission ${validated.submissionId} joined from state ${submission.state}.`
2437
+ });
2438
+ yield* sql`
2439
+ UPDATE effect_agent_submissions
2440
+ SET
2441
+ input_applied_record_id = ${validated.recordId},
2442
+ input_applied_sequence = ${validated.sequence},
2443
+ state = 'joined'
2444
+ WHERE submission_id = ${validated.submissionId}
2445
+ `.pipe(Effect.mapError(sqlFailure(operation)));
2446
+ }));
2447
+ yield* hitFailpoint("ledger:mark-joined:after", operation);
2448
+ });
2449
+ const revertJoining = Effect.fn("SqliteSubmissionLedger.revertJoining")(function* (request) {
2450
+ const operation = "ledger revert joining";
2451
+ const validated = yield* Schema.decodeUnknownEffect(Schema.toType(RevertJoiningRequest))(request).pipe(Effect.mapError(internalFailure(operation)));
2452
+ yield* hitFailpoint("ledger:revert-joining:before", operation);
2453
+ yield* inWriteTransaction(operation, Effect.gen(function* () {
2454
+ if ((yield* requireSubmission(operation, validated.submissionId)).state !== "joining") return;
2455
+ yield* sql`
2456
+ UPDATE effect_agent_submissions
2457
+ SET state = 'ready', joined_host_submission_id = NULL
2458
+ WHERE submission_id = ${validated.submissionId}
2459
+ `.pipe(Effect.mapError(sqlFailure(operation)));
2460
+ }));
2461
+ yield* hitFailpoint("ledger:revert-joining:after", operation);
2462
+ });
2463
+ const suspend = Effect.fn("SqliteSubmissionLedger.suspend")(function* (request) {
2464
+ const operation = "ledger suspend";
2465
+ const validated = yield* Schema.decodeUnknownEffect(Schema.toType(SuspendRequest))(request).pipe(Effect.mapError(internalFailure(operation)));
2466
+ const reasonJson = yield* encodeSuspensionReasonText(validated.reason).pipe(Effect.mapError(internalFailure(operation)));
2467
+ yield* hitFailpoint("ledger:suspend:before", operation);
2468
+ const outcome = yield* inWriteTransaction(operation, Effect.gen(function* () {
2469
+ const submission = yield* requireSubmission(operation, validated.submissionId);
2470
+ if (submission.state === "settled") {
2471
+ if (submission.settled_outcome === null) return yield* corruptionFailure(operation, "effect_agent_submissions", validated.submissionId, "A settled Submission carries no terminal outcome.");
2472
+ return yield* SettlementConflict.make({
2473
+ submissionId: validated.submissionId,
2474
+ existingOutcome: submission.settled_outcome
2475
+ });
2476
+ }
2477
+ const reservation = yield* readReservation(operation, validated.submissionId);
2478
+ if (Option.isSome(reservation)) return yield* SettlementConflict.make({
2479
+ submissionId: validated.submissionId,
2480
+ existingOutcome: reservation.value.outcome
2481
+ });
2482
+ yield* requireOwnership(operation, submission, validated.ownershipToken);
2483
+ if (validated.reason._tag === "ApprovalPending") {
2484
+ const decisions = yield* readApprovalDecisions(operation, validated.submissionId);
2485
+ const decided = new Set(decisions.map((row) => row.tool_call_id));
2486
+ if (validated.reason.toolCallIds.every((toolCallId) => decided.has(toolCallId))) return "resume-immediately";
2487
+ } else {
2488
+ let allSettled = true;
2489
+ for (const child of validated.reason.children) {
2490
+ const childRow = yield* readSubmission(operation, child.childSubmissionId);
2491
+ if (Option.isNone(childRow) || childRow.value.state !== "settled") {
2492
+ allSettled = false;
2493
+ break;
2494
+ }
2495
+ }
2496
+ if (allSettled) return "resume-immediately";
2497
+ }
2498
+ const now = yield* currentInstant;
2499
+ yield* sql`
2500
+ UPDATE effect_agent_submissions
2501
+ SET
2502
+ state = 'suspended',
2503
+ suspended_reason_json = ${reasonJson},
2504
+ suspended_at = ${now.iso}
2505
+ WHERE submission_id = ${validated.submissionId}
2506
+ `.pipe(Effect.mapError(sqlFailure(operation)));
2507
+ yield* sql`
2508
+ DELETE FROM effect_agent_submission_ownership
2509
+ WHERE submission_id = ${validated.submissionId}
2510
+ `.pipe(Effect.mapError(sqlFailure(operation)));
2511
+ return "suspended";
2512
+ }));
2513
+ yield* hitFailpoint("ledger:suspend:after", operation);
2514
+ return outcome;
2515
+ });
2516
+ /**
2517
+ * Once every pending call of a recorded ApprovalPending suspension has a decision intent,
2518
+ * the lane wakes: suspended → input-applied, suspension cleared (plan §2.6). A
2519
+ * WaitingForChild suspension wakes only through recordChildSettled. Runs inside the caller's
2520
+ * write transaction.
2521
+ */
2522
+ const wakeSuspendedIfCovered = Effect.fn("SqliteSubmissionLedger.wakeSuspendedIfCovered")(function* (operation, submission) {
2523
+ if (submission.state !== "suspended" || submission.suspended_reason_json === null) return;
2524
+ const reason = yield* Schema.decodeEffect(Schema.fromJsonString(SuspensionReason))(submission.suspended_reason_json).pipe(Effect.mapError((error) => corruptionFailure(operation, "effect_agent_submissions", submission.submission_id, error.message)));
2525
+ if (reason._tag !== "ApprovalPending") return;
2526
+ const decisions = yield* readApprovalDecisions(operation, submission.submission_id);
2527
+ const decided = new Set(decisions.map((row) => row.tool_call_id));
2528
+ if (!reason.toolCallIds.every((toolCallId) => decided.has(toolCallId))) return;
2529
+ yield* sql`
2530
+ UPDATE effect_agent_submissions
2531
+ SET
2532
+ state = 'input-applied',
2533
+ suspended_reason_json = NULL,
2534
+ suspended_at = NULL
2535
+ WHERE submission_id = ${submission.submission_id}
2536
+ `.pipe(Effect.mapError(sqlFailure(operation)));
2537
+ });
2538
+ const recordApprovalDecision = Effect.fn("SqliteSubmissionLedger.recordApprovalDecision")(function* (command) {
2539
+ const operation = "ledger record approval decision";
2540
+ const validated = yield* Schema.decodeUnknownEffect(Schema.toType(ApprovalDecisionCommand))(command).pipe(Effect.mapError(internalFailure(operation)));
2541
+ yield* hitFailpoint("ledger:approval-decision:before", operation);
2542
+ const intent = yield* inWriteTransaction(operation, Effect.gen(function* () {
2543
+ const submission = yield* requireSubmission(operation, validated.submissionId);
2544
+ if (submission.state === "settled") {
2545
+ if (submission.settled_outcome === null) return yield* corruptionFailure(operation, "effect_agent_submissions", validated.submissionId, "A settled Submission carries no terminal outcome.");
2546
+ return yield* SettlementConflict.make({
2547
+ submissionId: validated.submissionId,
2548
+ existingOutcome: submission.settled_outcome
2549
+ });
2550
+ }
2551
+ const existing = (yield* readApprovalDecisions(operation, validated.submissionId)).find((row) => row.tool_call_id === validated.toolCallId);
2552
+ if (existing !== void 0) {
2553
+ if (existing.decision !== validated.decision) return yield* ApprovalConflict.make({
2554
+ submissionId: validated.submissionId,
2555
+ toolCallId: validated.toolCallId,
2556
+ existingDecision: existing.decision
2557
+ });
2558
+ return yield* approvalIntentFromRow(operation, existing);
2559
+ }
2560
+ const now = yield* currentInstant;
2561
+ yield* sql`
2562
+ INSERT INTO effect_agent_approval_decisions (
2563
+ submission_id,
2564
+ tool_call_id,
2565
+ decision,
2566
+ resolver,
2567
+ reason,
2568
+ decided_at
2569
+ ) VALUES (
2570
+ ${validated.submissionId},
2571
+ ${validated.toolCallId},
2572
+ ${validated.decision},
2573
+ ${validated.resolver},
2574
+ ${validated.reason},
2575
+ ${now.iso}
2576
+ )
2577
+ `.pipe(Effect.mapError(sqlFailure(operation)));
2578
+ yield* wakeSuspendedIfCovered(operation, submission);
2579
+ return yield* decodeApprovalDecisionIntent({
2580
+ submissionId: validated.submissionId,
2581
+ toolCallId: validated.toolCallId,
2582
+ decision: validated.decision,
2583
+ resolver: validated.resolver,
2584
+ reason: validated.reason,
2585
+ decidedAt: now.iso
2586
+ }).pipe(Effect.mapError(internalFailure(operation)));
2587
+ }));
2588
+ yield* hitFailpoint("ledger:approval-decision:after", operation);
2589
+ return intent;
2590
+ });
2591
+ const markUnknown = Effect.fn("SqliteSubmissionLedger.markUnknown")(function* (request) {
2592
+ const operation = "ledger mark unknown";
2593
+ const validated = yield* Schema.decodeUnknownEffect(Schema.toType(MarkUnknownRequest))(request).pipe(Effect.mapError(internalFailure(operation)));
2594
+ yield* hitFailpoint("ledger:mark-unknown:before", operation);
2595
+ yield* inWriteTransaction(operation, Effect.gen(function* () {
2596
+ const submission = yield* requireSubmission(operation, validated.submissionId);
2597
+ if (submission.state === "settled") {
2598
+ if (submission.settled_outcome === null) return yield* corruptionFailure(operation, "effect_agent_submissions", validated.submissionId, "A settled Submission carries no terminal outcome.");
2599
+ return yield* SettlementConflict.make({
2600
+ submissionId: validated.submissionId,
2601
+ existingOutcome: submission.settled_outcome
2602
+ });
2603
+ }
2604
+ const reservation = yield* readReservation(operation, validated.submissionId);
2605
+ if (Option.isSome(reservation)) return yield* SettlementConflict.make({
2606
+ submissionId: validated.submissionId,
2607
+ existingOutcome: reservation.value.outcome
2608
+ });
2609
+ const existingIds = yield* storedUnknownToolCallIds(operation, submission);
2610
+ const known = new Set(existingIds);
2611
+ const merged = [...existingIds, ...validated.toolCallIds.filter((toolCallId) => !known.has(toolCallId))];
2612
+ const idsJson = yield* encodeToolCallIdsText(merged).pipe(Effect.mapError(internalFailure(operation)));
2613
+ yield* sql`
2614
+ UPDATE effect_agent_submissions
2615
+ SET
2616
+ state = 'unknown',
2617
+ unknown_reason = ${submission.unknown_reason ?? validated.reason},
2618
+ unknown_tool_call_ids_json = ${idsJson}
2619
+ WHERE submission_id = ${validated.submissionId}
2620
+ `.pipe(Effect.mapError(sqlFailure(operation)));
2621
+ }));
2622
+ yield* hitFailpoint("ledger:mark-unknown:after", operation);
2623
+ });
2624
+ const recordUnknownResolution = Effect.fn("SqliteSubmissionLedger.recordUnknownResolution")(function* (command) {
2625
+ const operation = "ledger record unknown resolution";
2626
+ const validated = yield* Schema.decodeUnknownEffect(Schema.toType(UnknownResolutionCommand))(command).pipe(Effect.mapError(internalFailure(operation)));
2627
+ const resolutionJson = yield* encodeUnknownResolutionText(validated.resolution).pipe(Effect.mapError(internalFailure(operation)));
2628
+ yield* hitFailpoint("ledger:unknown-resolution:before", operation);
2629
+ const intent = yield* inWriteTransaction(operation, Effect.gen(function* () {
2630
+ const submission = yield* requireSubmission(operation, validated.submissionId);
2631
+ if (submission.state === "settled") {
2632
+ if (submission.settled_outcome === null) return yield* corruptionFailure(operation, "effect_agent_submissions", validated.submissionId, "A settled Submission carries no terminal outcome.");
2633
+ return yield* SettlementConflict.make({
2634
+ submissionId: validated.submissionId,
2635
+ existingOutcome: submission.settled_outcome
2636
+ });
2637
+ }
2638
+ const existing = (yield* readUnknownResolutions(operation, validated.submissionId)).find((row) => row.tool_call_id === validated.toolCallId);
2639
+ if (existing !== void 0 && existing.resolution_json !== resolutionJson) return yield* UnknownResolutionConflict.make({
2640
+ submissionId: validated.submissionId,
2641
+ toolCallId: validated.toolCallId
2642
+ });
2643
+ let resolved;
2644
+ if (existing !== void 0) resolved = yield* unknownResolutionIntentFromRow(operation, existing);
2645
+ else {
2646
+ const now = yield* currentInstant;
2647
+ yield* sql`
2648
+ INSERT INTO effect_agent_unknown_resolutions (
2649
+ submission_id,
2650
+ tool_call_id,
2651
+ author,
2652
+ reason,
2653
+ resolution_json,
2654
+ resolved_at
2655
+ ) VALUES (
2656
+ ${validated.submissionId},
2657
+ ${validated.toolCallId},
2658
+ ${validated.author},
2659
+ ${validated.reason},
2660
+ ${resolutionJson},
2661
+ ${now.iso}
2662
+ )
2663
+ `.pipe(Effect.mapError(sqlFailure(operation)));
2664
+ const resolution = yield* parseStoredJsonText(resolutionJson).pipe(Effect.mapError(internalFailure(operation)));
2665
+ resolved = yield* decodeUnknownResolutionIntent({
2666
+ submissionId: validated.submissionId,
2667
+ toolCallId: validated.toolCallId,
2668
+ author: validated.author,
2669
+ reason: validated.reason,
2670
+ resolution,
2671
+ resolvedAt: now.iso
2672
+ }).pipe(Effect.mapError(internalFailure(operation)));
2673
+ }
2674
+ if (submission.state === "unknown" && submission.unknown_tool_call_ids_json !== null) {
2675
+ const markedIds = yield* storedUnknownToolCallIds(operation, submission);
2676
+ const covering = yield* readUnknownResolutions(operation, validated.submissionId);
2677
+ const coveredIds = new Set(covering.map((row) => row.tool_call_id));
2678
+ if (markedIds.every((toolCallId) => coveredIds.has(toolCallId))) yield* sql`
2679
+ UPDATE effect_agent_submissions
2680
+ SET
2681
+ state = 'input-applied',
2682
+ unknown_reason = NULL,
2683
+ unknown_tool_call_ids_json = NULL
2684
+ WHERE submission_id = ${validated.submissionId}
2685
+ `.pipe(Effect.mapError(sqlFailure(operation)));
2686
+ }
2687
+ return resolved;
2688
+ }));
2689
+ yield* hitFailpoint("ledger:unknown-resolution:after", operation);
2690
+ return intent;
2691
+ });
2692
+ const recordChildSettled = Effect.fn("SqliteSubmissionLedger.recordChildSettled")(function* (request) {
2693
+ const operation = "ledger record child settled";
2694
+ const validated = yield* Schema.decodeUnknownEffect(Schema.toType(ChildSettledNotification))(request).pipe(Effect.mapError(internalFailure(operation)));
2695
+ yield* hitFailpoint("ledger:child-settled:before", operation);
2696
+ const outcome = yield* inWriteTransaction(operation, Effect.gen(function* () {
2697
+ const parent = yield* requireSubmission(operation, validated.parentSubmissionId);
2698
+ const child = yield* readSubmission(operation, validated.childSubmissionId);
2699
+ if (Option.isNone(child) || child.value.state !== "settled") return yield* LedgerError.make({
2700
+ operation,
2701
+ message: `Child submission ${validated.childSubmissionId} has no recorded settlement.`
2702
+ });
2703
+ if (parent.state !== "suspended" || parent.suspended_reason_json === null) return "not-waiting";
2704
+ const reason = yield* Schema.decodeEffect(Schema.fromJsonString(SuspensionReason))(parent.suspended_reason_json).pipe(Effect.mapError((error) => corruptionFailure(operation, "effect_agent_submissions", parent.submission_id, error.message)));
2705
+ if (reason._tag !== "WaitingForChild") return "not-waiting";
2706
+ if (!reason.children.some((entry) => entry.childSubmissionId === validated.childSubmissionId)) return "not-waiting";
2707
+ for (const entry of reason.children) {
2708
+ const listed = yield* readSubmission(operation, entry.childSubmissionId);
2709
+ if (Option.isNone(listed) || listed.value.state !== "settled") return "still-waiting";
2710
+ }
2711
+ yield* sql`
2712
+ UPDATE effect_agent_submissions
2713
+ SET
2714
+ state = 'input-applied',
2715
+ suspended_reason_json = NULL,
2716
+ suspended_at = NULL
2717
+ WHERE submission_id = ${validated.parentSubmissionId}
2718
+ `.pipe(Effect.mapError(sqlFailure(operation)));
2719
+ return "woken";
2720
+ }));
2721
+ yield* hitFailpoint("ledger:child-settled:after", operation);
2722
+ return outcome;
2723
+ });
2724
+ const reserveChildBudget = Effect.fn("SqliteSubmissionLedger.reserveChildBudget")(function* (request) {
2725
+ const operation = "ledger reserve child budget";
2726
+ const validated = yield* Schema.decodeUnknownEffect(Schema.toType(ChildBudgetReservationRequest))(request).pipe(Effect.mapError(internalFailure(operation)));
2727
+ const allocationJson = yield* encodePersistedJsonText(validated.allocation).pipe(Effect.mapError(internalFailure(operation)));
2728
+ yield* hitFailpoint("ledger:child-reservation:before", operation);
2729
+ const reserved = yield* inWriteTransaction(operation, Effect.gen(function* () {
2730
+ const existing = yield* readChildReservation(operation, validated.reservationId);
2731
+ if (Option.isSome(existing)) {
2732
+ if (!(existing.value.parent_submission_id === validated.parentSubmissionId && existing.value.parent_tool_call_id === validated.parentToolCallId && existing.value.allocation_digest === validated.allocationDigest && existing.value.allocation_json === allocationJson)) return yield* ChildReservationConflict.make({
2733
+ reservationId: validated.reservationId,
2734
+ status: existing.value.status,
2735
+ message: "A reservation with this identity exists with a different parent Tool Call or allocation."
2736
+ });
2737
+ return ReservedChildBudget.make({
2738
+ reservation: yield* childReservationSnapshotFromRow(operation, existing.value),
2739
+ replayed: true
2740
+ });
2741
+ }
2742
+ const collision = yield* readChildReservationForCall(operation, validated.parentSubmissionId, validated.parentToolCallId);
2743
+ if (Option.isSome(collision)) return yield* ChildReservationConflict.make({
2744
+ reservationId: validated.reservationId,
2745
+ status: collision.value.status,
2746
+ message: `Parent Tool Call ${validated.parentToolCallId} already owns reservation ${collision.value.reservation_id}.`
2747
+ });
2748
+ const parent = yield* requireSubmission(operation, validated.parentSubmissionId);
2749
+ yield* requireOwnership(operation, parent, validated.ownershipToken);
2750
+ const now = yield* currentInstant;
2751
+ yield* sql`
2752
+ INSERT INTO effect_agent_child_reservations (
2753
+ reservation_id,
2754
+ parent_submission_id,
2755
+ parent_tool_call_id,
2756
+ status,
2757
+ allocation_json,
2758
+ allocation_digest,
2759
+ reserved_at
2760
+ ) VALUES (
2761
+ ${validated.reservationId},
2762
+ ${validated.parentSubmissionId},
2763
+ ${validated.parentToolCallId},
2764
+ 'reserved',
2765
+ ${allocationJson},
2766
+ ${validated.allocationDigest},
2767
+ ${now.iso}
2768
+ )
2769
+ `.pipe(Effect.mapError(sqlFailure(operation)));
2770
+ const inserted = yield* readChildReservation(operation, validated.reservationId);
2771
+ if (Option.isNone(inserted)) return yield* corruptionFailure(operation, "effect_agent_child_reservations", validated.reservationId, "An inserted child reservation row is missing inside its own transaction.");
2772
+ return ReservedChildBudget.make({
2773
+ reservation: yield* childReservationSnapshotFromRow(operation, inserted.value),
2774
+ replayed: false
2775
+ });
2776
+ }));
2777
+ yield* hitFailpoint("ledger:child-reservation:after", operation);
2778
+ return reserved;
2779
+ });
2780
+ const attachChildToReservation = Effect.fn("SqliteSubmissionLedger.attachChildToReservation")(function* (request) {
2781
+ const operation = "ledger attach child to reservation";
2782
+ const validated = yield* Schema.decodeUnknownEffect(Schema.toType(AttachChildToReservationRequest))(request).pipe(Effect.mapError(internalFailure(operation)));
2783
+ yield* hitFailpoint("ledger:child-attach:before", operation);
2784
+ const attached = yield* inWriteTransaction(operation, Effect.gen(function* () {
2785
+ const existing = yield* readChildReservation(operation, validated.reservationId);
2786
+ if (Option.isNone(existing)) return yield* LedgerError.make({
2787
+ operation,
2788
+ message: `Unknown child reservation ${validated.reservationId}.`
2789
+ });
2790
+ if (existing.value.child_submission_id !== null) {
2791
+ if (existing.value.child_submission_id === validated.childSubmissionId) return yield* childReservationSnapshotFromRow(operation, existing.value);
2792
+ return yield* ChildReservationConflict.make({
2793
+ reservationId: validated.reservationId,
2794
+ status: existing.value.status,
2795
+ message: `Reservation ${validated.reservationId} already records child ${existing.value.child_submission_id}.`
2796
+ });
2797
+ }
2798
+ const parent = yield* requireSubmission(operation, existing.value.parent_submission_id);
2799
+ yield* requireOwnership(operation, parent, validated.ownershipToken);
2800
+ if (existing.value.status !== "reserved") return yield* ChildReservationConflict.make({
2801
+ reservationId: validated.reservationId,
2802
+ status: existing.value.status,
2803
+ message: `Cannot attach a child to a ${existing.value.status} reservation.`
2804
+ });
2805
+ const child = yield* readSubmission(operation, validated.childSubmissionId);
2806
+ if (Option.isNone(child)) return yield* LedgerError.make({
2807
+ operation,
2808
+ message: `Unknown child submission ${validated.childSubmissionId}.`
2809
+ });
2810
+ yield* sql`
2811
+ UPDATE effect_agent_child_reservations
2812
+ SET child_submission_id = ${validated.childSubmissionId}
2813
+ WHERE reservation_id = ${validated.reservationId}
2814
+ `.pipe(Effect.mapError(sqlFailure(operation)));
2815
+ const updated = yield* readChildReservation(operation, validated.reservationId);
2816
+ if (Option.isNone(updated)) return yield* corruptionFailure(operation, "effect_agent_child_reservations", validated.reservationId, "An updated child reservation row is missing inside its own transaction.");
2817
+ return yield* childReservationSnapshotFromRow(operation, updated.value);
2818
+ }));
2819
+ yield* hitFailpoint("ledger:child-attach:after", operation);
2820
+ return attached;
2821
+ });
2822
+ const beginChildBudgetRelease = Effect.fn("SqliteSubmissionLedger.beginChildBudgetRelease")(function* (request) {
2823
+ const operation = "ledger begin child budget release";
2824
+ const validated = yield* Schema.decodeUnknownEffect(Schema.toType(BeginChildBudgetReleaseRequest))(request).pipe(Effect.mapError(internalFailure(operation)));
2825
+ const accountingJson = yield* encodePersistedJsonText(validated.accounting).pipe(Effect.mapError(internalFailure(operation)));
2826
+ yield* hitFailpoint("ledger:child-release-pending:before", operation);
2827
+ const frozen = yield* inWriteTransaction(operation, Effect.gen(function* () {
2828
+ const existing = yield* readChildReservation(operation, validated.reservationId);
2829
+ if (Option.isNone(existing)) return yield* LedgerError.make({
2830
+ operation,
2831
+ message: `Unknown child reservation ${validated.reservationId}.`
2832
+ });
2833
+ if (existing.value.status !== "reserved") {
2834
+ if (existing.value.accounting_json === accountingJson) return yield* childReservationSnapshotFromRow(operation, existing.value);
2835
+ return yield* ChildReservationConflict.make({
2836
+ reservationId: validated.reservationId,
2837
+ status: existing.value.status,
2838
+ message: "A different accounting decision is already frozen for this reservation."
2839
+ });
2840
+ }
2841
+ const now = yield* currentInstant;
2842
+ yield* sql`
2843
+ UPDATE effect_agent_child_reservations
2844
+ SET
2845
+ status = 'releasePending',
2846
+ accounting_json = ${accountingJson},
2847
+ release_began_at = ${now.iso}
2848
+ WHERE reservation_id = ${validated.reservationId}
2849
+ `.pipe(Effect.mapError(sqlFailure(operation)));
2850
+ const updated = yield* readChildReservation(operation, validated.reservationId);
2851
+ if (Option.isNone(updated)) return yield* corruptionFailure(operation, "effect_agent_child_reservations", validated.reservationId, "An updated child reservation row is missing inside its own transaction.");
2852
+ return yield* childReservationSnapshotFromRow(operation, updated.value);
2853
+ }));
2854
+ yield* hitFailpoint("ledger:child-release-pending:after", operation);
2855
+ return frozen;
2856
+ });
2857
+ const releaseChildBudget = Effect.fn("SqliteSubmissionLedger.releaseChildBudget")(function* (request) {
2858
+ const operation = "ledger release child budget";
2859
+ const validated = yield* Schema.decodeUnknownEffect(Schema.toType(ReleaseChildBudgetRequest))(request).pipe(Effect.mapError(internalFailure(operation)));
2860
+ yield* hitFailpoint("ledger:child-release:before", operation);
2861
+ const released = yield* inWriteTransaction(operation, Effect.gen(function* () {
2862
+ const existing = yield* readChildReservation(operation, validated.reservationId);
2863
+ if (Option.isNone(existing)) return yield* LedgerError.make({
2864
+ operation,
2865
+ message: `Unknown child reservation ${validated.reservationId}.`
2866
+ });
2867
+ if (existing.value.status === "released") return yield* childReservationSnapshotFromRow(operation, existing.value);
2868
+ if (existing.value.status !== "releasePending") return yield* ChildReservationConflict.make({
2869
+ reservationId: validated.reservationId,
2870
+ status: existing.value.status,
2871
+ message: "Cannot release a reservation whose accounting decision is not frozen."
2872
+ });
2873
+ const now = yield* currentInstant;
2874
+ yield* sql`
2875
+ UPDATE effect_agent_child_reservations
2876
+ SET status = 'released', released_at = ${now.iso}
2877
+ WHERE reservation_id = ${validated.reservationId}
2878
+ `.pipe(Effect.mapError(sqlFailure(operation)));
2879
+ const updated = yield* readChildReservation(operation, validated.reservationId);
2880
+ if (Option.isNone(updated)) return yield* corruptionFailure(operation, "effect_agent_child_reservations", validated.reservationId, "An updated child reservation row is missing inside its own transaction.");
2881
+ return yield* childReservationSnapshotFromRow(operation, updated.value);
2882
+ }));
2883
+ yield* hitFailpoint("ledger:child-release:after", operation);
2884
+ return released;
2885
+ });
2886
+ const scanPage = Effect.fn("SqliteSubmissionLedger.scanPage")(function* (cursor) {
2887
+ const operation = "ledger scan nonterminal";
2888
+ const rows = yield* (cursor === void 0 ? sql`
2889
+ SELECT ${sql.literal(SUBMISSION_COLUMNS)}
2890
+ FROM effect_agent_submissions
2891
+ WHERE state <> 'settled'
2892
+ ORDER BY conversation_id ASC, queue_sequence ASC
2893
+ LIMIT ${SCAN_PAGE_SIZE}
2894
+ ` : sql`
2895
+ SELECT ${sql.literal(SUBMISSION_COLUMNS)}
2896
+ FROM effect_agent_submissions
2897
+ WHERE state <> 'settled'
2898
+ AND (
2899
+ conversation_id > ${cursor.conversationId}
2900
+ OR (
2901
+ conversation_id = ${cursor.conversationId}
2902
+ AND queue_sequence > ${cursor.queueSequence}
2903
+ )
2904
+ )
2905
+ ORDER BY conversation_id ASC, queue_sequence ASC
2906
+ LIMIT ${SCAN_PAGE_SIZE}
2907
+ `).pipe(Effect.mapError(sqlFailure(operation)));
2908
+ const decoded = yield* decodeSubmissionRows(operation, "nonterminal_scan", rows);
2909
+ const snapshots = yield* Effect.forEach(decoded, (row) => decodeSubmissionSnapshot(operation, row));
2910
+ const last = decoded[decoded.length - 1];
2911
+ return [snapshots, last === void 0 || decoded.length < SCAN_PAGE_SIZE ? Option.none() : Option.some({
2912
+ conversationId: last.conversation_id,
2913
+ queueSequence: last.queue_sequence
2914
+ })];
2915
+ });
2916
+ const scanNonterminal = Stream.paginate(void 0, scanPage);
2917
+ const loadRecoverySnapshot = Effect.fn("SqliteSubmissionLedger.loadRecoverySnapshot")(function* (request) {
2918
+ const operation = "ledger load recovery snapshot";
2919
+ const validated = yield* Schema.decodeUnknownEffect(Schema.toType(RecoverySnapshotRequest))(request).pipe(Effect.mapError(internalFailure(operation)));
2920
+ return yield* sql.withTransaction(Effect.gen(function* () {
2921
+ const submissionRow = yield* requireSubmission(operation, validated.submissionId);
2922
+ const submission = yield* decodeSubmissionSnapshot(operation, submissionRow);
2923
+ let ownership;
2924
+ const ownershipRow = yield* readOwnership(operation, validated.submissionId);
2925
+ if (Option.isSome(ownershipRow)) ownership = yield* decodeOwnershipSnapshot({
2926
+ attemptId: ownershipRow.value.attempt_id,
2927
+ ownerProducerId: ownershipRow.value.owner_producer_id,
2928
+ producerEpoch: ownershipRow.value.producer_epoch,
2929
+ leaseExpiresAt: ownershipRow.value.lease_expires_at
2930
+ }).pipe(Effect.mapError(internalFailure(operation)));
2931
+ let inputApplied;
2932
+ if (submissionRow.input_applied_record_id !== null && submissionRow.input_applied_sequence !== null) inputApplied = yield* decodeInputAppliedMarker({
2933
+ recordId: submissionRow.input_applied_record_id,
2934
+ sequence: submissionRow.input_applied_sequence
2935
+ }).pipe(Effect.mapError(internalFailure(operation)));
2936
+ let reservation;
2937
+ const reservationRow = yield* readReservation(operation, validated.submissionId);
2938
+ if (Option.isSome(reservationRow)) {
2939
+ const record = yield* decodeRecordEnvelopeText(reservationRow.value.record_json).pipe(Effect.mapError((error) => corruptionFailure(operation, "effect_agent_settlement_reservations", validated.submissionId, error.message)));
2940
+ const settlementId = yield* Schema.decodeUnknownEffect(SettlementReservationSnapshot.fields.settlementId)(reservationRow.value.settlement_id).pipe(Effect.mapError(internalFailure(operation)));
2941
+ reservation = SettlementReservationSnapshot.make({
2942
+ settlementId,
2943
+ outcome: reservationRow.value.outcome,
2944
+ record,
2945
+ recordDigest: reservationRow.value.record_digest,
2946
+ finalized: reservationRow.value.finalized_at !== null
2947
+ });
2948
+ }
2949
+ let abortIntent;
2950
+ const abortRow = yield* readAbortIntent(operation, validated.submissionId);
2951
+ if (Option.isSome(abortRow)) abortIntent = yield* abortIntentFromRow(operation, submissionRow, validated.submissionId, abortRow.value);
2952
+ const joinRows = yield* sql`
2953
+ SELECT ${sql.literal(SUBMISSION_COLUMNS)}
2954
+ FROM effect_agent_submissions
2955
+ WHERE joined_host_submission_id = ${validated.submissionId}
2956
+ ORDER BY queue_sequence ASC
2957
+ `.pipe(Effect.mapError(sqlFailure(operation)));
2958
+ const joinSubmissions = yield* decodeSubmissionRows(operation, validated.submissionId, joinRows);
2959
+ const joins = yield* Effect.forEach(joinSubmissions, (row) => decodeJoinSnapshot({
2960
+ submissionId: row.submission_id,
2961
+ state: row.state,
2962
+ hostSubmissionId: validated.submissionId
2963
+ }).pipe(Effect.mapError(internalFailure(operation))));
2964
+ let hostSubmissionId;
2965
+ if (submissionRow.joined_host_submission_id !== null) hostSubmissionId = yield* decodeSubmissionId(submissionRow.joined_host_submission_id).pipe(Effect.mapError(internalFailure(operation)));
2966
+ let suspension;
2967
+ if (submissionRow.suspended_reason_json !== null && submissionRow.suspended_at !== null) {
2968
+ const reason = yield* parseStoredJsonText(submissionRow.suspended_reason_json).pipe(Effect.mapError((error) => corruptionFailure(operation, "effect_agent_submissions", validated.submissionId, error.message)));
2969
+ suspension = yield* decodeSuspensionSnapshot({
2970
+ reason,
2971
+ suspendedAt: submissionRow.suspended_at
2972
+ }).pipe(Effect.mapError((error) => corruptionFailure(operation, "effect_agent_submissions", validated.submissionId, error.message)));
2973
+ }
2974
+ const decisionRows = yield* readApprovalDecisions(operation, validated.submissionId);
2975
+ const approvalDecisions = yield* Effect.forEach(decisionRows, (row) => approvalIntentFromRow(operation, row));
2976
+ const resolutionRows = yield* readUnknownResolutions(operation, validated.submissionId);
2977
+ const unknownResolutions = yield* Effect.forEach(resolutionRows, (row) => unknownResolutionIntentFromRow(operation, row));
2978
+ const childReservationRows = yield* sql`
2979
+ SELECT ${sql.literal(CHILD_RESERVATION_COLUMNS)}
2980
+ FROM effect_agent_child_reservations
2981
+ WHERE parent_submission_id = ${validated.submissionId}
2982
+ ORDER BY parent_tool_call_id ASC
2983
+ `.pipe(Effect.mapError(sqlFailure(operation)));
2984
+ const decodedChildReservations = yield* decodeChildReservationRows(operation, validated.submissionId, childReservationRows);
2985
+ const childReservations = yield* Effect.forEach(decodedChildReservations, (row) => childReservationSnapshotFromRow(operation, row));
2986
+ const childAttachments = [];
2987
+ for (const row of decodedChildReservations) {
2988
+ if (row.child_submission_id === null) continue;
2989
+ const child = yield* readSubmission(operation, row.child_submission_id);
2990
+ if (Option.isNone(child)) continue;
2991
+ childAttachments.push(yield* decodeChildAttachmentSnapshot({
2992
+ toolCallId: row.parent_tool_call_id,
2993
+ childSubmissionId: row.child_submission_id,
2994
+ childState: child.value.state,
2995
+ ...child.value.settled_outcome === null ? {} : { childOutcome: child.value.settled_outcome }
2996
+ }).pipe(Effect.mapError(internalFailure(operation))));
2997
+ }
2998
+ let parentLinkage;
2999
+ if (submissionRow.parent_submission_id !== null && submissionRow.parent_tool_call_id !== null) parentLinkage = yield* decodeParentLinkage({
3000
+ parentSubmissionId: submissionRow.parent_submission_id,
3001
+ parentToolCallId: submissionRow.parent_tool_call_id
3002
+ }).pipe(Effect.mapError(internalFailure(operation)));
3003
+ return RecoverySnapshot.make({
3004
+ submission,
3005
+ joins,
3006
+ approvalDecisions,
3007
+ unknownResolutions,
3008
+ childReservations,
3009
+ childAttachments,
3010
+ ...parentLinkage === void 0 ? {} : { parentLinkage },
3011
+ ...hostSubmissionId === void 0 ? {} : { hostSubmissionId },
3012
+ ...suspension === void 0 ? {} : { suspension },
3013
+ ...ownership === void 0 ? {} : { ownership },
3014
+ ...inputApplied === void 0 ? {} : { inputApplied },
3015
+ ...reservation === void 0 ? {} : { reservation },
3016
+ ...abortIntent === void 0 ? {} : { abortIntent }
3017
+ });
3018
+ })).pipe(Effect.catchTag("SqlError", (error) => Effect.fail(sqlFailure(operation)(error))));
3019
+ });
3020
+ return Context.make(SubmissionLedger, SubmissionLedger.of({
3021
+ capabilities,
3022
+ admit,
3023
+ markReady,
3024
+ lookup,
3025
+ resolveAdmission,
3026
+ claim,
3027
+ renewOwnership,
3028
+ releaseOwnership,
3029
+ markInputApplied,
3030
+ reserveSettlement,
3031
+ finalizeSettlement,
3032
+ requestAbort,
3033
+ claimJoining,
3034
+ markJoined,
3035
+ revertJoining,
3036
+ suspend,
3037
+ recordApprovalDecision,
3038
+ markUnknown,
3039
+ recordUnknownResolution,
3040
+ recordChildSettled,
3041
+ reserveChildBudget,
3042
+ attachChildToReservation,
3043
+ beginChildBudgetRelease,
3044
+ releaseChildBudget,
3045
+ scanNonterminal,
3046
+ loadRecoverySnapshot
3047
+ }));
3048
+ });
3049
+ /**
3050
+ * SQLite SubmissionLedger implementation sharing the journal's database file, write
3051
+ * transaction discipline, and producer-epoch fencing substrate. Configuration, failpoint,
3052
+ * SQL, and Crypto authority stay visible in the input channel.
3053
+ */
3054
+ const submissionLedgerLayer = Layer.effectContext(makeServices());
3055
+ /**
3056
+ * A composition-root convenience Layer for the durable Submission Ledger. Point it at the
3057
+ * same database file as the ConversationStore so claims fence the same producer epochs.
3058
+ */
3059
+ const ledgerLayer = (options) => submissionLedgerLayer.pipe(Layer.provide(Layer.mergeAll(storageConfigLayer(options), storageFailpointLayer(options), SqliteClient.layer({ filename: options.filename }), NodeCrypto.layer)));
3060
+ //#endregion
3061
+ export { CurrentSqliteStorageVersion, SqliteAppendConflict, SqliteCheckpointConflict, SqliteFenceRejected, SqliteLedgerError, SqliteStorageCompatibilityError, SqliteStorageConfig, SqliteStorageConfigValue, SqliteStorageCorruptionError, SqliteStorageError, SqliteStorageFailpoint, SqliteStorageFailpointError, SqliteStorageFailpointLocation, SqliteStorageFailpointTestControl, SqliteWriteContention, conversationStoreLayer, layer, ledgerLayer, observationOffsetAt, sqliteMigrations, storageConfigLayer, storageFailpointLayer, submissionLedgerLayer };
3062
+
3063
+ //# sourceMappingURL=index.mjs.map