@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,1004 @@
1
+ import { ThreadId } from '@systemfsoftware/agent/identifiers'
2
+ import {
3
+ applyMessageDeliveryChange,
4
+ defaultMessageDeliveryStoreLimits,
5
+ isWorkerUpdateDelivery,
6
+ messageDeliveryCapacity,
7
+ MessageDeliveryChange,
8
+ messageDeliveryDeadline,
9
+ MessageDeliveryError,
10
+ MessageDeliveryFailpoint,
11
+ MessageDeliveryKey,
12
+ messageDeliveryKeyString,
13
+ MessageDeliveryPageRequest,
14
+ MessageDeliveryRecord,
15
+ MessageDeliveryStore,
16
+ MessageDeliveryStoreLimits,
17
+ messageDeliveryUsesCapacity,
18
+ peerMessageRetentionDeadline,
19
+ sameMessageDeliveryIdentity,
20
+ validateMessageDelivery,
21
+ } from '@systemfsoftware/agent/message-delivery'
22
+ import { PreparedInput } from '@systemfsoftware/agent/prepared-input-admission'
23
+ import { ScheduleInstant } from '@systemfsoftware/agent/schedule'
24
+ import { validateCanonicalSettlement } from '@systemfsoftware/agent/settlement-publisher'
25
+ import {
26
+ Settlement,
27
+ settlementFailureFromRecord,
28
+ submissionSettlementId,
29
+ submissionSettlementRecordId,
30
+ } from '@systemfsoftware/agent/submission-ledger'
31
+ import {
32
+ invalidThreadArchive,
33
+ ThreadDeliveryImportReader,
34
+ ThreadImportRejected,
35
+ } from '@systemfsoftware/agent/thread-import'
36
+ import { makeTransferFactCheck, ThreadStoreError } from '@systemfsoftware/agent/thread-store'
37
+ import { type ThreadWorkEntry, workId } from '@systemfsoftware/agent/thread-work'
38
+ import * as Effect from 'effect/Effect'
39
+ import * as Layer from 'effect/Layer'
40
+ import * as MutableRef from 'effect/MutableRef'
41
+ import * as Ref from 'effect/Ref'
42
+ import * as Schema from 'effect/Schema'
43
+
44
+ import { MemoryThreadStoreKernel } from './internal/MemoryThreadStoreKernel'
45
+ import { boundedWorkSelection } from './internal/WorkSelection'
46
+
47
+ const codec = Schema.fromJsonString(MessageDeliveryRecord)
48
+ const deliveryFitsTransfer = makeTransferFactCheck(MessageDeliveryRecord)
49
+
50
+ const checkTransfer = (record: MessageDeliveryRecord) =>
51
+ deliveryFitsTransfer(record.key.ownerThreadId, { ...record, leaseUntilMillis: null })
52
+ ? Effect.void
53
+ : Effect.fail(
54
+ MessageDeliveryError.make({ reason: 'capacity', operation: 'transfer-page-bytes' }),
55
+ )
56
+
57
+ const decode = (text: string) =>
58
+ Schema.decodeEffect(codec)(text).pipe(
59
+ Effect.mapError(() => MessageDeliveryError.make({ reason: 'corrupt', operation: 'decode' })),
60
+ )
61
+
62
+ const Scan = Schema.Struct({
63
+ nowMillis: ScheduleInstant,
64
+ limit: Schema.Int.check(Schema.isGreaterThan(0), Schema.isLessThanOrEqualTo(100)),
65
+ ownerThreadId: Schema.optionalKey(ThreadId),
66
+ })
67
+
68
+ const position = (keys: ReadonlyArray<string>, key: string) => {
69
+ let low = 0
70
+ let high = keys.length
71
+
72
+ while (low < high) {
73
+ const mid = Math.floor((low + high) / 2)
74
+
75
+ if (keys[mid] < key) low = mid + 1
76
+ else high = mid
77
+ }
78
+
79
+ return low
80
+ }
81
+
82
+ const retainKey = (keys: Array<string>, key: string) => {
83
+ const at = position(keys, key)
84
+
85
+ if (keys[at] !== key) keys.splice(at, 0, key)
86
+ }
87
+
88
+ const removeKey = (keys: Array<string>, key: string) => {
89
+ const at = position(keys, key)
90
+
91
+ if (keys[at] === key) keys.splice(at, 1)
92
+ }
93
+
94
+ /** First deadline after the request time; retained evidence also supports clock rollback. */
95
+ const deadlinePosition = (deadlines: ReadonlyArray<number>, nowMillis: number) => {
96
+ let low = 0
97
+ let high = deadlines.length
98
+
99
+ while (low < high) {
100
+ const mid = Math.floor((low + high) / 2)
101
+
102
+ if (deadlines[mid] <= nowMillis) low = mid + 1
103
+ else high = mid
104
+ }
105
+
106
+ return low
107
+ }
108
+
109
+ const backend = () => ({
110
+ records: new Map<string, string>(),
111
+ work: new Map<string, ThreadWorkEntry>(),
112
+ ordered: new Map<string, Array<string>>(),
113
+ pending: new Map<ThreadId, Set<MessageDeliveryKey['messageId']>>(),
114
+ retainedPeers: new Map<ThreadId, Array<number>>(),
115
+ counts: new Map<ThreadId, { retained: number; ordinary: number; update: number; peer: number }>(),
116
+ metadata: new Map<
117
+ string,
118
+ {
119
+ update: boolean
120
+ pending: boolean
121
+ peer: boolean
122
+ peerRetentionDeadline: number | null
123
+ deadlineKey?: string
124
+ importVisit?: 'visiting' | 'verified'
125
+ }
126
+ >(),
127
+ deadlines: new Map<string, { readonly key: MessageDeliveryKey; readonly deadline: number }>(),
128
+ deadlineKeys: new Array<string>(),
129
+ ownerDeadlineKeys: new Map<ThreadId, Array<string>>(),
130
+ })
131
+
132
+ const ownerKey = (id: ThreadId) => JSON.stringify([id])
133
+
134
+ interface PreparedDeliveryInsert {
135
+ readonly record: MessageDeliveryRecord
136
+ readonly encoded: string
137
+ }
138
+
139
+ const keysFor = (current: ReturnType<typeof backend>, key: string) => {
140
+ let keys = current.ordered.get(key)
141
+
142
+ if (keys === undefined) current.ordered.set(key, keys = [])
143
+
144
+ return keys
145
+ }
146
+
147
+ export interface MemoryMessageDeliveryStoreOptions {
148
+ /** UTF-8 bound on the complete stored record, including a processed Settlement. */
149
+ readonly maxStoredValueBytes?: number
150
+ }
151
+
152
+ /**
153
+ * Pair with MemoryThreadStoreLive to publish canonical messages and their deliveries atomically.
154
+ * Export/import preserves every retained delivery obligation.
155
+ * Each retained value and live partition is bounded; completed deduplication evidence is never evicted.
156
+ */
157
+ export const memoryMessageDeliveryStoreLayer = (
158
+ limits: MessageDeliveryStoreLimits = defaultMessageDeliveryStoreLimits,
159
+ options: MemoryMessageDeliveryStoreOptions = {},
160
+ ): Layer.Layer<MessageDeliveryStore, MessageDeliveryError, MemoryThreadStoreKernel> =>
161
+ Layer.effect(
162
+ MessageDeliveryStore,
163
+ Effect.gen(function*() {
164
+ const journal = yield* MemoryThreadStoreKernel
165
+ const config = yield* validateMessageDelivery(MessageDeliveryStoreLimits, limits, 'limits')
166
+
167
+ const maxStoredValueBytes = yield* validateMessageDelivery(
168
+ Schema.Int.check(Schema.isGreaterThan(0)),
169
+ options.maxStoredValueBytes ?? 16 * 1_024 * 1_024,
170
+ 'stored-value-limit',
171
+ )
172
+
173
+ const state = yield* Ref.make(backend())
174
+
175
+ yield* journal.registerWorkOwner('deliveries', {
176
+ threads: (request) =>
177
+ Ref.get(state).pipe(
178
+ Effect.map((current) => {
179
+ const candidates = boundedWorkSelection<ThreadId>(
180
+ request.limit,
181
+ (id) => id,
182
+ request.afterThreadId,
183
+ )
184
+
185
+ for (const threadId of current.pending.keys()) candidates.add(threadId)
186
+ const threadIds = candidates.values
187
+
188
+ const afterThreadId = threadIds.length === request.limit ? threadIds.at(-1) : undefined
189
+
190
+ return {
191
+ threadIds,
192
+ ...(afterThreadId === undefined ? {} : { afterThreadId }),
193
+ }
194
+ }),
195
+ ),
196
+ page: Effect.fnUntraced(function*(threadId, after, limit) {
197
+ const current = yield* Ref.get(state)
198
+
199
+ const candidates = boundedWorkSelection<MessageDeliveryKey['messageId']>(
200
+ limit + 1,
201
+ (id) => id,
202
+ after,
203
+ )
204
+
205
+ for (const id of current.pending.get(threadId) ?? []) candidates.add(id)
206
+ const ids = candidates.values
207
+
208
+ const entries: Array<ThreadWorkEntry> = []
209
+
210
+ for (const messageId of ids.slice(0, limit)) {
211
+ const key = messageDeliveryKeyString({ ownerThreadId: threadId, messageId })
212
+ const entry = current.work.get(key)
213
+
214
+ if (entry === undefined || !current.records.has(key)) {
215
+ return yield* ThreadStoreError.make({
216
+ operation: 'delivery work',
217
+ message: 'Pending delivery index is incomplete or corrupt',
218
+ })
219
+ }
220
+ entries.push(entry)
221
+ }
222
+ const next = ids.length > limit ? ids[limit - 1] : undefined
223
+
224
+ return { entries, ...(next === undefined ? {} : { after: next }) }
225
+ }),
226
+ })
227
+
228
+ const commitInto = (
229
+ current: ReturnType<typeof backend>,
230
+ record: MessageDeliveryRecord,
231
+ encoded: string,
232
+ publish: boolean,
233
+ ) => {
234
+ const key = messageDeliveryKeyString(record.key)
235
+ const owner = record.key.ownerThreadId
236
+ const old = current.metadata.get(key)
237
+ const update = isWorkerUpdateDelivery(record)
238
+ const pending = messageDeliveryUsesCapacity(record)
239
+
240
+ const peer = record.envelope.messageAdmission !== undefined &&
241
+ 'peerName' in record.envelope.messageAdmission
242
+
243
+ let counts = current.counts.get(owner)
244
+
245
+ if (counts === undefined) {
246
+ current.counts.set(owner, counts = { retained: 0, ordinary: 0, update: 0, peer: 0 })
247
+ }
248
+ if (old === undefined) counts.retained++
249
+ if (old?.pending) {
250
+ if (old.update) counts.update--
251
+ else counts.ordinary--
252
+ if (old.peer) counts.peer--
253
+ }
254
+ if (pending) {
255
+ if (update) counts.update++
256
+ else counts.ordinary++
257
+ if (peer) counts.peer++
258
+ }
259
+ const retentionDeadline = peerMessageRetentionDeadline(record)
260
+ const previousDeadline = old?.peerRetentionDeadline ?? null
261
+
262
+ if (previousDeadline !== retentionDeadline) {
263
+ let retained = current.retainedPeers.get(owner)
264
+
265
+ if (retained === undefined) current.retainedPeers.set(owner, retained = [])
266
+ if (previousDeadline !== null) {
267
+ retained.splice(deadlinePosition(retained, previousDeadline) - 1, 1)
268
+ }
269
+ if (retentionDeadline !== null) {
270
+ retained.splice(deadlinePosition(retained, retentionDeadline), 0, retentionDeadline)
271
+ }
272
+ if (retained.length === 0) current.retainedPeers.delete(owner)
273
+ }
274
+ let owned = current.pending.get(owner)
275
+
276
+ if (owned === undefined) current.pending.set(owner, owned = new Set())
277
+ if (pending) owned.add(record.key.messageId)
278
+ else owned.delete(record.key.messageId)
279
+ if (owned.size === 0) current.pending.delete(owner)
280
+ retainKey(keysFor(current, ownerKey(owner)), record.key.messageId)
281
+ const admission = record.envelope.workerAdmission
282
+
283
+ if (admission !== undefined) {
284
+ const worker = admission.origin.worker
285
+
286
+ if (record.key.messageId === admission.origin.firstMessageId) {
287
+ retainKey(
288
+ keysFor(current, JSON.stringify([owner, worker.delegationId, worker.targetAgentId])),
289
+ record.key.messageId,
290
+ )
291
+ }
292
+ const inputs = keysFor(current, JSON.stringify([owner, worker.threadId]))
293
+
294
+ if (
295
+ (record.status === 'pending' || record.status === 'parked') &&
296
+ record.receipt === null
297
+ ) {
298
+ retainKey(inputs, record.key.messageId)
299
+ } else removeKey(inputs, record.key.messageId)
300
+ }
301
+ const deadline = messageDeliveryDeadline(record)
302
+ let ownerDeadlines = current.ownerDeadlineKeys.get(owner)
303
+
304
+ if (ownerDeadlines === undefined) {
305
+ current.ownerDeadlineKeys.set(owner, ownerDeadlines = [])
306
+ }
307
+ if (old?.deadlineKey !== undefined) {
308
+ current.deadlines.delete(old.deadlineKey)
309
+ removeKey(current.deadlineKeys, old.deadlineKey)
310
+ removeKey(ownerDeadlines, old.deadlineKey)
311
+ }
312
+
313
+ const deadlineKey = deadline === null ? undefined : `${String(deadline).padStart(16, '0')}:${key}`
314
+
315
+ if (deadlineKey !== undefined && deadline !== null) {
316
+ current.deadlines.set(deadlineKey, { key: record.key, deadline })
317
+ retainKey(current.deadlineKeys, deadlineKey)
318
+ retainKey(ownerDeadlines, deadlineKey)
319
+ }
320
+ current.metadata.set(key, {
321
+ update,
322
+ pending,
323
+ peer,
324
+ peerRetentionDeadline: retentionDeadline,
325
+ ...(deadlineKey === undefined ? {} : { deadlineKey }),
326
+ })
327
+ if (pending) {
328
+ current.work.set(key, {
329
+ id: workId('delivery', record.key.messageId),
330
+ owner: { _tag: 'Delivery', messageId: record.key.messageId },
331
+ partition: update ? 'update' : 'ordinary',
332
+ stateReference: {
333
+ _tag: 'Delivery',
334
+ messageId: record.key.messageId,
335
+ version: record.version,
336
+ },
337
+ state: record.status === 'pending' ? 'ready' : 'waiting',
338
+ ...(record.status === 'parked'
339
+ ? { wait: 'parked' as const }
340
+ : record.receipt !== null
341
+ ? { wait: 'destination' as const }
342
+ : {}),
343
+ ...(deadline === null ? {} : { notBeforeMillis: deadline }),
344
+ ...(record.receipt === null
345
+ ? {}
346
+ : {
347
+ receiptId: record.receipt.receiptId,
348
+ queueSequence: record.receipt.queueSequence,
349
+ }),
350
+ })
351
+ } else current.work.delete(key)
352
+ current.records.set(key, encoded)
353
+ if (publish) journal.initializeWork(owner)
354
+ }
355
+
356
+ const commit = (record: MessageDeliveryRecord, encoded: string) =>
357
+ Effect.sync(() => commitInto(MutableRef.get(state.ref), record, encoded, true))
358
+
359
+ const failpoint = yield* MessageDeliveryFailpoint
360
+
361
+ const encode = Effect.fnUntraced(function*(record: MessageDeliveryRecord) {
362
+ const text = yield* Schema.encodeEffect(codec)(record).pipe(
363
+ Effect.mapError(() => MessageDeliveryError.make({ reason: 'corrupt', operation: 'encode' })),
364
+ )
365
+
366
+ if (new TextEncoder().encode(text).byteLength > maxStoredValueBytes) {
367
+ return yield* MessageDeliveryError.make({
368
+ reason: 'capacity',
369
+ operation: 'stored-value-bytes',
370
+ })
371
+ }
372
+
373
+ return text
374
+ })
375
+
376
+ const prepareInsert = Effect.fnUntraced(function*(record: MessageDeliveryRecord) {
377
+ const encoded = yield* encode(record)
378
+ const input = yield* decode(encoded)
379
+
380
+ if (
381
+ input.version !== 1 ||
382
+ input.status !== 'pending' ||
383
+ input.leaseUntilMillis !== null ||
384
+ input.retry.attempts !== 0 ||
385
+ input.retry.generation !== 0 ||
386
+ input.retry.automaticAttempts !== 0 ||
387
+ input.retry.nextAttemptAtMillis !== input.createdAtMillis ||
388
+ input.retry.lastAttemptAtMillis !== null ||
389
+ input.retry.lastFailure !== null ||
390
+ input.deadlineAtMillis !== input.initialDeadlineAtMillis
391
+ ) {
392
+ return yield* MessageDeliveryError.make({
393
+ reason: 'validation',
394
+ operation: 'insert-state',
395
+ })
396
+ }
397
+ if (
398
+ new TextEncoder().encode(JSON.stringify(input.envelope)).byteLength >
399
+ config.maxEnvelopeBytes
400
+ ) {
401
+ return yield* MessageDeliveryError.make({
402
+ reason: 'capacity',
403
+ operation: 'envelope-bytes',
404
+ })
405
+ }
406
+
407
+ return { record: input, encoded }
408
+ })
409
+
410
+ /** The caller holds the journal gate through staging and synchronous publication. */
411
+ const stageInsert = Effect.fnUntraced(function*(
412
+ inputs: ReadonlyArray<PreparedDeliveryInsert>,
413
+ ) {
414
+ const current = yield* Ref.get(state)
415
+ const additions = new Map<string, PreparedDeliveryInsert>()
416
+ const counts = new Map<ThreadId, { ordinary: number; update: number }>()
417
+ const retained: Array<MessageDeliveryRecord> = []
418
+
419
+ for (const prepared of inputs) {
420
+ const input = prepared.record
421
+ const owner = input.key.ownerThreadId
422
+
423
+ yield* journal
424
+ .checkThreadCapacity(owner)
425
+ .pipe(
426
+ Effect.mapError(() => MessageDeliveryError.make({ reason: 'capacity', operation: 'Thread capacity' })),
427
+ )
428
+ const key = messageDeliveryKeyString(input.key)
429
+ const existingText = current.records.get(key)
430
+
431
+ const existing = additions.get(key)?.record ??
432
+ (existingText === undefined ? undefined : yield* decode(existingText))
433
+
434
+ if (existing !== undefined) {
435
+ if (!sameMessageDeliveryIdentity(existing, input)) {
436
+ return yield* MessageDeliveryError.make({
437
+ reason: 'conflict',
438
+ operation: 'insert',
439
+ })
440
+ }
441
+ retained.push(existing)
442
+ continue
443
+ }
444
+
445
+ yield* checkTransfer(input)
446
+ const update = isWorkerUpdateDelivery(input)
447
+ const partition = update ? 'update' : 'ordinary'
448
+ const capacity = messageDeliveryCapacity(config, update)
449
+ let count = counts.get(owner)
450
+
451
+ if (count === undefined) {
452
+ const previous = current.counts.get(owner)
453
+
454
+ count = { ordinary: previous?.ordinary ?? 0, update: previous?.update ?? 0 }
455
+ counts.set(owner, count)
456
+ }
457
+ if (count[partition] >= capacity.pending) {
458
+ return yield* MessageDeliveryError.make({ reason: 'capacity', operation: 'insert' })
459
+ }
460
+ count[partition]++
461
+ additions.set(key, prepared)
462
+ retained.push(input)
463
+ }
464
+
465
+ return {
466
+ records: retained,
467
+ commit: () => {
468
+ for (const { record, encoded } of additions.values()) {
469
+ commitInto(current, record, encoded, true)
470
+ }
471
+ },
472
+ }
473
+ })
474
+
475
+ yield* journal.registerDeliveryWriter((records) =>
476
+ Effect.forEach(records, prepareInsert).pipe(
477
+ Effect.flatMap(stageInsert),
478
+ Effect.map((staged) => staged.commit),
479
+ )
480
+ )
481
+
482
+ const insert: MessageDeliveryStore['Service']['insert'] = Effect.fnUntraced(
483
+ function*(record) {
484
+ const prepared = yield* prepareInsert(record)
485
+
486
+ yield* failpoint.hit('message-delivery:insert:before')
487
+
488
+ const inserted = yield* journal.withMutation(
489
+ Effect.uninterruptible(
490
+ Effect.gen(function*() {
491
+ const staged = yield* stageInsert([prepared])
492
+
493
+ yield* Effect.sync(staged.commit)
494
+
495
+ return staged.records[0]
496
+ }),
497
+ ),
498
+ )
499
+
500
+ yield* failpoint.hit('message-delivery:insert:after')
501
+
502
+ return yield* decode(yield* encode(inserted))
503
+ },
504
+ )
505
+
506
+ const get: MessageDeliveryStore['Service']['get'] = Effect.fnUntraced(function*(key) {
507
+ const input = yield* validateMessageDelivery(MessageDeliveryKey, key, 'get')
508
+ const text = (yield* Ref.get(state)).records.get(messageDeliveryKeyString(input))
509
+
510
+ return text === undefined ? null : yield* decode(text)
511
+ })
512
+
513
+ const change: MessageDeliveryStore['Service']['change'] = Effect.fnUntraced(
514
+ function*(key, change) {
515
+ const input = yield* validateMessageDelivery(MessageDeliveryChange, change, 'change')
516
+ const decodedKey = yield* validateMessageDelivery(MessageDeliveryKey, key, 'change')
517
+ const point = `message-delivery:${input._tag.toLowerCase()}`
518
+
519
+ yield* failpoint.hit(`${point}:before`)
520
+
521
+ const changed = yield* journal.withMutation(
522
+ Effect.uninterruptible(
523
+ Effect.gen(function*() {
524
+ const existing = yield* get(decodedKey)
525
+
526
+ if (existing === null) {
527
+ return yield* MessageDeliveryError.make({
528
+ reason: 'not-found',
529
+ operation: 'change',
530
+ })
531
+ }
532
+ const next = yield* Effect.fromResult(applyMessageDeliveryChange(existing, input))
533
+
534
+ if (next === existing) return existing
535
+ yield* checkTransfer(next)
536
+ const encoded = yield* encode(next)
537
+
538
+ yield* commit(next, encoded)
539
+
540
+ return next
541
+ }),
542
+ ),
543
+ )
544
+
545
+ yield* failpoint.hit(`${point}:after`)
546
+
547
+ return yield* decode(yield* encode(changed))
548
+ },
549
+ )
550
+
551
+ const transferDecode = (text: string) =>
552
+ decode(text).pipe(
553
+ Effect.mapError(() =>
554
+ ThreadStoreError.make({
555
+ operation: 'delivery transfer',
556
+ message: 'Invalid retained delivery wire',
557
+ })
558
+ ),
559
+ )
560
+
561
+ yield* journal.registerDeliveryTransfer({
562
+ record: (threadId, messageId) => {
563
+ const text = MutableRef.get(state.ref).records.get(
564
+ messageDeliveryKeyString({ ownerThreadId: threadId, messageId }),
565
+ )
566
+
567
+ return text === undefined ? Effect.as(Effect.void, undefined) : transferDecode(text)
568
+ },
569
+ snapshot: (threadId) => {
570
+ const counts = MutableRef.get(state.ref).counts.get(threadId)
571
+
572
+ return {
573
+ idle: (MutableRef.get(state.ref).pending.get(threadId)?.size ?? 0) === 0,
574
+ deliveries: counts?.retained ?? 0,
575
+ }
576
+ },
577
+ peerCount: (threadId, nowMillis, limit) => {
578
+ const current = MutableRef.get(state.ref)
579
+ const retained = current.retainedPeers.get(threadId) ?? []
580
+
581
+ return Math.min(
582
+ (current.counts.get(threadId)?.peer ?? 0) +
583
+ retained.length -
584
+ deadlinePosition(retained, nowMillis),
585
+ limit,
586
+ )
587
+ },
588
+ facts: Effect.fnUntraced(function*(threadId, after) {
589
+ const current = MutableRef.get(state.ref)
590
+ const keys = current.ordered.get(ownerKey(threadId)) ?? []
591
+
592
+ const at = after === undefined
593
+ ? 0
594
+ : position(keys, after) + Number(keys[position(keys, after)] === after)
595
+
596
+ const messageId = keys[at]
597
+
598
+ const record = messageId === undefined
599
+ ? undefined
600
+ : yield* transferDecode(
601
+ current.records.get(
602
+ messageDeliveryKeyString({
603
+ ownerThreadId: threadId,
604
+ messageId: yield* Schema.decodeEffect(MessageDeliveryKey.fields.messageId)(
605
+ messageId,
606
+ ).pipe(Effect.orDie),
607
+ }),
608
+ ) ?? '',
609
+ )
610
+
611
+ return {
612
+ facts: {
613
+ admissions: [],
614
+ commands: { aborts: [], approvals: [], resolutions: [] },
615
+ deliveries: record === undefined
616
+ ? []
617
+ : [MessageDeliveryRecord.make({ ...record, leaseUntilMillis: null })],
618
+ },
619
+ after: messageId ?? after ?? '',
620
+ }
621
+ }),
622
+ startImport: Effect.fnUntraced(function*(threadId) {
623
+ const current = MutableRef.get(state.ref)
624
+
625
+ if ((current.counts.get(threadId)?.retained ?? 0) > 0) {
626
+ return yield* ThreadImportRejected.make({
627
+ threadId,
628
+ reason: 'target-not-empty',
629
+ message: 'Destination Thread owns retained deliveries',
630
+ })
631
+ }
632
+ const staged = backend()
633
+
634
+ return {
635
+ record: (messageId) => {
636
+ const text = staged.records.get(
637
+ messageDeliveryKeyString({ ownerThreadId: threadId, messageId }),
638
+ )
639
+
640
+ return text === undefined ? Effect.as(Effect.void, undefined) : transferDecode(text)
641
+ },
642
+ stage: Effect.fnUntraced(function*(page) {
643
+ for (const record of page.archive.deliveries) {
644
+ const key = messageDeliveryKeyString(record.key)
645
+
646
+ if (staged.records.has(key) || current.records.has(key)) {
647
+ return yield* invalidThreadArchive('Duplicate retained delivery', threadId)
648
+ }
649
+
650
+ const text = yield* encode(record).pipe(
651
+ Effect.mapError(() =>
652
+ ThreadImportRejected.make({
653
+ threadId,
654
+ reason: 'unsupported-capacity',
655
+ message: 'Delivery wire exceeds destination stored-value bound',
656
+ })
657
+ ),
658
+ )
659
+
660
+ if (
661
+ new TextEncoder().encode(
662
+ JSON.stringify(
663
+ yield* Schema.encodeEffect(PreparedInput)(record.envelope).pipe(
664
+ Effect.mapError(() => invalidThreadArchive('Invalid delivery envelope', threadId)),
665
+ ),
666
+ ),
667
+ ).byteLength > config.maxEnvelopeBytes
668
+ ) {
669
+ return yield* ThreadImportRejected.make({
670
+ threadId,
671
+ reason: 'unsupported-capacity',
672
+ message: 'Delivery envelope exceeds destination bound',
673
+ })
674
+ }
675
+ const counts = staged.counts.get(threadId)
676
+
677
+ if (
678
+ messageDeliveryUsesCapacity(record) &&
679
+ (isWorkerUpdateDelivery(record)
680
+ ? (counts?.update ?? 0)
681
+ : (counts?.ordinary ?? 0)) >=
682
+ messageDeliveryCapacity(config, isWorkerUpdateDelivery(record)).pending
683
+ ) {
684
+ return yield* ThreadImportRejected.make({
685
+ threadId,
686
+ reason: 'unsupported-capacity',
687
+ message: 'Pending delivery capacity exceeded',
688
+ })
689
+ }
690
+ commitInto(staged, record, text, false)
691
+ }
692
+ }),
693
+ prepareCommit: Effect.gen(function*() {
694
+ const reader = yield* ThreadDeliveryImportReader
695
+
696
+ const read = (messageId: MessageDeliveryKey['messageId']) => {
697
+ const text = staged.records.get(
698
+ messageDeliveryKeyString({ ownerThreadId: threadId, messageId }),
699
+ )
700
+
701
+ return text === undefined
702
+ ? Effect.fail(invalidThreadArchive('Missing delivery predecessor', threadId))
703
+ : transferDecode(text)
704
+ }
705
+
706
+ const visit = (messageId: MessageDeliveryKey['messageId']) => {
707
+ const metadata = staged.metadata.get(
708
+ messageDeliveryKeyString({ ownerThreadId: threadId, messageId }),
709
+ )
710
+
711
+ return metadata === undefined
712
+ ? Effect.fail(
713
+ invalidThreadArchive('Missing delivery predecessor metadata', threadId),
714
+ )
715
+ : Effect.succeed(metadata)
716
+ }
717
+
718
+ const verifyPredecessors = Effect.fnUntraced(function*(
719
+ start: MessageDeliveryKey['messageId'],
720
+ ) {
721
+ let cursor: MessageDeliveryKey['messageId'] | undefined = start
722
+
723
+ while (cursor !== undefined) {
724
+ const metadata = yield* visit(cursor)
725
+
726
+ if (metadata.importVisit === 'verified') break
727
+ if (metadata.importVisit === 'visiting') {
728
+ return yield* invalidThreadArchive('Delivery predecessor cycle', threadId)
729
+ }
730
+ metadata.importVisit = 'visiting'
731
+ const record: MessageDeliveryRecord = yield* read(cursor)
732
+
733
+ if (
734
+ record.predecessor !== undefined &&
735
+ (yield* read(record.predecessor)).createdAtMillis > record.createdAtMillis
736
+ ) {
737
+ return yield* invalidThreadArchive(
738
+ 'Delivery predecessor has a later boundary',
739
+ threadId,
740
+ )
741
+ }
742
+ cursor = record.predecessor
743
+ }
744
+ cursor = start
745
+ while (cursor !== undefined) {
746
+ const metadata = yield* visit(cursor)
747
+
748
+ if (metadata.importVisit === 'verified') break
749
+ metadata.importVisit = 'verified'
750
+ cursor = (yield* read(cursor)).predecessor
751
+ }
752
+ })
753
+
754
+ for (const text of staged.records.values()) {
755
+ const d = yield* transferDecode(text)
756
+
757
+ yield* verifyPredecessors(d.key.messageId)
758
+ if (d.receipt !== null) {
759
+ if (
760
+ d.settlement !== null &&
761
+ d.settlement.settlementId !== submissionSettlementId(d.receipt.submissionId)
762
+ ) {
763
+ return yield* invalidThreadArchive(
764
+ 'Delivery settlement identity is not canonical',
765
+ threadId,
766
+ )
767
+ }
768
+ const foreign = d.receipt.threadId !== threadId
769
+
770
+ if (foreign && d.status !== 'processed') {
771
+ return yield* ThreadImportRejected.make({
772
+ threadId,
773
+ reason: 'unsupported-obligations',
774
+ message: 'Live foreign delivery receipt cannot be restored',
775
+ })
776
+ }
777
+
778
+ const destination = yield* reader.admission(
779
+ d.receipt.threadId,
780
+ d.receipt.submissionId,
781
+ )
782
+
783
+ // A closed foreign delivery retains frozen evidence, not the receiver's execution authority.
784
+ if (destination === undefined) {
785
+ if (foreign && d.status === 'processed') continue
786
+
787
+ return yield* invalidThreadArchive(
788
+ 'Destination delivery receipt evidence is missing',
789
+ threadId,
790
+ )
791
+ }
792
+
793
+ const expected = PreparedInput.make({
794
+ schemaVersion: 1,
795
+ authorization: d.envelope.authorization,
796
+ threadId: destination.threadId,
797
+ deliveryPrincipal: destination.principal,
798
+ admissionKey: destination.idempotencyKey,
799
+ agentId: destination.agentId,
800
+ definitions: destination.agentDigests,
801
+ input: destination.inputPayload,
802
+ inputDigest: destination.inputDigest,
803
+ ...(destination.admissionGroup === undefined
804
+ ? {}
805
+ : { admissionGroup: destination.admissionGroup }),
806
+ ...(destination.admissionFence === undefined
807
+ ? {}
808
+ : { admissionFence: destination.admissionFence }),
809
+ ...(destination.workerAdmission === undefined
810
+ ? {}
811
+ : { workerAdmission: destination.workerAdmission }),
812
+ ...(destination.messageAdmission === undefined
813
+ ? {}
814
+ : { messageAdmission: destination.messageAdmission }),
815
+ })
816
+
817
+ if (
818
+ d.receipt.receiptId !== destination.receiptId ||
819
+ d.receipt.queueSequence !== destination.queueSequence ||
820
+ !Schema.toEquivalence(PreparedInput)(d.envelope, expected)
821
+ ) {
822
+ return yield* invalidThreadArchive(
823
+ 'Delivery envelope differs from destination admission',
824
+ threadId,
825
+ )
826
+ }
827
+ if (d.settlement !== null) {
828
+ const record = yield* reader.record(
829
+ destination.threadId,
830
+ submissionSettlementRecordId(destination.submissionId),
831
+ )
832
+
833
+ if (record === undefined) {
834
+ if (foreign) continue
835
+
836
+ return yield* invalidThreadArchive(
837
+ 'Processed delivery has no destination settlement',
838
+ threadId,
839
+ )
840
+ }
841
+
842
+ const settled = yield* validateCanonicalSettlement(record, destination).pipe(
843
+ Effect.mapError(() => invalidThreadArchive('Invalid destination settlement', threadId)),
844
+ )
845
+
846
+ const failure = settlementFailureFromRecord(record)
847
+
848
+ const expected = Settlement.make({
849
+ submissionId: settled.submissionId,
850
+ receiptId: settled.receiptId,
851
+ settlementId: settled.settlementId,
852
+ outcome: settled.outcome,
853
+ settledAt: d.settlement.settledAt,
854
+ ...(failure === undefined ? {} : { failure }),
855
+ ...(d.settlement.runDisposition === undefined ||
856
+ settled.runDisposition === undefined
857
+ ? {}
858
+ : { runDisposition: settled.runDisposition }),
859
+ ...(d.settlement.usageSummary === undefined ||
860
+ settled.usageSummary === undefined
861
+ ? {}
862
+ : { usageSummary: settled.usageSummary }),
863
+ })
864
+
865
+ if (!Schema.toEquivalence(Settlement)(d.settlement, expected)) {
866
+ return yield* invalidThreadArchive(
867
+ 'Delivery settlement differs from destination evidence',
868
+ threadId,
869
+ )
870
+ }
871
+ }
872
+ }
873
+ }
874
+
875
+ return () => {
876
+ for (const text of staged.records.values()) {
877
+ commitInto(current, Schema.decodeSync(codec)(text), text, true)
878
+ }
879
+ }
880
+ }),
881
+ }
882
+ }),
883
+ })
884
+
885
+ return MessageDeliveryStore.of({
886
+ limits: config,
887
+ maxStoredValueBytes,
888
+ insert,
889
+ get,
890
+ change,
891
+ list: Effect.fnUntraced(function*(request) {
892
+ const input = yield* validateMessageDelivery(MessageDeliveryPageRequest, request, 'list')
893
+
894
+ const current = yield* Ref.get(state)
895
+
896
+ const workerKey = input.workerStarts !== undefined
897
+ ? JSON.stringify([
898
+ input.ownerThreadId,
899
+ input.workerStarts.delegationId,
900
+ input.workerStarts.targetAgentId,
901
+ ])
902
+ : input.pendingWorker !== undefined
903
+ ? JSON.stringify([input.ownerThreadId, input.pendingWorker])
904
+ : undefined
905
+
906
+ const keys = workerKey === undefined
907
+ ? input.pendingOnly
908
+ ? Array.from(current.pending.get(input.ownerThreadId) ?? []).sort()
909
+ : (current.ordered.get(ownerKey(input.ownerThreadId)) ?? [])
910
+ : (current.ordered.get(workerKey) ?? [])
911
+
912
+ const start = input.after === undefined
913
+ ? 0
914
+ : position(keys, input.after) +
915
+ Number(keys[position(keys, input.after)] === input.after)
916
+
917
+ const items: Array<MessageDeliveryRecord> = []
918
+ let bytes = 0
919
+ let at = start
920
+
921
+ while (at < keys.length && items.length < input.limit) {
922
+ const text = current.records.get(
923
+ messageDeliveryKeyString({
924
+ ownerThreadId: input.ownerThreadId,
925
+ messageId: yield* Schema.decodeEffect(MessageDeliveryKey.fields.messageId)(
926
+ keys[at],
927
+ ).pipe(Effect.orDie),
928
+ }),
929
+ )
930
+
931
+ if (text === undefined) {
932
+ return yield* MessageDeliveryError.make({
933
+ reason: 'corrupt',
934
+ operation: 'list locator',
935
+ })
936
+ }
937
+ const size = new TextEncoder().encode(text).byteLength
938
+
939
+ if (size > 32 * 1024 * 1024) {
940
+ return yield* MessageDeliveryError.make({
941
+ reason: 'capacity',
942
+ operation: 'list byte bound',
943
+ })
944
+ }
945
+ if (bytes + size > 32 * 1024 * 1024) break
946
+ items.push(yield* decode(text))
947
+ bytes += size
948
+ at++
949
+ }
950
+
951
+ return {
952
+ items,
953
+ next: at < keys.length ? (items.at(-1)?.key.messageId ?? null) : null,
954
+ }
955
+ }),
956
+ due: Effect.fnUntraced(function*(nowMillis, limit, ownerThreadId) {
957
+ const input = yield* validateMessageDelivery(
958
+ Scan,
959
+ { nowMillis, limit, ...(ownerThreadId === undefined ? {} : { ownerThreadId }) },
960
+ 'due',
961
+ )
962
+
963
+ const current = MutableRef.get(state.ref)
964
+
965
+ const keys = input.ownerThreadId === undefined
966
+ ? current.deadlineKeys
967
+ : (current.ownerDeadlineKeys.get(input.ownerThreadId) ?? [])
968
+
969
+ const selected: Array<MessageDeliveryKey> = []
970
+
971
+ for (const key of keys) {
972
+ const row = current.deadlines.get(key)
973
+
974
+ if (row === undefined) {
975
+ return yield* MessageDeliveryError.make({
976
+ reason: 'corrupt',
977
+ operation: 'deadline index',
978
+ })
979
+ }
980
+ if (row.deadline > input.nowMillis || selected.length === input.limit) break
981
+ selected.push(row.key)
982
+ }
983
+
984
+ return selected
985
+ }),
986
+ nextDeadline: Effect.fnUntraced(function*(ownerThreadId) {
987
+ if (ownerThreadId !== undefined) {
988
+ yield* validateMessageDelivery(ThreadId, ownerThreadId, 'nextDeadline')
989
+ }
990
+ const current = MutableRef.get(state.ref)
991
+
992
+ const first = (
993
+ ownerThreadId === undefined
994
+ ? current.deadlineKeys
995
+ : current.ownerDeadlineKeys.get(ownerThreadId)
996
+ )?.[0]
997
+
998
+ return first === undefined ? null : (current.deadlines.get(first)?.deadline ?? null)
999
+ }),
1000
+ })
1001
+ }),
1002
+ )
1003
+
1004
+ export const MemoryMessageDeliveryStoreLive = memoryMessageDeliveryStoreLayer()