@effect-agent/storage-sqlite 0.1.0-beta.11 → 0.1.0-beta.110

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 (63) hide show
  1. package/dist/SqliteActivityStore.d.mts +14 -0
  2. package/dist/SqliteActivityStore.mjs +310 -0
  3. package/dist/SqliteActivityStore.mjs.map +1 -0
  4. package/dist/SqliteMessageDeliveryStore.d.mts +14 -0
  5. package/dist/SqliteMessageDeliveryStore.mjs +24 -0
  6. package/dist/SqliteMessageDeliveryStore.mjs.map +1 -0
  7. package/dist/SqliteScheduleStore.d.mts +14 -0
  8. package/dist/SqliteScheduleStore.mjs +255 -0
  9. package/dist/SqliteScheduleStore.mjs.map +1 -0
  10. package/dist/SqliteStorageConfig.d.mts +34 -0
  11. package/dist/SqliteStorageConfig.mjs +39 -0
  12. package/dist/SqliteStorageConfig.mjs.map +1 -0
  13. package/dist/SqliteStorageError-DVWeaWLm.d.mts +86 -0
  14. package/dist/SqliteStorageError.d.mts +2 -0
  15. package/dist/SqliteStorageError.mjs +150 -0
  16. package/dist/SqliteStorageError.mjs.map +1 -0
  17. package/dist/SqliteStorageFailpoint.d.mts +17 -0
  18. package/dist/SqliteStorageFailpoint.mjs +14 -0
  19. package/dist/SqliteStorageFailpoint.mjs.map +1 -0
  20. package/dist/SqliteStorageFailpointTesting.d.mts +14 -0
  21. package/dist/SqliteStorageFailpointTesting.mjs +19 -0
  22. package/dist/SqliteStorageFailpointTesting.mjs.map +1 -0
  23. package/dist/SqliteStorageVersion-BO6U_VHq.d.mts +11 -0
  24. package/dist/SqliteStorageVersion.d.mts +2 -0
  25. package/dist/SqliteStorageVersion.mjs +8 -0
  26. package/dist/SqliteStorageVersion.mjs.map +1 -0
  27. package/dist/SqliteSubmissionLedger.d.mts +23 -0
  28. package/dist/SqliteSubmissionLedger.mjs +1803 -0
  29. package/dist/SqliteSubmissionLedger.mjs.map +1 -0
  30. package/dist/SqliteSubscriptionStore.d.mts +13 -0
  31. package/dist/SqliteSubscriptionStore.mjs +28 -0
  32. package/dist/SqliteSubscriptionStore.mjs.map +1 -0
  33. package/dist/SqliteThreadStore.d.mts +49 -0
  34. package/dist/SqliteThreadStore.mjs +464 -0
  35. package/dist/SqliteThreadStore.mjs.map +1 -0
  36. package/dist/index.d.mts +11 -193
  37. package/dist/index.mjs +11 -3082
  38. package/dist/migrations-BZ89iaTY.mjs +350 -0
  39. package/dist/migrations-BZ89iaTY.mjs.map +1 -0
  40. package/dist/rolldown-runtime-D7D4PA-g.mjs +13 -0
  41. package/dist/sqlite-journal-BCyBc87Y.mjs +1044 -0
  42. package/dist/sqlite-journal-BCyBc87Y.mjs.map +1 -0
  43. package/package.json +1 -41
  44. package/src/SqliteActivityStore.ts +556 -0
  45. package/src/SqliteMessageDeliveryStore.ts +42 -0
  46. package/src/SqliteScheduleStore.ts +404 -0
  47. package/src/{sqlite-storage-config.ts → SqliteStorageConfig.ts} +1 -1
  48. package/src/{errors.ts → SqliteStorageError.ts} +10 -3
  49. package/src/SqliteStorageFailpoint.ts +23 -0
  50. package/src/{sqlite-storage-failpoint.ts → SqliteStorageFailpointTesting.ts} +7 -18
  51. package/src/SqliteStorageVersion.ts +2 -0
  52. package/src/{sqlite-ledger.ts → SqliteSubmissionLedger.ts} +958 -233
  53. package/src/SqliteSubscriptionStore.ts +55 -0
  54. package/src/SqliteThreadStore.ts +1004 -0
  55. package/src/index.ts +10 -6
  56. package/src/internal/message-delivery-schema.ts +24 -0
  57. package/src/internal/migrations.ts +356 -0
  58. package/src/internal/recovery-checkpoint-schema.ts +17 -0
  59. package/src/internal/sqlite-journal.ts +1684 -0
  60. package/dist/index.mjs.map +0 -1
  61. package/src/migrations.ts +0 -275
  62. package/src/sqlite-conversation-store.ts +0 -841
  63. package/src/sqlite-journal.ts +0 -1086
