@systemfsoftware/agent-storage-memory 0.0.0-bootstrap.0 → 0.1.0-beta.192

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 (48) hide show
  1. package/LICENSE +21 -0
  2. package/dist/MemoryMessageDeliveryStore-B50JDqxF.mjs +609 -0
  3. package/dist/MemoryMessageDeliveryStore-B50JDqxF.mjs.map +1 -0
  4. package/dist/MemoryMessageDeliveryStore-BmLntoBA.d.mts +18 -0
  5. package/dist/MemoryMessageDeliveryStore.d.mts +2 -0
  6. package/dist/MemoryMessageDeliveryStore.mjs +1 -0
  7. package/dist/MemoryScheduleStore-Bb85CXg1.mjs +163 -0
  8. package/dist/MemoryScheduleStore-Bb85CXg1.mjs.map +1 -0
  9. package/dist/MemoryScheduleStore-C_ll7Xyr.d.mts +8 -0
  10. package/dist/MemoryScheduleStore.d.mts +2 -0
  11. package/dist/MemoryScheduleStore.mjs +1 -0
  12. package/dist/MemorySemanticIndex-DYljUBy4.mjs +224 -0
  13. package/dist/MemorySemanticIndex-DYljUBy4.mjs.map +1 -0
  14. package/dist/MemorySemanticIndex-DrcJ7UG4.d.mts +20 -0
  15. package/dist/MemorySemanticIndex.d.mts +2 -0
  16. package/dist/MemorySemanticIndex.mjs +1 -0
  17. package/dist/MemorySubmissionLedger-DO-F22Gu.d.mts +28 -0
  18. package/dist/MemorySubmissionLedger-lc4VJ_vq.mjs +1566 -0
  19. package/dist/MemorySubmissionLedger-lc4VJ_vq.mjs.map +1 -0
  20. package/dist/MemorySubmissionLedger.d.mts +2 -0
  21. package/dist/MemorySubmissionLedger.mjs +1 -0
  22. package/dist/MemorySubscriptionStore-BWZ9lcIY.d.mts +7 -0
  23. package/dist/MemorySubscriptionStore-CFuGVxFD.mjs +929 -0
  24. package/dist/MemorySubscriptionStore-CFuGVxFD.mjs.map +1 -0
  25. package/dist/MemorySubscriptionStore.d.mts +2 -0
  26. package/dist/MemorySubscriptionStore.mjs +1 -0
  27. package/dist/MemoryThreadStore-BX3sRYhE.d.mts +21 -0
  28. package/dist/MemoryThreadStore-Dtwe-7h4.mjs +1415 -0
  29. package/dist/MemoryThreadStore-Dtwe-7h4.mjs.map +1 -0
  30. package/dist/MemoryThreadStore.d.mts +2 -0
  31. package/dist/MemoryThreadStore.mjs +1 -0
  32. package/dist/MemoryThreadStoreKernel-5ya9AJvL.d.mts +85 -0
  33. package/dist/WorkSelection-Xr9mCon_.mjs +29 -0
  34. package/dist/WorkSelection-Xr9mCon_.mjs.map +1 -0
  35. package/dist/index.d.mts +7 -0
  36. package/dist/index.mjs +7 -0
  37. package/dist/rolldown-runtime-D3KUYPsf.mjs +12 -0
  38. package/package.json +67 -5
  39. package/src/MemoryMessageDeliveryStore.ts +1004 -0
  40. package/src/MemoryScheduleStore.ts +324 -0
  41. package/src/MemorySemanticIndex.ts +360 -0
  42. package/src/MemorySubmissionLedger.ts +3590 -0
  43. package/src/MemorySubscriptionStore.ts +1762 -0
  44. package/src/MemoryThreadStore.ts +2810 -0
  45. package/src/index.ts +6 -0
  46. package/src/internal/MemoryThreadStoreKernel.ts +156 -0
  47. package/src/internal/WorkSelection.ts +29 -0
  48. package/README.md +0 -3
