@yielded/agent-storage-cloudflare 0.1.0-beta.166

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 (77) hide show
  1. package/LICENSE +21 -0
  2. package/dist/DoMemoryStore.d.mts +30 -0
  3. package/dist/DoMemoryStore.mjs +66 -0
  4. package/dist/DoMemoryStore.mjs.map +1 -0
  5. package/dist/DoMessageDeliveryStore.d.mts +17 -0
  6. package/dist/DoMessageDeliveryStore.mjs +30 -0
  7. package/dist/DoMessageDeliveryStore.mjs.map +1 -0
  8. package/dist/DoScheduleStore.d.mts +36 -0
  9. package/dist/DoScheduleStore.mjs +388 -0
  10. package/dist/DoScheduleStore.mjs.map +1 -0
  11. package/dist/DoStorageConfig.d.mts +45 -0
  12. package/dist/DoStorageConfig.mjs +52 -0
  13. package/dist/DoStorageConfig.mjs.map +1 -0
  14. package/dist/DoStorageError-CGuAfSwF.d.mts +101 -0
  15. package/dist/DoStorageError.d.mts +2 -0
  16. package/dist/DoStorageError.mjs +167 -0
  17. package/dist/DoStorageError.mjs.map +1 -0
  18. package/dist/DoStorageFailpoint.d.mts +17 -0
  19. package/dist/DoStorageFailpoint.mjs +14 -0
  20. package/dist/DoStorageFailpoint.mjs.map +1 -0
  21. package/dist/DoStorageFailpointTesting.d.mts +24 -0
  22. package/dist/DoStorageFailpointTesting.mjs +22 -0
  23. package/dist/DoStorageFailpointTesting.mjs.map +1 -0
  24. package/dist/DoStorageVersion-iNSyi3cJ.d.mts +12 -0
  25. package/dist/DoStorageVersion.d.mts +2 -0
  26. package/dist/DoStorageVersion.mjs +8 -0
  27. package/dist/DoStorageVersion.mjs.map +1 -0
  28. package/dist/DoSubmissionLedger.d.mts +23 -0
  29. package/dist/DoSubmissionLedger.mjs +1979 -0
  30. package/dist/DoSubmissionLedger.mjs.map +1 -0
  31. package/dist/DoSubscriptionStore.d.mts +25 -0
  32. package/dist/DoSubscriptionStore.mjs +186 -0
  33. package/dist/DoSubscriptionStore.mjs.map +1 -0
  34. package/dist/DoThreadStore-D_83OjCH.d.mts +72 -0
  35. package/dist/DoThreadStore.d.mts +2 -0
  36. package/dist/DoThreadStore.mjs +529 -0
  37. package/dist/DoThreadStore.mjs.map +1 -0
  38. package/dist/MemoryProtocol.d.mts +38160 -0
  39. package/dist/MemoryProtocol.mjs +219 -0
  40. package/dist/MemoryProtocol.mjs.map +1 -0
  41. package/dist/PortProtocol.d.mts +7726 -0
  42. package/dist/PortProtocol.mjs +234 -0
  43. package/dist/PortProtocol.mjs.map +1 -0
  44. package/dist/PortRouting.d.mts +97 -0
  45. package/dist/PortRouting.mjs +544 -0
  46. package/dist/PortRouting.mjs.map +1 -0
  47. package/dist/do-journal-DUhjZkOf.mjs +1352 -0
  48. package/dist/do-journal-DUhjZkOf.mjs.map +1 -0
  49. package/dist/index.d.mts +14 -0
  50. package/dist/index.mjs +14 -0
  51. package/dist/migrations-DtKz_Gxr.mjs +306 -0
  52. package/dist/migrations-DtKz_Gxr.mjs.map +1 -0
  53. package/dist/owned-state-DHm2aRXx.mjs +119 -0
  54. package/dist/owned-state-DHm2aRXx.mjs.map +1 -0
  55. package/dist/rolldown-runtime-D7D4PA-g.mjs +13 -0
  56. package/package.json +1 -0
  57. package/src/DoMemoryStore.ts +73 -0
  58. package/src/DoMessageDeliveryStore.ts +39 -0
  59. package/src/DoScheduleStore.ts +622 -0
  60. package/src/DoStorageConfig.ts +53 -0
  61. package/src/DoStorageError.ts +180 -0
  62. package/src/DoStorageFailpoint.ts +20 -0
  63. package/src/DoStorageFailpointTesting.ts +41 -0
  64. package/src/DoStorageVersion.ts +2 -0
  65. package/src/DoSubmissionLedger.ts +4027 -0
  66. package/src/DoSubscriptionStore.ts +327 -0
  67. package/src/DoThreadStore.ts +1121 -0
  68. package/src/MemoryProtocol.ts +355 -0
  69. package/src/PortProtocol.ts +436 -0
  70. package/src/PortRouting.ts +1464 -0
  71. package/src/index.ts +13 -0
  72. package/src/internal/do-journal.ts +2282 -0
  73. package/src/internal/message-delivery-schema.ts +24 -0
  74. package/src/internal/migrations.ts +304 -0
  75. package/src/internal/owned-state.ts +228 -0
  76. package/src/internal/recovery-checkpoint-schema.ts +17 -0
  77. package/src/internal/storage-span.ts +44 -0
