@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,3590 @@
1
+ import { canonicalJson, utf8ByteLength } from '@systemfsoftware/agent/digest'
2
+ import {
3
+ type AgentId,
4
+ AttemptId,
5
+ ReceiptId,
6
+ type RunId,
7
+ type SettlementId,
8
+ SubmissionId,
9
+ type ThreadId,
10
+ type ToolCallId,
11
+ } from '@systemfsoftware/agent/identifiers'
12
+ import { InputMessage } from '@systemfsoftware/agent/messaging'
13
+ import {
14
+ type DefinitionDigests,
15
+ type DeploymentId,
16
+ type Digest,
17
+ MAX_RUN_EVIDENCE_BYTES,
18
+ MAX_RUN_EVIDENCE_RECORDS,
19
+ PersistedJson,
20
+ type RecordEnvelope,
21
+ type SettlementOutcome,
22
+ WorkerAdmission,
23
+ } from '@systemfsoftware/agent/records'
24
+ import { runIdForSubmission } from '@systemfsoftware/agent/run-journal'
25
+ import {
26
+ SettlementPublicationResult,
27
+ SettlementPublisher,
28
+ validateCanonicalSettlement,
29
+ validateJoinedSettlement,
30
+ validatePublication,
31
+ } from '@systemfsoftware/agent/settlement-publisher'
32
+ import {
33
+ AbortCommand,
34
+ AbortIntent,
35
+ AbortIntentRequest,
36
+ AdmissionAdmitted,
37
+ AdmissionConflict,
38
+ AdmissionIndeterminate,
39
+ AdmissionNotAdmitted,
40
+ AdmissionPolicyError,
41
+ AdmissionRequest,
42
+ AdmissionResult,
43
+ ApprovalConflict,
44
+ ApprovalDecisionCommand,
45
+ ApprovalDecisionIntent,
46
+ approvalDecisionsCover,
47
+ AttachChildToReservationRequest,
48
+ BeginChildBudgetReleaseRequest,
49
+ ChildAttachmentSnapshot,
50
+ ChildBudgetReservationRequest,
51
+ ChildBudgetReservationSnapshot,
52
+ ChildReservationConflict,
53
+ type ChildReservationId,
54
+ type ChildReservationStatus,
55
+ ChildSettledNotification,
56
+ type ChildSettledOutcome,
57
+ Claim,
58
+ ClaimJoiningRequest,
59
+ ClaimRequest,
60
+ FundingOwner,
61
+ FundingOwnerRequest,
62
+ type IdempotencyKey,
63
+ InputAppliedMarker,
64
+ JoinedToHost,
65
+ JoiningClaim,
66
+ JoinSnapshot,
67
+ LedgerCapabilities,
68
+ LedgerError,
69
+ MarkInputAppliedRequest,
70
+ MarkJoinedRequest,
71
+ MarkReadyRequest,
72
+ MarkUnknownRequest,
73
+ OwnershipLost,
74
+ type ParentLinkage,
75
+ type Principal,
76
+ QueueSequence,
77
+ RecoverySnapshot,
78
+ RecoverySnapshotRequest,
79
+ ReleaseChildBudgetRequest,
80
+ ReservedChildBudget,
81
+ RevertJoiningRequest,
82
+ Settlement,
83
+ SettlementConflict,
84
+ settlementFailureFromRecord,
85
+ SettlementFinalization,
86
+ SubmissionAdmissionFence,
87
+ SubmissionLedger,
88
+ SubmissionLookup,
89
+ SubmissionLookupByKey,
90
+ submissionSettlementRecordId,
91
+ SubmissionSnapshot,
92
+ type SubmissionState,
93
+ SubmissionWorkItem,
94
+ SuspendRequest,
95
+ type SuspensionOutcome,
96
+ type SuspensionReason,
97
+ SuspensionSnapshot,
98
+ UnknownResolution,
99
+ UnknownResolutionCommand,
100
+ UnknownResolutionConflict,
101
+ UnknownResolutionIntent,
102
+ unknownResolutionKind,
103
+ unknownResolutionMatchesResult,
104
+ WorkerLedgerState,
105
+ WorkerStopCommand,
106
+ workerTerminalFromRecord,
107
+ } from '@systemfsoftware/agent/submission-ledger'
108
+ import {
109
+ invalidThreadArchive,
110
+ rebuildClosedSubmission,
111
+ RebuiltSubmission,
112
+ ThreadImportRejected,
113
+ } from '@systemfsoftware/agent/thread-import'
114
+ import {
115
+ makeTransferFactCheck,
116
+ ThreadAbortFact,
117
+ ThreadAdmission,
118
+ ThreadApprovalFact,
119
+ ThreadResolutionFact,
120
+ ThreadStoreError,
121
+ transferPageFits,
122
+ } from '@systemfsoftware/agent/thread-store'
123
+ import { admissionWork } from '@systemfsoftware/agent/thread-work'
124
+ import * as Cause from 'effect/Cause'
125
+ import * as Clock from 'effect/Clock'
126
+ import * as Context from 'effect/Context'
127
+ import * as SecureRandom from 'effect/crypto/SecureRandom'
128
+ import * as DateTime from 'effect/DateTime'
129
+ import * as Effect from 'effect/Effect'
130
+ import * as Exit from 'effect/Exit'
131
+ import * as Fiber from 'effect/Fiber'
132
+ import * as Layer from 'effect/Layer'
133
+ import * as MutableRef from 'effect/MutableRef'
134
+ import * as Option from 'effect/Option'
135
+ import * as Ref from 'effect/Ref'
136
+ import * as Result from 'effect/Result'
137
+ import * as Schema from 'effect/Schema'
138
+ import * as Stream from 'effect/Stream'
139
+
140
+ import { MemoryThreadStoreKernel } from './internal/MemoryThreadStoreKernel'
141
+ import { boundedWorkSelection } from './internal/WorkSelection'
142
+
143
+ /**
144
+ * Lifecycle ordering used to advance-but-never-regress the operational state marker: a reclaimed
145
+ * Attempt must not erase progress markers (input-applied) that an earlier Attempt
146
+ * already committed.
147
+ */
148
+ const STATE_RANK: Record<SubmissionState, number> = {
149
+ admitted: 0,
150
+ ready: 1,
151
+ joining: 2,
152
+ joined: 3,
153
+ 'input-applied': 5,
154
+ suspended: 6,
155
+ unknown: 7,
156
+ settled: 8,
157
+ }
158
+
159
+ interface SubmissionRow {
160
+ readonly submissionId: SubmissionId
161
+ readonly threadId: ThreadId
162
+ readonly queueSequence: QueueSequence
163
+ readonly principal: Principal
164
+ readonly idempotencyKey: IdempotencyKey
165
+ readonly agentId: AgentId
166
+ readonly agentDigests: DefinitionDigests
167
+ readonly deploymentId: DeploymentId
168
+ readonly inputPayload: PersistedJson
169
+ readonly inputDigest: Digest
170
+ readonly receiptId: ReceiptId
171
+ readonly state: SubmissionState
172
+ readonly settledOutcome: SettlementOutcome | undefined
173
+ readonly createdAtMillis: number
174
+ readonly readyAtMillis: number | undefined
175
+ /** Immutable child-side lineage recorded at admission (spec §12 step 5). */
176
+ readonly parentLinkage: ParentLinkage | undefined
177
+ readonly admissionGroup?: string
178
+ readonly admissionFence?: AdmissionRequest['admissionFence']
179
+ readonly workerAdmissionJson?: string
180
+ readonly messageAdmissionJson?: string
181
+ }
182
+
183
+ interface StoredFinalization {
184
+ readonly settlementId: SettlementId
185
+ readonly finalizedAtMillis: number
186
+ readonly recordId: RecordEnvelope['recordId']
187
+ }
188
+
189
+ interface StoredSuspension {
190
+ readonly reason: SuspensionReason
191
+ readonly suspendedAtMillis: number
192
+ }
193
+
194
+ interface StoredUnknownMark {
195
+ readonly reason: MarkUnknownRequest['reason']
196
+ readonly toolCallIds: ReadonlyArray<ToolCallId>
197
+ }
198
+
199
+ interface StoredUnknownResolution {
200
+ readonly intent: UnknownResolutionIntent
201
+ }
202
+
203
+ interface StoredSubmission {
204
+ readonly row: SubmissionRow
205
+ readonly inputApplied: InputAppliedMarker | undefined
206
+ readonly finalization: StoredFinalization | undefined
207
+ readonly abortIntent: AbortIntent | undefined
208
+ /** Host linkage recorded at `claimJoining` time; cleared by `revertJoining` (DUR-016). */
209
+ readonly joinedHostSubmissionId: SubmissionId | undefined
210
+ readonly suspension: StoredSuspension | undefined
211
+ readonly unknownMark: StoredUnknownMark | undefined
212
+ readonly approvalDecisions: ReadonlyMap<ToolCallId, ApprovalDecisionIntent>
213
+ readonly unknownResolutions: ReadonlyMap<string, StoredUnknownResolution>
214
+ }
215
+
216
+ /**
217
+ * States in which `claim` never grants the head: the lane is host-owned (`joining`/`joined`)
218
+ * or durably suspended rather than worker-claimable. Unknown heads are checked against abort
219
+ * intent separately: abort authorizes cleanup and settlement, never ordinary Tool replay.
220
+ */
221
+ const BLOCKED_HEAD_STATES: ReadonlySet<SubmissionState> = new Set([
222
+ 'joining',
223
+ 'joined',
224
+ 'suspended',
225
+ ])
226
+
227
+ interface LaneState {
228
+ readonly nextQueueSequence: number
229
+ }
230
+
231
+ /** One parent-owned child budget reservation row (spec §12 steps 2 and 6). */
232
+ interface StoredChildReservation {
233
+ readonly reservationId: ChildReservationId
234
+ readonly parentSubmissionId: SubmissionId
235
+ readonly parentToolCallId: ToolCallId
236
+ readonly childSubmissionId: SubmissionId | undefined
237
+ readonly status: ChildReservationStatus
238
+ readonly allocation: PersistedJson
239
+ readonly allocationDigest: Digest
240
+ readonly accounting: PersistedJson | undefined
241
+ readonly reservedAtMillis: number
242
+ readonly releaseBeganAtMillis: number | undefined
243
+ readonly releasedAtMillis: number | undefined
244
+ }
245
+
246
+ interface ThreadDirectory {
247
+ readonly ordered: Array<SubmissionId>
248
+ readonly commands: {
249
+ readonly aborts: Array<CommandLocator>
250
+ readonly approvals: Array<CommandLocator>
251
+ readonly resolutions: Array<CommandLocator>
252
+ }
253
+ children: number
254
+ workers: number
255
+ reservations: number
256
+ }
257
+ interface CommandLocator {
258
+ readonly key: string
259
+ readonly submissionId: SubmissionId
260
+ readonly toolCallId?: ToolCallId
261
+ readonly resolutionKey?: string
262
+ }
263
+
264
+ const commandPosition = (entries: ReadonlyArray<CommandLocator>, key: string) => {
265
+ let low = 0
266
+ let high = entries.length
267
+
268
+ while (low < high) {
269
+ const middle = Math.floor((low + high) / 2)
270
+
271
+ if (entries[middle].key < key) low = middle + 1
272
+ else high = middle
273
+ }
274
+
275
+ return low
276
+ }
277
+
278
+ const retainCommand = (
279
+ entries: Array<CommandLocator>,
280
+ submissionId: SubmissionId,
281
+ toolCallId?: ToolCallId,
282
+ resolutionKey?: string,
283
+ ) => {
284
+ // Acceptance order is native, stable and append-only; publishing a command never shifts history.
285
+ const key = String(entries.length + 1).padStart(16, '0')
286
+
287
+ entries.push({
288
+ key,
289
+ submissionId,
290
+ ...(toolCallId === undefined ? {} : { toolCallId }),
291
+ ...(resolutionKey === undefined ? {} : { resolutionKey }),
292
+ })
293
+ }
294
+
295
+ interface LedgerState {
296
+ readonly byThread: Map<ThreadId, ThreadDirectory>
297
+ readonly receipts: Map<ReceiptId, SubmissionId>
298
+ readonly joinsByHost: Map<SubmissionId, Set<SubmissionId>>
299
+ readonly childrenByParent: Map<SubmissionId, Set<ChildReservationId>>
300
+ readonly submissions: Map<SubmissionId, StoredSubmission>
301
+ readonly admissionIndex: Map<string, SubmissionId>
302
+ readonly lanes: Map<ThreadId, LaneState>
303
+ readonly childReservations: Map<ChildReservationId, StoredChildReservation>
304
+ /** Bounded local ordering for fresh work identities; imported facts never seed it. */
305
+ readonly freshAdmissionSequence: number
306
+ readonly latestByThread: Map<ThreadId, SubmissionId>
307
+ readonly activeByThread: Map<ThreadId, Set<SubmissionId>>
308
+ readonly stoppedWorkers: Map<ThreadId, WorkerLedgerState['terminal']>
309
+ }
310
+
311
+ type Decision<A, E> =
312
+ | { readonly _tag: 'failure'; readonly error: E }
313
+ | { readonly _tag: 'success'; readonly value: A }
314
+
315
+ const failure = <E>(error: E): Decision<never, E> => ({ _tag: 'failure', error })
316
+ const success = <A>(value: A): Decision<A, never> => ({ _tag: 'success', value })
317
+
318
+ const ledgerError = (operation: string, message: string, cause?: unknown): LedgerError =>
319
+ cause === undefined
320
+ ? LedgerError.make({ operation, message })
321
+ : LedgerError.make({ operation, message, cause })
322
+
323
+ const validate = <A, I>(
324
+ schema: Schema.Codec<A, I>,
325
+ operation: string,
326
+ value: unknown,
327
+ ): Effect.Effect<A, LedgerError> =>
328
+ Schema.encodeUnknownEffect(schema)(value).pipe(
329
+ Effect.flatMap(Schema.decodeUnknownEffect(schema)),
330
+ Effect.mapError((error) => ledgerError(operation, `Invalid ${operation} request`, error)),
331
+ )
332
+
333
+ const decodeSubmissionId = Schema.decodeSync(SubmissionId)
334
+ const decodeReceiptId = Schema.decodeSync(ReceiptId)
335
+ const decodeAttemptId = Schema.decodeSync(AttemptId)
336
+ // Imported identities are opaque facts and never influence fresh identity sizes.
337
+ const MemoryIdentityNonce = Schema.String.check(Schema.isUUID(4))
338
+ const decodeQueueSequence = Schema.decodeSync(QueueSequence)
339
+ const equivalentPersistedJson = Schema.toEquivalence(PersistedJson)
340
+ const equivalentUnknownResolution = Schema.toEquivalence(UnknownResolution)
341
+ const admissionFitsTransfer = makeTransferFactCheck(ThreadAdmission)
342
+ const abortFitsTransfer = makeTransferFactCheck(ThreadAbortFact)
343
+ const approvalFitsTransfer = makeTransferFactCheck(ThreadApprovalFact)
344
+ const resolutionFitsTransfer = makeTransferFactCheck(ThreadResolutionFact)
345
+
346
+ const transferCapacityError = (operation: string) =>
347
+ ledgerError(operation, 'Accepted fact exceeds its bounded transfer representation')
348
+
349
+ const utc = (millis: number): DateTime.Utc => DateTime.toUtc(DateTime.makeUnsafe(millis))
350
+
351
+ const admissionKey = (
352
+ threadId: ThreadId,
353
+ principal: Principal,
354
+ idempotencyKey: IdempotencyKey,
355
+ ): string => JSON.stringify([threadId, principal, idempotencyKey])
356
+
357
+ const toSnapshot = (row: SubmissionRow): SubmissionSnapshot =>
358
+ SubmissionSnapshot.make({
359
+ submissionId: row.submissionId,
360
+ threadId: row.threadId,
361
+ queueSequence: row.queueSequence,
362
+ principal: row.principal,
363
+ idempotencyKey: row.idempotencyKey,
364
+ agentId: row.agentId,
365
+ agentDigests: row.agentDigests,
366
+ deploymentId: row.deploymentId,
367
+ inputPayload: row.inputPayload,
368
+ inputDigest: row.inputDigest,
369
+ receiptId: row.receiptId,
370
+ state: row.state,
371
+ createdAt: utc(row.createdAtMillis),
372
+ ...(row.admissionGroup === undefined ? {} : { admissionGroup: row.admissionGroup }),
373
+ ...(row.admissionFence === undefined ? {} : { admissionFence: row.admissionFence }),
374
+ ...(row.workerAdmissionJson === undefined
375
+ ? {}
376
+ : {
377
+ workerAdmission: Schema.decodeSync(Schema.fromJsonString(WorkerAdmission))(
378
+ row.workerAdmissionJson,
379
+ ),
380
+ }),
381
+ ...(row.messageAdmissionJson === undefined
382
+ ? {}
383
+ : {
384
+ messageAdmission: Schema.decodeSync(Schema.fromJsonString(InputMessage))(
385
+ row.messageAdmissionJson,
386
+ ),
387
+ }),
388
+ ...(row.settledOutcome === undefined ? {} : { settledOutcome: row.settledOutcome }),
389
+ ...(row.readyAtMillis === undefined ? {} : { readyAt: utc(row.readyAtMillis) }),
390
+ ...(row.parentLinkage === undefined ? {} : { parentLinkage: row.parentLinkage }),
391
+ })
392
+
393
+ const toReservationSnapshot = (row: StoredChildReservation): ChildBudgetReservationSnapshot =>
394
+ ChildBudgetReservationSnapshot.make({
395
+ reservationId: row.reservationId,
396
+ parentSubmissionId: row.parentSubmissionId,
397
+ parentToolCallId: row.parentToolCallId,
398
+ status: row.status,
399
+ allocation: row.allocation,
400
+ allocationDigest: row.allocationDigest,
401
+ reservedAt: utc(row.reservedAtMillis),
402
+ ...(row.childSubmissionId === undefined ? {} : { childSubmissionId: row.childSubmissionId }),
403
+ ...(row.accounting === undefined ? {} : { accounting: row.accounting }),
404
+ ...(row.releaseBeganAtMillis === undefined
405
+ ? {}
406
+ : { releaseBeganAt: utc(row.releaseBeganAtMillis) }),
407
+ ...(row.releasedAtMillis === undefined ? {} : { releasedAt: utc(row.releasedAtMillis) }),
408
+ })
409
+
410
+ const fromRebuilt = (rebuilt: RebuiltSubmission): StoredSubmission => {
411
+ const admission = rebuilt.admission
412
+ const threadId = admission.threadId
413
+ const canonicalSettlement = rebuilt.settlement?.payload
414
+
415
+ const settlement = canonicalSettlement?._tag === 'SubmissionSettled' ? canonicalSettlement : undefined
416
+
417
+ return {
418
+ row: {
419
+ submissionId: admission.submissionId,
420
+ threadId,
421
+ queueSequence: admission.queueSequence,
422
+ principal: admission.principal,
423
+ idempotencyKey: admission.idempotencyKey,
424
+ agentId: admission.agentId,
425
+ agentDigests: admission.agentDigests,
426
+ deploymentId: admission.deploymentId,
427
+ inputPayload: admission.inputPayload,
428
+ inputDigest: admission.inputDigest,
429
+ receiptId: admission.receiptId,
430
+ state: rebuilt.state,
431
+ settledOutcome: settlement?.outcome,
432
+ createdAtMillis: DateTime.toEpochMillis(admission.createdAt),
433
+ readyAtMillis: rebuilt.state === 'ready' ? DateTime.toEpochMillis(admission.createdAt) : undefined,
434
+ parentLinkage: admission.parentLinkage,
435
+ ...(admission.workerAdmission === undefined
436
+ ? {}
437
+ : {
438
+ workerAdmissionJson: Schema.encodeSync(Schema.fromJsonString(WorkerAdmission))(
439
+ admission.workerAdmission,
440
+ ),
441
+ }),
442
+ ...(admission.messageAdmission === undefined
443
+ ? {}
444
+ : {
445
+ messageAdmissionJson: Schema.encodeSync(Schema.fromJsonString(InputMessage))(
446
+ admission.messageAdmission,
447
+ ),
448
+ }),
449
+ ...(admission.admissionGroup === undefined
450
+ ? {}
451
+ : { admissionGroup: admission.admissionGroup }),
452
+ ...(admission.admissionFence === undefined
453
+ ? {}
454
+ : { admissionFence: admission.admissionFence }),
455
+ },
456
+ inputApplied: rebuilt.inputApplied,
457
+ finalization: settlement === undefined ||
458
+ rebuilt.settlement === undefined ||
459
+ admission.settledAt === undefined
460
+ ? undefined
461
+ : {
462
+ settlementId: settlement.settlementId,
463
+ recordId: rebuilt.settlement.recordId,
464
+ finalizedAtMillis: DateTime.toEpochMillis(admission.settledAt),
465
+ },
466
+ abortIntent: rebuilt.abort,
467
+ joinedHostSubmissionId: rebuilt.joinedHostSubmissionId,
468
+ suspension: rebuilt.suspension === undefined
469
+ ? undefined
470
+ : {
471
+ reason: rebuilt.suspension.reason,
472
+ suspendedAtMillis: DateTime.toEpochMillis(rebuilt.suspension.suspendedAt),
473
+ },
474
+ unknownMark: rebuilt.unknownToolCallIds.length === 0
475
+ ? undefined
476
+ : {
477
+ reason: 'Unresolved Tool execution recovered from the canonical log',
478
+ toolCallIds: rebuilt.unknownToolCallIds,
479
+ },
480
+ approvalDecisions: new Map(rebuilt.approvals.map((intent) => [intent.toolCallId, intent])),
481
+ unknownResolutions: new Map(
482
+ rebuilt.resolutions.map((intent) => [
483
+ JSON.stringify([intent.toolCallId, unknownResolutionKind(intent.resolution)]),
484
+ { intent },
485
+ ]),
486
+ ),
487
+ }
488
+ }
489
+
490
+ /** Linkage equality: both absent, or both present naming the same parent Tool Call. */
491
+ const sameParentLinkage = (
492
+ left: ParentLinkage | undefined,
493
+ right: ParentLinkage | undefined,
494
+ ): boolean =>
495
+ left === undefined
496
+ ? right === undefined
497
+ : right !== undefined &&
498
+ left.parentSubmissionId === right.parentSubmissionId &&
499
+ left.parentToolCallId === right.parentToolCallId
500
+
501
+ const ownershipLost = (stored: StoredSubmission): OwnershipLost =>
502
+ OwnershipLost.make({ submissionId: stored.row.submissionId })
503
+
504
+ const withSubmission = (state: LedgerState, stored: StoredSubmission): LedgerState => {
505
+ const row = stored.row
506
+ const previous = state.submissions.get(row.submissionId)
507
+ let directory = state.byThread.get(row.threadId)
508
+
509
+ if (directory === undefined) {
510
+ directory = {
511
+ ordered: [],
512
+ commands: { aborts: [], approvals: [], resolutions: [] },
513
+ children: 0,
514
+ workers: 0,
515
+ reservations: 0,
516
+ }
517
+ state.byThread.set(row.threadId, directory)
518
+ }
519
+ if (previous === undefined) {
520
+ let low = 0
521
+ let high = directory.ordered.length
522
+
523
+ while (low < high) {
524
+ const middle = Math.floor((low + high) / 2)
525
+ const candidate = state.submissions.get(directory.ordered[middle])
526
+
527
+ if (candidate !== undefined && candidate.row.queueSequence < row.queueSequence) {
528
+ low = middle + 1
529
+ } else high = middle
530
+ }
531
+ directory.ordered.splice(low, 0, row.submissionId)
532
+ state.receipts.set(row.receiptId, row.submissionId)
533
+ state.admissionIndex.set(
534
+ admissionKey(row.threadId, row.principal, row.idempotencyKey),
535
+ row.submissionId,
536
+ )
537
+ const latest = state.latestByThread.get(row.threadId)
538
+
539
+ if (
540
+ latest === undefined ||
541
+ (state.submissions.get(latest)?.row.queueSequence ?? -1) < row.queueSequence
542
+ ) {
543
+ state.latestByThread.set(row.threadId, row.submissionId)
544
+ }
545
+ }
546
+ directory.children += Number(row.state !== 'settled' && row.parentLinkage !== undefined) -
547
+ Number(
548
+ previous !== undefined &&
549
+ previous.row.state !== 'settled' &&
550
+ previous.row.parentLinkage !== undefined,
551
+ )
552
+ directory.workers += Number(row.state !== 'settled' && row.workerAdmissionJson !== undefined) -
553
+ Number(
554
+ previous !== undefined &&
555
+ previous.row.state !== 'settled' &&
556
+ previous.row.workerAdmissionJson !== undefined,
557
+ )
558
+ if (stored.abortIntent !== undefined && previous?.abortIntent === undefined) {
559
+ retainCommand(directory.commands.aborts, row.submissionId)
560
+ }
561
+ if (stored.approvalDecisions !== previous?.approvalDecisions) {
562
+ for (const id of stored.approvalDecisions.keys()) {
563
+ if (!previous?.approvalDecisions.has(id)) {
564
+ retainCommand(directory.commands.approvals, row.submissionId, id)
565
+ }
566
+ }
567
+ }
568
+ if (stored.unknownResolutions !== previous?.unknownResolutions) {
569
+ for (const [id, value] of stored.unknownResolutions) {
570
+ if (!previous?.unknownResolutions.has(id)) {
571
+ retainCommand(
572
+ directory.commands.resolutions,
573
+ row.submissionId,
574
+ value.intent.toolCallId,
575
+ id,
576
+ )
577
+ }
578
+ }
579
+ }
580
+ if (
581
+ previous?.joinedHostSubmissionId !== undefined &&
582
+ previous.joinedHostSubmissionId !== stored.joinedHostSubmissionId
583
+ ) {
584
+ state.joinsByHost.get(previous.joinedHostSubmissionId)?.delete(row.submissionId)
585
+ }
586
+ if (stored.joinedHostSubmissionId !== undefined) {
587
+ let joins = state.joinsByHost.get(stored.joinedHostSubmissionId)
588
+
589
+ if (joins === undefined) {
590
+ state.joinsByHost.set(stored.joinedHostSubmissionId, joins = new Set())
591
+ }
592
+ joins.add(row.submissionId)
593
+ }
594
+ let active = state.activeByThread.get(row.threadId)
595
+
596
+ if (active === undefined) state.activeByThread.set(row.threadId, active = new Set())
597
+ if (row.state === 'settled') active.delete(row.submissionId)
598
+ else active.add(row.submissionId)
599
+ state.submissions.set(row.submissionId, stored)
600
+
601
+ return state
602
+ }
603
+
604
+ const withChildReservation = (
605
+ state: LedgerState,
606
+ reservation: StoredChildReservation,
607
+ ): LedgerState => {
608
+ const previous = state.childReservations.get(reservation.reservationId)
609
+
610
+ state.childReservations.set(reservation.reservationId, reservation)
611
+ let children = state.childrenByParent.get(reservation.parentSubmissionId)
612
+
613
+ if (children === undefined) {
614
+ state.childrenByParent.set(reservation.parentSubmissionId, children = new Set())
615
+ }
616
+ children.add(reservation.reservationId)
617
+ const parent = state.submissions.get(reservation.parentSubmissionId)
618
+
619
+ if (parent !== undefined) {
620
+ const directory = state.byThread.get(parent.row.threadId)
621
+
622
+ if (directory !== undefined) {
623
+ directory.reservations += Number(reservation.status !== 'released') -
624
+ Number(previous !== undefined && previous.status !== 'released')
625
+ }
626
+ }
627
+
628
+ return state
629
+ }
630
+
631
+ const findHead = (state: LedgerState, threadId: ThreadId): StoredSubmission | undefined => {
632
+ let head: StoredSubmission | undefined
633
+
634
+ for (const id of state.activeByThread.get(threadId) ?? []) {
635
+ const stored = state.submissions.get(id)
636
+
637
+ if (
638
+ stored === undefined ||
639
+ (stored.row.state === 'unknown' && stored.abortIntent === undefined)
640
+ ) {
641
+ continue
642
+ }
643
+ if (head === undefined || stored.row.queueSequence < head.row.queueSequence) head = stored
644
+ }
645
+
646
+ return head
647
+ }
648
+
649
+ function* threadRows(state: LedgerState, threadId: ThreadId, after = -1) {
650
+ const ordered = state.byThread.get(threadId)?.ordered ?? []
651
+ let low = 0
652
+ let high = ordered.length
653
+
654
+ while (low < high) {
655
+ const middle = Math.floor((low + high) / 2)
656
+
657
+ if ((state.submissions.get(ordered[middle])?.row.queueSequence ?? -1) <= after) {
658
+ low = middle + 1
659
+ } else high = middle
660
+ }
661
+ for (let index = low; index < ordered.length; index++) {
662
+ const stored = state.submissions.get(ordered[index])
663
+
664
+ if (stored !== undefined) yield stored
665
+ }
666
+ }
667
+
668
+ const makeSubmissionLedger = Effect.fnUntraced(
669
+ /**
670
+ * Reference in-memory SubmissionLedger. Admission, ordered selection and canonical settlement
671
+ * share the Memory kernel's mutation gate. The kernel Scope owns local Run capabilities;
672
+ * selecting work does not write execution ownership into the ledger.
673
+ *
674
+ * Joining retains the contiguous ready prefix and exact host linkage. Canonical settlement
675
+ * authorizes finalization and child wake repair, while bound sessions reject late commands.
676
+ * Child wake checks read the child rows directly, without a separate notification marker.
677
+ * Admission resolution is strongly consistent; resolveAdmissionFault injects the
678
+ * Indeterminate outcome for existing caller conformance workflows.
679
+ */
680
+ function*(options: MemorySubmissionLedgerOptions = {}) {
681
+ const journal = yield* MemoryThreadStoreKernel
682
+ const crypto = yield* SecureRandom.SecureRandom
683
+
684
+ const mintIdentity = (operation: string) =>
685
+ crypto.uuidV4().pipe(
686
+ Effect.flatMap(Schema.decodeEffect(MemoryIdentityNonce)),
687
+ Effect.mapError((cause) => ledgerError(operation, 'Cannot mint a Memory identity', cause)),
688
+ )
689
+
690
+ const state = yield* Ref.make<LedgerState>({
691
+ byThread: new Map(),
692
+ receipts: new Map(),
693
+ joinsByHost: new Map(),
694
+ childrenByParent: new Map(),
695
+ submissions: new Map(),
696
+ admissionIndex: new Map(),
697
+ lanes: new Map(),
698
+ childReservations: new Map(),
699
+ freshAdmissionSequence: 0,
700
+ stoppedWorkers: new Map(),
701
+ latestByThread: new Map(),
702
+ activeByThread: new Map(),
703
+ })
704
+
705
+ yield* journal.registerWorkOwner('admissions', {
706
+ threads: (request) =>
707
+ Ref.get(state).pipe(
708
+ Effect.map((current) => {
709
+ const candidates = boundedWorkSelection<ThreadId>(
710
+ request.limit,
711
+ (id) => id,
712
+ request.afterThreadId,
713
+ )
714
+
715
+ for (const [threadId, ids] of current.activeByThread) {
716
+ if (ids.size > 0) candidates.add(threadId)
717
+ }
718
+ const threadIds = candidates.values
719
+
720
+ const afterThreadId = threadIds.length === request.limit ? threadIds.at(-1) : undefined
721
+
722
+ return {
723
+ threadIds,
724
+ ...(afterThreadId === undefined ? {} : { afterThreadId }),
725
+ }
726
+ }),
727
+ ),
728
+ page: Effect.fnUntraced(function*(threadId, after, limit) {
729
+ const current = yield* Ref.get(state)
730
+
731
+ const candidates = boundedWorkSelection<SubmissionId>(limit + 1, (id) => id, after)
732
+
733
+ for (const id of current.activeByThread.get(threadId) ?? []) candidates.add(id)
734
+ const ids = candidates.values
735
+
736
+ const entries = []
737
+
738
+ for (const id of ids.slice(0, limit)) {
739
+ const stored = current.submissions.get(id)
740
+
741
+ if (
742
+ stored === undefined ||
743
+ stored.row.threadId !== threadId ||
744
+ stored.row.state === 'settled'
745
+ ) {
746
+ return yield* ThreadStoreError.make({
747
+ operation: 'admission work',
748
+ message: 'Active admission index is incomplete or corrupt',
749
+ })
750
+ }
751
+ const entry = admissionWork(stored.row)
752
+
753
+ entries.push(
754
+ stored.suspension === undefined
755
+ ? entry
756
+ : {
757
+ ...entry,
758
+ wait: stored.suspension.reason._tag === 'WaitingForChild'
759
+ ? ('child' as const)
760
+ : ('approval' as const),
761
+ },
762
+ )
763
+ }
764
+ const next = ids.length > limit ? ids[limit - 1] : undefined
765
+
766
+ return { entries, ...(next === undefined ? {} : { after: next }) }
767
+ }),
768
+ })
769
+
770
+ const admissionFence = yield* SubmissionAdmissionFence
771
+
772
+ const capabilities = Effect.succeed(LedgerCapabilities.make({ durability: 'non-durable' }))
773
+
774
+ const admit: SubmissionLedger['Service']['admit'] = Effect.fnUntraced(function*(unvalidated) {
775
+ const request = yield* validate(AdmissionRequest, 'admit', unvalidated)
776
+
777
+ const workerAdmissionJson = request.workerAdmission === undefined
778
+ ? undefined
779
+ : yield* Schema.encodeEffect(Schema.fromJsonString(WorkerAdmission))(
780
+ request.workerAdmission,
781
+ ).pipe(
782
+ Effect.mapError(() => ledgerError('admit', 'Invalid worker admission metadata')),
783
+ )
784
+
785
+ const messageAdmissionJson = request.messageAdmission === undefined
786
+ ? undefined
787
+ : yield* Schema.encodeEffect(Schema.fromJsonString(InputMessage))(
788
+ request.messageAdmission,
789
+ ).pipe(
790
+ Effect.mapError(() => ledgerError('admit', 'Invalid message admission metadata')),
791
+ )
792
+
793
+ yield* journal
794
+ .checkThreadCapacity(request.threadId)
795
+ .pipe(Effect.mapError((cause) => ledgerError('admit', cause.message, cause)))
796
+ const nowMillis = yield* Clock.currentTimeMillis
797
+ const retained = yield* Ref.get(state)
798
+
799
+ const identity = retained.admissionIndex.has(
800
+ admissionKey(request.threadId, request.principal, request.idempotencyKey),
801
+ )
802
+ ? Result.fail(ledgerError('admit', 'Retained admission disappeared'))
803
+ : yield* Effect.result(mintIdentity('admit'))
804
+
805
+ const services = yield* Effect.context<never>()
806
+
807
+ const decision = yield* Ref.modify(
808
+ state,
809
+ (
810
+ current,
811
+ ): readonly [
812
+ (
813
+ | Decision<AdmissionResult, AdmissionConflict | AdmissionPolicyError | LedgerError>
814
+ | { readonly _tag: 'cause'; readonly cause: Cause.Cause<AdmissionPolicyError> }
815
+ ),
816
+ LedgerState,
817
+ ] => {
818
+ const key = admissionKey(request.threadId, request.principal, request.idempotencyKey)
819
+ const existingId = current.admissionIndex.get(key)
820
+
821
+ if (existingId !== undefined) {
822
+ const existing = current.submissions.get(existingId)
823
+
824
+ if (existing === undefined) {
825
+ return [
826
+ failure(ledgerError('admit', 'Admission index references a missing Submission')),
827
+ current,
828
+ ]
829
+ }
830
+ // A replay must repeat the exact canonical input AND the exact parent linkage
831
+ // (or its absence): linkage is immutable lineage (spec §12 step 5, SUB-016).
832
+ if (
833
+ existing.row.inputDigest !== request.inputDigest ||
834
+ !sameParentLinkage(existing.row.parentLinkage, request.parentLinkage) ||
835
+ existing.row.admissionGroup !== request.admissionGroup ||
836
+ !Schema.toEquivalence(Schema.optional(WorkerAdmission))(
837
+ existing.row.workerAdmissionJson === undefined
838
+ ? undefined
839
+ : Schema.decodeSync(Schema.fromJsonString(WorkerAdmission))(
840
+ existing.row.workerAdmissionJson,
841
+ ),
842
+ request.workerAdmission,
843
+ ) ||
844
+ !Schema.toEquivalence(Schema.optional(InputMessage))(
845
+ existing.row.messageAdmissionJson === undefined
846
+ ? undefined
847
+ : Schema.decodeSync(Schema.fromJsonString(InputMessage))(
848
+ existing.row.messageAdmissionJson,
849
+ ),
850
+ request.messageAdmission,
851
+ ) ||
852
+ !Schema.toEquivalence(Schema.optional(Schema.Json))(
853
+ existing.row.admissionFence,
854
+ request.admissionFence,
855
+ )
856
+ ) {
857
+ return [
858
+ failure(
859
+ AdmissionConflict.make({
860
+ threadId: request.threadId,
861
+ principal: request.principal,
862
+ idempotencyKey: request.idempotencyKey,
863
+ existingInputDigest: existing.row.inputDigest,
864
+ attemptedInputDigest: request.inputDigest,
865
+ }),
866
+ ),
867
+ current,
868
+ ]
869
+ }
870
+
871
+ return [
872
+ success(
873
+ AdmissionResult.make({
874
+ submissionId: existing.row.submissionId,
875
+ receiptId: existing.row.receiptId,
876
+ queueSequence: existing.row.queueSequence,
877
+ state: existing.row.state,
878
+ replayed: true,
879
+ }),
880
+ ),
881
+ current,
882
+ ]
883
+ }
884
+
885
+ if (current.stoppedWorkers.has(request.threadId)) {
886
+ return [
887
+ failure(AdmissionPolicyError.make({ reason: 'refused', code: 'worker-stopped' })),
888
+ current,
889
+ ]
890
+ }
891
+
892
+ // A Thread's first admission fixes its worker origin before canonical materialization.
893
+ const first = threadRows(current, request.threadId).next().value
894
+
895
+ if (first !== undefined) {
896
+ const previous = first.row.workerAdmissionJson === undefined
897
+ ? undefined
898
+ : Schema.decodeSync(Schema.fromJsonString(WorkerAdmission))(
899
+ first.row.workerAdmissionJson,
900
+ )
901
+
902
+ if (
903
+ !Schema.toEquivalence(Schema.optional(WorkerAdmission.fields.origin))(
904
+ previous?.origin,
905
+ request.workerAdmission?.origin,
906
+ )
907
+ ) {
908
+ return [
909
+ failure(
910
+ AdmissionPolicyError.make({
911
+ reason: 'refused',
912
+ code: 'worker-origin-conflict',
913
+ }),
914
+ ),
915
+ current,
916
+ ]
917
+ }
918
+ }
919
+ // A memory policy and the ledger mutation share one synchronous critical section.
920
+ // An asynchronous policy cannot fence this Ref and therefore fails closed.
921
+ const checked = Effect.runSyncExitWith(services)(admissionFence.check(request))
922
+
923
+ if (Exit.isFailure(checked)) {
924
+ return [{ _tag: 'cause', cause: checked.cause }, current]
925
+ }
926
+ if (
927
+ request.admissionGroup !== undefined &&
928
+ Array.from(current.activeByThread.get(request.threadId) ?? []).some(
929
+ (id) => current.submissions.get(id)?.row.admissionGroup === request.admissionGroup,
930
+ )
931
+ ) {
932
+ return [
933
+ failure(AdmissionPolicyError.make({ reason: 'occupied', code: 'admission-group' })),
934
+ current,
935
+ ]
936
+ }
937
+
938
+ // A concurrent matching acceptance still wins over a failed fresh allocation.
939
+ if (Result.isFailure(identity)) return [failure(identity.failure), current]
940
+
941
+ const lane = current.lanes.get(request.threadId) ?? {
942
+ nextQueueSequence: 1,
943
+ }
944
+
945
+ const freshAdmissionSequence = current.freshAdmissionSequence + 1
946
+
947
+ if (!Number.isSafeInteger(freshAdmissionSequence)) {
948
+ return [
949
+ failure(ledgerError('admit', 'Fresh admission sequence is exhausted')),
950
+ current,
951
+ ]
952
+ }
953
+
954
+ // Native work scans compare Submission identities lexically.
955
+ const orderedIdentity = `${String(freshAdmissionSequence).padStart(16, '0')}-${identity.success}`
956
+ const submissionId = decodeSubmissionId(`submission-memory-${orderedIdentity}`)
957
+ const receiptId = decodeReceiptId(`receipt-memory-${orderedIdentity}`)
958
+
959
+ if (current.submissions.has(submissionId) || current.receipts.has(receiptId)) {
960
+ return [
961
+ failure(ledgerError('admit', 'Fresh admission identity already exists')),
962
+ current,
963
+ ]
964
+ }
965
+
966
+ const row: SubmissionRow = {
967
+ submissionId,
968
+ threadId: request.threadId,
969
+ queueSequence: decodeQueueSequence(lane.nextQueueSequence),
970
+ principal: request.principal,
971
+ idempotencyKey: request.idempotencyKey,
972
+ agentId: request.agentId,
973
+ agentDigests: request.agentDigests,
974
+ deploymentId: request.deploymentId,
975
+ inputPayload: request.inputPayload,
976
+ inputDigest: request.inputDigest,
977
+ receiptId,
978
+ state: 'admitted',
979
+ settledOutcome: undefined,
980
+ createdAtMillis: nowMillis,
981
+ readyAtMillis: undefined,
982
+ parentLinkage: request.parentLinkage,
983
+ ...(workerAdmissionJson === undefined ? {} : { workerAdmissionJson }),
984
+ ...(messageAdmissionJson === undefined ? {} : { messageAdmissionJson }),
985
+ ...(request.admissionGroup === undefined
986
+ ? {}
987
+ : { admissionGroup: request.admissionGroup }),
988
+ ...(request.admissionFence === undefined
989
+ ? {}
990
+ : { admissionFence: request.admissionFence }),
991
+ }
992
+
993
+ const stored: StoredSubmission = {
994
+ row,
995
+ inputApplied: undefined,
996
+ finalization: undefined,
997
+ abortIntent: undefined,
998
+ joinedHostSubmissionId: undefined,
999
+ suspension: undefined,
1000
+ unknownMark: undefined,
1001
+ approvalDecisions: new Map<ToolCallId, ApprovalDecisionIntent>(),
1002
+ unknownResolutions: new Map<string, StoredUnknownResolution>(),
1003
+ }
1004
+
1005
+ if (!admissionFitsTransfer(request.threadId, toAdmission(row))) {
1006
+ return [failure(transferCapacityError('admit')), current]
1007
+ }
1008
+
1009
+ journal.initializeWork(request.threadId)
1010
+ const admissionIndex = current.admissionIndex
1011
+
1012
+ const lanes = current.lanes.set(request.threadId, {
1013
+ nextQueueSequence: lane.nextQueueSequence + 1,
1014
+ })
1015
+
1016
+ return [
1017
+ success(
1018
+ AdmissionResult.make({
1019
+ submissionId: row.submissionId,
1020
+ receiptId: row.receiptId,
1021
+ queueSequence: row.queueSequence,
1022
+ state: row.state,
1023
+ replayed: false,
1024
+ }),
1025
+ ),
1026
+ {
1027
+ ...withSubmission(current, stored),
1028
+ admissionIndex,
1029
+ lanes,
1030
+ freshAdmissionSequence,
1031
+ },
1032
+ ]
1033
+ },
1034
+ )
1035
+
1036
+ if (decision._tag === 'failure') return yield* decision.error
1037
+ if (decision._tag === 'cause') {
1038
+ for (const reason of decision.cause.reasons) {
1039
+ if (Cause.isDieReason(reason) && Cause.isAsyncFiberError(reason.defect)) {
1040
+ yield* Fiber.interrupt(reason.defect.fiber)
1041
+
1042
+ return yield* AdmissionPolicyError.make({
1043
+ reason: 'unavailable',
1044
+ code: 'synchronous-memory-policy-required',
1045
+ })
1046
+ }
1047
+ }
1048
+
1049
+ return yield* Effect.failCause(decision.cause)
1050
+ }
1051
+
1052
+ return decision.value
1053
+ }, Effect.uninterruptible)
1054
+
1055
+ const markReady: SubmissionLedger['Service']['markReady'] = Effect.fnUntraced(
1056
+ function*(unvalidated) {
1057
+ const request = yield* validate(MarkReadyRequest, 'markReady', unvalidated)
1058
+ const nowMillis = yield* Clock.currentTimeMillis
1059
+
1060
+ const decision = yield* Ref.modify(
1061
+ state,
1062
+ (current): readonly [Decision<void, LedgerError>, LedgerState] => {
1063
+ const stored = current.submissions.get(request.submissionId)
1064
+
1065
+ if (stored === undefined) {
1066
+ return [
1067
+ failure(ledgerError('markReady', `Unknown Submission ${request.submissionId}`)),
1068
+ current,
1069
+ ]
1070
+ }
1071
+ if (stored.row.state !== 'admitted') return [success(undefined), current]
1072
+
1073
+ return [
1074
+ success(undefined),
1075
+ withSubmission(current, {
1076
+ ...stored,
1077
+ row: { ...stored.row, state: 'ready', readyAtMillis: nowMillis },
1078
+ }),
1079
+ ]
1080
+ },
1081
+ )
1082
+
1083
+ if (decision._tag === 'failure') return yield* decision.error
1084
+ },
1085
+ )
1086
+
1087
+ const lookup: SubmissionLedger['Service']['lookup'] = Effect.fnUntraced(
1088
+ function*(unvalidated) {
1089
+ const request = yield* validate(SubmissionLookup, 'lookup', unvalidated)
1090
+ const current = yield* Ref.get(state)
1091
+
1092
+ const submissionId = request._tag === 'SubmissionLookupById'
1093
+ ? request.submissionId
1094
+ : current.admissionIndex.get(
1095
+ admissionKey(request.threadId, request.principal, request.idempotencyKey),
1096
+ )
1097
+
1098
+ const stored = submissionId === undefined ? undefined : current.submissions.get(submissionId)
1099
+
1100
+ return stored === undefined ? Option.none() : Option.some(toSnapshot(stored.row))
1101
+ },
1102
+ )
1103
+
1104
+ const resolveAdmission: SubmissionLedger['Service']['resolveAdmission'] = Effect.fnUntraced(
1105
+ function*(unvalidated) {
1106
+ const request = yield* validate(SubmissionLookupByKey, 'resolveAdmission', unvalidated)
1107
+
1108
+ // Test-only fault seam: lets suites exercise the Indeterminate classification that a
1109
+ // single strongly consistent store never produces on its own (SUB-031, P6 honesty).
1110
+ if (options.resolveAdmissionFault !== undefined) {
1111
+ const fault = yield* options.resolveAdmissionFault
1112
+
1113
+ if (Option.isSome(fault)) {
1114
+ return AdmissionIndeterminate.make({ reason: fault.value })
1115
+ }
1116
+ }
1117
+ const current = yield* Ref.get(state)
1118
+
1119
+ const submissionId = current.admissionIndex.get(
1120
+ admissionKey(request.threadId, request.principal, request.idempotencyKey),
1121
+ )
1122
+
1123
+ const stored = submissionId === undefined ? undefined : current.submissions.get(submissionId)
1124
+
1125
+ return stored === undefined
1126
+ ? AdmissionNotAdmitted.make()
1127
+ : AdmissionAdmitted.make({ submission: toSnapshot(stored.row) })
1128
+ },
1129
+ )
1130
+
1131
+ const selectHead: SubmissionLedger['Service']['selectHead'] = Effect.fn(
1132
+ 'MemorySubmissionLedger.selectHead',
1133
+ )((unvalidated) =>
1134
+ Effect.gen(function*() {
1135
+ const request = yield* validate(ClaimRequest, 'claim', unvalidated)
1136
+ const identity = yield* mintIdentity('claim')
1137
+
1138
+ const decision = yield* Ref.modify(
1139
+ state,
1140
+ (current): readonly [Decision<Option.Option<Claim>, LedgerError>, LedgerState] => {
1141
+ if (journal.owner.hasOwner(request.threadId)) return [success(Option.none()), current]
1142
+ let head = findHead(current, request.threadId)
1143
+
1144
+ if (request.handoff !== undefined) {
1145
+ const handoff = request.handoff
1146
+
1147
+ const candidates = Array.from(
1148
+ current.activeByThread.get(request.threadId) ?? [],
1149
+ (id) => current.submissions.get(id),
1150
+ )
1151
+ .filter(
1152
+ (entry): entry is StoredSubmission =>
1153
+ entry !== undefined &&
1154
+ !(entry.row.state === 'unknown' && entry.abortIntent === undefined),
1155
+ )
1156
+ .sort((a, b) => a.row.queueSequence - b.row.queueSequence)
1157
+
1158
+ for (const candidate of candidates) {
1159
+ if (candidate.row.submissionId === handoff.submissionId) {
1160
+ head = candidate
1161
+ break
1162
+ }
1163
+ if (
1164
+ !handoff.deferredSubmissionIds.includes(candidate.row.submissionId) ||
1165
+ candidate.row.state !== 'input-applied' ||
1166
+ candidate.abortIntent !== undefined
1167
+ ) {
1168
+ return [success(Option.none()), current]
1169
+ }
1170
+ }
1171
+ if (
1172
+ head?.row.submissionId !== handoff.submissionId ||
1173
+ (head.row.state !== 'ready' && head.row.state !== 'input-applied')
1174
+ ) {
1175
+ return [success(Option.none()), current]
1176
+ }
1177
+ }
1178
+
1179
+ if (head === undefined) return [success(Option.none()), current]
1180
+ if (BLOCKED_HEAD_STATES.has(head.row.state)) return [success(Option.none()), current]
1181
+
1182
+ return [
1183
+ success(
1184
+ Option.some(
1185
+ Claim.make({
1186
+ submissionId: head.row.submissionId,
1187
+ attemptId: decodeAttemptId(`attempt-memory-${identity}`),
1188
+ inputPayload: head.row.inputPayload,
1189
+ }),
1190
+ ),
1191
+ ),
1192
+ current,
1193
+ ]
1194
+ },
1195
+ )
1196
+
1197
+ if (decision._tag === 'failure') return yield* decision.error
1198
+
1199
+ return decision.value
1200
+ })
1201
+ )
1202
+
1203
+ const markInputApplied: SubmissionLedger['Service']['markInputApplied'] = Effect.fnUntraced(
1204
+ function*(unvalidated) {
1205
+ const request = yield* validate(MarkInputAppliedRequest, 'markInputApplied', unvalidated)
1206
+
1207
+ const decision = yield* Ref.modify(
1208
+ state,
1209
+ (current): readonly [Decision<void, OwnershipLost | LedgerError>, LedgerState] => {
1210
+ const stored = current.submissions.get(request.submissionId)
1211
+
1212
+ if (stored === undefined) {
1213
+ return [
1214
+ failure(
1215
+ ledgerError('markInputApplied', `Unknown Submission ${request.submissionId}`),
1216
+ ),
1217
+ current,
1218
+ ]
1219
+ }
1220
+ if (!journal.owner.hasOwner(stored.row.threadId, stored.row.submissionId)) {
1221
+ return [failure(ownershipLost(stored)), current]
1222
+ }
1223
+
1224
+ if (stored.inputApplied !== undefined) {
1225
+ if (
1226
+ stored.inputApplied.recordId === request.recordId &&
1227
+ stored.inputApplied.sequence === request.sequence
1228
+ ) {
1229
+ return [success(undefined), current]
1230
+ }
1231
+
1232
+ return [
1233
+ failure(
1234
+ ledgerError(
1235
+ 'markInputApplied',
1236
+ `A different canonical input marker is already recorded for Submission ${request.submissionId}`,
1237
+ ),
1238
+ ),
1239
+ current,
1240
+ ]
1241
+ }
1242
+
1243
+ const marker = InputAppliedMarker.make({
1244
+ recordId: request.recordId,
1245
+ sequence: request.sequence,
1246
+ })
1247
+
1248
+ const row: SubmissionRow = STATE_RANK[stored.row.state] < STATE_RANK['input-applied']
1249
+ ? { ...stored.row, state: 'input-applied' }
1250
+ : stored.row
1251
+
1252
+ return [
1253
+ success(undefined),
1254
+ withSubmission(current, { ...stored, row, inputApplied: marker }),
1255
+ ]
1256
+ },
1257
+ )
1258
+
1259
+ if (decision._tag === 'failure') return yield* decision.error
1260
+ },
1261
+ )
1262
+
1263
+ const canonicalSettlement = Effect.fnUntraced(function*(submission: SubmissionRow) {
1264
+ const record = yield* journal.record(
1265
+ submission.threadId,
1266
+ submissionSettlementRecordId(submission.submissionId),
1267
+ )
1268
+
1269
+ if (record === undefined) return undefined
1270
+ const settlement = yield* validateCanonicalSettlement(record, submission)
1271
+
1272
+ return { record, settlement }
1273
+ })
1274
+
1275
+ const publish: SettlementPublisher['Service']['publish'] = Effect.fn(
1276
+ 'MemorySettlementPublisher.publish',
1277
+ )(function*(input) {
1278
+ const { request, record, settlement } = yield* validatePublication(input)
1279
+ const prepared = yield* journal.prepareAppend(request.append)
1280
+
1281
+ return yield* journal.owner.withProgress(
1282
+ request.append.threadId,
1283
+ journal.withMutation(
1284
+ Effect.gen(function*() {
1285
+ const current = yield* Ref.get(state)
1286
+ const stored = current.submissions.get(request.submissionId)
1287
+
1288
+ if (stored === undefined) {
1289
+ return yield* ledgerError('publish settlement', 'Unknown Submission')
1290
+ }
1291
+ if (stored.row.threadId !== prepared.request.threadId) {
1292
+ return yield* ledgerError('publish settlement', 'Publication targets another Thread')
1293
+ }
1294
+ yield* validateCanonicalSettlement(record, stored.row)
1295
+ const existing = yield* canonicalSettlement(stored.row)
1296
+ const tail = yield* journal.tail(stored.row.threadId)
1297
+
1298
+ // Replay still requires authority: finalization releases Owned tokens, while
1299
+ // retained host linkage or abort intent can authorize tokenless settled replay.
1300
+ switch (request.authority._tag) {
1301
+ case 'Owned':
1302
+ if (!journal.owner.hasOwner(stored.row.threadId, stored.row.submissionId)) {
1303
+ return yield* ownershipLost(stored)
1304
+ }
1305
+ yield* validateCanonicalSettlement(record, {
1306
+ submissionId: request.submissionId,
1307
+ receiptId: stored.row.receiptId,
1308
+ ...(settlement.outcome === 'aborted' && settlement.runId === undefined
1309
+ ? {}
1310
+ : { runId: runIdForSubmission(request.submissionId) }),
1311
+ })
1312
+ break
1313
+ case 'Joined': {
1314
+ if (
1315
+ (stored.row.state !== 'joined' &&
1316
+ !(stored.row.state === 'settled' && existing !== undefined)) ||
1317
+ stored.joinedHostSubmissionId !== request.authority.hostSubmissionId
1318
+ ) {
1319
+ return yield* ledgerError(
1320
+ 'publish settlement',
1321
+ 'Submission is not joined to this host',
1322
+ )
1323
+ }
1324
+ const host = current.submissions.get(request.authority.hostSubmissionId)
1325
+
1326
+ const canonicalHost = host === undefined || host.row.threadId !== stored.row.threadId
1327
+ ? undefined
1328
+ : yield* canonicalSettlement(host.row)
1329
+
1330
+ if (canonicalHost === undefined) {
1331
+ return yield* ledgerError(
1332
+ 'publish settlement',
1333
+ 'Joined host has no canonical settlement',
1334
+ )
1335
+ }
1336
+ yield* validateJoinedSettlement(settlement, canonicalHost.settlement)
1337
+ break
1338
+ }
1339
+ case 'QueuedAbort':
1340
+ if (
1341
+ (stored.row.state !== 'ready' &&
1342
+ !(stored.row.state === 'settled' && existing !== undefined)) ||
1343
+ stored.abortIntent === undefined ||
1344
+ journal.owner.hasOwner(stored.row.threadId, stored.row.submissionId) ||
1345
+ settlement.outcome !== 'aborted'
1346
+ ) {
1347
+ return yield* ledgerError(
1348
+ 'publish settlement',
1349
+ 'Submission is not an unclaimed queued abort',
1350
+ )
1351
+ }
1352
+ yield* validateCanonicalSettlement(record, {
1353
+ submissionId: request.submissionId,
1354
+ receiptId: stored.row.receiptId,
1355
+ runId: undefined,
1356
+ })
1357
+ break
1358
+ }
1359
+ if (existing !== undefined) {
1360
+ return SettlementPublicationResult.make({
1361
+ record: existing.record,
1362
+ tailSequence: tail.tailSequence,
1363
+ replayed: true,
1364
+ })
1365
+ }
1366
+ if (stored.row.state === 'settled') {
1367
+ return yield* ledgerError(
1368
+ 'publish settlement',
1369
+ 'Finalized Submission has no canonical settlement',
1370
+ )
1371
+ }
1372
+ const appended = yield* journal.appendPrepared(prepared)
1373
+
1374
+ return SettlementPublicationResult.make({
1375
+ record,
1376
+ tailSequence: appended.lastSequence,
1377
+ replayed: false,
1378
+ })
1379
+ }),
1380
+ ),
1381
+ )
1382
+ })
1383
+
1384
+ const finalizeSettlement: SubmissionLedger['Service']['finalizeSettlement'] = Effect.fn(
1385
+ 'MemorySubmissionLedger.finalizeSettlement',
1386
+ )((unvalidated) =>
1387
+ Effect.gen(function*() {
1388
+ const request = yield* validate(SettlementFinalization, 'finalizeSettlement', unvalidated)
1389
+ const before = (yield* Ref.get(state)).submissions.get(request.submissionId)
1390
+ const canonical = before === undefined ? undefined : yield* canonicalSettlement(before.row)
1391
+
1392
+ if (canonical === undefined) {
1393
+ return yield* ledgerError('finalizeSettlement', 'Submission has no canonical settlement')
1394
+ }
1395
+ const { record, settlement } = canonical
1396
+ const nowMillis = yield* Clock.currentTimeMillis
1397
+
1398
+ const decision = yield* Ref.modify(
1399
+ state,
1400
+ (
1401
+ current,
1402
+ ): readonly [Decision<Settlement, SettlementConflict | LedgerError>, LedgerState] => {
1403
+ const stored = current.submissions.get(request.submissionId)
1404
+
1405
+ if (stored === undefined) {
1406
+ return [
1407
+ failure(
1408
+ ledgerError('finalizeSettlement', `Unknown Submission ${request.submissionId}`),
1409
+ ),
1410
+ current,
1411
+ ]
1412
+ }
1413
+ const settlementFailure = settlementFailureFromRecord(record)
1414
+
1415
+ if (settlement.settlementId !== request.settlementId) {
1416
+ return [
1417
+ failure(
1418
+ SettlementConflict.make({
1419
+ submissionId: request.submissionId,
1420
+ existingOutcome: settlement.outcome,
1421
+ }),
1422
+ ),
1423
+ current,
1424
+ ]
1425
+ }
1426
+ if (stored.finalization !== undefined) {
1427
+ if (
1428
+ stored.row.state !== 'settled' ||
1429
+ stored.row.settledOutcome !== settlement.outcome ||
1430
+ stored.finalization.settlementId !== request.settlementId ||
1431
+ stored.finalization.recordId !== record.recordId
1432
+ ) {
1433
+ return [
1434
+ failure(
1435
+ ledgerError(
1436
+ 'finalizeSettlement',
1437
+ 'Finalized identity disagrees with canonical settlement',
1438
+ ),
1439
+ ),
1440
+ current,
1441
+ ]
1442
+ }
1443
+
1444
+ return [
1445
+ success(
1446
+ Settlement.make({
1447
+ submissionId: stored.row.submissionId,
1448
+ settlementId: settlement.settlementId,
1449
+ receiptId: stored.row.receiptId,
1450
+ outcome: settlement.outcome,
1451
+ ...(settlementFailure === undefined ? {} : { failure: settlementFailure }),
1452
+ settledAt: utc(stored.finalization.finalizedAtMillis),
1453
+ }),
1454
+ ),
1455
+ current,
1456
+ ]
1457
+ }
1458
+ if (stored.row.state === 'settled') {
1459
+ return [
1460
+ failure(ledgerError('finalizeSettlement', 'Finalized timestamp is missing')),
1461
+ current,
1462
+ ]
1463
+ }
1464
+
1465
+ const terminal = stored.row.workerAdmissionJson === undefined
1466
+ ? undefined
1467
+ : workerTerminalFromRecord(toSnapshot(stored.row), record)
1468
+
1469
+ const latestId = current.latestByThread.get(stored.row.threadId)
1470
+ const latest = latestId === undefined ? undefined : current.submissions.get(latestId)
1471
+
1472
+ const pendingNewer = terminal === 'completed' &&
1473
+ latest !== undefined &&
1474
+ latest.row.queueSequence > stored.row.queueSequence &&
1475
+ !(
1476
+ latest.joinedHostSubmissionId === stored.row.submissionId &&
1477
+ latest.inputApplied !== undefined
1478
+ )
1479
+
1480
+ let sealed = current
1481
+
1482
+ if (
1483
+ terminal !== undefined &&
1484
+ !pendingNewer &&
1485
+ !current.stoppedWorkers.has(stored.row.threadId)
1486
+ ) {
1487
+ const submissions = current.submissions
1488
+
1489
+ if (!transferPageFits(stored.row.threadId)) {
1490
+ return [failure(transferCapacityError('finalizeSettlement')), current]
1491
+ }
1492
+
1493
+ // Validate every fresh fact before mutating, without retaining a second active set.
1494
+ for (const apply of [false, true]) {
1495
+ for (const id of current.activeByThread.get(stored.row.threadId) ?? []) {
1496
+ const other = submissions.get(id)
1497
+
1498
+ if (other === undefined) continue
1499
+ if (
1500
+ id !== stored.row.submissionId &&
1501
+ !(
1502
+ other.joinedHostSubmissionId === stored.row.submissionId &&
1503
+ other.inputApplied !== undefined
1504
+ ) &&
1505
+ other.abortIntent === undefined
1506
+ ) {
1507
+ const abortIntent = AbortIntent.make({
1508
+ submissionId: id,
1509
+ author: stored.row.principal,
1510
+ reason: `Worker assignment ${terminal}`,
1511
+ requestedAt: utc(nowMillis),
1512
+ })
1513
+
1514
+ if (!apply && !abortFitsTransfer(other.row.threadId, abortIntent)) {
1515
+ return [failure(transferCapacityError('finalizeSettlement')), current]
1516
+ }
1517
+ if (apply) {
1518
+ withSubmission(current, {
1519
+ ...other,
1520
+ abortIntent,
1521
+ })
1522
+ }
1523
+ }
1524
+ }
1525
+ }
1526
+ sealed = {
1527
+ ...current,
1528
+ submissions,
1529
+ stoppedWorkers: current.stoppedWorkers.set(stored.row.threadId, terminal),
1530
+ }
1531
+ }
1532
+
1533
+ const next = withSubmission(sealed, {
1534
+ ...stored,
1535
+ row: { ...stored.row, state: 'settled', settledOutcome: settlement.outcome },
1536
+ finalization: {
1537
+ settlementId: settlement.settlementId,
1538
+ recordId: record.recordId,
1539
+ finalizedAtMillis: nowMillis,
1540
+ },
1541
+ })
1542
+
1543
+ return [
1544
+ success(
1545
+ Settlement.make({
1546
+ submissionId: stored.row.submissionId,
1547
+ settlementId: settlement.settlementId,
1548
+ receiptId: stored.row.receiptId,
1549
+ outcome: settlement.outcome,
1550
+ ...(settlementFailure === undefined ? {} : { failure: settlementFailure }),
1551
+ settledAt: utc(nowMillis),
1552
+ }),
1553
+ ),
1554
+ next,
1555
+ ]
1556
+ },
1557
+ )
1558
+
1559
+ if (decision._tag === 'failure') return yield* decision.error
1560
+
1561
+ if (before !== undefined) {
1562
+ journal.owner.closeSubmission(before.row.threadId, request.submissionId)
1563
+ }
1564
+
1565
+ return decision.value
1566
+ })
1567
+ )
1568
+
1569
+ const inspectWorker = Effect.fnUntraced(function*(threadId: ThreadId) {
1570
+ const current = yield* Ref.get(state)
1571
+ const latestId = current.latestByThread.get(threadId)
1572
+ const latest = latestId === undefined ? undefined : current.submissions.get(latestId)
1573
+
1574
+ const active = [...(current.activeByThread.get(threadId) ?? [])]
1575
+ .flatMap((id) => {
1576
+ const row = current.submissions.get(id)
1577
+
1578
+ return row === undefined ? [] : [row]
1579
+ })
1580
+ .sort((a, b) => a.row.queueSequence - b.row.queueSequence)[0]
1581
+
1582
+ const terminal = current.stoppedWorkers.get(threadId)
1583
+
1584
+ return WorkerLedgerState.make({
1585
+ latest: latest === undefined ? null : toSnapshot(latest.row),
1586
+ active: active === undefined ? null : toSnapshot(active.row),
1587
+ stopped: current.stoppedWorkers.has(threadId),
1588
+ ...(terminal === undefined ? {} : { terminal }),
1589
+ })
1590
+ })
1591
+
1592
+ const stopWorker = Effect.fnUntraced(function*(unvalidated: WorkerStopCommand) {
1593
+ const request = yield* validate(WorkerStopCommand, 'stopWorker', unvalidated)
1594
+ const now = yield* Clock.currentTimeMillis
1595
+
1596
+ const decision = yield* Ref.modify(
1597
+ state,
1598
+ (current): readonly [Decision<number, LedgerError>, LedgerState] => {
1599
+ const submissions = current.submissions
1600
+ let owned = 0
1601
+
1602
+ if (!current.stoppedWorkers.has(request.threadId) && !transferPageFits(request.threadId)) {
1603
+ return [failure(transferCapacityError('stopWorker')), current]
1604
+ }
1605
+
1606
+ // Both passes run in this Ref.modify; no mutation precedes complete validation.
1607
+ for (const apply of [false, true]) {
1608
+ for (const id of current.activeByThread.get(request.threadId) ?? []) {
1609
+ const stored = submissions.get(id)
1610
+
1611
+ if (stored === undefined) continue
1612
+ if (!apply && journal.owner.hasOwner(stored.row.threadId, stored.row.submissionId)) {
1613
+ owned++
1614
+ }
1615
+ if (stored.abortIntent === undefined) {
1616
+ const abortIntent = AbortIntent.make({
1617
+ submissionId: id,
1618
+ author: request.author,
1619
+ reason: 'Worker owner stopped the worker',
1620
+ requestedAt: utc(now),
1621
+ })
1622
+
1623
+ if (!apply && !abortFitsTransfer(stored.row.threadId, abortIntent)) {
1624
+ return [failure(transferCapacityError('stopWorker')), current]
1625
+ }
1626
+ if (apply) withSubmission(current, { ...stored, abortIntent })
1627
+ }
1628
+ }
1629
+ }
1630
+
1631
+ return [
1632
+ success(owned),
1633
+ {
1634
+ ...current,
1635
+ submissions,
1636
+ stoppedWorkers: current.stoppedWorkers.has(request.threadId)
1637
+ ? current.stoppedWorkers
1638
+ : current.stoppedWorkers.set(request.threadId, undefined),
1639
+ },
1640
+ ] as const
1641
+ },
1642
+ )
1643
+
1644
+ if (decision._tag === 'failure') return yield* decision.error
1645
+
1646
+ return decision.value
1647
+ })
1648
+
1649
+ const requestAbort: SubmissionLedger['Service']['requestAbort'] = Effect.fnUntraced(
1650
+ function*(unvalidated) {
1651
+ const request = yield* validate(AbortCommand, 'requestAbort', unvalidated)
1652
+ const nowMillis = yield* Clock.currentTimeMillis
1653
+
1654
+ const decision = yield* Ref.modify(
1655
+ state,
1656
+ (
1657
+ current,
1658
+ ): readonly [
1659
+ Decision<AbortIntent, SettlementConflict | JoinedToHost | LedgerError>,
1660
+ LedgerState,
1661
+ ] => {
1662
+ const stored = current.submissions.get(request.submissionId)
1663
+
1664
+ if (stored === undefined) {
1665
+ return [
1666
+ failure(ledgerError('requestAbort', `Unknown Submission ${request.submissionId}`)),
1667
+ current,
1668
+ ]
1669
+ }
1670
+ // A joined Submission settles WITH its host; the abort target is the host (plan
1671
+ // §2.5). A joining Submission still records the intent: it is honored only if the
1672
+ // host has not consumed the input (revert-then-abort).
1673
+ if (stored.row.state === 'joined') {
1674
+ if (stored.joinedHostSubmissionId === undefined) {
1675
+ return [
1676
+ failure(
1677
+ ledgerError(
1678
+ 'requestAbort',
1679
+ `Joined Submission ${request.submissionId} is missing its host linkage`,
1680
+ ),
1681
+ ),
1682
+ current,
1683
+ ]
1684
+ }
1685
+
1686
+ return [
1687
+ failure(
1688
+ JoinedToHost.make({
1689
+ submissionId: request.submissionId,
1690
+ hostSubmissionId: stored.joinedHostSubmissionId,
1691
+ }),
1692
+ ),
1693
+ current,
1694
+ ]
1695
+ }
1696
+ if (stored.row.state === 'settled') {
1697
+ if (stored.row.settledOutcome === undefined) {
1698
+ return [
1699
+ failure(
1700
+ ledgerError(
1701
+ 'requestAbort',
1702
+ `Settled Submission ${request.submissionId} is missing its outcome`,
1703
+ ),
1704
+ ),
1705
+ current,
1706
+ ]
1707
+ }
1708
+
1709
+ return [
1710
+ failure(
1711
+ SettlementConflict.make({
1712
+ submissionId: request.submissionId,
1713
+ existingOutcome: stored.row.settledOutcome,
1714
+ }),
1715
+ ),
1716
+ current,
1717
+ ]
1718
+ }
1719
+ if (stored.abortIntent !== undefined) return [success(stored.abortIntent), current]
1720
+
1721
+ const intent = AbortIntent.make({
1722
+ submissionId: request.submissionId,
1723
+ author: request.author,
1724
+ reason: request.reason,
1725
+ requestedAt: utc(nowMillis),
1726
+ })
1727
+
1728
+ if (!abortFitsTransfer(stored.row.threadId, intent)) {
1729
+ return [failure(transferCapacityError('requestAbort')), current]
1730
+ }
1731
+
1732
+ return [success(intent), withSubmission(current, { ...stored, abortIntent: intent })]
1733
+ },
1734
+ )
1735
+
1736
+ if (decision._tag === 'failure') return yield* decision.error
1737
+
1738
+ return decision.value
1739
+ },
1740
+ )
1741
+
1742
+ const claimJoining: SubmissionLedger['Service']['claimJoining'] = Effect.fnUntraced(
1743
+ function*(unvalidated) {
1744
+ const request = yield* validate(ClaimJoiningRequest, 'claimJoining', unvalidated)
1745
+ const published = new Map<SubmissionId, Settlement['outcome']>()
1746
+
1747
+ const before = yield* Ref.get(state)
1748
+
1749
+ for (const id of before.activeByThread.get(request.threadId) ?? []) {
1750
+ const stored = before.submissions.get(id)
1751
+
1752
+ if (stored === undefined || stored.row.state !== 'ready') continue
1753
+ const canonical = yield* canonicalSettlement(stored.row)
1754
+
1755
+ if (canonical !== undefined) {
1756
+ published.set(stored.row.submissionId, canonical.settlement.outcome)
1757
+ }
1758
+ }
1759
+
1760
+ const decision = yield* Ref.modify(
1761
+ state,
1762
+ (
1763
+ current,
1764
+ ): readonly [
1765
+ Decision<ReadonlyArray<JoiningClaim>, OwnershipLost | LedgerError>,
1766
+ LedgerState,
1767
+ ] => {
1768
+ if (current.stoppedWorkers.has(request.threadId)) return [success([]), current]
1769
+
1770
+ const host = current.submissions.get(request.hostSubmissionId)
1771
+
1772
+ if (host === undefined) {
1773
+ return [
1774
+ failure(
1775
+ ledgerError('claimJoining', `Unknown Submission ${request.hostSubmissionId}`),
1776
+ ),
1777
+ current,
1778
+ ]
1779
+ }
1780
+ if (host.row.threadId !== request.threadId) {
1781
+ return [
1782
+ failure(
1783
+ ledgerError(
1784
+ 'claimJoining',
1785
+ `Host Submission ${request.hostSubmissionId} does not belong to Thread ${request.threadId}`,
1786
+ ),
1787
+ ),
1788
+ current,
1789
+ ]
1790
+ }
1791
+ if (!journal.owner.hasOwner(host.row.threadId, host.row.submissionId)) {
1792
+ return [failure(ownershipLost(host)), current]
1793
+ }
1794
+
1795
+ const later = threadRows(current, request.threadId, host.row.queueSequence)
1796
+
1797
+ const claims: Array<JoiningClaim> = []
1798
+ const submissions = current.submissions
1799
+
1800
+ for (const stored of later) {
1801
+ if (claims.length >= request.maxCount) break
1802
+ // Rows already claimed by THIS host extend its contiguous prefix and are skipped;
1803
+ // the coordinator re-delivers already-joined input through the coverage rule.
1804
+ if (
1805
+ (stored.row.state === 'joining' || stored.row.state === 'joined') &&
1806
+ stored.joinedHostSubmissionId === request.hostSubmissionId
1807
+ ) {
1808
+ continue
1809
+ }
1810
+ // P7 §7(c): an aborted-settled row is a CLOSED obligation, not a gap — recovery
1811
+ // settles aborted never-claimed queued work immediately, and settlement order of
1812
+ // never-run work is not execution order (DUR-004 bounds execution).
1813
+ if (stored.row.state === 'settled' && stored.row.settledOutcome === 'aborted') {
1814
+ continue
1815
+ }
1816
+ // Any other non-ready row — an admitted-not-ready gap in particular — breaks the
1817
+ // contiguous ready prefix (plan §2.5); later ready work stays queued (DUR-004).
1818
+ if (stored.row.state !== 'ready') break
1819
+ const terminal = published.get(stored.row.submissionId)
1820
+
1821
+ if (terminal === 'aborted') continue
1822
+ if (terminal !== undefined) break
1823
+ withSubmission(current, {
1824
+ ...stored,
1825
+ row: { ...stored.row, state: 'joining' },
1826
+ joinedHostSubmissionId: request.hostSubmissionId,
1827
+ })
1828
+ claims.push(
1829
+ JoiningClaim.make({
1830
+ submissionId: stored.row.submissionId,
1831
+ queueSequence: stored.row.queueSequence,
1832
+ inputPayload: stored.row.inputPayload,
1833
+ }),
1834
+ )
1835
+ }
1836
+
1837
+ return [success(claims), { ...current, submissions }]
1838
+ },
1839
+ )
1840
+
1841
+ if (decision._tag === 'failure') return yield* decision.error
1842
+
1843
+ return decision.value
1844
+ },
1845
+ )
1846
+
1847
+ const markJoined: SubmissionLedger['Service']['markJoined'] = Effect.fnUntraced(
1848
+ function*(unvalidated) {
1849
+ const request = yield* validate(MarkJoinedRequest, 'markJoined', unvalidated)
1850
+
1851
+ const decision = yield* Ref.modify(
1852
+ state,
1853
+ (current): readonly [Decision<void, OwnershipLost | LedgerError>, LedgerState] => {
1854
+ const stored = current.submissions.get(request.submissionId)
1855
+
1856
+ if (stored === undefined) {
1857
+ return [
1858
+ failure(ledgerError('markJoined', `Unknown Submission ${request.submissionId}`)),
1859
+ current,
1860
+ ]
1861
+ }
1862
+ if (stored.joinedHostSubmissionId === undefined) {
1863
+ return [
1864
+ failure(
1865
+ ledgerError(
1866
+ 'markJoined',
1867
+ `Submission ${request.submissionId} was never claimed for joining`,
1868
+ ),
1869
+ ),
1870
+ current,
1871
+ ]
1872
+ }
1873
+ const host = current.submissions.get(stored.joinedHostSubmissionId)
1874
+
1875
+ if (host === undefined) {
1876
+ return [
1877
+ failure(
1878
+ ledgerError(
1879
+ 'markJoined',
1880
+ `Host Submission ${stored.joinedHostSubmissionId} is missing`,
1881
+ ),
1882
+ ),
1883
+ current,
1884
+ ]
1885
+ }
1886
+ // The lane is host-owned: the presented token must own the HOST's ownership period,
1887
+ // which also lets a later host Attempt repair a lost marker from history (DUR-016).
1888
+ if (!journal.owner.hasOwner(host.row.threadId, host.row.submissionId)) {
1889
+ return [failure(ownershipLost(host)), current]
1890
+ }
1891
+ if (stored.inputApplied !== undefined) {
1892
+ if (
1893
+ stored.inputApplied.recordId === request.recordId &&
1894
+ stored.inputApplied.sequence === request.sequence
1895
+ ) {
1896
+ return [success(undefined), current]
1897
+ }
1898
+
1899
+ return [
1900
+ failure(
1901
+ ledgerError(
1902
+ 'markJoined',
1903
+ `A different join marker is already recorded for Submission ${request.submissionId}`,
1904
+ ),
1905
+ ),
1906
+ current,
1907
+ ]
1908
+ }
1909
+ if (stored.row.state !== 'joining' && stored.row.state !== 'joined') {
1910
+ return [
1911
+ failure(
1912
+ ledgerError(
1913
+ 'markJoined',
1914
+ `Cannot mark Submission ${request.submissionId} joined from state ${stored.row.state}`,
1915
+ ),
1916
+ ),
1917
+ current,
1918
+ ]
1919
+ }
1920
+
1921
+ const marker = InputAppliedMarker.make({
1922
+ recordId: request.recordId,
1923
+ sequence: request.sequence,
1924
+ })
1925
+
1926
+ return [
1927
+ success(undefined),
1928
+ withSubmission(current, {
1929
+ ...stored,
1930
+ row: { ...stored.row, state: 'joined' },
1931
+ inputApplied: marker,
1932
+ }),
1933
+ ]
1934
+ },
1935
+ )
1936
+
1937
+ if (decision._tag === 'failure') return yield* decision.error
1938
+ },
1939
+ )
1940
+
1941
+ const revertJoining: SubmissionLedger['Service']['revertJoining'] = Effect.fnUntraced(
1942
+ function*(unvalidated) {
1943
+ const request = yield* validate(RevertJoiningRequest, 'revertJoining', unvalidated)
1944
+
1945
+ const decision = yield* Ref.modify(
1946
+ state,
1947
+ (current): readonly [Decision<void, LedgerError>, LedgerState] => {
1948
+ const stored = current.submissions.get(request.submissionId)
1949
+
1950
+ if (stored === undefined) {
1951
+ return [
1952
+ failure(ledgerError('revertJoining', `Unknown Submission ${request.submissionId}`)),
1953
+ current,
1954
+ ]
1955
+ }
1956
+ // Idempotent and recovery-only: only a still-`joining` Submission reverts; an
1957
+ // already-joined (or already-reverted) Submission is a no-op (DUR-016).
1958
+ if (stored.row.state !== 'joining') return [success(undefined), current]
1959
+
1960
+ const guard = request.guard
1961
+
1962
+ if (guard !== undefined) {
1963
+ if (stored.joinedHostSubmissionId !== guard.hostSubmissionId) {
1964
+ return [success(undefined), current]
1965
+ }
1966
+ const host = current.submissions.get(guard.hostSubmissionId)
1967
+
1968
+ if (host === undefined || host.row.threadId !== stored.row.threadId) {
1969
+ return [
1970
+ failure(
1971
+ ledgerError(
1972
+ 'revertJoining',
1973
+ `Host Submission ${guard.hostSubmissionId} is missing or belongs to another Thread`,
1974
+ ),
1975
+ ),
1976
+ current,
1977
+ ]
1978
+ }
1979
+ if (
1980
+ host.row.state !== 'settled' &&
1981
+ !journal.owner.hasOwner(host.row.threadId, host.row.submissionId)
1982
+ ) {
1983
+ return [
1984
+ failure(
1985
+ ledgerError('revertJoining', 'The linked host has no active local session'),
1986
+ ),
1987
+ current,
1988
+ ]
1989
+ }
1990
+ }
1991
+
1992
+ return [
1993
+ success(undefined),
1994
+ withSubmission(current, {
1995
+ ...stored,
1996
+ row: { ...stored.row, state: 'ready' },
1997
+ joinedHostSubmissionId: undefined,
1998
+ }),
1999
+ ]
2000
+ },
2001
+ )
2002
+
2003
+ if (decision._tag === 'failure') return yield* decision.error
2004
+ },
2005
+ )
2006
+
2007
+ const suspend: SubmissionLedger['Service']['suspend'] = Effect.fnUntraced(
2008
+ function*(unvalidated) {
2009
+ const request = yield* validate(SuspendRequest, 'suspend', unvalidated)
2010
+ const nowMillis = yield* Clock.currentTimeMillis
2011
+
2012
+ const target = (yield* Ref.get(state)).submissions.get(request.submissionId)
2013
+ const canonical = target === undefined ? undefined : yield* canonicalSettlement(target.row)
2014
+ const announcedChildren = new Set<SubmissionId>()
2015
+
2016
+ if (request.reason._tag === 'WaitingForChild') {
2017
+ const current = yield* Ref.get(state)
2018
+
2019
+ for (const { childSubmissionId } of request.reason.children) {
2020
+ const child = current.submissions.get(childSubmissionId)
2021
+
2022
+ if (child !== undefined && (yield* canonicalSettlement(child.row)) !== undefined) {
2023
+ announcedChildren.add(childSubmissionId)
2024
+ }
2025
+ }
2026
+ }
2027
+
2028
+ const decision = yield* Ref.modify(
2029
+ state,
2030
+ (
2031
+ current,
2032
+ ): readonly [
2033
+ Decision<SuspensionOutcome, OwnershipLost | SettlementConflict | LedgerError>,
2034
+ LedgerState,
2035
+ ] => {
2036
+ const stored = current.submissions.get(request.submissionId)
2037
+
2038
+ if (stored === undefined) {
2039
+ return [
2040
+ failure(ledgerError('suspend', `Unknown Submission ${request.submissionId}`)),
2041
+ current,
2042
+ ]
2043
+ }
2044
+ if (stored.row.state === 'settled') {
2045
+ if (stored.row.settledOutcome === undefined) {
2046
+ return [
2047
+ failure(
2048
+ ledgerError(
2049
+ 'suspend',
2050
+ `Settled Submission ${request.submissionId} is missing its outcome`,
2051
+ ),
2052
+ ),
2053
+ current,
2054
+ ]
2055
+ }
2056
+
2057
+ return [
2058
+ failure(
2059
+ SettlementConflict.make({
2060
+ submissionId: request.submissionId,
2061
+ existingOutcome: stored.row.settledOutcome,
2062
+ }),
2063
+ ),
2064
+ current,
2065
+ ]
2066
+ }
2067
+ // Canonical publication wins over a late parking transition.
2068
+ if (canonical !== undefined) {
2069
+ return [
2070
+ failure(
2071
+ SettlementConflict.make({
2072
+ submissionId: request.submissionId,
2073
+ existingOutcome: canonical.settlement.outcome,
2074
+ }),
2075
+ ),
2076
+ current,
2077
+ ]
2078
+ }
2079
+ if (!journal.owner.hasOwner(stored.row.threadId, stored.row.submissionId)) {
2080
+ return [failure(ownershipLost(stored)), current]
2081
+ }
2082
+
2083
+ // A covering event that raced ahead of the suspend transaction (an approval decision,
2084
+ // or a child settlement observed directly from the child's row in this single store)
2085
+ // resumes the caller immediately WITHOUT releasing the lane (plan §2.6, spec §12).
2086
+ const alreadyCovered = request.reason._tag === 'ApprovalPending'
2087
+ ? approvalDecisionsCover(
2088
+ request.reason.toolCallIds,
2089
+ (toolCallId) => stored.approvalDecisions.get(toolCallId)?.decision,
2090
+ )
2091
+ : request.reason.children.every((child) => announcedChildren.has(child.childSubmissionId))
2092
+
2093
+ if (alreadyCovered) {
2094
+ return [success('resume-immediately' as const), current]
2095
+ }
2096
+
2097
+ return [
2098
+ success('suspended' as const),
2099
+ withSubmission(current, {
2100
+ ...stored,
2101
+ row: { ...stored.row, state: 'suspended' },
2102
+ suspension: { reason: request.reason, suspendedAtMillis: nowMillis },
2103
+ }),
2104
+ ]
2105
+ },
2106
+ )
2107
+
2108
+ if (decision._tag === 'failure') return yield* decision.error
2109
+
2110
+ if (decision.value === 'suspended' && target !== undefined) {
2111
+ journal.owner.closeSubmission(target.row.threadId, request.submissionId)
2112
+ }
2113
+
2114
+ return decision.value
2115
+ },
2116
+ )
2117
+
2118
+ const recordApprovalDecision: SubmissionLedger['Service']['recordApprovalDecision'] = Effect.fnUntraced(
2119
+ function*(unvalidated) {
2120
+ const command = yield* validate(
2121
+ ApprovalDecisionCommand,
2122
+ 'recordApprovalDecision',
2123
+ unvalidated,
2124
+ )
2125
+
2126
+ const nowMillis = yield* Clock.currentTimeMillis
2127
+
2128
+ const decision = yield* Ref.modify(
2129
+ state,
2130
+ (
2131
+ current,
2132
+ ): readonly [
2133
+ Decision<ApprovalDecisionIntent, ApprovalConflict | SettlementConflict | LedgerError>,
2134
+ LedgerState,
2135
+ ] => {
2136
+ const stored = current.submissions.get(command.submissionId)
2137
+
2138
+ if (stored === undefined) {
2139
+ return [
2140
+ failure(
2141
+ ledgerError(
2142
+ 'recordApprovalDecision',
2143
+ `Unknown Submission ${command.submissionId}`,
2144
+ ),
2145
+ ),
2146
+ current,
2147
+ ]
2148
+ }
2149
+ if (stored.row.state === 'settled') {
2150
+ if (stored.row.settledOutcome === undefined) {
2151
+ return [
2152
+ failure(
2153
+ ledgerError(
2154
+ 'recordApprovalDecision',
2155
+ `Settled Submission ${command.submissionId} is missing its outcome`,
2156
+ ),
2157
+ ),
2158
+ current,
2159
+ ]
2160
+ }
2161
+
2162
+ return [
2163
+ failure(
2164
+ SettlementConflict.make({
2165
+ submissionId: command.submissionId,
2166
+ existingOutcome: stored.row.settledOutcome,
2167
+ }),
2168
+ ),
2169
+ current,
2170
+ ]
2171
+ }
2172
+ const existing = stored.approvalDecisions.get(command.toolCallId)
2173
+
2174
+ if (existing !== undefined) {
2175
+ if (existing.decision !== command.decision) {
2176
+ return [
2177
+ failure(
2178
+ ApprovalConflict.make({
2179
+ submissionId: command.submissionId,
2180
+ toolCallId: command.toolCallId,
2181
+ existingDecision: existing.decision,
2182
+ }),
2183
+ ),
2184
+ current,
2185
+ ]
2186
+ }
2187
+
2188
+ return [success(existing), current]
2189
+ }
2190
+
2191
+ const intent = ApprovalDecisionIntent.make({
2192
+ submissionId: command.submissionId,
2193
+ toolCallId: command.toolCallId,
2194
+ decision: command.decision,
2195
+ resolver: command.resolver,
2196
+ reason: command.reason,
2197
+ decidedAt: utc(nowMillis),
2198
+ })
2199
+
2200
+ if (!approvalFitsTransfer(stored.row.threadId, intent)) {
2201
+ return [failure(transferCapacityError('recordApprovalDecision')), current]
2202
+ }
2203
+
2204
+ const approvalDecisions = new Map(stored.approvalDecisions).set(
2205
+ command.toolCallId,
2206
+ intent,
2207
+ )
2208
+
2209
+ // A denial or decisions for every pending call wake an ApprovalPending lane:
2210
+ // suspended → input-applied. A WaitingForChild suspension wakes
2211
+ // only through recordChildSettled.
2212
+ const wakes = stored.row.state === 'suspended' &&
2213
+ stored.suspension !== undefined &&
2214
+ stored.suspension.reason._tag === 'ApprovalPending' &&
2215
+ approvalDecisionsCover(
2216
+ stored.suspension.reason.toolCallIds,
2217
+ (toolCallId) => approvalDecisions.get(toolCallId)?.decision,
2218
+ )
2219
+
2220
+ return [
2221
+ success(intent),
2222
+ withSubmission(current, {
2223
+ ...stored,
2224
+ row: wakes ? { ...stored.row, state: 'input-applied' } : stored.row,
2225
+ suspension: wakes ? undefined : stored.suspension,
2226
+ approvalDecisions,
2227
+ }),
2228
+ ]
2229
+ },
2230
+ )
2231
+
2232
+ if (decision._tag === 'failure') return yield* decision.error
2233
+
2234
+ return decision.value
2235
+ },
2236
+ )
2237
+
2238
+ const markUnknown: SubmissionLedger['Service']['markUnknown'] = Effect.fnUntraced(
2239
+ function*(unvalidated) {
2240
+ const request = yield* validate(MarkUnknownRequest, 'markUnknown', unvalidated)
2241
+
2242
+ const target = (yield* Ref.get(state)).submissions.get(request.submissionId)
2243
+ const canonical = target === undefined ? undefined : yield* canonicalSettlement(target.row)
2244
+
2245
+ const decision = yield* Ref.modify(
2246
+ state,
2247
+ (current): readonly [Decision<void, SettlementConflict | LedgerError>, LedgerState] => {
2248
+ const stored = current.submissions.get(request.submissionId)
2249
+
2250
+ if (stored === undefined) {
2251
+ return [
2252
+ failure(ledgerError('markUnknown', `Unknown Submission ${request.submissionId}`)),
2253
+ current,
2254
+ ]
2255
+ }
2256
+ if (stored.row.state === 'settled') {
2257
+ if (stored.row.settledOutcome === undefined) {
2258
+ return [
2259
+ failure(
2260
+ ledgerError(
2261
+ 'markUnknown',
2262
+ `Settled Submission ${request.submissionId} is missing its outcome`,
2263
+ ),
2264
+ ),
2265
+ current,
2266
+ ]
2267
+ }
2268
+
2269
+ return [
2270
+ failure(
2271
+ SettlementConflict.make({
2272
+ submissionId: request.submissionId,
2273
+ existingOutcome: stored.row.settledOutcome,
2274
+ }),
2275
+ ),
2276
+ current,
2277
+ ]
2278
+ }
2279
+ // Canonical publication wins over a late Unknown marking.
2280
+ if (canonical !== undefined) {
2281
+ return [
2282
+ failure(
2283
+ SettlementConflict.make({
2284
+ submissionId: request.submissionId,
2285
+ existingOutcome: canonical.settlement.outcome,
2286
+ }),
2287
+ ),
2288
+ current,
2289
+ ]
2290
+ }
2291
+ // Idempotent merge: repeating is a no-op; additional open calls extend the marked
2292
+ // set while the first recorded reason is kept.
2293
+ const existing = stored.unknownMark
2294
+ const known = new Set(existing?.toolCallIds ?? [])
2295
+
2296
+ const merged = [
2297
+ ...(existing?.toolCallIds ?? []),
2298
+ ...request.toolCallIds.filter((toolCallId) => !known.has(toolCallId)),
2299
+ ]
2300
+
2301
+ return [
2302
+ success(undefined),
2303
+ withSubmission(current, {
2304
+ ...stored,
2305
+ row: stored.row.state === 'unknown' ? stored.row : { ...stored.row, state: 'unknown' },
2306
+ unknownMark: { reason: existing?.reason ?? request.reason, toolCallIds: merged },
2307
+ }),
2308
+ ]
2309
+ },
2310
+ )
2311
+
2312
+ if (decision._tag === 'failure') return yield* decision.error
2313
+ },
2314
+ )
2315
+
2316
+ const recordUnknownResolution: SubmissionLedger['Service']['recordUnknownResolution'] = Effect.fnUntraced(
2317
+ function*(unvalidated) {
2318
+ const command = yield* validate(
2319
+ UnknownResolutionCommand,
2320
+ 'recordUnknownResolution',
2321
+ unvalidated,
2322
+ )
2323
+
2324
+ const nowMillis = yield* Clock.currentTimeMillis
2325
+
2326
+ const before = (yield* Ref.get(state)).submissions.get(command.submissionId)
2327
+ const kind = unknownResolutionKind(command.resolution)
2328
+
2329
+ if (
2330
+ before !== undefined &&
2331
+ kind === 'factual' &&
2332
+ !before.unknownResolutions.has(JSON.stringify([command.toolCallId, kind]))
2333
+ ) {
2334
+ const runId = runIdForSubmission(before.row.submissionId)
2335
+
2336
+ const outcomes = yield* journal.toolCallResults(
2337
+ before.row.threadId,
2338
+ runId,
2339
+ command.toolCallId,
2340
+ )
2341
+
2342
+ const result = outcomes[0]?.payload
2343
+
2344
+ if (
2345
+ outcomes.length > 1 ||
2346
+ (result !== undefined &&
2347
+ (result._tag !== 'ToolCallSettled' ||
2348
+ result.runId !== runId ||
2349
+ result.toolCallId !== command.toolCallId))
2350
+ ) {
2351
+ return yield* ledgerError(
2352
+ 'recordUnknownResolution',
2353
+ 'Canonical Tool result identity is inconsistent',
2354
+ )
2355
+ }
2356
+
2357
+ if (
2358
+ result?._tag === 'ToolCallSettled' &&
2359
+ !unknownResolutionMatchesResult(command.resolution, result)
2360
+ ) {
2361
+ return yield* UnknownResolutionConflict.make({
2362
+ submissionId: command.submissionId,
2363
+ toolCallId: command.toolCallId,
2364
+ })
2365
+ }
2366
+ }
2367
+
2368
+ const decision = yield* Ref.modify(
2369
+ state,
2370
+ (
2371
+ current,
2372
+ ): readonly [
2373
+ Decision<
2374
+ UnknownResolutionIntent,
2375
+ UnknownResolutionConflict | SettlementConflict | LedgerError
2376
+ >,
2377
+ LedgerState,
2378
+ ] => {
2379
+ const stored = current.submissions.get(command.submissionId)
2380
+
2381
+ if (stored === undefined) {
2382
+ return [
2383
+ failure(
2384
+ ledgerError(
2385
+ 'recordUnknownResolution',
2386
+ `Unknown Submission ${command.submissionId}`,
2387
+ ),
2388
+ ),
2389
+ current,
2390
+ ]
2391
+ }
2392
+ if (stored.row.state === 'settled') {
2393
+ if (stored.row.settledOutcome === undefined) {
2394
+ return [
2395
+ failure(
2396
+ ledgerError(
2397
+ 'recordUnknownResolution',
2398
+ `Settled Submission ${command.submissionId} is missing its outcome`,
2399
+ ),
2400
+ ),
2401
+ current,
2402
+ ]
2403
+ }
2404
+
2405
+ // Factual closure may outlive settlement; it never restores execution authority.
2406
+ if (
2407
+ command.resolution._tag !== 'CompletedWithResult' &&
2408
+ command.resolution._tag !== 'NeverHappened'
2409
+ ) {
2410
+ return [
2411
+ failure(
2412
+ SettlementConflict.make({
2413
+ submissionId: command.submissionId,
2414
+ existingOutcome: stored.row.settledOutcome,
2415
+ }),
2416
+ ),
2417
+ current,
2418
+ ]
2419
+ }
2420
+ }
2421
+ const key = JSON.stringify([command.toolCallId, kind])
2422
+ const existing = stored.unknownResolutions.get(key)
2423
+
2424
+ if (
2425
+ (existing !== undefined &&
2426
+ !equivalentUnknownResolution(existing.intent.resolution, command.resolution)) ||
2427
+ (existing === undefined &&
2428
+ kind === 'execution' &&
2429
+ stored.unknownResolutions.has(JSON.stringify([command.toolCallId, 'factual'])))
2430
+ ) {
2431
+ return [
2432
+ failure(
2433
+ UnknownResolutionConflict.make({
2434
+ submissionId: command.submissionId,
2435
+ toolCallId: command.toolCallId,
2436
+ }),
2437
+ ),
2438
+ current,
2439
+ ]
2440
+ }
2441
+
2442
+ const intent = existing?.intent ??
2443
+ UnknownResolutionIntent.make({
2444
+ submissionId: command.submissionId,
2445
+ toolCallId: command.toolCallId,
2446
+ author: command.author,
2447
+ reason: command.reason,
2448
+ resolution: command.resolution,
2449
+ resolvedAt: utc(nowMillis),
2450
+ })
2451
+
2452
+ if (existing === undefined && !resolutionFitsTransfer(stored.row.threadId, intent)) {
2453
+ return [failure(transferCapacityError('recordUnknownResolution')), current]
2454
+ }
2455
+
2456
+ const unknownResolutions = existing !== undefined
2457
+ ? stored.unknownResolutions
2458
+ : new Map(stored.unknownResolutions).set(key, {
2459
+ intent,
2460
+ })
2461
+
2462
+ // The lane reopens only when EVERY marked open call has a durable resolution
2463
+ // intent: unknown → input-applied (DUR-017). Replays re-run the coverage check so
2464
+ // a recovering caller can wake the lane idempotently.
2465
+ const wakes = stored.row.state === 'unknown' &&
2466
+ stored.unknownMark !== undefined &&
2467
+ stored.unknownMark.toolCallIds.every(
2468
+ (toolCallId) =>
2469
+ unknownResolutions.has(JSON.stringify([toolCallId, 'execution'])) ||
2470
+ unknownResolutions.has(JSON.stringify([toolCallId, 'factual'])),
2471
+ )
2472
+
2473
+ return [
2474
+ success(intent),
2475
+ withSubmission(current, {
2476
+ ...stored,
2477
+ row: wakes ? { ...stored.row, state: 'input-applied' } : stored.row,
2478
+ unknownMark: wakes ? undefined : stored.unknownMark,
2479
+ unknownResolutions,
2480
+ }),
2481
+ ]
2482
+ },
2483
+ )
2484
+
2485
+ if (decision._tag === 'failure') return yield* decision.error
2486
+
2487
+ return decision.value
2488
+ },
2489
+ )
2490
+
2491
+ const recordChildSettled: SubmissionLedger['Service']['recordChildSettled'] = Effect.fnUntraced(
2492
+ function*(unvalidated) {
2493
+ const request = yield* validate(
2494
+ ChildSettledNotification,
2495
+ 'recordChildSettled',
2496
+ unvalidated,
2497
+ )
2498
+
2499
+ const before = yield* Ref.get(state)
2500
+ const waiting = before.submissions.get(request.parentSubmissionId)?.suspension?.reason
2501
+
2502
+ const ids = new Set([
2503
+ request.childSubmissionId,
2504
+ ...(waiting?._tag === 'WaitingForChild'
2505
+ ? waiting.children.map((child) => child.childSubmissionId)
2506
+ : []),
2507
+ ])
2508
+
2509
+ const announcedChildren = new Set<SubmissionId>()
2510
+
2511
+ for (const id of ids) {
2512
+ const child = before.submissions.get(id)
2513
+
2514
+ if (child !== undefined && (yield* canonicalSettlement(child.row)) !== undefined) {
2515
+ announcedChildren.add(id)
2516
+ }
2517
+ }
2518
+
2519
+ const decision = yield* Ref.modify(
2520
+ state,
2521
+ (current): readonly [Decision<ChildSettledOutcome, LedgerError>, LedgerState] => {
2522
+ const parent = current.submissions.get(request.parentSubmissionId)
2523
+
2524
+ if (parent === undefined) {
2525
+ return [
2526
+ failure(
2527
+ ledgerError(
2528
+ 'recordChildSettled',
2529
+ `Unknown Submission ${request.parentSubmissionId}`,
2530
+ ),
2531
+ ),
2532
+ current,
2533
+ ]
2534
+ }
2535
+ // Canonical publication is visible before child ledger finalization.
2536
+ const announced = announcedChildren.has(request.childSubmissionId)
2537
+
2538
+ if (!announced) {
2539
+ return [
2540
+ failure(
2541
+ ledgerError(
2542
+ 'recordChildSettled',
2543
+ `Child Submission ${request.childSubmissionId} has no recorded settlement`,
2544
+ ),
2545
+ ),
2546
+ current,
2547
+ ]
2548
+ }
2549
+ if (
2550
+ parent.row.state !== 'suspended' ||
2551
+ parent.suspension === undefined ||
2552
+ parent.suspension.reason._tag !== 'WaitingForChild'
2553
+ ) {
2554
+ return [success('not-waiting' as const), current]
2555
+ }
2556
+ const children = parent.suspension.reason.children
2557
+
2558
+ if (!children.some((entry) => entry.childSubmissionId === request.childSubmissionId)) {
2559
+ return [success('not-waiting' as const), current]
2560
+ }
2561
+
2562
+ const allSettled = children.every((entry) => announcedChildren.has(entry.childSubmissionId))
2563
+
2564
+ if (!allSettled) return [success('still-waiting' as const), current]
2565
+
2566
+ return [
2567
+ success('woken' as const),
2568
+ withSubmission(current, {
2569
+ ...parent,
2570
+ row: { ...parent.row, state: 'input-applied' },
2571
+ suspension: undefined,
2572
+ }),
2573
+ ]
2574
+ },
2575
+ )
2576
+
2577
+ if (decision._tag === 'failure') return yield* decision.error
2578
+
2579
+ return decision.value
2580
+ },
2581
+ )
2582
+
2583
+ const reserveChildBudget: SubmissionLedger['Service']['reserveChildBudget'] = Effect.fnUntraced(
2584
+ function*(unvalidated) {
2585
+ const request = yield* validate(
2586
+ ChildBudgetReservationRequest,
2587
+ 'reserveChildBudget',
2588
+ unvalidated,
2589
+ )
2590
+
2591
+ const nowMillis = yield* Clock.currentTimeMillis
2592
+
2593
+ const decision = yield* Ref.modify(
2594
+ state,
2595
+ (
2596
+ current,
2597
+ ): readonly [
2598
+ Decision<ReservedChildBudget, ChildReservationConflict | OwnershipLost | LedgerError>,
2599
+ LedgerState,
2600
+ ] => {
2601
+ const existing = current.childReservations.get(request.reservationId)
2602
+
2603
+ if (existing !== undefined) {
2604
+ // Identical replays short-circuit before the fence, retaining the first committed allocation:
2605
+ // a replay creates nothing, so a recovering caller resumes rather than duplicates.
2606
+ const identical = existing.parentSubmissionId === request.parentSubmissionId &&
2607
+ existing.parentToolCallId === request.parentToolCallId &&
2608
+ existing.allocationDigest === request.allocationDigest &&
2609
+ equivalentPersistedJson(existing.allocation, request.allocation)
2610
+
2611
+ if (!identical) {
2612
+ return [
2613
+ failure(
2614
+ ChildReservationConflict.make({
2615
+ reservationId: request.reservationId,
2616
+ status: existing.status,
2617
+ message:
2618
+ 'A reservation with this identity exists with a different parent Tool Call or allocation.',
2619
+ }),
2620
+ ),
2621
+ current,
2622
+ ]
2623
+ }
2624
+
2625
+ return [
2626
+ success(
2627
+ ReservedChildBudget.make({
2628
+ reservation: toReservationSnapshot(existing),
2629
+ replayed: true,
2630
+ }),
2631
+ ),
2632
+ current,
2633
+ ]
2634
+ }
2635
+ for (const id of current.childrenByParent.get(request.parentSubmissionId) ?? []) {
2636
+ const reservation = current.childReservations.get(id)
2637
+
2638
+ if (reservation === undefined) continue
2639
+ if (
2640
+ reservation.parentSubmissionId === request.parentSubmissionId &&
2641
+ reservation.parentToolCallId === request.parentToolCallId
2642
+ ) {
2643
+ return [
2644
+ failure(
2645
+ ChildReservationConflict.make({
2646
+ reservationId: request.reservationId,
2647
+ status: reservation.status,
2648
+ message:
2649
+ `Parent Tool Call ${request.parentToolCallId} already owns reservation ${reservation.reservationId}.`,
2650
+ }),
2651
+ ),
2652
+ current,
2653
+ ]
2654
+ }
2655
+ }
2656
+ const parent = current.submissions.get(request.parentSubmissionId)
2657
+
2658
+ if (parent === undefined) {
2659
+ return [
2660
+ failure(
2661
+ ledgerError(
2662
+ 'reserveChildBudget',
2663
+ `Unknown Submission ${request.parentSubmissionId}`,
2664
+ ),
2665
+ ),
2666
+ current,
2667
+ ]
2668
+ }
2669
+ // Creation is fenced by the parent lane's live ownership (spec §12 step 2): a stale
2670
+ // parent Attempt can never create new reservation state.
2671
+ if (!journal.owner.hasOwner(parent.row.threadId, parent.row.submissionId)) {
2672
+ return [failure(ownershipLost(parent)), current]
2673
+ }
2674
+
2675
+ const reservation: StoredChildReservation = {
2676
+ reservationId: request.reservationId,
2677
+ parentSubmissionId: request.parentSubmissionId,
2678
+ parentToolCallId: request.parentToolCallId,
2679
+ childSubmissionId: undefined,
2680
+ status: 'reserved',
2681
+ allocation: request.allocation,
2682
+ allocationDigest: request.allocationDigest,
2683
+ accounting: undefined,
2684
+ reservedAtMillis: nowMillis,
2685
+ releaseBeganAtMillis: undefined,
2686
+ releasedAtMillis: undefined,
2687
+ }
2688
+
2689
+ return [
2690
+ success(
2691
+ ReservedChildBudget.make({
2692
+ reservation: toReservationSnapshot(reservation),
2693
+ replayed: false,
2694
+ }),
2695
+ ),
2696
+ withChildReservation(current, reservation),
2697
+ ]
2698
+ },
2699
+ )
2700
+
2701
+ if (decision._tag === 'failure') return yield* decision.error
2702
+
2703
+ return decision.value
2704
+ },
2705
+ )
2706
+
2707
+ const attachChildToReservation: SubmissionLedger['Service']['attachChildToReservation'] = Effect.fnUntraced(
2708
+ function*(unvalidated) {
2709
+ const request = yield* validate(
2710
+ AttachChildToReservationRequest,
2711
+ 'attachChildToReservation',
2712
+ unvalidated,
2713
+ )
2714
+
2715
+ const decision = yield* Ref.modify(
2716
+ state,
2717
+ (
2718
+ current,
2719
+ ): readonly [
2720
+ Decision<
2721
+ ChildBudgetReservationSnapshot,
2722
+ ChildReservationConflict | OwnershipLost | LedgerError
2723
+ >,
2724
+ LedgerState,
2725
+ ] => {
2726
+ const reservation = current.childReservations.get(request.reservationId)
2727
+
2728
+ if (reservation === undefined) {
2729
+ return [
2730
+ failure(
2731
+ ledgerError(
2732
+ 'attachChildToReservation',
2733
+ `Unknown child reservation ${request.reservationId}`,
2734
+ ),
2735
+ ),
2736
+ current,
2737
+ ]
2738
+ }
2739
+ if (reservation.childSubmissionId !== undefined) {
2740
+ // Idempotent replay of the recorded attachment (unfenced — it mutates nothing).
2741
+ if (reservation.childSubmissionId === request.childSubmissionId) {
2742
+ return [success(toReservationSnapshot(reservation)), current]
2743
+ }
2744
+
2745
+ return [
2746
+ failure(
2747
+ ChildReservationConflict.make({
2748
+ reservationId: request.reservationId,
2749
+ status: reservation.status,
2750
+ message:
2751
+ `Reservation ${request.reservationId} already records child ${reservation.childSubmissionId}.`,
2752
+ }),
2753
+ ),
2754
+ current,
2755
+ ]
2756
+ }
2757
+ const parent = current.submissions.get(reservation.parentSubmissionId)
2758
+
2759
+ if (parent === undefined) {
2760
+ return [
2761
+ failure(
2762
+ ledgerError(
2763
+ 'attachChildToReservation',
2764
+ `Unknown Submission ${reservation.parentSubmissionId}`,
2765
+ ),
2766
+ ),
2767
+ current,
2768
+ ]
2769
+ }
2770
+ if (!journal.owner.hasOwner(parent.row.threadId, parent.row.submissionId)) {
2771
+ return [failure(ownershipLost(parent)), current]
2772
+ }
2773
+ if (reservation.status !== 'reserved') {
2774
+ return [
2775
+ failure(
2776
+ ChildReservationConflict.make({
2777
+ reservationId: request.reservationId,
2778
+ status: reservation.status,
2779
+ message: `Cannot attach a child to a ${reservation.status} reservation.`,
2780
+ }),
2781
+ ),
2782
+ current,
2783
+ ]
2784
+ }
2785
+ // Single-store latitude: the admitted child must exist here, so a dangling
2786
+ // attachment can never enter the recovery view.
2787
+ if (!current.submissions.has(request.childSubmissionId)) {
2788
+ return [
2789
+ failure(
2790
+ ledgerError(
2791
+ 'attachChildToReservation',
2792
+ `Unknown child Submission ${request.childSubmissionId}`,
2793
+ ),
2794
+ ),
2795
+ current,
2796
+ ]
2797
+ }
2798
+
2799
+ const attached: StoredChildReservation = {
2800
+ ...reservation,
2801
+ childSubmissionId: request.childSubmissionId,
2802
+ }
2803
+
2804
+ return [
2805
+ success(toReservationSnapshot(attached)),
2806
+ withChildReservation(current, attached),
2807
+ ]
2808
+ },
2809
+ )
2810
+
2811
+ if (decision._tag === 'failure') return yield* decision.error
2812
+
2813
+ return decision.value
2814
+ },
2815
+ )
2816
+
2817
+ const beginChildBudgetRelease: SubmissionLedger['Service']['beginChildBudgetRelease'] = Effect.fnUntraced(
2818
+ function*(unvalidated) {
2819
+ const request = yield* validate(
2820
+ BeginChildBudgetReleaseRequest,
2821
+ 'beginChildBudgetRelease',
2822
+ unvalidated,
2823
+ )
2824
+
2825
+ const nowMillis = yield* Clock.currentTimeMillis
2826
+
2827
+ const decision = yield* Ref.modify(
2828
+ state,
2829
+ (
2830
+ current,
2831
+ ): readonly [
2832
+ Decision<ChildBudgetReservationSnapshot, ChildReservationConflict | LedgerError>,
2833
+ LedgerState,
2834
+ ] => {
2835
+ const reservation = current.childReservations.get(request.reservationId)
2836
+
2837
+ if (reservation === undefined) {
2838
+ return [
2839
+ failure(
2840
+ ledgerError(
2841
+ 'beginChildBudgetRelease',
2842
+ `Unknown child reservation ${request.reservationId}`,
2843
+ ),
2844
+ ),
2845
+ current,
2846
+ ]
2847
+ }
2848
+ if (reservation.status !== 'reserved') {
2849
+ // The accounting decision was already frozen exactly once; an identical replay is
2850
+ // a no-op and a divergent decision conflicts (spec §12 join step 6).
2851
+ if (
2852
+ reservation.accounting !== undefined &&
2853
+ equivalentPersistedJson(reservation.accounting, request.accounting)
2854
+ ) {
2855
+ return [success(toReservationSnapshot(reservation)), current]
2856
+ }
2857
+
2858
+ return [
2859
+ failure(
2860
+ ChildReservationConflict.make({
2861
+ reservationId: request.reservationId,
2862
+ status: reservation.status,
2863
+ message: 'A different accounting decision is already frozen for this reservation.',
2864
+ }),
2865
+ ),
2866
+ current,
2867
+ ]
2868
+ }
2869
+
2870
+ const frozen: StoredChildReservation = {
2871
+ ...reservation,
2872
+ status: 'releasePending',
2873
+ accounting: request.accounting,
2874
+ releaseBeganAtMillis: nowMillis,
2875
+ }
2876
+
2877
+ return [success(toReservationSnapshot(frozen)), withChildReservation(current, frozen)]
2878
+ },
2879
+ )
2880
+
2881
+ if (decision._tag === 'failure') return yield* decision.error
2882
+
2883
+ return decision.value
2884
+ },
2885
+ )
2886
+
2887
+ const releaseChildBudget: SubmissionLedger['Service']['releaseChildBudget'] = Effect.fnUntraced(
2888
+ function*(unvalidated) {
2889
+ const request = yield* validate(
2890
+ ReleaseChildBudgetRequest,
2891
+ 'releaseChildBudget',
2892
+ unvalidated,
2893
+ )
2894
+
2895
+ const nowMillis = yield* Clock.currentTimeMillis
2896
+
2897
+ const decision = yield* Ref.modify(
2898
+ state,
2899
+ (
2900
+ current,
2901
+ ): readonly [
2902
+ Decision<ChildBudgetReservationSnapshot, ChildReservationConflict | LedgerError>,
2903
+ LedgerState,
2904
+ ] => {
2905
+ const reservation = current.childReservations.get(request.reservationId)
2906
+
2907
+ if (reservation === undefined) {
2908
+ return [
2909
+ failure(
2910
+ ledgerError(
2911
+ 'releaseChildBudget',
2912
+ `Unknown child reservation ${request.reservationId}`,
2913
+ ),
2914
+ ),
2915
+ current,
2916
+ ]
2917
+ }
2918
+ // Applied exactly once: replaying a released reservation returns the stored row
2919
+ // unchanged (spec §12: "never available twice").
2920
+ if (reservation.status === 'released') {
2921
+ return [success(toReservationSnapshot(reservation)), current]
2922
+ }
2923
+ if (reservation.status !== 'releasePending') {
2924
+ return [
2925
+ failure(
2926
+ ChildReservationConflict.make({
2927
+ reservationId: request.reservationId,
2928
+ status: reservation.status,
2929
+ message: 'Cannot release a reservation whose accounting decision is not frozen.',
2930
+ }),
2931
+ ),
2932
+ current,
2933
+ ]
2934
+ }
2935
+
2936
+ const released: StoredChildReservation = {
2937
+ ...reservation,
2938
+ status: 'released',
2939
+ releasedAtMillis: nowMillis,
2940
+ }
2941
+
2942
+ return [
2943
+ success(toReservationSnapshot(released)),
2944
+ withChildReservation(current, released),
2945
+ ]
2946
+ },
2947
+ )
2948
+
2949
+ if (decision._tag === 'failure') return yield* decision.error
2950
+
2951
+ return decision.value
2952
+ },
2953
+ )
2954
+
2955
+ const scanNonterminal: SubmissionLedger['Service']['scanNonterminal'] = Stream.paginate<
2956
+ string | undefined,
2957
+ SubmissionWorkItem,
2958
+ never
2959
+ >(undefined, (after) =>
2960
+ Effect.sync(() => {
2961
+ const current = MutableRef.get(state.ref)
2962
+
2963
+ const candidates = boundedWorkSelection<StoredSubmission>(
2964
+ 8,
2965
+ (stored) => `${stored.row.threadId}\u0000${String(stored.row.queueSequence).padStart(16, '0')}`,
2966
+ after,
2967
+ )
2968
+
2969
+ for (const ids of current.activeByThread.values()) {
2970
+ for (const id of ids) {
2971
+ const stored = current.submissions.get(id)
2972
+
2973
+ if (stored !== undefined) candidates.add(stored)
2974
+ }
2975
+ }
2976
+ const items = candidates.values.map(({ row }) => SubmissionWorkItem.make(row))
2977
+ const last = candidates.values.at(-1)?.row
2978
+
2979
+ return [
2980
+ items,
2981
+ last === undefined
2982
+ ? Option.none<string | undefined>()
2983
+ : Option.some(`${last.threadId}\u0000${String(last.queueSequence).padStart(16, '0')}`),
2984
+ ] as const
2985
+ }))
2986
+
2987
+ const readAbortIntent: SubmissionLedger['Service']['readAbortIntent'] = Effect.fnUntraced(
2988
+ function*(unvalidated) {
2989
+ const request = yield* validate(AbortIntentRequest, 'readAbortIntent', unvalidated)
2990
+ const stored = (yield* Ref.get(state)).submissions.get(request.submissionId)
2991
+
2992
+ if (stored === undefined) {
2993
+ return yield* ledgerError(
2994
+ 'readAbortIntent',
2995
+ `Unknown Submission ${request.submissionId}`,
2996
+ )
2997
+ }
2998
+
2999
+ return stored.abortIntent
3000
+ },
3001
+ )
3002
+
3003
+ const loadRecoverySnapshot: SubmissionLedger['Service']['loadRecoverySnapshot'] = Effect.fnUntraced(
3004
+ function*(unvalidated) {
3005
+ const request = yield* validate(
3006
+ RecoverySnapshotRequest,
3007
+ 'loadRecoverySnapshot',
3008
+ unvalidated,
3009
+ )
3010
+
3011
+ const current = yield* Ref.get(state)
3012
+ const stored = current.submissions.get(request.submissionId)
3013
+
3014
+ if (stored === undefined) {
3015
+ return yield* ledgerError(
3016
+ 'loadRecoverySnapshot',
3017
+ `Unknown Submission ${request.submissionId}`,
3018
+ )
3019
+ }
3020
+
3021
+ const joins = Array.from(
3022
+ current.joinsByHost.get(request.submissionId) ?? [],
3023
+ (id) => current.submissions.get(id),
3024
+ )
3025
+ .filter((candidate): candidate is StoredSubmission => candidate !== undefined)
3026
+ .sort((left, right) => left.row.queueSequence - right.row.queueSequence)
3027
+ .map((candidate) =>
3028
+ JoinSnapshot.make({
3029
+ submissionId: candidate.row.submissionId,
3030
+ state: candidate.row.state,
3031
+ hostSubmissionId: request.submissionId,
3032
+ })
3033
+ )
3034
+
3035
+ const byToolCallId = <A extends { readonly toolCallId: ToolCallId }>(
3036
+ left: A,
3037
+ right: A,
3038
+ ): number => left.toolCallId < right.toolCallId ? -1 : left.toolCallId > right.toolCallId ? 1 : 0
3039
+
3040
+ // Parent-side subagent view: this Submission's child budget reservations in parent Tool
3041
+ // Call order, plus each attached child's current lane state (a disposable derived view;
3042
+ // the canonical records stay the recovery truth, DUR-015).
3043
+ const childReservations = Array.from(
3044
+ current.childrenByParent.get(request.submissionId) ?? [],
3045
+ (id) => current.childReservations.get(id),
3046
+ )
3047
+ .filter((reservation): reservation is StoredChildReservation => reservation !== undefined)
3048
+ .sort((left, right) =>
3049
+ left.parentToolCallId < right.parentToolCallId
3050
+ ? -1
3051
+ : left.parentToolCallId > right.parentToolCallId
3052
+ ? 1
3053
+ : 0
3054
+ )
3055
+
3056
+ const childAttachments: Array<ChildAttachmentSnapshot> = []
3057
+
3058
+ for (const reservation of childReservations) {
3059
+ if (reservation.childSubmissionId === undefined) continue
3060
+ const child = current.submissions.get(reservation.childSubmissionId)
3061
+
3062
+ if (child === undefined) continue
3063
+ childAttachments.push(
3064
+ ChildAttachmentSnapshot.make({
3065
+ toolCallId: reservation.parentToolCallId,
3066
+ childSubmissionId: reservation.childSubmissionId,
3067
+ childState: child.row.state,
3068
+ ...(child.row.settledOutcome === undefined
3069
+ ? {}
3070
+ : { childOutcome: child.row.settledOutcome }),
3071
+ }),
3072
+ )
3073
+ }
3074
+
3075
+ return RecoverySnapshot.make({
3076
+ submission: toSnapshot(stored.row),
3077
+ joins,
3078
+ approvalDecisions: [...stored.approvalDecisions.values()].sort(byToolCallId),
3079
+ unknownResolutions: [...stored.unknownResolutions.values()]
3080
+ .map((resolution) => resolution.intent)
3081
+ .sort(byToolCallId),
3082
+ childReservations: childReservations.map(toReservationSnapshot),
3083
+ childAttachments,
3084
+ ...(stored.row.parentLinkage === undefined
3085
+ ? {}
3086
+ : { parentLinkage: stored.row.parentLinkage }),
3087
+ ...(stored.joinedHostSubmissionId === undefined
3088
+ ? {}
3089
+ : { hostSubmissionId: stored.joinedHostSubmissionId }),
3090
+ ...(stored.suspension === undefined
3091
+ ? {}
3092
+ : {
3093
+ suspension: SuspensionSnapshot.make({
3094
+ reason: stored.suspension.reason,
3095
+ suspendedAt: utc(stored.suspension.suspendedAtMillis),
3096
+ }),
3097
+ }),
3098
+ hasOwner: journal.owner.hasOwner(stored.row.threadId, stored.row.submissionId),
3099
+ ...(stored.inputApplied === undefined ? {} : { inputApplied: stored.inputApplied }),
3100
+ ...(stored.abortIntent === undefined ? {} : { abortIntent: stored.abortIntent }),
3101
+ })
3102
+ },
3103
+ )
3104
+
3105
+ const ledger = SubmissionLedger.of({
3106
+ capabilities,
3107
+ resolveFundingOwner: Effect.fnUntraced(function*(unvalidated) {
3108
+ const request = yield* validate(FundingOwnerRequest, 'funding owner', unvalidated)
3109
+ const current = MutableRef.get(state.ref)
3110
+ const selected = current.submissions.get(request.submissionId)
3111
+
3112
+ if (selected === undefined || selected.row.threadId !== request.threadId) {
3113
+ return yield* ledgerError(
3114
+ 'funding owner',
3115
+ 'Selected admission belongs to another Thread or is missing',
3116
+ )
3117
+ }
3118
+ if (
3119
+ selected.row.state === 'joining' ||
3120
+ (selected.joinedHostSubmissionId !== undefined && selected.inputApplied === undefined)
3121
+ ) {
3122
+ return yield* ledgerError(
3123
+ 'funding owner',
3124
+ 'Joining funding owner is not yet frozen by exact applied input evidence',
3125
+ )
3126
+ }
3127
+
3128
+ const owner = selected.joinedHostSubmissionId === undefined
3129
+ ? selected
3130
+ : current.submissions.get(selected.joinedHostSubmissionId)
3131
+
3132
+ if (
3133
+ owner === undefined ||
3134
+ owner.row.threadId !== request.threadId ||
3135
+ (owner !== selected && owner.row.queueSequence >= selected.row.queueSequence)
3136
+ ) {
3137
+ return yield* ledgerError(
3138
+ 'funding owner',
3139
+ 'Exact joined funding owner is missing or inconsistent',
3140
+ )
3141
+ }
3142
+
3143
+ return FundingOwner.make({
3144
+ selected: toSnapshot(selected.row),
3145
+ owner: toSnapshot(owner.row),
3146
+ })
3147
+ }),
3148
+ admit: (request) => journal.withMutation(admit(request)),
3149
+ markReady: (request) => journal.withMutation(markReady(request)),
3150
+ lookup,
3151
+ resolveAdmission,
3152
+ selectHead: (request) => journal.withMutation(selectHead(request)),
3153
+ markInputApplied: (request) => journal.withMutation(markInputApplied(request)),
3154
+ finalizeSettlement: (request) => journal.withMutation(finalizeSettlement(request)),
3155
+ requestAbort: (request) => journal.withMutation(requestAbort(request)),
3156
+ stopWorker: (request) => journal.withMutation(stopWorker(request)),
3157
+ inspectWorker,
3158
+ claimJoining: (request) => journal.withMutation(claimJoining(request)),
3159
+ markJoined: (request) => journal.withMutation(markJoined(request)),
3160
+ revertJoining: (request) => journal.withMutation(revertJoining(request)),
3161
+ suspend: (request) => journal.withMutation(suspend(request)),
3162
+ recordApprovalDecision: (request) => journal.withMutation(recordApprovalDecision(request)),
3163
+ markUnknown: (request) => journal.withMutation(markUnknown(request)),
3164
+ recordUnknownResolution: (request) => journal.withMutation(recordUnknownResolution(request)),
3165
+ recordChildSettled: (request) => journal.withMutation(recordChildSettled(request)),
3166
+ reserveChildBudget: (request) => journal.withMutation(reserveChildBudget(request)),
3167
+ attachChildToReservation: (request) => journal.withMutation(attachChildToReservation(request)),
3168
+ beginChildBudgetRelease: (request) => journal.withMutation(beginChildBudgetRelease(request)),
3169
+ releaseChildBudget: (request) => journal.withMutation(releaseChildBudget(request)),
3170
+ scanNonterminal,
3171
+ loadRecoverySnapshot,
3172
+ readAbortIntent,
3173
+ })
3174
+
3175
+ const toAdmission = (row: SubmissionRow, settledAtMillis?: number) =>
3176
+ ThreadAdmission.make({
3177
+ ...toSnapshot(row),
3178
+ ...(settledAtMillis === undefined ? {} : { settledAt: utc(settledAtMillis) }),
3179
+ })
3180
+
3181
+ const cleanCommand = <A extends { readonly canonicalRecordId?: RecordEnvelope['recordId'] }>(
3182
+ value: A,
3183
+ ) => {
3184
+ const { canonicalRecordId: _, ...fact } = value
3185
+
3186
+ return fact
3187
+ }
3188
+
3189
+ const commands = (stored: StoredSubmission | undefined) => {
3190
+ return {
3191
+ aborts: stored?.abortIntent === undefined ? [] : [cleanCommand(stored.abortIntent)],
3192
+ approvals: Array.from(stored?.approvalDecisions.values() ?? [], cleanCommand),
3193
+ resolutions: Array.from(stored?.unknownResolutions.values() ?? [], ({ intent }) => cleanCommand(intent)),
3194
+ }
3195
+ }
3196
+
3197
+ const readCommands = Effect.fnUntraced(function*(stored: StoredSubmission | undefined) {
3198
+ if (
3199
+ (stored?.approvalDecisions.size ?? 0) > MAX_RUN_EVIDENCE_RECORDS ||
3200
+ (stored?.unknownResolutions.size ?? 0) > MAX_RUN_EVIDENCE_RECORDS
3201
+ ) {
3202
+ return yield* ThreadStoreError.make({
3203
+ operation: 'read commands',
3204
+ message: 'Accepted commands exceed Run record bounds',
3205
+ })
3206
+ }
3207
+ let bytes = 0
3208
+
3209
+ const add = <A, I>(schema: Schema.Codec<A, I>, value: A) =>
3210
+ Schema.encodeEffect(Schema.toCodecJson(schema))(value).pipe(
3211
+ Effect.mapError(() =>
3212
+ ThreadStoreError.make({
3213
+ operation: 'read commands',
3214
+ message: 'Invalid accepted command wire',
3215
+ })
3216
+ ),
3217
+ Effect.flatMap((wire) => {
3218
+ bytes += utf8ByteLength(canonicalJson(wire))
3219
+
3220
+ return bytes > MAX_RUN_EVIDENCE_BYTES
3221
+ ? Effect.fail(
3222
+ ThreadStoreError.make({
3223
+ operation: 'read commands',
3224
+ message: 'Accepted commands exceed Run byte bounds',
3225
+ }),
3226
+ )
3227
+ : Effect.void
3228
+ }),
3229
+ )
3230
+
3231
+ if (stored?.abortIntent !== undefined) yield* add(AbortIntent, stored.abortIntent)
3232
+ for (const value of stored?.approvalDecisions.values() ?? []) {
3233
+ yield* add(ApprovalDecisionIntent, value)
3234
+ }
3235
+ for (const { intent } of stored?.unknownResolutions.values() ?? []) {
3236
+ yield* add(UnknownResolutionIntent, intent)
3237
+ }
3238
+
3239
+ return commands(stored)
3240
+ })
3241
+
3242
+ const lookupAdmission = (threadId: ThreadId, submissionId: SubmissionId) =>
3243
+ Effect.sync(() => {
3244
+ const stored = MutableRef.get(state.ref).submissions.get(submissionId)
3245
+
3246
+ return stored?.row.threadId === threadId
3247
+ ? toAdmission(stored.row, stored.finalization?.finalizedAtMillis)
3248
+ : undefined
3249
+ })
3250
+
3251
+ yield* journal.registerLedgerTransfer({
3252
+ admission: lookupAdmission,
3253
+ commands: (id) => readCommands(MutableRef.get(state.ref).submissions.get(id)),
3254
+ snapshot: (threadId) =>
3255
+ Effect.sync(() => {
3256
+ const current = MutableRef.get(state.ref)
3257
+ const directory = current.byThread.get(threadId)
3258
+
3259
+ return {
3260
+ idle: (current.activeByThread.get(threadId)?.size ?? 0) === 0 &&
3261
+ (directory?.reservations ?? 0) === 0,
3262
+ admissions: directory?.ordered.length ?? 0,
3263
+ aborts: directory?.commands.aborts.length ?? 0,
3264
+ approvals: directory?.commands.approvals.length ?? 0,
3265
+ resolutions: directory?.commands.resolutions.length ?? 0,
3266
+ ...(current.stoppedWorkers.has(threadId)
3267
+ ? {
3268
+ workerSeal: current.stoppedWorkers.get(threadId) === undefined
3269
+ ? {}
3270
+ : { terminal: current.stoppedWorkers.get(threadId) },
3271
+ }
3272
+ : {}),
3273
+ }
3274
+ }),
3275
+ facts: (threadId, section, after) =>
3276
+ Effect.sync(() => {
3277
+ const current = MutableRef.get(state.ref)
3278
+
3279
+ const facts = {
3280
+ admissions: new Array<ThreadAdmission>(),
3281
+ commands: commands(undefined),
3282
+ deliveries: [],
3283
+ }
3284
+
3285
+ let next = after ?? ''
3286
+
3287
+ if (section === 'admissions') {
3288
+ const stored = threadRows(
3289
+ current,
3290
+ threadId,
3291
+ after === undefined ? -1 : Number(after),
3292
+ ).next().value
3293
+
3294
+ if (stored !== undefined) {
3295
+ facts.admissions.push(
3296
+ toAdmission(stored.row, stored.finalization?.finalizedAtMillis),
3297
+ )
3298
+ next = String(stored.row.queueSequence)
3299
+ }
3300
+ } else {
3301
+ const entries = current.byThread.get(threadId)?.commands[section] ?? []
3302
+ const at = after === undefined ? 0 : commandPosition(entries, after)
3303
+ const choice = entries[at + Number(after !== undefined && entries[at]?.key === after)]
3304
+
3305
+ if (choice !== undefined) {
3306
+ next = choice.key
3307
+ const stored = current.submissions.get(choice.submissionId)
3308
+
3309
+ if (section === 'aborts' && stored?.abortIntent !== undefined) {
3310
+ facts.commands.aborts.push(cleanCommand(stored.abortIntent))
3311
+ } else if (section === 'approvals' && choice.toolCallId !== undefined) {
3312
+ const value = stored?.approvalDecisions.get(choice.toolCallId)
3313
+
3314
+ if (value !== undefined) facts.commands.approvals.push(cleanCommand(value))
3315
+ } else if (section === 'resolutions' && choice.resolutionKey !== undefined) {
3316
+ const value = stored?.unknownResolutions.get(choice.resolutionKey)
3317
+
3318
+ if (value !== undefined) {
3319
+ facts.commands.resolutions.push(cleanCommand(value.intent))
3320
+ }
3321
+ }
3322
+ }
3323
+ }
3324
+
3325
+ return { facts, after: next }
3326
+ }),
3327
+ submissions: (threadId) =>
3328
+ Stream.paginate(-1, (after) =>
3329
+ Effect.sync(() => {
3330
+ const stored = threadRows(MutableRef.get(state.ref), threadId, after).next().value
3331
+
3332
+ return [
3333
+ stored === undefined ? [] : [toSnapshot(stored.row)],
3334
+ stored === undefined ? Option.none<number>() : Option.some(stored.row.queueSequence),
3335
+ ] as const
3336
+ })),
3337
+ startImport: Effect.fnUntraced(function*(threadId) {
3338
+ const current = yield* Ref.get(state)
3339
+
3340
+ if (
3341
+ current.lanes.has(threadId) ||
3342
+ current.byThread.has(threadId) ||
3343
+ current.stoppedWorkers.has(threadId)
3344
+ ) {
3345
+ return yield* ThreadImportRejected.make({
3346
+ threadId,
3347
+ reason: 'target-not-empty',
3348
+ message: 'Destination ledger contains Thread data',
3349
+ })
3350
+ }
3351
+
3352
+ const staged: LedgerState = {
3353
+ submissions: new Map(),
3354
+ admissionIndex: new Map(),
3355
+ lanes: new Map(),
3356
+ childReservations: new Map(),
3357
+ freshAdmissionSequence: current.freshAdmissionSequence,
3358
+ stoppedWorkers: new Map(),
3359
+ latestByThread: new Map(),
3360
+ activeByThread: new Map(),
3361
+ byThread: new Map(),
3362
+ receipts: new Map(),
3363
+ joinsByHost: new Map(),
3364
+ childrenByParent: new Map(),
3365
+ }
3366
+
3367
+ const commandBytes = new Map<SubmissionId, number>()
3368
+ const settledTimes = new Map<SubmissionId, number>()
3369
+
3370
+ const retainCommandBytes = Effect.fnUntraced(function*<A, I>(
3371
+ schema: Schema.Codec<A, I>,
3372
+ value: A,
3373
+ id: SubmissionId,
3374
+ ) {
3375
+ const wire = yield* Schema.encodeEffect(Schema.toCodecJson(schema))(value).pipe(
3376
+ Effect.mapError(() => invalidThreadArchive('Invalid accepted command wire', threadId)),
3377
+ )
3378
+
3379
+ const bytes = (commandBytes.get(id) ?? 0) + utf8ByteLength(canonicalJson(wire))
3380
+
3381
+ if (bytes > MAX_RUN_EVIDENCE_BYTES) {
3382
+ return yield* invalidThreadArchive(
3383
+ 'Accepted commands exceed Run byte bounds',
3384
+ threadId,
3385
+ )
3386
+ }
3387
+ commandBytes.set(id, bytes)
3388
+ })
3389
+
3390
+ const reader = {
3391
+ admission: (id: SubmissionId) =>
3392
+ Effect.sync(() => {
3393
+ const stored = staged.submissions.get(id)
3394
+
3395
+ return stored === undefined
3396
+ ? undefined
3397
+ : toAdmission(stored.row, settledTimes.get(id))
3398
+ }),
3399
+ runOwner: Effect.fnUntraced(function*(runId: RunId) {
3400
+ if (!runId.startsWith('run:')) return undefined
3401
+ const id = yield* Schema.decodeEffect(SubmissionId)(runId.slice(4)).pipe(Effect.orDie)
3402
+ const stored = staged.submissions.get(id)
3403
+
3404
+ return stored === undefined ? undefined : toAdmission(stored.row, settledTimes.get(id))
3405
+ }),
3406
+ commands: (id: SubmissionId) => readCommands(staged.submissions.get(id)),
3407
+ }
3408
+
3409
+ return {
3410
+ reader,
3411
+ stage: Effect.fnUntraced(function*(page) {
3412
+ for (const a of page.archive.admissions) {
3413
+ const key = admissionKey(threadId, a.principal, a.idempotencyKey)
3414
+
3415
+ if (
3416
+ current.submissions.has(a.submissionId) ||
3417
+ staged.submissions.has(a.submissionId) ||
3418
+ current.receipts.has(a.receiptId) ||
3419
+ staged.receipts.has(a.receiptId) ||
3420
+ current.admissionIndex.has(key) ||
3421
+ staged.admissionIndex.has(key)
3422
+ ) {
3423
+ return yield* ThreadImportRejected.make({
3424
+ threadId,
3425
+ reason: 'destination-conflict',
3426
+ message: 'Admission, receipt, or immutable admission key already exists',
3427
+ })
3428
+ }
3429
+ const previous = threadRows(staged, threadId, a.queueSequence - 1).next().value
3430
+
3431
+ if (previous?.row.queueSequence === a.queueSequence) {
3432
+ return yield* invalidThreadArchive('Duplicate admission queue position', threadId)
3433
+ }
3434
+ if (a.settledAt !== undefined) {
3435
+ settledTimes.set(a.submissionId, DateTime.toEpochMillis(a.settledAt))
3436
+ }
3437
+ withSubmission(
3438
+ staged,
3439
+ fromRebuilt(
3440
+ RebuiltSubmission.make({
3441
+ admission: a,
3442
+ state: 'admitted',
3443
+ unknownToolCallIds: [],
3444
+ approvals: [],
3445
+ resolutions: [],
3446
+ }),
3447
+ ),
3448
+ )
3449
+ }
3450
+ for (const fact of page.archive.commands.aborts) {
3451
+ const stored = staged.submissions.get(fact.submissionId)
3452
+
3453
+ if (stored === undefined || stored.abortIntent !== undefined) {
3454
+ return yield* invalidThreadArchive(
3455
+ 'Missing admission or duplicate abort',
3456
+ threadId,
3457
+ )
3458
+ }
3459
+ const intent = AbortIntent.make(fact)
3460
+
3461
+ yield* retainCommandBytes(AbortIntent, intent, fact.submissionId)
3462
+ withSubmission(staged, { ...stored, abortIntent: intent })
3463
+ }
3464
+ for (const fact of page.archive.commands.approvals) {
3465
+ const stored = staged.submissions.get(fact.submissionId)
3466
+
3467
+ if (stored === undefined || stored.approvalDecisions.has(fact.toolCallId)) {
3468
+ return yield* invalidThreadArchive(
3469
+ 'Missing admission or duplicate approval',
3470
+ threadId,
3471
+ )
3472
+ }
3473
+ if (stored.approvalDecisions.size >= MAX_RUN_EVIDENCE_RECORDS) {
3474
+ return yield* invalidThreadArchive(
3475
+ 'Accepted approvals exceed Run record bounds',
3476
+ threadId,
3477
+ )
3478
+ }
3479
+ const intent = ApprovalDecisionIntent.make(fact)
3480
+
3481
+ yield* retainCommandBytes(ApprovalDecisionIntent, intent, fact.submissionId)
3482
+
3483
+ const approvals = new Map(stored.approvalDecisions).set(fact.toolCallId, intent)
3484
+
3485
+ withSubmission(staged, { ...stored, approvalDecisions: approvals })
3486
+ }
3487
+ for (const fact of page.archive.commands.resolutions) {
3488
+ const stored = staged.submissions.get(fact.submissionId)
3489
+ const key = JSON.stringify([fact.toolCallId, unknownResolutionKind(fact.resolution)])
3490
+
3491
+ if (stored === undefined || stored.unknownResolutions.has(key)) {
3492
+ return yield* invalidThreadArchive(
3493
+ 'Missing admission or duplicate resolution',
3494
+ threadId,
3495
+ )
3496
+ }
3497
+ if (stored.unknownResolutions.size >= MAX_RUN_EVIDENCE_RECORDS) {
3498
+ return yield* invalidThreadArchive(
3499
+ 'Accepted resolutions exceed Run record bounds',
3500
+ threadId,
3501
+ )
3502
+ }
3503
+ const intent = UnknownResolutionIntent.make(fact)
3504
+
3505
+ yield* retainCommandBytes(UnknownResolutionIntent, intent, fact.submissionId)
3506
+
3507
+ const resolutions = new Map(stored.unknownResolutions).set(key, { intent })
3508
+
3509
+ withSubmission(staged, { ...stored, unknownResolutions: resolutions })
3510
+ }
3511
+ }),
3512
+ prepareCommit: Effect.fnUntraced(function*(workerSeal) {
3513
+ let lastQueue = 0
3514
+ let terminalEvidence = workerSeal?.terminal === undefined
3515
+
3516
+ for (const stored of threadRows(staged, threadId)) {
3517
+ const a = toAdmission(stored.row, settledTimes.get(stored.row.submissionId))
3518
+ const rebuilt = yield* rebuildClosedSubmission(a)
3519
+
3520
+ if (
3521
+ rebuilt.settlement !== undefined &&
3522
+ workerTerminalFromRecord(toSnapshot(stored.row), rebuilt.settlement) ===
3523
+ workerSeal?.terminal
3524
+ ) {
3525
+ terminalEvidence = true
3526
+ }
3527
+ withSubmission(staged, fromRebuilt(rebuilt))
3528
+ lastQueue = Math.max(lastQueue, a.queueSequence)
3529
+ }
3530
+ if (!terminalEvidence) {
3531
+ return yield* invalidThreadArchive(
3532
+ 'Worker seal terminal has no exact completed input evidence',
3533
+ threadId,
3534
+ )
3535
+ }
3536
+ if (!Number.isSafeInteger(lastQueue + 1)) {
3537
+ return yield* ThreadImportRejected.make({
3538
+ threadId,
3539
+ reason: 'unsupported-capacity',
3540
+ message: 'Admission queue sequence is exhausted',
3541
+ })
3542
+ }
3543
+
3544
+ return () => {
3545
+ for (const stored of staged.submissions.values()) withSubmission(current, stored)
3546
+ current.lanes.set(threadId, { nextQueueSequence: lastQueue + 1 })
3547
+ if (workerSeal !== undefined) {
3548
+ current.stoppedWorkers.set(threadId, workerSeal.terminal)
3549
+ }
3550
+ }
3551
+ }),
3552
+ }
3553
+ }),
3554
+ })
3555
+
3556
+ return Context.make(SubmissionLedger, ledger).pipe(
3557
+ Context.add(SettlementPublisher, { publish }),
3558
+ )
3559
+ },
3560
+ )
3561
+
3562
+ /** Construction options for the in-memory reference SubmissionLedger. */
3563
+ export interface MemorySubmissionLedgerOptions {
3564
+ /**
3565
+ * Test-only fault seam for `resolveAdmission` (SUB-031): when the effect yields a reason,
3566
+ * the resolution answers `Indeterminate` with it instead of consulting the store — modelling
3567
+ * an authoritative child owner that is temporarily unreachable. `Option.none()` restores the
3568
+ * store-derived answer. Ledger state is never mutated by the fault.
3569
+ */
3570
+ readonly resolveAdmissionFault?: Effect.Effect<Option.Option<string>>
3571
+ }
3572
+
3573
+ /**
3574
+ * In-memory reference SubmissionLedger Layer (durability `non-durable`). All state lives in one
3575
+ * `Ref` owned by the Layer's Scope. Fresh identities use the supplied `SecureRandom` service;
3576
+ * imported identities remain unchanged. No daemon fibers are spawned and no wall clock is consulted.
3577
+ */
3578
+ export const memorySubmissionLedgerLayer = (
3579
+ options: MemorySubmissionLedgerOptions = {},
3580
+ ): Layer.Layer<
3581
+ SubmissionLedger | SettlementPublisher,
3582
+ never,
3583
+ MemoryThreadStoreKernel | SecureRandom.SecureRandom
3584
+ > => Layer.effectContext(makeSubmissionLedger(options))
3585
+
3586
+ export const MemorySubmissionLedgerLive: Layer.Layer<
3587
+ SubmissionLedger | SettlementPublisher,
3588
+ never,
3589
+ MemoryThreadStoreKernel | SecureRandom.SecureRandom
3590
+ > = memorySubmissionLedgerLayer()