@@ -0,0 +1,2810 @@
1
+ import { canonicalJson, utf8ByteLength } from '@systemfsoftware/agent/digest'
2
+ import { RunId, SubmissionId as importSubmissionId, type ThreadId } from '@systemfsoftware/agent/identifiers'
3
+ import { MessageDeliveryError, prepareCanonicalMessageDeliveries } from '@systemfsoftware/agent/message-delivery'
4
+ import { ExportBatch, ExportedRecord, ExportRecord, ReadRecord } from '@systemfsoftware/agent/record-format'
5
+ import {
6
+ type BatchId,
7
+ CanonicalRecordEnvelope,
8
+ CanonicalSequence,
9
+ CURRENT_RECORD_FORMAT,
10
+ MAX_RUN_EVIDENCE_BYTES,
11
+ MAX_RUN_EVIDENCE_RECORDS,
12
+ MAX_RUN_RECOVERY_SUFFIX_BYTES,
13
+ MAX_RUN_RECOVERY_SUFFIX_RECORDS,
14
+ MAX_RUN_TERMINAL_BYTES,
15
+ ObservationOffset,
16
+ PromptRecord,
17
+ type PromptRecordEnvelope,
18
+ RecordEnvelope,
19
+ type RecordId,
20
+ RUN_TERMINAL_RESERVE_RECORDS,
21
+ } from '@systemfsoftware/agent/records'
22
+ import {
23
+ canonicalRecordBytes,
24
+ canonicalRunIds,
25
+ isWorkHandoff,
26
+ prepareProgressAppend,
27
+ ProgressAppendReader,
28
+ validateProgressAppend,
29
+ verifyRunContinuations,
30
+ } from '@systemfsoftware/agent/run-continuation'
31
+ import {
32
+ runIdForSubmission,
33
+ subagentLineageRecordId,
34
+ toolCallSettledRecordId,
35
+ workerInputRecordId,
36
+ workerOriginRecordId,
37
+ } from '@systemfsoftware/agent/run-journal'
38
+ import { makeStorageOwner, StorageOwner } from '@systemfsoftware/agent/run-storage'
39
+ import {
40
+ submissionAbortRecordId,
41
+ submissionInputRecordId,
42
+ submissionSettlementRecordId,
43
+ } from '@systemfsoftware/agent/submission-ledger'
44
+ import {
45
+ MAX_ARCHIVE_RANGE_BYTES,
46
+ MAX_ARCHIVE_RANGE_RECORDS,
47
+ ThreadArchiveRange,
48
+ ThreadArchiveRangePublish,
49
+ ThreadArchiveRangeRead,
50
+ ThreadArchiveRangeRequest,
51
+ ThreadArchiveRangeSeal,
52
+ type ThreadArchiveStorage,
53
+ } from '@systemfsoftware/agent/thread-archive-range'
54
+ import {
55
+ captureImportSource,
56
+ finishThreadImport,
57
+ invalidThreadArchive,
58
+ makeThreadImportProgress,
59
+ prepareImportPage,
60
+ rebuildClosedSubmission,
61
+ ThreadDeliveryImportReader,
62
+ ThreadImport,
63
+ ThreadImportReader,
64
+ ThreadImportRejected,
65
+ validateClosedRun,
66
+ verifyImportedReferences,
67
+ } from '@systemfsoftware/agent/thread-import'
68
+ import { verifyThreadInvariants } from '@systemfsoftware/agent/thread-invariants'
69
+ import {
70
+ AppendConflict,
71
+ type AppendRequest,
72
+ AppendResult,
73
+ canonicalBatchFitsTransfer,
74
+ type CommitBatch,
75
+ type ExecutionCheckpoint,
76
+ PreparedAppend,
77
+ PROMPT_EVIDENCE_TAGS,
78
+ streamExport,
79
+ ThreadExportRecord,
80
+ ThreadExportRejected,
81
+ ThreadExportSource,
82
+ ThreadIdentity,
83
+ ThreadIdentityRequest,
84
+ ThreadMaterialization,
85
+ ThreadNotMaterialized,
86
+ ThreadObservation,
87
+ ThreadPeerCountRequest,
88
+ ThreadPromptRead,
89
+ ThreadReader,
90
+ ThreadReadRequest,
91
+ ThreadStore,
92
+ ThreadStoreError,
93
+ ThreadTail,
94
+ ThreadTailRequest,
95
+ ThreadVerificationRequest,
96
+ ThreadWorkerCapacity,
97
+ ThreadWorkerCapacityRequest,
98
+ transferPageFits,
99
+ } from '@systemfsoftware/agent/thread-store'
100
+ import {
101
+ checkExportSource,
102
+ exportThreadPage,
103
+ ThreadExporterReader,
104
+ type TransferManifest,
105
+ } from '@systemfsoftware/agent/thread-transfer'
106
+ import {
107
+ advanceWorkEntry,
108
+ type CanonicalWorkEntry,
109
+ decodeWorkCursor,
110
+ encodeWorkCursor,
111
+ MAX_WORK_REBUILD_BYTES,
112
+ MAX_WORK_REBUILD_RECORDS,
113
+ ThreadWorkRequest,
114
+ type ThreadWorkStorage,
115
+ validateWorkPage,
116
+ WORK_INDEX_VERSION,
117
+ WorkDiscoveryUnavailable,
118
+ type WorkerReportingMode,
119
+ workIndexChanges,
120
+ WorkIndexRebuildRequest,
121
+ WorkThreadsRequest,
122
+ } from '@systemfsoftware/agent/thread-work'
123
+ import * as Context from 'effect/Context'
124
+ import * as CryptoDigest from 'effect/crypto/Digest'
125
+ import * as Effect from 'effect/Effect'
126
+ import * as Base64 from 'effect/encoding/Base64'
127
+ import * as Layer from 'effect/Layer'
128
+ import * as MutableRef from 'effect/MutableRef'
129
+ import * as Option from 'effect/Option'
130
+ import * as PubSub from 'effect/PubSub'
131
+ import * as Ref from 'effect/Ref'
132
+ import * as Schema from 'effect/Schema'
133
+ import * as Semaphore from 'effect/Semaphore'
134
+ import * as Stream from 'effect/Stream'
135
+
136
+ import {
137
+ type MemoryDeliveryImport,
138
+ type MemoryDeliveryTransfer,
139
+ type MemoryDeliveryWriter,
140
+ type MemoryLedgerImport,
141
+ type MemoryLedgerTransfer,
142
+ MemoryThreadStoreKernel,
143
+ type MemoryWorkOwner,
144
+ type PreparedMemoryAppend,
145
+ } from './internal/MemoryThreadStoreKernel'
146
+ import { boundedWorkSelection } from './internal/WorkSelection'
147
+
148
+ const MAX_THREADS = 256
149
+ const RECORD_CHUNK_SIZE = 1_024
150
+ const READ_PAGE_SIZE = 8
151
+
152
+ const ThreadCapacity = Context.Reference<number>(
153
+ '@effect-agent/storage-memory/MemoryThreadStore/ThreadCapacity',
154
+ { defaultValue: () => MAX_THREADS },
155
+ )
156
+
157
+ interface StoredBatch {
158
+ /** Preserve the exact destination wire, including additive fields unknown to this reader. */
159
+ readonly batchJson: string
160
+ readonly result: AppendResult
161
+ }
162
+
163
+ interface StoredThread {
164
+ /** Append-only owner indexes; readers must constrain them to their captured canonical tail. */
165
+ readonly runRecords: Map<string, Array<CanonicalRecordEnvelope>>
166
+ readonly operationRecords: Map<string, Array<CanonicalRecordEnvelope>>
167
+ readonly handoffs: Array<CanonicalRecordEnvelope>
168
+ readonly agentUpdates: Array<CanonicalRecordEnvelope>
169
+ readonly deliveryPredecessors: Array<CanonicalRecordEnvelope>
170
+ readonly toolDeclarations: Map<string, CanonicalRecordEnvelope | null>
171
+ readonly promptEvidence: Array<CanonicalRecordEnvelope>
172
+ readonly modelCompletions: Array<CanonicalRecordEnvelope>
173
+ readonly applicationInputs: Array<CanonicalRecordEnvelope>
174
+ readonly durableOwners: Array<CanonicalRecordEnvelope>
175
+ readonly windowBoundaries: Map<string, Array<CanonicalRecordEnvelope>>
176
+ readonly workerRecords: Map<string, Array<CanonicalRecordEnvelope>>
177
+ readonly byId: Map<string, CanonicalRecordEnvelope>
178
+ readonly runInputs: Map<string, CanonicalRecordEnvelope | null>
179
+ readonly tailSequence: CanonicalSequence
180
+ readonly ranges: Map<number, ThreadArchiveRange>
181
+ readonly rangeStarts: Array<number>
182
+ readonly archiveContents: Map<number, Map<BatchId, string>>
183
+ readonly chunks: Map<
184
+ number,
185
+ { readonly records: Array<CanonicalRecordEnvelope>; readonly bytes: Array<number> }
186
+ >
187
+ readonly batches: Map<BatchId, StoredBatch>
188
+ readonly executions: Map<RunId, ExecutionCheckpoint>
189
+ readonly executionCommits: Map<
190
+ RunId,
191
+ { readonly batchId: BatchId; readonly intent: string; readonly result: AppendResult }
192
+ >
193
+ readonly batchesByFirst: Map<number, BatchId>
194
+ }
195
+
196
+ const storedRecord = (thread: StoredThread, sequence: number) =>
197
+ thread.chunks.get(Math.floor((sequence - 1) / RECORD_CHUNK_SIZE))?.records[
198
+ (sequence - 1) % RECORD_CHUNK_SIZE
199
+ ]
200
+
201
+ const storedBytes = (thread: StoredThread, sequence: number) =>
202
+ thread.chunks.get(Math.floor((sequence - 1) / RECORD_CHUNK_SIZE))?.bytes[
203
+ (sequence - 1) % RECORD_CHUNK_SIZE
204
+ ]
205
+
206
+ const storedPage = Effect.fnUntraced(function*(
207
+ thread: StoredThread,
208
+ after: number,
209
+ limit: number,
210
+ ) {
211
+ const page: Array<CanonicalRecordEnvelope> = []
212
+ let bytes = 0
213
+
214
+ for (
215
+ let sequence = after + 1;
216
+ sequence <= Math.min(thread.tailSequence, after + limit);
217
+ sequence++
218
+ ) {
219
+ const record = storedRecord(thread, sequence)
220
+
221
+ if (record === undefined) return yield* storeError('read', 'Incomplete canonical chunk table')
222
+ const size = storedBytes(thread, sequence) ?? 0
223
+
224
+ if (bytes + size > 32 * 1024 * 1024) break
225
+ bytes += size
226
+ page.push(record)
227
+ }
228
+
229
+ return page
230
+ })
231
+
232
+ const retainRecords = (thread: StoredThread, records: ReadonlyArray<CanonicalRecordEnvelope>) => {
233
+ for (const entry of records) {
234
+ const chunkId = Math.floor((entry.sequence - 1) / RECORD_CHUNK_SIZE)
235
+ let chunk = thread.chunks.get(chunkId)
236
+
237
+ if (chunk === undefined) {
238
+ chunk = { records: [], bytes: [] }
239
+ thread.chunks.set(chunkId, chunk)
240
+ }
241
+ chunk.records.push(entry)
242
+ chunk.bytes.push(canonicalRecordBytes(entry.record))
243
+ }
244
+ }
245
+
246
+ interface MemoryState {
247
+ readonly threads: Map<ThreadId, StoredThread>
248
+ }
249
+
250
+ type NativeIndexes = Pick<
251
+ StoredThread,
252
+ | 'toolDeclarations'
253
+ | 'promptEvidence'
254
+ | 'modelCompletions'
255
+ | 'applicationInputs'
256
+ | 'durableOwners'
257
+ | 'windowBoundaries'
258
+ | 'workerRecords'
259
+ | 'byId'
260
+ | 'runInputs'
261
+ | 'runRecords'
262
+ | 'handoffs'
263
+ | 'operationRecords'
264
+ | 'agentUpdates'
265
+ | 'deliveryPredecessors'
266
+ >
267
+
268
+ const emptyIndexes = (): NativeIndexes => ({
269
+ toolDeclarations: new Map(),
270
+ promptEvidence: [],
271
+ modelCompletions: [],
272
+ applicationInputs: [],
273
+ durableOwners: [],
274
+ windowBoundaries: new Map(),
275
+ workerRecords: new Map(),
276
+ byId: new Map(),
277
+ runInputs: new Map(),
278
+ runRecords: new Map(),
279
+ handoffs: [],
280
+ agentUpdates: [],
281
+ deliveryPredecessors: [],
282
+ operationRecords: new Map(),
283
+ })
284
+
285
+ interface WorkIndex {
286
+ readonly version: number
287
+ readonly state: 'ready' | 'rebuilding'
288
+ readonly through: CanonicalSequence
289
+ readonly reporting: WorkerReportingMode
290
+ readonly entryCount: number
291
+ readonly entries: Map<string, CanonicalWorkEntry>
292
+ readonly workers: Map<ThreadId, { ordinary: number; update: number; effects: number }>
293
+ readonly liveInputs: Array<LiveInputLocator>
294
+ readonly inputsByWorker: Map<ThreadId, Array<LiveInputLocator>>
295
+ readonly rebuildingIndexes?: NativeIndexes
296
+ }
297
+
298
+ interface LiveInputLocator {
299
+ readonly sequence: CanonicalSequence
300
+ readonly id: string
301
+ }
302
+
303
+ const liveInputPosition = (entries: ReadonlyArray<LiveInputLocator>, sequence: number) => {
304
+ let low = 0
305
+ let high = entries.length
306
+
307
+ while (low < high) {
308
+ const middle = Math.floor((low + high) / 2)
309
+
310
+ if (entries[middle].sequence < sequence) low = middle + 1
311
+ else high = middle
312
+ }
313
+
314
+ return low
315
+ }
316
+
317
+ const changeLiveInput = (
318
+ entries: Array<LiveInputLocator>,
319
+ entry: CanonicalWorkEntry,
320
+ change: 1 | -1,
321
+ ) => {
322
+ const at = liveInputPosition(entries, entry.createdSequence)
323
+
324
+ if (change === 1) entries.splice(at, 0, { sequence: entry.createdSequence, id: entry.id })
325
+ else if (entries[at]?.id === entry.id) entries.splice(at, 1)
326
+ }
327
+
328
+ const emptyWorkIndex = (): WorkIndex => ({
329
+ version: WORK_INDEX_VERSION,
330
+ state: 'ready',
331
+ through: ZERO_CANONICAL_SEQUENCE,
332
+ reporting: 'none',
333
+ entryCount: 0,
334
+ entries: new Map(),
335
+ workers: new Map(),
336
+ liveInputs: [],
337
+ inputsByWorker: new Map(),
338
+ })
339
+
340
+ const changeWorkCounts = (index: WorkIndex, entry: CanonicalWorkEntry, change: 1 | -1) => {
341
+ const owner = entry.owner
342
+
343
+ if (owner._tag === 'WorkerInput') {
344
+ changeLiveInput(index.liveInputs, entry, change)
345
+ let inputs = index.inputsByWorker.get(owner.workerThreadId)
346
+
347
+ if (inputs === undefined) index.inputsByWorker.set(owner.workerThreadId, inputs = [])
348
+ changeLiveInput(inputs, entry, change)
349
+ if (inputs.length === 0) index.inputsByWorker.delete(owner.workerThreadId)
350
+ let worker = index.workers.get(owner.workerThreadId)
351
+
352
+ if (worker === undefined) {
353
+ index.workers.set(owner.workerThreadId, worker = { ordinary: 0, update: 0, effects: 0 })
354
+ }
355
+ if (owner.update) worker.update += change
356
+ else worker.ordinary += change
357
+ if (worker.ordinary + worker.update + worker.effects === 0) {
358
+ index.workers.delete(owner.workerThreadId)
359
+ }
360
+ }
361
+ }
362
+
363
+ /** Prepare only this batch's changes; commit under the writer gate with canonical publication. */
364
+ const prepareWork = Effect.fnUntraced(function*(
365
+ previous: WorkIndex,
366
+ records: ReadonlyArray<CanonicalRecordEnvelope>,
367
+ ) {
368
+ const changes = new Map<string, CanonicalWorkEntry | undefined>()
369
+ let reporting = previous.reporting
370
+ let through = previous.through
371
+
372
+ for (const record of records) {
373
+ for (const change of yield* workIndexChanges(record, reporting)) {
374
+ if (change._tag === 'WorkerMode') reporting = change.mode
375
+ else if (change._tag === 'Remove') {
376
+ const entry = changes.has(change.id)
377
+ ? changes.get(change.id)
378
+ : previous.entries.get(change.id)
379
+
380
+ if (
381
+ change.stateRecordId === undefined ||
382
+ (entry?.stateReference._tag === 'Canonical' &&
383
+ entry.stateReference.recordId === change.stateRecordId)
384
+ ) {
385
+ changes.set(change.id, undefined)
386
+ }
387
+ } else {
388
+ const entry = advanceWorkEntry(
389
+ changes.has(change.entry.id)
390
+ ? changes.get(change.entry.id)
391
+ : previous.entries.get(change.entry.id),
392
+ change.entry,
393
+ )
394
+
395
+ changes.set(entry.id, entry)
396
+ }
397
+ }
398
+ through = record.sequence
399
+ }
400
+
401
+ return (): WorkIndex => {
402
+ const { entries } = previous
403
+
404
+ for (const [id, entry] of changes) {
405
+ const old = entries.get(id)
406
+
407
+ if (old !== undefined) changeWorkCounts(previous, old, -1)
408
+
409
+ if (entry === undefined) entries.delete(id)
410
+ else {
411
+ entries.set(id, entry)
412
+ changeWorkCounts(previous, entry, 1)
413
+ }
414
+ }
415
+
416
+ return { ...previous, through, reporting, entryCount: entries.size }
417
+ }
418
+ })
419
+
420
+ /** First sequence strictly after the cursor, without traversing a Run's earlier facts. */
421
+ const upperSequence = (records: ReadonlyArray<CanonicalRecordEnvelope>, sequence: number) => {
422
+ let low = 0
423
+ let high = records.length
424
+
425
+ while (low < high) {
426
+ const mid = Math.floor((low + high) / 2)
427
+
428
+ if (records[mid].sequence <= sequence) low = mid + 1
429
+ else high = mid
430
+ }
431
+
432
+ return low
433
+ }
434
+
435
+ const appendToIndex = (
436
+ index: Map<string, Array<CanonicalRecordEnvelope>>,
437
+ key: string,
438
+ entry: CanonicalRecordEnvelope,
439
+ ) => {
440
+ const records = index.get(key)
441
+
442
+ if (records === undefined) index.set(key, [entry])
443
+ else records.push(entry)
444
+ }
445
+
446
+ /** Only call at successful synchronous publication, or on indexes not yet reachable by readers. */
447
+ const commitIndex = (
448
+ index: Map<string, Array<CanonicalRecordEnvelope>>,
449
+ additions: ReadonlyMap<string, Array<CanonicalRecordEnvelope>>,
450
+ ) => {
451
+ for (const [key, entries] of additions) {
452
+ const records = index.get(key)
453
+
454
+ if (records === undefined) index.set(key, entries)
455
+ else for (const entry of entries) records.push(entry)
456
+ }
457
+ }
458
+
459
+ const prepareIndexes = (
460
+ previous: NativeIndexes,
461
+ records: ReadonlyArray<CanonicalRecordEnvelope>,
462
+ ) => {
463
+ // Latest execution entries are replaced in this private map; owner histories only append.
464
+ // Rebuild staging is private: reuse it only in the synchronous cursor publication step.
465
+ const workerRecords = new Map<string, Array<CanonicalRecordEnvelope>>()
466
+
467
+ const wasWorker = (previous.workerRecords.get('worker') ?? []).some(
468
+ ({ record }) => record.payload._tag === 'WorkerOriginRecorded',
469
+ )
470
+
471
+ const isWorker = wasWorker || records.some(({ record }) => record.payload._tag === 'WorkerOriginRecorded')
472
+
473
+ // A Thread can gain a Worker origin after its initial history. Initialize once on that boundary.
474
+ if (isWorker && !wasWorker) {
475
+ for (const entry of previous.byId.values()) {
476
+ const payload = entry.record.payload
477
+
478
+ if (
479
+ (payload._tag === 'UserInputRecorded' || payload._tag === 'SubmissionSettled') &&
480
+ payload.runId !== undefined
481
+ ) {
482
+ const key = `execution:${payload._tag}`
483
+
484
+ if ((workerRecords.get(key)?.[0]?.sequence ?? 0) < entry.sequence) {
485
+ workerRecords.set(key, [entry])
486
+ }
487
+ }
488
+ }
489
+ }
490
+ const workerAppends = new Map<string, Array<CanonicalRecordEnvelope>>()
491
+ const byId = new Map<string, CanonicalRecordEnvelope>()
492
+ const runInputs = new Map<string, CanonicalRecordEnvelope | null>()
493
+ const runRecords = new Map<string, Array<CanonicalRecordEnvelope>>()
494
+ const handoffs: Array<CanonicalRecordEnvelope> = []
495
+ const agentUpdates: Array<CanonicalRecordEnvelope> = []
496
+
497
+ const deliveryPredecessors: Array<CanonicalRecordEnvelope> = []
498
+
499
+ const nativeAdds = emptyIndexes()
500
+ const operationAppends = new Map<string, Array<CanonicalRecordEnvelope>>()
501
+
502
+ for (const entry of records) {
503
+ byId.set(entry.record.recordId, entry)
504
+ const payload = entry.record.payload
505
+
506
+ if (payload._tag === 'ModelResponseRecorded') {
507
+ for (const operation of payload.toolOperations) {
508
+ const id = toolCallSettledRecordId(payload.runId, payload.turn, operation.toolCallId)
509
+
510
+ nativeAdds.toolDeclarations.set(
511
+ id,
512
+ previous.toolDeclarations.has(id) || nativeAdds.toolDeclarations.has(id) ? null : entry,
513
+ )
514
+ }
515
+ }
516
+ if (PROMPT_EVIDENCE_TAGS.some((tag) => tag === payload._tag)) {
517
+ nativeAdds.promptEvidence.push(entry)
518
+ }
519
+ if (payload._tag === 'ModelCompleted') nativeAdds.modelCompletions.push(entry)
520
+ if (payload._tag === 'UserInputRecorded') {
521
+ const message = payload.messageAdmission
522
+
523
+ if (
524
+ message === undefined ||
525
+ !('_tag' in message) ||
526
+ (message._tag !== 'WorkerCompletion' && message._tag !== 'WorkerUpdate')
527
+ ) {
528
+ nativeAdds.applicationInputs.push(entry)
529
+ }
530
+ }
531
+ if (
532
+ (payload._tag === 'UserInputRecorded' && payload.submissionId !== undefined) ||
533
+ [
534
+ 'RunStarted',
535
+ 'SubmissionSettled',
536
+ 'AbortRequested',
537
+ 'WorkerOriginRecorded',
538
+ 'SubagentLineageRecorded',
539
+ ].includes(payload._tag)
540
+ ) {
541
+ nativeAdds.durableOwners.push(entry)
542
+ }
543
+ if (payload._tag === 'CompactionCreated' && payload.kind === 'rollover') {
544
+ for (let height = 0; height < 53; height++) {
545
+ appendToIndex(
546
+ nativeAdds.windowBoundaries,
547
+ `${height}:${Math.floor(payload.coversThrough / 2 ** height)}`,
548
+ entry,
549
+ )
550
+ }
551
+ }
552
+
553
+ for (const runId of canonicalRunIds(entry.record)) appendToIndex(runRecords, runId, entry)
554
+ if (isWorkHandoff(entry.record)) handoffs.push(entry)
555
+ if (payload._tag === 'AgentUpdateEmitted') agentUpdates.push(entry)
556
+ if (
557
+ payload._tag === 'WorkerReportPrepared' ||
558
+ (payload._tag === 'AgentUpdateEmitted' && payload.delivery !== undefined)
559
+ ) {
560
+ deliveryPredecessors.push(entry)
561
+ }
562
+ if ('runId' in payload && payload.runId !== undefined && 'toolCallId' in payload) {
563
+ appendToIndex(operationAppends, JSON.stringify([payload.runId, payload.toolCallId]), entry)
564
+ if (payload._tag === 'ToolApprovalRequested' || payload._tag === 'ToolApprovalDecided') {
565
+ appendToIndex(
566
+ operationAppends,
567
+ JSON.stringify([payload.runId, payload.toolCallId, 'approval']),
568
+ entry,
569
+ )
570
+ }
571
+ if (payload._tag === 'ToolCallSettled') {
572
+ appendToIndex(
573
+ operationAppends,
574
+ JSON.stringify([payload.runId, payload.toolCallId, 'settled']),
575
+ entry,
576
+ )
577
+ }
578
+ }
579
+
580
+ if (
581
+ isWorker &&
582
+ (payload._tag === 'UserInputRecorded' || payload._tag === 'SubmissionSettled') &&
583
+ payload.runId !== undefined
584
+ ) {
585
+ workerRecords.set(`execution:${payload._tag}`, [entry])
586
+ }
587
+
588
+ const workerKey = payload._tag === 'SubtreeBudgetReserved'
589
+ ? `subtree:${payload.sourceSubmissionId ?? ''}`
590
+ : payload._tag === 'SubagentJoined'
591
+ ? `joined:${payload.runId}`
592
+ : ['ThreadCreated', 'WorkerOriginRecorded', 'SubagentLineageRecorded'].includes(
593
+ payload._tag,
594
+ )
595
+ ? 'worker'
596
+ : undefined
597
+
598
+ if (workerKey !== undefined) appendToIndex(workerAppends, workerKey, entry)
599
+ if (payload._tag === 'WorkerStopRequested') {
600
+ appendToIndex(workerAppends, `stop:${payload.command.worker.threadId}`, entry)
601
+ }
602
+ if (
603
+ payload._tag === 'WorkerInputRequested' &&
604
+ payload.admission.sourceSubmissionId !== undefined
605
+ ) {
606
+ appendToIndex(workerAppends, `funding:${payload.admission.sourceSubmissionId}`, entry)
607
+ }
608
+ if (payload._tag === 'WorkerInputCompleted') {
609
+ const requested = previous.byId.get(workerInputRecordId(payload.messageId)) ??
610
+ byId.get(workerInputRecordId(payload.messageId))
611
+
612
+ const admission = requested?.record.payload
613
+
614
+ if (
615
+ admission?._tag === 'WorkerInputRequested' &&
616
+ admission.admission.sourceSubmissionId !== undefined
617
+ ) {
618
+ appendToIndex(workerAppends, `funding:${admission.admission.sourceSubmissionId}`, entry)
619
+ }
620
+ }
621
+ if (payload._tag === 'WorkerInputRefused') {
622
+ const reserved = (
623
+ previous.byId.get(payload.reservation.recordId) ?? byId.get(payload.reservation.recordId)
624
+ )?.record.payload
625
+
626
+ const sourceSubmissionId = reserved?._tag === 'WorkerInputRequested'
627
+ ? reserved.admission.sourceSubmissionId
628
+ : reserved?._tag === 'SubtreeBudgetReserved'
629
+ ? reserved.sourceSubmissionId
630
+ : undefined
631
+
632
+ if (sourceSubmissionId !== undefined) {
633
+ appendToIndex(workerAppends, `funding:${sourceSubmissionId}`, entry)
634
+ }
635
+ }
636
+ if (
637
+ payload._tag === 'UserInputRecorded' &&
638
+ payload.kind === 'user' &&
639
+ payload.runId !== undefined
640
+ ) {
641
+ runInputs.set(
642
+ payload.runId,
643
+ runInputs.has(payload.runId) || previous.runInputs.has(payload.runId) ? null : entry,
644
+ )
645
+ }
646
+ }
647
+
648
+ return {
649
+ indexes: previous,
650
+ commit: () => {
651
+ commitIndex(previous.runRecords, runRecords)
652
+ commitIndex(previous.operationRecords, operationAppends)
653
+ for (const [id, entry] of nativeAdds.toolDeclarations) {
654
+ previous.toolDeclarations.set(id, entry)
655
+ }
656
+ for (const key of ['promptEvidence', 'modelCompletions', 'applicationInputs'] as const) {
657
+ for (const entry of nativeAdds[key]) previous[key].push(entry)
658
+ }
659
+ commitIndex(previous.windowBoundaries, nativeAdds.windowBoundaries)
660
+ if (previous.durableOwners.length === 0 && nativeAdds.durableOwners[0] !== undefined) {
661
+ previous.durableOwners.push(nativeAdds.durableOwners[0])
662
+ }
663
+ for (const [id, entry] of byId) previous.byId.set(id, entry)
664
+ for (const [id, entry] of runInputs) previous.runInputs.set(id, entry)
665
+ for (const [key, entries] of workerRecords) previous.workerRecords.set(key, entries)
666
+ commitIndex(previous.workerRecords, workerAppends)
667
+ for (const entry of handoffs) previous.handoffs.push(entry)
668
+ for (const entry of agentUpdates) previous.agentUpdates.push(entry)
669
+ for (const entry of deliveryPredecessors) previous.deliveryPredecessors.push(entry)
670
+ },
671
+ }
672
+ }
673
+
674
+ type AppendDecision =
675
+ | {
676
+ readonly _tag: 'failure'
677
+ readonly error: ThreadStoreError | ThreadNotMaterialized | AppendConflict
678
+ }
679
+ | {
680
+ readonly _tag: 'success'
681
+ readonly result: AppendResult
682
+ readonly records: ReadonlyArray<CanonicalRecordEnvelope>
683
+ }
684
+
685
+ type MaterializeDecision =
686
+ | { readonly _tag: 'failure'; readonly error: ThreadStoreError }
687
+ | { readonly _tag: 'success' }
688
+
689
+ const storeError = (operation: string, message: string, cause?: unknown): ThreadStoreError =>
690
+ cause === undefined
691
+ ? ThreadStoreError.make({ operation, message })
692
+ : ThreadStoreError.make({ operation, message, cause })
693
+
694
+ const deliveryError = (message: string, cause: MessageDeliveryError): ThreadStoreError =>
695
+ ThreadStoreError.make({ operation: 'append', message, cause, deliveryReason: cause.reason })
696
+
697
+ const validate = <A, I>(
698
+ schema: Schema.Codec<A, I>,
699
+ operation: string,
700
+ value: unknown,
701
+ ): Effect.Effect<A, ThreadStoreError> =>
702
+ Schema.encodeUnknownEffect(schema)(value).pipe(
703
+ Effect.flatMap(Schema.decodeUnknownEffect(schema)),
704
+ Effect.mapError((error) => storeError(operation, `Invalid ${operation} request`, error)),
705
+ )
706
+
707
+ const decodeCanonicalSequence = Schema.decodeSync(CanonicalSequence)
708
+ const ZERO_CANONICAL_SEQUENCE = decodeCanonicalSequence(0)
709
+
710
+ const offsetSequence = Effect.fnUntraced(function*(
711
+ threadId: ThreadId,
712
+ offset: ObservationOffset | undefined,
713
+ ): Effect.fn.Return<CanonicalSequence, ThreadStoreError> {
714
+ if (offset === undefined) return yield* Effect.succeed(ZERO_CANONICAL_SEQUENCE)
715
+ const prefix = `memory:v1:${Base64.encode(threadId)}:`
716
+ const encodedSequence = offset.startsWith(prefix) ? offset.slice(prefix.length) : ''
717
+
718
+ if (!/^\d+$/.test(encodedSequence)) {
719
+ return yield* storeError('observe', 'Malformed observation offset')
720
+ }
721
+ const sequence = Number(encodedSequence)
722
+
723
+ return yield* Number.isSafeInteger(sequence)
724
+ ? Schema.decodeEffect(CanonicalSequence)(sequence).pipe(
725
+ Effect.mapError(() => storeError('observe', 'Malformed observation offset')),
726
+ )
727
+ : Effect.fail(storeError('observe', 'Malformed observation offset'))
728
+ })
729
+
730
+ const observationOffset = (threadId: ThreadId, sequence: CanonicalSequence): ObservationOffset =>
731
+ Schema.decodeSync(ObservationOffset)(`memory:v1:${Base64.encode(threadId)}:${sequence}`)
732
+
733
+ const batchEnvelopes = (
734
+ threadId: ThreadId,
735
+ batch: CommitBatch,
736
+ firstSequence: CanonicalSequence,
737
+ ): ReadonlyArray<CanonicalRecordEnvelope> =>
738
+ batch.records.map((record, index) => {
739
+ const sequence = decodeCanonicalSequence(firstSequence + index)
740
+
741
+ return CanonicalRecordEnvelope.make({
742
+ threadId,
743
+ batchId: batch.batchId,
744
+ sequence,
745
+ offset: observationOffset(threadId, sequence),
746
+ record,
747
+ })
748
+ })
749
+
750
+ const decodeStoredBatch = (batchJson: string, operation: string) =>
751
+ Schema.decodeEffect(Schema.fromJsonString(ExportBatch))(batchJson).pipe(
752
+ Effect.mapError((cause) => storeError(operation, 'Invalid canonical batch JSON', cause)),
753
+ )
754
+
755
+ const findThread = Effect.fnUntraced(function*(
756
+ state: MemoryState,
757
+ threadId: ThreadId,
758
+ ): Effect.fn.Return<StoredThread, ThreadNotMaterialized> {
759
+ const thread = state.threads.get(threadId)
760
+
761
+ return yield* thread === undefined
762
+ ? Effect.fail(ThreadNotMaterialized.make({ threadId }))
763
+ : Effect.succeed(thread)
764
+ })
765
+
766
+ const makeThreadStore = Effect.gen(function*() {
767
+ const maxThreads = yield* ThreadCapacity
768
+ const crypto = yield* CryptoDigest.Digest
769
+ const state = yield* Ref.make<MemoryState>({ threads: new Map() })
770
+ const gate = yield* Semaphore.make(1)
771
+ const owner = yield* makeStorageOwner(gate.withPermits(1))
772
+ const withMutation = owner.withMutation
773
+ const updates = yield* PubSub.sliding<void>(1)
774
+ let ledgerTransfer: MemoryLedgerTransfer | undefined
775
+ let deliveryTransfer: MemoryDeliveryTransfer | undefined
776
+ let deliveryWriter: MemoryDeliveryWriter | undefined
777
+
778
+ const workState = yield* Ref.make(new Map<ThreadId, WorkIndex>())
779
+ const workOwners = new Map<'admissions' | 'deliveries', MemoryWorkOwner>()
780
+
781
+ const publishWork = (threadId: ThreadId, index: WorkIndex) => MutableRef.get(workState.ref).set(threadId, index)
782
+
783
+ const readyIndex = (
784
+ threadId: ThreadId,
785
+ tail: number,
786
+ ): Effect.Effect<WorkIndex, WorkDiscoveryUnavailable> => {
787
+ const index = MutableRef.get(workState.ref).get(threadId)
788
+
789
+ if (
790
+ index === undefined ||
791
+ index.version !== WORK_INDEX_VERSION ||
792
+ index.entries.size !== index.entryCount
793
+ ) {
794
+ return Effect.fail(WorkDiscoveryUnavailable.make({ threadId, reason: 'missing-index' }))
795
+ }
796
+ if (index.state !== 'ready' || index.through !== tail) {
797
+ return Effect.fail(WorkDiscoveryUnavailable.make({ threadId, reason: 'incomplete-rebuild' }))
798
+ }
799
+
800
+ return Effect.succeed(index)
801
+ }
802
+
803
+ const work: ThreadWorkStorage = {
804
+ threads: (unvalidated) =>
805
+ withMutation(
806
+ Effect.gen(function*() {
807
+ const request = yield* validate(WorkThreadsRequest, 'work threads', unvalidated)
808
+ const current = yield* Ref.get(state)
809
+ const catalogue = yield* Ref.get(workState)
810
+
811
+ const candidates = boundedWorkSelection<ThreadId>(
812
+ request.limit,
813
+ (id) => id,
814
+ request.afterThreadId,
815
+ )
816
+
817
+ for (const [threadId, thread] of current.threads) {
818
+ const index = catalogue.get(threadId)
819
+
820
+ if (
821
+ index === undefined ||
822
+ index.version !== WORK_INDEX_VERSION ||
823
+ index.state !== 'ready' ||
824
+ index.through !== thread.tailSequence ||
825
+ index.entryCount !== index.entries.size ||
826
+ index.entryCount > 0
827
+ ) {
828
+ candidates.add(threadId)
829
+ }
830
+ }
831
+ for (const owner of workOwners.values()) {
832
+ const page = yield* owner.threads(request)
833
+
834
+ for (const threadId of page.threadIds) candidates.add(threadId)
835
+ }
836
+ const threadIds = candidates.values
837
+ const afterThreadId = threadIds.length === request.limit ? threadIds.at(-1) : undefined
838
+
839
+ // A full page may have more owner rows; the next bounded call proves exhaustion.
840
+ return {
841
+ threadIds,
842
+ ...(afterThreadId === undefined ? {} : { afterThreadId }),
843
+ }
844
+ }),
845
+ ),
846
+ page: (unvalidated) =>
847
+ withMutation(
848
+ Effect.gen(function*() {
849
+ const request = yield* validate(ThreadWorkRequest, 'work page', unvalidated)
850
+
851
+ const cursor = yield* decodeWorkCursor(request).pipe(
852
+ Effect.provideService(CryptoDigest.Digest, crypto),
853
+ )
854
+
855
+ const thread = (yield* Ref.get(state)).threads.get(request.threadId)
856
+ // Accepted input can precede canonical Thread materialization entirely.
857
+ const index = yield* readyIndex(request.threadId, thread?.tailSequence ?? 0)
858
+
859
+ if (cursor.source === 'canonical') {
860
+ const candidates = boundedWorkSelection<CanonicalWorkEntry>(
861
+ request.limit + 1,
862
+ (entry) => entry.id,
863
+ cursor.after,
864
+ )
865
+
866
+ for (const entry of index.entries.values()) candidates.add(entry)
867
+ const selected = candidates.values
868
+
869
+ const entries = selected.slice(0, request.limit)
870
+ const after = selected.length > request.limit ? entries.at(-1)?.id : undefined
871
+
872
+ return yield* validateWorkPage(
873
+ {
874
+ entries,
875
+ cursor: encodeWorkCursor({
876
+ version: WORK_INDEX_VERSION,
877
+ threadDigest: cursor.threadDigest,
878
+ source: after === undefined ? 'deliveries' : 'canonical',
879
+ ...(after === undefined ? {} : { after }),
880
+ }),
881
+ },
882
+ request.limit,
883
+ )
884
+ }
885
+
886
+ const page = yield* (
887
+ workOwners.get(cursor.source)?.page(request.threadId, cursor.after, request.limit) ??
888
+ Effect.succeed<Effect.Success<ReturnType<MemoryWorkOwner['page']>>>({ entries: [] })
889
+ )
890
+
891
+ const next = page.after === undefined
892
+ ? cursor.source === 'admissions'
893
+ ? 'canonical'
894
+ : undefined
895
+ : cursor.source
896
+
897
+ return yield* validateWorkPage(
898
+ {
899
+ entries: [...page.entries],
900
+ ...(next === undefined
901
+ ? {}
902
+ : {
903
+ cursor: encodeWorkCursor({
904
+ version: WORK_INDEX_VERSION,
905
+ threadDigest: cursor.threadDigest,
906
+ source: next,
907
+ ...(page.after === undefined ? {} : { after: page.after }),
908
+ }),
909
+ }),
910
+ },
911
+ request.limit,
912
+ )
913
+ }),
914
+ ),
915
+ rebuild: (unvalidated) =>
916
+ withMutation(
917
+ Effect.gen(function*() {
918
+ const request = yield* validate(WorkIndexRebuildRequest, 'rebuild work', unvalidated)
919
+ const current = yield* Ref.get(state)
920
+ const thread = current.threads.get(request.threadId)
921
+ const tail = thread?.tailSequence ?? ZERO_CANONICAL_SEQUENCE
922
+ const prior = (yield* Ref.get(workState)).get(request.threadId)
923
+
924
+ const index: WorkIndex = request.restart ||
925
+ prior === undefined ||
926
+ prior.version !== WORK_INDEX_VERSION ||
927
+ prior.entries.size !== prior.entryCount ||
928
+ (prior.state === 'ready' && prior.through !== tail)
929
+ ? { ...emptyWorkIndex(), state: 'rebuilding', rebuildingIndexes: emptyIndexes() }
930
+ : prior
931
+
932
+ if (index.state === 'ready') {
933
+ return {
934
+ version: WORK_INDEX_VERSION,
935
+ threadId: request.threadId,
936
+ state: 'ready',
937
+ throughSequence: index.through,
938
+ tailSequence: tail,
939
+ processedRecords: 0,
940
+ processedBytes: 0,
941
+ }
942
+ }
943
+ if (index.rebuildingIndexes === undefined) {
944
+ return yield* WorkDiscoveryUnavailable.make({
945
+ threadId: request.threadId,
946
+ reason: 'incomplete-rebuild',
947
+ })
948
+ }
949
+ const rebuildingIndexes = index.rebuildingIndexes
950
+ const records: Array<CanonicalRecordEnvelope> = []
951
+ let bytes = 0
952
+ const end = Math.min(tail, index.through + (request.limit ?? MAX_WORK_REBUILD_RECORDS))
953
+
954
+ for (let position = index.through; position < end; position++) {
955
+ const size = thread === undefined ? undefined : storedBytes(thread, position + 1)
956
+
957
+ if (size === undefined) {
958
+ return yield* storeError('rebuild work', 'Canonical record byte length is missing')
959
+ }
960
+ if (bytes + size > MAX_WORK_REBUILD_BYTES) break
961
+ const record = thread === undefined ? undefined : storedRecord(thread, position + 1)
962
+
963
+ if (record === undefined || record.sequence !== position + 1) {
964
+ return yield* storeError('rebuild work', 'Canonical rebuild sequence is incomplete')
965
+ }
966
+ bytes += size
967
+ records.push(record)
968
+ }
969
+ if (index.through < tail && records.length === 0) {
970
+ return yield* storeError(
971
+ 'rebuild work',
972
+ 'Canonical rebuild cannot advance within its byte bound',
973
+ )
974
+ }
975
+
976
+ const commitWork = yield* prepareWork(index, records).pipe(
977
+ Effect.provideService(CryptoDigest.Digest, crypto),
978
+ )
979
+
980
+ // Shared writer gate fences the current tail; publish native locators and catalogue together.
981
+ const next = yield* Effect.sync(() => {
982
+ const native = prepareIndexes(rebuildingIndexes, records)
983
+ const rebuilt = commitWork()
984
+ const complete = rebuilt.through === tail
985
+
986
+ const next: WorkIndex = {
987
+ version: rebuilt.version,
988
+ through: rebuilt.through,
989
+ reporting: rebuilt.reporting,
990
+ entryCount: rebuilt.entryCount,
991
+ entries: rebuilt.entries,
992
+ workers: rebuilt.workers,
993
+ liveInputs: rebuilt.liveInputs,
994
+ inputsByWorker: rebuilt.inputsByWorker,
995
+ state: complete ? 'ready' : 'rebuilding',
996
+ ...(complete ? {} : { rebuildingIndexes: native.indexes }),
997
+ }
998
+
999
+ native.commit()
1000
+ if (thread !== undefined && complete) {
1001
+ MutableRef.set(state.ref, {
1002
+ threads: new Map(current.threads).set(request.threadId, {
1003
+ ...thread,
1004
+ ...native.indexes,
1005
+ }),
1006
+ })
1007
+ }
1008
+ publishWork(request.threadId, next)
1009
+
1010
+ return next
1011
+ })
1012
+
1013
+ return {
1014
+ version: WORK_INDEX_VERSION,
1015
+ threadId: request.threadId,
1016
+ state: next.state,
1017
+ throughSequence: next.through,
1018
+ tailSequence: tail,
1019
+ processedRecords: records.length,
1020
+ processedBytes: bytes,
1021
+ }
1022
+ }),
1023
+ ),
1024
+ }
1025
+
1026
+ yield* Effect.addFinalizer(() => PubSub.shutdown(updates))
1027
+
1028
+ const materialize: ThreadStore['Service']['materialize'] = Effect.fnUntraced(
1029
+ function*(unvalidated) {
1030
+ const request = yield* validate(ThreadMaterialization, 'materialize', unvalidated)
1031
+
1032
+ const decision = yield* Ref.modify(
1033
+ state,
1034
+ (current): readonly [MaterializeDecision, MemoryState] => {
1035
+ const existing = current.threads.get(request.threadId)
1036
+
1037
+ if (existing !== undefined) return [{ _tag: 'success' }, current]
1038
+ if (
1039
+ !MutableRef.get(workState.ref).has(request.threadId) &&
1040
+ MutableRef.get(workState.ref).size >= maxThreads
1041
+ ) {
1042
+ return [
1043
+ {
1044
+ _tag: 'failure',
1045
+ error: storeError('materialize', `In-memory thread limit ${maxThreads} exceeded`),
1046
+ },
1047
+ current,
1048
+ ]
1049
+ }
1050
+ if (!transferPageFits(request.threadId)) {
1051
+ return [
1052
+ {
1053
+ _tag: 'failure',
1054
+ error: storeError(
1055
+ 'materialize',
1056
+ 'Thread identity exceeds its bounded transfer representation',
1057
+ ),
1058
+ },
1059
+ current,
1060
+ ]
1061
+ }
1062
+ const threads = new Map(current.threads)
1063
+
1064
+ threads.set(request.threadId, {
1065
+ tailSequence: ZERO_CANONICAL_SEQUENCE,
1066
+ byId: new Map(),
1067
+ workerRecords: new Map(),
1068
+ runInputs: new Map(),
1069
+ runRecords: new Map(),
1070
+ operationRecords: new Map(),
1071
+ handoffs: [],
1072
+ agentUpdates: [],
1073
+ deliveryPredecessors: [],
1074
+ toolDeclarations: new Map(),
1075
+ promptEvidence: [],
1076
+ modelCompletions: [],
1077
+ applicationInputs: [],
1078
+ durableOwners: [],
1079
+ windowBoundaries: new Map(),
1080
+ ranges: new Map(),
1081
+ rangeStarts: [],
1082
+ archiveContents: new Map(),
1083
+ chunks: new Map(),
1084
+ batchesByFirst: new Map(),
1085
+ batches: new Map(),
1086
+ executions: new Map(),
1087
+ executionCommits: new Map(),
1088
+ })
1089
+
1090
+ publishWork(request.threadId, emptyWorkIndex())
1091
+
1092
+ return [{ _tag: 'success' }, { threads }]
1093
+ },
1094
+ )
1095
+
1096
+ if (decision._tag === 'failure') return yield* decision.error
1097
+ },
1098
+ )
1099
+
1100
+ const prepareAppend = Effect.fnUntraced(function*(unvalidated: AppendRequest) {
1101
+ const captured = yield* PreparedAppend.capture(unvalidated)
1102
+ const request = captured
1103
+ const batchJson = captured.batchJson
1104
+
1105
+ const batchBytes = new TextEncoder().encode(batchJson).byteLength
1106
+
1107
+ if (batchBytes > 16 * 1024 * 1024) {
1108
+ return yield* storeError('append', 'Canonical batch exceeds 16 MiB')
1109
+ }
1110
+
1111
+ const offsetBytes = 4 * Math.ceil(utf8ByteLength(request.threadId) / 3) + 36
1112
+
1113
+ if (!canonicalBatchFitsTransfer(request.threadId, request.batch, batchBytes, offsetBytes)) {
1114
+ return yield* storeError(
1115
+ 'append',
1116
+ 'Canonical batch exceeds its bounded transfer representation',
1117
+ )
1118
+ }
1119
+
1120
+ const deliveries = yield* prepareCanonicalMessageDeliveries(
1121
+ request.threadId,
1122
+ request.batch.records,
1123
+ ).pipe(
1124
+ Effect.provideService(CryptoDigest.Digest, crypto),
1125
+ Effect.mapError((cause) => deliveryError('Invalid canonical delivery', cause)),
1126
+ )
1127
+
1128
+ return { request, batchJson, deliveries }
1129
+ })
1130
+
1131
+ const appendPrepared = Effect.fnUntraced(function*({
1132
+ request,
1133
+ batchJson,
1134
+ deliveries,
1135
+ }: PreparedMemoryAppend) {
1136
+ // Every caller holds the shared kernel mutation gate across validation and Ref publication.
1137
+ const current = yield* Ref.get(state)
1138
+ const thread = current.threads.get(request.threadId)
1139
+
1140
+ const executionIntent = JSON.stringify({
1141
+ batch: batchJson,
1142
+ operational: (request.executions ?? []).flatMap((update) =>
1143
+ update.facts.map((fact) => Schema.encodeSync(RecordEnvelope)(fact))
1144
+ ),
1145
+ })
1146
+
1147
+ const latestIntent = thread === undefined
1148
+ ? undefined
1149
+ : [...thread.executionCommits.values()].find(
1150
+ (entry) => entry.batchId === request.batch.batchId,
1151
+ )
1152
+
1153
+ if (thread !== undefined && latestIntent === undefined && request.batch.records.length === 0) {
1154
+ for (const update of request.executions ?? []) {
1155
+ const prior = thread.executions.get(update.checkpoint.progress.runId)
1156
+
1157
+ if (
1158
+ prior !== undefined &&
1159
+ update.previousRevision < prior.progress.revision &&
1160
+ update.facts.every((fact) => prior.operational.some((known) => known.recordId === fact.recordId))
1161
+ ) {
1162
+ return yield* AppendConflict.make({
1163
+ threadId: request.threadId,
1164
+ batchId: request.batch.batchId,
1165
+ reason: 'stale-command',
1166
+ })
1167
+ }
1168
+ }
1169
+ }
1170
+ if (
1171
+ thread !== undefined &&
1172
+ thread.tailSequence === request.expectedTailSequence &&
1173
+ !thread.batches.has(request.batch.batchId) &&
1174
+ latestIntent === undefined
1175
+ ) {
1176
+ const executions = request.executions ?? []
1177
+
1178
+ if (
1179
+ new Set(executions.map((update) => update.checkpoint.progress.runId)).size !==
1180
+ executions.length
1181
+ ) {
1182
+ return yield* storeError('append', 'Duplicate active execution identity')
1183
+ }
1184
+ for (const update of request.executions ?? []) {
1185
+ const prior = thread.executions.get(update.checkpoint.progress.runId)
1186
+
1187
+ if ((prior?.progress.revision ?? 0) !== update.previousRevision) {
1188
+ return yield* AppendConflict.make({
1189
+ threadId: request.threadId,
1190
+ batchId: request.batch.batchId,
1191
+ reason: 'tail',
1192
+ actualTailSequence: thread.tailSequence,
1193
+ })
1194
+ }
1195
+ if (
1196
+ update.checkpoint.throughSequence !==
1197
+ thread.tailSequence + request.batch.records.length ||
1198
+ update.checkpoint.batchId !== request.batch.batchId ||
1199
+ (prior !== undefined && update.checkpoint.originalSequence !== prior.originalSequence)
1200
+ ) {
1201
+ return yield* storeError(
1202
+ 'append',
1203
+ 'Active checkpoint differs from its committed history boundary',
1204
+ )
1205
+ }
1206
+ if (
1207
+ update.retire &&
1208
+ ![
1209
+ ...request.batch.records,
1210
+ ...(thread.runRecords.get(update.checkpoint.progress.runId) ?? []).map(
1211
+ (entry) => entry.record,
1212
+ ),
1213
+ ].some(
1214
+ ({ payload }) =>
1215
+ payload._tag === 'SubmissionSettled' &&
1216
+ payload.runId === update.checkpoint.progress.runId &&
1217
+ payload.submissionId === update.checkpoint.progress.submissionId,
1218
+ )
1219
+ ) {
1220
+ return yield* storeError(
1221
+ 'append',
1222
+ 'Active state cannot retire without a canonical terminal outcome',
1223
+ )
1224
+ }
1225
+ }
1226
+ yield* validateProgressAppend(
1227
+ prepareProgressAppend(request.batch.records),
1228
+ request.executions,
1229
+ ).pipe(
1230
+ Effect.provideService(ProgressAppendReader, {
1231
+ previous: (runId) => Effect.succeed(thread.executions.get(runId)?.progress),
1232
+ initial: (next) => Effect.succeed((thread.runRecords.get(next.runId) ?? []).map((entry) => entry.record)),
1233
+ }),
1234
+ )
1235
+ }
1236
+
1237
+ const currentWork = (yield* Ref.get(workState)).get(request.threadId)
1238
+
1239
+ const preparedWork = thread !== undefined &&
1240
+ thread.tailSequence === request.expectedTailSequence &&
1241
+ !thread.batches.has(request.batch.batchId) &&
1242
+ latestIntent === undefined &&
1243
+ currentWork?.version === WORK_INDEX_VERSION &&
1244
+ currentWork.state === 'ready' &&
1245
+ currentWork.through === thread.tailSequence &&
1246
+ currentWork.entryCount === currentWork.entries.size
1247
+ ? yield* prepareWork(
1248
+ currentWork,
1249
+ batchEnvelopes(
1250
+ request.threadId,
1251
+ request.batch,
1252
+ decodeCanonicalSequence(thread.tailSequence + 1),
1253
+ ),
1254
+ ).pipe(Effect.provideService(CryptoDigest.Digest, crypto))
1255
+ : undefined
1256
+
1257
+ let commitDeliveries: (() => void) | undefined
1258
+
1259
+ if (deliveries.length > 0) {
1260
+ if (deliveryWriter === undefined) {
1261
+ return yield* deliveryError(
1262
+ 'Canonical messages require a paired MemoryMessageDeliveryStore',
1263
+ MessageDeliveryError.make({ reason: 'storage', operation: 'canonical publication' }),
1264
+ )
1265
+ }
1266
+ commitDeliveries = yield* deliveryWriter(deliveries).pipe(
1267
+ Effect.mapError((cause) => deliveryError('Canonical delivery rejected', cause)),
1268
+ )
1269
+ }
1270
+
1271
+ const decision = yield* Effect.uninterruptible(
1272
+ Ref.modify(state, (current): readonly [AppendDecision, MemoryState] => {
1273
+ const thread = current.threads.get(request.threadId)
1274
+
1275
+ if (thread === undefined) {
1276
+ return [
1277
+ {
1278
+ _tag: 'failure',
1279
+ error: ThreadNotMaterialized.make({
1280
+ threadId: request.threadId,
1281
+ }),
1282
+ },
1283
+ current,
1284
+ ]
1285
+ }
1286
+ const priorExecution = latestIntent
1287
+
1288
+ if (priorExecution !== undefined) {
1289
+ if (priorExecution.intent !== executionIntent) {
1290
+ return [
1291
+ {
1292
+ _tag: 'failure',
1293
+ error: AppendConflict.make({
1294
+ threadId: request.threadId,
1295
+ batchId: request.batch.batchId,
1296
+ reason: 'batch-content',
1297
+ }),
1298
+ },
1299
+ current,
1300
+ ]
1301
+ }
1302
+
1303
+ commitDeliveries?.()
1304
+
1305
+ return [
1306
+ {
1307
+ _tag: 'success',
1308
+ result: AppendResult.make({ ...priorExecution.result, replayed: true }),
1309
+ records: [],
1310
+ },
1311
+ current,
1312
+ ]
1313
+ }
1314
+ const previous = thread.batches.get(request.batch.batchId)
1315
+
1316
+ if (previous !== undefined) {
1317
+ if (previous.batchJson !== batchJson) {
1318
+ return [
1319
+ {
1320
+ _tag: 'failure',
1321
+ error: AppendConflict.make({
1322
+ threadId: request.threadId,
1323
+ batchId: request.batch.batchId,
1324
+ reason: 'batch-content',
1325
+ }),
1326
+ },
1327
+ current,
1328
+ ]
1329
+ }
1330
+
1331
+ commitDeliveries?.()
1332
+
1333
+ return [
1334
+ {
1335
+ _tag: 'success',
1336
+ result: AppendResult.make({
1337
+ firstSequence: previous.result.firstSequence,
1338
+ lastSequence: previous.result.lastSequence,
1339
+ replayed: true,
1340
+ }),
1341
+ records: [],
1342
+ },
1343
+ current,
1344
+ ]
1345
+ }
1346
+ if (request.expectedTailSequence !== thread.tailSequence) {
1347
+ return [
1348
+ {
1349
+ _tag: 'failure',
1350
+ error: AppendConflict.make({
1351
+ threadId: request.threadId,
1352
+ batchId: request.batch.batchId,
1353
+ reason: 'tail',
1354
+ actualTailSequence: thread.tailSequence,
1355
+ }),
1356
+ },
1357
+ current,
1358
+ ]
1359
+ }
1360
+ const batchRecordIds = new Set<RecordId>()
1361
+
1362
+ for (const record of request.batch.records) {
1363
+ if (thread.byId.has(record.recordId) || batchRecordIds.has(record.recordId)) {
1364
+ return [
1365
+ {
1366
+ _tag: 'failure',
1367
+ error: AppendConflict.make({
1368
+ threadId: request.threadId,
1369
+ batchId: request.batch.batchId,
1370
+ reason: 'record-identity',
1371
+ }),
1372
+ },
1373
+ current,
1374
+ ]
1375
+ }
1376
+ batchRecordIds.add(record.recordId)
1377
+ }
1378
+
1379
+ const records = batchEnvelopes(
1380
+ request.threadId,
1381
+ request.batch,
1382
+ decodeCanonicalSequence(thread.tailSequence + 1),
1383
+ )
1384
+
1385
+ const lastSequence = decodeCanonicalSequence(thread.tailSequence + records.length)
1386
+
1387
+ const result = AppendResult.make({
1388
+ firstSequence: decodeCanonicalSequence(
1389
+ thread.tailSequence + (records.length > 0 ? 1 : 0),
1390
+ ),
1391
+ lastSequence,
1392
+ replayed: false,
1393
+ })
1394
+
1395
+ const indexes = prepareIndexes(thread, records)
1396
+
1397
+ const next: StoredThread = {
1398
+ ...thread,
1399
+ ...indexes.indexes,
1400
+ tailSequence: lastSequence,
1401
+ }
1402
+
1403
+ // Every rejection and asynchronous validation precedes this synchronous publication.
1404
+ if (records.length > 0) {
1405
+ thread.batches.set(request.batch.batchId, { result, batchJson })
1406
+ thread.batchesByFirst.set(result.firstSequence, request.batch.batchId)
1407
+ retainRecords(thread, records)
1408
+ }
1409
+ for (const update of request.executions ?? []) {
1410
+ const runId = update.checkpoint.progress.runId
1411
+
1412
+ if (update.retire) {
1413
+ thread.executions.delete(runId)
1414
+ thread.executionCommits.delete(runId)
1415
+ } else {
1416
+ thread.executions.set(runId, update.checkpoint)
1417
+ thread.executionCommits.set(runId, {
1418
+ batchId: request.batch.batchId,
1419
+ intent: executionIntent,
1420
+ result,
1421
+ })
1422
+ }
1423
+ }
1424
+ indexes.commit()
1425
+ if (preparedWork !== undefined) publishWork(request.threadId, preparedWork())
1426
+ current.threads.set(request.threadId, next)
1427
+ commitDeliveries?.()
1428
+
1429
+ const publication: readonly [AppendDecision, MemoryState] = [
1430
+ { _tag: 'success', result, records },
1431
+ current,
1432
+ ]
1433
+
1434
+ return publication
1435
+ }).pipe(
1436
+ Effect.tap((decision) =>
1437
+ decision._tag === 'success' && decision.records.length > 0
1438
+ ? PubSub.publish(updates, undefined)
1439
+ : Effect.void
1440
+ ),
1441
+ ),
1442
+ )
1443
+
1444
+ if (decision._tag === 'failure') return yield* decision.error
1445
+
1446
+ return decision.result
1447
+ })
1448
+
1449
+ const append: ThreadStore['Service']['append'] = Effect.fn('MemoryThreadStore.append')(
1450
+ (request) =>
1451
+ prepareAppend(request).pipe(
1452
+ Effect.flatMap((prepared) =>
1453
+ owner.withProgress(prepared.request.threadId, withMutation(appendPrepared(prepared)))
1454
+ ),
1455
+ ),
1456
+ )
1457
+
1458
+ const countPeerMessages: NonNullable<ThreadStore['Service']['countPeerMessages']> = Effect.fnUntraced(
1459
+ function*(request) {
1460
+ yield* validate(ThreadPeerCountRequest, 'countPeerMessages', request)
1461
+ yield* findThread(yield* Ref.get(state), request.threadId)
1462
+
1463
+ return Math.min(
1464
+ deliveryTransfer?.peerCount(request.threadId, request.nowMillis, request.limit) ?? 0,
1465
+ request.limit,
1466
+ )
1467
+ },
1468
+ )
1469
+
1470
+ const readSnapshot = (
1471
+ threadId: ThreadId,
1472
+ afterSequence: CanonicalSequence | undefined,
1473
+ limit: number,
1474
+ ) =>
1475
+ Ref.get(state).pipe(
1476
+ Effect.flatMap((current) => findThread(current, threadId)),
1477
+ Effect.flatMap((thread) => {
1478
+ // Append assigns gap-free sequences starting at 1, so the exclusive cursor is an index.
1479
+ const start = afterSequence ?? ZERO_CANONICAL_SEQUENCE
1480
+
1481
+ return storedPage(thread, start, limit)
1482
+ }),
1483
+ )
1484
+
1485
+ const selectedStream = (
1486
+ sources: ReadonlyArray<ReadonlyArray<CanonicalRecordEnvelope>>,
1487
+ after: number,
1488
+ through: number,
1489
+ maximum: number,
1490
+ ) =>
1491
+ Stream.paginate({ after, count: 0 }, (cursor) =>
1492
+ Effect.gen(function*() {
1493
+ const page: Array<CanonicalRecordEnvelope> = []
1494
+ let bytes = 0
1495
+ let last = cursor.after
1496
+
1497
+ while (page.length < Math.min(READ_PAGE_SIZE, maximum - cursor.count)) {
1498
+ let selected: CanonicalRecordEnvelope | undefined
1499
+
1500
+ for (const source of sources) {
1501
+ const next = source[upperSequence(source, last)]
1502
+
1503
+ if (
1504
+ next !== undefined &&
1505
+ next.sequence <= through &&
1506
+ (selected === undefined || next.sequence < selected.sequence)
1507
+ ) {
1508
+ selected = next
1509
+ }
1510
+ }
1511
+ if (selected === undefined) break
1512
+ const size = canonicalRecordBytes(selected.record)
1513
+
1514
+ if (size > 32 * 1024 * 1024) {
1515
+ return yield* storeError('read', 'Canonical value exceeds the page byte bound')
1516
+ }
1517
+ if (bytes + size > 32 * 1024 * 1024) break
1518
+ bytes += size
1519
+ page.push(selected)
1520
+ last = selected.sequence
1521
+ }
1522
+ const next = { after: last, count: cursor.count + page.length }
1523
+
1524
+ return [
1525
+ page,
1526
+ page.length === 0 || next.count >= maximum
1527
+ ? Option.none<typeof next>()
1528
+ : Option.some(next),
1529
+ ] as const
1530
+ }))
1531
+
1532
+ const readFromThread = (threadId: ThreadId, thread: StoredThread, request: ThreadReadRequest) =>
1533
+ Stream.unwrap(
1534
+ Effect.gen(function*() {
1535
+ if (request.threadId !== threadId) {
1536
+ return yield* storeError('read snapshot', 'Thread differs from the captured snapshot')
1537
+ }
1538
+
1539
+ if (!('selection' in request)) {
1540
+ return Stream.paginate(
1541
+ { after: request.afterSequence ?? ZERO_CANONICAL_SEQUENCE, count: 0 },
1542
+ (cursor) =>
1543
+ Effect.gen(function*() {
1544
+ const page = yield* storedPage(
1545
+ thread,
1546
+ cursor.after,
1547
+ Math.min(READ_PAGE_SIZE, request.limit - cursor.count),
1548
+ )
1549
+
1550
+ const next = {
1551
+ after: page.at(-1)?.sequence ?? cursor.after,
1552
+ count: cursor.count + page.length,
1553
+ }
1554
+
1555
+ return [
1556
+ page,
1557
+ page.length === 0 || next.count >= request.limit
1558
+ ? Option.none<typeof next>()
1559
+ : Option.some(next),
1560
+ ] as const
1561
+ }),
1562
+ )
1563
+ }
1564
+ const selection = request.selection
1565
+
1566
+ if (
1567
+ 'expectedTailSequence' in selection &&
1568
+ selection.expectedTailSequence !== thread.tailSequence
1569
+ ) {
1570
+ return yield* storeError('selected read', 'Canonical tail changed')
1571
+ }
1572
+ if ('throughSequence' in selection && selection.throughSequence > thread.tailSequence) {
1573
+ return yield* storeError('selected read', 'Captured sequence is ahead of canonical tail')
1574
+ }
1575
+
1576
+ const through = 'throughSequence' in selection ? selection.throughSequence : thread.tailSequence
1577
+
1578
+ const after = request.page.afterSequence ?? 0
1579
+ let sources: ReadonlyArray<ReadonlyArray<CanonicalRecordEnvelope>> = []
1580
+
1581
+ const one = (entry: CanonicalRecordEnvelope | null | undefined) =>
1582
+ entry === undefined || entry === null ? [] : [entry]
1583
+
1584
+ const latest = (entries: ReadonlyArray<CanonicalRecordEnvelope>) =>
1585
+ one(entries[upperSequence(entries, through) - 1])
1586
+
1587
+ switch (selection._tag) {
1588
+ case 'RecordId':
1589
+ sources = [one(thread.byId.get(selection.recordId))]
1590
+ break
1591
+ case 'RunInput': {
1592
+ const entry = thread.runInputs.get(selection.runId)
1593
+
1594
+ if (entry === null) {
1595
+ return yield* storeError('selected read', 'Ambiguous original Run input')
1596
+ }
1597
+ sources = [one(entry)]
1598
+ break
1599
+ }
1600
+ case 'ToolDeclaration': {
1601
+ const entry = thread.toolDeclarations.get(selection.settlementRecordId)
1602
+
1603
+ if (entry === null) {
1604
+ return yield* storeError('selected read', 'Ambiguous original tool declaration')
1605
+ }
1606
+ if (entry !== undefined) {
1607
+ const payload = entry.record.payload
1608
+
1609
+ if (
1610
+ payload._tag !== 'ModelResponseRecorded' ||
1611
+ !payload.toolOperations.some(
1612
+ (operation) =>
1613
+ toolCallSettledRecordId(payload.runId, payload.turn, operation.toolCallId) ===
1614
+ selection.settlementRecordId,
1615
+ )
1616
+ ) {
1617
+ return yield* storeError('selected read', 'Invalid exact tool declaration pointer')
1618
+ }
1619
+ }
1620
+ sources = [one(entry)]
1621
+ break
1622
+ }
1623
+ case 'RunEvidence':
1624
+ sources = [
1625
+ thread.runRecords.get(selection.runId) ?? [],
1626
+ [
1627
+ submissionInputRecordId(selection.submissionId),
1628
+ submissionAbortRecordId(selection.submissionId),
1629
+ submissionSettlementRecordId(selection.submissionId),
1630
+ ]
1631
+ .flatMap((id) => one(thread.byId.get(id)))
1632
+ .sort((a, b) => a.sequence - b.sequence),
1633
+ ]
1634
+ break
1635
+ case 'OperationEvidence':
1636
+ sources = [
1637
+ thread.operationRecords.get(
1638
+ JSON.stringify([selection.runId, selection.toolCallId]),
1639
+ ) ?? [],
1640
+ ...selection.approvalToolCallIds.flatMap((toolCallId) =>
1641
+ toolCallId === selection.toolCallId
1642
+ ? []
1643
+ : [
1644
+ thread.operationRecords.get(
1645
+ JSON.stringify([selection.runId, toolCallId, 'approval']),
1646
+ ) ?? [],
1647
+ ]
1648
+ ),
1649
+ one(thread.byId.get(selection.originRecordId)),
1650
+ ]
1651
+ break
1652
+ case 'LastAgentUpdate':
1653
+ sources = [latest(thread.agentUpdates)]
1654
+ break
1655
+ case 'DeliveryPredecessor':
1656
+ sources = [latest(thread.deliveryPredecessors)]
1657
+ break
1658
+ case 'LatestModelCompleted':
1659
+ sources = [latest(thread.modelCompletions)]
1660
+ break
1661
+ case 'LatestApplicationInput':
1662
+ sources = [latest(thread.applicationInputs)]
1663
+ break
1664
+ case 'DurableHistoryOwner':
1665
+ sources = [one(thread.durableOwners[0])]
1666
+ break
1667
+ case 'PromptEvidence':
1668
+ sources = [thread.promptEvidence]
1669
+ break
1670
+ case 'WorkHandoffs':
1671
+ sources = [thread.handoffs]
1672
+ break
1673
+ case 'ContextWindowBoundary': {
1674
+ // Match native SQL's disjoint coverage-prefix seeks. Each bucket contains
1675
+ // canonical sequence order; captured-tail reads never assume monotone coverage.
1676
+ let start = 0
1677
+ let selected: CanonicalRecordEnvelope | undefined
1678
+
1679
+ while (start < selection.atSequence) {
1680
+ const remaining = selection.atSequence - start
1681
+ let height = Math.floor(Math.log2(remaining))
1682
+
1683
+ while (2 ** height > remaining) height--
1684
+ const width = 2 ** height
1685
+ const entries = thread.windowBoundaries.get(`${height}:${start / width}`) ?? []
1686
+ const candidate = entries[upperSequence(entries, through) - 1]
1687
+
1688
+ if (
1689
+ candidate !== undefined &&
1690
+ (selected === undefined || candidate.sequence > selected.sequence)
1691
+ ) {
1692
+ selected = candidate
1693
+ }
1694
+ start += width
1695
+ }
1696
+ sources = [one(selected)]
1697
+ break
1698
+ }
1699
+ case 'WorkerStop':
1700
+ sources = [latest(thread.workerRecords.get(`stop:${selection.workerThreadId}`) ?? [])]
1701
+ break
1702
+ case 'WorkerExecution':
1703
+ sources = [
1704
+ thread.workerRecords.get('execution:UserInputRecorded') ?? [],
1705
+ thread.workerRecords.get('execution:SubmissionSettled') ?? [],
1706
+ ]
1707
+ break
1708
+ case 'WorkerState':
1709
+ sources = [
1710
+ thread.workerRecords.get('worker') ?? [],
1711
+ ...(selection.sourceSubmissionId === undefined
1712
+ ? []
1713
+ : [
1714
+ thread.workerRecords.get(`subtree:${selection.sourceSubmissionId}`) ?? [],
1715
+ thread.workerRecords.get(
1716
+ `joined:${runIdForSubmission(selection.sourceSubmissionId)}`,
1717
+ ) ?? [],
1718
+ thread.workerRecords.get(`funding:${selection.sourceSubmissionId}`) ?? [],
1719
+ ]),
1720
+ ]
1721
+ break
1722
+ case 'LiveWorkerInputs': {
1723
+ const index = yield* readyIndex(request.threadId, thread.tailSequence).pipe(
1724
+ Effect.mapError((e) => storeError('selected read', e.message)),
1725
+ )
1726
+
1727
+ if (selection.throughSequence !== thread.tailSequence) {
1728
+ return yield* storeError(
1729
+ 'selected read',
1730
+ 'Live work requires the current exact tail',
1731
+ )
1732
+ }
1733
+
1734
+ const locators = selection.workerThreadId === undefined
1735
+ ? index.liveInputs
1736
+ : (index.inputsByWorker.get(selection.workerThreadId) ?? [])
1737
+
1738
+ const start = liveInputPosition(locators, after + 1)
1739
+ const selected: Array<CanonicalRecordEnvelope> = []
1740
+
1741
+ for (let at = start; at < Math.min(locators.length, start + request.page.limit); at++) {
1742
+ const entry = index.entries.get(locators[at].id)
1743
+
1744
+ const origin = entry === undefined ? undefined : thread.byId.get(entry.originRecordId)
1745
+
1746
+ if (
1747
+ entry?.owner._tag !== 'WorkerInput' ||
1748
+ origin?.record.payload._tag !== 'WorkerInputRequested' ||
1749
+ origin.sequence !== locators[at].sequence ||
1750
+ origin.record.payload.admission.origin.worker.threadId !==
1751
+ entry.owner.workerThreadId ||
1752
+ (origin.record.payload.admission.reportKind === 'update') !== entry.owner.update
1753
+ ) {
1754
+ return yield* storeError(
1755
+ 'selected read',
1756
+ 'Invalid live worker input locator or origin',
1757
+ )
1758
+ }
1759
+ selected.push(origin)
1760
+ }
1761
+ sources = [selected]
1762
+ break
1763
+ }
1764
+ }
1765
+
1766
+ return selectedStream(sources, after, through, request.page.limit)
1767
+ }),
1768
+ )
1769
+
1770
+ const read: ThreadStore['Service']['read'] = (input) =>
1771
+ Stream.unwrap(
1772
+ Effect.gen(function*() {
1773
+ const request = yield* validate(ThreadReadRequest, 'read', input)
1774
+ const thread = yield* findThread(MutableRef.get(state.ref), request.threadId)
1775
+
1776
+ return readFromThread(request.threadId, thread, request)
1777
+ }),
1778
+ )
1779
+
1780
+ const decodePromptRecord = Schema.decodeUnknownEffect(PromptRecord)
1781
+
1782
+ const readPrompt: ThreadStore['Service']['readPrompt'] = (input) =>
1783
+ Stream.unwrap(
1784
+ Effect.gen(function*() {
1785
+ const request = yield* validate(ThreadPromptRead, 'readPrompt', input)
1786
+ const thread = yield* findThread(MutableRef.get(state.ref), request.threadId)
1787
+
1788
+ if (request.throughSequence > thread.tailSequence) {
1789
+ return yield* storeError('readPrompt', 'Captured sequence is ahead of canonical tail')
1790
+ }
1791
+ const start = upperSequence(thread.promptEvidence, request.afterSequence ?? 0)
1792
+ const records: Array<PromptRecordEnvelope> = []
1793
+
1794
+ for (
1795
+ let at = start;
1796
+ at < Math.min(thread.promptEvidence.length, start + request.limit);
1797
+ at++
1798
+ ) {
1799
+ const entry = thread.promptEvidence[at]
1800
+
1801
+ if (entry.sequence > request.throughSequence) break
1802
+
1803
+ const record = yield* decodePromptRecord(
1804
+ Schema.is(ExportedRecord)(entry.record) &&
1805
+ Object.prototype.isPrototypeOf.call(ExportedRecord.prototype, entry.record)
1806
+ ? entry.record.wire
1807
+ : entry.record,
1808
+ ).pipe(
1809
+ Effect.mapError((cause) => storeError('readPrompt', 'Invalid prompt record', cause)),
1810
+ )
1811
+
1812
+ records.push({ threadId: request.threadId, sequence: entry.sequence, record })
1813
+ }
1814
+
1815
+ return Stream.fromIterable(records)
1816
+ }),
1817
+ )
1818
+
1819
+ const observe: ThreadStore['Service']['observe'] = (unvalidated) =>
1820
+ Stream.unwrap(
1821
+ Effect.gen(function*() {
1822
+ const request = yield* validate(ThreadObservation, 'observe', unvalidated)
1823
+ let after = yield* offsetSequence(request.threadId, request.afterOffset)
1824
+ const subscription = yield* PubSub.subscribe(updates)
1825
+
1826
+ const drain = () =>
1827
+ Stream.paginate(after, (cursor) =>
1828
+ readSnapshot(request.threadId, cursor, READ_PAGE_SIZE).pipe(
1829
+ Effect.map((records) => {
1830
+ after = records.at(-1)?.sequence ?? cursor
1831
+
1832
+ return [
1833
+ records,
1834
+ records.length > 0 ? Option.some(after) : Option.none<CanonicalSequence>(),
1835
+ ] as const
1836
+ }),
1837
+ ))
1838
+
1839
+ return drain().pipe(
1840
+ Stream.concat(
1841
+ Stream.fromEffectRepeat(PubSub.take(subscription)).pipe(Stream.flatMap(drain)),
1842
+ ),
1843
+ )
1844
+ }),
1845
+ )
1846
+
1847
+ const emptyThread = (): StoredThread => ({
1848
+ ...emptyIndexes(),
1849
+ tailSequence: ZERO_CANONICAL_SEQUENCE,
1850
+ ranges: new Map(),
1851
+ rangeStarts: [],
1852
+ archiveContents: new Map(),
1853
+ chunks: new Map(),
1854
+ batches: new Map(),
1855
+ executions: new Map(),
1856
+ executionCommits: new Map(),
1857
+ batchesByFirst: new Map(),
1858
+ })
1859
+
1860
+ const makeExportReader = (idleOnly: boolean) =>
1861
+ ThreadExporterReader.of({
1862
+ snapshot: Effect.fnUntraced(function*(threadId: ThreadId, captured?: TransferManifest) {
1863
+ const thread = MutableRef.get(state.ref).threads.get(threadId)
1864
+
1865
+ const facts = ledgerTransfer === undefined
1866
+ ? { idle: true, admissions: 0, aborts: 0, approvals: 0, resolutions: 0 }
1867
+ : yield* ledgerTransfer.snapshot(threadId)
1868
+
1869
+ const delivered = deliveryTransfer?.snapshot(threadId) ?? { idle: true, deliveries: 0 }
1870
+
1871
+ if (thread === undefined && facts.admissions === 0 && delivered.deliveries === 0) {
1872
+ return yield* ThreadNotMaterialized.make({ threadId })
1873
+ }
1874
+ if (idleOnly) {
1875
+ const index = yield* readyIndex(threadId, thread?.tailSequence ?? 0).pipe(
1876
+ Effect.mapError((e) => storeError('export', e.message)),
1877
+ )
1878
+
1879
+ if (
1880
+ owner.hasOwner(threadId) ||
1881
+ (thread?.executions.size ?? 0) > 0 ||
1882
+ index.entries.size > 0 ||
1883
+ !facts.idle ||
1884
+ !delivered.idle
1885
+ ) {
1886
+ return yield* ThreadExportRejected.make({ threadId, reason: 'non-idle' })
1887
+ }
1888
+ // Only the first page performs the full closed-receipt proof. The caller keeps
1889
+ // the source quiescent; subsequent pages still check current work and the tail.
1890
+ if (captured === undefined && thread !== undefined) {
1891
+ yield* Effect.gen(function*() {
1892
+ for (const runId of thread.runRecords.keys()) {
1893
+ yield* validateClosedRun(
1894
+ threadId,
1895
+ yield* Schema.decodeEffect(RunId)(runId).pipe(Effect.orDie),
1896
+ )
1897
+ }
1898
+ if (ledgerTransfer !== undefined) {
1899
+ const ledger = ledgerTransfer
1900
+
1901
+ yield* Stream.runForEach(ledger.submissions(threadId), (submission) =>
1902
+ Effect.gen(function*() {
1903
+ const admission = yield* ledger.admission(threadId, submission.submissionId)
1904
+
1905
+ if (admission === undefined) {
1906
+ return yield* storeError('export', 'Missing immutable admission')
1907
+ }
1908
+ yield* rebuildClosedSubmission(admission)
1909
+ }))
1910
+ }
1911
+ }).pipe(
1912
+ Effect.provide(ThreadImportReader.layer(importReader(threadId, thread))),
1913
+ Effect.mapError((cause) =>
1914
+ Schema.is(ThreadImportRejected)(cause)
1915
+ ? ThreadExportRejected.make({ threadId, reason: 'non-idle' })
1916
+ : cause
1917
+ ),
1918
+ )
1919
+ }
1920
+ }
1921
+
1922
+ return {
1923
+ format: CURRENT_RECORD_FORMAT,
1924
+ threadId,
1925
+ tailSequence: thread?.tailSequence ?? ZERO_CANONICAL_SEQUENCE,
1926
+ snapshot: {
1927
+ admissions: facts.admissions,
1928
+ aborts: facts.aborts,
1929
+ approvals: facts.approvals,
1930
+ resolutions: facts.resolutions,
1931
+ deliveries: delivered.deliveries,
1932
+ },
1933
+ ...(facts.workerSeal === undefined ? {} : { workerSeal: facts.workerSeal }),
1934
+ }
1935
+ }),
1936
+ batch: Effect.fnUntraced(function*(threadId: ThreadId, fromSequence: number) {
1937
+ const thread = yield* findThread(MutableRef.get(state.ref), threadId)
1938
+ const batchId = thread.batchesByFirst.get(fromSequence)
1939
+ const stored = batchId === undefined ? undefined : thread.batches.get(batchId)
1940
+
1941
+ if (
1942
+ stored === undefined ||
1943
+ new TextEncoder().encode(stored.batchJson).byteLength > 16 * 1024 * 1024
1944
+ ) {
1945
+ return yield* storeError('export', 'Missing or oversized canonical batch wire')
1946
+ }
1947
+ const batch = yield* decodeStoredBatch(stored.batchJson, 'export')
1948
+ const records: Array<ThreadExportRecord> = []
1949
+
1950
+ for (const [index, record] of batch.records.entries()) {
1951
+ const sequence = decodeCanonicalSequence(fromSequence + index)
1952
+ const exact = storedRecord(thread, sequence)
1953
+
1954
+ if (
1955
+ exact === undefined ||
1956
+ exact.batchId !== batch.batchId ||
1957
+ exact.record.recordId !== record.recordId
1958
+ ) {
1959
+ return yield* storeError('export', 'Canonical batch index differs from its wire')
1960
+ }
1961
+ records.push(
1962
+ ThreadExportRecord.make({
1963
+ threadId,
1964
+ batchId: batch.batchId,
1965
+ sequence,
1966
+ offset: observationOffset(threadId, sequence),
1967
+ record,
1968
+ }),
1969
+ )
1970
+ }
1971
+
1972
+ return { batches: [{ batchId: batch.batchId, producerId: batch.producerId }], records }
1973
+ }),
1974
+ facts: (threadId, section, after) => {
1975
+ const empty = Effect.succeed({
1976
+ facts: {
1977
+ admissions: [],
1978
+ commands: { aborts: [], approvals: [], resolutions: [] },
1979
+ deliveries: [],
1980
+ },
1981
+ after: after ?? '',
1982
+ })
1983
+
1984
+ return section === 'deliveries'
1985
+ ? (deliveryTransfer?.facts(threadId, after) ?? empty)
1986
+ : (ledgerTransfer?.facts(threadId, section, after) ?? empty)
1987
+ },
1988
+ })
1989
+
1990
+ const exportReader = makeExportReader(true)
1991
+ const verificationReader = makeExportReader(false)
1992
+
1993
+ const exportThread: ThreadStore['Service']['export'] = (request) =>
1994
+ exportThreadPage(request).pipe(Effect.provideService(ThreadExporterReader, exportReader))
1995
+
1996
+ const verificationPage: ThreadStore['Service']['export'] = (request) =>
1997
+ exportThreadPage(request).pipe(Effect.provideService(ThreadExporterReader, verificationReader))
1998
+
1999
+ const exactRunRecords = Effect.fnUntraced(function*(thread: StoredThread, runId: RunId) {
2000
+ const records: Array<CanonicalRecordEnvelope> = []
2001
+ let bytes = 0
2002
+ const facts = thread.runRecords.get(runId) ?? []
2003
+
2004
+ if (
2005
+ facts.length >
2006
+ MAX_RUN_EVIDENCE_RECORDS + RUN_TERMINAL_RESERVE_RECORDS + MAX_RUN_RECOVERY_SUFFIX_RECORDS
2007
+ ) {
2008
+ return yield* storeError('Run evidence', 'Run record bounds exceeded')
2009
+ }
2010
+ for (const entry of facts) {
2011
+ bytes += canonicalRecordBytes(entry.record)
2012
+ if (bytes > MAX_RUN_EVIDENCE_BYTES + MAX_RUN_TERMINAL_BYTES + MAX_RUN_RECOVERY_SUFFIX_BYTES) {
2013
+ return yield* storeError('Run evidence', 'Run byte bounds exceeded')
2014
+ }
2015
+ records.push(entry)
2016
+ }
2017
+
2018
+ return records.sort((a, b) => a.sequence - b.sequence)
2019
+ })
2020
+
2021
+ const exactRecordReader = (
2022
+ threadId: ThreadId,
2023
+ thread: StoredThread,
2024
+ ): Pick<
2025
+ ThreadImportReader['Service'],
2026
+ 'read' | 'record' | 'runRecords' | 'execution' | 'hasAgent'
2027
+ > => ({
2028
+ read: (input) =>
2029
+ Stream.unwrap(
2030
+ validate(ThreadReadRequest, 'read snapshot', input).pipe(
2031
+ Effect.map((request) => readFromThread(threadId, thread, request)),
2032
+ ),
2033
+ ),
2034
+ record: (id) => Effect.succeed(thread.byId.get(id)),
2035
+ runRecords: (id) => exactRunRecords(thread, id),
2036
+ execution: (id) => Effect.succeed(thread.executions.get(id)),
2037
+ hasAgent: (id) =>
2038
+ Effect.succeed(
2039
+ (thread.workerRecords.get('worker') ?? []).some(
2040
+ ({ record }) => record.payload._tag === 'ThreadCreated' && record.payload.agentId === id,
2041
+ ),
2042
+ ),
2043
+ })
2044
+
2045
+ const importReader = (id: ThreadId, thread: StoredThread): ThreadImportReader['Service'] => ({
2046
+ ...exactRecordReader(id, thread),
2047
+ admission: (sid) => ledgerTransfer?.admission(id, sid) ?? Effect.as(Effect.void, undefined),
2048
+ runOwner: (runId) =>
2049
+ runId.startsWith('run:')
2050
+ ? (ledgerTransfer?.admission(id, Schema.decodeSync(importSubmissionId)(runId.slice(4))) ??
2051
+ Effect.as(Effect.void, undefined))
2052
+ : Effect.as(Effect.void, undefined),
2053
+ commands: (sid) =>
2054
+ ledgerTransfer?.commands(sid) ??
2055
+ Effect.succeed({ aborts: [], approvals: [], resolutions: [] }),
2056
+ delivery: (messageId) => deliveryTransfer?.record(id, messageId) ?? Effect.as(Effect.void, undefined),
2057
+ })
2058
+
2059
+ const importThread: ThreadImport['Service']['import'] = (pages) =>
2060
+ captureImportSource(pages, (captured) =>
2061
+ withMutation(
2062
+ Effect.gen(function*() {
2063
+ const progress = makeThreadImportProgress()
2064
+ let staged: StoredThread | undefined
2065
+ let stagedWork = emptyWorkIndex()
2066
+ let stagedLedger: MemoryLedgerImport | undefined
2067
+ let stagedDelivery: MemoryDeliveryImport | undefined
2068
+ let existing: StoredThread | undefined
2069
+
2070
+ yield* Stream.runForEach(captured, (input) =>
2071
+ Effect.gen(function*() {
2072
+ const page = yield* prepareImportPage(progress, input).pipe(
2073
+ Effect.provideService(CryptoDigest.Digest, crypto),
2074
+ )
2075
+
2076
+ const id = page.archive.threadId
2077
+
2078
+ if (staged === undefined) {
2079
+ const current = MutableRef.get(state.ref)
2080
+
2081
+ existing = current.threads.get(id)
2082
+ const existingWork = MutableRef.get(workState.ref).get(id)
2083
+
2084
+ if (
2085
+ (existing !== undefined &&
2086
+ (existing.tailSequence > 0 ||
2087
+ existing.batches.size > 0 ||
2088
+ existing.executions.size > 0 ||
2089
+ existing.executionCommits.size > 0 ||
2090
+ existing.ranges.size > 0 ||
2091
+ existing.archiveContents.size > 0)) ||
2092
+ (existingWork !== undefined &&
2093
+ (existingWork.entries.size > 0 ||
2094
+ existingWork.state !== 'ready' ||
2095
+ existingWork.through !== 0))
2096
+ ) {
2097
+ return yield* ThreadImportRejected.make({
2098
+ threadId: id,
2099
+ reason: 'target-not-empty',
2100
+ message: 'Destination canonical Thread is not empty',
2101
+ })
2102
+ }
2103
+ if (
2104
+ !MutableRef.get(workState.ref).has(id) &&
2105
+ MutableRef.get(workState.ref).size >= maxThreads
2106
+ ) {
2107
+ return yield* storeError('import', 'Destination Thread capacity exceeded')
2108
+ }
2109
+ staged = emptyThread()
2110
+ stagedLedger = ledgerTransfer === undefined ? undefined : yield* ledgerTransfer.startImport(id)
2111
+ stagedDelivery = deliveryTransfer === undefined
2112
+ ? undefined
2113
+ : yield* deliveryTransfer.startImport(id)
2114
+ if (page.archive.workerSeal !== undefined && stagedLedger === undefined) {
2115
+ return yield* ThreadImportRejected.make({
2116
+ threadId: id,
2117
+ reason: 'unsupported-obligations',
2118
+ message: 'A paired ledger is required to preserve the worker seal',
2119
+ })
2120
+ }
2121
+ }
2122
+ if (page.archive.admissions.length > 0 && stagedLedger === undefined) {
2123
+ return yield* ThreadImportRejected.make({
2124
+ threadId: id,
2125
+ reason: 'unsupported-obligations',
2126
+ message: 'A paired ledger is required for admission restore',
2127
+ })
2128
+ }
2129
+ if (page.archive.deliveries.length > 0 && stagedDelivery === undefined) {
2130
+ return yield* ThreadImportRejected.make({
2131
+ threadId: id,
2132
+ reason: 'unsupported-obligations',
2133
+ message: 'A paired delivery store is required for delivery restore',
2134
+ })
2135
+ }
2136
+ for (const batch of page.batches) {
2137
+ if (
2138
+ !canonicalBatchFitsTransfer(
2139
+ id,
2140
+ batch.batch,
2141
+ utf8ByteLength(batch.batchJson),
2142
+ 4 * Math.ceil(utf8ByteLength(id) / 3) + 36,
2143
+ )
2144
+ ) {
2145
+ return yield* ThreadImportRejected.make({
2146
+ threadId: id,
2147
+ reason: 'unsupported-capacity',
2148
+ message: 'Canonical batch exceeds its bounded transfer representation',
2149
+ })
2150
+ }
2151
+
2152
+ if (staged.batches.has(batch.batch.batchId)) {
2153
+ return yield* invalidThreadArchive('Duplicate canonical batch identity', id)
2154
+ }
2155
+
2156
+ const records = page.records
2157
+ .filter((entry) => entry.batchId === batch.batch.batchId)
2158
+ .map((entry) =>
2159
+ CanonicalRecordEnvelope.make({
2160
+ ...entry,
2161
+ offset: observationOffset(id, entry.sequence),
2162
+ })
2163
+ )
2164
+
2165
+ for (const entry of records) {
2166
+ if (staged.byId.has(entry.record.recordId)) {
2167
+ return yield* invalidThreadArchive('Duplicate canonical record identity', id)
2168
+ }
2169
+ }
2170
+ const native = prepareIndexes(staged, records)
2171
+
2172
+ const commitWork = yield* prepareWork(stagedWork, records).pipe(
2173
+ Effect.provideService(CryptoDigest.Digest, crypto),
2174
+ )
2175
+
2176
+ retainRecords(staged, records)
2177
+ native.commit()
2178
+ staged = {
2179
+ ...staged,
2180
+ ...native.indexes,
2181
+ tailSequence: batch.lastSequence,
2182
+ }
2183
+ staged.batches.set(batch.batch.batchId, {
2184
+ batchJson: batch.batchJson,
2185
+ result: AppendResult.make({
2186
+ firstSequence: batch.firstSequence,
2187
+ lastSequence: batch.lastSequence,
2188
+ replayed: false,
2189
+ }),
2190
+ })
2191
+ staged.batchesByFirst.set(batch.firstSequence, batch.batch.batchId)
2192
+ stagedWork = commitWork()
2193
+ }
2194
+ if (stagedLedger !== undefined) yield* stagedLedger.stage(page)
2195
+ if (stagedDelivery !== undefined) yield* stagedDelivery.stage(page)
2196
+ }))
2197
+ const result = yield* finishThreadImport(progress)
2198
+
2199
+ if (staged === undefined) return yield* invalidThreadArchive('Missing transfer pages')
2200
+ const restoredThread = staged
2201
+ const id = result.threadId
2202
+
2203
+ const fallback = {
2204
+ admission: () => Effect.as(Effect.void, undefined),
2205
+ runOwner: () => Effect.as(Effect.void, undefined),
2206
+ commands: () => Effect.succeed({ aborts: [], approvals: [], resolutions: [] }),
2207
+ }
2208
+
2209
+ const reader: ThreadImportReader['Service'] = {
2210
+ ...exactRecordReader(id, restoredThread),
2211
+ ...(stagedLedger?.reader ?? fallback),
2212
+ delivery: stagedDelivery?.record ?? (() => Effect.as(Effect.void, undefined)),
2213
+ }
2214
+
2215
+ return yield* Effect.gen(function*() {
2216
+ for (const runId of restoredThread.runRecords.keys()) {
2217
+ yield* verifyRunContinuations(
2218
+ yield* reader.runRecords(
2219
+ yield* Schema.decodeEffect(RunId)(runId).pipe(Effect.orDie),
2220
+ ),
2221
+ { verifyContext: false },
2222
+ ).pipe(Effect.mapError((e) => invalidThreadArchive(e.message, id)))
2223
+ yield* validateClosedRun(
2224
+ id,
2225
+ yield* Schema.decodeEffect(RunId)(runId).pipe(Effect.orDie),
2226
+ )
2227
+ }
2228
+ let lastInputQueue = -1
2229
+
2230
+ for (let sequence = 1; sequence <= restoredThread.tailSequence; sequence++) {
2231
+ const entry = storedRecord(restoredThread, sequence)
2232
+
2233
+ if (entry === undefined) {
2234
+ return yield* invalidThreadArchive('Incomplete canonical staging', id)
2235
+ }
2236
+ yield* verifyImportedReferences(entry)
2237
+ const payload = entry.record.payload
2238
+
2239
+ if (payload._tag === 'UserInputRecorded' && payload.submissionId !== undefined) {
2240
+ const admission = yield* reader.admission(payload.submissionId)
2241
+
2242
+ if (admission === undefined || admission.queueSequence <= lastInputQueue) {
2243
+ return yield* invalidThreadArchive(
2244
+ 'Canonical inputs violate immutable admission order',
2245
+ id,
2246
+ )
2247
+ }
2248
+ lastInputQueue = admission.queueSequence
2249
+ }
2250
+
2251
+ if (
2252
+ payload._tag === 'UserInputRecorded' &&
2253
+ payload.submissionId !== undefined &&
2254
+ entry.record.recordId !== submissionInputRecordId(payload.submissionId)
2255
+ ) {
2256
+ return yield* invalidThreadArchive('Canonical input identity is ambiguous', id)
2257
+ }
2258
+ if (
2259
+ payload._tag === 'SubmissionSettled' &&
2260
+ entry.record.recordId !== submissionSettlementRecordId(payload.submissionId)
2261
+ ) {
2262
+ return yield* invalidThreadArchive(
2263
+ 'Canonical settlement identity is ambiguous',
2264
+ id,
2265
+ )
2266
+ }
2267
+ if (
2268
+ payload._tag !== 'WorkerInputCompleted' &&
2269
+ 'submissionId' in payload &&
2270
+ payload.submissionId !== undefined &&
2271
+ (yield* reader.admission(payload.submissionId)) === undefined
2272
+ ) {
2273
+ return yield* invalidThreadArchive('Canonical submission has no admission', id)
2274
+ }
2275
+ }
2276
+ if (stagedWork.entries.size > 0) {
2277
+ return yield* ThreadImportRejected.make({
2278
+ threadId: id,
2279
+ reason: 'unsupported-obligations',
2280
+ message: 'Transfer contains unresolved work',
2281
+ })
2282
+ }
2283
+
2284
+ const commitLedger = stagedLedger === undefined
2285
+ ? undefined
2286
+ : yield* stagedLedger.prepareCommit(progress.manifest?.workerSeal)
2287
+
2288
+ const commitDelivery = stagedDelivery === undefined ? undefined : yield* stagedDelivery.prepareCommit
2289
+
2290
+ const installed = restoredThread
2291
+
2292
+ yield* Effect.uninterruptible(
2293
+ Effect.sync(() => {
2294
+ commitLedger?.()
2295
+ commitDelivery?.()
2296
+ publishWork(id, stagedWork)
2297
+ MutableRef.get(state.ref).threads.set(id, installed)
2298
+ }).pipe(Effect.andThen(PubSub.publish(updates, undefined))),
2299
+ )
2300
+
2301
+ return result
2302
+ }).pipe(
2303
+ Effect.provide(ThreadImportReader.layer(reader)),
2304
+ Effect.provideService(ThreadDeliveryImportReader, {
2305
+ admission: (threadId, sid) =>
2306
+ threadId === id
2307
+ ? reader.admission(sid)
2308
+ : (ledgerTransfer?.admission(threadId, sid) ?? Effect.as(Effect.void, undefined)),
2309
+ record: (threadId, recordId) =>
2310
+ Effect.succeed(
2311
+ threadId === id
2312
+ ? restoredThread.byId.get(recordId)?.record
2313
+ : MutableRef.get(state.ref).threads.get(threadId)?.byId.get(recordId)?.record,
2314
+ ),
2315
+ }),
2316
+ )
2317
+ }).pipe(Effect.provideService(CryptoDigest.Digest, crypto)),
2318
+ ))
2319
+
2320
+ const inspectTail: ThreadStore['Service']['inspectTail'] = Effect.fnUntraced(
2321
+ function*(unvalidated) {
2322
+ const request = yield* validate(ThreadTailRequest, 'inspectTail', unvalidated)
2323
+
2324
+ const thread = yield* Ref.get(state).pipe(
2325
+ Effect.flatMap((current) => findThread(current, request.threadId)),
2326
+ )
2327
+
2328
+ return ThreadTail.make({
2329
+ threadId: request.threadId,
2330
+ tailSequence: thread.tailSequence,
2331
+ })
2332
+ },
2333
+ )
2334
+
2335
+ const readIdentity: ThreadStore['Service']['readIdentity'] = Effect.fnUntraced(
2336
+ function*(unvalidated) {
2337
+ const request = yield* validate(ThreadIdentityRequest, 'readIdentity', unvalidated)
2338
+
2339
+ const thread = yield* Ref.get(state).pipe(
2340
+ Effect.flatMap((current) => findThread(current, request.threadId)),
2341
+ )
2342
+
2343
+ const selected = [
2344
+ storedRecord(thread, 1),
2345
+ thread.byId.get(workerOriginRecordId(request.threadId)),
2346
+ thread.byId.get(subagentLineageRecordId(request.threadId)),
2347
+ ].filter((entry) => entry !== undefined)
2348
+
2349
+ return yield* ThreadIdentity.makeEffect({
2350
+ threadId: request.threadId,
2351
+ tailSequence: thread.tailSequence,
2352
+ hasAdmissions: ledgerTransfer !== undefined &&
2353
+ (yield* ledgerTransfer.snapshot(request.threadId)).admissions > 0,
2354
+ records: selected.filter(
2355
+ (entry, index) =>
2356
+ selected.findIndex((other) => other.record.recordId === entry.record.recordId) ===
2357
+ index,
2358
+ ),
2359
+ }).pipe(
2360
+ Effect.mapError((cause) => storeError('readIdentity', 'Invalid canonical identity', cause)),
2361
+ )
2362
+ },
2363
+ )
2364
+
2365
+ // Range contents remain volatile RAM. Publishing an archive locator adds no durability.
2366
+ const verifyRange = Effect.fnUntraced(function*(
2367
+ thread: StoredThread,
2368
+ range: ThreadArchiveRange,
2369
+ source?: Map<BatchId, string>,
2370
+ ) {
2371
+ let sequence = range.firstSequence
2372
+ let bytes = 0
2373
+ let batches = 0
2374
+ const captured = new Map<BatchId, string>()
2375
+
2376
+ while (sequence <= range.lastSequence) {
2377
+ const id = thread.batchesByFirst.get(sequence)
2378
+ const batch = id === undefined ? undefined : thread.batches.get(id)
2379
+
2380
+ const text = id === undefined ? undefined : source === undefined ? batch?.batchJson : source.get(id)
2381
+
2382
+ if (
2383
+ id === undefined ||
2384
+ batch === undefined ||
2385
+ text === undefined ||
2386
+ batch.result.lastSequence > range.lastSequence
2387
+ ) {
2388
+ return yield* storeError('verify range', 'Incomplete canonical batch range')
2389
+ }
2390
+ bytes += new TextEncoder().encode(text).byteLength
2391
+ batches++
2392
+ if (
2393
+ bytes > MAX_ARCHIVE_RANGE_BYTES ||
2394
+ batches > MAX_ARCHIVE_RANGE_RECORDS ||
2395
+ text !== batch.batchJson
2396
+ ) {
2397
+ return yield* storeError(
2398
+ 'verify range',
2399
+ 'Range wire or bounds differ from canonical storage',
2400
+ )
2401
+ }
2402
+
2403
+ const wire = yield* Schema.decodeEffect(Schema.fromJsonString(ExportBatch))(text).pipe(
2404
+ Effect.mapError((cause) => storeError('verify range', 'Invalid range wire', cause)),
2405
+ )
2406
+
2407
+ if (
2408
+ wire.batchId !== id ||
2409
+ batch.result.firstSequence !== sequence ||
2410
+ batch.result.lastSequence !== sequence + wire.records.length - 1
2411
+ ) {
2412
+ return yield* storeError('verify range', 'Canonical batch span or identity differs')
2413
+ }
2414
+
2415
+ for (const [index, record] of wire.records.entries()) {
2416
+ const expected = storedRecord(thread, sequence + index)
2417
+
2418
+ if (
2419
+ expected === undefined ||
2420
+ expected.threadId !== range.threadId ||
2421
+ expected.sequence !== sequence + index ||
2422
+ expected.batchId !== id ||
2423
+ expected.record.recordId !== record.recordId
2424
+ ) {
2425
+ return yield* storeError('verify range', 'Canonical record identity or order differs')
2426
+ }
2427
+
2428
+ const canonical = yield* Schema.encodeEffect(ReadRecord)(expected.record).pipe(
2429
+ Effect.mapError((cause) => storeError('verify range', 'Invalid canonical record', cause)),
2430
+ )
2431
+
2432
+ const archived = yield* Schema.encodeEffect(ExportRecord)(record).pipe(
2433
+ Effect.mapError((cause) => storeError('verify range', 'Invalid archive record', cause)),
2434
+ )
2435
+
2436
+ if (canonicalJson(canonical) !== canonicalJson(archived)) {
2437
+ return yield* storeError('verify range', 'Archive and canonical record bytes differ')
2438
+ }
2439
+ }
2440
+ captured.set(id, text)
2441
+ sequence = decodeCanonicalSequence(batch.result.lastSequence + 1)
2442
+ }
2443
+ if (
2444
+ bytes !== range.byteCount ||
2445
+ batches !== range.batchCount ||
2446
+ range.recordCount !== range.lastSequence - range.firstSequence + 1
2447
+ ) {
2448
+ return yield* storeError('verify range', 'Range spans or counts differ')
2449
+ }
2450
+
2451
+ return captured
2452
+ })
2453
+
2454
+ const archiveTarget = Effect.fnUntraced(function*(request: ThreadArchiveRangeSeal) {
2455
+ const thread = yield* findThread(MutableRef.get(state.ref), request.threadId)
2456
+
2457
+ return thread
2458
+ })
2459
+
2460
+ const archives: ThreadArchiveStorage = {
2461
+ page: Effect.fnUntraced(function*(unvalidated) {
2462
+ const request = yield* validate(ThreadArchiveRangeRead, 'range page', unvalidated)
2463
+ const thread = yield* findThread(MutableRef.get(state.ref), request.threadId)
2464
+ let low = 0
2465
+ let high = thread.rangeStarts.length
2466
+
2467
+ while (low < high) {
2468
+ const middle = Math.floor((low + high) / 2)
2469
+ const range = thread.ranges.get(thread.rangeStarts[middle])
2470
+
2471
+ if (range === undefined) {
2472
+ return yield* storeError('page ranges', 'Range locator has no exact range')
2473
+ }
2474
+ if (range.lastSequence <= (request.afterSequence ?? 0)) low = middle + 1
2475
+ else high = middle
2476
+ }
2477
+ const ranges: Array<ThreadArchiveRange> = []
2478
+ const limit = request.limit ?? 32
2479
+
2480
+ for (let at = low; at < Math.min(thread.rangeStarts.length, low + limit); at++) {
2481
+ const range = thread.ranges.get(thread.rangeStarts[at])
2482
+
2483
+ if (range === undefined) {
2484
+ return yield* storeError('page ranges', 'Range locator has no exact range')
2485
+ }
2486
+ ranges.push(range)
2487
+ }
2488
+
2489
+ const afterSequence = low + ranges.length < thread.rangeStarts.length ? ranges.at(-1)?.lastSequence : undefined
2490
+
2491
+ return { ranges, ...(afterSequence === undefined ? {} : { afterSequence }) }
2492
+ }),
2493
+ seal: (unvalidated) =>
2494
+ withMutation(
2495
+ Effect.gen(function*() {
2496
+ const request = yield* validate(ThreadArchiveRangeSeal, 'seal range', unvalidated)
2497
+ const thread = yield* archiveTarget(request)
2498
+ const previousStart = thread.rangeStarts.at(-1)
2499
+
2500
+ const previous = previousStart === undefined ? undefined : thread.ranges.get(previousStart)
2501
+
2502
+ if (previousStart !== undefined && previous === undefined) {
2503
+ return yield* storeError('seal range', 'Range locator has no exact range')
2504
+ }
2505
+ const firstSequence = (previous?.lastSequence ?? 0) + 1
2506
+
2507
+ if (firstSequence > thread.tailSequence) return Option.none<ThreadArchiveRange>()
2508
+ let nextSequence = firstSequence
2509
+ let byteCount = 0
2510
+ let batchCount = 0
2511
+
2512
+ while (nextSequence <= thread.tailSequence) {
2513
+ const batchId = thread.batchesByFirst.get(nextSequence)
2514
+ const batch = batchId === undefined ? undefined : thread.batches.get(batchId)
2515
+
2516
+ if (batch === undefined) {
2517
+ return yield* storeError('seal range', 'Missing exact canonical batch')
2518
+ }
2519
+ const bytes = utf8ByteLength(batch.batchJson)
2520
+
2521
+ if (
2522
+ batchCount > 0 &&
2523
+ (batch.result.lastSequence - firstSequence + 1 > MAX_ARCHIVE_RANGE_RECORDS ||
2524
+ byteCount + bytes > MAX_ARCHIVE_RANGE_BYTES)
2525
+ ) {
2526
+ break
2527
+ }
2528
+ byteCount += bytes
2529
+ batchCount++
2530
+ nextSequence = batch.result.lastSequence + 1
2531
+ }
2532
+
2533
+ const range = ThreadArchiveRange.make({
2534
+ format: 'effect-agent/thread-range@2',
2535
+ threadId: request.threadId,
2536
+ firstSequence: decodeCanonicalSequence(firstSequence),
2537
+ lastSequence: decodeCanonicalSequence(nextSequence - 1),
2538
+ recordCount: nextSequence - firstSequence,
2539
+ batchCount,
2540
+ byteCount,
2541
+ state: 'sealed',
2542
+ })
2543
+
2544
+ yield* verifyRange(thread, range)
2545
+ thread.ranges.set(firstSequence, range)
2546
+ thread.rangeStarts.push(firstSequence)
2547
+
2548
+ return Option.some(range)
2549
+ }),
2550
+ ),
2551
+ verify: Effect.fnUntraced(function*(unvalidated) {
2552
+ const request = yield* validate(ThreadArchiveRangeRequest, 'verify range', unvalidated)
2553
+ const thread = yield* findThread(MutableRef.get(state.ref), request.threadId)
2554
+ const range = thread.ranges.get(request.firstSequence)
2555
+
2556
+ if (range === undefined) return yield* storeError('verify range', 'Unknown sealed range')
2557
+ yield* verifyRange(
2558
+ thread,
2559
+ range,
2560
+ range.state === 'archived' ? thread.archiveContents.get(range.firstSequence) : undefined,
2561
+ )
2562
+ if (range.state === 'archived' && !thread.archiveContents.has(range.firstSequence)) {
2563
+ return yield* storeError('verify range', 'Published archive contents are missing')
2564
+ }
2565
+
2566
+ return range
2567
+ }),
2568
+ archive: (unvalidated) =>
2569
+ withMutation(
2570
+ Effect.gen(function*() {
2571
+ const request = yield* validate(ThreadArchiveRangePublish, 'archive range', unvalidated)
2572
+ const thread = yield* archiveTarget(request)
2573
+ const range = thread.ranges.get(request.firstSequence)
2574
+
2575
+ if (range === undefined) {
2576
+ return yield* storeError('archive range', 'Unknown sealed range')
2577
+ }
2578
+ if (range.state === 'archived') {
2579
+ const contents = thread.archiveContents.get(range.firstSequence)
2580
+
2581
+ if (contents === undefined) {
2582
+ return yield* storeError('archive range', 'Published archive contents are missing')
2583
+ }
2584
+ yield* verifyRange(thread, range, contents)
2585
+
2586
+ return range
2587
+ }
2588
+ const contents = yield* verifyRange(thread, range)
2589
+
2590
+ yield* verifyRange(thread, range, contents)
2591
+
2592
+ const published = ThreadArchiveRange.make({
2593
+ ...range,
2594
+ state: 'archived',
2595
+ locator: `memory:${encodeURIComponent(request.threadId)}:${range.firstSequence}`,
2596
+ })
2597
+
2598
+ thread.archiveContents.set(range.firstSequence, contents)
2599
+ thread.ranges.set(range.firstSequence, published)
2600
+
2601
+ return published
2602
+ }),
2603
+ ),
2604
+ }
2605
+
2606
+ const readWorkerCapacity: NonNullable<ThreadStore['Service']['readWorkerCapacity']> = Effect.fnUntraced(
2607
+ function*(unvalidated) {
2608
+ const request = yield* validate(ThreadWorkerCapacityRequest, 'worker capacity', unvalidated)
2609
+ const thread = yield* findThread(MutableRef.get(state.ref), request.threadId)
2610
+
2611
+ if (request.expectedTailSequence !== thread.tailSequence) {
2612
+ return yield* storeError('worker capacity', 'Canonical tail changed')
2613
+ }
2614
+
2615
+ const index = yield* readyIndex(request.threadId, thread.tailSequence).pipe(
2616
+ Effect.mapError((e) => storeError('worker capacity', e.message)),
2617
+ )
2618
+
2619
+ const worker = index.workers.get(request.workerThreadId)
2620
+
2621
+ return ThreadWorkerCapacity.make({
2622
+ threadId: request.threadId,
2623
+ tailSequence: thread.tailSequence,
2624
+ activeWorkers: Math.min(index.workers.size, request.activeLimit + 1),
2625
+ workerActive: worker !== undefined,
2626
+ pendingInputs: Math.min(
2627
+ request.update ? (worker?.update ?? 0) : (worker?.ordinary ?? 0),
2628
+ request.pendingLimit + 1,
2629
+ ),
2630
+ })
2631
+ },
2632
+ )
2633
+
2634
+ const verification = {
2635
+ verify: (unvalidated: ThreadVerificationRequest) =>
2636
+ withMutation(
2637
+ Effect.gen(function*() {
2638
+ const request = yield* validate(ThreadVerificationRequest, 'verify Thread', unvalidated)
2639
+ const thread = yield* findThread(MutableRef.get(state.ref), request.threadId)
2640
+ const id = request.threadId
2641
+
2642
+ const reader = importReader(id, thread)
2643
+
2644
+ const submissions = () => ledgerTransfer?.submissions(id) ?? Stream.empty
2645
+
2646
+ const runs = Stream.fromIterable(thread.runRecords.keys()).pipe(
2647
+ Stream.map((runId) => Schema.decodeSync(RunId)(runId)),
2648
+ )
2649
+
2650
+ return yield* verifyThreadInvariants({
2651
+ threadId: id,
2652
+ runs,
2653
+ executions: Stream.fromIterable(thread.executions.values()),
2654
+ submissions: submissions(),
2655
+ pages: streamExport({ threadId: id }).pipe(
2656
+ Stream.provideService(ThreadExportSource, { export: verificationPage }),
2657
+ Stream.mapError((cause) =>
2658
+ Schema.is(ThreadExportRejected)(cause)
2659
+ ? storeError('verify Thread', 'Internal verification snapshot changed')
2660
+ : cause
2661
+ ),
2662
+ ),
2663
+ ...(request.requireAllSettled === undefined
2664
+ ? {}
2665
+ : { requireAllSettled: request.requireAllSettled }),
2666
+ }).pipe(
2667
+ Effect.provide(ThreadImportReader.layer(reader)),
2668
+ Effect.provideService(CryptoDigest.Digest, crypto),
2669
+ )
2670
+ }),
2671
+ ),
2672
+ }
2673
+
2674
+ const threadStore = ThreadStore.of({
2675
+ work,
2676
+ archives,
2677
+ verification,
2678
+ readWorkerCapacity,
2679
+ readIdentity,
2680
+ countPeerMessages,
2681
+ materialize: (request) => withMutation(materialize(request)),
2682
+ append,
2683
+ readExecution: (request) =>
2684
+ withMutation(
2685
+ Effect.gen(function*() {
2686
+ const thread = (yield* Ref.get(state)).threads.get(request.threadId)
2687
+
2688
+ if (thread === undefined) {
2689
+ return yield* ThreadNotMaterialized.make({ threadId: request.threadId })
2690
+ }
2691
+
2692
+ return Option.fromUndefinedOr(thread.executions.get(request.runId))
2693
+ }),
2694
+ ),
2695
+ read,
2696
+ readPrompt,
2697
+ observe,
2698
+ export: (request) => checkExportSource(request.threadId).pipe(Effect.andThen(withMutation(exportThread(request)))),
2699
+ inspectTail,
2700
+ })
2701
+
2702
+ return Context.make(ThreadStore, threadStore).pipe(
2703
+ Context.add(StorageOwner, owner),
2704
+ Context.add(ThreadImport, { import: importThread }),
2705
+ Context.add(MemoryThreadStoreKernel, {
2706
+ owner,
2707
+ withMutation,
2708
+ checkThreadCapacity: (threadId) =>
2709
+ Effect.suspend(() =>
2710
+ !MutableRef.get(workState.ref).has(threadId) &&
2711
+ MutableRef.get(workState.ref).size >= maxThreads
2712
+ ? Effect.fail(storeError('Thread capacity', 'Retained Thread quota exceeded'))
2713
+ : Effect.void
2714
+ ),
2715
+ initializeWork: (threadId) => {
2716
+ if (
2717
+ !MutableRef.get(state.ref).threads.has(threadId) &&
2718
+ !MutableRef.get(workState.ref).has(threadId)
2719
+ ) {
2720
+ publishWork(threadId, emptyWorkIndex())
2721
+ }
2722
+ },
2723
+ registerWorkOwner: (kind, owner) =>
2724
+ withMutation(
2725
+ Effect.gen(function*() {
2726
+ if (workOwners.has(kind)) {
2727
+ return yield* Effect.die(
2728
+ storeError('initialize', `MemoryThreadStore already has a ${kind} work owner`),
2729
+ )
2730
+ }
2731
+ workOwners.set(kind, owner)
2732
+ }),
2733
+ ),
2734
+ registerDeliveryWriter: (writer) =>
2735
+ withMutation(
2736
+ Effect.gen(function*() {
2737
+ if (deliveryWriter !== undefined) {
2738
+ return yield* Effect.die(
2739
+ storeError('initialize', 'MemoryThreadStore already has a delivery writer'),
2740
+ )
2741
+ }
2742
+ deliveryWriter = writer
2743
+ }),
2744
+ ),
2745
+ registerLedgerTransfer: (transfer) =>
2746
+ withMutation(
2747
+ Effect.gen(function*() {
2748
+ if (ledgerTransfer !== undefined) {
2749
+ return yield* Effect.die(
2750
+ storeError('initialize', 'MemoryThreadStore already has a paired SubmissionLedger'),
2751
+ )
2752
+ }
2753
+ ledgerTransfer = transfer
2754
+ }),
2755
+ ),
2756
+ registerDeliveryTransfer: (transfer) =>
2757
+ withMutation(
2758
+ Effect.gen(function*() {
2759
+ if (deliveryTransfer !== undefined) {
2760
+ return yield* Effect.die(
2761
+ storeError('initialize', 'MemoryThreadStore already has a paired delivery store'),
2762
+ )
2763
+ }
2764
+ deliveryTransfer = transfer
2765
+ }),
2766
+ ),
2767
+ prepareAppend,
2768
+ appendPrepared,
2769
+ record: (threadId, recordId) =>
2770
+ Ref.get(state).pipe(
2771
+ Effect.map((current) => current.threads.get(threadId)?.byId.get(recordId)?.record),
2772
+ ),
2773
+ toolCallResults: (threadId, runId, toolCallId) =>
2774
+ Ref.get(state).pipe(
2775
+ Effect.map((current) =>
2776
+ (
2777
+ current.threads
2778
+ .get(threadId)
2779
+ ?.operationRecords.get(JSON.stringify([runId, toolCallId, 'settled'])) ?? []
2780
+ )
2781
+ .slice(0, 2)
2782
+ .map((entry) => entry.record)
2783
+ ),
2784
+ ),
2785
+ tail: (threadId) => inspectTail(ThreadTailRequest.make({ threadId })),
2786
+ }),
2787
+ )
2788
+ })
2789
+
2790
+ /**
2791
+ * In-memory canonical Thread persistence. Durable accepted work is served by the separate
2792
+ * SubmissionLedger port; this Layer provides ThreadStore, ThreadReader, and ThreadImport.
2793
+ * Importing admissions requires a MemorySubmissionLedger paired with this store.
2794
+ * Publishing canonical messages requires a paired MemoryMessageDeliveryStore.
2795
+ */
2796
+ export const MemoryThreadStoreLive = ThreadReader.layer().pipe(
2797
+ Layer.provideMerge(Layer.effectContext(makeThreadStore)),
2798
+ )
2799
+
2800
+ /** Configure a finite retained Thread capacity. Invalid construction options throw immediately. */
2801
+ export const memoryThreadStoreLayer = (options: { readonly maxThreads?: number } = {}) =>
2802
+ MemoryThreadStoreLive.pipe(
2803
+ Layer.provide(
2804
+ Layer.succeed(ThreadCapacity)(
2805
+ Schema.decodeSync(
2806
+ Schema.Int.check(Schema.isGreaterThan(0), Schema.isLessThanOrEqualTo(65_536)),
2807
+ )(options.maxThreads ?? MAX_THREADS),
2808
+ ),
2809
+ ),
2810
+ )