@@ -0,0 +1,2282 @@
1
+ import { SqliteMigrator } from "@effect/sql-sqlite-do";
2
+ import {
3
+ makeSqlLifecyclePublication,
4
+ type SqlLifecycleRetainMany,
5
+ SqlLifecycleSource,
6
+ SqlLifecycleRetainer,
7
+ } from "@yielded/agent-storage-sql/sql-lifecycle-publication";
8
+ import { createMessageDeliveryPendingIndex } from "@yielded/agent-storage-sql/sql-message-delivery-store";
9
+ import { SqlStorageProgress } from "@yielded/agent-storage-sql/sql-storage-progress";
10
+ import { checkV2ThreadLayout } from "@yielded/agent-storage-sql/sql-storage-v2-upgrade";
11
+ import {
12
+ createNativeReadIndexes,
13
+ seedNativeReadIndexes,
14
+ indexCanonicalRecord,
15
+ canonicalRecordOutstanding,
16
+ } from "@yielded/agent-storage-sql/sql-thread-native-reads";
17
+ import { EMPTY_TAIL_DIGEST } from "@yielded/agent/digest";
18
+ import { ThreadId } from "@yielded/agent/identifiers";
19
+ import {
20
+ LifecyclePublicationFact,
21
+ LifecyclePublicationError,
22
+ } from "@yielded/agent/lifecycle-publication";
23
+ import { CanonicalRecord, CanonicalSequence, ProducerEpoch } from "@yielded/agent/records";
24
+ import { SqlStorageOwner } from "@yielded/agent/sql-memory-store";
25
+ import {
26
+ MAX_THREAD_EXPORT_RECORDS,
27
+ CheckpointRejected,
28
+ FenceRejected,
29
+ ThreadNotMaterialized,
30
+ ThreadStoreDiagnostic,
31
+ type SaveRecoveryCheckpointRequest,
32
+ } from "@yielded/agent/thread-store";
33
+ import { Cause, Clock, Effect, Option, Schema, Stream } from "effect";
34
+ import * as SqlClient from "effect/sql/SqlClient";
35
+ import { SqlError } from "effect/sql/SqlError";
36
+
37
+ import {
38
+ type DoStorageFailpointError,
39
+ DoAppendConflict,
40
+ DoCheckpointConflict,
41
+ DoFenceRejected,
42
+ DoStorageCompatibilityError,
43
+ DoStorageCorruptionError,
44
+ DoStorageError,
45
+ DoValueBoundExceeded,
46
+ type DoStorageFailpointLocation,
47
+ } from "../DoStorageError.ts";
48
+ import { createMessageDeliveryTables } from "./message-delivery-schema.ts";
49
+ import {
50
+ CurrentDoStorageVersion,
51
+ createNonterminalIndex,
52
+ createWorkerStops,
53
+ doMigrations,
54
+ } from "./migrations.ts";
55
+ import { ownedState, ownedRows, type OwnedState } from "./owned-state.ts";
56
+ import { createRecoveryCheckpointTable } from "./recovery-checkpoint-schema.ts";
57
+ import {
58
+ isAppendContention,
59
+ annotateStorageError,
60
+ storageResult,
61
+ withStorageSpan,
62
+ } from "./storage-span.ts";
63
+
64
+ /**
65
+ * Static schema ceiling for stored text columns. Writes are bounded in BYTES by the
66
+ * configured `maxStoredValueBytes` (always ≤ 2,000,000); UTF-8 byte length is never smaller
67
+ * than UTF-16 string length, so any value that passed the byte bound also passes this
68
+ * decode-side character ceiling.
69
+ */
70
+ const BoundedStoredText = Schema.String.check(Schema.isMaxLength(2_000_000));
71
+ const BoundedIdentifier = Schema.NonEmptyString.check(Schema.isMaxLength(1024));
72
+ const MAX_RECORDS_PER_THREAD = MAX_THREAD_EXPORT_RECORDS;
73
+ const ZERO_SEQUENCE = Schema.decodeSync(CanonicalSequence)(0);
74
+ const MAX_IDENTIFIER_LENGTH = 1_024;
75
+ const MAX_READ_PAGE_JSON_BYTES = 4 * 1024 * 1024;
76
+ // A shared isolate budget permits multi-page hydration without multiplying its
77
+ // retained payload by the number of resident Durable Object instances.
78
+ const MAX_RECORD_CACHE_JSON_BYTES = 8 * 1024 * 1024;
79
+ const MAX_RECORD_CACHE_ENTRIES = 4_096;
80
+ /** Durable Object SQL storage allows at most 100 bound parameters per statement. */
81
+ const MAX_BOUND_PARAMETERS = 100;
82
+ const isSqlError = Schema.is(SqlError);
83
+
84
+ const storedTextBytes = (value: string): number => new TextEncoder().encode(value).byteLength;
85
+
86
+ const chunked = <A>(values: ReadonlyArray<A>, size: number): Array<ReadonlyArray<A>> => {
87
+ const chunks: Array<ReadonlyArray<A>> = [];
88
+
89
+ for (let index = 0; index < values.length; index += size) {
90
+ chunks.push(values.slice(index, index + size));
91
+ }
92
+
93
+ return chunks;
94
+ };
95
+
96
+ class DoMetaRow extends Schema.Class<DoMetaRow>("DoMetaRow")({
97
+ value: Schema.NonEmptyString.check(Schema.isMaxLength(128)),
98
+ }) {}
99
+
100
+ class DoNameRow extends Schema.Class<DoNameRow>("DoNameRow")({
101
+ name: BoundedIdentifier,
102
+ }) {}
103
+
104
+ class ThreadRow extends Schema.Class<ThreadRow>("ThreadRow")({
105
+ thread_id: BoundedIdentifier,
106
+ created_at: Schema.NonEmptyString.check(Schema.isMaxLength(128)),
107
+ producer_epoch: ProducerEpoch,
108
+ tail_digest: BoundedStoredText,
109
+ tail_sequence: CanonicalSequence,
110
+ }) {}
111
+
112
+ const threadRows = ownedRows(
113
+ ThreadRow,
114
+ "effect_agent_threads",
115
+ (row) => row.thread_id,
116
+ "thread_id",
117
+ );
118
+
119
+ class BatchRow extends Schema.Class<BatchRow>("BatchRow")({
120
+ batch_digest: BoundedStoredText,
121
+ batch_id: BoundedIdentifier,
122
+ batch_json: BoundedStoredText,
123
+ thread_id: BoundedIdentifier,
124
+ first_sequence: CanonicalSequence,
125
+ last_sequence: CanonicalSequence,
126
+ tail_digest: BoundedStoredText,
127
+ }) {}
128
+
129
+ class RecordRow extends Schema.Class<RecordRow>("RecordRow")({
130
+ batch_id: BoundedIdentifier,
131
+ thread_id: BoundedIdentifier,
132
+ record_id: BoundedIdentifier,
133
+ record_json: BoundedStoredText,
134
+ sequence: CanonicalSequence,
135
+ }) {}
136
+
137
+ interface RecordCacheEntry {
138
+ readonly row: RecordRow;
139
+ readonly bytes: number;
140
+ readonly evict: () => void;
141
+ }
142
+
143
+ // Entries retain only their local row map, never a storage owner or incarnation.
144
+ const isolateRecords = new Map<RecordCacheEntry, true>();
145
+ let isolateRecordBytes = 0;
146
+
147
+ const releaseRecord = (entry: RecordCacheEntry) => {
148
+ if (!isolateRecords.delete(entry)) return;
149
+ isolateRecordBytes -= entry.bytes;
150
+ entry.evict();
151
+ };
152
+
153
+ const recordCaches = new WeakMap<OwnedState, ReturnType<typeof makeRecordCache>>();
154
+
155
+ const makeRecordCache = () => {
156
+ const records = new Map<string, RecordCacheEntry>();
157
+ const key = (thread: string, sequence: number) => JSON.stringify([thread, sequence]);
158
+
159
+ return {
160
+ clear: () => {
161
+ for (const entry of records.values()) releaseRecord(entry);
162
+ },
163
+ get: (thread: string, sequence: number) => records.get(key(thread, sequence))?.row,
164
+ prefix: (thread: string, through: number): ReadonlyArray<RecordRow> | undefined => {
165
+ const prefix: Array<RecordRow> = [];
166
+
167
+ for (let sequence = 1; sequence <= through; sequence++) {
168
+ const row = records.get(key(thread, sequence));
169
+
170
+ if (row === undefined) return undefined;
171
+ prefix.push(row.row);
172
+ }
173
+
174
+ return prefix;
175
+ },
176
+ put: (row: RecordRow) => {
177
+ const id = key(row.thread_id, row.sequence);
178
+ const prior = records.get(id);
179
+
180
+ if (prior?.row === row) return;
181
+ const size = storedTextBytes(row.record_json);
182
+
183
+ if (prior !== undefined) releaseRecord(prior);
184
+
185
+ const entry: RecordCacheEntry = {
186
+ row,
187
+ bytes: size,
188
+ evict: () => records.delete(id),
189
+ };
190
+
191
+ records.set(id, entry);
192
+ isolateRecords.set(entry, true);
193
+ isolateRecordBytes += size;
194
+ while (
195
+ isolateRecordBytes > MAX_RECORD_CACHE_JSON_BYTES ||
196
+ isolateRecords.size > MAX_RECORD_CACHE_ENTRIES
197
+ ) {
198
+ const oldest = isolateRecords.keys().next().value;
199
+
200
+ if (oldest === undefined) break;
201
+ releaseRecord(oldest);
202
+ }
203
+ },
204
+ };
205
+ };
206
+
207
+ const ReadPlanRow = Schema.Struct({
208
+ sequence: CanonicalSequence,
209
+ record_json_bytes: Schema.Natural.check(Schema.isLessThanOrEqualTo(MAX_READ_PAGE_JSON_BYTES)),
210
+ });
211
+
212
+ type ReadPage = [typeof ReadPlanRow.Type, ...Array<typeof ReadPlanRow.Type>];
213
+
214
+ class CheckpointRow extends Schema.Class<CheckpointRow>("CheckpointRow")({
215
+ checkpoint_json: BoundedStoredText,
216
+ thread_id: BoundedIdentifier,
217
+ tail_digest: BoundedStoredText,
218
+ through_sequence: CanonicalSequence,
219
+ }) {}
220
+
221
+ const recoveryRows = ownedRows(
222
+ CheckpointRow,
223
+ "effect_agent_recovery_checkpoints",
224
+ (row) => row.thread_id,
225
+ "thread_id",
226
+ );
227
+
228
+ const LifecycleCursorRow = Schema.Struct({
229
+ thread_id: BoundedIdentifier,
230
+ through_sequence: CanonicalSequence,
231
+ });
232
+
233
+ const lifecycleCursorRows = ownedRows(
234
+ LifecycleCursorRow,
235
+ "effect_agent_lifecycle_cursors",
236
+ (row) => row.thread_id,
237
+ "thread_id",
238
+ );
239
+
240
+ const initializedLifecycleSources = new WeakSet<OwnedState>();
241
+
242
+ export class RawRecord extends Schema.Class<RawRecord>(
243
+ "@effect-agent/storage-cloudflare/RawRecord",
244
+ )({
245
+ recordId: BoundedIdentifier,
246
+ recordJson: BoundedStoredText,
247
+ }) {}
248
+
249
+ export class RawAppendRequest extends Schema.Class<RawAppendRequest>(
250
+ "@effect-agent/storage-cloudflare/RawAppendRequest",
251
+ )({
252
+ batchDigest: BoundedStoredText,
253
+ batchId: BoundedIdentifier,
254
+ batchJson: BoundedStoredText,
255
+ threadId: BoundedIdentifier,
256
+ expectedTailDigest: BoundedStoredText,
257
+ expectedTailSequence: CanonicalSequence,
258
+ producerEpoch: ProducerEpoch,
259
+ records: Schema.NonEmptyArray(RawRecord).check(Schema.isMaxLength(256)),
260
+ tailDigest: BoundedStoredText,
261
+ }) {}
262
+
263
+ export class RawAppendResult extends Schema.Class<RawAppendResult>(
264
+ "@effect-agent/storage-cloudflare/RawAppendResult",
265
+ )({
266
+ firstSequence: CanonicalSequence,
267
+ lastSequence: CanonicalSequence,
268
+ replayed: Schema.Boolean,
269
+ tailDigest: BoundedStoredText,
270
+ }) {}
271
+
272
+ export class RawReadRequest extends Schema.Class<RawReadRequest>(
273
+ "@effect-agent/storage-cloudflare/RawReadRequest",
274
+ )({
275
+ threadId: BoundedIdentifier,
276
+ fromSequenceExclusive: CanonicalSequence,
277
+ limit: Schema.Int.check(Schema.isGreaterThan(0), Schema.isLessThanOrEqualTo(1_024)),
278
+ }) {}
279
+
280
+ export class RawCheckpoint extends Schema.Class<RawCheckpoint>(
281
+ "@effect-agent/storage-cloudflare/RawCheckpoint",
282
+ )({
283
+ checkpointJson: BoundedStoredText,
284
+ threadId: BoundedIdentifier,
285
+ tailDigest: BoundedStoredText,
286
+ throughSequence: CanonicalSequence,
287
+ }) {}
288
+
289
+ export class RawThreadExport extends Schema.Class<RawThreadExport>(
290
+ "@effect-agent/storage-cloudflare/RawThreadExport",
291
+ )({
292
+ thread: ThreadRow,
293
+ records: Schema.Array(RecordRow),
294
+ }) {}
295
+
296
+ type AppendError =
297
+ | DoAppendConflict
298
+ | DoFenceRejected
299
+ | DoStorageCorruptionError
300
+ | DoStorageError
301
+ | DoStorageFailpointError
302
+ | DoValueBoundExceeded;
303
+
304
+ type CheckpointError =
305
+ | DoCheckpointConflict
306
+ | DoStorageCorruptionError
307
+ | DoStorageError
308
+ | DoValueBoundExceeded;
309
+
310
+ type DoJournalFailpoint = (
311
+ location: DoStorageFailpointLocation,
312
+ ) => Effect.Effect<void, DoStorageFailpointError>;
313
+
314
+ const noFailpoint: DoJournalFailpoint = () => Effect.void;
315
+
316
+ const storageError =
317
+ (operation: string) =>
318
+ (error: SqlError): DoStorageError =>
319
+ DoStorageError.make({
320
+ cause: error,
321
+ operation,
322
+ message: error.message,
323
+ diagnostic: ThreadStoreDiagnostic.make({
324
+ causeTag: error._tag,
325
+ operation,
326
+ issueTag: error.reason._tag,
327
+ }),
328
+ });
329
+
330
+ /** Decode raw Durable Object SQLite rows against a Schema, reporting failures as typed corruption. */
331
+ export const decodeRows = Effect.fn(
332
+ <A, I>(
333
+ schema: Schema.Codec<ReadonlyArray<A>, ReadonlyArray<I>>,
334
+ table: string,
335
+ rowKey: string,
336
+ rows: unknown,
337
+ decoder: string = table,
338
+ ): Effect.Effect<ReadonlyArray<A>, DoStorageCorruptionError> =>
339
+ Schema.decodeUnknownEffect(schema)(rows).pipe(
340
+ Effect.mapError((error) =>
341
+ DoStorageCorruptionError.make({
342
+ table,
343
+ rowKey,
344
+ message: "Stored rows do not satisfy the storage schema",
345
+ diagnostic: ThreadStoreDiagnostic.make({
346
+ causeTag: error._tag,
347
+ operation: "decode storage rows",
348
+ decoder,
349
+ issueTag: error.issue._tag,
350
+ }),
351
+ }),
352
+ ),
353
+ Effect.tapError((error) =>
354
+ Effect.annotateCurrentSpan({
355
+ "storage.failure.operation": error.diagnostic?.operation,
356
+ "storage.failure.cause": error.diagnostic?.causeTag,
357
+ "storage.failure.decoder": decoder,
358
+ "storage.failure.issue": error.diagnostic?.issueTag,
359
+ }),
360
+ ),
361
+ ),
362
+ );
363
+
364
+ /** Decode exactly one raw row against a Schema, reporting failures as typed corruption. */
365
+ export const decodeSingleRow = Effect.fn(
366
+ <A, I>(
367
+ schema: Schema.Codec<ReadonlyArray<A>, ReadonlyArray<I>>,
368
+ table: string,
369
+ rowKey: string,
370
+ rows: unknown,
371
+ ): Effect.Effect<A, DoStorageCorruptionError> =>
372
+ decodeRows(schema, table, rowKey, rows).pipe(
373
+ Effect.flatMap((decoded) =>
374
+ decoded.length === 1
375
+ ? Effect.succeed(decoded[0])
376
+ : Effect.fail(
377
+ DoStorageCorruptionError.make({
378
+ table,
379
+ rowKey,
380
+ message: `Expected exactly one row but found ${decoded.length}.`,
381
+ }),
382
+ ),
383
+ ),
384
+ ),
385
+ );
386
+
387
+ /** Column inventory of the supported v3 predecessor, independent of physical column order. */
388
+ const predecessorColumns = {
389
+ effect_agent_threads: [
390
+ "thread_id",
391
+ "created_at",
392
+ "tail_sequence",
393
+ "tail_digest",
394
+ "producer_epoch",
395
+ ],
396
+ effect_agent_canonical_batches: [
397
+ "thread_id",
398
+ "batch_id",
399
+ "first_sequence",
400
+ "last_sequence",
401
+ "batch_digest",
402
+ "tail_digest",
403
+ "batch_json",
404
+ ],
405
+ effect_agent_canonical_records: ["thread_id", "sequence", "record_id", "batch_id", "record_json"],
406
+ effect_agent_checkpoints: ["thread_id", "through_sequence", "tail_digest", "checkpoint_json"],
407
+ effect_agent_submissions: [
408
+ "submission_id",
409
+ "thread_id",
410
+ "queue_sequence",
411
+ "principal",
412
+ "idempotency_key",
413
+ "agent_id",
414
+ "agent_digests_json",
415
+ "deployment_id",
416
+ "input_json",
417
+ "input_digest",
418
+ "receipt_id",
419
+ "state",
420
+ "settled_outcome",
421
+ "created_at",
422
+ "ready_at",
423
+ "input_applied_record_id",
424
+ "input_applied_sequence",
425
+ "joined_host_submission_id",
426
+ "suspended_reason_json",
427
+ "suspended_at",
428
+ "unknown_reason",
429
+ "unknown_tool_call_ids_json",
430
+ "parent_submission_id",
431
+ "parent_tool_call_id",
432
+ "admission_group",
433
+ "admission_fence_json",
434
+ ],
435
+ effect_agent_submission_ownership: [
436
+ "submission_id",
437
+ "attempt_id",
438
+ "ownership_token",
439
+ "producer_epoch",
440
+ "owner_producer_id",
441
+ "lease_expires_at",
442
+ ],
443
+ effect_agent_attempts: [
444
+ "attempt_id",
445
+ "submission_id",
446
+ "thread_id",
447
+ "owner_producer_id",
448
+ "producer_epoch",
449
+ "claimed_at",
450
+ ],
451
+ effect_agent_settlement_reservations: [
452
+ "submission_id",
453
+ "settlement_id",
454
+ "outcome",
455
+ "record_id",
456
+ "record_json",
457
+ "record_digest",
458
+ "reserved_at",
459
+ "finalized_at",
460
+ ],
461
+ effect_agent_abort_intents: [
462
+ "submission_id",
463
+ "author",
464
+ "reason",
465
+ "requested_at",
466
+ "canonical_record_id",
467
+ ],
468
+ effect_agent_approval_decisions: [
469
+ "submission_id",
470
+ "tool_call_id",
471
+ "decision",
472
+ "resolver",
473
+ "reason",
474
+ "decided_at",
475
+ ],
476
+ effect_agent_unknown_resolutions: [
477
+ "submission_id",
478
+ "tool_call_id",
479
+ "author",
480
+ "reason",
481
+ "resolution_json",
482
+ "resolved_at",
483
+ ],
484
+ effect_agent_child_reservations: [
485
+ "reservation_id",
486
+ "parent_submission_id",
487
+ "parent_tool_call_id",
488
+ "child_submission_id",
489
+ "status",
490
+ "allocation_json",
491
+ "allocation_digest",
492
+ "accounting_json",
493
+ "reserved_at",
494
+ "release_began_at",
495
+ "released_at",
496
+ ],
497
+ effect_agent_meta: ["key", "value"],
498
+ effect_agent_child_settlements: [
499
+ "parent_submission_id",
500
+ "child_submission_id",
501
+ "child_outcome",
502
+ "recorded_at",
503
+ ],
504
+ } as const;
505
+
506
+ const checkPredecessorLayout = Effect.fn("DoJournal.checkPredecessorLayout")(function* (
507
+ version: 3 | 4 | 5 | 7,
508
+ ) {
509
+ const sql = (yield* SqlClient.SqlClient).withoutTransforms();
510
+
511
+ const messageColumns =
512
+ version === 3
513
+ ? predecessorColumns
514
+ : {
515
+ ...predecessorColumns,
516
+ effect_agent_submissions: [
517
+ ...predecessorColumns.effect_agent_submissions,
518
+ "worker_admission_json",
519
+ "message_admission_json",
520
+ ],
521
+ effect_agent_message_deliveries: [
522
+ "owner_thread_id",
523
+ "message_id",
524
+ "version",
525
+ "state",
526
+ "deadline_at_millis",
527
+ "record_json",
528
+ ],
529
+ };
530
+
531
+ const expectedColumns = {
532
+ ...messageColumns,
533
+ ...(version === 7
534
+ ? {
535
+ effect_agent_canonical_records: [
536
+ ...predecessorColumns.effect_agent_canonical_records,
537
+ "outstanding",
538
+ ],
539
+ }
540
+ : {}),
541
+ ...(version >= 5
542
+ ? {
543
+ effect_agent_recovery_checkpoints: [
544
+ "thread_id",
545
+ "through_sequence",
546
+ "tail_digest",
547
+ "checkpoint_json",
548
+ ],
549
+ }
550
+ : {}),
551
+ };
552
+
553
+ for (const [table, expected] of Object.entries(expectedColumns)) {
554
+ const columns = yield* decodeRows(
555
+ Schema.Array(Schema.Struct({ name: BoundedIdentifier })),
556
+ table,
557
+ "schema",
558
+ yield* sql.unsafe(`PRAGMA table_info(${table})`),
559
+ );
560
+
561
+ const names = new Set<string>(expected);
562
+
563
+ if (columns.length !== names.size || columns.some((column) => !names.has(column.name)))
564
+ return yield* DoStorageCompatibilityError.make({
565
+ actualVersion: version,
566
+ supportedVersion: CurrentDoStorageVersion,
567
+ message: `The v${version} ${table} columns do not match the supported predecessor; no upgrade was committed.`,
568
+ });
569
+ }
570
+ });
571
+
572
+ const REQUIRED_TABLES = [
573
+ "effect_agent_abort_intents",
574
+ "effect_agent_approval_decisions",
575
+ "effect_agent_attempts",
576
+ "effect_agent_canonical_batches",
577
+ "effect_agent_canonical_records",
578
+ "effect_agent_checkpoints",
579
+ "effect_agent_child_reservations",
580
+ "effect_agent_child_settlements",
581
+ "effect_agent_threads",
582
+ "effect_agent_meta",
583
+ "effect_agent_settlement_reservations",
584
+ "effect_agent_submission_ownership",
585
+ "effect_agent_submissions",
586
+ "effect_agent_unknown_resolutions",
587
+ ] as const;
588
+
589
+ /**
590
+ * Supported-predecessor or fresh storage gate (DEPLOY-008) over `effect_agent_meta` instead of
591
+ * `PRAGMA user_version` (unverified on Durable Object SQL storage; a meta table is portable
592
+ * regardless). No WAL check (Durable Object storage owns durability and confirms writes
593
+ * through output gates) and no busy timeout (a Durable Object has exactly one writer): the
594
+ * Node machinery those served has no DC analogue and is deliberately absent.
595
+ */
596
+ const ensureCurrentStorage = Effect.fn("DoJournal.ensureCurrentStorage")(function* (
597
+ sql: SqlClient.SqlClient,
598
+ failpoint: DoJournalFailpoint = noFailpoint,
599
+ maxStoredValueBytes: number,
600
+ ) {
601
+ const verifyWorkerPredecessor = Effect.fnUntraced(function* (workerContract: boolean) {
602
+ const requiredRows = yield* sql<Record<string, unknown>>`
603
+ SELECT name
604
+ FROM sqlite_master
605
+ WHERE (type = 'table'
606
+ AND name IN ${sql.in([...REQUIRED_TABLES, "effect_agent_message_deliveries", "effect_agent_recovery_checkpoints"])}
607
+ ) 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'))
608
+ OR (${workerContract ? 1 : 0} = 1 AND name IN ('effect_agent_worker_stops', 'effect_agent_worker_starts', 'effect_agent_worker_pending', 'effect_agent_worker_execution'))
609
+ ORDER BY name
610
+ `.pipe(Effect.mapError(storageError("verify storage tables")));
611
+
612
+ const required = yield* decodeRows(
613
+ Schema.Array(DoNameRow),
614
+ "sqlite_master",
615
+ "required_tables",
616
+ requiredRows,
617
+ );
618
+
619
+ if (required.length !== REQUIRED_TABLES.length + 9 + (workerContract ? 4 : 0)) {
620
+ return yield* DoStorageCompatibilityError.make({
621
+ actualVersion: CurrentDoStorageVersion,
622
+ supportedVersion: CurrentDoStorageVersion,
623
+ message:
624
+ "The Durable Object claims the current format but is missing required tables or its nonterminal index. Retain the original store for inspection.",
625
+ });
626
+ }
627
+ });
628
+
629
+ const metaTableRows = yield* sql<Record<string, unknown>>`
630
+ SELECT name
631
+ FROM sqlite_master
632
+ WHERE type = 'table'
633
+ AND name = 'effect_agent_meta'
634
+ `.pipe(Effect.mapError(storageError("read storage version table")));
635
+
636
+ const metaTables = yield* decodeRows(
637
+ Schema.Array(DoNameRow),
638
+ "sqlite_master",
639
+ "effect_agent_meta",
640
+ metaTableRows,
641
+ );
642
+
643
+ if (metaTables.length === 0) {
644
+ const existingRows = yield* sql<Record<string, unknown>>`
645
+ SELECT name
646
+ FROM sqlite_master
647
+ WHERE type = 'table'
648
+ AND name LIKE 'effect_agent_%'
649
+ ORDER BY name
650
+ `.pipe(Effect.mapError(storageError("inspect unversioned storage")));
651
+
652
+ const existing = yield* decodeRows(
653
+ Schema.Array(DoNameRow),
654
+ "sqlite_master",
655
+ "effect_agent_%",
656
+ existingRows,
657
+ );
658
+
659
+ if (existing.length > 0) {
660
+ return yield* DoStorageCompatibilityError.make({
661
+ actualVersion: 0,
662
+ supportedVersion: CurrentDoStorageVersion,
663
+ message:
664
+ "The Durable Object contains unversioned Effect Agent tables. Refusing to mutate ambiguous stored data; retain it for inspection with its original writer.",
665
+ });
666
+ }
667
+
668
+ yield* SqliteMigrator.run({
669
+ loader: doMigrations,
670
+ // An application can share this SQL client and own its own migration history.
671
+ // Keep bookkeeping outside effect_agent_% so interrupted unversioned schemas
672
+ // still fail the ambiguity check above.
673
+ table: "effect_sql_migrations_agent_threads",
674
+ }).pipe(
675
+ // SqliteMigrator depends on the generic client supplied by this adapter. The concrete
676
+ // Durable Object client is kept at the outer Layer boundary.
677
+ Effect.provideService(SqlClient.SqlClient, sql),
678
+ Effect.mapError((error) =>
679
+ DoStorageError.make({
680
+ cause: error,
681
+ operation: "initialize current storage",
682
+ message: error.message,
683
+ }),
684
+ ),
685
+ );
686
+ } else {
687
+ const versionRows = yield* sql<Record<string, unknown>>`
688
+ SELECT value
689
+ FROM effect_agent_meta
690
+ WHERE key = 'storage_version'
691
+ `.pipe(Effect.mapError(storageError("read storage version")));
692
+
693
+ const version = yield* decodeSingleRow(
694
+ Schema.Array(DoMetaRow),
695
+ "effect_agent_meta",
696
+ "storage_version",
697
+ versionRows,
698
+ );
699
+
700
+ if (
701
+ version.value === "2" ||
702
+ version.value === "3" ||
703
+ version.value === "4" ||
704
+ version.value === "5"
705
+ ) {
706
+ yield* sql
707
+ .withTransaction(
708
+ Effect.gen(function* () {
709
+ const current = yield* sql<{
710
+ value: string;
711
+ }>`SELECT value FROM effect_agent_meta WHERE key='storage_version'`;
712
+
713
+ if (current.length === 1 && current[0].value === String(CurrentDoStorageVersion))
714
+ return;
715
+ if (
716
+ current.length !== 1 ||
717
+ (current[0].value !== "2" &&
718
+ current[0].value !== "3" &&
719
+ current[0].value !== "4" &&
720
+ current[0].value !== "5")
721
+ )
722
+ return yield* DoStorageCompatibilityError.make({
723
+ actualVersion: -1,
724
+ supportedVersion: CurrentDoStorageVersion,
725
+ message: "Storage version changed while acquiring the upgrade transaction.",
726
+ });
727
+
728
+ const required = yield* decodeRows(
729
+ Schema.Array(DoNameRow),
730
+ "sqlite_master",
731
+ "required_tables",
732
+ yield* sql`SELECT name FROM sqlite_master WHERE type='table' AND name IN ${sql.in([...REQUIRED_TABLES])}`,
733
+ );
734
+
735
+ if (required.length !== REQUIRED_TABLES.length)
736
+ return yield* DoStorageCompatibilityError.make({
737
+ actualVersion: Number(current[0].value),
738
+ supportedVersion: CurrentDoStorageVersion,
739
+ message:
740
+ "The predecessor store is missing required tables. Retain the original store for inspection; no upgrade was committed.",
741
+ });
742
+
743
+ const recoveryTables =
744
+ yield* sql`SELECT name FROM sqlite_master WHERE type='table' AND name='effect_agent_recovery_checkpoints'`;
745
+
746
+ if (recoveryTables.length !== (current[0].value === "5" ? 1 : 0))
747
+ return yield* DoStorageCompatibilityError.make({
748
+ actualVersion: Number(current[0].value),
749
+ supportedVersion: CurrentDoStorageVersion,
750
+ message:
751
+ "The predecessor recovery checkpoint storage does not match its version; refusing ambiguous data without mutation.",
752
+ });
753
+
754
+ const indexes =
755
+ yield* sql`SELECT name FROM sqlite_master WHERE name='effect_agent_submissions_nonterminal'`;
756
+
757
+ if (indexes.length !== 0)
758
+ return yield* DoStorageCompatibilityError.make({
759
+ actualVersion: Number(current[0].value),
760
+ supportedVersion: CurrentDoStorageVersion,
761
+ message:
762
+ "The predecessor already contains the nonterminal index; refusing ambiguous storage without mutation.",
763
+ });
764
+ if (current[0].value === "2") {
765
+ yield* checkV2ThreadLayout();
766
+ for (const statement of [
767
+ sql`ALTER TABLE effect_agent_submissions ADD COLUMN admission_group TEXT`,
768
+ sql`ALTER TABLE effect_agent_submissions ADD COLUMN admission_fence_json TEXT`,
769
+ sql`CREATE INDEX effect_agent_submissions_group ON effect_agent_submissions (thread_id, admission_group, state)`,
770
+ ]) {
771
+ yield* failpoint("upgrade:before-mutation");
772
+ yield* statement;
773
+ yield* failpoint("upgrade:after-mutation");
774
+ }
775
+ }
776
+ if (current[0].value === "3") yield* checkPredecessorLayout(3);
777
+ if (current[0].value === "4") yield* checkPredecessorLayout(4);
778
+ if (current[0].value === "5") yield* checkPredecessorLayout(5);
779
+ if (current[0].value === "2" || current[0].value === "3") {
780
+ yield* failpoint("upgrade:before-mutation");
781
+ yield* sql`ALTER TABLE effect_agent_submissions ADD COLUMN worker_admission_json TEXT`;
782
+ yield* failpoint("upgrade:after-mutation");
783
+ yield* failpoint("upgrade:before-mutation");
784
+ yield* sql`ALTER TABLE effect_agent_submissions ADD COLUMN message_admission_json TEXT`;
785
+ yield* failpoint("upgrade:after-mutation");
786
+ yield* failpoint("upgrade:before-mutation");
787
+ yield* createMessageDeliveryTables;
788
+ yield* failpoint("upgrade:after-mutation");
789
+ }
790
+ if (current[0].value !== "5") {
791
+ yield* failpoint("upgrade:before-mutation");
792
+ yield* createRecoveryCheckpointTable;
793
+ yield* failpoint("upgrade:after-mutation");
794
+ }
795
+ yield* failpoint("upgrade:before-mutation");
796
+ yield* createNonterminalIndex;
797
+ yield* failpoint("upgrade:after-mutation");
798
+ yield* failpoint("upgrade:before-version");
799
+ yield* createNativeReadIndexes();
800
+ yield* createMessageDeliveryPendingIndex();
801
+ yield* seedNativeReadIndexes.pipe(
802
+ Effect.catchTag("ThreadStoreError", (error) =>
803
+ DoStorageCorruptionError.make({
804
+ table: "effect_agent_canonical_records",
805
+ rowKey: "upgrade",
806
+ message: error.message,
807
+ }),
808
+ ),
809
+ );
810
+ yield* createWorkerStops;
811
+ yield* sql`UPDATE effect_agent_meta SET value='9' WHERE key='storage_version'`;
812
+ yield* failpoint("upgrade:after-version");
813
+ }),
814
+ )
815
+ .pipe(
816
+ Effect.catchTag("DoStorageFailpointError", (error) =>
817
+ DoStorageError.make({
818
+ cause: error,
819
+ operation: "upgrade storage",
820
+ message: error.message,
821
+ }),
822
+ ),
823
+ Effect.catchTag("StorageUpgradeError", (error) =>
824
+ DoStorageCorruptionError.make({
825
+ table: error.table,
826
+ rowKey: error.rowKey,
827
+ message: error.message,
828
+ }),
829
+ ),
830
+ Effect.catchTag("SchemaError", (error) =>
831
+ DoStorageCorruptionError.make({
832
+ table: "effect_agent_canonical_records",
833
+ rowKey: "upgrade",
834
+ message: error.message,
835
+ }),
836
+ ),
837
+ Effect.catchTag("SqlError", storageError("upgrade supported thread storage")),
838
+ );
839
+ } else if (version.value === "6") {
840
+ yield* sql
841
+ .withTransaction(
842
+ Effect.gen(function* () {
843
+ const current = yield* sql<{
844
+ value: string;
845
+ }>`SELECT value FROM effect_agent_meta WHERE key = 'storage_version'`;
846
+
847
+ if (current[0]?.value === "9") return;
848
+ if (current[0]?.value !== "6")
849
+ return yield* DoStorageCompatibilityError.make({
850
+ actualVersion: -1,
851
+ supportedVersion: 9,
852
+ message: "Storage version changed during native index upgrade",
853
+ });
854
+ yield* checkPredecessorLayout(5);
855
+
856
+ const requiredIndex =
857
+ yield* sql`SELECT name FROM sqlite_master WHERE type = 'index' AND name = 'effect_agent_submissions_nonterminal'`;
858
+
859
+ if (requiredIndex.length !== 1)
860
+ return yield* DoStorageCompatibilityError.make({
861
+ actualVersion: 6,
862
+ supportedVersion: 9,
863
+ message: "Predecessor storage is missing its required nonterminal index",
864
+ });
865
+ yield* failpoint("upgrade:before-mutation");
866
+ yield* createNativeReadIndexes();
867
+ yield* createMessageDeliveryPendingIndex();
868
+ yield* seedNativeReadIndexes.pipe(
869
+ Effect.catchTag("ThreadStoreError", (error) =>
870
+ DoStorageCorruptionError.make({
871
+ table: "effect_agent_canonical_records",
872
+ rowKey: "upgrade",
873
+ message: error.message,
874
+ }),
875
+ ),
876
+ );
877
+ yield* failpoint("upgrade:after-mutation");
878
+ yield* failpoint("upgrade:before-version");
879
+ yield* createWorkerStops;
880
+ yield* sql`UPDATE effect_agent_meta SET value='9' WHERE key='storage_version'`;
881
+ yield* failpoint("upgrade:after-version");
882
+ }),
883
+ )
884
+ .pipe(
885
+ Effect.mapError((error) =>
886
+ DoStorageError.make({
887
+ operation: "upgrade native indexes",
888
+ message: error.message,
889
+ cause: error,
890
+ }),
891
+ ),
892
+ );
893
+ } else if (version.value === "7") {
894
+ yield* sql
895
+ .withTransaction(
896
+ Effect.gen(function* () {
897
+ const current = yield* sql<{
898
+ value: string;
899
+ }>`SELECT value FROM effect_agent_meta WHERE key = 'storage_version'`;
900
+
901
+ if (current[0]?.value === "9") return;
902
+ if (current[0]?.value !== "7")
903
+ return yield* DoStorageCompatibilityError.make({
904
+ actualVersion: -1,
905
+ supportedVersion: 9,
906
+ message: "Storage version changed during worker stop upgrade",
907
+ });
908
+ yield* checkPredecessorLayout(7);
909
+ yield* verifyWorkerPredecessor(false);
910
+ yield* failpoint("upgrade:before-mutation");
911
+ yield* createWorkerStops;
912
+ yield* failpoint("upgrade:after-mutation");
913
+ yield* failpoint("upgrade:before-version");
914
+ yield* sql`UPDATE effect_agent_meta SET value='9' WHERE key='storage_version'`;
915
+ yield* failpoint("upgrade:after-version");
916
+ }),
917
+ )
918
+ .pipe(
919
+ Effect.mapError((cause) =>
920
+ DoStorageError.make({
921
+ operation: "upgrade worker stop",
922
+ message: "Worker stop upgrade failed",
923
+ cause,
924
+ }),
925
+ ),
926
+ );
927
+ } else if (version.value === "8") {
928
+ yield* sql
929
+ .withTransaction(
930
+ Effect.gen(function* () {
931
+ const current = yield* sql<{
932
+ value: string;
933
+ }>`SELECT value FROM effect_agent_meta WHERE key = 'storage_version'`;
934
+
935
+ if (current[0]?.value === "9") return;
936
+ if (current[0]?.value !== "8")
937
+ return yield* DoStorageCompatibilityError.make({
938
+ actualVersion: -1,
939
+ supportedVersion: 9,
940
+ message: "Storage version changed during assignment seal upgrade",
941
+ });
942
+ yield* checkPredecessorLayout(7);
943
+ yield* verifyWorkerPredecessor(true);
944
+ const columns = yield* sql`PRAGMA table_info(effect_agent_worker_stops)`;
945
+
946
+ yield* Schema.decodeUnknownEffect(
947
+ Schema.Tuple([
948
+ Schema.Struct({
949
+ cid: Schema.Literal(0),
950
+ name: Schema.Literal("thread_id"),
951
+ type: Schema.Literal("TEXT"),
952
+ notnull: Schema.Literal(1),
953
+ dflt_value: Schema.Null,
954
+ pk: Schema.Literal(1),
955
+ }),
956
+ ]),
957
+ )(columns).pipe(
958
+ Effect.mapError(() =>
959
+ DoStorageCompatibilityError.make({
960
+ actualVersion: 8,
961
+ supportedVersion: 9,
962
+ message: "Unsupported worker seal layout; no upgrade was committed",
963
+ }),
964
+ ),
965
+ );
966
+ yield* failpoint("upgrade:before-mutation");
967
+ yield* sql`ALTER TABLE effect_agent_worker_stops ADD COLUMN terminal TEXT`;
968
+ yield* failpoint("upgrade:after-mutation");
969
+ yield* failpoint("upgrade:before-version");
970
+ yield* sql`UPDATE effect_agent_meta SET value='9' WHERE key='storage_version'`;
971
+ yield* failpoint("upgrade:after-version");
972
+ }),
973
+ )
974
+ .pipe(
975
+ Effect.mapError((cause) =>
976
+ DoStorageError.make({
977
+ operation: "upgrade assignment seals",
978
+ message: "Assignment seal upgrade failed",
979
+ cause,
980
+ }),
981
+ ),
982
+ );
983
+ } else if (version.value !== String(CurrentDoStorageVersion)) {
984
+ const actualVersion = Number.parseInt(version.value, 10);
985
+
986
+ return yield* DoStorageCompatibilityError.make({
987
+ actualVersion: Number.isSafeInteger(actualVersion) ? actualVersion : -1,
988
+ supportedVersion: CurrentDoStorageVersion,
989
+ message:
990
+ `The Durable Object uses unsupported storage version ${version.value}; ` +
991
+ `this build supports exactly version ${CurrentDoStorageVersion}. ` +
992
+ "Only supported v2, v3, v4, v5, v6, v7 and v8 can be upgraded automatically. Keep the original store and use a compatible library version.",
993
+ });
994
+ }
995
+ }
996
+
997
+ yield* verifyWorkerPredecessor(true);
998
+
999
+ const state = yield* ownedState(sql);
1000
+ const owner = (yield* SqlStorageOwner) ?? state;
1001
+ let journal: DoJournal | undefined;
1002
+
1003
+ const lifecycle = yield* makeSqlLifecyclePublication(undefined, maxStoredValueBytes).pipe(
1004
+ Effect.provideService(SqlStorageOwner, owner),
1005
+ Effect.provideService(SqlLifecycleSource, {
1006
+ beforeRetain: (threadId) =>
1007
+ Effect.suspend(() =>
1008
+ journal === undefined
1009
+ ? Effect.fail(LifecyclePublicationError.make({ reason: "unavailable" }))
1010
+ : journal.flushCanonical(threadId),
1011
+ ),
1012
+ beforePending: Effect.suspend(() =>
1013
+ journal === undefined
1014
+ ? Effect.fail(LifecyclePublicationError.make({ reason: "unavailable" }))
1015
+ : journal.flushPublications(),
1016
+ ),
1017
+ }),
1018
+ Effect.provideService(SqlClient.SqlClient, sql),
1019
+ Effect.mapError((cause) =>
1020
+ DoStorageError.make({
1021
+ operation: "initialize lifecycle publication",
1022
+ message: "Native publication storage unavailable",
1023
+ cause,
1024
+ }),
1025
+ ),
1026
+ );
1027
+
1028
+ journal = yield* makeJournal(sql, failpoint, maxStoredValueBytes, lifecycle, state).pipe(
1029
+ Effect.provideService(SqlStorageOwner, owner),
1030
+ );
1031
+ if (lifecycle !== undefined) yield* journal.initializeLifecycleSource();
1032
+
1033
+ return journal;
1034
+ });
1035
+
1036
+ const makeJournal = (
1037
+ sql: SqlClient.SqlClient,
1038
+ failpoint: DoJournalFailpoint,
1039
+ maxStoredValueBytes: number,
1040
+ lifecycle: Effect.Success<ReturnType<typeof makeSqlLifecyclePublication>>,
1041
+ state: OwnedState,
1042
+ ) =>
1043
+ Effect.gen(function* () {
1044
+ const owner = (yield* SqlStorageOwner) ?? state;
1045
+ const progress = yield* SqlStorageProgress;
1046
+ const threads = threadRows(state, sql);
1047
+ const recovery = recoveryRows(state, sql);
1048
+ const cursors = lifecycleCursorRows(state, sql);
1049
+ let records = recordCaches.get(state);
1050
+
1051
+ if (records === undefined) {
1052
+ records = makeRecordCache();
1053
+ recordCaches.set(state, records);
1054
+ state.invalidators.add(records.clear);
1055
+ }
1056
+ const recordCache = records;
1057
+
1058
+ /** Typed pre-write refusal for any single value over the configured byte bound. */
1059
+ const checkValueBound = (
1060
+ operation: string,
1061
+ value: string,
1062
+ ): Effect.Effect<void, DoValueBoundExceeded> => {
1063
+ const actualBytes = storedTextBytes(value);
1064
+
1065
+ return actualBytes > maxStoredValueBytes
1066
+ ? Effect.fail(
1067
+ DoValueBoundExceeded.make({
1068
+ actualBytes,
1069
+ maxBytes: maxStoredValueBytes,
1070
+ operation,
1071
+ }),
1072
+ )
1073
+ : Effect.void;
1074
+ };
1075
+
1076
+ /**
1077
+ * Runs one journal write transaction on the Durable Object storage-backed
1078
+ * `withTransaction` (`ctx.storage.transaction()` under the hood). Within one Durable
1079
+ * Object there is exactly ONE writer, so the Node `BEGIN IMMEDIATE` + busy-retry +
1080
+ * `SqliteWriteContention` machinery has no analogue here and is deliberately absent.
1081
+ * Ownership-token and epoch checks still run INSIDE the transaction, so fencing atomicity
1082
+ * (DUR-006) is preserved identically.
1083
+ *
1084
+ * Journal write transactions are always top level: the Durable Object client rejects
1085
+ * nested transactions, so new journal operations must not wrap this helper inside another
1086
+ * transaction. Expected outcomes may be captured only when every such refusal precedes
1087
+ * mutation; real faults still roll back. Successful preflight reads never authorize a write.
1088
+ */
1089
+ const withWriteTransaction =
1090
+ (operation: string, expected: (error: { readonly _tag: string }) => boolean = () => false) =>
1091
+ <A, E extends { readonly _tag: string }>(
1092
+ effect: Effect.Effect<A, E>,
1093
+ ): Effect.Effect<A, E | DoStorageError> =>
1094
+ owner.transaction(storageResult(effect, expected)).pipe(
1095
+ Effect.provideService(SqlClient.SqlClient, sql),
1096
+ Effect.mapError((error) => (isSqlError(error) ? storageError(operation)(error) : error)),
1097
+ Effect.tapError(annotateStorageError),
1098
+ Effect.withSpan("DoJournal.withWriteTransaction", { attributes: { operation } }),
1099
+ Effect.flatMap(Effect.fromResult),
1100
+ );
1101
+
1102
+ const materialize = Effect.fnUntraced(
1103
+ function* (
1104
+ threadId: string,
1105
+ createdAt: string,
1106
+ emptyTailDigest: string,
1107
+ producerEpoch: ProducerEpoch,
1108
+ ): Effect.fn.Return<
1109
+ void,
1110
+ DoFenceRejected | DoStorageCorruptionError | DoStorageError | DoValueBoundExceeded
1111
+ > {
1112
+ if (threadId.length > MAX_IDENTIFIER_LENGTH) {
1113
+ return yield* DoStorageError.make({
1114
+ operation: "materialize thread",
1115
+ message: "Thread identity exceeds the Durable Object storage bounds.",
1116
+ });
1117
+ }
1118
+ yield* checkValueBound("materialize thread", emptyTailDigest);
1119
+ // Refusals and idempotent materialization need no transaction. Recheck before writes.
1120
+ const current = yield* getThread(threadId);
1121
+
1122
+ if (current.length === 1 && producerEpoch <= current[0].producer_epoch) {
1123
+ if (producerEpoch === current[0].producer_epoch) return;
1124
+
1125
+ return yield* DoFenceRejected.make({
1126
+ producerEpoch,
1127
+ actualEpoch: current[0].producer_epoch,
1128
+ message: "The materialization producer epoch is stale.",
1129
+ });
1130
+ }
1131
+ yield* withWriteTransaction(
1132
+ "materialize transaction",
1133
+ (error) => error._tag === "DoFenceRejected",
1134
+ )(
1135
+ Effect.gen(function* () {
1136
+ const existingRows = yield* getThread(threadId);
1137
+
1138
+ const existing = yield* decodeRows(
1139
+ Schema.Array(ThreadRow),
1140
+ "effect_agent_threads",
1141
+ threadId,
1142
+ existingRows,
1143
+ );
1144
+
1145
+ if (existing.length > 1) {
1146
+ return yield* DoStorageCorruptionError.make({
1147
+ table: "effect_agent_threads",
1148
+ rowKey: threadId,
1149
+ message: "A thread primary key returned more than one row.",
1150
+ });
1151
+ }
1152
+ if (existing.length === 0) {
1153
+ yield* sql`
1154
+ INSERT INTO effect_agent_threads (
1155
+ thread_id,
1156
+ created_at,
1157
+ tail_sequence,
1158
+ tail_digest,
1159
+ producer_epoch
1160
+ ) VALUES (
1161
+ ${threadId},
1162
+ ${createdAt},
1163
+ 0,
1164
+ ${emptyTailDigest},
1165
+ ${producerEpoch}
1166
+ )
1167
+ RETURNING *`.pipe(
1168
+ threads.write,
1169
+ Effect.mapError((error) =>
1170
+ error._tag === "SqlError" ? storageError("materialize thread")(error) : error,
1171
+ ),
1172
+ );
1173
+
1174
+ if (lifecycle !== undefined)
1175
+ yield* sql`INSERT INTO effect_agent_lifecycle_cursors (thread_id, through_sequence)
1176
+ VALUES (${threadId}, 0) RETURNING *`.pipe(
1177
+ cursors.write,
1178
+ Effect.mapError((error) =>
1179
+ error._tag === "SqlError"
1180
+ ? storageError("initialize lifecycle source")(error)
1181
+ : error,
1182
+ ),
1183
+ );
1184
+
1185
+ return;
1186
+ }
1187
+ if (producerEpoch < existing[0].producer_epoch) {
1188
+ return yield* DoFenceRejected.make({
1189
+ producerEpoch,
1190
+ actualEpoch: existing[0].producer_epoch,
1191
+ message: `Producer epoch ${producerEpoch} is stale; current epoch is ${existing[0].producer_epoch}.`,
1192
+ });
1193
+ }
1194
+ if (producerEpoch > existing[0].producer_epoch) {
1195
+ yield* sql`
1196
+ UPDATE effect_agent_threads
1197
+ SET producer_epoch = ${producerEpoch}
1198
+ WHERE thread_id = ${threadId}
1199
+ RETURNING *`.pipe(
1200
+ threads.write,
1201
+ Effect.mapError((error) =>
1202
+ error._tag === "SqlError"
1203
+ ? storageError("advance materialization epoch")(error)
1204
+ : error,
1205
+ ),
1206
+ );
1207
+ }
1208
+ }),
1209
+ );
1210
+ },
1211
+ withStorageSpan("DoJournal.materialize", (error) => error._tag === "DoFenceRejected"),
1212
+ );
1213
+
1214
+ const getThread = Effect.fn("DoJournal.getThread")(function* (threadId: string) {
1215
+ return (yield* threads
1216
+ .by("thread_id", threadId)
1217
+ .pipe(
1218
+ Effect.mapError((error) =>
1219
+ error._tag === "SqlError" ? storageError("read thread")(error) : error,
1220
+ ),
1221
+ )).filter((row) => row.thread_id === threadId);
1222
+ });
1223
+
1224
+ const hasRecord = Effect.fnUntraced(function* (threadId: string, recordId: string) {
1225
+ const thread = (yield* getThread(threadId))[0];
1226
+ const prefix = recordCache.prefix(threadId, thread?.tail_sequence ?? 0);
1227
+
1228
+ if (prefix !== undefined) return prefix.some((row) => row.record_id === recordId);
1229
+
1230
+ const rows = yield* sql`SELECT record_id FROM effect_agent_canonical_records
1231
+ WHERE thread_id = ${threadId} AND record_id = ${recordId}`.pipe(
1232
+ Effect.mapError(storageError("read canonical record identity")),
1233
+ );
1234
+
1235
+ return rows.length > 0;
1236
+ });
1237
+
1238
+ const append = Effect.fnUntraced(
1239
+ function* (
1240
+ request: RawAppendRequest,
1241
+ observed: ThreadRow,
1242
+ ): Effect.fn.Return<RawAppendResult, AppendError> {
1243
+ if (
1244
+ request.threadId.length > MAX_IDENTIFIER_LENGTH ||
1245
+ request.batchId.length > MAX_IDENTIFIER_LENGTH ||
1246
+ request.records.some((record) => record.recordId.length > MAX_IDENTIFIER_LENGTH)
1247
+ ) {
1248
+ return yield* DoStorageError.make({
1249
+ operation: "append canonical batch",
1250
+ message: "Canonical identifiers exceed the Durable Object storage bounds.",
1251
+ });
1252
+ }
1253
+ // The platform's ~2 MB per-value limit, enforced typed BEFORE any write (plan §1.2).
1254
+ yield* checkValueBound("append canonical batch", request.batchJson);
1255
+ yield* checkValueBound("append canonical batch", request.batchDigest);
1256
+ yield* checkValueBound("append canonical batch", request.tailDigest);
1257
+ yield* Effect.forEach(
1258
+ request.records,
1259
+ (record) => checkValueBound("append canonical record", record.recordJson),
1260
+ { discard: true },
1261
+ );
1262
+
1263
+ const recordIds = request.records.map((record) => record.recordId);
1264
+
1265
+ if (new Set(recordIds).size !== recordIds.length) {
1266
+ return yield* DoAppendConflict.make({
1267
+ message: `Batch ${request.batchId} contains duplicate canonical record IDs.`,
1268
+ reason: "record-identity",
1269
+ });
1270
+ }
1271
+
1272
+ // The facade already read this tail. Reject a known stale writer without opening a
1273
+ // transaction; a matching tail is still checked atomically below. Replays precede tail
1274
+ // conflicts, preserving retry identity even after the log has advanced.
1275
+ if (request.producerEpoch !== observed.producer_epoch) {
1276
+ return yield* DoFenceRejected.make({
1277
+ producerEpoch: request.producerEpoch,
1278
+ actualEpoch: observed.producer_epoch,
1279
+ message: "The append producer epoch is not current.",
1280
+ });
1281
+ }
1282
+ if (
1283
+ request.expectedTailSequence !== observed.tail_sequence ||
1284
+ request.expectedTailDigest !== observed.tail_digest
1285
+ ) {
1286
+ const batches = yield* sql`
1287
+ SELECT batch_id FROM effect_agent_canonical_batches
1288
+ WHERE thread_id = ${request.threadId} AND batch_id = ${request.batchId}
1289
+ `.pipe(Effect.mapError(storageError("preflight append replay")));
1290
+
1291
+ // A possible replay still checks the current epoch and digest in the transaction.
1292
+ if (batches.length === 0) {
1293
+ return yield* DoAppendConflict.make({
1294
+ reason: "tail",
1295
+ message: "The canonical tail has advanced.",
1296
+ actualTailSequence: observed.tail_sequence,
1297
+ actualTailDigest: observed.tail_digest,
1298
+ });
1299
+ }
1300
+ }
1301
+
1302
+ return yield* withWriteTransaction(
1303
+ "append transaction",
1304
+ isAppendContention,
1305
+ )(
1306
+ Effect.gen(function* () {
1307
+ const threadRows = yield* getThread(request.threadId);
1308
+
1309
+ const thread = yield* decodeSingleRow(
1310
+ Schema.Array(ThreadRow),
1311
+ "effect_agent_threads",
1312
+ request.threadId,
1313
+ threadRows,
1314
+ );
1315
+
1316
+ if (request.producerEpoch !== thread.producer_epoch) {
1317
+ return yield* DoFenceRejected.make({
1318
+ producerEpoch: request.producerEpoch,
1319
+ actualEpoch: thread.producer_epoch,
1320
+ message: `Producer epoch ${request.producerEpoch} is not the current epoch ${thread.producer_epoch}.`,
1321
+ });
1322
+ }
1323
+
1324
+ const prefix = recordCache.prefix(request.threadId, thread.tail_sequence);
1325
+
1326
+ const batchRows =
1327
+ prefix !== undefined && !prefix.some((row) => row.batch_id === request.batchId)
1328
+ ? []
1329
+ : yield* sql<Record<string, unknown>>`
1330
+ SELECT
1331
+ thread_id,
1332
+ batch_id,
1333
+ first_sequence,
1334
+ last_sequence,
1335
+ batch_digest,
1336
+ tail_digest,
1337
+ batch_json
1338
+ FROM effect_agent_canonical_batches
1339
+ WHERE thread_id = ${request.threadId}
1340
+ AND batch_id = ${request.batchId}
1341
+ `.pipe(Effect.mapError(storageError("read idempotent batch")));
1342
+
1343
+ const batches = yield* decodeRows(
1344
+ Schema.Array(BatchRow),
1345
+ "effect_agent_canonical_batches",
1346
+ `${request.threadId}/${request.batchId}`,
1347
+ batchRows,
1348
+ );
1349
+
1350
+ if (batches.length > 1) {
1351
+ return yield* DoStorageCorruptionError.make({
1352
+ table: "effect_agent_canonical_batches",
1353
+ rowKey: `${request.threadId}/${request.batchId}`,
1354
+ message: "A canonical batch primary key returned more than one row.",
1355
+ });
1356
+ }
1357
+ if (batches.length === 1) {
1358
+ const existing = batches[0];
1359
+
1360
+ if (existing.batch_digest !== request.batchDigest) {
1361
+ return yield* DoAppendConflict.make({
1362
+ message: `Batch ${request.batchId} already exists with different canonical content.`,
1363
+ reason: "batch-digest",
1364
+ });
1365
+ }
1366
+
1367
+ return RawAppendResult.make({
1368
+ firstSequence: existing.first_sequence,
1369
+ lastSequence: existing.last_sequence,
1370
+ replayed: true,
1371
+ tailDigest: existing.tail_digest,
1372
+ });
1373
+ }
1374
+
1375
+ if (
1376
+ request.expectedTailSequence !== thread.tail_sequence ||
1377
+ request.expectedTailDigest !== thread.tail_digest
1378
+ ) {
1379
+ return yield* DoAppendConflict.make({
1380
+ message:
1381
+ `Expected tail ${request.expectedTailSequence}/${request.expectedTailDigest} ` +
1382
+ `but found ${thread.tail_sequence}/${thread.tail_digest}.`,
1383
+ reason: "tail",
1384
+ actualTailSequence: thread.tail_sequence,
1385
+ actualTailDigest: thread.tail_digest,
1386
+ });
1387
+ }
1388
+ if (thread.tail_sequence + request.records.length > MAX_RECORDS_PER_THREAD) {
1389
+ return yield* DoStorageError.make({
1390
+ operation: "append canonical batch",
1391
+ message: `Thread record limit ${MAX_RECORDS_PER_THREAD} would be exceeded.`,
1392
+ });
1393
+ }
1394
+
1395
+ // Chunked to respect the Durable Object platform's 100-bound-parameter statement
1396
+ // limit: a batch may carry up to 256 records.
1397
+ const existingRecords: Array<RecordRow> =
1398
+ prefix === undefined ? [] : prefix.filter((row) => recordIds.includes(row.record_id));
1399
+
1400
+ for (const chunk of prefix === undefined
1401
+ ? chunked(recordIds, MAX_BOUND_PARAMETERS - 10)
1402
+ : []) {
1403
+ const existingRecordRows = yield* sql<Record<string, unknown>>`
1404
+ SELECT
1405
+ thread_id,
1406
+ sequence,
1407
+ record_id,
1408
+ batch_id,
1409
+ record_json
1410
+ FROM effect_agent_canonical_records
1411
+ WHERE thread_id = ${request.threadId}
1412
+ AND record_id IN ${sql.in([...chunk])}
1413
+ ORDER BY sequence
1414
+ `.pipe(Effect.mapError(storageError("check canonical record identities")));
1415
+
1416
+ existingRecords.push(
1417
+ ...(yield* decodeRows(
1418
+ Schema.Array(RecordRow),
1419
+ "effect_agent_canonical_records",
1420
+ `${request.threadId}/record_ids`,
1421
+ existingRecordRows,
1422
+ )),
1423
+ );
1424
+ }
1425
+ if (existingRecords.length > 0) {
1426
+ return yield* DoAppendConflict.make({
1427
+ message: `Canonical record ID ${existingRecords[0].record_id} already exists.`,
1428
+ reason: "record-identity",
1429
+ });
1430
+ }
1431
+
1432
+ const firstSequence = yield* Schema.decodeEffect(CanonicalSequence)(
1433
+ thread.tail_sequence + 1,
1434
+ ).pipe(
1435
+ Effect.mapError((error) =>
1436
+ DoStorageError.make({
1437
+ cause: error,
1438
+ operation: "append canonical batch",
1439
+ message: error.message,
1440
+ }),
1441
+ ),
1442
+ );
1443
+
1444
+ const lastSequence = yield* Schema.decodeEffect(CanonicalSequence)(
1445
+ firstSequence + request.records.length - 1,
1446
+ ).pipe(
1447
+ Effect.mapError((error) =>
1448
+ DoStorageError.make({
1449
+ cause: error,
1450
+ operation: "append canonical batch",
1451
+ message: error.message,
1452
+ }),
1453
+ ),
1454
+ );
1455
+
1456
+ yield* sql`
1457
+ INSERT INTO effect_agent_canonical_batches (
1458
+ thread_id,
1459
+ batch_id,
1460
+ first_sequence,
1461
+ last_sequence,
1462
+ batch_digest,
1463
+ tail_digest,
1464
+ batch_json
1465
+ ) VALUES (
1466
+ ${request.threadId},
1467
+ ${request.batchId},
1468
+ ${firstSequence},
1469
+ ${lastSequence},
1470
+ ${request.batchDigest},
1471
+ ${request.tailDigest},
1472
+ ${request.batchJson}
1473
+ )
1474
+ `.pipe(Effect.mapError(storageError("insert canonical batch")));
1475
+ yield* failpoint("append:after-batch-insert");
1476
+
1477
+ const records = yield* Effect.forEach(request.records, (record, index) =>
1478
+ Effect.gen(function* () {
1479
+ const canonical = yield* Schema.decodeEffect(
1480
+ Schema.fromJsonString(CanonicalRecord),
1481
+ )(record.recordJson).pipe(
1482
+ Effect.mapError((error) =>
1483
+ DoStorageCorruptionError.make({
1484
+ table: "effect_agent_canonical_records",
1485
+ rowKey: record.recordId,
1486
+ message: error.message,
1487
+ }),
1488
+ ),
1489
+ );
1490
+
1491
+ return {
1492
+ record,
1493
+ canonical,
1494
+ row: {
1495
+ thread_id: request.threadId,
1496
+ sequence: firstSequence + index,
1497
+ record_id: record.recordId,
1498
+ batch_id: request.batchId,
1499
+ record_json: record.recordJson,
1500
+ outstanding: canonicalRecordOutstanding(canonical),
1501
+ },
1502
+ };
1503
+ }),
1504
+ );
1505
+
1506
+ // Six bound columns per row; preserve the logical batch and every append barrier.
1507
+ for (const group of chunked(records, Math.floor(MAX_BOUND_PARAMETERS / 6))) {
1508
+ yield* sql`INSERT INTO effect_agent_canonical_records ${sql.insert(group.map(({ row }) => row))}`.pipe(
1509
+ Effect.mapError(storageError("insert canonical records")),
1510
+ );
1511
+ for (const { canonical, row } of group) {
1512
+ yield* indexCanonicalRecord(request.threadId, canonical, undefined, {
1513
+ sequence: row.sequence,
1514
+ }).pipe(
1515
+ Effect.provideService(SqlClient.SqlClient, sql),
1516
+ Effect.mapError(storageError("index canonical record")),
1517
+ );
1518
+ recordCache.put(
1519
+ RecordRow.make({
1520
+ ...row,
1521
+ sequence: Schema.decodeSync(CanonicalSequence)(row.sequence),
1522
+ }),
1523
+ );
1524
+ yield* failpoint("append:after-record-insert");
1525
+ }
1526
+ }
1527
+
1528
+ yield* sql`
1529
+ UPDATE effect_agent_threads
1530
+ SET
1531
+ tail_sequence = ${lastSequence},
1532
+ tail_digest = ${request.tailDigest},
1533
+ producer_epoch = ${request.producerEpoch}
1534
+ WHERE thread_id = ${request.threadId}
1535
+ RETURNING *`.pipe(
1536
+ threads.write,
1537
+ Effect.mapError((error) =>
1538
+ error._tag === "SqlError" ? storageError("advance thread tail")(error) : error,
1539
+ ),
1540
+ );
1541
+ yield* failpoint("append:after-tail-update");
1542
+
1543
+ // Retain one start prefix atomically with its canonical proof, before model/tool
1544
+ // execution. Later facts stay journal-backed until the settlement publication wave.
1545
+ if (
1546
+ lifecycle !== undefined &&
1547
+ records.some(
1548
+ ({ canonical: { payload } }) =>
1549
+ payload._tag === "RunStarted" || payload._tag === "SubagentStarted",
1550
+ )
1551
+ )
1552
+ yield* flushCanonical(request.threadId).pipe(
1553
+ Effect.provideService(SqlLifecycleRetainer, { retainMany: lifecycle.retainMany }),
1554
+ Effect.mapError((cause) =>
1555
+ DoStorageError.make({
1556
+ operation: "retain lifecycle start prefix",
1557
+ message: "Lifecycle start intent could not be retained",
1558
+ cause,
1559
+ }),
1560
+ ),
1561
+ );
1562
+
1563
+ yield* progress.committed("canonical").pipe(
1564
+ Effect.catchCause((cause) =>
1565
+ Effect.failCause(
1566
+ Cause.map(cause, (error) =>
1567
+ DoStorageError.make({
1568
+ operation: "enroll canonical progress",
1569
+ message: error.message,
1570
+ cause: error,
1571
+ }),
1572
+ ),
1573
+ ),
1574
+ ),
1575
+ );
1576
+
1577
+ return RawAppendResult.make({
1578
+ firstSequence,
1579
+ lastSequence,
1580
+ replayed: false,
1581
+ tailDigest: request.tailDigest,
1582
+ });
1583
+ }),
1584
+ );
1585
+ },
1586
+ withStorageSpan("DoJournal.append", isAppendContention),
1587
+ );
1588
+
1589
+ const read = Effect.fnUntraced(function* (request: RawReadRequest) {
1590
+ const thread = (yield* getThread(request.threadId))[0];
1591
+
1592
+ const through = Math.min(
1593
+ thread?.tail_sequence ?? 0,
1594
+ request.fromSequenceExclusive + request.limit,
1595
+ );
1596
+
1597
+ const cached: Array<RecordRow> = [];
1598
+
1599
+ for (let sequence = request.fromSequenceExclusive + 1; sequence <= through; sequence++) {
1600
+ const record = recordCache.get(request.threadId, sequence);
1601
+
1602
+ if (record === undefined) break;
1603
+ cached.push(record);
1604
+ }
1605
+ if (cached.length === Math.max(0, through - request.fromSequenceExclusive)) {
1606
+ return { count: cached.length, records: Stream.fromIterable(cached) };
1607
+ }
1608
+
1609
+ // Capture membership without retaining payloads. Append-only sequences keep each later
1610
+ // payload query inside this snapshot, even when new records arrive during consumption.
1611
+ const planRows = yield* sql<Record<string, unknown>>`
1612
+ SELECT
1613
+ sequence,
1614
+ length(CAST(record_json AS BLOB)) AS record_json_bytes
1615
+ FROM effect_agent_canonical_records
1616
+ WHERE thread_id = ${request.threadId}
1617
+ AND sequence > ${request.fromSequenceExclusive}
1618
+ ORDER BY sequence
1619
+ LIMIT ${request.limit}
1620
+ `.pipe(Effect.mapError(storageError("read canonical records")));
1621
+
1622
+ const plan = yield* decodeRows(
1623
+ Schema.Array(ReadPlanRow),
1624
+ "effect_agent_canonical_records",
1625
+ `${request.threadId}>${request.fromSequenceExclusive}`,
1626
+ planRows,
1627
+ "ReadPlanRow",
1628
+ );
1629
+
1630
+ const mismatch = () =>
1631
+ DoStorageCorruptionError.make({
1632
+ table: "effect_agent_canonical_records",
1633
+ rowKey: `${request.threadId}>${request.fromSequenceExclusive}`,
1634
+ message:
1635
+ "Canonical read membership, sequence, or payload size changed from its read plan.",
1636
+ });
1637
+
1638
+ if (plan.length > request.limit) return yield* mismatch();
1639
+
1640
+ const pages: Array<ReadPage> = [];
1641
+ let page: ReadPage | undefined;
1642
+ let pageBytes = 0;
1643
+ let previousSequence = request.fromSequenceExclusive;
1644
+
1645
+ for (const row of plan) {
1646
+ if (row.sequence !== previousSequence + 1) return yield* mismatch();
1647
+ previousSequence = row.sequence;
1648
+ if (page === undefined || pageBytes + row.record_json_bytes > MAX_READ_PAGE_JSON_BYTES) {
1649
+ page = [row];
1650
+ pages.push(page);
1651
+ pageBytes = row.record_json_bytes;
1652
+ } else {
1653
+ page.push(row);
1654
+ pageBytes += row.record_json_bytes;
1655
+ }
1656
+ }
1657
+
1658
+ const readPage = Effect.fn("DoJournal.readPage")(function* (page: ReadPage) {
1659
+ const rows = yield* sql<Record<string, unknown>>`
1660
+ SELECT thread_id, sequence, record_id, batch_id, record_json
1661
+ FROM effect_agent_canonical_records
1662
+ WHERE thread_id = ${request.threadId}
1663
+ AND sequence >= ${page[0].sequence}
1664
+ AND sequence <= ${page[page.length - 1].sequence}
1665
+ ORDER BY sequence
1666
+ `.pipe(Effect.mapError(storageError("read canonical records")));
1667
+
1668
+ const decoded = yield* decodeRows(
1669
+ Schema.Array(RecordRow),
1670
+ "effect_agent_canonical_records",
1671
+ `${request.threadId}/${page[0].sequence}`,
1672
+ rows,
1673
+ "RecordRow",
1674
+ );
1675
+
1676
+ if (
1677
+ decoded.length !== page.length ||
1678
+ decoded.some(
1679
+ (row, index) =>
1680
+ row.thread_id !== request.threadId ||
1681
+ row.sequence !== page[index].sequence ||
1682
+ storedTextBytes(row.record_json) !== page[index].record_json_bytes,
1683
+ )
1684
+ ) {
1685
+ return yield* mismatch();
1686
+ }
1687
+
1688
+ for (const row of decoded) recordCache.put(row);
1689
+
1690
+ return decoded;
1691
+ });
1692
+
1693
+ return {
1694
+ count: plan.length,
1695
+ records: Stream.fromIterable(pages).pipe(
1696
+ Stream.flatMap((page) => Stream.fromIterableEffect(state.read(readPage(page)))),
1697
+ ),
1698
+ };
1699
+ });
1700
+
1701
+ const exportThread = Effect.fn("DoJournal.exportThread")(function* (threadId: string) {
1702
+ return yield* state
1703
+ .transaction(
1704
+ Effect.gen(function* () {
1705
+ const threadRows = yield* getThread(threadId);
1706
+
1707
+ const thread = yield* decodeSingleRow(
1708
+ Schema.Array(ThreadRow),
1709
+ "effect_agent_threads",
1710
+ threadId,
1711
+ threadRows,
1712
+ );
1713
+
1714
+ yield* failpoint("export:after-thread-read");
1715
+
1716
+ if (thread.tail_sequence > MAX_RECORDS_PER_THREAD)
1717
+ return yield* DoStorageError.make({
1718
+ operation: "export thread",
1719
+ message: "The thread exceeds the current export record limit.",
1720
+ });
1721
+ const records: Array<RecordRow> = [];
1722
+ let afterSequence = ZERO_SEQUENCE;
1723
+
1724
+ while (afterSequence < thread.tail_sequence) {
1725
+ const limit = Math.min(1_024, thread.tail_sequence - afterSequence);
1726
+
1727
+ const request = RawReadRequest.make({
1728
+ threadId,
1729
+ fromSequenceExclusive: afterSequence,
1730
+ limit,
1731
+ });
1732
+
1733
+ const plan = yield* read(request);
1734
+ const page = yield* Stream.runCollect(plan.records);
1735
+
1736
+ if (
1737
+ page.length !== limit ||
1738
+ page.some((record, index) => record.sequence !== afterSequence + index + 1)
1739
+ ) {
1740
+ return yield* DoStorageCorruptionError.make({
1741
+ table: "effect_agent_canonical_records",
1742
+ rowKey: threadId,
1743
+ message:
1744
+ "The exported canonical prefix is not contiguous through its captured tail.",
1745
+ });
1746
+ }
1747
+ records.push(...page);
1748
+ afterSequence = page[page.length - 1].sequence;
1749
+ }
1750
+
1751
+ const beyondTail =
1752
+ yield* sql`SELECT sequence FROM effect_agent_canonical_records WHERE thread_id=${threadId} AND sequence > ${thread.tail_sequence} LIMIT 1`.pipe(
1753
+ Effect.mapError(storageError("verify export tail")),
1754
+ );
1755
+
1756
+ if (beyondTail.length !== 0)
1757
+ return yield* DoStorageCorruptionError.make({
1758
+ table: "effect_agent_canonical_records",
1759
+ rowKey: threadId,
1760
+ message: "Canonical records exist beyond the captured thread tail.",
1761
+ });
1762
+
1763
+ return RawThreadExport.make({ thread, records });
1764
+ }),
1765
+ )
1766
+ .pipe(
1767
+ Effect.provideService(SqlClient.SqlClient, sql),
1768
+ Effect.catchTag("SqlError", (error) =>
1769
+ Effect.fail(storageError("export transaction")(error)),
1770
+ ),
1771
+ );
1772
+ });
1773
+
1774
+ const saveCheckpoint = Effect.fn("DoJournal.saveCheckpoint")(function* (
1775
+ checkpoint: RawCheckpoint,
1776
+ ): Effect.fn.Return<void, CheckpointError> {
1777
+ if (checkpoint.threadId.length > MAX_IDENTIFIER_LENGTH) {
1778
+ return yield* DoStorageError.make({
1779
+ operation: "save checkpoint",
1780
+ message: "Checkpoint identity exceeds the Durable Object storage bounds.",
1781
+ });
1782
+ }
1783
+ yield* checkValueBound("save checkpoint", checkpoint.checkpointJson);
1784
+ yield* withWriteTransaction("checkpoint transaction")(
1785
+ Effect.gen(function* () {
1786
+ const threadRows = yield* getThread(checkpoint.threadId);
1787
+
1788
+ const thread = yield* decodeSingleRow(
1789
+ Schema.Array(ThreadRow),
1790
+ "effect_agent_threads",
1791
+ checkpoint.threadId,
1792
+ threadRows,
1793
+ );
1794
+
1795
+ if (checkpoint.throughSequence > thread.tail_sequence) {
1796
+ return yield* DoCheckpointConflict.make({
1797
+ message:
1798
+ `Checkpoint sequence ${checkpoint.throughSequence} is after canonical tail ` +
1799
+ `${thread.tail_sequence}.`,
1800
+ });
1801
+ }
1802
+
1803
+ const checkpointRows = yield* sql<Record<string, unknown>>`
1804
+ SELECT
1805
+ thread_id,
1806
+ through_sequence,
1807
+ tail_digest,
1808
+ checkpoint_json
1809
+ FROM effect_agent_checkpoints
1810
+ WHERE thread_id = ${checkpoint.threadId}
1811
+ AND through_sequence = ${checkpoint.throughSequence}
1812
+ `.pipe(Effect.mapError(storageError("read idempotent checkpoint")));
1813
+
1814
+ const existing = yield* decodeRows(
1815
+ Schema.Array(CheckpointRow),
1816
+ "effect_agent_checkpoints",
1817
+ `${checkpoint.threadId}/${checkpoint.throughSequence}`,
1818
+ checkpointRows,
1819
+ );
1820
+
1821
+ if (existing.length > 1) {
1822
+ return yield* DoStorageCorruptionError.make({
1823
+ table: "effect_agent_checkpoints",
1824
+ rowKey: `${checkpoint.threadId}/${checkpoint.throughSequence}`,
1825
+ message: "A checkpoint primary key returned more than one row.",
1826
+ });
1827
+ }
1828
+ if (existing.length === 1) {
1829
+ if (
1830
+ existing[0].tail_digest !== checkpoint.tailDigest ||
1831
+ existing[0].checkpoint_json !== checkpoint.checkpointJson
1832
+ ) {
1833
+ return yield* DoCheckpointConflict.make({
1834
+ message: "A different checkpoint already exists at this canonical sequence.",
1835
+ });
1836
+ }
1837
+
1838
+ return;
1839
+ }
1840
+
1841
+ yield* sql`
1842
+ INSERT INTO effect_agent_checkpoints (
1843
+ thread_id,
1844
+ through_sequence,
1845
+ tail_digest,
1846
+ checkpoint_json
1847
+ ) VALUES (
1848
+ ${checkpoint.threadId},
1849
+ ${checkpoint.throughSequence},
1850
+ ${checkpoint.tailDigest},
1851
+ ${checkpoint.checkpointJson}
1852
+ )
1853
+ `.pipe(Effect.mapError(storageError("insert checkpoint")));
1854
+ }),
1855
+ );
1856
+ });
1857
+
1858
+ const saveRecoveryCheckpoint = Effect.fn("DoJournal.saveRecoveryCheckpoint")(function* (
1859
+ request: SaveRecoveryCheckpointRequest,
1860
+ checkpointJson: string,
1861
+ ) {
1862
+ const { checkpoint } = request;
1863
+
1864
+ if (checkpoint.threadId.length > MAX_IDENTIFIER_LENGTH) {
1865
+ return yield* DoStorageError.make({
1866
+ operation: "save recovery checkpoint",
1867
+ message: "Checkpoint identity exceeds the Durable Object storage bounds.",
1868
+ });
1869
+ }
1870
+ yield* checkValueBound("save recovery checkpoint", checkpointJson);
1871
+ // Keep injected waits outside the storage-backed transaction callback.
1872
+ yield* failpoint("save-recovery-checkpoint:before");
1873
+ yield* withWriteTransaction("recovery checkpoint transaction")(
1874
+ Effect.gen(function* () {
1875
+ const threads = yield* getThread(checkpoint.threadId);
1876
+ const thread = threads[0];
1877
+
1878
+ if (thread === undefined)
1879
+ return yield* ThreadNotMaterialized.make({ threadId: checkpoint.threadId });
1880
+ if (request.producerEpoch !== thread.producer_epoch)
1881
+ return yield* FenceRejected.make({
1882
+ threadId: checkpoint.threadId,
1883
+ actualEpoch: thread.producer_epoch,
1884
+ attemptedEpoch: request.producerEpoch,
1885
+ });
1886
+ if (checkpoint.throughSequence > thread.tail_sequence)
1887
+ return yield* CheckpointRejected.make({
1888
+ threadId: checkpoint.threadId,
1889
+ reason: "ahead-of-tail",
1890
+ });
1891
+
1892
+ const digests =
1893
+ checkpoint.throughSequence === 0
1894
+ ? [EMPTY_TAIL_DIGEST]
1895
+ : yield* getTailDigestAt(checkpoint.threadId, checkpoint.throughSequence);
1896
+
1897
+ if (digests.length !== 1 || digests[0] !== checkpoint.tailDigest)
1898
+ return yield* CheckpointRejected.make({
1899
+ threadId: checkpoint.threadId,
1900
+ reason: "digest-mismatch",
1901
+ });
1902
+
1903
+ yield* sql`
1904
+ INSERT INTO effect_agent_recovery_checkpoints (thread_id, through_sequence, tail_digest, checkpoint_json)
1905
+ VALUES (${checkpoint.threadId}, ${checkpoint.throughSequence}, ${checkpoint.tailDigest}, ${checkpointJson})
1906
+ ON CONFLICT (thread_id) DO UPDATE SET
1907
+ through_sequence = excluded.through_sequence,
1908
+ tail_digest = excluded.tail_digest,
1909
+ checkpoint_json = excluded.checkpoint_json
1910
+ WHERE excluded.through_sequence >= effect_agent_recovery_checkpoints.through_sequence
1911
+ RETURNING *
1912
+ `.pipe(
1913
+ recovery.write,
1914
+ Effect.mapError((error) =>
1915
+ error._tag === "SqlError" ? storageError("save recovery checkpoint")(error) : error,
1916
+ ),
1917
+ );
1918
+ }),
1919
+ );
1920
+ yield* failpoint("save-recovery-checkpoint:after");
1921
+ });
1922
+
1923
+ const loadRecoveryCheckpoint = Effect.fn("DoJournal.loadRecoveryCheckpoint")(function* (
1924
+ threadId: string,
1925
+ ) {
1926
+ return yield* recovery
1927
+ .by("thread_id", threadId)
1928
+ .pipe(
1929
+ Effect.mapError((error) =>
1930
+ error._tag === "SqlError" ? storageError("load recovery checkpoint")(error) : error,
1931
+ ),
1932
+ );
1933
+ });
1934
+
1935
+ const loadCheckpoint = Effect.fn("DoJournal.loadCheckpoint")(function* (
1936
+ threadId: string,
1937
+ atOrBeforeSequence: CanonicalSequence,
1938
+ ) {
1939
+ const rows = yield* sql<Record<string, unknown>>`
1940
+ SELECT
1941
+ thread_id,
1942
+ through_sequence,
1943
+ tail_digest,
1944
+ checkpoint_json
1945
+ FROM effect_agent_checkpoints
1946
+ WHERE thread_id = ${threadId}
1947
+ AND through_sequence <= ${atOrBeforeSequence}
1948
+ ORDER BY through_sequence DESC
1949
+ LIMIT 1
1950
+ `.pipe(Effect.mapError(storageError("load checkpoint")));
1951
+
1952
+ return yield* decodeRows(
1953
+ Schema.Array(CheckpointRow),
1954
+ "effect_agent_checkpoints",
1955
+ `${threadId}<=${atOrBeforeSequence}`,
1956
+ rows,
1957
+ );
1958
+ });
1959
+
1960
+ const getTailDigestAt = Effect.fn("DoJournal.getTailDigestAt")(function* (
1961
+ threadId: string,
1962
+ sequence: CanonicalSequence,
1963
+ ) {
1964
+ const thread = (yield* getThread(threadId))[0];
1965
+
1966
+ if (thread !== undefined && sequence === thread.tail_sequence) return [thread.tail_digest];
1967
+ if (sequence === 0) {
1968
+ const threads = yield* getThread(threadId);
1969
+
1970
+ return threads.length === 0
1971
+ ? []
1972
+ : [threads[0].tail_sequence === 0 ? threads[0].tail_digest : undefined].filter(
1973
+ (value): value is string => value !== undefined,
1974
+ );
1975
+ }
1976
+
1977
+ // Resolve both primary keys; last_sequence alone scans the Thread's archived batches.
1978
+ // Retain the batch-end predicate so an interior record cannot certify a checkpoint.
1979
+ const rows = yield* sql<Record<string, unknown>>`
1980
+ SELECT
1981
+ thread_id,
1982
+ batch_id,
1983
+ first_sequence,
1984
+ last_sequence,
1985
+ batch_digest,
1986
+ tail_digest,
1987
+ batch_json
1988
+ FROM effect_agent_canonical_batches
1989
+ WHERE thread_id = ${threadId}
1990
+ AND batch_id = (
1991
+ SELECT batch_id FROM effect_agent_canonical_records
1992
+ WHERE thread_id = ${threadId} AND sequence = ${sequence}
1993
+ )
1994
+ AND last_sequence = ${sequence}
1995
+ `.pipe(Effect.mapError(storageError("read canonical digest at sequence")));
1996
+
1997
+ const batches = yield* decodeRows(
1998
+ Schema.Array(BatchRow),
1999
+ "effect_agent_canonical_batches",
2000
+ `${threadId}/${sequence}`,
2001
+ rows,
2002
+ );
2003
+
2004
+ return batches.map((batch) => batch.tail_digest);
2005
+ });
2006
+
2007
+ const scanStoredPayloads = Effect.fn("DoJournal.scanStoredPayloads")(function* () {
2008
+ return yield* state
2009
+ .transaction(
2010
+ Effect.gen(function* () {
2011
+ const threads = yield* sql<Record<string, unknown>>`
2012
+ SELECT
2013
+ thread_id,
2014
+ created_at,
2015
+ tail_sequence,
2016
+ tail_digest,
2017
+ producer_epoch
2018
+ FROM effect_agent_threads
2019
+ ORDER BY thread_id
2020
+ `.pipe(Effect.mapError(storageError("scan threads")));
2021
+
2022
+ const batches = yield* sql<Record<string, unknown>>`
2023
+ SELECT
2024
+ thread_id,
2025
+ batch_id,
2026
+ first_sequence,
2027
+ last_sequence,
2028
+ batch_digest,
2029
+ tail_digest,
2030
+ batch_json
2031
+ FROM effect_agent_canonical_batches
2032
+ ORDER BY thread_id, first_sequence
2033
+ `.pipe(Effect.mapError(storageError("scan canonical batches")));
2034
+
2035
+ const records = yield* sql<Record<string, unknown>>`
2036
+ SELECT
2037
+ thread_id,
2038
+ sequence,
2039
+ record_id,
2040
+ batch_id,
2041
+ record_json
2042
+ FROM effect_agent_canonical_records
2043
+ ORDER BY thread_id, sequence
2044
+ `.pipe(Effect.mapError(storageError("scan canonical records")));
2045
+
2046
+ const checkpoints = yield* sql<Record<string, unknown>>`
2047
+ SELECT
2048
+ thread_id,
2049
+ through_sequence,
2050
+ tail_digest,
2051
+ checkpoint_json
2052
+ FROM effect_agent_checkpoints
2053
+ ORDER BY thread_id, through_sequence
2054
+ `.pipe(Effect.mapError(storageError("scan checkpoints")));
2055
+
2056
+ return {
2057
+ threads: yield* decodeRows(
2058
+ Schema.Array(ThreadRow),
2059
+ "effect_agent_threads",
2060
+ "startup_scan",
2061
+ threads,
2062
+ ),
2063
+ batches: yield* decodeRows(
2064
+ Schema.Array(BatchRow),
2065
+ "effect_agent_canonical_batches",
2066
+ "startup_scan",
2067
+ batches,
2068
+ ),
2069
+ records: yield* decodeRows(
2070
+ Schema.Array(RecordRow),
2071
+ "effect_agent_canonical_records",
2072
+ "startup_scan",
2073
+ records,
2074
+ ),
2075
+ checkpoints: yield* decodeRows(
2076
+ Schema.Array(CheckpointRow),
2077
+ "effect_agent_checkpoints",
2078
+ "startup_scan",
2079
+ checkpoints,
2080
+ ),
2081
+ };
2082
+ }),
2083
+ )
2084
+ .pipe(
2085
+ Effect.provideService(SqlClient.SqlClient, sql),
2086
+ Effect.catchTag("SqlError", (error) =>
2087
+ Effect.fail(storageError("startup scan transaction")(error)),
2088
+ ),
2089
+ );
2090
+ });
2091
+
2092
+ const sourceFailure = (cause: unknown) =>
2093
+ LifecyclePublicationError.make({ reason: "unavailable", cause });
2094
+
2095
+ const sourceThreads = Effect.fnUntraced(function* () {
2096
+ const all = yield* threads.matching(
2097
+ "lifecycle-owners",
2098
+ () => true,
2099
+ sql`SELECT * FROM effect_agent_threads LIMIT 129`,
2100
+ 128,
2101
+ );
2102
+
2103
+ if (all.length <= 128) return all;
2104
+
2105
+ // Large custom hosts hydrate only owners whose journal has an unmaterialized suffix.
2106
+ return yield* Schema.decodeUnknownEffect(Schema.Array(ThreadRow))(
2107
+ yield* sql`SELECT t.* FROM effect_agent_threads t LEFT JOIN effect_agent_lifecycle_cursors c ON c.thread_id=t.thread_id
2108
+ WHERE c.thread_id IS NULL OR t.tail_sequence > c.through_sequence ORDER BY t.thread_id LIMIT 128`,
2109
+ );
2110
+ });
2111
+
2112
+ const initializeLifecycleSource = Effect.fnUntraced(function* () {
2113
+ if (initializedLifecycleSources.has(state)) return;
2114
+ yield* state
2115
+ .transaction(
2116
+ Effect.gen(function* () {
2117
+ const existing =
2118
+ yield* sql`SELECT name FROM sqlite_master WHERE name='effect_agent_lifecycle_cursors'`;
2119
+
2120
+ if (existing.length === 0) {
2121
+ yield* sql`CREATE TABLE effect_agent_lifecycle_cursors (
2122
+ thread_id TEXT PRIMARY KEY, through_sequence INTEGER NOT NULL
2123
+ )`;
2124
+ // Existing inline writers already retained their facts. Enabling publication on an
2125
+ // old store starts here too; it does not publish historical facts retroactively.
2126
+ }
2127
+ // New Threads created with publication disabled have no cursor. Never advance
2128
+ // existing cursors: they can owe intent from an interrupted Attempt.
2129
+ yield* sql`INSERT INTO effect_agent_lifecycle_cursors(thread_id, through_sequence)
2130
+ SELECT thread_id, tail_sequence FROM effect_agent_threads WHERE true
2131
+ ON CONFLICT(thread_id) DO NOTHING`;
2132
+ yield* sourceThreads();
2133
+ }),
2134
+ )
2135
+ .pipe(
2136
+ Effect.provideService(SqlClient.SqlClient, sql),
2137
+ Effect.mapError((cause) =>
2138
+ DoStorageError.make({
2139
+ operation: "initialize lifecycle source",
2140
+ message: "Lifecycle source cursor unavailable",
2141
+ cause,
2142
+ }),
2143
+ ),
2144
+ );
2145
+ initializedLifecycleSources.add(state);
2146
+ });
2147
+
2148
+ /** The journal is durable intent; only the bounded publication wave materializes a write set. */
2149
+ const flushCanonical = Effect.fnUntraced(function* (threadId: string, maxRecords = Infinity) {
2150
+ const { retainMany } = yield* SqlLifecycleRetainer;
2151
+ const thread = (yield* getThread(threadId))[0];
2152
+
2153
+ if (thread === undefined) return;
2154
+ const cursor = (yield* cursors.by("thread_id", threadId))[0];
2155
+
2156
+ if (cursor === undefined || cursor.through_sequence > thread.tail_sequence)
2157
+ return yield* LifecyclePublicationError.make({ reason: "corrupt" });
2158
+ let through = cursor.through_sequence;
2159
+ const bound = Math.min(thread.tail_sequence, through + maxRecords);
2160
+
2161
+ while (through < bound) {
2162
+ const page = yield* read(
2163
+ RawReadRequest.make({
2164
+ threadId,
2165
+ fromSequenceExclusive: through,
2166
+ limit: Math.min(128, bound - through),
2167
+ }),
2168
+ );
2169
+
2170
+ const facts: Array<Parameters<SqlLifecycleRetainMany>[0][number]> = [];
2171
+ let bytes = 0;
2172
+
2173
+ yield* Stream.runForEach(page.records, (row) =>
2174
+ Effect.gen(function* () {
2175
+ const record = yield* Schema.decodeEffect(Schema.fromJsonString(CanonicalRecord))(
2176
+ row.record_json,
2177
+ );
2178
+
2179
+ if (record.recordId !== row.record_id || row.sequence !== through + 1)
2180
+ return yield* LifecyclePublicationError.make({ reason: "corrupt" });
2181
+ if (Schema.is(Schema.toType(LifecyclePublicationFact))(record.payload)) {
2182
+ if (
2183
+ bytes + storedTextBytes(row.record_json) > MAX_READ_PAGE_JSON_BYTES &&
2184
+ facts.length > 0
2185
+ ) {
2186
+ yield* retainMany(facts);
2187
+ facts.length = 0;
2188
+ bytes = 0;
2189
+ }
2190
+ facts.push({
2191
+ id: JSON.stringify([threadId, "record", record.recordId]),
2192
+ ownerThreadId: yield* Schema.decodeEffect(ThreadId)(threadId),
2193
+ canonicalSequence: row.sequence,
2194
+ createdAt: record.createdAt,
2195
+ fact: record.payload,
2196
+ });
2197
+ bytes += storedTextBytes(row.record_json);
2198
+ }
2199
+ through = row.sequence;
2200
+ }),
2201
+ );
2202
+ if (page.count === 0) return yield* LifecyclePublicationError.make({ reason: "corrupt" });
2203
+ yield* retainMany(facts);
2204
+ yield* sql`UPDATE effect_agent_lifecycle_cursors SET through_sequence=${through} WHERE thread_id=${threadId} RETURNING *`.pipe(
2205
+ cursors.write,
2206
+ );
2207
+ }
2208
+ }, Effect.mapError(sourceFailure));
2209
+
2210
+ const flushPublications = Effect.fnUntraced(function* () {
2211
+ let owners = 0;
2212
+
2213
+ for (const thread of yield* sourceThreads()) {
2214
+ const cursor = (yield* cursors.by("thread_id", thread.thread_id))[0];
2215
+
2216
+ if (cursor !== undefined && cursor.through_sequence === thread.tail_sequence) continue;
2217
+ yield* flushCanonical(thread.thread_id, 1024);
2218
+ if (++owners === 4) break;
2219
+ }
2220
+ }, Effect.mapError(sourceFailure));
2221
+
2222
+ const sourcePending = Effect.gen(function* () {
2223
+ for (const thread of yield* sourceThreads()) {
2224
+ const cursor = (yield* cursors.by("thread_id", thread.thread_id))[0];
2225
+
2226
+ if (cursor === undefined || cursor.through_sequence > thread.tail_sequence)
2227
+ return yield* LifecyclePublicationError.make({ reason: "corrupt" });
2228
+ if (cursor.through_sequence < thread.tail_sequence) return true;
2229
+ }
2230
+
2231
+ return false;
2232
+ }).pipe(Effect.mapError(sourceFailure));
2233
+
2234
+ const ownedLifecycle =
2235
+ lifecycle === undefined
2236
+ ? undefined
2237
+ : {
2238
+ ...lifecycle,
2239
+ storage: {
2240
+ ...lifecycle.storage,
2241
+ retainedPendingDeadline: lifecycle.storage.pendingDeadline,
2242
+ pendingDeadline: state.read(
2243
+ Effect.gen(function* () {
2244
+ const deadline = yield* lifecycle.storage.pendingDeadline;
2245
+
2246
+ if (!(yield* sourcePending)) return deadline;
2247
+ const now = yield* Clock.currentTimeMillis;
2248
+
2249
+ return Option.some(Option.isSome(deadline) ? Math.min(now, deadline.value) : now);
2250
+ }),
2251
+ ),
2252
+ },
2253
+ };
2254
+
2255
+ return {
2256
+ state,
2257
+ owner,
2258
+ threads,
2259
+ lifecycle: ownedLifecycle,
2260
+ initializeLifecycleSource,
2261
+ flushCanonical,
2262
+ flushPublications,
2263
+ append,
2264
+ checkValueBound,
2265
+ exportThread,
2266
+ getThread,
2267
+ hasRecord,
2268
+ getTailDigestAt,
2269
+ loadCheckpoint,
2270
+ loadRecoveryCheckpoint,
2271
+ saveRecoveryCheckpoint,
2272
+ materialize,
2273
+ read: (request: RawReadRequest) => state.read(read(request)),
2274
+ saveCheckpoint,
2275
+ scanStoredPayloads,
2276
+ withWriteTransaction,
2277
+ } as const;
2278
+ });
2279
+
2280
+ export type DoJournal = Effect.Success<ReturnType<typeof makeJournal>>;
2281
+
2282
+ export const initializeDoJournal = ensureCurrentStorage;