@@ -0,0 +1,1044 @@
1
+ import { SqliteStorageConfig } from "./SqliteStorageConfig.mjs";
2
+ import { SqliteAppendConflict, SqliteCheckpointConflict, SqliteFenceRejected, SqliteStorageCompatibilityError, SqliteStorageCorruptionError, SqliteStorageError, SqliteStorageFailpointLocation, SqliteWriteContention } from "./SqliteStorageError.mjs";
3
+ import { SqliteStorageFailpoint } from "./SqliteStorageFailpoint.mjs";
4
+ import { a as createMessageDeliveryTables, i as createRecoveryCheckpointTable, n as createNonterminalIndex, r as sqliteMigrations } from "./migrations-BZ89iaTY.mjs";
5
+ import { Effect, Exit, Schema } from "effect";
6
+ import { createMessageDeliveryPendingIndex } from "effect-agent/sql-message-delivery-store";
7
+ import * as SqlClient from "effect/unstable/sql/SqlClient";
8
+ import { NodeCrypto } from "@effect/platform-node";
9
+ import { SqliteMigrator } from "@effect/sql-sqlite-node";
10
+ import { EMPTY_TAIL_DIGEST } from "effect-agent/digest";
11
+ import { CanonicalRecord, CanonicalSequence, ProducerEpoch } from "effect-agent/records";
12
+ import { ScheduleFailpoint, ScheduleFailpointError } from "effect-agent/schedule";
13
+ import { checkV2ThreadLayout, upgradeV2Schedules, upgradeV2Subscriptions } from "effect-agent/sql-storage-v2-upgrade";
14
+ import { createNativeReadIndexes, indexCanonicalRecord, seedNativeReadIndexes } from "effect-agent/sql-thread-native-reads";
15
+ import { SubscriptionFailpoint, SubscriptionFailpointError } from "effect-agent/subscription";
16
+ import { CheckpointRejected, FenceRejected, MAX_THREAD_EXPORT_RECORDS, ThreadNotMaterialized } from "effect-agent/thread-store";
17
+ //#region src/internal/sqlite-journal.ts
18
+ const BoundedStoredText = Schema.String.check(Schema.isMaxLength(16777216));
19
+ const BoundedIdentifier = Schema.NonEmptyString.check(Schema.isMaxLength(1024));
20
+ const NonNegativeInt = Schema.Int.check(Schema.isGreaterThanOrEqualTo(0));
21
+ const MAX_RECORDS_PER_THREAD = MAX_THREAD_EXPORT_RECORDS;
22
+ const ZERO_SEQUENCE = Schema.decodeSync(CanonicalSequence)(0);
23
+ const MAX_STORED_TEXT_BYTES = 16777216;
24
+ const MAX_IDENTIFIER_LENGTH = 1024;
25
+ const storedTextBytes = (value) => new TextEncoder().encode(value).byteLength;
26
+ var SqliteVersionRow = class extends Schema.Class("SqliteVersionRow")({ user_version: NonNegativeInt }) {};
27
+ var SqliteJournalModeRow = class extends Schema.Class("SqliteJournalModeRow")({ journal_mode: Schema.NonEmptyString.check(Schema.isMaxLength(32)) }) {};
28
+ var SqliteNameRow = class extends Schema.Class("SqliteNameRow")({ name: BoundedIdentifier }) {};
29
+ var ThreadRow = class extends Schema.Class("ThreadRow")({
30
+ thread_id: BoundedIdentifier,
31
+ created_at: Schema.NonEmptyString.check(Schema.isMaxLength(128)),
32
+ producer_epoch: ProducerEpoch,
33
+ tail_digest: BoundedStoredText,
34
+ tail_sequence: CanonicalSequence
35
+ }) {};
36
+ var BatchRow = class extends Schema.Class("BatchRow")({
37
+ batch_digest: BoundedStoredText,
38
+ batch_id: BoundedIdentifier,
39
+ batch_json: BoundedStoredText,
40
+ thread_id: BoundedIdentifier,
41
+ first_sequence: CanonicalSequence,
42
+ last_sequence: CanonicalSequence,
43
+ tail_digest: BoundedStoredText
44
+ }) {};
45
+ var RecordRow = class extends Schema.Class("RecordRow")({
46
+ batch_id: BoundedIdentifier,
47
+ thread_id: BoundedIdentifier,
48
+ record_id: BoundedIdentifier,
49
+ record_json: BoundedStoredText,
50
+ sequence: CanonicalSequence
51
+ }) {};
52
+ var CheckpointRow = class extends Schema.Class("CheckpointRow")({
53
+ checkpoint_json: BoundedStoredText,
54
+ thread_id: BoundedIdentifier,
55
+ tail_digest: BoundedStoredText,
56
+ through_sequence: CanonicalSequence
57
+ }) {};
58
+ var RawRecord = class extends Schema.Class("@effect-agent/storage-sqlite/RawRecord")({
59
+ recordId: BoundedIdentifier,
60
+ recordJson: BoundedStoredText
61
+ }) {};
62
+ var RawAppendRequest = class extends Schema.Class("@effect-agent/storage-sqlite/RawAppendRequest")({
63
+ batchDigest: BoundedStoredText,
64
+ batchId: BoundedIdentifier,
65
+ batchJson: BoundedStoredText,
66
+ threadId: BoundedIdentifier,
67
+ expectedTailDigest: BoundedStoredText,
68
+ expectedTailSequence: CanonicalSequence,
69
+ producerEpoch: ProducerEpoch,
70
+ records: Schema.NonEmptyArray(RawRecord).check(Schema.isMaxLength(256)),
71
+ tailDigest: BoundedStoredText
72
+ }) {};
73
+ var RawAppendResult = class extends Schema.Class("@effect-agent/storage-sqlite/RawAppendResult")({
74
+ firstSequence: CanonicalSequence,
75
+ lastSequence: CanonicalSequence,
76
+ replayed: Schema.Boolean,
77
+ tailDigest: BoundedStoredText
78
+ }) {};
79
+ var RawReadRequest = class extends Schema.Class("@effect-agent/storage-sqlite/RawReadRequest")({
80
+ threadId: BoundedIdentifier,
81
+ fromSequenceExclusive: CanonicalSequence,
82
+ limit: Schema.Int.check(Schema.isGreaterThan(0), Schema.isLessThanOrEqualTo(1024))
83
+ }) {};
84
+ var RawCheckpoint = class extends Schema.Class("@effect-agent/storage-sqlite/RawCheckpoint")({
85
+ checkpointJson: BoundedStoredText,
86
+ threadId: BoundedIdentifier,
87
+ tailDigest: BoundedStoredText,
88
+ throughSequence: CanonicalSequence
89
+ }) {};
90
+ var RawThreadExport = class extends Schema.Class("@effect-agent/storage-sqlite/RawThreadExport")({
91
+ thread: ThreadRow,
92
+ records: Schema.Array(RecordRow)
93
+ }) {};
94
+ const storageError = (operation) => (error) => SqliteStorageError.make({
95
+ cause: error,
96
+ operation,
97
+ message: error.message
98
+ });
99
+ /** Decode raw SQLite rows against a Schema, reporting failures as typed corruption. */
100
+ const decodeRows = Effect.fn("SqliteJournal.decodeRows")((schema, table, rowKey, rows) => Schema.decodeUnknownEffect(schema)(rows).pipe(Effect.mapError((error) => SqliteStorageCorruptionError.make({
101
+ table,
102
+ rowKey,
103
+ message: String(error)
104
+ }))));
105
+ /** Decode exactly one raw SQLite row against a Schema, reporting failures as typed corruption. */
106
+ const decodeSingleRow = Effect.fn("SqliteJournal.decodeSingleRow")((schema, table, rowKey, rows) => decodeRows(schema, table, rowKey, rows).pipe(Effect.flatMap((decoded) => decoded.length === 1 ? Effect.succeed(decoded[0]) : Effect.fail(SqliteStorageCorruptionError.make({
107
+ table,
108
+ rowKey,
109
+ message: `Expected exactly one row but found ${decoded.length}.`
110
+ })))));
111
+ /** Column inventory of the supported v8 predecessor, independent of physical column order. */
112
+ const predecessorColumns = {
113
+ effect_agent_threads: [
114
+ "thread_id",
115
+ "created_at",
116
+ "tail_sequence",
117
+ "tail_digest",
118
+ "producer_epoch"
119
+ ],
120
+ effect_agent_canonical_batches: [
121
+ "thread_id",
122
+ "batch_id",
123
+ "first_sequence",
124
+ "last_sequence",
125
+ "batch_digest",
126
+ "tail_digest",
127
+ "batch_json"
128
+ ],
129
+ effect_agent_canonical_records: [
130
+ "thread_id",
131
+ "sequence",
132
+ "record_id",
133
+ "batch_id",
134
+ "record_json"
135
+ ],
136
+ effect_agent_checkpoints: [
137
+ "thread_id",
138
+ "through_sequence",
139
+ "tail_digest",
140
+ "checkpoint_json"
141
+ ],
142
+ effect_agent_submissions: [
143
+ "submission_id",
144
+ "thread_id",
145
+ "queue_sequence",
146
+ "principal",
147
+ "idempotency_key",
148
+ "agent_id",
149
+ "agent_digests_json",
150
+ "deployment_id",
151
+ "input_json",
152
+ "input_digest",
153
+ "receipt_id",
154
+ "state",
155
+ "settled_outcome",
156
+ "created_at",
157
+ "ready_at",
158
+ "input_applied_record_id",
159
+ "input_applied_sequence",
160
+ "joined_host_submission_id",
161
+ "suspended_reason_json",
162
+ "suspended_at",
163
+ "unknown_reason",
164
+ "unknown_tool_call_ids_json",
165
+ "parent_submission_id",
166
+ "parent_tool_call_id",
167
+ "admission_group",
168
+ "admission_fence_json"
169
+ ],
170
+ effect_agent_submission_ownership: [
171
+ "submission_id",
172
+ "attempt_id",
173
+ "ownership_token",
174
+ "producer_epoch",
175
+ "owner_producer_id",
176
+ "lease_expires_at"
177
+ ],
178
+ effect_agent_attempts: [
179
+ "attempt_id",
180
+ "submission_id",
181
+ "thread_id",
182
+ "owner_producer_id",
183
+ "producer_epoch",
184
+ "claimed_at"
185
+ ],
186
+ effect_agent_settlement_reservations: [
187
+ "submission_id",
188
+ "settlement_id",
189
+ "outcome",
190
+ "record_id",
191
+ "record_json",
192
+ "record_digest",
193
+ "reserved_at",
194
+ "finalized_at"
195
+ ],
196
+ effect_agent_abort_intents: [
197
+ "submission_id",
198
+ "author",
199
+ "reason",
200
+ "requested_at",
201
+ "canonical_record_id"
202
+ ],
203
+ effect_agent_approval_decisions: [
204
+ "submission_id",
205
+ "tool_call_id",
206
+ "decision",
207
+ "resolver",
208
+ "reason",
209
+ "decided_at"
210
+ ],
211
+ effect_agent_unknown_resolutions: [
212
+ "submission_id",
213
+ "tool_call_id",
214
+ "author",
215
+ "reason",
216
+ "resolution_json",
217
+ "resolved_at"
218
+ ],
219
+ effect_agent_child_reservations: [
220
+ "reservation_id",
221
+ "parent_submission_id",
222
+ "parent_tool_call_id",
223
+ "child_submission_id",
224
+ "status",
225
+ "allocation_json",
226
+ "allocation_digest",
227
+ "accounting_json",
228
+ "reserved_at",
229
+ "release_began_at",
230
+ "released_at"
231
+ ],
232
+ effect_agent_schedules: [
233
+ "tenant_id",
234
+ "owner_id",
235
+ "schedule_id",
236
+ "deadline_at_millis",
237
+ "record_json"
238
+ ],
239
+ effect_agent_subscription_sequences: [
240
+ "tenant_id",
241
+ "source_address",
242
+ "sequence",
243
+ "event_scan_cursor",
244
+ "delivery_scan_cursor",
245
+ "recovery_scan_cursor"
246
+ ],
247
+ effect_agent_subscriptions: [
248
+ "tenant_id",
249
+ "source_address",
250
+ "owner_id",
251
+ "subscription_id",
252
+ "ordinal",
253
+ "source_name",
254
+ "source_version",
255
+ "matching_key",
256
+ "state",
257
+ "expires_at_millis",
258
+ "recovery_at_millis",
259
+ "recovery_present",
260
+ "record_json"
261
+ ],
262
+ effect_agent_subscription_events: [
263
+ "tenant_id",
264
+ "source_address",
265
+ "event_id",
266
+ "source_name",
267
+ "source_version",
268
+ "matching_key",
269
+ "payload_digest",
270
+ "cutoff",
271
+ "cursor",
272
+ "routing_complete",
273
+ "next_attempt_at_millis",
274
+ "record_json",
275
+ "tombstone"
276
+ ],
277
+ effect_agent_subscription_deliveries: [
278
+ "tenant_id",
279
+ "source_address",
280
+ "owner_id",
281
+ "subscription_id",
282
+ "event_id",
283
+ "delivery_key",
284
+ "state",
285
+ "next_attempt_at_millis",
286
+ "record_json"
287
+ ]
288
+ };
289
+ const checkPredecessorLayout = Effect.fn("SqliteJournal.checkPredecessorLayout")(function* (version) {
290
+ const sql = yield* SqlClient.SqlClient;
291
+ const expectedColumns = {
292
+ ...version === 8 ? predecessorColumns : {
293
+ ...predecessorColumns,
294
+ effect_agent_submissions: [
295
+ ...predecessorColumns.effect_agent_submissions,
296
+ "worker_admission_json",
297
+ "message_admission_json"
298
+ ],
299
+ effect_agent_message_deliveries: [
300
+ "owner_thread_id",
301
+ "message_id",
302
+ "version",
303
+ "state",
304
+ "deadline_at_millis",
305
+ "record_json"
306
+ ]
307
+ },
308
+ ...version === 10 ? { effect_agent_recovery_checkpoints: [
309
+ "thread_id",
310
+ "through_sequence",
311
+ "tail_digest",
312
+ "checkpoint_json"
313
+ ] } : {}
314
+ };
315
+ for (const [table, expected] of Object.entries(expectedColumns)) {
316
+ const columns = yield* decodeRows(Schema.Array(Schema.Struct({ name: BoundedIdentifier })), table, "schema", yield* sql.unsafe(`PRAGMA table_info(${table})`));
317
+ const names = new Set(expected);
318
+ if (columns.length !== names.size || columns.some((column) => !names.has(column.name))) return yield* SqliteStorageCompatibilityError.make({
319
+ actualVersion: version,
320
+ supportedVersion: 12,
321
+ message: `The v${version} ${table} columns do not match the supported predecessor; no upgrade was committed.`
322
+ });
323
+ }
324
+ });
325
+ const initializeSqliteJournal = Effect.fn("SqliteJournal.initialize")(function* () {
326
+ const sql = yield* SqlClient.SqlClient;
327
+ const { hit: failpoint } = yield* SqliteStorageFailpoint;
328
+ const { busyTimeout } = yield* SqliteStorageConfig;
329
+ yield* sql`PRAGMA foreign_keys = ON`.pipe(Effect.mapError(storageError("enable foreign keys")));
330
+ yield* sql.unsafe(`PRAGMA busy_timeout = ${busyTimeout}`).pipe(Effect.mapError(storageError("configure busy timeout")));
331
+ const journalModeRows = yield* sql`PRAGMA journal_mode`.pipe(Effect.mapError(storageError("read journal mode")));
332
+ const journalMode = yield* decodeSingleRow(Schema.Array(SqliteJournalModeRow), "pragma_journal_mode", "singleton", journalModeRows);
333
+ if (journalMode.journal_mode.toLowerCase() !== "wal") return yield* SqliteStorageCompatibilityError.make({
334
+ actualVersion: 0,
335
+ supportedVersion: 12,
336
+ message: `SQLite WAL mode is required; the database reported ${journalMode.journal_mode}.`
337
+ });
338
+ const versionRows = yield* sql`PRAGMA user_version`.pipe(Effect.mapError(storageError("read storage version")));
339
+ const version = yield* decodeSingleRow(Schema.Array(SqliteVersionRow), "pragma_user_version", "singleton", versionRows);
340
+ if (version.user_version !== 0 && version.user_version !== 7 && version.user_version !== 8 && version.user_version !== 9 && version.user_version !== 10 && version.user_version !== 11 && version.user_version !== 12) return yield* SqliteStorageCompatibilityError.make({
341
+ actualVersion: version.user_version,
342
+ supportedVersion: 12,
343
+ message: `The SQLite file uses unsupported storage version ${version.user_version}; this build supports exactly version 12. Only supported v7, v8, v9, v10 and v11 can be upgraded automatically. Keep the original file and use a compatible library version.`
344
+ });
345
+ if (version.user_version === 7 || version.user_version === 8 || version.user_version === 9 || version.user_version === 10) yield* sql.withTransaction(Effect.gen(function* () {
346
+ const current = yield* sql`PRAGMA user_version`;
347
+ if (current.length === 1 && current[0].user_version === 12) return;
348
+ if (current.length !== 1 || current[0].user_version !== 7 && current[0].user_version !== 8 && current[0].user_version !== 9 && current[0].user_version !== 10) return yield* SqliteStorageCompatibilityError.make({
349
+ actualVersion: -1,
350
+ supportedVersion: 12,
351
+ message: "Storage version changed while acquiring the upgrade transaction."
352
+ });
353
+ if ((yield* sql`SELECT name FROM sqlite_master WHERE type='table' AND name IN (
354
+ 'effect_agent_threads', 'effect_agent_canonical_batches', 'effect_agent_canonical_records',
355
+ 'effect_agent_checkpoints', 'effect_agent_submissions', 'effect_agent_submission_ownership',
356
+ 'effect_agent_attempts', 'effect_agent_settlement_reservations', 'effect_agent_abort_intents',
357
+ 'effect_agent_approval_decisions', 'effect_agent_unknown_resolutions', 'effect_agent_schedules'
358
+ )`).length !== 12) return yield* SqliteStorageCompatibilityError.make({
359
+ actualVersion: current[0].user_version,
360
+ supportedVersion: 12,
361
+ message: "The predecessor store is missing required tables; no upgrade was committed."
362
+ });
363
+ if ((yield* sql`SELECT name FROM sqlite_master WHERE type='table' AND name='effect_agent_recovery_checkpoints'`).length !== (current[0].user_version === 10 ? 1 : 0)) return yield* SqliteStorageCompatibilityError.make({
364
+ actualVersion: current[0].user_version,
365
+ supportedVersion: 12,
366
+ message: "The predecessor recovery checkpoint storage does not match its version; refusing ambiguous data without mutation."
367
+ });
368
+ if ((yield* sql`SELECT name FROM sqlite_master WHERE name='effect_agent_submissions_nonterminal'`).length !== 0) return yield* SqliteStorageCompatibilityError.make({
369
+ actualVersion: current[0].user_version,
370
+ supportedVersion: 12,
371
+ message: "The predecessor already contains the nonterminal index; refusing ambiguous storage without mutation."
372
+ });
373
+ if (current[0].user_version === 7) {
374
+ yield* checkV2ThreadLayout();
375
+ for (const statement of [
376
+ sql`ALTER TABLE effect_agent_submissions ADD COLUMN admission_group TEXT`,
377
+ sql`ALTER TABLE effect_agent_submissions ADD COLUMN admission_fence_json TEXT`,
378
+ sql`CREATE INDEX effect_agent_submissions_group ON effect_agent_submissions (thread_id, admission_group, state)`
379
+ ]) {
380
+ yield* failpoint("upgrade:before-mutation");
381
+ yield* statement;
382
+ yield* failpoint("upgrade:after-mutation");
383
+ }
384
+ yield* upgradeV2Schedules(16777216).pipe(Effect.provideService(ScheduleFailpoint, { hit: (point) => Schema.decodeUnknownEffect(SqliteStorageFailpointLocation)(point).pipe(Effect.flatMap(failpoint), Effect.mapError(() => ScheduleFailpointError.make({ point }))) }));
385
+ yield* upgradeV2Subscriptions(16777216).pipe(Effect.provideService(SubscriptionFailpoint, { hit: (point) => Schema.decodeUnknownEffect(SqliteStorageFailpointLocation)(point).pipe(Effect.flatMap(failpoint), Effect.mapError(() => SubscriptionFailpointError.make({ point }))) }));
386
+ }
387
+ if (current[0].user_version === 8 || current[0].user_version === 9 || current[0].user_version === 10) yield* checkPredecessorLayout(current[0].user_version);
388
+ if (current[0].user_version === 7 || current[0].user_version === 8) {
389
+ yield* failpoint("upgrade:before-mutation");
390
+ yield* sql`ALTER TABLE effect_agent_submissions ADD COLUMN worker_admission_json TEXT`;
391
+ yield* failpoint("upgrade:after-mutation");
392
+ yield* failpoint("upgrade:before-mutation");
393
+ yield* sql`ALTER TABLE effect_agent_submissions ADD COLUMN message_admission_json TEXT`;
394
+ yield* failpoint("upgrade:after-mutation");
395
+ yield* failpoint("upgrade:before-mutation");
396
+ yield* createMessageDeliveryTables;
397
+ yield* failpoint("upgrade:after-mutation");
398
+ }
399
+ if (current[0].user_version !== 10) {
400
+ yield* failpoint("upgrade:before-mutation");
401
+ yield* createRecoveryCheckpointTable;
402
+ yield* failpoint("upgrade:after-mutation");
403
+ }
404
+ yield* failpoint("upgrade:before-mutation");
405
+ yield* createNonterminalIndex;
406
+ yield* failpoint("upgrade:after-mutation");
407
+ yield* failpoint("upgrade:before-version");
408
+ yield* createNativeReadIndexes;
409
+ yield* createMessageDeliveryPendingIndex;
410
+ yield* seedNativeReadIndexes.pipe(Effect.catchTag("ThreadStoreError", (error) => SqliteStorageCorruptionError.make({
411
+ table: "effect_agent_canonical_records",
412
+ rowKey: "upgrade",
413
+ message: error.message
414
+ })));
415
+ yield* sql`PRAGMA user_version = 12`;
416
+ yield* failpoint("upgrade:after-version");
417
+ })).pipe(Effect.provide(NodeCrypto.layer), Effect.catchTag("SqliteStorageFailpointError", (error) => SqliteStorageError.make({
418
+ cause: error,
419
+ operation: "upgrade storage",
420
+ message: error.message
421
+ })), Effect.catchTag(["ScheduleFailpointError", "SubscriptionFailpointError"], (error) => SqliteStorageError.make({
422
+ cause: error,
423
+ operation: "upgrade storage",
424
+ message: "Injected storage upgrade failure"
425
+ })), Effect.catchTag("StorageUpgradeError", (error) => SqliteStorageCorruptionError.make({
426
+ table: error.table,
427
+ rowKey: error.rowKey,
428
+ message: error.message
429
+ })), Effect.catchTag("SqlError", storageError("upgrade supported storage")), Effect.catchTag("SchemaError", (error) => SqliteStorageCorruptionError.make({
430
+ table: "upgrade",
431
+ rowKey: "v7",
432
+ message: error.message
433
+ })));
434
+ if (version.user_version === 0) {
435
+ const existingRows = yield* sql`
436
+ SELECT name
437
+ FROM sqlite_master
438
+ WHERE type = 'table'
439
+ AND name LIKE 'effect_agent_%'
440
+ ORDER BY name
441
+ `.pipe(Effect.mapError(storageError("inspect unversioned storage")));
442
+ if ((yield* decodeRows(Schema.Array(SqliteNameRow), "sqlite_master", "effect_agent_%", existingRows)).length > 0) return yield* SqliteStorageCompatibilityError.make({
443
+ actualVersion: 0,
444
+ supportedVersion: 12,
445
+ message: "The SQLite file contains unversioned Effect Agent tables. Refusing to mutate ambiguous stored data; retain it for inspection with its original writer."
446
+ });
447
+ yield* SqliteMigrator.run({ loader: sqliteMigrations }).pipe(Effect.mapError((error) => SqliteStorageError.make({
448
+ cause: error,
449
+ operation: "initialize current storage",
450
+ message: error.message
451
+ })));
452
+ }
453
+ if (version.user_version === 11) yield* sql.withTransaction(Effect.gen(function* () {
454
+ const current = yield* sql`PRAGMA user_version`;
455
+ if (current[0]?.user_version === 12) return;
456
+ if (current[0]?.user_version !== 11) return yield* SqliteStorageCompatibilityError.make({
457
+ actualVersion: current[0]?.user_version ?? -1,
458
+ supportedVersion: 12,
459
+ message: "Storage version changed during native index upgrade"
460
+ });
461
+ yield* checkPredecessorLayout(10);
462
+ if ((yield* sql`SELECT name FROM sqlite_master WHERE type = 'index' AND name = 'effect_agent_submissions_nonterminal'`).length !== 1) return yield* SqliteStorageCompatibilityError.make({
463
+ actualVersion: 11,
464
+ supportedVersion: 12,
465
+ message: "Predecessor storage is missing its required nonterminal index"
466
+ });
467
+ yield* failpoint("upgrade:before-mutation");
468
+ yield* createNativeReadIndexes;
469
+ yield* createMessageDeliveryPendingIndex;
470
+ yield* seedNativeReadIndexes.pipe(Effect.catchTag("ThreadStoreError", (error) => SqliteStorageCorruptionError.make({
471
+ table: "effect_agent_canonical_records",
472
+ rowKey: "upgrade",
473
+ message: error.message
474
+ })));
475
+ yield* failpoint("upgrade:after-mutation");
476
+ yield* failpoint("upgrade:before-version");
477
+ yield* sql`PRAGMA user_version = 12`;
478
+ yield* failpoint("upgrade:after-version");
479
+ })).pipe(Effect.mapError((error) => SqliteStorageError.make({
480
+ operation: "upgrade native indexes",
481
+ message: error.message,
482
+ cause: error
483
+ })));
484
+ const requiredRows = yield* sql`
485
+ SELECT name
486
+ FROM sqlite_master
487
+ WHERE (type = 'table'
488
+ AND name IN (
489
+ 'effect_agent_threads',
490
+ 'effect_agent_canonical_batches',
491
+ 'effect_agent_canonical_records',
492
+ 'effect_agent_checkpoints',
493
+ 'effect_agent_submissions',
494
+ 'effect_agent_submission_ownership',
495
+ 'effect_agent_attempts',
496
+ 'effect_agent_settlement_reservations',
497
+ 'effect_agent_abort_intents',
498
+ 'effect_agent_approval_decisions',
499
+ 'effect_agent_unknown_resolutions',
500
+ 'effect_agent_schedules',
501
+ 'effect_agent_message_deliveries',
502
+ 'effect_agent_recovery_checkpoints'
503
+ )) 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'))
504
+ ORDER BY name
505
+ `.pipe(Effect.mapError(storageError("verify storage tables")));
506
+ if ((yield* decodeRows(Schema.Array(SqliteNameRow), "sqlite_master", "required_tables", requiredRows)).length !== 21) return yield* SqliteStorageCompatibilityError.make({
507
+ actualVersion: 12,
508
+ supportedVersion: 12,
509
+ message: "The SQLite file claims the current format but is missing required tables or its nonterminal index. Retain the original store for inspection."
510
+ });
511
+ const classifyWriteFailure = (operation) => (error) => error.reason._tag === "LockTimeoutError" ? SqliteWriteContention.make({
512
+ cause: error,
513
+ operation,
514
+ message: `Another producer holds the SQLite write lock; ${operation} is safe to retry.`
515
+ }) : storageError(operation)(error);
516
+ /**
517
+ * Runs one journal write transaction under `BEGIN IMMEDIATE`. SQLite's deferred `BEGIN`
518
+ * would let a read-then-write transaction start as a reader and fail with
519
+ * SQLITE_BUSY_SNAPSHOT on upgrade, which `busy_timeout` never retries. Taking the write
520
+ * lock up front keeps cross-owner contention inside the bounded busy retry; a lock
521
+ * timeout is classified as the retryable SqliteWriteContention. A failed `BEGIN` leaves
522
+ * no transaction, so no rollback is attempted for it.
523
+ *
524
+ * Journal write transactions are always top level. Nesting one inside another would
525
+ * deadlock the single-connection client, so new journal operations must not wrap this
526
+ * helper inside another transaction.
527
+ */
528
+ const withWriteTransaction = (operation) => (effect) => Effect.uninterruptibleMask((restore) => Effect.scoped(Effect.gen(function* () {
529
+ const connection = yield* sql.reserve.pipe(Effect.mapError(classifyWriteFailure(operation)));
530
+ yield* connection.executeUnprepared("BEGIN IMMEDIATE", [], void 0).pipe(Effect.mapError(classifyWriteFailure(operation)));
531
+ const exit = yield* restore(Effect.provideService(effect, sql.transactionService, [connection, 0])).pipe(Effect.exit);
532
+ if (Exit.isSuccess(exit)) {
533
+ yield* connection.executeUnprepared("COMMIT", [], void 0).pipe(Effect.mapError(classifyWriteFailure(operation)));
534
+ return exit.value;
535
+ }
536
+ yield* Effect.orDie(connection.executeUnprepared("ROLLBACK", [], void 0));
537
+ return yield* exit;
538
+ })).pipe(Effect.withSpan("SqliteJournal.withWriteTransaction", { attributes: { operation } })));
539
+ /**
540
+ * Runs a read-only snapshot under a deferred transaction. Effect's SQLite client now
541
+ * starts every writable-client `withTransaction` with `BEGIN IMMEDIATE`, which is the
542
+ * right default for mutations but would make exports take the write lock and block a
543
+ * concurrent append. Reserving the connection and beginning explicitly preserves the
544
+ * adapter's snapshot-with-concurrent-writer contract. As with the write helper, a failed
545
+ * `BEGIN` is reported directly because there is no transaction to roll back.
546
+ */
547
+ const withReadTransaction = (operation) => (effect) => Effect.uninterruptibleMask((restore) => Effect.scoped(Effect.gen(function* () {
548
+ const connection = yield* sql.reserve.pipe(Effect.mapError(storageError(operation)));
549
+ yield* connection.executeUnprepared("BEGIN", [], void 0).pipe(Effect.mapError(storageError(operation)));
550
+ const exit = yield* restore(Effect.provideService(effect, sql.transactionService, [connection, 0])).pipe(Effect.exit);
551
+ if (Exit.isSuccess(exit)) {
552
+ yield* connection.executeUnprepared("COMMIT", [], void 0).pipe(Effect.mapError(storageError(operation)));
553
+ return exit.value;
554
+ }
555
+ yield* Effect.orDie(connection.executeUnprepared("ROLLBACK", [], void 0));
556
+ return yield* exit;
557
+ })).pipe(Effect.withSpan("SqliteJournal.withReadTransaction", { attributes: { operation } })));
558
+ const materialize = Effect.fn("SqliteJournal.materialize")(function* (threadId, createdAt, emptyTailDigest, producerEpoch) {
559
+ if (threadId.length > MAX_IDENTIFIER_LENGTH || storedTextBytes(emptyTailDigest) > MAX_STORED_TEXT_BYTES) return yield* SqliteStorageError.make({
560
+ operation: "materialize thread",
561
+ message: "Thread identity or initial digest exceeds the SQLite storage bounds."
562
+ });
563
+ yield* withWriteTransaction("materialize transaction")(Effect.gen(function* () {
564
+ const existingRows = yield* sql`
565
+ SELECT
566
+ thread_id,
567
+ created_at,
568
+ tail_sequence,
569
+ tail_digest,
570
+ producer_epoch
571
+ FROM effect_agent_threads
572
+ WHERE thread_id = ${threadId}
573
+ `.pipe(Effect.mapError(storageError("read materialized thread")));
574
+ const existing = yield* decodeRows(Schema.Array(ThreadRow), "effect_agent_threads", threadId, existingRows);
575
+ if (existing.length > 1) return yield* SqliteStorageCorruptionError.make({
576
+ table: "effect_agent_threads",
577
+ rowKey: threadId,
578
+ message: "A thread primary key returned more than one row."
579
+ });
580
+ if (existing.length === 0) {
581
+ yield* sql`
582
+ INSERT INTO effect_agent_threads (
583
+ thread_id,
584
+ created_at,
585
+ tail_sequence,
586
+ tail_digest,
587
+ producer_epoch
588
+ ) VALUES (
589
+ ${threadId},
590
+ ${createdAt},
591
+ 0,
592
+ ${emptyTailDigest},
593
+ ${producerEpoch}
594
+ )
595
+ `.pipe(Effect.mapError(storageError("materialize thread")));
596
+ return;
597
+ }
598
+ if (producerEpoch < existing[0].producer_epoch) return yield* SqliteFenceRejected.make({
599
+ producerEpoch,
600
+ actualEpoch: existing[0].producer_epoch,
601
+ message: `Producer epoch ${producerEpoch} is stale; current epoch is ${existing[0].producer_epoch}.`
602
+ });
603
+ if (producerEpoch > existing[0].producer_epoch) yield* sql`
604
+ UPDATE effect_agent_threads
605
+ SET producer_epoch = ${producerEpoch}
606
+ WHERE thread_id = ${threadId}
607
+ `.pipe(Effect.mapError(storageError("advance materialization epoch")));
608
+ }));
609
+ });
610
+ const getThread = Effect.fn("SqliteJournal.getThread")(function* (threadId) {
611
+ const rows = yield* sql`
612
+ SELECT
613
+ thread_id,
614
+ created_at,
615
+ tail_sequence,
616
+ tail_digest,
617
+ producer_epoch
618
+ FROM effect_agent_threads
619
+ WHERE thread_id = ${threadId}
620
+ `.pipe(Effect.mapError(storageError("read thread")));
621
+ return yield* decodeRows(Schema.Array(ThreadRow), "effect_agent_threads", threadId, rows);
622
+ });
623
+ const append = Effect.fn("SqliteJournal.append")(function* (request) {
624
+ if (request.threadId.length > MAX_IDENTIFIER_LENGTH || request.batchId.length > MAX_IDENTIFIER_LENGTH || storedTextBytes(request.batchJson) > MAX_STORED_TEXT_BYTES || storedTextBytes(request.batchDigest) > MAX_STORED_TEXT_BYTES || storedTextBytes(request.tailDigest) > MAX_STORED_TEXT_BYTES || request.records.some((record) => record.recordId.length > MAX_IDENTIFIER_LENGTH || storedTextBytes(record.recordJson) > MAX_STORED_TEXT_BYTES)) return yield* SqliteStorageError.make({
625
+ operation: "append canonical batch",
626
+ message: "Canonical identifiers or encoded JSON exceed the SQLite storage bounds."
627
+ });
628
+ return yield* withWriteTransaction("append transaction")(Effect.gen(function* () {
629
+ const recordIds = request.records.map((record) => record.recordId);
630
+ if (new Set(recordIds).size !== recordIds.length) return yield* SqliteAppendConflict.make({
631
+ message: `Batch ${request.batchId} contains duplicate canonical record IDs.`,
632
+ reason: "record-identity"
633
+ });
634
+ const threadRows = yield* sql`
635
+ SELECT
636
+ thread_id,
637
+ created_at,
638
+ tail_sequence,
639
+ tail_digest,
640
+ producer_epoch
641
+ FROM effect_agent_threads
642
+ WHERE thread_id = ${request.threadId}
643
+ `.pipe(Effect.mapError(storageError("read append tail")));
644
+ const thread = yield* decodeSingleRow(Schema.Array(ThreadRow), "effect_agent_threads", request.threadId, threadRows);
645
+ if (request.producerEpoch !== thread.producer_epoch) return yield* SqliteFenceRejected.make({
646
+ producerEpoch: request.producerEpoch,
647
+ actualEpoch: thread.producer_epoch,
648
+ message: `Producer epoch ${request.producerEpoch} is not the current epoch ${thread.producer_epoch}.`
649
+ });
650
+ const batchRows = yield* sql`
651
+ SELECT
652
+ thread_id,
653
+ batch_id,
654
+ first_sequence,
655
+ last_sequence,
656
+ batch_digest,
657
+ tail_digest,
658
+ batch_json
659
+ FROM effect_agent_canonical_batches
660
+ WHERE thread_id = ${request.threadId}
661
+ AND batch_id = ${request.batchId}
662
+ `.pipe(Effect.mapError(storageError("read idempotent batch")));
663
+ const batches = yield* decodeRows(Schema.Array(BatchRow), "effect_agent_canonical_batches", `${request.threadId}/${request.batchId}`, batchRows);
664
+ if (batches.length > 1) return yield* SqliteStorageCorruptionError.make({
665
+ table: "effect_agent_canonical_batches",
666
+ rowKey: `${request.threadId}/${request.batchId}`,
667
+ message: "A canonical batch primary key returned more than one row."
668
+ });
669
+ if (batches.length === 1) {
670
+ const existing = batches[0];
671
+ if (existing.batch_digest !== request.batchDigest) return yield* SqliteAppendConflict.make({
672
+ message: `Batch ${request.batchId} already exists with different canonical content.`,
673
+ reason: "batch-digest"
674
+ });
675
+ return RawAppendResult.make({
676
+ firstSequence: existing.first_sequence,
677
+ lastSequence: existing.last_sequence,
678
+ replayed: true,
679
+ tailDigest: existing.tail_digest
680
+ });
681
+ }
682
+ if (request.expectedTailSequence !== thread.tail_sequence || request.expectedTailDigest !== thread.tail_digest) return yield* SqliteAppendConflict.make({
683
+ message: `Expected tail ${request.expectedTailSequence}/${request.expectedTailDigest} but found ${thread.tail_sequence}/${thread.tail_digest}.`,
684
+ reason: "tail",
685
+ actualTailSequence: thread.tail_sequence,
686
+ actualTailDigest: thread.tail_digest
687
+ });
688
+ if (thread.tail_sequence + request.records.length > MAX_RECORDS_PER_THREAD) return yield* SqliteStorageError.make({
689
+ operation: "append canonical batch",
690
+ message: `Thread record limit ${MAX_RECORDS_PER_THREAD} would be exceeded.`
691
+ });
692
+ const existingRecordRows = yield* sql`
693
+ SELECT
694
+ thread_id,
695
+ sequence,
696
+ record_id,
697
+ batch_id,
698
+ record_json
699
+ FROM effect_agent_canonical_records
700
+ WHERE thread_id = ${request.threadId}
701
+ AND record_id IN ${sql.in(recordIds)}
702
+ ORDER BY sequence
703
+ `.pipe(Effect.mapError(storageError("check canonical record identities")));
704
+ const existingRecords = yield* decodeRows(Schema.Array(RecordRow), "effect_agent_canonical_records", `${request.threadId}/record_ids`, existingRecordRows);
705
+ if (existingRecords.length > 0) return yield* SqliteAppendConflict.make({
706
+ message: `Canonical record ID ${existingRecords[0].record_id} already exists.`,
707
+ reason: "record-identity"
708
+ });
709
+ const firstSequence = yield* Schema.decodeEffect(CanonicalSequence)(thread.tail_sequence + 1).pipe(Effect.mapError((error) => SqliteStorageError.make({
710
+ cause: error,
711
+ operation: "append canonical batch",
712
+ message: error.message
713
+ })));
714
+ const lastSequence = yield* Schema.decodeEffect(CanonicalSequence)(firstSequence + request.records.length - 1).pipe(Effect.mapError((error) => SqliteStorageError.make({
715
+ cause: error,
716
+ operation: "append canonical batch",
717
+ message: error.message
718
+ })));
719
+ yield* sql`
720
+ INSERT INTO effect_agent_canonical_batches (
721
+ thread_id,
722
+ batch_id,
723
+ first_sequence,
724
+ last_sequence,
725
+ batch_digest,
726
+ tail_digest,
727
+ batch_json
728
+ ) VALUES (
729
+ ${request.threadId},
730
+ ${request.batchId},
731
+ ${firstSequence},
732
+ ${lastSequence},
733
+ ${request.batchDigest},
734
+ ${request.tailDigest},
735
+ ${request.batchJson}
736
+ )
737
+ `.pipe(Effect.mapError(storageError("insert canonical batch")));
738
+ yield* failpoint("append:after-batch-insert");
739
+ yield* Effect.forEach(request.records, (record, index) => Effect.gen(function* () {
740
+ yield* sql`
741
+ INSERT INTO effect_agent_canonical_records (
742
+ thread_id,
743
+ sequence,
744
+ record_id,
745
+ batch_id,
746
+ record_json
747
+ ) VALUES (
748
+ ${request.threadId},
749
+ ${firstSequence + index},
750
+ ${record.recordId},
751
+ ${request.batchId},
752
+ ${record.recordJson}
753
+ )
754
+ `.pipe(Effect.mapError(storageError("insert canonical record")));
755
+ const canonical = yield* Schema.decodeEffect(Schema.fromJsonString(CanonicalRecord))(record.recordJson).pipe(Effect.mapError((error) => SqliteStorageCorruptionError.make({
756
+ table: "effect_agent_canonical_records",
757
+ rowKey: record.recordId,
758
+ message: error.message
759
+ })));
760
+ yield* indexCanonicalRecord(request.threadId, canonical).pipe(Effect.provideService(SqlClient.SqlClient, sql), Effect.mapError(storageError("index canonical record")));
761
+ yield* failpoint("append:after-record-insert");
762
+ }), { discard: true });
763
+ yield* sql`
764
+ UPDATE effect_agent_threads
765
+ SET
766
+ tail_sequence = ${lastSequence},
767
+ tail_digest = ${request.tailDigest},
768
+ producer_epoch = ${request.producerEpoch}
769
+ WHERE thread_id = ${request.threadId}
770
+ `.pipe(Effect.mapError(storageError("advance thread tail")));
771
+ yield* failpoint("append:after-tail-update");
772
+ return RawAppendResult.make({
773
+ firstSequence,
774
+ lastSequence,
775
+ replayed: false,
776
+ tailDigest: request.tailDigest
777
+ });
778
+ }));
779
+ });
780
+ const read = Effect.fn("SqliteJournal.read")(function* (request) {
781
+ const rows = yield* sql`
782
+ SELECT
783
+ thread_id,
784
+ sequence,
785
+ record_id,
786
+ batch_id,
787
+ record_json
788
+ FROM effect_agent_canonical_records
789
+ WHERE thread_id = ${request.threadId}
790
+ AND sequence > ${request.fromSequenceExclusive}
791
+ ORDER BY sequence
792
+ LIMIT ${request.limit}
793
+ `.pipe(Effect.mapError(storageError("read canonical records")));
794
+ return yield* decodeRows(Schema.Array(RecordRow), "effect_agent_canonical_records", `${request.threadId}>${request.fromSequenceExclusive}`, rows);
795
+ });
796
+ const exportThread = Effect.fn("SqliteJournal.exportThread")(function* (threadId) {
797
+ return yield* withReadTransaction("export transaction")(Effect.gen(function* () {
798
+ const threadRows = yield* sql`
799
+ SELECT
800
+ thread_id,
801
+ created_at,
802
+ tail_sequence,
803
+ tail_digest,
804
+ producer_epoch
805
+ FROM effect_agent_threads
806
+ WHERE thread_id = ${threadId}
807
+ `.pipe(Effect.mapError(storageError("export thread")));
808
+ const thread = yield* decodeSingleRow(Schema.Array(ThreadRow), "effect_agent_threads", threadId, threadRows);
809
+ yield* failpoint("export:after-thread-read");
810
+ if (thread.tail_sequence > MAX_RECORDS_PER_THREAD) return yield* SqliteStorageError.make({
811
+ operation: "export thread",
812
+ message: "The thread exceeds the current export record limit."
813
+ });
814
+ const records = [];
815
+ let afterSequence = ZERO_SEQUENCE;
816
+ while (afterSequence < thread.tail_sequence) {
817
+ const limit = Math.min(1024, thread.tail_sequence - afterSequence);
818
+ const request = RawReadRequest.make({
819
+ threadId,
820
+ fromSequenceExclusive: afterSequence,
821
+ limit
822
+ });
823
+ const page = yield* read(request);
824
+ if (page.length !== limit || page.some((record, index) => record.sequence !== afterSequence + index + 1)) return yield* SqliteStorageCorruptionError.make({
825
+ table: "effect_agent_canonical_records",
826
+ rowKey: threadId,
827
+ message: "The exported canonical prefix is not contiguous through its captured tail."
828
+ });
829
+ records.push(...page);
830
+ afterSequence = page[page.length - 1].sequence;
831
+ }
832
+ if ((yield* sql`SELECT sequence FROM effect_agent_canonical_records WHERE thread_id=${threadId} AND sequence > ${thread.tail_sequence} LIMIT 1`.pipe(Effect.mapError(storageError("verify export tail")))).length !== 0) return yield* SqliteStorageCorruptionError.make({
833
+ table: "effect_agent_canonical_records",
834
+ rowKey: threadId,
835
+ message: "Canonical records exist beyond the captured thread tail."
836
+ });
837
+ return RawThreadExport.make({
838
+ thread,
839
+ records
840
+ });
841
+ }));
842
+ });
843
+ const saveCheckpoint = Effect.fn("SqliteJournal.saveCheckpoint")(function* (checkpoint) {
844
+ if (checkpoint.threadId.length > MAX_IDENTIFIER_LENGTH || storedTextBytes(checkpoint.checkpointJson) > MAX_STORED_TEXT_BYTES) return yield* SqliteStorageError.make({
845
+ operation: "save checkpoint",
846
+ message: "Checkpoint identity or encoded JSON exceeds the SQLite storage bounds."
847
+ });
848
+ yield* withWriteTransaction("checkpoint transaction")(Effect.gen(function* () {
849
+ const threadRows = yield* sql`
850
+ SELECT
851
+ thread_id,
852
+ created_at,
853
+ tail_sequence,
854
+ tail_digest,
855
+ producer_epoch
856
+ FROM effect_agent_threads
857
+ WHERE thread_id = ${checkpoint.threadId}
858
+ `.pipe(Effect.mapError(storageError("read checkpoint tail")));
859
+ const thread = yield* decodeSingleRow(Schema.Array(ThreadRow), "effect_agent_threads", checkpoint.threadId, threadRows);
860
+ if (checkpoint.throughSequence > thread.tail_sequence) return yield* SqliteCheckpointConflict.make({ message: `Checkpoint sequence ${checkpoint.throughSequence} is after canonical tail ${thread.tail_sequence}.` });
861
+ const checkpointRows = yield* sql`
862
+ SELECT
863
+ thread_id,
864
+ through_sequence,
865
+ tail_digest,
866
+ checkpoint_json
867
+ FROM effect_agent_checkpoints
868
+ WHERE thread_id = ${checkpoint.threadId}
869
+ AND through_sequence = ${checkpoint.throughSequence}
870
+ `.pipe(Effect.mapError(storageError("read idempotent checkpoint")));
871
+ const existing = yield* decodeRows(Schema.Array(CheckpointRow), "effect_agent_checkpoints", `${checkpoint.threadId}/${checkpoint.throughSequence}`, checkpointRows);
872
+ if (existing.length > 1) return yield* SqliteStorageCorruptionError.make({
873
+ table: "effect_agent_checkpoints",
874
+ rowKey: `${checkpoint.threadId}/${checkpoint.throughSequence}`,
875
+ message: "A checkpoint primary key returned more than one row."
876
+ });
877
+ if (existing.length === 1) {
878
+ if (existing[0].tail_digest !== checkpoint.tailDigest || existing[0].checkpoint_json !== checkpoint.checkpointJson) return yield* SqliteCheckpointConflict.make({ message: "A different checkpoint already exists at this canonical sequence." });
879
+ return;
880
+ }
881
+ yield* sql`
882
+ INSERT INTO effect_agent_checkpoints (
883
+ thread_id,
884
+ through_sequence,
885
+ tail_digest,
886
+ checkpoint_json
887
+ ) VALUES (
888
+ ${checkpoint.threadId},
889
+ ${checkpoint.throughSequence},
890
+ ${checkpoint.tailDigest},
891
+ ${checkpoint.checkpointJson}
892
+ )
893
+ `.pipe(Effect.mapError(storageError("insert checkpoint")));
894
+ }));
895
+ });
896
+ const saveRecoveryCheckpoint = Effect.fn("SqliteJournal.saveRecoveryCheckpoint")(function* (request, checkpointJson) {
897
+ const { checkpoint } = request;
898
+ if (checkpoint.threadId.length > MAX_IDENTIFIER_LENGTH || storedTextBytes(checkpointJson) > MAX_STORED_TEXT_BYTES) return yield* SqliteStorageError.make({
899
+ operation: "save recovery checkpoint",
900
+ message: "Checkpoint identity or encoded JSON exceeds the SQLite storage bounds."
901
+ });
902
+ yield* withWriteTransaction("recovery checkpoint transaction")(Effect.gen(function* () {
903
+ const thread = (yield* getThread(checkpoint.threadId))[0];
904
+ if (thread === void 0) return yield* ThreadNotMaterialized.make({ threadId: checkpoint.threadId });
905
+ if (request.producerEpoch !== thread.producer_epoch) return yield* FenceRejected.make({
906
+ threadId: checkpoint.threadId,
907
+ actualEpoch: thread.producer_epoch,
908
+ attemptedEpoch: request.producerEpoch
909
+ });
910
+ if (checkpoint.throughSequence > thread.tail_sequence) return yield* CheckpointRejected.make({
911
+ threadId: checkpoint.threadId,
912
+ reason: "ahead-of-tail"
913
+ });
914
+ const digests = checkpoint.throughSequence === 0 ? [EMPTY_TAIL_DIGEST] : yield* getTailDigestAt(checkpoint.threadId, checkpoint.throughSequence);
915
+ if (digests.length !== 1 || digests[0] !== checkpoint.tailDigest) return yield* CheckpointRejected.make({
916
+ threadId: checkpoint.threadId,
917
+ reason: "digest-mismatch"
918
+ });
919
+ yield* failpoint("save-recovery-checkpoint:before");
920
+ yield* sql`
921
+ INSERT INTO effect_agent_recovery_checkpoints (thread_id, through_sequence, tail_digest, checkpoint_json)
922
+ VALUES (${checkpoint.threadId}, ${checkpoint.throughSequence}, ${checkpoint.tailDigest}, ${checkpointJson})
923
+ ON CONFLICT (thread_id) DO UPDATE SET
924
+ through_sequence = excluded.through_sequence,
925
+ tail_digest = excluded.tail_digest,
926
+ checkpoint_json = excluded.checkpoint_json
927
+ WHERE excluded.through_sequence >= effect_agent_recovery_checkpoints.through_sequence
928
+ `.pipe(Effect.mapError(storageError("save recovery checkpoint")));
929
+ }));
930
+ yield* failpoint("save-recovery-checkpoint:after");
931
+ });
932
+ const loadRecoveryCheckpoint = Effect.fn("SqliteJournal.loadRecoveryCheckpoint")(function* (threadId) {
933
+ const rows = yield* sql`
934
+ SELECT thread_id, through_sequence, tail_digest, checkpoint_json
935
+ FROM effect_agent_recovery_checkpoints
936
+ WHERE thread_id = ${threadId}
937
+ `.pipe(Effect.mapError(storageError("load recovery checkpoint")));
938
+ return yield* decodeRows(Schema.Array(CheckpointRow), "effect_agent_recovery_checkpoints", threadId, rows);
939
+ });
940
+ const loadCheckpoint = Effect.fn("SqliteJournal.loadCheckpoint")(function* (threadId, atOrBeforeSequence) {
941
+ const rows = yield* sql`
942
+ SELECT
943
+ thread_id,
944
+ through_sequence,
945
+ tail_digest,
946
+ checkpoint_json
947
+ FROM effect_agent_checkpoints
948
+ WHERE thread_id = ${threadId}
949
+ AND through_sequence <= ${atOrBeforeSequence}
950
+ ORDER BY through_sequence DESC
951
+ LIMIT 1
952
+ `.pipe(Effect.mapError(storageError("load checkpoint")));
953
+ return yield* decodeRows(Schema.Array(CheckpointRow), "effect_agent_checkpoints", `${threadId}<=${atOrBeforeSequence}`, rows);
954
+ });
955
+ const getTailDigestAt = Effect.fn("SqliteJournal.getTailDigestAt")(function* (threadId, sequence) {
956
+ if (sequence === 0) {
957
+ const threads = yield* getThread(threadId);
958
+ return threads.length === 0 ? [] : [threads[0].tail_sequence === 0 ? threads[0].tail_digest : void 0].filter((value) => value !== void 0);
959
+ }
960
+ const rows = yield* sql`
961
+ SELECT
962
+ thread_id,
963
+ batch_id,
964
+ first_sequence,
965
+ last_sequence,
966
+ batch_digest,
967
+ tail_digest,
968
+ batch_json
969
+ FROM effect_agent_canonical_batches
970
+ WHERE thread_id = ${threadId}
971
+ AND last_sequence = ${sequence}
972
+ `.pipe(Effect.mapError(storageError("read canonical digest at sequence")));
973
+ return (yield* decodeRows(Schema.Array(BatchRow), "effect_agent_canonical_batches", `${threadId}/${sequence}`, rows)).map((batch) => batch.tail_digest);
974
+ });
975
+ return {
976
+ append,
977
+ exportThread,
978
+ getThread,
979
+ getTailDigestAt,
980
+ loadCheckpoint,
981
+ loadRecoveryCheckpoint,
982
+ saveRecoveryCheckpoint,
983
+ materialize,
984
+ read,
985
+ saveCheckpoint,
986
+ scanStoredPayloads: Effect.fn("SqliteJournal.scanStoredPayloads")(function* () {
987
+ return yield* withReadTransaction("startup scan transaction")(Effect.gen(function* () {
988
+ const threads = yield* sql`
989
+ SELECT
990
+ thread_id,
991
+ created_at,
992
+ tail_sequence,
993
+ tail_digest,
994
+ producer_epoch
995
+ FROM effect_agent_threads
996
+ ORDER BY thread_id
997
+ `.pipe(Effect.mapError(storageError("scan threads")));
998
+ const batches = yield* sql`
999
+ SELECT
1000
+ thread_id,
1001
+ batch_id,
1002
+ first_sequence,
1003
+ last_sequence,
1004
+ batch_digest,
1005
+ tail_digest,
1006
+ batch_json
1007
+ FROM effect_agent_canonical_batches
1008
+ ORDER BY thread_id, first_sequence
1009
+ `.pipe(Effect.mapError(storageError("scan canonical batches")));
1010
+ const records = yield* sql`
1011
+ SELECT
1012
+ thread_id,
1013
+ sequence,
1014
+ record_id,
1015
+ batch_id,
1016
+ record_json
1017
+ FROM effect_agent_canonical_records
1018
+ ORDER BY thread_id, sequence
1019
+ `.pipe(Effect.mapError(storageError("scan canonical records")));
1020
+ const checkpoints = yield* sql`
1021
+ SELECT
1022
+ thread_id,
1023
+ through_sequence,
1024
+ tail_digest,
1025
+ checkpoint_json
1026
+ FROM effect_agent_checkpoints
1027
+ ORDER BY thread_id, through_sequence
1028
+ `.pipe(Effect.mapError(storageError("scan checkpoints")));
1029
+ return {
1030
+ threads: yield* decodeRows(Schema.Array(ThreadRow), "effect_agent_threads", "startup_scan", threads),
1031
+ batches: yield* decodeRows(Schema.Array(BatchRow), "effect_agent_canonical_batches", "startup_scan", batches),
1032
+ records: yield* decodeRows(Schema.Array(RecordRow), "effect_agent_canonical_records", "startup_scan", records),
1033
+ checkpoints: yield* decodeRows(Schema.Array(CheckpointRow), "effect_agent_checkpoints", "startup_scan", checkpoints)
1034
+ };
1035
+ }));
1036
+ }),
1037
+ withWriteTransaction,
1038
+ withReadTransaction
1039
+ };
1040
+ });
1041
+ //#endregion
1042
+ export { initializeSqliteJournal as a, decodeRows as i, RawCheckpoint as n, RawReadRequest as r, RawAppendRequest as t };
1043
+
1044
+ //# sourceMappingURL=sqlite-journal-BCyBc87Y.mjs.map