@effect-agent/storage-cloudflare 0.1.0-beta.12 → 0.1.0-beta.120

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.
Files changed (74) hide show
  1. package/dist/DoMemoryStore.d.mts +29 -0
  2. package/dist/DoMemoryStore.mjs +55 -0
  3. package/dist/DoMemoryStore.mjs.map +1 -0
  4. package/dist/DoMessageDeliveryStore.d.mts +17 -0
  5. package/dist/DoMessageDeliveryStore.mjs +32 -0
  6. package/dist/DoMessageDeliveryStore.mjs.map +1 -0
  7. package/dist/DoScheduleStore.d.mts +36 -0
  8. package/dist/DoScheduleStore.mjs +388 -0
  9. package/dist/DoScheduleStore.mjs.map +1 -0
  10. package/dist/DoStorageConfig.d.mts +45 -0
  11. package/dist/DoStorageConfig.mjs +52 -0
  12. package/dist/DoStorageConfig.mjs.map +1 -0
  13. package/dist/DoStorageError-DjpuLHmX.d.mts +101 -0
  14. package/dist/DoStorageError.d.mts +2 -0
  15. package/dist/DoStorageError.mjs +167 -0
  16. package/dist/DoStorageError.mjs.map +1 -0
  17. package/dist/DoStorageFailpoint.d.mts +17 -0
  18. package/dist/DoStorageFailpoint.mjs +14 -0
  19. package/dist/DoStorageFailpoint.mjs.map +1 -0
  20. package/dist/DoStorageFailpointTesting.d.mts +33 -0
  21. package/dist/DoStorageFailpointTesting.mjs +35 -0
  22. package/dist/DoStorageFailpointTesting.mjs.map +1 -0
  23. package/dist/DoStorageVersion-DJwZzqel.d.mts +12 -0
  24. package/dist/DoStorageVersion.d.mts +2 -0
  25. package/dist/DoStorageVersion.mjs +8 -0
  26. package/dist/DoStorageVersion.mjs.map +1 -0
  27. package/dist/DoSubmissionLedger.d.mts +23 -0
  28. package/dist/DoSubmissionLedger.mjs +1939 -0
  29. package/dist/DoSubmissionLedger.mjs.map +1 -0
  30. package/dist/DoSubscriptionStore.d.mts +25 -0
  31. package/dist/DoSubscriptionStore.mjs +183 -0
  32. package/dist/DoSubscriptionStore.mjs.map +1 -0
  33. package/dist/DoThreadStore.d.mts +59 -0
  34. package/dist/DoThreadStore.mjs +499 -0
  35. package/dist/DoThreadStore.mjs.map +1 -0
  36. package/dist/MemoryProtocol.d.mts +38160 -0
  37. package/dist/MemoryProtocol.mjs +219 -0
  38. package/dist/MemoryProtocol.mjs.map +1 -0
  39. package/dist/PortProtocol.d.mts +5521 -0
  40. package/dist/PortProtocol.mjs +206 -0
  41. package/dist/PortProtocol.mjs.map +1 -0
  42. package/dist/PortRouting.d.mts +86 -0
  43. package/dist/PortRouting.mjs +461 -0
  44. package/dist/PortRouting.mjs.map +1 -0
  45. package/dist/do-journal-D65Iuln6.mjs +1119 -0
  46. package/dist/do-journal-D65Iuln6.mjs.map +1 -0
  47. package/dist/index.d.mts +14 -1525
  48. package/dist/index.mjs +14 -3695
  49. package/dist/migrations-Br6QqMIf.mjs +306 -0
  50. package/dist/migrations-Br6QqMIf.mjs.map +1 -0
  51. package/dist/rolldown-runtime-D7D4PA-g.mjs +13 -0
  52. package/package.json +1 -45
  53. package/src/DoMemoryStore.ts +56 -0
  54. package/src/DoMessageDeliveryStore.ts +53 -0
  55. package/src/DoScheduleStore.ts +622 -0
  56. package/src/{errors.ts → DoStorageError.ts} +13 -3
  57. package/src/DoStorageFailpoint.ts +20 -0
  58. package/src/{do-storage-failpoint.ts → DoStorageFailpointTesting.ts} +5 -18
  59. package/src/DoStorageVersion.ts +2 -0
  60. package/src/{do-ledger.ts → DoSubmissionLedger.ts} +1119 -262
  61. package/src/DoSubscriptionStore.ts +329 -0
  62. package/src/DoThreadStore.ts +1064 -0
  63. package/src/MemoryProtocol.ts +351 -0
  64. package/src/{port-protocol.ts → PortProtocol.ts} +103 -38
  65. package/src/{routing.ts → PortRouting.ts} +440 -264
  66. package/src/index.ts +13 -32
  67. package/src/internal/do-journal.ts +1789 -0
  68. package/src/internal/message-delivery-schema.ts +24 -0
  69. package/src/{migrations.ts → internal/migrations.ts} +72 -35
  70. package/src/internal/recovery-checkpoint-schema.ts +17 -0
  71. package/dist/index.mjs.map +0 -1
  72. package/src/do-conversation-store.ts +0 -850
  73. package/src/do-journal.ts +0 -1078
  74. /package/src/{do-storage-config.ts → DoStorageConfig.ts} +0 -0
