@effect-agent/storage-memory 0.0.1-beta.0

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.
@@ -0,0 +1,2227 @@
1
+ import {
2
+ AttemptId,
3
+ ReceiptId,
4
+ SubmissionId,
5
+ ToolCallId,
6
+ type AgentId,
7
+ type ConversationId,
8
+ type SettlementId,
9
+ } from "@effect-agent/core";
10
+ import {
11
+ AbortCommand,
12
+ AdmissionAdmitted,
13
+ AdmissionConflict,
14
+ AdmissionIndeterminate,
15
+ AdmissionNotAdmitted,
16
+ AdmissionRequest,
17
+ AdmissionResult,
18
+ ApprovalConflict,
19
+ ApprovalDecisionCommand,
20
+ ApprovalDecisionIntent,
21
+ AttachChildToReservationRequest,
22
+ BeginChildBudgetReleaseRequest,
23
+ ChildAttachmentSnapshot,
24
+ ChildBudgetReservationRequest,
25
+ ChildBudgetReservationSnapshot,
26
+ ChildReservationConflict,
27
+ ChildSettledNotification,
28
+ Claim,
29
+ ClaimJoiningRequest,
30
+ ClaimRequest,
31
+ DEFAULT_OWNERSHIP_LEASE_DURATION,
32
+ InputAppliedMarker,
33
+ JoinSnapshot,
34
+ JoinedToHost,
35
+ JoiningClaim,
36
+ LedgerCapabilities,
37
+ LedgerError,
38
+ MarkInputAppliedRequest,
39
+ MarkJoinedRequest,
40
+ MarkReadyRequest,
41
+ MarkUnknownRequest,
42
+ OwnershipLost,
43
+ OwnershipRenewal,
44
+ OwnershipSnapshot,
45
+ OwnershipToken,
46
+ ParentLinkage,
47
+ ProducerEpoch,
48
+ QueueSequence,
49
+ RecoverySnapshot,
50
+ RecoverySnapshotRequest,
51
+ ReleaseChildBudgetRequest,
52
+ ReleaseOwnershipRequest,
53
+ RenewOwnershipRequest,
54
+ ReservedChildBudget,
55
+ ReservedSettlement,
56
+ RevertJoiningRequest,
57
+ Settlement,
58
+ SettlementConflict,
59
+ SettlementFinalization,
60
+ SettlementReservation,
61
+ SettlementReservationSnapshot,
62
+ AbortIntent,
63
+ SubmissionLedger,
64
+ SubmissionLookup,
65
+ SubmissionLookupByKey,
66
+ SubmissionSnapshot,
67
+ SuspendRequest,
68
+ SuspensionSnapshot,
69
+ UnknownResolution,
70
+ UnknownResolutionCommand,
71
+ UnknownResolutionConflict,
72
+ UnknownResolutionIntent,
73
+ type ChildReservationId,
74
+ type ChildReservationStatus,
75
+ type ChildSettledOutcome,
76
+ type DefinitionDigests,
77
+ type DeploymentId,
78
+ type Digest,
79
+ type IdempotencyKey,
80
+ type PersistedJson,
81
+ type Principal,
82
+ type ProducerId,
83
+ type RecordEnvelope,
84
+ type SettlementOutcome,
85
+ type SubmissionState,
86
+ type SuspensionOutcome,
87
+ type SuspensionReason,
88
+ } from "@effect-agent/session";
89
+ import { Clock, DateTime, Duration, Effect, Layer, Option, Ref, Schema, Stream } from "effect";
90
+
91
+ const MAX_SUBMISSIONS = 65_536;
92
+
93
+ /**
94
+ * Lifecycle ordering used to advance-but-never-regress the operational state marker: a reclaimed
95
+ * Attempt must not erase progress markers (input-applied, terminalizing) that an earlier Attempt
96
+ * already committed.
97
+ */
98
+ const STATE_RANK: Record<SubmissionState, number> = {
99
+ admitted: 0,
100
+ ready: 1,
101
+ joining: 2,
102
+ joined: 3,
103
+ running: 4,
104
+ "input-applied": 5,
105
+ suspended: 6,
106
+ unknown: 7,
107
+ terminalizing: 8,
108
+ settled: 9,
109
+ };
110
+
111
+ interface SubmissionRow {
112
+ readonly submissionId: SubmissionId;
113
+ readonly conversationId: ConversationId;
114
+ readonly queueSequence: QueueSequence;
115
+ readonly principal: Principal;
116
+ readonly idempotencyKey: IdempotencyKey;
117
+ readonly agentId: AgentId;
118
+ readonly agentDigests: DefinitionDigests;
119
+ readonly deploymentId: DeploymentId;
120
+ readonly inputPayload: PersistedJson;
121
+ readonly inputDigest: Digest;
122
+ readonly receiptId: ReceiptId;
123
+ readonly state: SubmissionState;
124
+ readonly settledOutcome: SettlementOutcome | undefined;
125
+ readonly createdAtMillis: number;
126
+ readonly readyAtMillis: number | undefined;
127
+ /** Immutable child-side lineage recorded at admission (spec §12 step 5). */
128
+ readonly parentLinkage: ParentLinkage | undefined;
129
+ }
130
+
131
+ interface StoredOwnership {
132
+ readonly attemptId: AttemptId;
133
+ readonly ownershipToken: OwnershipToken;
134
+ readonly producerEpoch: ProducerEpoch;
135
+ readonly ownerProducerId: ProducerId;
136
+ readonly leaseExpiresAtMillis: number;
137
+ }
138
+
139
+ interface StoredReservation {
140
+ readonly settlementId: SettlementId;
141
+ readonly outcome: SettlementOutcome;
142
+ readonly record: RecordEnvelope;
143
+ readonly recordDigest: Digest;
144
+ readonly finalizedAtMillis: number | undefined;
145
+ }
146
+
147
+ interface StoredSuspension {
148
+ readonly reason: SuspensionReason;
149
+ readonly suspendedAtMillis: number;
150
+ }
151
+
152
+ interface StoredUnknownMark {
153
+ readonly reason: MarkUnknownRequest["reason"];
154
+ readonly toolCallIds: ReadonlyArray<ToolCallId>;
155
+ }
156
+
157
+ interface StoredUnknownResolution {
158
+ readonly intent: UnknownResolutionIntent;
159
+ /** Canonical JSON of the Schema-encoded resolution, for divergent re-resolution detection. */
160
+ readonly resolutionJson: string;
161
+ }
162
+
163
+ interface StoredSubmission {
164
+ readonly row: SubmissionRow;
165
+ readonly ownership: StoredOwnership | undefined;
166
+ readonly inputApplied: InputAppliedMarker | undefined;
167
+ readonly reservation: StoredReservation | undefined;
168
+ readonly abortIntent: AbortIntent | undefined;
169
+ /** Host linkage recorded at `claimJoining` time; cleared by `revertJoining` (DUR-016). */
170
+ readonly joinedHostSubmissionId: SubmissionId | undefined;
171
+ readonly suspension: StoredSuspension | undefined;
172
+ readonly unknownMark: StoredUnknownMark | undefined;
173
+ readonly approvalDecisions: ReadonlyMap<ToolCallId, ApprovalDecisionIntent>;
174
+ readonly unknownResolutions: ReadonlyMap<ToolCallId, StoredUnknownResolution>;
175
+ }
176
+
177
+ /**
178
+ * States in which `claim` never grants the head: the lane is host-owned (`joining`/`joined`)
179
+ * or durably blocked (`suspended`/`unknown`) rather than worker-claimable.
180
+ */
181
+ const BLOCKED_HEAD_STATES: ReadonlySet<SubmissionState> = new Set([
182
+ "joining",
183
+ "joined",
184
+ "suspended",
185
+ "unknown",
186
+ ]);
187
+
188
+ interface LaneState {
189
+ readonly nextQueueSequence: number;
190
+ readonly producerEpoch: number;
191
+ }
192
+
193
+ /** One parent-owned child budget reservation row (spec §12 steps 2 and 6). */
194
+ interface StoredChildReservation {
195
+ readonly reservationId: ChildReservationId;
196
+ readonly parentSubmissionId: SubmissionId;
197
+ readonly parentToolCallId: ToolCallId;
198
+ readonly childSubmissionId: SubmissionId | undefined;
199
+ readonly status: ChildReservationStatus;
200
+ readonly allocation: PersistedJson;
201
+ /** Canonical JSON of the allocation, for divergent-replay detection. */
202
+ readonly allocationJson: string;
203
+ readonly allocationDigest: Digest;
204
+ readonly accounting: PersistedJson | undefined;
205
+ /** Canonical JSON of the frozen accounting decision, for divergent-freeze detection. */
206
+ readonly accountingJson: string | undefined;
207
+ readonly reservedAtMillis: number;
208
+ readonly releaseBeganAtMillis: number | undefined;
209
+ readonly releasedAtMillis: number | undefined;
210
+ }
211
+
212
+ interface LedgerState {
213
+ readonly submissions: ReadonlyMap<SubmissionId, StoredSubmission>;
214
+ readonly admissionIndex: ReadonlyMap<string, SubmissionId>;
215
+ readonly lanes: ReadonlyMap<ConversationId, LaneState>;
216
+ readonly childReservations: ReadonlyMap<ChildReservationId, StoredChildReservation>;
217
+ readonly mintCounter: number;
218
+ }
219
+
220
+ type Decision<A, E> =
221
+ | { readonly _tag: "failure"; readonly error: E }
222
+ | { readonly _tag: "success"; readonly value: A };
223
+
224
+ const failure = <E>(error: E): Decision<never, E> => ({ _tag: "failure", error });
225
+ const success = <A>(value: A): Decision<A, never> => ({ _tag: "success", value });
226
+
227
+ const ledgerError = (operation: string, message: string, cause?: unknown): LedgerError =>
228
+ cause === undefined
229
+ ? LedgerError.make({ operation, message })
230
+ : LedgerError.make({ operation, message, cause });
231
+
232
+ const validate = Effect.fn("MemorySubmissionLedger.validate")(
233
+ <A, I>(
234
+ schema: Schema.Codec<A, I>,
235
+ operation: string,
236
+ value: unknown,
237
+ ): Effect.Effect<A, LedgerError> =>
238
+ Schema.encodeUnknownEffect(schema)(value).pipe(
239
+ Effect.flatMap(Schema.decodeUnknownEffect(schema)),
240
+ Effect.mapError((error) => ledgerError(operation, `Invalid ${operation} request`, error)),
241
+ ),
242
+ );
243
+
244
+ const decodeSubmissionId = Schema.decodeSync(SubmissionId);
245
+ const decodeReceiptId = Schema.decodeSync(ReceiptId);
246
+ const decodeAttemptId = Schema.decodeSync(AttemptId);
247
+ const decodeOwnershipToken = Schema.decodeSync(OwnershipToken);
248
+ const decodeQueueSequence = Schema.decodeSync(QueueSequence);
249
+ const decodeProducerEpoch = Schema.decodeSync(ProducerEpoch);
250
+
251
+ const utc = (millis: number): DateTime.Utc => DateTime.toUtc(DateTime.makeUnsafe(millis));
252
+
253
+ const admissionKey = (
254
+ conversationId: ConversationId,
255
+ principal: Principal,
256
+ idempotencyKey: IdempotencyKey,
257
+ ): string => `${conversationId}\u001f${principal}\u001f${idempotencyKey}`;
258
+
259
+ const toSnapshot = (row: SubmissionRow): SubmissionSnapshot =>
260
+ SubmissionSnapshot.make({
261
+ submissionId: row.submissionId,
262
+ conversationId: row.conversationId,
263
+ queueSequence: row.queueSequence,
264
+ principal: row.principal,
265
+ idempotencyKey: row.idempotencyKey,
266
+ agentId: row.agentId,
267
+ agentDigests: row.agentDigests,
268
+ deploymentId: row.deploymentId,
269
+ inputPayload: row.inputPayload,
270
+ inputDigest: row.inputDigest,
271
+ receiptId: row.receiptId,
272
+ state: row.state,
273
+ createdAt: utc(row.createdAtMillis),
274
+ ...(row.settledOutcome === undefined ? {} : { settledOutcome: row.settledOutcome }),
275
+ ...(row.readyAtMillis === undefined ? {} : { readyAt: utc(row.readyAtMillis) }),
276
+ ...(row.parentLinkage === undefined ? {} : { parentLinkage: row.parentLinkage }),
277
+ });
278
+
279
+ const toReservationSnapshot = (row: StoredChildReservation): ChildBudgetReservationSnapshot =>
280
+ ChildBudgetReservationSnapshot.make({
281
+ reservationId: row.reservationId,
282
+ parentSubmissionId: row.parentSubmissionId,
283
+ parentToolCallId: row.parentToolCallId,
284
+ status: row.status,
285
+ allocation: row.allocation,
286
+ allocationDigest: row.allocationDigest,
287
+ reservedAt: utc(row.reservedAtMillis),
288
+ ...(row.childSubmissionId === undefined ? {} : { childSubmissionId: row.childSubmissionId }),
289
+ ...(row.accounting === undefined ? {} : { accounting: row.accounting }),
290
+ ...(row.releaseBeganAtMillis === undefined
291
+ ? {}
292
+ : { releaseBeganAt: utc(row.releaseBeganAtMillis) }),
293
+ ...(row.releasedAtMillis === undefined ? {} : { releasedAt: utc(row.releasedAtMillis) }),
294
+ });
295
+
296
+ /** Linkage equality: both absent, or both present naming the same parent Tool Call. */
297
+ const sameParentLinkage = (
298
+ left: ParentLinkage | undefined,
299
+ right: ParentLinkage | undefined,
300
+ ): boolean =>
301
+ left === undefined
302
+ ? right === undefined
303
+ : right !== undefined &&
304
+ left.parentSubmissionId === right.parentSubmissionId &&
305
+ left.parentToolCallId === right.parentToolCallId;
306
+
307
+ const laneEpoch = (state: LedgerState, conversationId: ConversationId): number =>
308
+ state.lanes.get(conversationId)?.producerEpoch ?? 0;
309
+
310
+ const ownershipLost = (state: LedgerState, stored: StoredSubmission): OwnershipLost =>
311
+ OwnershipLost.make({
312
+ submissionId: stored.row.submissionId,
313
+ actualEpoch: decodeProducerEpoch(laneEpoch(state, stored.row.conversationId)),
314
+ });
315
+
316
+ /** The presented token owns the lane only while it matches the live ownership record. */
317
+ const ownsLane = (stored: StoredSubmission, ownershipToken: OwnershipToken): boolean =>
318
+ stored.ownership !== undefined && stored.ownership.ownershipToken === ownershipToken;
319
+
320
+ const withSubmission = (state: LedgerState, stored: StoredSubmission): LedgerState => ({
321
+ ...state,
322
+ submissions: new Map(state.submissions).set(stored.row.submissionId, stored),
323
+ });
324
+
325
+ const withChildReservation = (
326
+ state: LedgerState,
327
+ reservation: StoredChildReservation,
328
+ ): LedgerState => ({
329
+ ...state,
330
+ childReservations: new Map(state.childReservations).set(reservation.reservationId, reservation),
331
+ });
332
+
333
+ const findHead = (
334
+ state: LedgerState,
335
+ conversationId: ConversationId,
336
+ ): StoredSubmission | undefined => {
337
+ let head: StoredSubmission | undefined;
338
+ for (const stored of state.submissions.values()) {
339
+ if (stored.row.conversationId !== conversationId || stored.row.state === "settled") continue;
340
+ if (head === undefined || stored.row.queueSequence < head.row.queueSequence) head = stored;
341
+ }
342
+ return head;
343
+ };
344
+
345
+ /**
346
+ * Reference in-memory SubmissionLedger. It implements the full port contract — atomic idempotent
347
+ * admission, FIFO-head claims, producer-epoch fencing, Clock-driven ownership leases, idempotent
348
+ * settlement reservation/finalization, and durable abort intent — with every transition applied
349
+ * as one atomic `Ref.modify`, but its state does not survive the process (`non-durable`).
350
+ *
351
+ * Adapter-specific semantics within the port's latitude:
352
+ *
353
+ * - Time comes exclusively from the Effect `Clock` service, so `TestClock` drives lease expiry
354
+ * deterministically; no wall clock is consulted.
355
+ * - The ownership lease is pinned to `DEFAULT_OWNERSHIP_LEASE_DURATION` (D5); durable adapters
356
+ * own the configuration seam.
357
+ * - A live lease blocks claims from other producers only: the same `producerId` may reclaim its
358
+ * own live lease (restart recovery), which supersedes and fences the prior Attempt's token.
359
+ * - Claiming advances `ready` to `running` and otherwise preserves the recorded state, so
360
+ * progress markers from an earlier Attempt survive a reclaim.
361
+ * - `renewOwnership` keeps the token stable (the port allows rotation); a replayed admission
362
+ * reports the Submission's current state alongside the original identities.
363
+ * - `claimJoining` walks the strictly-later queue: rows already `joining`/`joined` to the
364
+ * SAME host extend the claimed prefix and are skipped, and an aborted-settled row is a
365
+ * closed obligation that is also skipped (P7 §7(c)); any other non-`ready` row (an
366
+ * `admitted` gap, a non-aborted settled row, foreign-host linkage) breaks the prefix
367
+ * conservatively.
368
+ * - `markJoined` verifies the token against the HOST's live ownership (the lane is
369
+ * host-owned), so a later host Attempt can repair a lost marker from history (DUR-016). The
370
+ * join marker reuses the input-applied marker: the joined input IS `input:{sid}`.
371
+ * - `suspend` and `markUnknown` refuse when an exact settlement is already reserved
372
+ * (`SettlementConflict` with the reserved outcome) — DUR-011's reservation wins.
373
+ * - `resolveAdmission` derives its answer from the single strongly consistent store, so it
374
+ * never answers `Indeterminate` on its own; the test-only `resolveAdmissionFault` option
375
+ * injects the `Indeterminate` classification so SUB-031 callers can be conformance-tested.
376
+ * - `recordChildSettled` and `suspend(WaitingForChild)` observe child settlement directly from
377
+ * the child rows (single-store latitude); no separate notification marker is stored.
378
+ */
379
+ const makeSubmissionLedger = (options: MemorySubmissionLedgerOptions = {}) =>
380
+ Effect.gen(function* () {
381
+ const state = yield* Ref.make<LedgerState>({
382
+ submissions: new Map(),
383
+ admissionIndex: new Map(),
384
+ lanes: new Map(),
385
+ childReservations: new Map(),
386
+ mintCounter: 0,
387
+ });
388
+ const leaseMillis = Duration.toMillis(DEFAULT_OWNERSHIP_LEASE_DURATION);
389
+
390
+ const capabilities = Effect.succeed(LedgerCapabilities.make({ durability: "non-durable" }));
391
+
392
+ const admit: SubmissionLedger["Service"]["admit"] = Effect.fn("MemorySubmissionLedger.admit")(
393
+ (unvalidated) =>
394
+ Effect.gen(function* () {
395
+ const request = yield* validate(AdmissionRequest, "admit", unvalidated);
396
+ const nowMillis = yield* Clock.currentTimeMillis;
397
+ const decision = yield* Ref.modify(
398
+ state,
399
+ (
400
+ current,
401
+ ): readonly [
402
+ Decision<AdmissionResult, AdmissionConflict | LedgerError>,
403
+ LedgerState,
404
+ ] => {
405
+ const key = admissionKey(
406
+ request.conversationId,
407
+ request.principal,
408
+ request.idempotencyKey,
409
+ );
410
+ const existingId = current.admissionIndex.get(key);
411
+ if (existingId !== undefined) {
412
+ const existing = current.submissions.get(existingId);
413
+ if (existing === undefined) {
414
+ return [
415
+ failure(
416
+ ledgerError("admit", "Admission index references a missing Submission"),
417
+ ),
418
+ current,
419
+ ];
420
+ }
421
+ // A replay must repeat the exact canonical input AND the exact parent linkage
422
+ // (or its absence): linkage is immutable lineage (spec §12 step 5, SUB-016).
423
+ if (
424
+ existing.row.inputDigest !== request.inputDigest ||
425
+ !sameParentLinkage(existing.row.parentLinkage, request.parentLinkage)
426
+ ) {
427
+ return [
428
+ failure(
429
+ AdmissionConflict.make({
430
+ conversationId: request.conversationId,
431
+ principal: request.principal,
432
+ idempotencyKey: request.idempotencyKey,
433
+ existingInputDigest: existing.row.inputDigest,
434
+ attemptedInputDigest: request.inputDigest,
435
+ }),
436
+ ),
437
+ current,
438
+ ];
439
+ }
440
+ return [
441
+ success(
442
+ AdmissionResult.make({
443
+ submissionId: existing.row.submissionId,
444
+ receiptId: existing.row.receiptId,
445
+ queueSequence: existing.row.queueSequence,
446
+ state: existing.row.state,
447
+ replayed: true,
448
+ }),
449
+ ),
450
+ current,
451
+ ];
452
+ }
453
+ if (current.submissions.size >= MAX_SUBMISSIONS) {
454
+ return [
455
+ failure(
456
+ ledgerError("admit", `In-memory submission limit ${MAX_SUBMISSIONS} exceeded`),
457
+ ),
458
+ current,
459
+ ];
460
+ }
461
+ const lane = current.lanes.get(request.conversationId) ?? {
462
+ nextQueueSequence: 1,
463
+ producerEpoch: 0,
464
+ };
465
+ const mintCounter = current.mintCounter + 1;
466
+ const row: SubmissionRow = {
467
+ submissionId: decodeSubmissionId(`submission-memory-${mintCounter}`),
468
+ conversationId: request.conversationId,
469
+ queueSequence: decodeQueueSequence(lane.nextQueueSequence),
470
+ principal: request.principal,
471
+ idempotencyKey: request.idempotencyKey,
472
+ agentId: request.agentId,
473
+ agentDigests: request.agentDigests,
474
+ deploymentId: request.deploymentId,
475
+ inputPayload: request.inputPayload,
476
+ inputDigest: request.inputDigest,
477
+ receiptId: decodeReceiptId(`receipt-memory-${mintCounter}`),
478
+ state: "admitted",
479
+ settledOutcome: undefined,
480
+ createdAtMillis: nowMillis,
481
+ readyAtMillis: undefined,
482
+ parentLinkage: request.parentLinkage,
483
+ };
484
+ const submissions = new Map(current.submissions).set(row.submissionId, {
485
+ row,
486
+ ownership: undefined,
487
+ inputApplied: undefined,
488
+ reservation: undefined,
489
+ abortIntent: undefined,
490
+ joinedHostSubmissionId: undefined,
491
+ suspension: undefined,
492
+ unknownMark: undefined,
493
+ approvalDecisions: new Map<ToolCallId, ApprovalDecisionIntent>(),
494
+ unknownResolutions: new Map<ToolCallId, StoredUnknownResolution>(),
495
+ });
496
+ const admissionIndex = new Map(current.admissionIndex).set(key, row.submissionId);
497
+ const lanes = new Map(current.lanes).set(request.conversationId, {
498
+ nextQueueSequence: lane.nextQueueSequence + 1,
499
+ producerEpoch: lane.producerEpoch,
500
+ });
501
+ return [
502
+ success(
503
+ AdmissionResult.make({
504
+ submissionId: row.submissionId,
505
+ receiptId: row.receiptId,
506
+ queueSequence: row.queueSequence,
507
+ state: row.state,
508
+ replayed: false,
509
+ }),
510
+ ),
511
+ { ...current, submissions, admissionIndex, lanes, mintCounter },
512
+ ];
513
+ },
514
+ );
515
+ if (decision._tag === "failure") return yield* decision.error;
516
+ return decision.value;
517
+ }),
518
+ );
519
+
520
+ const markReady: SubmissionLedger["Service"]["markReady"] = Effect.fn(
521
+ "MemorySubmissionLedger.markReady",
522
+ )((unvalidated) =>
523
+ Effect.gen(function* () {
524
+ const request = yield* validate(MarkReadyRequest, "markReady", unvalidated);
525
+ const nowMillis = yield* Clock.currentTimeMillis;
526
+ const decision = yield* Ref.modify(
527
+ state,
528
+ (current): readonly [Decision<void, LedgerError>, LedgerState] => {
529
+ const stored = current.submissions.get(request.submissionId);
530
+ if (stored === undefined) {
531
+ return [
532
+ failure(ledgerError("markReady", `Unknown Submission ${request.submissionId}`)),
533
+ current,
534
+ ];
535
+ }
536
+ if (stored.row.state !== "admitted") return [success(undefined), current];
537
+ return [
538
+ success(undefined),
539
+ withSubmission(current, {
540
+ ...stored,
541
+ row: { ...stored.row, state: "ready", readyAtMillis: nowMillis },
542
+ }),
543
+ ];
544
+ },
545
+ );
546
+ if (decision._tag === "failure") return yield* decision.error;
547
+ }),
548
+ );
549
+
550
+ const lookup: SubmissionLedger["Service"]["lookup"] = Effect.fn(
551
+ "MemorySubmissionLedger.lookup",
552
+ )((unvalidated) =>
553
+ Effect.gen(function* () {
554
+ const request = yield* validate(SubmissionLookup, "lookup", unvalidated);
555
+ const current = yield* Ref.get(state);
556
+ const submissionId =
557
+ request._tag === "SubmissionLookupById"
558
+ ? request.submissionId
559
+ : current.admissionIndex.get(
560
+ admissionKey(request.conversationId, request.principal, request.idempotencyKey),
561
+ );
562
+ const stored =
563
+ submissionId === undefined ? undefined : current.submissions.get(submissionId);
564
+ return stored === undefined ? Option.none() : Option.some(toSnapshot(stored.row));
565
+ }),
566
+ );
567
+
568
+ const resolveAdmission: SubmissionLedger["Service"]["resolveAdmission"] = Effect.fn(
569
+ "MemorySubmissionLedger.resolveAdmission",
570
+ )((unvalidated) =>
571
+ Effect.gen(function* () {
572
+ const request = yield* validate(SubmissionLookupByKey, "resolveAdmission", unvalidated);
573
+ // Test-only fault seam: lets suites exercise the Indeterminate classification that a
574
+ // single strongly consistent store never produces on its own (SUB-031, P6 honesty).
575
+ if (options.resolveAdmissionFault !== undefined) {
576
+ const fault = yield* options.resolveAdmissionFault;
577
+ if (Option.isSome(fault)) {
578
+ return AdmissionIndeterminate.make({ reason: fault.value });
579
+ }
580
+ }
581
+ const current = yield* Ref.get(state);
582
+ const submissionId = current.admissionIndex.get(
583
+ admissionKey(request.conversationId, request.principal, request.idempotencyKey),
584
+ );
585
+ const stored =
586
+ submissionId === undefined ? undefined : current.submissions.get(submissionId);
587
+ return stored === undefined
588
+ ? AdmissionNotAdmitted.make()
589
+ : AdmissionAdmitted.make({ submission: toSnapshot(stored.row) });
590
+ }),
591
+ );
592
+
593
+ const claim: SubmissionLedger["Service"]["claim"] = Effect.fn("MemorySubmissionLedger.claim")(
594
+ (unvalidated) =>
595
+ Effect.gen(function* () {
596
+ const request = yield* validate(ClaimRequest, "claim", unvalidated);
597
+ const nowMillis = yield* Clock.currentTimeMillis;
598
+ const decision = yield* Ref.modify(
599
+ state,
600
+ (current): readonly [Decision<Option.Option<Claim>, LedgerError>, LedgerState] => {
601
+ const head = findHead(current, request.conversationId);
602
+ if (head === undefined) return [success(Option.none()), current];
603
+ // A joining/joined head is host-owned and a suspended/unknown head is durably
604
+ // blocked; the lane produces no claim and later ready work is never skipped.
605
+ if (BLOCKED_HEAD_STATES.has(head.row.state)) return [success(Option.none()), current];
606
+ if (
607
+ head.ownership !== undefined &&
608
+ head.ownership.leaseExpiresAtMillis > nowMillis &&
609
+ head.ownership.ownerProducerId !== request.producerId
610
+ ) {
611
+ return [success(Option.none()), current];
612
+ }
613
+ const lane = current.lanes.get(request.conversationId);
614
+ if (lane === undefined) {
615
+ return [
616
+ failure(ledgerError("claim", "Claimable head without a Conversation lane")),
617
+ current,
618
+ ];
619
+ }
620
+ const producerEpoch = decodeProducerEpoch(lane.producerEpoch + 1);
621
+ const mintCounter = current.mintCounter + 1;
622
+ const ownership: StoredOwnership = {
623
+ attemptId: decodeAttemptId(`attempt-memory-${mintCounter}`),
624
+ ownershipToken: decodeOwnershipToken(`ownership-memory-${mintCounter}`),
625
+ producerEpoch,
626
+ ownerProducerId: request.producerId,
627
+ leaseExpiresAtMillis: nowMillis + leaseMillis,
628
+ };
629
+ const row: SubmissionRow =
630
+ head.row.state === "ready" ? { ...head.row, state: "running" } : head.row;
631
+ const next = withSubmission(current, { ...head, row, ownership });
632
+ const lanes = new Map(next.lanes).set(request.conversationId, {
633
+ nextQueueSequence: lane.nextQueueSequence,
634
+ producerEpoch: lane.producerEpoch + 1,
635
+ });
636
+ return [
637
+ success(
638
+ Option.some(
639
+ Claim.make({
640
+ submissionId: row.submissionId,
641
+ attemptId: ownership.attemptId,
642
+ ownershipToken: ownership.ownershipToken,
643
+ producerEpoch,
644
+ leaseExpiresAt: utc(ownership.leaseExpiresAtMillis),
645
+ inputPayload: row.inputPayload,
646
+ }),
647
+ ),
648
+ ),
649
+ { ...next, lanes, mintCounter },
650
+ ];
651
+ },
652
+ );
653
+ if (decision._tag === "failure") return yield* decision.error;
654
+ return decision.value;
655
+ }),
656
+ );
657
+
658
+ const renewOwnership: SubmissionLedger["Service"]["renewOwnership"] = Effect.fn(
659
+ "MemorySubmissionLedger.renewOwnership",
660
+ )((unvalidated) =>
661
+ Effect.gen(function* () {
662
+ const request = yield* validate(RenewOwnershipRequest, "renewOwnership", unvalidated);
663
+ const nowMillis = yield* Clock.currentTimeMillis;
664
+ const decision = yield* Ref.modify(
665
+ state,
666
+ (
667
+ current,
668
+ ): readonly [Decision<OwnershipRenewal, OwnershipLost | LedgerError>, LedgerState] => {
669
+ const stored = current.submissions.get(request.submissionId);
670
+ if (stored === undefined) {
671
+ return [
672
+ failure(
673
+ ledgerError("renewOwnership", `Unknown Submission ${request.submissionId}`),
674
+ ),
675
+ current,
676
+ ];
677
+ }
678
+ if (stored.ownership === undefined || !ownsLane(stored, request.ownershipToken)) {
679
+ return [failure(ownershipLost(current, stored)), current];
680
+ }
681
+ const ownership: StoredOwnership = {
682
+ ...stored.ownership,
683
+ leaseExpiresAtMillis: nowMillis + leaseMillis,
684
+ };
685
+ return [
686
+ success(
687
+ OwnershipRenewal.make({
688
+ ownershipToken: ownership.ownershipToken,
689
+ leaseExpiresAt: utc(ownership.leaseExpiresAtMillis),
690
+ }),
691
+ ),
692
+ withSubmission(current, { ...stored, ownership }),
693
+ ];
694
+ },
695
+ );
696
+ if (decision._tag === "failure") return yield* decision.error;
697
+ return decision.value;
698
+ }),
699
+ );
700
+
701
+ const releaseOwnership: SubmissionLedger["Service"]["releaseOwnership"] = Effect.fn(
702
+ "MemorySubmissionLedger.releaseOwnership",
703
+ )((unvalidated) =>
704
+ Effect.gen(function* () {
705
+ const request = yield* validate(ReleaseOwnershipRequest, "releaseOwnership", unvalidated);
706
+ const decision = yield* Ref.modify(
707
+ state,
708
+ (current): readonly [Decision<void, OwnershipLost | LedgerError>, LedgerState] => {
709
+ const stored = current.submissions.get(request.submissionId);
710
+ if (stored === undefined) {
711
+ return [
712
+ failure(
713
+ ledgerError("releaseOwnership", `Unknown Submission ${request.submissionId}`),
714
+ ),
715
+ current,
716
+ ];
717
+ }
718
+ if (!ownsLane(stored, request.ownershipToken)) {
719
+ return [failure(ownershipLost(current, stored)), current];
720
+ }
721
+ return [
722
+ success(undefined),
723
+ withSubmission(current, { ...stored, ownership: undefined }),
724
+ ];
725
+ },
726
+ );
727
+ if (decision._tag === "failure") return yield* decision.error;
728
+ }),
729
+ );
730
+
731
+ const markInputApplied: SubmissionLedger["Service"]["markInputApplied"] = Effect.fn(
732
+ "MemorySubmissionLedger.markInputApplied",
733
+ )((unvalidated) =>
734
+ Effect.gen(function* () {
735
+ const request = yield* validate(MarkInputAppliedRequest, "markInputApplied", unvalidated);
736
+ const decision = yield* Ref.modify(
737
+ state,
738
+ (current): readonly [Decision<void, OwnershipLost | LedgerError>, LedgerState] => {
739
+ const stored = current.submissions.get(request.submissionId);
740
+ if (stored === undefined) {
741
+ return [
742
+ failure(
743
+ ledgerError("markInputApplied", `Unknown Submission ${request.submissionId}`),
744
+ ),
745
+ current,
746
+ ];
747
+ }
748
+ if (!ownsLane(stored, request.ownershipToken)) {
749
+ return [failure(ownershipLost(current, stored)), current];
750
+ }
751
+ const marker = InputAppliedMarker.make({
752
+ recordId: request.recordId,
753
+ sequence: request.sequence,
754
+ });
755
+ const row: SubmissionRow =
756
+ STATE_RANK[stored.row.state] < STATE_RANK["input-applied"]
757
+ ? { ...stored.row, state: "input-applied" }
758
+ : stored.row;
759
+ return [
760
+ success(undefined),
761
+ withSubmission(current, { ...stored, row, inputApplied: marker }),
762
+ ];
763
+ },
764
+ );
765
+ if (decision._tag === "failure") return yield* decision.error;
766
+ }),
767
+ );
768
+
769
+ const reserveSettlement: SubmissionLedger["Service"]["reserveSettlement"] = Effect.fn(
770
+ "MemorySubmissionLedger.reserveSettlement",
771
+ )((unvalidated) =>
772
+ Effect.gen(function* () {
773
+ const request = yield* validate(SettlementReservation, "reserveSettlement", unvalidated);
774
+ const decision = yield* Ref.modify(
775
+ state,
776
+ (
777
+ current,
778
+ ): readonly [
779
+ Decision<ReservedSettlement, SettlementConflict | OwnershipLost | LedgerError>,
780
+ LedgerState,
781
+ ] => {
782
+ const stored = current.submissions.get(request.submissionId);
783
+ if (stored === undefined) {
784
+ return [
785
+ failure(
786
+ ledgerError("reserveSettlement", `Unknown Submission ${request.submissionId}`),
787
+ ),
788
+ current,
789
+ ];
790
+ }
791
+ // A `joined` Submission settles WITH its host (plan §2.5) and its lane is never
792
+ // worker-claimable, so no ownership token can exist for it: the recorded host
793
+ // linkage authorizes the reservation and the presented token is not consulted.
794
+ const joinedSettlement =
795
+ stored.row.state === "joined" && stored.joinedHostSubmissionId !== undefined;
796
+ // P7 §7(c): an aborted, never-claimed, still-queued Submission likewise has no
797
+ // live ownership to fence against — its durable abort intent authorizes exactly
798
+ // its ABORTED settlement (`terminalizing` is the same pass's crash replay). Every
799
+ // other reservation stays fenced by the target lane's live ownership.
800
+ const queuedAbortSettlement =
801
+ request.outcome === "aborted" &&
802
+ stored.abortIntent !== undefined &&
803
+ stored.ownership === undefined &&
804
+ (stored.row.state === "ready" || stored.row.state === "terminalizing");
805
+ if (
806
+ !joinedSettlement &&
807
+ !queuedAbortSettlement &&
808
+ !ownsLane(stored, request.ownershipToken)
809
+ ) {
810
+ return [failure(ownershipLost(current, stored)), current];
811
+ }
812
+ const existing = stored.reservation;
813
+ if (existing !== undefined) {
814
+ if (
815
+ existing.settlementId !== request.settlementId ||
816
+ existing.outcome !== request.outcome ||
817
+ existing.recordDigest !== request.recordDigest
818
+ ) {
819
+ return [
820
+ failure(
821
+ SettlementConflict.make({
822
+ submissionId: request.submissionId,
823
+ existingOutcome: existing.outcome,
824
+ }),
825
+ ),
826
+ current,
827
+ ];
828
+ }
829
+ return [
830
+ success(
831
+ ReservedSettlement.make({
832
+ submissionId: request.submissionId,
833
+ settlementId: existing.settlementId,
834
+ outcome: existing.outcome,
835
+ record: existing.record,
836
+ recordDigest: existing.recordDigest,
837
+ replayed: true,
838
+ }),
839
+ ),
840
+ current,
841
+ ];
842
+ }
843
+ const reservation: StoredReservation = {
844
+ settlementId: request.settlementId,
845
+ outcome: request.outcome,
846
+ record: request.record,
847
+ recordDigest: request.recordDigest,
848
+ finalizedAtMillis: undefined,
849
+ };
850
+ const row: SubmissionRow =
851
+ STATE_RANK[stored.row.state] < STATE_RANK.terminalizing
852
+ ? { ...stored.row, state: "terminalizing" }
853
+ : stored.row;
854
+ return [
855
+ success(
856
+ ReservedSettlement.make({
857
+ submissionId: request.submissionId,
858
+ settlementId: reservation.settlementId,
859
+ outcome: reservation.outcome,
860
+ record: reservation.record,
861
+ recordDigest: reservation.recordDigest,
862
+ replayed: false,
863
+ }),
864
+ ),
865
+ withSubmission(current, { ...stored, row, reservation }),
866
+ ];
867
+ },
868
+ );
869
+ if (decision._tag === "failure") return yield* decision.error;
870
+ return decision.value;
871
+ }),
872
+ );
873
+
874
+ const finalizeSettlement: SubmissionLedger["Service"]["finalizeSettlement"] = Effect.fn(
875
+ "MemorySubmissionLedger.finalizeSettlement",
876
+ )((unvalidated) =>
877
+ Effect.gen(function* () {
878
+ const request = yield* validate(SettlementFinalization, "finalizeSettlement", unvalidated);
879
+ const nowMillis = yield* Clock.currentTimeMillis;
880
+ const decision = yield* Ref.modify(
881
+ state,
882
+ (
883
+ current,
884
+ ): readonly [Decision<Settlement, SettlementConflict | LedgerError>, LedgerState] => {
885
+ const stored = current.submissions.get(request.submissionId);
886
+ if (stored === undefined) {
887
+ return [
888
+ failure(
889
+ ledgerError("finalizeSettlement", `Unknown Submission ${request.submissionId}`),
890
+ ),
891
+ current,
892
+ ];
893
+ }
894
+ const reservation = stored.reservation;
895
+ if (reservation === undefined) {
896
+ return [
897
+ failure(
898
+ ledgerError(
899
+ "finalizeSettlement",
900
+ `No settlement reservation for Submission ${request.submissionId}`,
901
+ ),
902
+ ),
903
+ current,
904
+ ];
905
+ }
906
+ if (reservation.settlementId !== request.settlementId) {
907
+ return [
908
+ failure(
909
+ SettlementConflict.make({
910
+ submissionId: request.submissionId,
911
+ existingOutcome: reservation.outcome,
912
+ }),
913
+ ),
914
+ current,
915
+ ];
916
+ }
917
+ if (reservation.finalizedAtMillis !== undefined) {
918
+ return [
919
+ success(
920
+ Settlement.make({
921
+ submissionId: stored.row.submissionId,
922
+ settlementId: reservation.settlementId,
923
+ receiptId: stored.row.receiptId,
924
+ outcome: reservation.outcome,
925
+ settledAt: utc(reservation.finalizedAtMillis),
926
+ }),
927
+ ),
928
+ current,
929
+ ];
930
+ }
931
+ const next = withSubmission(current, {
932
+ ...stored,
933
+ row: { ...stored.row, state: "settled", settledOutcome: reservation.outcome },
934
+ ownership: undefined,
935
+ reservation: { ...reservation, finalizedAtMillis: nowMillis },
936
+ });
937
+ return [
938
+ success(
939
+ Settlement.make({
940
+ submissionId: stored.row.submissionId,
941
+ settlementId: reservation.settlementId,
942
+ receiptId: stored.row.receiptId,
943
+ outcome: reservation.outcome,
944
+ settledAt: utc(nowMillis),
945
+ }),
946
+ ),
947
+ next,
948
+ ];
949
+ },
950
+ );
951
+ if (decision._tag === "failure") return yield* decision.error;
952
+ return decision.value;
953
+ }),
954
+ );
955
+
956
+ const requestAbort: SubmissionLedger["Service"]["requestAbort"] = Effect.fn(
957
+ "MemorySubmissionLedger.requestAbort",
958
+ )((unvalidated) =>
959
+ Effect.gen(function* () {
960
+ const request = yield* validate(AbortCommand, "requestAbort", unvalidated);
961
+ const nowMillis = yield* Clock.currentTimeMillis;
962
+ const decision = yield* Ref.modify(
963
+ state,
964
+ (
965
+ current,
966
+ ): readonly [
967
+ Decision<AbortIntent, SettlementConflict | JoinedToHost | LedgerError>,
968
+ LedgerState,
969
+ ] => {
970
+ const stored = current.submissions.get(request.submissionId);
971
+ if (stored === undefined) {
972
+ return [
973
+ failure(ledgerError("requestAbort", `Unknown Submission ${request.submissionId}`)),
974
+ current,
975
+ ];
976
+ }
977
+ // A joined Submission settles WITH its host; the abort target is the host (plan
978
+ // §2.5). A joining Submission still records the intent: it is honored only if the
979
+ // host has not consumed the input (revert-then-abort).
980
+ if (stored.row.state === "joined") {
981
+ if (stored.joinedHostSubmissionId === undefined) {
982
+ return [
983
+ failure(
984
+ ledgerError(
985
+ "requestAbort",
986
+ `Joined Submission ${request.submissionId} is missing its host linkage`,
987
+ ),
988
+ ),
989
+ current,
990
+ ];
991
+ }
992
+ return [
993
+ failure(
994
+ JoinedToHost.make({
995
+ submissionId: request.submissionId,
996
+ hostSubmissionId: stored.joinedHostSubmissionId,
997
+ }),
998
+ ),
999
+ current,
1000
+ ];
1001
+ }
1002
+ if (stored.row.state === "settled") {
1003
+ if (stored.row.settledOutcome === undefined) {
1004
+ return [
1005
+ failure(
1006
+ ledgerError(
1007
+ "requestAbort",
1008
+ `Settled Submission ${request.submissionId} is missing its outcome`,
1009
+ ),
1010
+ ),
1011
+ current,
1012
+ ];
1013
+ }
1014
+ return [
1015
+ failure(
1016
+ SettlementConflict.make({
1017
+ submissionId: request.submissionId,
1018
+ existingOutcome: stored.row.settledOutcome,
1019
+ }),
1020
+ ),
1021
+ current,
1022
+ ];
1023
+ }
1024
+ if (stored.abortIntent !== undefined) return [success(stored.abortIntent), current];
1025
+ const intent = AbortIntent.make({
1026
+ submissionId: request.submissionId,
1027
+ author: request.author,
1028
+ reason: request.reason,
1029
+ requestedAt: utc(nowMillis),
1030
+ });
1031
+ return [success(intent), withSubmission(current, { ...stored, abortIntent: intent })];
1032
+ },
1033
+ );
1034
+ if (decision._tag === "failure") return yield* decision.error;
1035
+ return decision.value;
1036
+ }),
1037
+ );
1038
+
1039
+ const claimJoining: SubmissionLedger["Service"]["claimJoining"] = Effect.fn(
1040
+ "MemorySubmissionLedger.claimJoining",
1041
+ )((unvalidated) =>
1042
+ Effect.gen(function* () {
1043
+ const request = yield* validate(ClaimJoiningRequest, "claimJoining", unvalidated);
1044
+ const decision = yield* Ref.modify(
1045
+ state,
1046
+ (
1047
+ current,
1048
+ ): readonly [
1049
+ Decision<ReadonlyArray<JoiningClaim>, OwnershipLost | LedgerError>,
1050
+ LedgerState,
1051
+ ] => {
1052
+ const host = current.submissions.get(request.hostSubmissionId);
1053
+ if (host === undefined) {
1054
+ return [
1055
+ failure(
1056
+ ledgerError("claimJoining", `Unknown Submission ${request.hostSubmissionId}`),
1057
+ ),
1058
+ current,
1059
+ ];
1060
+ }
1061
+ if (host.row.conversationId !== request.conversationId) {
1062
+ return [
1063
+ failure(
1064
+ ledgerError(
1065
+ "claimJoining",
1066
+ `Host Submission ${request.hostSubmissionId} does not belong to Conversation ${request.conversationId}`,
1067
+ ),
1068
+ ),
1069
+ current,
1070
+ ];
1071
+ }
1072
+ if (!ownsLane(host, request.ownershipToken)) {
1073
+ return [failure(ownershipLost(current, host)), current];
1074
+ }
1075
+ const later = [...current.submissions.values()]
1076
+ .filter(
1077
+ (stored) =>
1078
+ stored.row.conversationId === request.conversationId &&
1079
+ stored.row.queueSequence > host.row.queueSequence,
1080
+ )
1081
+ .sort((left, right) => left.row.queueSequence - right.row.queueSequence);
1082
+ const claims: Array<JoiningClaim> = [];
1083
+ const submissions = new Map(current.submissions);
1084
+ for (const stored of later) {
1085
+ if (claims.length >= request.maxCount) break;
1086
+ // Rows already claimed by THIS host extend its contiguous prefix and are skipped;
1087
+ // the coordinator re-delivers already-joined input through the coverage rule.
1088
+ if (
1089
+ (stored.row.state === "joining" || stored.row.state === "joined") &&
1090
+ stored.joinedHostSubmissionId === request.hostSubmissionId
1091
+ ) {
1092
+ continue;
1093
+ }
1094
+ // P7 §7(c): an aborted-settled row is a CLOSED obligation, not a gap — recovery
1095
+ // settles aborted never-claimed queued work immediately, and settlement order of
1096
+ // never-run work is not execution order (DUR-004 bounds execution).
1097
+ if (stored.row.state === "settled" && stored.row.settledOutcome === "aborted") {
1098
+ continue;
1099
+ }
1100
+ // Any other non-ready row — an admitted-not-ready gap in particular — breaks the
1101
+ // contiguous ready prefix (plan §2.5); later ready work stays queued (DUR-004).
1102
+ if (stored.row.state !== "ready") break;
1103
+ submissions.set(stored.row.submissionId, {
1104
+ ...stored,
1105
+ row: { ...stored.row, state: "joining" },
1106
+ joinedHostSubmissionId: request.hostSubmissionId,
1107
+ });
1108
+ claims.push(
1109
+ JoiningClaim.make({
1110
+ submissionId: stored.row.submissionId,
1111
+ queueSequence: stored.row.queueSequence,
1112
+ inputPayload: stored.row.inputPayload,
1113
+ }),
1114
+ );
1115
+ }
1116
+ return [success(claims), { ...current, submissions }];
1117
+ },
1118
+ );
1119
+ if (decision._tag === "failure") return yield* decision.error;
1120
+ return decision.value;
1121
+ }),
1122
+ );
1123
+
1124
+ const markJoined: SubmissionLedger["Service"]["markJoined"] = Effect.fn(
1125
+ "MemorySubmissionLedger.markJoined",
1126
+ )((unvalidated) =>
1127
+ Effect.gen(function* () {
1128
+ const request = yield* validate(MarkJoinedRequest, "markJoined", unvalidated);
1129
+ const decision = yield* Ref.modify(
1130
+ state,
1131
+ (current): readonly [Decision<void, OwnershipLost | LedgerError>, LedgerState] => {
1132
+ const stored = current.submissions.get(request.submissionId);
1133
+ if (stored === undefined) {
1134
+ return [
1135
+ failure(ledgerError("markJoined", `Unknown Submission ${request.submissionId}`)),
1136
+ current,
1137
+ ];
1138
+ }
1139
+ if (stored.joinedHostSubmissionId === undefined) {
1140
+ return [
1141
+ failure(
1142
+ ledgerError(
1143
+ "markJoined",
1144
+ `Submission ${request.submissionId} was never claimed for joining`,
1145
+ ),
1146
+ ),
1147
+ current,
1148
+ ];
1149
+ }
1150
+ const host = current.submissions.get(stored.joinedHostSubmissionId);
1151
+ if (host === undefined) {
1152
+ return [
1153
+ failure(
1154
+ ledgerError(
1155
+ "markJoined",
1156
+ `Host Submission ${stored.joinedHostSubmissionId} is missing`,
1157
+ ),
1158
+ ),
1159
+ current,
1160
+ ];
1161
+ }
1162
+ // The lane is host-owned: the presented token must own the HOST's ownership period,
1163
+ // which also lets a later host Attempt repair a lost marker from history (DUR-016).
1164
+ if (!ownsLane(host, request.ownershipToken)) {
1165
+ return [failure(ownershipLost(current, host)), current];
1166
+ }
1167
+ if (stored.inputApplied !== undefined) {
1168
+ if (
1169
+ stored.inputApplied.recordId === request.recordId &&
1170
+ stored.inputApplied.sequence === request.sequence
1171
+ ) {
1172
+ return [success(undefined), current];
1173
+ }
1174
+ return [
1175
+ failure(
1176
+ ledgerError(
1177
+ "markJoined",
1178
+ `A different join marker is already recorded for Submission ${request.submissionId}`,
1179
+ ),
1180
+ ),
1181
+ current,
1182
+ ];
1183
+ }
1184
+ if (stored.row.state !== "joining" && stored.row.state !== "joined") {
1185
+ return [
1186
+ failure(
1187
+ ledgerError(
1188
+ "markJoined",
1189
+ `Cannot mark Submission ${request.submissionId} joined from state ${stored.row.state}`,
1190
+ ),
1191
+ ),
1192
+ current,
1193
+ ];
1194
+ }
1195
+ const marker = InputAppliedMarker.make({
1196
+ recordId: request.recordId,
1197
+ sequence: request.sequence,
1198
+ });
1199
+ return [
1200
+ success(undefined),
1201
+ withSubmission(current, {
1202
+ ...stored,
1203
+ row: { ...stored.row, state: "joined" },
1204
+ inputApplied: marker,
1205
+ }),
1206
+ ];
1207
+ },
1208
+ );
1209
+ if (decision._tag === "failure") return yield* decision.error;
1210
+ }),
1211
+ );
1212
+
1213
+ const revertJoining: SubmissionLedger["Service"]["revertJoining"] = Effect.fn(
1214
+ "MemorySubmissionLedger.revertJoining",
1215
+ )((unvalidated) =>
1216
+ Effect.gen(function* () {
1217
+ const request = yield* validate(RevertJoiningRequest, "revertJoining", unvalidated);
1218
+ const decision = yield* Ref.modify(
1219
+ state,
1220
+ (current): readonly [Decision<void, LedgerError>, LedgerState] => {
1221
+ const stored = current.submissions.get(request.submissionId);
1222
+ if (stored === undefined) {
1223
+ return [
1224
+ failure(ledgerError("revertJoining", `Unknown Submission ${request.submissionId}`)),
1225
+ current,
1226
+ ];
1227
+ }
1228
+ // Idempotent and recovery-only: only a still-`joining` Submission reverts; an
1229
+ // already-joined (or already-reverted) Submission is a no-op (DUR-016).
1230
+ if (stored.row.state !== "joining") return [success(undefined), current];
1231
+ return [
1232
+ success(undefined),
1233
+ withSubmission(current, {
1234
+ ...stored,
1235
+ row: { ...stored.row, state: "ready" },
1236
+ joinedHostSubmissionId: undefined,
1237
+ }),
1238
+ ];
1239
+ },
1240
+ );
1241
+ if (decision._tag === "failure") return yield* decision.error;
1242
+ }),
1243
+ );
1244
+
1245
+ const suspend: SubmissionLedger["Service"]["suspend"] = Effect.fn(
1246
+ "MemorySubmissionLedger.suspend",
1247
+ )((unvalidated) =>
1248
+ Effect.gen(function* () {
1249
+ const request = yield* validate(SuspendRequest, "suspend", unvalidated);
1250
+ const nowMillis = yield* Clock.currentTimeMillis;
1251
+ const decision = yield* Ref.modify(
1252
+ state,
1253
+ (
1254
+ current,
1255
+ ): readonly [
1256
+ Decision<SuspensionOutcome, OwnershipLost | SettlementConflict | LedgerError>,
1257
+ LedgerState,
1258
+ ] => {
1259
+ const stored = current.submissions.get(request.submissionId);
1260
+ if (stored === undefined) {
1261
+ return [
1262
+ failure(ledgerError("suspend", `Unknown Submission ${request.submissionId}`)),
1263
+ current,
1264
+ ];
1265
+ }
1266
+ if (stored.row.state === "settled") {
1267
+ if (stored.row.settledOutcome === undefined) {
1268
+ return [
1269
+ failure(
1270
+ ledgerError(
1271
+ "suspend",
1272
+ `Settled Submission ${request.submissionId} is missing its outcome`,
1273
+ ),
1274
+ ),
1275
+ current,
1276
+ ];
1277
+ }
1278
+ return [
1279
+ failure(
1280
+ SettlementConflict.make({
1281
+ submissionId: request.submissionId,
1282
+ existingOutcome: stored.row.settledOutcome,
1283
+ }),
1284
+ ),
1285
+ current,
1286
+ ];
1287
+ }
1288
+ // An exact terminal outcome is already reserved (DUR-011); suspension would
1289
+ // contradict it, so the reservation wins.
1290
+ if (stored.reservation !== undefined) {
1291
+ return [
1292
+ failure(
1293
+ SettlementConflict.make({
1294
+ submissionId: request.submissionId,
1295
+ existingOutcome: stored.reservation.outcome,
1296
+ }),
1297
+ ),
1298
+ current,
1299
+ ];
1300
+ }
1301
+ if (!ownsLane(stored, request.ownershipToken)) {
1302
+ return [failure(ownershipLost(current, stored)), current];
1303
+ }
1304
+ // A covering event that raced ahead of the suspend transaction (an approval decision,
1305
+ // or a child settlement observed directly from the child's row in this single store)
1306
+ // resumes the caller immediately WITHOUT releasing the lane (plan §2.6, spec §12).
1307
+ const alreadyCovered =
1308
+ request.reason._tag === "ApprovalPending"
1309
+ ? request.reason.toolCallIds.every((toolCallId) =>
1310
+ stored.approvalDecisions.has(toolCallId),
1311
+ )
1312
+ : request.reason.children.every(
1313
+ (child) =>
1314
+ current.submissions.get(child.childSubmissionId)?.row.state === "settled",
1315
+ );
1316
+ if (alreadyCovered) {
1317
+ return [success("resume-immediately" as const), current];
1318
+ }
1319
+ return [
1320
+ success("suspended" as const),
1321
+ withSubmission(current, {
1322
+ ...stored,
1323
+ row: { ...stored.row, state: "suspended" },
1324
+ ownership: undefined,
1325
+ suspension: { reason: request.reason, suspendedAtMillis: nowMillis },
1326
+ }),
1327
+ ];
1328
+ },
1329
+ );
1330
+ if (decision._tag === "failure") return yield* decision.error;
1331
+ return decision.value;
1332
+ }),
1333
+ );
1334
+
1335
+ const recordApprovalDecision: SubmissionLedger["Service"]["recordApprovalDecision"] = Effect.fn(
1336
+ "MemorySubmissionLedger.recordApprovalDecision",
1337
+ )((unvalidated) =>
1338
+ Effect.gen(function* () {
1339
+ const command = yield* validate(
1340
+ ApprovalDecisionCommand,
1341
+ "recordApprovalDecision",
1342
+ unvalidated,
1343
+ );
1344
+ const nowMillis = yield* Clock.currentTimeMillis;
1345
+ const decision = yield* Ref.modify(
1346
+ state,
1347
+ (
1348
+ current,
1349
+ ): readonly [
1350
+ Decision<ApprovalDecisionIntent, ApprovalConflict | SettlementConflict | LedgerError>,
1351
+ LedgerState,
1352
+ ] => {
1353
+ const stored = current.submissions.get(command.submissionId);
1354
+ if (stored === undefined) {
1355
+ return [
1356
+ failure(
1357
+ ledgerError(
1358
+ "recordApprovalDecision",
1359
+ `Unknown Submission ${command.submissionId}`,
1360
+ ),
1361
+ ),
1362
+ current,
1363
+ ];
1364
+ }
1365
+ if (stored.row.state === "settled") {
1366
+ if (stored.row.settledOutcome === undefined) {
1367
+ return [
1368
+ failure(
1369
+ ledgerError(
1370
+ "recordApprovalDecision",
1371
+ `Settled Submission ${command.submissionId} is missing its outcome`,
1372
+ ),
1373
+ ),
1374
+ current,
1375
+ ];
1376
+ }
1377
+ return [
1378
+ failure(
1379
+ SettlementConflict.make({
1380
+ submissionId: command.submissionId,
1381
+ existingOutcome: stored.row.settledOutcome,
1382
+ }),
1383
+ ),
1384
+ current,
1385
+ ];
1386
+ }
1387
+ const existing = stored.approvalDecisions.get(command.toolCallId);
1388
+ if (existing !== undefined) {
1389
+ if (existing.decision !== command.decision) {
1390
+ return [
1391
+ failure(
1392
+ ApprovalConflict.make({
1393
+ submissionId: command.submissionId,
1394
+ toolCallId: command.toolCallId,
1395
+ existingDecision: existing.decision,
1396
+ }),
1397
+ ),
1398
+ current,
1399
+ ];
1400
+ }
1401
+ return [success(existing), current];
1402
+ }
1403
+ const intent = ApprovalDecisionIntent.make({
1404
+ submissionId: command.submissionId,
1405
+ toolCallId: command.toolCallId,
1406
+ decision: command.decision,
1407
+ resolver: command.resolver,
1408
+ reason: command.reason,
1409
+ decidedAt: utc(nowMillis),
1410
+ });
1411
+ const approvalDecisions = new Map(stored.approvalDecisions).set(
1412
+ command.toolCallId,
1413
+ intent,
1414
+ );
1415
+ // Once every pending call of an ApprovalPending suspension is decided, the lane
1416
+ // wakes: suspended → input-applied (plan §2.6). A WaitingForChild suspension wakes
1417
+ // only through recordChildSettled.
1418
+ const wakes =
1419
+ stored.row.state === "suspended" &&
1420
+ stored.suspension !== undefined &&
1421
+ stored.suspension.reason._tag === "ApprovalPending" &&
1422
+ stored.suspension.reason.toolCallIds.every((toolCallId) =>
1423
+ approvalDecisions.has(toolCallId),
1424
+ );
1425
+ return [
1426
+ success(intent),
1427
+ withSubmission(current, {
1428
+ ...stored,
1429
+ row: wakes ? { ...stored.row, state: "input-applied" } : stored.row,
1430
+ suspension: wakes ? undefined : stored.suspension,
1431
+ approvalDecisions,
1432
+ }),
1433
+ ];
1434
+ },
1435
+ );
1436
+ if (decision._tag === "failure") return yield* decision.error;
1437
+ return decision.value;
1438
+ }),
1439
+ );
1440
+
1441
+ const markUnknown: SubmissionLedger["Service"]["markUnknown"] = Effect.fn(
1442
+ "MemorySubmissionLedger.markUnknown",
1443
+ )((unvalidated) =>
1444
+ Effect.gen(function* () {
1445
+ const request = yield* validate(MarkUnknownRequest, "markUnknown", unvalidated);
1446
+ const decision = yield* Ref.modify(
1447
+ state,
1448
+ (current): readonly [Decision<void, SettlementConflict | LedgerError>, LedgerState] => {
1449
+ const stored = current.submissions.get(request.submissionId);
1450
+ if (stored === undefined) {
1451
+ return [
1452
+ failure(ledgerError("markUnknown", `Unknown Submission ${request.submissionId}`)),
1453
+ current,
1454
+ ];
1455
+ }
1456
+ if (stored.row.state === "settled") {
1457
+ if (stored.row.settledOutcome === undefined) {
1458
+ return [
1459
+ failure(
1460
+ ledgerError(
1461
+ "markUnknown",
1462
+ `Settled Submission ${request.submissionId} is missing its outcome`,
1463
+ ),
1464
+ ),
1465
+ current,
1466
+ ];
1467
+ }
1468
+ return [
1469
+ failure(
1470
+ SettlementConflict.make({
1471
+ submissionId: request.submissionId,
1472
+ existingOutcome: stored.row.settledOutcome,
1473
+ }),
1474
+ ),
1475
+ current,
1476
+ ];
1477
+ }
1478
+ // A reserved exact outcome wins over a late Unknown marking (DUR-011); the recovery
1479
+ // classifier orders reservation ahead of MarkUnknown for the same reason.
1480
+ if (stored.reservation !== undefined) {
1481
+ return [
1482
+ failure(
1483
+ SettlementConflict.make({
1484
+ submissionId: request.submissionId,
1485
+ existingOutcome: stored.reservation.outcome,
1486
+ }),
1487
+ ),
1488
+ current,
1489
+ ];
1490
+ }
1491
+ // Idempotent merge: repeating is a no-op; additional open calls extend the marked
1492
+ // set while the first recorded reason is kept.
1493
+ const existing = stored.unknownMark;
1494
+ const known = new Set(existing?.toolCallIds ?? []);
1495
+ const merged = [
1496
+ ...(existing?.toolCallIds ?? []),
1497
+ ...request.toolCallIds.filter((toolCallId) => !known.has(toolCallId)),
1498
+ ];
1499
+ return [
1500
+ success(undefined),
1501
+ withSubmission(current, {
1502
+ ...stored,
1503
+ row:
1504
+ stored.row.state === "unknown" ? stored.row : { ...stored.row, state: "unknown" },
1505
+ unknownMark: { reason: existing?.reason ?? request.reason, toolCallIds: merged },
1506
+ }),
1507
+ ];
1508
+ },
1509
+ );
1510
+ if (decision._tag === "failure") return yield* decision.error;
1511
+ }),
1512
+ );
1513
+
1514
+ const recordUnknownResolution: SubmissionLedger["Service"]["recordUnknownResolution"] =
1515
+ Effect.fn("MemorySubmissionLedger.recordUnknownResolution")((unvalidated) =>
1516
+ Effect.gen(function* () {
1517
+ const command = yield* validate(
1518
+ UnknownResolutionCommand,
1519
+ "recordUnknownResolution",
1520
+ unvalidated,
1521
+ );
1522
+ const nowMillis = yield* Clock.currentTimeMillis;
1523
+ const encodedResolution = yield* Schema.encodeUnknownEffect(UnknownResolution)(
1524
+ command.resolution,
1525
+ ).pipe(
1526
+ Effect.mapError((error) =>
1527
+ ledgerError("recordUnknownResolution", "Invalid unknown-outcome resolution", error),
1528
+ ),
1529
+ );
1530
+ const resolutionJson = JSON.stringify(encodedResolution);
1531
+ const decision = yield* Ref.modify(
1532
+ state,
1533
+ (
1534
+ current,
1535
+ ): readonly [
1536
+ Decision<
1537
+ UnknownResolutionIntent,
1538
+ UnknownResolutionConflict | SettlementConflict | LedgerError
1539
+ >,
1540
+ LedgerState,
1541
+ ] => {
1542
+ const stored = current.submissions.get(command.submissionId);
1543
+ if (stored === undefined) {
1544
+ return [
1545
+ failure(
1546
+ ledgerError(
1547
+ "recordUnknownResolution",
1548
+ `Unknown Submission ${command.submissionId}`,
1549
+ ),
1550
+ ),
1551
+ current,
1552
+ ];
1553
+ }
1554
+ if (stored.row.state === "settled") {
1555
+ if (stored.row.settledOutcome === undefined) {
1556
+ return [
1557
+ failure(
1558
+ ledgerError(
1559
+ "recordUnknownResolution",
1560
+ `Settled Submission ${command.submissionId} is missing its outcome`,
1561
+ ),
1562
+ ),
1563
+ current,
1564
+ ];
1565
+ }
1566
+ return [
1567
+ failure(
1568
+ SettlementConflict.make({
1569
+ submissionId: command.submissionId,
1570
+ existingOutcome: stored.row.settledOutcome,
1571
+ }),
1572
+ ),
1573
+ current,
1574
+ ];
1575
+ }
1576
+ const existing = stored.unknownResolutions.get(command.toolCallId);
1577
+ if (existing !== undefined && existing.resolutionJson !== resolutionJson) {
1578
+ return [
1579
+ failure(
1580
+ UnknownResolutionConflict.make({
1581
+ submissionId: command.submissionId,
1582
+ toolCallId: command.toolCallId,
1583
+ }),
1584
+ ),
1585
+ current,
1586
+ ];
1587
+ }
1588
+ const intent =
1589
+ existing?.intent ??
1590
+ UnknownResolutionIntent.make({
1591
+ submissionId: command.submissionId,
1592
+ toolCallId: command.toolCallId,
1593
+ author: command.author,
1594
+ reason: command.reason,
1595
+ resolution: command.resolution,
1596
+ resolvedAt: utc(nowMillis),
1597
+ });
1598
+ const unknownResolutions =
1599
+ existing !== undefined
1600
+ ? stored.unknownResolutions
1601
+ : new Map(stored.unknownResolutions).set(command.toolCallId, {
1602
+ intent,
1603
+ resolutionJson,
1604
+ });
1605
+ // The lane reopens only when EVERY marked open call has a durable resolution
1606
+ // intent: unknown → input-applied (DUR-017). Replays re-run the coverage check so
1607
+ // a recovering caller can wake the lane idempotently.
1608
+ const wakes =
1609
+ stored.row.state === "unknown" &&
1610
+ stored.unknownMark !== undefined &&
1611
+ stored.unknownMark.toolCallIds.every((toolCallId) =>
1612
+ unknownResolutions.has(toolCallId),
1613
+ );
1614
+ return [
1615
+ success(intent),
1616
+ withSubmission(current, {
1617
+ ...stored,
1618
+ row: wakes ? { ...stored.row, state: "input-applied" } : stored.row,
1619
+ unknownMark: wakes ? undefined : stored.unknownMark,
1620
+ unknownResolutions,
1621
+ }),
1622
+ ];
1623
+ },
1624
+ );
1625
+ if (decision._tag === "failure") return yield* decision.error;
1626
+ return decision.value;
1627
+ }),
1628
+ );
1629
+
1630
+ const recordChildSettled: SubmissionLedger["Service"]["recordChildSettled"] = Effect.fn(
1631
+ "MemorySubmissionLedger.recordChildSettled",
1632
+ )((unvalidated) =>
1633
+ Effect.gen(function* () {
1634
+ const request = yield* validate(
1635
+ ChildSettledNotification,
1636
+ "recordChildSettled",
1637
+ unvalidated,
1638
+ );
1639
+ const decision = yield* Ref.modify(
1640
+ state,
1641
+ (current): readonly [Decision<ChildSettledOutcome, LedgerError>, LedgerState] => {
1642
+ const parent = current.submissions.get(request.parentSubmissionId);
1643
+ if (parent === undefined) {
1644
+ return [
1645
+ failure(
1646
+ ledgerError(
1647
+ "recordChildSettled",
1648
+ `Unknown Submission ${request.parentSubmissionId}`,
1649
+ ),
1650
+ ),
1651
+ current,
1652
+ ];
1653
+ }
1654
+ // The child's canonical Settlement is the authority for this wake; a notification
1655
+ // for an unsettled (or unknown) child is a caller error in a single-store adapter.
1656
+ const child = current.submissions.get(request.childSubmissionId);
1657
+ if (child === undefined || child.row.state !== "settled") {
1658
+ return [
1659
+ failure(
1660
+ ledgerError(
1661
+ "recordChildSettled",
1662
+ `Child Submission ${request.childSubmissionId} has no recorded settlement`,
1663
+ ),
1664
+ ),
1665
+ current,
1666
+ ];
1667
+ }
1668
+ if (
1669
+ parent.row.state !== "suspended" ||
1670
+ parent.suspension === undefined ||
1671
+ parent.suspension.reason._tag !== "WaitingForChild"
1672
+ ) {
1673
+ return [success("not-waiting" as const), current];
1674
+ }
1675
+ const children = parent.suspension.reason.children;
1676
+ if (!children.some((entry) => entry.childSubmissionId === request.childSubmissionId)) {
1677
+ return [success("not-waiting" as const), current];
1678
+ }
1679
+ // The parent wakes exactly when EVERY listed child is settled (spec §12 step 10);
1680
+ // replays re-run the coverage check so a recovering caller wakes the lane
1681
+ // idempotently.
1682
+ const allSettled = children.every(
1683
+ (entry) => current.submissions.get(entry.childSubmissionId)?.row.state === "settled",
1684
+ );
1685
+ if (!allSettled) return [success("still-waiting" as const), current];
1686
+ return [
1687
+ success("woken" as const),
1688
+ withSubmission(current, {
1689
+ ...parent,
1690
+ row: { ...parent.row, state: "input-applied" },
1691
+ suspension: undefined,
1692
+ }),
1693
+ ];
1694
+ },
1695
+ );
1696
+ if (decision._tag === "failure") return yield* decision.error;
1697
+ return decision.value;
1698
+ }),
1699
+ );
1700
+
1701
+ const reserveChildBudget: SubmissionLedger["Service"]["reserveChildBudget"] = Effect.fn(
1702
+ "MemorySubmissionLedger.reserveChildBudget",
1703
+ )((unvalidated) =>
1704
+ Effect.gen(function* () {
1705
+ const request = yield* validate(
1706
+ ChildBudgetReservationRequest,
1707
+ "reserveChildBudget",
1708
+ unvalidated,
1709
+ );
1710
+ const nowMillis = yield* Clock.currentTimeMillis;
1711
+ const allocationJson = JSON.stringify(request.allocation);
1712
+ const decision = yield* Ref.modify(
1713
+ state,
1714
+ (
1715
+ current,
1716
+ ): readonly [
1717
+ Decision<ReservedChildBudget, ChildReservationConflict | OwnershipLost | LedgerError>,
1718
+ LedgerState,
1719
+ ] => {
1720
+ const existing = current.childReservations.get(request.reservationId);
1721
+ if (existing !== undefined) {
1722
+ // Identical replays short-circuit before the fence, mirroring reserveSettlement:
1723
+ // a replay creates nothing, so a recovering caller resumes rather than duplicates.
1724
+ const identical =
1725
+ existing.parentSubmissionId === request.parentSubmissionId &&
1726
+ existing.parentToolCallId === request.parentToolCallId &&
1727
+ existing.allocationDigest === request.allocationDigest &&
1728
+ existing.allocationJson === allocationJson;
1729
+ if (!identical) {
1730
+ return [
1731
+ failure(
1732
+ ChildReservationConflict.make({
1733
+ reservationId: request.reservationId,
1734
+ status: existing.status,
1735
+ message:
1736
+ "A reservation with this identity exists with a different parent Tool Call or allocation.",
1737
+ }),
1738
+ ),
1739
+ current,
1740
+ ];
1741
+ }
1742
+ return [
1743
+ success(
1744
+ ReservedChildBudget.make({
1745
+ reservation: toReservationSnapshot(existing),
1746
+ replayed: true,
1747
+ }),
1748
+ ),
1749
+ current,
1750
+ ];
1751
+ }
1752
+ for (const reservation of current.childReservations.values()) {
1753
+ if (
1754
+ reservation.parentSubmissionId === request.parentSubmissionId &&
1755
+ reservation.parentToolCallId === request.parentToolCallId
1756
+ ) {
1757
+ return [
1758
+ failure(
1759
+ ChildReservationConflict.make({
1760
+ reservationId: request.reservationId,
1761
+ status: reservation.status,
1762
+ message: `Parent Tool Call ${request.parentToolCallId} already owns reservation ${reservation.reservationId}.`,
1763
+ }),
1764
+ ),
1765
+ current,
1766
+ ];
1767
+ }
1768
+ }
1769
+ const parent = current.submissions.get(request.parentSubmissionId);
1770
+ if (parent === undefined) {
1771
+ return [
1772
+ failure(
1773
+ ledgerError(
1774
+ "reserveChildBudget",
1775
+ `Unknown Submission ${request.parentSubmissionId}`,
1776
+ ),
1777
+ ),
1778
+ current,
1779
+ ];
1780
+ }
1781
+ // Creation is fenced by the parent lane's live ownership (spec §12 step 2): a stale
1782
+ // parent Attempt can never create new reservation state.
1783
+ if (!ownsLane(parent, request.ownershipToken)) {
1784
+ return [failure(ownershipLost(current, parent)), current];
1785
+ }
1786
+ const reservation: StoredChildReservation = {
1787
+ reservationId: request.reservationId,
1788
+ parentSubmissionId: request.parentSubmissionId,
1789
+ parentToolCallId: request.parentToolCallId,
1790
+ childSubmissionId: undefined,
1791
+ status: "reserved",
1792
+ allocation: request.allocation,
1793
+ allocationJson,
1794
+ allocationDigest: request.allocationDigest,
1795
+ accounting: undefined,
1796
+ accountingJson: undefined,
1797
+ reservedAtMillis: nowMillis,
1798
+ releaseBeganAtMillis: undefined,
1799
+ releasedAtMillis: undefined,
1800
+ };
1801
+ return [
1802
+ success(
1803
+ ReservedChildBudget.make({
1804
+ reservation: toReservationSnapshot(reservation),
1805
+ replayed: false,
1806
+ }),
1807
+ ),
1808
+ withChildReservation(current, reservation),
1809
+ ];
1810
+ },
1811
+ );
1812
+ if (decision._tag === "failure") return yield* decision.error;
1813
+ return decision.value;
1814
+ }),
1815
+ );
1816
+
1817
+ const attachChildToReservation: SubmissionLedger["Service"]["attachChildToReservation"] =
1818
+ Effect.fn("MemorySubmissionLedger.attachChildToReservation")((unvalidated) =>
1819
+ Effect.gen(function* () {
1820
+ const request = yield* validate(
1821
+ AttachChildToReservationRequest,
1822
+ "attachChildToReservation",
1823
+ unvalidated,
1824
+ );
1825
+ const decision = yield* Ref.modify(
1826
+ state,
1827
+ (
1828
+ current,
1829
+ ): readonly [
1830
+ Decision<
1831
+ ChildBudgetReservationSnapshot,
1832
+ ChildReservationConflict | OwnershipLost | LedgerError
1833
+ >,
1834
+ LedgerState,
1835
+ ] => {
1836
+ const reservation = current.childReservations.get(request.reservationId);
1837
+ if (reservation === undefined) {
1838
+ return [
1839
+ failure(
1840
+ ledgerError(
1841
+ "attachChildToReservation",
1842
+ `Unknown child reservation ${request.reservationId}`,
1843
+ ),
1844
+ ),
1845
+ current,
1846
+ ];
1847
+ }
1848
+ if (reservation.childSubmissionId !== undefined) {
1849
+ // Idempotent replay of the recorded attachment (unfenced — it mutates nothing).
1850
+ if (reservation.childSubmissionId === request.childSubmissionId) {
1851
+ return [success(toReservationSnapshot(reservation)), current];
1852
+ }
1853
+ return [
1854
+ failure(
1855
+ ChildReservationConflict.make({
1856
+ reservationId: request.reservationId,
1857
+ status: reservation.status,
1858
+ message: `Reservation ${request.reservationId} already records child ${reservation.childSubmissionId}.`,
1859
+ }),
1860
+ ),
1861
+ current,
1862
+ ];
1863
+ }
1864
+ const parent = current.submissions.get(reservation.parentSubmissionId);
1865
+ if (parent === undefined) {
1866
+ return [
1867
+ failure(
1868
+ ledgerError(
1869
+ "attachChildToReservation",
1870
+ `Unknown Submission ${reservation.parentSubmissionId}`,
1871
+ ),
1872
+ ),
1873
+ current,
1874
+ ];
1875
+ }
1876
+ if (!ownsLane(parent, request.ownershipToken)) {
1877
+ return [failure(ownershipLost(current, parent)), current];
1878
+ }
1879
+ if (reservation.status !== "reserved") {
1880
+ return [
1881
+ failure(
1882
+ ChildReservationConflict.make({
1883
+ reservationId: request.reservationId,
1884
+ status: reservation.status,
1885
+ message: `Cannot attach a child to a ${reservation.status} reservation.`,
1886
+ }),
1887
+ ),
1888
+ current,
1889
+ ];
1890
+ }
1891
+ // Single-store latitude: the admitted child must exist here, so a dangling
1892
+ // attachment can never enter the recovery view.
1893
+ if (!current.submissions.has(request.childSubmissionId)) {
1894
+ return [
1895
+ failure(
1896
+ ledgerError(
1897
+ "attachChildToReservation",
1898
+ `Unknown child Submission ${request.childSubmissionId}`,
1899
+ ),
1900
+ ),
1901
+ current,
1902
+ ];
1903
+ }
1904
+ const attached: StoredChildReservation = {
1905
+ ...reservation,
1906
+ childSubmissionId: request.childSubmissionId,
1907
+ };
1908
+ return [
1909
+ success(toReservationSnapshot(attached)),
1910
+ withChildReservation(current, attached),
1911
+ ];
1912
+ },
1913
+ );
1914
+ if (decision._tag === "failure") return yield* decision.error;
1915
+ return decision.value;
1916
+ }),
1917
+ );
1918
+
1919
+ const beginChildBudgetRelease: SubmissionLedger["Service"]["beginChildBudgetRelease"] =
1920
+ Effect.fn("MemorySubmissionLedger.beginChildBudgetRelease")((unvalidated) =>
1921
+ Effect.gen(function* () {
1922
+ const request = yield* validate(
1923
+ BeginChildBudgetReleaseRequest,
1924
+ "beginChildBudgetRelease",
1925
+ unvalidated,
1926
+ );
1927
+ const nowMillis = yield* Clock.currentTimeMillis;
1928
+ const accountingJson = JSON.stringify(request.accounting);
1929
+ const decision = yield* Ref.modify(
1930
+ state,
1931
+ (
1932
+ current,
1933
+ ): readonly [
1934
+ Decision<ChildBudgetReservationSnapshot, ChildReservationConflict | LedgerError>,
1935
+ LedgerState,
1936
+ ] => {
1937
+ const reservation = current.childReservations.get(request.reservationId);
1938
+ if (reservation === undefined) {
1939
+ return [
1940
+ failure(
1941
+ ledgerError(
1942
+ "beginChildBudgetRelease",
1943
+ `Unknown child reservation ${request.reservationId}`,
1944
+ ),
1945
+ ),
1946
+ current,
1947
+ ];
1948
+ }
1949
+ if (reservation.status !== "reserved") {
1950
+ // The accounting decision was already frozen exactly once; an identical replay is
1951
+ // a no-op and a divergent decision conflicts (spec §12 join step 6).
1952
+ if (reservation.accountingJson === accountingJson) {
1953
+ return [success(toReservationSnapshot(reservation)), current];
1954
+ }
1955
+ return [
1956
+ failure(
1957
+ ChildReservationConflict.make({
1958
+ reservationId: request.reservationId,
1959
+ status: reservation.status,
1960
+ message:
1961
+ "A different accounting decision is already frozen for this reservation.",
1962
+ }),
1963
+ ),
1964
+ current,
1965
+ ];
1966
+ }
1967
+ const frozen: StoredChildReservation = {
1968
+ ...reservation,
1969
+ status: "releasePending",
1970
+ accounting: request.accounting,
1971
+ accountingJson,
1972
+ releaseBeganAtMillis: nowMillis,
1973
+ };
1974
+ return [
1975
+ success(toReservationSnapshot(frozen)),
1976
+ withChildReservation(current, frozen),
1977
+ ];
1978
+ },
1979
+ );
1980
+ if (decision._tag === "failure") return yield* decision.error;
1981
+ return decision.value;
1982
+ }),
1983
+ );
1984
+
1985
+ const releaseChildBudget: SubmissionLedger["Service"]["releaseChildBudget"] = Effect.fn(
1986
+ "MemorySubmissionLedger.releaseChildBudget",
1987
+ )((unvalidated) =>
1988
+ Effect.gen(function* () {
1989
+ const request = yield* validate(
1990
+ ReleaseChildBudgetRequest,
1991
+ "releaseChildBudget",
1992
+ unvalidated,
1993
+ );
1994
+ const nowMillis = yield* Clock.currentTimeMillis;
1995
+ const decision = yield* Ref.modify(
1996
+ state,
1997
+ (
1998
+ current,
1999
+ ): readonly [
2000
+ Decision<ChildBudgetReservationSnapshot, ChildReservationConflict | LedgerError>,
2001
+ LedgerState,
2002
+ ] => {
2003
+ const reservation = current.childReservations.get(request.reservationId);
2004
+ if (reservation === undefined) {
2005
+ return [
2006
+ failure(
2007
+ ledgerError(
2008
+ "releaseChildBudget",
2009
+ `Unknown child reservation ${request.reservationId}`,
2010
+ ),
2011
+ ),
2012
+ current,
2013
+ ];
2014
+ }
2015
+ // Applied exactly once: replaying a released reservation returns the stored row
2016
+ // unchanged (spec §12: "never available twice").
2017
+ if (reservation.status === "released") {
2018
+ return [success(toReservationSnapshot(reservation)), current];
2019
+ }
2020
+ if (reservation.status !== "releasePending") {
2021
+ return [
2022
+ failure(
2023
+ ChildReservationConflict.make({
2024
+ reservationId: request.reservationId,
2025
+ status: reservation.status,
2026
+ message:
2027
+ "Cannot release a reservation whose accounting decision is not frozen.",
2028
+ }),
2029
+ ),
2030
+ current,
2031
+ ];
2032
+ }
2033
+ const released: StoredChildReservation = {
2034
+ ...reservation,
2035
+ status: "released",
2036
+ releasedAtMillis: nowMillis,
2037
+ };
2038
+ return [
2039
+ success(toReservationSnapshot(released)),
2040
+ withChildReservation(current, released),
2041
+ ];
2042
+ },
2043
+ );
2044
+ if (decision._tag === "failure") return yield* decision.error;
2045
+ return decision.value;
2046
+ }),
2047
+ );
2048
+
2049
+ const scanNonterminal: SubmissionLedger["Service"]["scanNonterminal"] = Stream.unwrap(
2050
+ Ref.get(state).pipe(
2051
+ Effect.map((current) => {
2052
+ const snapshots = [...current.submissions.values()]
2053
+ .filter((stored) => stored.row.state !== "settled")
2054
+ .sort((left, right) =>
2055
+ left.row.conversationId < right.row.conversationId
2056
+ ? -1
2057
+ : left.row.conversationId > right.row.conversationId
2058
+ ? 1
2059
+ : left.row.queueSequence - right.row.queueSequence,
2060
+ )
2061
+ .map((stored) => toSnapshot(stored.row));
2062
+ return Stream.fromIterable(snapshots);
2063
+ }),
2064
+ ),
2065
+ );
2066
+
2067
+ const loadRecoverySnapshot: SubmissionLedger["Service"]["loadRecoverySnapshot"] = Effect.fn(
2068
+ "MemorySubmissionLedger.loadRecoverySnapshot",
2069
+ )((unvalidated) =>
2070
+ Effect.gen(function* () {
2071
+ const request = yield* validate(
2072
+ RecoverySnapshotRequest,
2073
+ "loadRecoverySnapshot",
2074
+ unvalidated,
2075
+ );
2076
+ const current = yield* Ref.get(state);
2077
+ const stored = current.submissions.get(request.submissionId);
2078
+ if (stored === undefined) {
2079
+ return yield* ledgerError(
2080
+ "loadRecoverySnapshot",
2081
+ `Unknown Submission ${request.submissionId}`,
2082
+ );
2083
+ }
2084
+ const joins = [...current.submissions.values()]
2085
+ .filter((candidate) => candidate.joinedHostSubmissionId === request.submissionId)
2086
+ .sort((left, right) => left.row.queueSequence - right.row.queueSequence)
2087
+ .map((candidate) =>
2088
+ JoinSnapshot.make({
2089
+ submissionId: candidate.row.submissionId,
2090
+ state: candidate.row.state,
2091
+ hostSubmissionId: request.submissionId,
2092
+ }),
2093
+ );
2094
+ const byToolCallId = <A extends { readonly toolCallId: ToolCallId }>(
2095
+ left: A,
2096
+ right: A,
2097
+ ): number =>
2098
+ left.toolCallId < right.toolCallId ? -1 : left.toolCallId > right.toolCallId ? 1 : 0;
2099
+ // Parent-side subagent view: this Submission's child budget reservations in parent Tool
2100
+ // Call order, plus each attached child's current lane state (a disposable derived view;
2101
+ // the canonical records stay the recovery truth, DUR-015).
2102
+ const childReservations = [...current.childReservations.values()]
2103
+ .filter((reservation) => reservation.parentSubmissionId === request.submissionId)
2104
+ .sort((left, right) =>
2105
+ left.parentToolCallId < right.parentToolCallId
2106
+ ? -1
2107
+ : left.parentToolCallId > right.parentToolCallId
2108
+ ? 1
2109
+ : 0,
2110
+ );
2111
+ const childAttachments: Array<ChildAttachmentSnapshot> = [];
2112
+ for (const reservation of childReservations) {
2113
+ if (reservation.childSubmissionId === undefined) continue;
2114
+ const child = current.submissions.get(reservation.childSubmissionId);
2115
+ if (child === undefined) continue;
2116
+ childAttachments.push(
2117
+ ChildAttachmentSnapshot.make({
2118
+ toolCallId: reservation.parentToolCallId,
2119
+ childSubmissionId: reservation.childSubmissionId,
2120
+ childState: child.row.state,
2121
+ ...(child.row.settledOutcome === undefined
2122
+ ? {}
2123
+ : { childOutcome: child.row.settledOutcome }),
2124
+ }),
2125
+ );
2126
+ }
2127
+ return RecoverySnapshot.make({
2128
+ submission: toSnapshot(stored.row),
2129
+ joins,
2130
+ approvalDecisions: [...stored.approvalDecisions.values()].sort(byToolCallId),
2131
+ unknownResolutions: [...stored.unknownResolutions.values()]
2132
+ .map((resolution) => resolution.intent)
2133
+ .sort(byToolCallId),
2134
+ childReservations: childReservations.map(toReservationSnapshot),
2135
+ childAttachments,
2136
+ ...(stored.row.parentLinkage === undefined
2137
+ ? {}
2138
+ : { parentLinkage: stored.row.parentLinkage }),
2139
+ ...(stored.joinedHostSubmissionId === undefined
2140
+ ? {}
2141
+ : { hostSubmissionId: stored.joinedHostSubmissionId }),
2142
+ ...(stored.suspension === undefined
2143
+ ? {}
2144
+ : {
2145
+ suspension: SuspensionSnapshot.make({
2146
+ reason: stored.suspension.reason,
2147
+ suspendedAt: utc(stored.suspension.suspendedAtMillis),
2148
+ }),
2149
+ }),
2150
+ ...(stored.ownership === undefined
2151
+ ? {}
2152
+ : {
2153
+ ownership: OwnershipSnapshot.make({
2154
+ attemptId: stored.ownership.attemptId,
2155
+ ownerProducerId: stored.ownership.ownerProducerId,
2156
+ producerEpoch: stored.ownership.producerEpoch,
2157
+ leaseExpiresAt: utc(stored.ownership.leaseExpiresAtMillis),
2158
+ }),
2159
+ }),
2160
+ ...(stored.inputApplied === undefined ? {} : { inputApplied: stored.inputApplied }),
2161
+ ...(stored.reservation === undefined
2162
+ ? {}
2163
+ : {
2164
+ reservation: SettlementReservationSnapshot.make({
2165
+ settlementId: stored.reservation.settlementId,
2166
+ outcome: stored.reservation.outcome,
2167
+ record: stored.reservation.record,
2168
+ recordDigest: stored.reservation.recordDigest,
2169
+ finalized: stored.reservation.finalizedAtMillis !== undefined,
2170
+ }),
2171
+ }),
2172
+ ...(stored.abortIntent === undefined ? {} : { abortIntent: stored.abortIntent }),
2173
+ });
2174
+ }),
2175
+ );
2176
+
2177
+ return SubmissionLedger.of({
2178
+ capabilities,
2179
+ admit,
2180
+ markReady,
2181
+ lookup,
2182
+ resolveAdmission,
2183
+ claim,
2184
+ renewOwnership,
2185
+ releaseOwnership,
2186
+ markInputApplied,
2187
+ reserveSettlement,
2188
+ finalizeSettlement,
2189
+ requestAbort,
2190
+ claimJoining,
2191
+ markJoined,
2192
+ revertJoining,
2193
+ suspend,
2194
+ recordApprovalDecision,
2195
+ markUnknown,
2196
+ recordUnknownResolution,
2197
+ recordChildSettled,
2198
+ reserveChildBudget,
2199
+ attachChildToReservation,
2200
+ beginChildBudgetRelease,
2201
+ releaseChildBudget,
2202
+ scanNonterminal,
2203
+ loadRecoverySnapshot,
2204
+ });
2205
+ });
2206
+
2207
+ /** Construction options for the in-memory reference SubmissionLedger. */
2208
+ export interface MemorySubmissionLedgerOptions {
2209
+ /**
2210
+ * Test-only fault seam for `resolveAdmission` (SUB-031): when the effect yields a reason,
2211
+ * the resolution answers `Indeterminate` with it instead of consulting the store — modelling
2212
+ * an authoritative child owner that is temporarily unreachable. `Option.none()` restores the
2213
+ * store-derived answer. Ledger state is never mutated by the fault.
2214
+ */
2215
+ readonly resolveAdmissionFault?: Effect.Effect<Option.Option<string>>;
2216
+ }
2217
+
2218
+ /**
2219
+ * In-memory reference SubmissionLedger Layer (durability `non-durable`). All state lives in one
2220
+ * `Ref` owned by the Layer's Scope; no daemon fibers are spawned and no wall clock is consulted.
2221
+ */
2222
+ export const memorySubmissionLedgerLayer = (
2223
+ options: MemorySubmissionLedgerOptions = {},
2224
+ ): Layer.Layer<SubmissionLedger> => Layer.effect(SubmissionLedger, makeSubmissionLedger(options));
2225
+
2226
+ export const MemorySubmissionLedgerLive: Layer.Layer<SubmissionLedger> =
2227
+ memorySubmissionLedgerLayer();