@@ -0,0 +1,1789 @@
1
+ import { SqliteMigrator } from "@effect/sql-sqlite-do";
2
+ import { Effect, Schema, Stream } from "effect";
3
+ import { EMPTY_TAIL_DIGEST } from "effect-agent/digest";
4
+ import { CanonicalRecord, CanonicalSequence, ProducerEpoch } from "effect-agent/records";
5
+ import { createMessageDeliveryPendingIndex } from "effect-agent/sql-message-delivery-store";
6
+ import { checkV2ThreadLayout } from "effect-agent/sql-storage-v2-upgrade";
7
+ import {
8
+ createNativeReadIndexes,
9
+ seedNativeReadIndexes,
10
+ indexCanonicalRecord,
11
+ } from "effect-agent/sql-thread-native-reads";
12
+ import {
13
+ MAX_THREAD_EXPORT_RECORDS,
14
+ CheckpointRejected,
15
+ FenceRejected,
16
+ ThreadNotMaterialized,
17
+ ThreadStoreDiagnostic,
18
+ type SaveRecoveryCheckpointRequest,
19
+ } from "effect-agent/thread-store";
20
+ import * as SqlClient from "effect/unstable/sql/SqlClient";
21
+ import { SqlError } from "effect/unstable/sql/SqlError";
22
+
23
+ import {
24
+ type DoStorageFailpointError,
25
+ DoAppendConflict,
26
+ DoCheckpointConflict,
27
+ DoFenceRejected,
28
+ DoStorageCompatibilityError,
29
+ DoStorageCorruptionError,
30
+ DoStorageError,
31
+ DoValueBoundExceeded,
32
+ type DoStorageFailpointLocation,
33
+ } from "../DoStorageError.ts";
34
+ import { createMessageDeliveryTables } from "./message-delivery-schema.ts";
35
+ import {
36
+ CurrentDoStorageVersion,
37
+ createNonterminalIndex,
38
+ createWorkerStops,
39
+ doMigrations,
40
+ } from "./migrations.ts";
41
+ import { createRecoveryCheckpointTable } from "./recovery-checkpoint-schema.ts";
42
+
43
+ /**
44
+ * Static schema ceiling for stored text columns. Writes are bounded in BYTES by the
45
+ * configured `maxStoredValueBytes` (always ≤ 2,000,000); UTF-8 byte length is never smaller
46
+ * than UTF-16 string length, so any value that passed the byte bound also passes this
47
+ * decode-side character ceiling.
48
+ */
49
+ const BoundedStoredText = Schema.String.check(Schema.isMaxLength(2_000_000));
50
+ const BoundedIdentifier = Schema.NonEmptyString.check(Schema.isMaxLength(1024));
51
+ const MAX_RECORDS_PER_THREAD = MAX_THREAD_EXPORT_RECORDS;
52
+ const ZERO_SEQUENCE = Schema.decodeSync(CanonicalSequence)(0);
53
+ const MAX_IDENTIFIER_LENGTH = 1_024;
54
+ const MAX_READ_PAGE_JSON_BYTES = 4 * 1024 * 1024;
55
+ /** Durable Object SQL storage allows at most 100 bound parameters per statement. */
56
+ const MAX_BOUND_PARAMETERS = 100;
57
+ const isSqlError = Schema.is(SqlError);
58
+
59
+ const storedTextBytes = (value: string): number => new TextEncoder().encode(value).byteLength;
60
+
61
+ const chunked = <A>(values: ReadonlyArray<A>, size: number): Array<ReadonlyArray<A>> => {
62
+ const chunks: Array<ReadonlyArray<A>> = [];
63
+
64
+ for (let index = 0; index < values.length; index += size) {
65
+ chunks.push(values.slice(index, index + size));
66
+ }
67
+
68
+ return chunks;
69
+ };
70
+
71
+ class DoMetaRow extends Schema.Class<DoMetaRow>("DoMetaRow")({
72
+ value: Schema.NonEmptyString.check(Schema.isMaxLength(128)),
73
+ }) {}
74
+
75
+ class DoNameRow extends Schema.Class<DoNameRow>("DoNameRow")({
76
+ name: BoundedIdentifier,
77
+ }) {}
78
+
79
+ class ThreadRow extends Schema.Class<ThreadRow>("ThreadRow")({
80
+ thread_id: BoundedIdentifier,
81
+ created_at: Schema.NonEmptyString.check(Schema.isMaxLength(128)),
82
+ producer_epoch: ProducerEpoch,
83
+ tail_digest: BoundedStoredText,
84
+ tail_sequence: CanonicalSequence,
85
+ }) {}
86
+
87
+ class BatchRow extends Schema.Class<BatchRow>("BatchRow")({
88
+ batch_digest: BoundedStoredText,
89
+ batch_id: BoundedIdentifier,
90
+ batch_json: BoundedStoredText,
91
+ thread_id: BoundedIdentifier,
92
+ first_sequence: CanonicalSequence,
93
+ last_sequence: CanonicalSequence,
94
+ tail_digest: BoundedStoredText,
95
+ }) {}
96
+
97
+ class RecordRow extends Schema.Class<RecordRow>("RecordRow")({
98
+ batch_id: BoundedIdentifier,
99
+ thread_id: BoundedIdentifier,
100
+ record_id: BoundedIdentifier,
101
+ record_json: BoundedStoredText,
102
+ sequence: CanonicalSequence,
103
+ }) {}
104
+
105
+ const ReadPlanRow = Schema.Struct({
106
+ sequence: CanonicalSequence,
107
+ record_json_bytes: Schema.Natural.check(Schema.isLessThanOrEqualTo(MAX_READ_PAGE_JSON_BYTES)),
108
+ });
109
+
110
+ type ReadPage = [typeof ReadPlanRow.Type, ...Array<typeof ReadPlanRow.Type>];
111
+
112
+ class CheckpointRow extends Schema.Class<CheckpointRow>("CheckpointRow")({
113
+ checkpoint_json: BoundedStoredText,
114
+ thread_id: BoundedIdentifier,
115
+ tail_digest: BoundedStoredText,
116
+ through_sequence: CanonicalSequence,
117
+ }) {}
118
+
119
+ export class RawRecord extends Schema.Class<RawRecord>(
120
+ "@effect-agent/storage-cloudflare/RawRecord",
121
+ )({
122
+ recordId: BoundedIdentifier,
123
+ recordJson: BoundedStoredText,
124
+ }) {}
125
+
126
+ export class RawAppendRequest extends Schema.Class<RawAppendRequest>(
127
+ "@effect-agent/storage-cloudflare/RawAppendRequest",
128
+ )({
129
+ batchDigest: BoundedStoredText,
130
+ batchId: BoundedIdentifier,
131
+ batchJson: BoundedStoredText,
132
+ threadId: BoundedIdentifier,
133
+ expectedTailDigest: BoundedStoredText,
134
+ expectedTailSequence: CanonicalSequence,
135
+ producerEpoch: ProducerEpoch,
136
+ records: Schema.NonEmptyArray(RawRecord).check(Schema.isMaxLength(256)),
137
+ tailDigest: BoundedStoredText,
138
+ }) {}
139
+
140
+ export class RawAppendResult extends Schema.Class<RawAppendResult>(
141
+ "@effect-agent/storage-cloudflare/RawAppendResult",
142
+ )({
143
+ firstSequence: CanonicalSequence,
144
+ lastSequence: CanonicalSequence,
145
+ replayed: Schema.Boolean,
146
+ tailDigest: BoundedStoredText,
147
+ }) {}
148
+
149
+ export class RawReadRequest extends Schema.Class<RawReadRequest>(
150
+ "@effect-agent/storage-cloudflare/RawReadRequest",
151
+ )({
152
+ threadId: BoundedIdentifier,
153
+ fromSequenceExclusive: CanonicalSequence,
154
+ limit: Schema.Int.check(Schema.isGreaterThan(0), Schema.isLessThanOrEqualTo(1_024)),
155
+ }) {}
156
+
157
+ export class RawCheckpoint extends Schema.Class<RawCheckpoint>(
158
+ "@effect-agent/storage-cloudflare/RawCheckpoint",
159
+ )({
160
+ checkpointJson: BoundedStoredText,
161
+ threadId: BoundedIdentifier,
162
+ tailDigest: BoundedStoredText,
163
+ throughSequence: CanonicalSequence,
164
+ }) {}
165
+
166
+ export class RawThreadExport extends Schema.Class<RawThreadExport>(
167
+ "@effect-agent/storage-cloudflare/RawThreadExport",
168
+ )({
169
+ thread: ThreadRow,
170
+ records: Schema.Array(RecordRow),
171
+ }) {}
172
+
173
+ type AppendError =
174
+ | DoAppendConflict
175
+ | DoFenceRejected
176
+ | DoStorageCorruptionError
177
+ | DoStorageError
178
+ | DoStorageFailpointError
179
+ | DoValueBoundExceeded;
180
+
181
+ type CheckpointError =
182
+ | DoCheckpointConflict
183
+ | DoStorageCorruptionError
184
+ | DoStorageError
185
+ | DoValueBoundExceeded;
186
+
187
+ type DoJournalFailpoint = (
188
+ location: DoStorageFailpointLocation,
189
+ ) => Effect.Effect<void, DoStorageFailpointError>;
190
+
191
+ const noFailpoint: DoJournalFailpoint = () => Effect.void;
192
+
193
+ const storageError =
194
+ (operation: string) =>
195
+ (error: SqlError): DoStorageError =>
196
+ DoStorageError.make({
197
+ cause: error,
198
+ operation,
199
+ message: error.message,
200
+ diagnostic: ThreadStoreDiagnostic.make({
201
+ causeTag: error._tag,
202
+ operation,
203
+ issueTag: error.reason._tag,
204
+ }),
205
+ });
206
+
207
+ /** Decode raw Durable Object SQLite rows against a Schema, reporting failures as typed corruption. */
208
+ export const decodeRows = Effect.fn(
209
+ <A, I>(
210
+ schema: Schema.Codec<ReadonlyArray<A>, ReadonlyArray<I>>,
211
+ table: string,
212
+ rowKey: string,
213
+ rows: unknown,
214
+ decoder: string = table,
215
+ ): Effect.Effect<ReadonlyArray<A>, DoStorageCorruptionError> =>
216
+ Schema.decodeUnknownEffect(schema)(rows).pipe(
217
+ Effect.mapError((error) =>
218
+ DoStorageCorruptionError.make({
219
+ table,
220
+ rowKey,
221
+ message: "Stored rows do not satisfy the storage schema",
222
+ diagnostic: ThreadStoreDiagnostic.make({
223
+ causeTag: error._tag,
224
+ operation: "decode storage rows",
225
+ decoder,
226
+ issueTag: error.issue._tag,
227
+ }),
228
+ }),
229
+ ),
230
+ Effect.tapError((error) =>
231
+ Effect.annotateCurrentSpan({
232
+ "storage.failure.operation": error.diagnostic?.operation,
233
+ "storage.failure.cause": error.diagnostic?.causeTag,
234
+ "storage.failure.decoder": decoder,
235
+ "storage.failure.issue": error.diagnostic?.issueTag,
236
+ }),
237
+ ),
238
+ ),
239
+ );
240
+
241
+ /** Decode exactly one raw row against a Schema, reporting failures as typed corruption. */
242
+ export const decodeSingleRow = Effect.fn(
243
+ <A, I>(
244
+ schema: Schema.Codec<ReadonlyArray<A>, ReadonlyArray<I>>,
245
+ table: string,
246
+ rowKey: string,
247
+ rows: unknown,
248
+ ): Effect.Effect<A, DoStorageCorruptionError> =>
249
+ decodeRows(schema, table, rowKey, rows).pipe(
250
+ Effect.flatMap((decoded) =>
251
+ decoded.length === 1
252
+ ? Effect.succeed(decoded[0])
253
+ : Effect.fail(
254
+ DoStorageCorruptionError.make({
255
+ table,
256
+ rowKey,
257
+ message: `Expected exactly one row but found ${decoded.length}.`,
258
+ }),
259
+ ),
260
+ ),
261
+ ),
262
+ );
263
+
264
+ /** Column inventory of the supported v3 predecessor, independent of physical column order. */
265
+ const predecessorColumns = {
266
+ effect_agent_threads: [
267
+ "thread_id",
268
+ "created_at",
269
+ "tail_sequence",
270
+ "tail_digest",
271
+ "producer_epoch",
272
+ ],
273
+ effect_agent_canonical_batches: [
274
+ "thread_id",
275
+ "batch_id",
276
+ "first_sequence",
277
+ "last_sequence",
278
+ "batch_digest",
279
+ "tail_digest",
280
+ "batch_json",
281
+ ],
282
+ effect_agent_canonical_records: ["thread_id", "sequence", "record_id", "batch_id", "record_json"],
283
+ effect_agent_checkpoints: ["thread_id", "through_sequence", "tail_digest", "checkpoint_json"],
284
+ effect_agent_submissions: [
285
+ "submission_id",
286
+ "thread_id",
287
+ "queue_sequence",
288
+ "principal",
289
+ "idempotency_key",
290
+ "agent_id",
291
+ "agent_digests_json",
292
+ "deployment_id",
293
+ "input_json",
294
+ "input_digest",
295
+ "receipt_id",
296
+ "state",
297
+ "settled_outcome",
298
+ "created_at",
299
+ "ready_at",
300
+ "input_applied_record_id",
301
+ "input_applied_sequence",
302
+ "joined_host_submission_id",
303
+ "suspended_reason_json",
304
+ "suspended_at",
305
+ "unknown_reason",
306
+ "unknown_tool_call_ids_json",
307
+ "parent_submission_id",
308
+ "parent_tool_call_id",
309
+ "admission_group",
310
+ "admission_fence_json",
311
+ ],
312
+ effect_agent_submission_ownership: [
313
+ "submission_id",
314
+ "attempt_id",
315
+ "ownership_token",
316
+ "producer_epoch",
317
+ "owner_producer_id",
318
+ "lease_expires_at",
319
+ ],
320
+ effect_agent_attempts: [
321
+ "attempt_id",
322
+ "submission_id",
323
+ "thread_id",
324
+ "owner_producer_id",
325
+ "producer_epoch",
326
+ "claimed_at",
327
+ ],
328
+ effect_agent_settlement_reservations: [
329
+ "submission_id",
330
+ "settlement_id",
331
+ "outcome",
332
+ "record_id",
333
+ "record_json",
334
+ "record_digest",
335
+ "reserved_at",
336
+ "finalized_at",
337
+ ],
338
+ effect_agent_abort_intents: [
339
+ "submission_id",
340
+ "author",
341
+ "reason",
342
+ "requested_at",
343
+ "canonical_record_id",
344
+ ],
345
+ effect_agent_approval_decisions: [
346
+ "submission_id",
347
+ "tool_call_id",
348
+ "decision",
349
+ "resolver",
350
+ "reason",
351
+ "decided_at",
352
+ ],
353
+ effect_agent_unknown_resolutions: [
354
+ "submission_id",
355
+ "tool_call_id",
356
+ "author",
357
+ "reason",
358
+ "resolution_json",
359
+ "resolved_at",
360
+ ],
361
+ effect_agent_child_reservations: [
362
+ "reservation_id",
363
+ "parent_submission_id",
364
+ "parent_tool_call_id",
365
+ "child_submission_id",
366
+ "status",
367
+ "allocation_json",
368
+ "allocation_digest",
369
+ "accounting_json",
370
+ "reserved_at",
371
+ "release_began_at",
372
+ "released_at",
373
+ ],
374
+ effect_agent_meta: ["key", "value"],
375
+ effect_agent_child_settlements: [
376
+ "parent_submission_id",
377
+ "child_submission_id",
378
+ "child_outcome",
379
+ "recorded_at",
380
+ ],
381
+ } as const;
382
+
383
+ const checkPredecessorLayout = Effect.fn("DoJournal.checkPredecessorLayout")(function* (
384
+ version: 3 | 4 | 5 | 7,
385
+ ) {
386
+ const sql = yield* SqlClient.SqlClient;
387
+
388
+ const messageColumns =
389
+ version === 3
390
+ ? predecessorColumns
391
+ : {
392
+ ...predecessorColumns,
393
+ effect_agent_submissions: [
394
+ ...predecessorColumns.effect_agent_submissions,
395
+ "worker_admission_json",
396
+ "message_admission_json",
397
+ ],
398
+ effect_agent_message_deliveries: [
399
+ "owner_thread_id",
400
+ "message_id",
401
+ "version",
402
+ "state",
403
+ "deadline_at_millis",
404
+ "record_json",
405
+ ],
406
+ };
407
+
408
+ const expectedColumns = {
409
+ ...messageColumns,
410
+ ...(version === 7
411
+ ? {
412
+ effect_agent_canonical_records: [
413
+ ...predecessorColumns.effect_agent_canonical_records,
414
+ "outstanding",
415
+ ],
416
+ }
417
+ : {}),
418
+ ...(version >= 5
419
+ ? {
420
+ effect_agent_recovery_checkpoints: [
421
+ "thread_id",
422
+ "through_sequence",
423
+ "tail_digest",
424
+ "checkpoint_json",
425
+ ],
426
+ }
427
+ : {}),
428
+ };
429
+
430
+ for (const [table, expected] of Object.entries(expectedColumns)) {
431
+ const columns = yield* decodeRows(
432
+ Schema.Array(Schema.Struct({ name: BoundedIdentifier })),
433
+ table,
434
+ "schema",
435
+ yield* sql.unsafe(`PRAGMA table_info(${table})`),
436
+ );
437
+
438
+ const names = new Set<string>(expected);
439
+
440
+ if (columns.length !== names.size || columns.some((column) => !names.has(column.name)))
441
+ return yield* DoStorageCompatibilityError.make({
442
+ actualVersion: version,
443
+ supportedVersion: CurrentDoStorageVersion,
444
+ message: `The v${version} ${table} columns do not match the supported predecessor; no upgrade was committed.`,
445
+ });
446
+ }
447
+ });
448
+
449
+ const REQUIRED_TABLES = [
450
+ "effect_agent_abort_intents",
451
+ "effect_agent_approval_decisions",
452
+ "effect_agent_attempts",
453
+ "effect_agent_canonical_batches",
454
+ "effect_agent_canonical_records",
455
+ "effect_agent_checkpoints",
456
+ "effect_agent_child_reservations",
457
+ "effect_agent_child_settlements",
458
+ "effect_agent_threads",
459
+ "effect_agent_meta",
460
+ "effect_agent_settlement_reservations",
461
+ "effect_agent_submission_ownership",
462
+ "effect_agent_submissions",
463
+ "effect_agent_unknown_resolutions",
464
+ ] as const;
465
+
466
+ /**
467
+ * Supported-predecessor or fresh storage gate (DEPLOY-008) over `effect_agent_meta` instead of
468
+ * `PRAGMA user_version` (unverified on Durable Object SQL storage; a meta table is portable
469
+ * regardless). No WAL check (Durable Object storage owns durability and confirms writes
470
+ * through output gates) and no busy timeout (a Durable Object has exactly one writer): the
471
+ * Node machinery those served has no DC analogue and is deliberately absent.
472
+ */
473
+ const ensureCurrentStorage = Effect.fn("DoJournal.ensureCurrentStorage")(function* (
474
+ sql: SqlClient.SqlClient,
475
+ failpoint: DoJournalFailpoint = noFailpoint,
476
+ maxStoredValueBytes: number,
477
+ ) {
478
+ const verifyWorkerPredecessor = Effect.fnUntraced(function* (workerContract: boolean) {
479
+ const requiredRows = yield* sql<Record<string, unknown>>`
480
+ SELECT name
481
+ FROM sqlite_master
482
+ WHERE (type = 'table'
483
+ AND name IN ${sql.in([...REQUIRED_TABLES, "effect_agent_message_deliveries", "effect_agent_recovery_checkpoints"])}
484
+ ) OR (type = 'index' AND name IN ('effect_agent_submissions_nonterminal', 'effect_agent_records_subtree', 'effect_agent_message_deliveries_pending', 'effect_agent_records_outstanding', 'effect_agent_records_call', 'effect_agent_records_run_input', 'effect_agent_records_worker_input'))
485
+ OR (${workerContract ? 1 : 0} = 1 AND name IN ('effect_agent_worker_stops', 'effect_agent_worker_starts', 'effect_agent_worker_pending', 'effect_agent_worker_execution'))
486
+ ORDER BY name
487
+ `.pipe(Effect.mapError(storageError("verify storage tables")));
488
+
489
+ const required = yield* decodeRows(
490
+ Schema.Array(DoNameRow),
491
+ "sqlite_master",
492
+ "required_tables",
493
+ requiredRows,
494
+ );
495
+
496
+ if (required.length !== REQUIRED_TABLES.length + 9 + (workerContract ? 4 : 0)) {
497
+ return yield* DoStorageCompatibilityError.make({
498
+ actualVersion: CurrentDoStorageVersion,
499
+ supportedVersion: CurrentDoStorageVersion,
500
+ message:
501
+ "The Durable Object claims the current format but is missing required tables or its nonterminal index. Retain the original store for inspection.",
502
+ });
503
+ }
504
+ });
505
+
506
+ const metaTableRows = yield* sql<Record<string, unknown>>`
507
+ SELECT name
508
+ FROM sqlite_master
509
+ WHERE type = 'table'
510
+ AND name = 'effect_agent_meta'
511
+ `.pipe(Effect.mapError(storageError("read storage version table")));
512
+
513
+ const metaTables = yield* decodeRows(
514
+ Schema.Array(DoNameRow),
515
+ "sqlite_master",
516
+ "effect_agent_meta",
517
+ metaTableRows,
518
+ );
519
+
520
+ if (metaTables.length === 0) {
521
+ const existingRows = yield* sql<Record<string, unknown>>`
522
+ SELECT name
523
+ FROM sqlite_master
524
+ WHERE type = 'table'
525
+ AND name LIKE 'effect_agent_%'
526
+ ORDER BY name
527
+ `.pipe(Effect.mapError(storageError("inspect unversioned storage")));
528
+
529
+ const existing = yield* decodeRows(
530
+ Schema.Array(DoNameRow),
531
+ "sqlite_master",
532
+ "effect_agent_%",
533
+ existingRows,
534
+ );
535
+
536
+ if (existing.length > 0) {
537
+ return yield* DoStorageCompatibilityError.make({
538
+ actualVersion: 0,
539
+ supportedVersion: CurrentDoStorageVersion,
540
+ message:
541
+ "The Durable Object contains unversioned Effect Agent tables. Refusing to mutate ambiguous stored data; retain it for inspection with its original writer.",
542
+ });
543
+ }
544
+
545
+ yield* SqliteMigrator.run({
546
+ loader: doMigrations,
547
+ // An application can share this SQL client and own its own migration history.
548
+ // Keep bookkeeping outside effect_agent_% so interrupted unversioned schemas
549
+ // still fail the ambiguity check above.
550
+ table: "effect_sql_migrations_agent_threads",
551
+ }).pipe(
552
+ // SqliteMigrator depends on the generic client supplied by this adapter. The concrete
553
+ // Durable Object client is kept at the outer Layer boundary.
554
+ Effect.provideService(SqlClient.SqlClient, sql),
555
+ Effect.mapError((error) =>
556
+ DoStorageError.make({
557
+ cause: error,
558
+ operation: "initialize current storage",
559
+ message: error.message,
560
+ }),
561
+ ),
562
+ );
563
+ } else {
564
+ const versionRows = yield* sql<Record<string, unknown>>`
565
+ SELECT value
566
+ FROM effect_agent_meta
567
+ WHERE key = 'storage_version'
568
+ `.pipe(Effect.mapError(storageError("read storage version")));
569
+
570
+ const version = yield* decodeSingleRow(
571
+ Schema.Array(DoMetaRow),
572
+ "effect_agent_meta",
573
+ "storage_version",
574
+ versionRows,
575
+ );
576
+
577
+ if (
578
+ version.value === "2" ||
579
+ version.value === "3" ||
580
+ version.value === "4" ||
581
+ version.value === "5"
582
+ ) {
583
+ yield* sql
584
+ .withTransaction(
585
+ Effect.gen(function* () {
586
+ const current = yield* sql<{
587
+ value: string;
588
+ }>`SELECT value FROM effect_agent_meta WHERE key='storage_version'`;
589
+
590
+ if (current.length === 1 && current[0].value === String(CurrentDoStorageVersion))
591
+ return;
592
+ if (
593
+ current.length !== 1 ||
594
+ (current[0].value !== "2" &&
595
+ current[0].value !== "3" &&
596
+ current[0].value !== "4" &&
597
+ current[0].value !== "5")
598
+ )
599
+ return yield* DoStorageCompatibilityError.make({
600
+ actualVersion: -1,
601
+ supportedVersion: CurrentDoStorageVersion,
602
+ message: "Storage version changed while acquiring the upgrade transaction.",
603
+ });
604
+
605
+ const required = yield* decodeRows(
606
+ Schema.Array(DoNameRow),
607
+ "sqlite_master",
608
+ "required_tables",
609
+ yield* sql`SELECT name FROM sqlite_master WHERE type='table' AND name IN ${sql.in([...REQUIRED_TABLES])}`,
610
+ );
611
+
612
+ if (required.length !== REQUIRED_TABLES.length)
613
+ return yield* DoStorageCompatibilityError.make({
614
+ actualVersion: Number(current[0].value),
615
+ supportedVersion: CurrentDoStorageVersion,
616
+ message:
617
+ "The predecessor store is missing required tables. Retain the original store for inspection; no upgrade was committed.",
618
+ });
619
+
620
+ const recoveryTables =
621
+ yield* sql`SELECT name FROM sqlite_master WHERE type='table' AND name='effect_agent_recovery_checkpoints'`;
622
+
623
+ if (recoveryTables.length !== (current[0].value === "5" ? 1 : 0))
624
+ return yield* DoStorageCompatibilityError.make({
625
+ actualVersion: Number(current[0].value),
626
+ supportedVersion: CurrentDoStorageVersion,
627
+ message:
628
+ "The predecessor recovery checkpoint storage does not match its version; refusing ambiguous data without mutation.",
629
+ });
630
+
631
+ const indexes =
632
+ yield* sql`SELECT name FROM sqlite_master WHERE name='effect_agent_submissions_nonterminal'`;
633
+
634
+ if (indexes.length !== 0)
635
+ return yield* DoStorageCompatibilityError.make({
636
+ actualVersion: Number(current[0].value),
637
+ supportedVersion: CurrentDoStorageVersion,
638
+ message:
639
+ "The predecessor already contains the nonterminal index; refusing ambiguous storage without mutation.",
640
+ });
641
+ if (current[0].value === "2") {
642
+ yield* checkV2ThreadLayout();
643
+ for (const statement of [
644
+ sql`ALTER TABLE effect_agent_submissions ADD COLUMN admission_group TEXT`,
645
+ sql`ALTER TABLE effect_agent_submissions ADD COLUMN admission_fence_json TEXT`,
646
+ sql`CREATE INDEX effect_agent_submissions_group ON effect_agent_submissions (thread_id, admission_group, state)`,
647
+ ]) {
648
+ yield* failpoint("upgrade:before-mutation");
649
+ yield* statement;
650
+ yield* failpoint("upgrade:after-mutation");
651
+ }
652
+ }
653
+ if (current[0].value === "3") yield* checkPredecessorLayout(3);
654
+ if (current[0].value === "4") yield* checkPredecessorLayout(4);
655
+ if (current[0].value === "5") yield* checkPredecessorLayout(5);
656
+ if (current[0].value === "2" || current[0].value === "3") {
657
+ yield* failpoint("upgrade:before-mutation");
658
+ yield* sql`ALTER TABLE effect_agent_submissions ADD COLUMN worker_admission_json TEXT`;
659
+ yield* failpoint("upgrade:after-mutation");
660
+ yield* failpoint("upgrade:before-mutation");
661
+ yield* sql`ALTER TABLE effect_agent_submissions ADD COLUMN message_admission_json TEXT`;
662
+ yield* failpoint("upgrade:after-mutation");
663
+ yield* failpoint("upgrade:before-mutation");
664
+ yield* createMessageDeliveryTables;
665
+ yield* failpoint("upgrade:after-mutation");
666
+ }
667
+ if (current[0].value !== "5") {
668
+ yield* failpoint("upgrade:before-mutation");
669
+ yield* createRecoveryCheckpointTable;
670
+ yield* failpoint("upgrade:after-mutation");
671
+ }
672
+ yield* failpoint("upgrade:before-mutation");
673
+ yield* createNonterminalIndex;
674
+ yield* failpoint("upgrade:after-mutation");
675
+ yield* failpoint("upgrade:before-version");
676
+ yield* createNativeReadIndexes;
677
+ yield* createMessageDeliveryPendingIndex;
678
+ yield* seedNativeReadIndexes.pipe(
679
+ Effect.catchTag("ThreadStoreError", (error) =>
680
+ DoStorageCorruptionError.make({
681
+ table: "effect_agent_canonical_records",
682
+ rowKey: "upgrade",
683
+ message: error.message,
684
+ }),
685
+ ),
686
+ );
687
+ yield* createWorkerStops;
688
+ yield* sql`UPDATE effect_agent_meta SET value='9' WHERE key='storage_version'`;
689
+ yield* failpoint("upgrade:after-version");
690
+ }),
691
+ )
692
+ .pipe(
693
+ Effect.catchTag("DoStorageFailpointError", (error) =>
694
+ DoStorageError.make({
695
+ cause: error,
696
+ operation: "upgrade storage",
697
+ message: error.message,
698
+ }),
699
+ ),
700
+ Effect.catchTag("StorageUpgradeError", (error) =>
701
+ DoStorageCorruptionError.make({
702
+ table: error.table,
703
+ rowKey: error.rowKey,
704
+ message: error.message,
705
+ }),
706
+ ),
707
+ Effect.catchTag("SchemaError", (error) =>
708
+ DoStorageCorruptionError.make({
709
+ table: "effect_agent_canonical_records",
710
+ rowKey: "upgrade",
711
+ message: error.message,
712
+ }),
713
+ ),
714
+ Effect.catchTag("SqlError", storageError("upgrade supported thread storage")),
715
+ );
716
+ } else if (version.value === "6") {
717
+ yield* sql
718
+ .withTransaction(
719
+ Effect.gen(function* () {
720
+ const current = yield* sql<{
721
+ value: string;
722
+ }>`SELECT value FROM effect_agent_meta WHERE key = 'storage_version'`;
723
+
724
+ if (current[0]?.value === "9") return;
725
+ if (current[0]?.value !== "6")
726
+ return yield* DoStorageCompatibilityError.make({
727
+ actualVersion: -1,
728
+ supportedVersion: 9,
729
+ message: "Storage version changed during native index upgrade",
730
+ });
731
+ yield* checkPredecessorLayout(5);
732
+
733
+ const requiredIndex =
734
+ yield* sql`SELECT name FROM sqlite_master WHERE type = 'index' AND name = 'effect_agent_submissions_nonterminal'`;
735
+
736
+ if (requiredIndex.length !== 1)
737
+ return yield* DoStorageCompatibilityError.make({
738
+ actualVersion: 6,
739
+ supportedVersion: 9,
740
+ message: "Predecessor storage is missing its required nonterminal index",
741
+ });
742
+ yield* failpoint("upgrade:before-mutation");
743
+ yield* createNativeReadIndexes;
744
+ yield* createMessageDeliveryPendingIndex;
745
+ yield* seedNativeReadIndexes.pipe(
746
+ Effect.catchTag("ThreadStoreError", (error) =>
747
+ DoStorageCorruptionError.make({
748
+ table: "effect_agent_canonical_records",
749
+ rowKey: "upgrade",
750
+ message: error.message,
751
+ }),
752
+ ),
753
+ );
754
+ yield* failpoint("upgrade:after-mutation");
755
+ yield* failpoint("upgrade:before-version");
756
+ yield* createWorkerStops;
757
+ yield* sql`UPDATE effect_agent_meta SET value='9' WHERE key='storage_version'`;
758
+ yield* failpoint("upgrade:after-version");
759
+ }),
760
+ )
761
+ .pipe(
762
+ Effect.mapError((error) =>
763
+ DoStorageError.make({
764
+ operation: "upgrade native indexes",
765
+ message: error.message,
766
+ cause: error,
767
+ }),
768
+ ),
769
+ );
770
+ } else if (version.value === "7") {
771
+ yield* sql
772
+ .withTransaction(
773
+ Effect.gen(function* () {
774
+ const current = yield* sql<{
775
+ value: string;
776
+ }>`SELECT value FROM effect_agent_meta WHERE key = 'storage_version'`;
777
+
778
+ if (current[0]?.value === "9") return;
779
+ if (current[0]?.value !== "7")
780
+ return yield* DoStorageCompatibilityError.make({
781
+ actualVersion: -1,
782
+ supportedVersion: 9,
783
+ message: "Storage version changed during worker stop upgrade",
784
+ });
785
+ yield* checkPredecessorLayout(7);
786
+ yield* verifyWorkerPredecessor(false);
787
+ yield* failpoint("upgrade:before-mutation");
788
+ yield* createWorkerStops;
789
+ yield* failpoint("upgrade:after-mutation");
790
+ yield* failpoint("upgrade:before-version");
791
+ yield* sql`UPDATE effect_agent_meta SET value='9' WHERE key='storage_version'`;
792
+ yield* failpoint("upgrade:after-version");
793
+ }),
794
+ )
795
+ .pipe(
796
+ Effect.mapError((cause) =>
797
+ DoStorageError.make({
798
+ operation: "upgrade worker stop",
799
+ message: "Worker stop upgrade failed",
800
+ cause,
801
+ }),
802
+ ),
803
+ );
804
+ } else if (version.value === "8") {
805
+ yield* sql
806
+ .withTransaction(
807
+ Effect.gen(function* () {
808
+ const current = yield* sql<{
809
+ value: string;
810
+ }>`SELECT value FROM effect_agent_meta WHERE key = 'storage_version'`;
811
+
812
+ if (current[0]?.value === "9") return;
813
+ if (current[0]?.value !== "8")
814
+ return yield* DoStorageCompatibilityError.make({
815
+ actualVersion: -1,
816
+ supportedVersion: 9,
817
+ message: "Storage version changed during assignment seal upgrade",
818
+ });
819
+ yield* checkPredecessorLayout(7);
820
+ yield* verifyWorkerPredecessor(true);
821
+ const columns = yield* sql`PRAGMA table_info(effect_agent_worker_stops)`;
822
+
823
+ yield* Schema.decodeUnknownEffect(
824
+ Schema.Tuple([
825
+ Schema.Struct({
826
+ cid: Schema.Literal(0),
827
+ name: Schema.Literal("thread_id"),
828
+ type: Schema.Literal("TEXT"),
829
+ notnull: Schema.Literal(1),
830
+ dflt_value: Schema.Null,
831
+ pk: Schema.Literal(1),
832
+ }),
833
+ ]),
834
+ )(columns).pipe(
835
+ Effect.mapError(() =>
836
+ DoStorageCompatibilityError.make({
837
+ actualVersion: 8,
838
+ supportedVersion: 9,
839
+ message: "Unsupported worker seal layout; no upgrade was committed",
840
+ }),
841
+ ),
842
+ );
843
+ yield* failpoint("upgrade:before-mutation");
844
+ yield* sql`ALTER TABLE effect_agent_worker_stops ADD COLUMN terminal TEXT`;
845
+ yield* failpoint("upgrade:after-mutation");
846
+ yield* failpoint("upgrade:before-version");
847
+ yield* sql`UPDATE effect_agent_meta SET value='9' WHERE key='storage_version'`;
848
+ yield* failpoint("upgrade:after-version");
849
+ }),
850
+ )
851
+ .pipe(
852
+ Effect.mapError((cause) =>
853
+ DoStorageError.make({
854
+ operation: "upgrade assignment seals",
855
+ message: "Assignment seal upgrade failed",
856
+ cause,
857
+ }),
858
+ ),
859
+ );
860
+ } else if (version.value !== String(CurrentDoStorageVersion)) {
861
+ const actualVersion = Number.parseInt(version.value, 10);
862
+
863
+ return yield* DoStorageCompatibilityError.make({
864
+ actualVersion: Number.isSafeInteger(actualVersion) ? actualVersion : -1,
865
+ supportedVersion: CurrentDoStorageVersion,
866
+ message:
867
+ `The Durable Object uses unsupported storage version ${version.value}; ` +
868
+ `this build supports exactly version ${CurrentDoStorageVersion}. ` +
869
+ "Only supported v2, v3, v4, v5, v6, v7 and v8 can be upgraded automatically. Keep the original store and use a compatible library version.",
870
+ });
871
+ }
872
+ }
873
+
874
+ yield* verifyWorkerPredecessor(true);
875
+
876
+ return makeJournal(sql, failpoint, maxStoredValueBytes);
877
+ });
878
+
879
+ const makeJournal = (
880
+ sql: SqlClient.SqlClient,
881
+ failpoint: DoJournalFailpoint,
882
+ maxStoredValueBytes: number,
883
+ ) => {
884
+ /** Typed pre-write refusal for any single value over the configured byte bound. */
885
+ const checkValueBound = (
886
+ operation: string,
887
+ value: string,
888
+ ): Effect.Effect<void, DoValueBoundExceeded> => {
889
+ const actualBytes = storedTextBytes(value);
890
+
891
+ return actualBytes > maxStoredValueBytes
892
+ ? Effect.fail(
893
+ DoValueBoundExceeded.make({
894
+ actualBytes,
895
+ maxBytes: maxStoredValueBytes,
896
+ operation,
897
+ }),
898
+ )
899
+ : Effect.void;
900
+ };
901
+
902
+ /**
903
+ * Runs one journal write transaction on the Durable Object storage-backed
904
+ * `withTransaction` (`ctx.storage.transaction()` under the hood). Within one Durable
905
+ * Object there is exactly ONE writer, so the Node `BEGIN IMMEDIATE` + busy-retry +
906
+ * `SqliteWriteContention` machinery has no analogue here and is deliberately absent.
907
+ * Ownership-token and epoch checks still run INSIDE the transaction, so fencing atomicity
908
+ * (DUR-006) is preserved identically.
909
+ *
910
+ * Journal write transactions are always top level: the Durable Object client rejects
911
+ * nested transactions, so new journal operations must not wrap this helper inside another
912
+ * transaction.
913
+ */
914
+ const withWriteTransaction =
915
+ (operation: string) =>
916
+ <A, E>(effect: Effect.Effect<A, E>): Effect.Effect<A, E | DoStorageError> =>
917
+ sql.withTransaction(effect).pipe(
918
+ Effect.mapError((error) => (isSqlError(error) ? storageError(operation)(error) : error)),
919
+ Effect.withSpan("DoJournal.withWriteTransaction", { attributes: { operation } }),
920
+ );
921
+
922
+ const materialize = Effect.fn("DoJournal.materialize")(function* (
923
+ threadId: string,
924
+ createdAt: string,
925
+ emptyTailDigest: string,
926
+ producerEpoch: ProducerEpoch,
927
+ ): Effect.fn.Return<
928
+ void,
929
+ DoFenceRejected | DoStorageCorruptionError | DoStorageError | DoValueBoundExceeded
930
+ > {
931
+ if (threadId.length > MAX_IDENTIFIER_LENGTH) {
932
+ return yield* DoStorageError.make({
933
+ operation: "materialize thread",
934
+ message: "Thread identity exceeds the Durable Object storage bounds.",
935
+ });
936
+ }
937
+ yield* checkValueBound("materialize thread", emptyTailDigest);
938
+ yield* withWriteTransaction("materialize transaction")(
939
+ Effect.gen(function* () {
940
+ const existingRows = yield* sql<Record<string, unknown>>`
941
+ SELECT
942
+ thread_id,
943
+ created_at,
944
+ tail_sequence,
945
+ tail_digest,
946
+ producer_epoch
947
+ FROM effect_agent_threads
948
+ WHERE thread_id = ${threadId}
949
+ `.pipe(Effect.mapError(storageError("read materialized thread")));
950
+
951
+ const existing = yield* decodeRows(
952
+ Schema.Array(ThreadRow),
953
+ "effect_agent_threads",
954
+ threadId,
955
+ existingRows,
956
+ );
957
+
958
+ if (existing.length > 1) {
959
+ return yield* DoStorageCorruptionError.make({
960
+ table: "effect_agent_threads",
961
+ rowKey: threadId,
962
+ message: "A thread primary key returned more than one row.",
963
+ });
964
+ }
965
+ if (existing.length === 0) {
966
+ yield* sql`
967
+ INSERT INTO effect_agent_threads (
968
+ thread_id,
969
+ created_at,
970
+ tail_sequence,
971
+ tail_digest,
972
+ producer_epoch
973
+ ) VALUES (
974
+ ${threadId},
975
+ ${createdAt},
976
+ 0,
977
+ ${emptyTailDigest},
978
+ ${producerEpoch}
979
+ )
980
+ `.pipe(Effect.mapError(storageError("materialize thread")));
981
+
982
+ return;
983
+ }
984
+ if (producerEpoch < existing[0].producer_epoch) {
985
+ return yield* DoFenceRejected.make({
986
+ producerEpoch,
987
+ actualEpoch: existing[0].producer_epoch,
988
+ message: `Producer epoch ${producerEpoch} is stale; current epoch is ${existing[0].producer_epoch}.`,
989
+ });
990
+ }
991
+ if (producerEpoch > existing[0].producer_epoch) {
992
+ yield* sql`
993
+ UPDATE effect_agent_threads
994
+ SET producer_epoch = ${producerEpoch}
995
+ WHERE thread_id = ${threadId}
996
+ `.pipe(Effect.mapError(storageError("advance materialization epoch")));
997
+ }
998
+ }),
999
+ );
1000
+ });
1001
+
1002
+ const getThread = Effect.fn("DoJournal.getThread")(function* (threadId: string) {
1003
+ const rows = yield* sql<Record<string, unknown>>`
1004
+ SELECT
1005
+ thread_id,
1006
+ created_at,
1007
+ tail_sequence,
1008
+ tail_digest,
1009
+ producer_epoch
1010
+ FROM effect_agent_threads
1011
+ WHERE thread_id = ${threadId}
1012
+ `.pipe(Effect.mapError(storageError("read thread")));
1013
+
1014
+ return yield* decodeRows(Schema.Array(ThreadRow), "effect_agent_threads", threadId, rows);
1015
+ });
1016
+
1017
+ const append = Effect.fn("DoJournal.append")(function* (
1018
+ request: RawAppendRequest,
1019
+ ): Effect.fn.Return<RawAppendResult, AppendError> {
1020
+ if (
1021
+ request.threadId.length > MAX_IDENTIFIER_LENGTH ||
1022
+ request.batchId.length > MAX_IDENTIFIER_LENGTH ||
1023
+ request.records.some((record) => record.recordId.length > MAX_IDENTIFIER_LENGTH)
1024
+ ) {
1025
+ return yield* DoStorageError.make({
1026
+ operation: "append canonical batch",
1027
+ message: "Canonical identifiers exceed the Durable Object storage bounds.",
1028
+ });
1029
+ }
1030
+ // The platform's ~2 MB per-value limit, enforced typed BEFORE any write (plan §1.2).
1031
+ yield* checkValueBound("append canonical batch", request.batchJson);
1032
+ yield* checkValueBound("append canonical batch", request.batchDigest);
1033
+ yield* checkValueBound("append canonical batch", request.tailDigest);
1034
+ yield* Effect.forEach(
1035
+ request.records,
1036
+ (record) => checkValueBound("append canonical record", record.recordJson),
1037
+ { discard: true },
1038
+ );
1039
+
1040
+ return yield* withWriteTransaction("append transaction")(
1041
+ Effect.gen(function* () {
1042
+ const recordIds = request.records.map((record) => record.recordId);
1043
+
1044
+ if (new Set(recordIds).size !== recordIds.length) {
1045
+ return yield* DoAppendConflict.make({
1046
+ message: `Batch ${request.batchId} contains duplicate canonical record IDs.`,
1047
+ reason: "record-identity",
1048
+ });
1049
+ }
1050
+
1051
+ const threadRows = yield* sql<Record<string, unknown>>`
1052
+ SELECT
1053
+ thread_id,
1054
+ created_at,
1055
+ tail_sequence,
1056
+ tail_digest,
1057
+ producer_epoch
1058
+ FROM effect_agent_threads
1059
+ WHERE thread_id = ${request.threadId}
1060
+ `.pipe(Effect.mapError(storageError("read append tail")));
1061
+
1062
+ const thread = yield* decodeSingleRow(
1063
+ Schema.Array(ThreadRow),
1064
+ "effect_agent_threads",
1065
+ request.threadId,
1066
+ threadRows,
1067
+ );
1068
+
1069
+ if (request.producerEpoch !== thread.producer_epoch) {
1070
+ return yield* DoFenceRejected.make({
1071
+ producerEpoch: request.producerEpoch,
1072
+ actualEpoch: thread.producer_epoch,
1073
+ message: `Producer epoch ${request.producerEpoch} is not the current epoch ${thread.producer_epoch}.`,
1074
+ });
1075
+ }
1076
+
1077
+ const batchRows = yield* sql<Record<string, unknown>>`
1078
+ SELECT
1079
+ thread_id,
1080
+ batch_id,
1081
+ first_sequence,
1082
+ last_sequence,
1083
+ batch_digest,
1084
+ tail_digest,
1085
+ batch_json
1086
+ FROM effect_agent_canonical_batches
1087
+ WHERE thread_id = ${request.threadId}
1088
+ AND batch_id = ${request.batchId}
1089
+ `.pipe(Effect.mapError(storageError("read idempotent batch")));
1090
+
1091
+ const batches = yield* decodeRows(
1092
+ Schema.Array(BatchRow),
1093
+ "effect_agent_canonical_batches",
1094
+ `${request.threadId}/${request.batchId}`,
1095
+ batchRows,
1096
+ );
1097
+
1098
+ if (batches.length > 1) {
1099
+ return yield* DoStorageCorruptionError.make({
1100
+ table: "effect_agent_canonical_batches",
1101
+ rowKey: `${request.threadId}/${request.batchId}`,
1102
+ message: "A canonical batch primary key returned more than one row.",
1103
+ });
1104
+ }
1105
+ if (batches.length === 1) {
1106
+ const existing = batches[0];
1107
+
1108
+ if (existing.batch_digest !== request.batchDigest) {
1109
+ return yield* DoAppendConflict.make({
1110
+ message: `Batch ${request.batchId} already exists with different canonical content.`,
1111
+ reason: "batch-digest",
1112
+ });
1113
+ }
1114
+
1115
+ return RawAppendResult.make({
1116
+ firstSequence: existing.first_sequence,
1117
+ lastSequence: existing.last_sequence,
1118
+ replayed: true,
1119
+ tailDigest: existing.tail_digest,
1120
+ });
1121
+ }
1122
+
1123
+ if (
1124
+ request.expectedTailSequence !== thread.tail_sequence ||
1125
+ request.expectedTailDigest !== thread.tail_digest
1126
+ ) {
1127
+ return yield* DoAppendConflict.make({
1128
+ message:
1129
+ `Expected tail ${request.expectedTailSequence}/${request.expectedTailDigest} ` +
1130
+ `but found ${thread.tail_sequence}/${thread.tail_digest}.`,
1131
+ reason: "tail",
1132
+ actualTailSequence: thread.tail_sequence,
1133
+ actualTailDigest: thread.tail_digest,
1134
+ });
1135
+ }
1136
+ if (thread.tail_sequence + request.records.length > MAX_RECORDS_PER_THREAD) {
1137
+ return yield* DoStorageError.make({
1138
+ operation: "append canonical batch",
1139
+ message: `Thread record limit ${MAX_RECORDS_PER_THREAD} would be exceeded.`,
1140
+ });
1141
+ }
1142
+
1143
+ // Chunked to respect the Durable Object platform's 100-bound-parameter statement
1144
+ // limit: a batch may carry up to 256 records.
1145
+ const existingRecords: Array<RecordRow> = [];
1146
+
1147
+ for (const chunk of chunked(recordIds, MAX_BOUND_PARAMETERS - 10)) {
1148
+ const existingRecordRows = yield* sql<Record<string, unknown>>`
1149
+ SELECT
1150
+ thread_id,
1151
+ sequence,
1152
+ record_id,
1153
+ batch_id,
1154
+ record_json
1155
+ FROM effect_agent_canonical_records
1156
+ WHERE thread_id = ${request.threadId}
1157
+ AND record_id IN ${sql.in([...chunk])}
1158
+ ORDER BY sequence
1159
+ `.pipe(Effect.mapError(storageError("check canonical record identities")));
1160
+
1161
+ existingRecords.push(
1162
+ ...(yield* decodeRows(
1163
+ Schema.Array(RecordRow),
1164
+ "effect_agent_canonical_records",
1165
+ `${request.threadId}/record_ids`,
1166
+ existingRecordRows,
1167
+ )),
1168
+ );
1169
+ }
1170
+ if (existingRecords.length > 0) {
1171
+ return yield* DoAppendConflict.make({
1172
+ message: `Canonical record ID ${existingRecords[0].record_id} already exists.`,
1173
+ reason: "record-identity",
1174
+ });
1175
+ }
1176
+
1177
+ const firstSequence = yield* Schema.decodeEffect(CanonicalSequence)(
1178
+ thread.tail_sequence + 1,
1179
+ ).pipe(
1180
+ Effect.mapError((error) =>
1181
+ DoStorageError.make({
1182
+ cause: error,
1183
+ operation: "append canonical batch",
1184
+ message: error.message,
1185
+ }),
1186
+ ),
1187
+ );
1188
+
1189
+ const lastSequence = yield* Schema.decodeEffect(CanonicalSequence)(
1190
+ firstSequence + request.records.length - 1,
1191
+ ).pipe(
1192
+ Effect.mapError((error) =>
1193
+ DoStorageError.make({
1194
+ cause: error,
1195
+ operation: "append canonical batch",
1196
+ message: error.message,
1197
+ }),
1198
+ ),
1199
+ );
1200
+
1201
+ yield* sql`
1202
+ INSERT INTO effect_agent_canonical_batches (
1203
+ thread_id,
1204
+ batch_id,
1205
+ first_sequence,
1206
+ last_sequence,
1207
+ batch_digest,
1208
+ tail_digest,
1209
+ batch_json
1210
+ ) VALUES (
1211
+ ${request.threadId},
1212
+ ${request.batchId},
1213
+ ${firstSequence},
1214
+ ${lastSequence},
1215
+ ${request.batchDigest},
1216
+ ${request.tailDigest},
1217
+ ${request.batchJson}
1218
+ )
1219
+ `.pipe(Effect.mapError(storageError("insert canonical batch")));
1220
+ yield* failpoint("append:after-batch-insert");
1221
+
1222
+ yield* Effect.forEach(
1223
+ request.records,
1224
+ (record, index) =>
1225
+ Effect.gen(function* () {
1226
+ yield* sql`
1227
+ INSERT INTO effect_agent_canonical_records (
1228
+ thread_id,
1229
+ sequence,
1230
+ record_id,
1231
+ batch_id,
1232
+ record_json
1233
+ ) VALUES (
1234
+ ${request.threadId},
1235
+ ${firstSequence + index},
1236
+ ${record.recordId},
1237
+ ${request.batchId},
1238
+ ${record.recordJson}
1239
+ )
1240
+ `.pipe(Effect.mapError(storageError("insert canonical record")));
1241
+
1242
+ const canonical = yield* Schema.decodeEffect(Schema.fromJsonString(CanonicalRecord))(
1243
+ record.recordJson,
1244
+ ).pipe(
1245
+ Effect.mapError((error) =>
1246
+ DoStorageCorruptionError.make({
1247
+ table: "effect_agent_canonical_records",
1248
+ rowKey: record.recordId,
1249
+ message: error.message,
1250
+ }),
1251
+ ),
1252
+ );
1253
+
1254
+ yield* indexCanonicalRecord(request.threadId, canonical).pipe(
1255
+ Effect.provideService(SqlClient.SqlClient, sql),
1256
+ Effect.mapError(storageError("index canonical record")),
1257
+ );
1258
+ yield* failpoint("append:after-record-insert");
1259
+ }),
1260
+ { discard: true },
1261
+ );
1262
+
1263
+ yield* sql`
1264
+ UPDATE effect_agent_threads
1265
+ SET
1266
+ tail_sequence = ${lastSequence},
1267
+ tail_digest = ${request.tailDigest},
1268
+ producer_epoch = ${request.producerEpoch}
1269
+ WHERE thread_id = ${request.threadId}
1270
+ `.pipe(Effect.mapError(storageError("advance thread tail")));
1271
+ yield* failpoint("append:after-tail-update");
1272
+
1273
+ return RawAppendResult.make({
1274
+ firstSequence,
1275
+ lastSequence,
1276
+ replayed: false,
1277
+ tailDigest: request.tailDigest,
1278
+ });
1279
+ }),
1280
+ );
1281
+ });
1282
+
1283
+ const read = Effect.fnUntraced(function* (request: RawReadRequest) {
1284
+ // Capture membership without retaining payloads. Append-only sequences keep each later
1285
+ // payload query inside this snapshot, even when new records arrive during consumption.
1286
+ const planRows = yield* sql<Record<string, unknown>>`
1287
+ SELECT
1288
+ sequence,
1289
+ length(CAST(record_json AS BLOB)) AS record_json_bytes
1290
+ FROM effect_agent_canonical_records
1291
+ WHERE thread_id = ${request.threadId}
1292
+ AND sequence > ${request.fromSequenceExclusive}
1293
+ ORDER BY sequence
1294
+ LIMIT ${request.limit}
1295
+ `.pipe(Effect.mapError(storageError("read canonical records")));
1296
+
1297
+ const plan = yield* decodeRows(
1298
+ Schema.Array(ReadPlanRow),
1299
+ "effect_agent_canonical_records",
1300
+ `${request.threadId}>${request.fromSequenceExclusive}`,
1301
+ planRows,
1302
+ "ReadPlanRow",
1303
+ );
1304
+
1305
+ const mismatch = () =>
1306
+ DoStorageCorruptionError.make({
1307
+ table: "effect_agent_canonical_records",
1308
+ rowKey: `${request.threadId}>${request.fromSequenceExclusive}`,
1309
+ message: "Canonical read membership, sequence, or payload size changed from its read plan.",
1310
+ });
1311
+
1312
+ if (plan.length > request.limit) return yield* mismatch();
1313
+
1314
+ const pages: Array<ReadPage> = [];
1315
+ let page: ReadPage | undefined;
1316
+ let pageBytes = 0;
1317
+ let previousSequence = request.fromSequenceExclusive;
1318
+
1319
+ for (const row of plan) {
1320
+ if (row.sequence !== previousSequence + 1) return yield* mismatch();
1321
+ previousSequence = row.sequence;
1322
+ if (page === undefined || pageBytes + row.record_json_bytes > MAX_READ_PAGE_JSON_BYTES) {
1323
+ page = [row];
1324
+ pages.push(page);
1325
+ pageBytes = row.record_json_bytes;
1326
+ } else {
1327
+ page.push(row);
1328
+ pageBytes += row.record_json_bytes;
1329
+ }
1330
+ }
1331
+
1332
+ const readPage = Effect.fn("DoJournal.readPage")(function* (page: ReadPage) {
1333
+ const rows = yield* sql<Record<string, unknown>>`
1334
+ SELECT thread_id, sequence, record_id, batch_id, record_json
1335
+ FROM effect_agent_canonical_records
1336
+ WHERE thread_id = ${request.threadId}
1337
+ AND sequence >= ${page[0].sequence}
1338
+ AND sequence <= ${page[page.length - 1].sequence}
1339
+ ORDER BY sequence
1340
+ `.pipe(Effect.mapError(storageError("read canonical records")));
1341
+
1342
+ const decoded = yield* decodeRows(
1343
+ Schema.Array(RecordRow),
1344
+ "effect_agent_canonical_records",
1345
+ `${request.threadId}/${page[0].sequence}`,
1346
+ rows,
1347
+ "RecordRow",
1348
+ );
1349
+
1350
+ if (
1351
+ decoded.length !== page.length ||
1352
+ decoded.some(
1353
+ (row, index) =>
1354
+ row.thread_id !== request.threadId ||
1355
+ row.sequence !== page[index].sequence ||
1356
+ storedTextBytes(row.record_json) !== page[index].record_json_bytes,
1357
+ )
1358
+ ) {
1359
+ return yield* mismatch();
1360
+ }
1361
+
1362
+ return decoded;
1363
+ });
1364
+
1365
+ return {
1366
+ count: plan.length,
1367
+ records: Stream.fromIterable(pages).pipe(
1368
+ Stream.flatMap((page) => Stream.fromIterableEffect(readPage(page))),
1369
+ ),
1370
+ };
1371
+ });
1372
+
1373
+ const exportThread = Effect.fn("DoJournal.exportThread")(function* (threadId: string) {
1374
+ return yield* sql
1375
+ .withTransaction(
1376
+ Effect.gen(function* () {
1377
+ const threadRows = yield* sql<Record<string, unknown>>`
1378
+ SELECT
1379
+ thread_id,
1380
+ created_at,
1381
+ tail_sequence,
1382
+ tail_digest,
1383
+ producer_epoch
1384
+ FROM effect_agent_threads
1385
+ WHERE thread_id = ${threadId}
1386
+ `.pipe(Effect.mapError(storageError("export thread")));
1387
+
1388
+ const thread = yield* decodeSingleRow(
1389
+ Schema.Array(ThreadRow),
1390
+ "effect_agent_threads",
1391
+ threadId,
1392
+ threadRows,
1393
+ );
1394
+
1395
+ yield* failpoint("export:after-thread-read");
1396
+
1397
+ if (thread.tail_sequence > MAX_RECORDS_PER_THREAD)
1398
+ return yield* DoStorageError.make({
1399
+ operation: "export thread",
1400
+ message: "The thread exceeds the current export record limit.",
1401
+ });
1402
+ const records: Array<RecordRow> = [];
1403
+ let afterSequence = ZERO_SEQUENCE;
1404
+
1405
+ while (afterSequence < thread.tail_sequence) {
1406
+ const limit = Math.min(1_024, thread.tail_sequence - afterSequence);
1407
+
1408
+ const request = RawReadRequest.make({
1409
+ threadId,
1410
+ fromSequenceExclusive: afterSequence,
1411
+ limit,
1412
+ });
1413
+
1414
+ const plan = yield* read(request);
1415
+ const page = yield* Stream.runCollect(plan.records);
1416
+
1417
+ if (
1418
+ page.length !== limit ||
1419
+ page.some((record, index) => record.sequence !== afterSequence + index + 1)
1420
+ ) {
1421
+ return yield* DoStorageCorruptionError.make({
1422
+ table: "effect_agent_canonical_records",
1423
+ rowKey: threadId,
1424
+ message:
1425
+ "The exported canonical prefix is not contiguous through its captured tail.",
1426
+ });
1427
+ }
1428
+ records.push(...page);
1429
+ afterSequence = page[page.length - 1].sequence;
1430
+ }
1431
+
1432
+ const beyondTail =
1433
+ yield* sql`SELECT sequence FROM effect_agent_canonical_records WHERE thread_id=${threadId} AND sequence > ${thread.tail_sequence} LIMIT 1`.pipe(
1434
+ Effect.mapError(storageError("verify export tail")),
1435
+ );
1436
+
1437
+ if (beyondTail.length !== 0)
1438
+ return yield* DoStorageCorruptionError.make({
1439
+ table: "effect_agent_canonical_records",
1440
+ rowKey: threadId,
1441
+ message: "Canonical records exist beyond the captured thread tail.",
1442
+ });
1443
+
1444
+ return RawThreadExport.make({ thread, records });
1445
+ }),
1446
+ )
1447
+ .pipe(
1448
+ Effect.catchTag("SqlError", (error) =>
1449
+ Effect.fail(storageError("export transaction")(error)),
1450
+ ),
1451
+ );
1452
+ });
1453
+
1454
+ const saveCheckpoint = Effect.fn("DoJournal.saveCheckpoint")(function* (
1455
+ checkpoint: RawCheckpoint,
1456
+ ): Effect.fn.Return<void, CheckpointError> {
1457
+ if (checkpoint.threadId.length > MAX_IDENTIFIER_LENGTH) {
1458
+ return yield* DoStorageError.make({
1459
+ operation: "save checkpoint",
1460
+ message: "Checkpoint identity exceeds the Durable Object storage bounds.",
1461
+ });
1462
+ }
1463
+ yield* checkValueBound("save checkpoint", checkpoint.checkpointJson);
1464
+ yield* withWriteTransaction("checkpoint transaction")(
1465
+ Effect.gen(function* () {
1466
+ const threadRows = yield* sql<Record<string, unknown>>`
1467
+ SELECT
1468
+ thread_id,
1469
+ created_at,
1470
+ tail_sequence,
1471
+ tail_digest,
1472
+ producer_epoch
1473
+ FROM effect_agent_threads
1474
+ WHERE thread_id = ${checkpoint.threadId}
1475
+ `.pipe(Effect.mapError(storageError("read checkpoint tail")));
1476
+
1477
+ const thread = yield* decodeSingleRow(
1478
+ Schema.Array(ThreadRow),
1479
+ "effect_agent_threads",
1480
+ checkpoint.threadId,
1481
+ threadRows,
1482
+ );
1483
+
1484
+ if (checkpoint.throughSequence > thread.tail_sequence) {
1485
+ return yield* DoCheckpointConflict.make({
1486
+ message:
1487
+ `Checkpoint sequence ${checkpoint.throughSequence} is after canonical tail ` +
1488
+ `${thread.tail_sequence}.`,
1489
+ });
1490
+ }
1491
+
1492
+ const checkpointRows = yield* sql<Record<string, unknown>>`
1493
+ SELECT
1494
+ thread_id,
1495
+ through_sequence,
1496
+ tail_digest,
1497
+ checkpoint_json
1498
+ FROM effect_agent_checkpoints
1499
+ WHERE thread_id = ${checkpoint.threadId}
1500
+ AND through_sequence = ${checkpoint.throughSequence}
1501
+ `.pipe(Effect.mapError(storageError("read idempotent checkpoint")));
1502
+
1503
+ const existing = yield* decodeRows(
1504
+ Schema.Array(CheckpointRow),
1505
+ "effect_agent_checkpoints",
1506
+ `${checkpoint.threadId}/${checkpoint.throughSequence}`,
1507
+ checkpointRows,
1508
+ );
1509
+
1510
+ if (existing.length > 1) {
1511
+ return yield* DoStorageCorruptionError.make({
1512
+ table: "effect_agent_checkpoints",
1513
+ rowKey: `${checkpoint.threadId}/${checkpoint.throughSequence}`,
1514
+ message: "A checkpoint primary key returned more than one row.",
1515
+ });
1516
+ }
1517
+ if (existing.length === 1) {
1518
+ if (
1519
+ existing[0].tail_digest !== checkpoint.tailDigest ||
1520
+ existing[0].checkpoint_json !== checkpoint.checkpointJson
1521
+ ) {
1522
+ return yield* DoCheckpointConflict.make({
1523
+ message: "A different checkpoint already exists at this canonical sequence.",
1524
+ });
1525
+ }
1526
+
1527
+ return;
1528
+ }
1529
+
1530
+ yield* sql`
1531
+ INSERT INTO effect_agent_checkpoints (
1532
+ thread_id,
1533
+ through_sequence,
1534
+ tail_digest,
1535
+ checkpoint_json
1536
+ ) VALUES (
1537
+ ${checkpoint.threadId},
1538
+ ${checkpoint.throughSequence},
1539
+ ${checkpoint.tailDigest},
1540
+ ${checkpoint.checkpointJson}
1541
+ )
1542
+ `.pipe(Effect.mapError(storageError("insert checkpoint")));
1543
+ }),
1544
+ );
1545
+ });
1546
+
1547
+ const saveRecoveryCheckpoint = Effect.fn("DoJournal.saveRecoveryCheckpoint")(function* (
1548
+ request: SaveRecoveryCheckpointRequest,
1549
+ checkpointJson: string,
1550
+ ) {
1551
+ const { checkpoint } = request;
1552
+
1553
+ if (checkpoint.threadId.length > MAX_IDENTIFIER_LENGTH) {
1554
+ return yield* DoStorageError.make({
1555
+ operation: "save recovery checkpoint",
1556
+ message: "Checkpoint identity exceeds the Durable Object storage bounds.",
1557
+ });
1558
+ }
1559
+ yield* checkValueBound("save recovery checkpoint", checkpointJson);
1560
+ // Keep injected waits outside the storage-backed transaction callback.
1561
+ yield* failpoint("save-recovery-checkpoint:before");
1562
+ yield* withWriteTransaction("recovery checkpoint transaction")(
1563
+ Effect.gen(function* () {
1564
+ const threads = yield* getThread(checkpoint.threadId);
1565
+ const thread = threads[0];
1566
+
1567
+ if (thread === undefined)
1568
+ return yield* ThreadNotMaterialized.make({ threadId: checkpoint.threadId });
1569
+ if (request.producerEpoch !== thread.producer_epoch)
1570
+ return yield* FenceRejected.make({
1571
+ threadId: checkpoint.threadId,
1572
+ actualEpoch: thread.producer_epoch,
1573
+ attemptedEpoch: request.producerEpoch,
1574
+ });
1575
+ if (checkpoint.throughSequence > thread.tail_sequence)
1576
+ return yield* CheckpointRejected.make({
1577
+ threadId: checkpoint.threadId,
1578
+ reason: "ahead-of-tail",
1579
+ });
1580
+
1581
+ const digests =
1582
+ checkpoint.throughSequence === 0
1583
+ ? [EMPTY_TAIL_DIGEST]
1584
+ : yield* getTailDigestAt(checkpoint.threadId, checkpoint.throughSequence);
1585
+
1586
+ if (digests.length !== 1 || digests[0] !== checkpoint.tailDigest)
1587
+ return yield* CheckpointRejected.make({
1588
+ threadId: checkpoint.threadId,
1589
+ reason: "digest-mismatch",
1590
+ });
1591
+
1592
+ yield* sql`
1593
+ INSERT INTO effect_agent_recovery_checkpoints (thread_id, through_sequence, tail_digest, checkpoint_json)
1594
+ VALUES (${checkpoint.threadId}, ${checkpoint.throughSequence}, ${checkpoint.tailDigest}, ${checkpointJson})
1595
+ ON CONFLICT (thread_id) DO UPDATE SET
1596
+ through_sequence = excluded.through_sequence,
1597
+ tail_digest = excluded.tail_digest,
1598
+ checkpoint_json = excluded.checkpoint_json
1599
+ WHERE excluded.through_sequence >= effect_agent_recovery_checkpoints.through_sequence
1600
+ `.pipe(Effect.mapError(storageError("save recovery checkpoint")));
1601
+ }),
1602
+ );
1603
+ yield* failpoint("save-recovery-checkpoint:after");
1604
+ });
1605
+
1606
+ const loadRecoveryCheckpoint = Effect.fn("DoJournal.loadRecoveryCheckpoint")(function* (
1607
+ threadId: string,
1608
+ ) {
1609
+ const rows = yield* sql<Record<string, unknown>>`
1610
+ SELECT thread_id, through_sequence, tail_digest, checkpoint_json
1611
+ FROM effect_agent_recovery_checkpoints
1612
+ WHERE thread_id = ${threadId}
1613
+ `.pipe(Effect.mapError(storageError("load recovery checkpoint")));
1614
+
1615
+ return yield* decodeRows(
1616
+ Schema.Array(CheckpointRow),
1617
+ "effect_agent_recovery_checkpoints",
1618
+ threadId,
1619
+ rows,
1620
+ );
1621
+ });
1622
+
1623
+ const loadCheckpoint = Effect.fn("DoJournal.loadCheckpoint")(function* (
1624
+ threadId: string,
1625
+ atOrBeforeSequence: CanonicalSequence,
1626
+ ) {
1627
+ const rows = yield* sql<Record<string, unknown>>`
1628
+ SELECT
1629
+ thread_id,
1630
+ through_sequence,
1631
+ tail_digest,
1632
+ checkpoint_json
1633
+ FROM effect_agent_checkpoints
1634
+ WHERE thread_id = ${threadId}
1635
+ AND through_sequence <= ${atOrBeforeSequence}
1636
+ ORDER BY through_sequence DESC
1637
+ LIMIT 1
1638
+ `.pipe(Effect.mapError(storageError("load checkpoint")));
1639
+
1640
+ return yield* decodeRows(
1641
+ Schema.Array(CheckpointRow),
1642
+ "effect_agent_checkpoints",
1643
+ `${threadId}<=${atOrBeforeSequence}`,
1644
+ rows,
1645
+ );
1646
+ });
1647
+
1648
+ const getTailDigestAt = Effect.fn("DoJournal.getTailDigestAt")(function* (
1649
+ threadId: string,
1650
+ sequence: CanonicalSequence,
1651
+ ) {
1652
+ if (sequence === 0) {
1653
+ const threads = yield* getThread(threadId);
1654
+
1655
+ return threads.length === 0
1656
+ ? []
1657
+ : [threads[0].tail_sequence === 0 ? threads[0].tail_digest : undefined].filter(
1658
+ (value): value is string => value !== undefined,
1659
+ );
1660
+ }
1661
+
1662
+ const rows = yield* sql<Record<string, unknown>>`
1663
+ SELECT
1664
+ thread_id,
1665
+ batch_id,
1666
+ first_sequence,
1667
+ last_sequence,
1668
+ batch_digest,
1669
+ tail_digest,
1670
+ batch_json
1671
+ FROM effect_agent_canonical_batches
1672
+ WHERE thread_id = ${threadId}
1673
+ AND last_sequence = ${sequence}
1674
+ `.pipe(Effect.mapError(storageError("read canonical digest at sequence")));
1675
+
1676
+ const batches = yield* decodeRows(
1677
+ Schema.Array(BatchRow),
1678
+ "effect_agent_canonical_batches",
1679
+ `${threadId}/${sequence}`,
1680
+ rows,
1681
+ );
1682
+
1683
+ return batches.map((batch) => batch.tail_digest);
1684
+ });
1685
+
1686
+ const scanStoredPayloads = Effect.fn("DoJournal.scanStoredPayloads")(function* () {
1687
+ return yield* sql
1688
+ .withTransaction(
1689
+ Effect.gen(function* () {
1690
+ const threads = yield* sql<Record<string, unknown>>`
1691
+ SELECT
1692
+ thread_id,
1693
+ created_at,
1694
+ tail_sequence,
1695
+ tail_digest,
1696
+ producer_epoch
1697
+ FROM effect_agent_threads
1698
+ ORDER BY thread_id
1699
+ `.pipe(Effect.mapError(storageError("scan threads")));
1700
+
1701
+ const batches = yield* sql<Record<string, unknown>>`
1702
+ SELECT
1703
+ thread_id,
1704
+ batch_id,
1705
+ first_sequence,
1706
+ last_sequence,
1707
+ batch_digest,
1708
+ tail_digest,
1709
+ batch_json
1710
+ FROM effect_agent_canonical_batches
1711
+ ORDER BY thread_id, first_sequence
1712
+ `.pipe(Effect.mapError(storageError("scan canonical batches")));
1713
+
1714
+ const records = yield* sql<Record<string, unknown>>`
1715
+ SELECT
1716
+ thread_id,
1717
+ sequence,
1718
+ record_id,
1719
+ batch_id,
1720
+ record_json
1721
+ FROM effect_agent_canonical_records
1722
+ ORDER BY thread_id, sequence
1723
+ `.pipe(Effect.mapError(storageError("scan canonical records")));
1724
+
1725
+ const checkpoints = yield* sql<Record<string, unknown>>`
1726
+ SELECT
1727
+ thread_id,
1728
+ through_sequence,
1729
+ tail_digest,
1730
+ checkpoint_json
1731
+ FROM effect_agent_checkpoints
1732
+ ORDER BY thread_id, through_sequence
1733
+ `.pipe(Effect.mapError(storageError("scan checkpoints")));
1734
+
1735
+ return {
1736
+ threads: yield* decodeRows(
1737
+ Schema.Array(ThreadRow),
1738
+ "effect_agent_threads",
1739
+ "startup_scan",
1740
+ threads,
1741
+ ),
1742
+ batches: yield* decodeRows(
1743
+ Schema.Array(BatchRow),
1744
+ "effect_agent_canonical_batches",
1745
+ "startup_scan",
1746
+ batches,
1747
+ ),
1748
+ records: yield* decodeRows(
1749
+ Schema.Array(RecordRow),
1750
+ "effect_agent_canonical_records",
1751
+ "startup_scan",
1752
+ records,
1753
+ ),
1754
+ checkpoints: yield* decodeRows(
1755
+ Schema.Array(CheckpointRow),
1756
+ "effect_agent_checkpoints",
1757
+ "startup_scan",
1758
+ checkpoints,
1759
+ ),
1760
+ };
1761
+ }),
1762
+ )
1763
+ .pipe(
1764
+ Effect.catchTag("SqlError", (error) =>
1765
+ Effect.fail(storageError("startup scan transaction")(error)),
1766
+ ),
1767
+ );
1768
+ });
1769
+
1770
+ return {
1771
+ append,
1772
+ checkValueBound,
1773
+ exportThread,
1774
+ getThread,
1775
+ getTailDigestAt,
1776
+ loadCheckpoint,
1777
+ loadRecoveryCheckpoint,
1778
+ saveRecoveryCheckpoint,
1779
+ materialize,
1780
+ read,
1781
+ saveCheckpoint,
1782
+ scanStoredPayloads,
1783
+ withWriteTransaction,
1784
+ } as const;
1785
+ };
1786
+
1787
+ export type DoJournal = ReturnType<typeof makeJournal>;
1788
+
1789
+ export const initializeDoJournal = ensureCurrentStorage;