@effect-agent/storage-memory 0.1.0-beta.97 → 0.1.0-beta.98

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.
@@ -110,8 +110,8 @@ const ownershipLost = (state, stored) => OwnershipLost.make({
110
110
  submissionId: stored.row.submissionId,
111
111
  actualEpoch: decodeProducerEpoch(laneEpoch(state, stored.row.threadId))
112
112
  });
113
- /** The presented token owns the lane only while it matches the live ownership record. */
114
- const ownsLane = (stored, ownershipToken) => stored.ownership !== void 0 && stored.ownership.ownershipToken === ownershipToken;
113
+ /** A retained row token cannot outlive a newer owner of the same Thread. */
114
+ const ownsLane = (state, stored, ownershipToken) => stored.ownership !== void 0 && stored.ownership.ownershipToken === ownershipToken && stored.ownership.producerEpoch === laneEpoch(state, stored.row.threadId);
115
115
  const withSubmission = (state, stored) => ({
116
116
  ...state,
117
117
  submissions: new Map(state.submissions).set(stored.row.submissionId, stored)
@@ -123,14 +123,14 @@ const withChildReservation = (state, reservation) => ({
123
123
  const findHead = (state, threadId) => {
124
124
  let head;
125
125
  for (const stored of state.submissions.values()) {
126
- if (stored.row.threadId !== threadId || stored.row.state === "settled") continue;
126
+ if (stored.row.threadId !== threadId || stored.row.state === "settled" || stored.row.state === "unknown" && stored.abortIntent === void 0) continue;
127
127
  if (head === void 0 || stored.row.queueSequence < head.row.queueSequence) head = stored;
128
128
  }
129
129
  return head;
130
130
  };
131
131
  /**
132
132
  * Reference in-memory SubmissionLedger. It implements the full port contract — atomic idempotent
133
- * admission, FIFO-head claims, producer-epoch fencing, Clock-driven ownership leases, idempotent
133
+ * admission, eligible FIFO claims, producer-epoch fencing, Clock-driven ownership leases, idempotent
134
134
  * settlement reservation/finalization, and durable abort intent — with every transition applied
135
135
  * as one atomic `Ref.modify`, but its state does not survive the process (`non-durable`).
136
136
  *
@@ -140,8 +140,8 @@ const findHead = (state, threadId) => {
140
140
  * deterministically; no wall clock is consulted.
141
141
  * - The ownership lease is pinned to `DEFAULT_OWNERSHIP_LEASE_DURATION` (D5); durable adapters
142
142
  * own the configuration seam.
143
- * - A live lease blocks claims from other producers only: the same `producerId` may reclaim its
144
- * own live lease (restart recovery), which supersedes and fences the prior Attempt's token.
143
+ * - Any live lease in the Thread blocks every new claim, including the same `producerId`.
144
+ * Unresolved unknown work is skipped only after ownership is released or expires.
145
145
  * - Claiming advances `ready` to `running` and otherwise preserves the recorded state, so
146
146
  * progress markers from an earlier Attempt survive a reclaim.
147
147
  * - `renewOwnership` keeps the token stable (the port allows rotation); a replayed admission
@@ -329,10 +329,10 @@ const makeSubmissionLedger = (options = {}) => Effect.gen(function* () {
329
329
  const request = yield* validate(ClaimRequest, "claim", unvalidated);
330
330
  const nowMillis = yield* Clock.currentTimeMillis;
331
331
  const decision = yield* Ref.modify(state, (current) => {
332
+ for (const stored of current.submissions.values()) if (stored.row.threadId === request.threadId && stored.ownership !== void 0 && stored.ownership.leaseExpiresAtMillis > nowMillis) return [success(Option.none()), current];
332
333
  const head = findHead(current, request.threadId);
333
334
  if (head === void 0) return [success(Option.none()), current];
334
- if (BLOCKED_HEAD_STATES.has(head.row.state) || head.row.state === "unknown" && head.abortIntent === void 0) return [success(Option.none()), current];
335
- if (head.ownership !== void 0 && head.ownership.leaseExpiresAtMillis > nowMillis && head.ownership.ownerProducerId !== request.producerId) return [success(Option.none()), current];
335
+ if (BLOCKED_HEAD_STATES.has(head.row.state)) return [success(Option.none()), current];
336
336
  const lane = current.lanes.get(request.threadId);
337
337
  if (lane === void 0) return [failure(ledgerError("claim", "Claimable head without a Thread lane")), current];
338
338
  const producerEpoch = decodeProducerEpoch(lane.producerEpoch + 1);
@@ -379,7 +379,7 @@ const makeSubmissionLedger = (options = {}) => Effect.gen(function* () {
379
379
  const decision = yield* Ref.modify(state, (current) => {
380
380
  const stored = current.submissions.get(request.submissionId);
381
381
  if (stored === void 0) return [failure(ledgerError("renewOwnership", `Unknown Submission ${request.submissionId}`)), current];
382
- if (stored.ownership === void 0 || !ownsLane(stored, request.ownershipToken)) return [failure(ownershipLost(current, stored)), current];
382
+ if (stored.ownership === void 0 || !ownsLane(current, stored, request.ownershipToken)) return [failure(ownershipLost(current, stored)), current];
383
383
  const ownership = {
384
384
  ...stored.ownership,
385
385
  leaseExpiresAtMillis: nowMillis + leaseMillis
@@ -400,7 +400,7 @@ const makeSubmissionLedger = (options = {}) => Effect.gen(function* () {
400
400
  const decision = yield* Ref.modify(state, (current) => {
401
401
  const stored = current.submissions.get(request.submissionId);
402
402
  if (stored === void 0) return [failure(ledgerError("releaseOwnership", `Unknown Submission ${request.submissionId}`)), current];
403
- if (!ownsLane(stored, request.ownershipToken)) return [failure(ownershipLost(current, stored)), current];
403
+ if (!ownsLane(current, stored, request.ownershipToken)) return [failure(ownershipLost(current, stored)), current];
404
404
  return [success(void 0), withSubmission(current, {
405
405
  ...stored,
406
406
  ownership: void 0
@@ -413,7 +413,7 @@ const makeSubmissionLedger = (options = {}) => Effect.gen(function* () {
413
413
  const decision = yield* Ref.modify(state, (current) => {
414
414
  const stored = current.submissions.get(request.submissionId);
415
415
  if (stored === void 0) return [failure(ledgerError("markInputApplied", `Unknown Submission ${request.submissionId}`)), current];
416
- if (!ownsLane(stored, request.ownershipToken)) return [failure(ownershipLost(current, stored)), current];
416
+ if (!ownsLane(current, stored, request.ownershipToken)) return [failure(ownershipLost(current, stored)), current];
417
417
  if (stored.inputApplied !== void 0) {
418
418
  if (stored.inputApplied.recordId === request.recordId && stored.inputApplied.sequence === request.sequence) return [success(void 0), current];
419
419
  return [failure(ledgerError("markInputApplied", `A different canonical input marker is already recorded for Submission ${request.submissionId}`)), current];
@@ -441,7 +441,7 @@ const makeSubmissionLedger = (options = {}) => Effect.gen(function* () {
441
441
  if (stored === void 0) return [failure(ledgerError("reserveSettlement", `Unknown Submission ${request.submissionId}`)), current];
442
442
  const joinedSettlement = stored.row.state === "joined" && stored.joinedHostSubmissionId !== void 0;
443
443
  const queuedAbortSettlement = request.outcome === "aborted" && stored.abortIntent !== void 0 && stored.ownership === void 0 && (stored.row.state === "ready" || stored.row.state === "terminalizing");
444
- if (!joinedSettlement && !queuedAbortSettlement && !ownsLane(stored, request.ownershipToken)) return [failure(ownershipLost(current, stored)), current];
444
+ if (!joinedSettlement && !queuedAbortSettlement && !ownsLane(current, stored, request.ownershipToken)) return [failure(ownershipLost(current, stored)), current];
445
445
  const existing = stored.reservation;
446
446
  if (existing !== void 0) {
447
447
  if (existing.settlementId !== request.settlementId || existing.outcome !== request.outcome || existing.recordDigest !== request.recordDigest) return [failure(SettlementConflict.make({
@@ -572,7 +572,7 @@ const makeSubmissionLedger = (options = {}) => Effect.gen(function* () {
572
572
  const host = current.submissions.get(request.hostSubmissionId);
573
573
  if (host === void 0) return [failure(ledgerError("claimJoining", `Unknown Submission ${request.hostSubmissionId}`)), current];
574
574
  if (host.row.threadId !== request.threadId) return [failure(ledgerError("claimJoining", `Host Submission ${request.hostSubmissionId} does not belong to Thread ${request.threadId}`)), current];
575
- if (!ownsLane(host, request.ownershipToken)) return [failure(ownershipLost(current, host)), current];
575
+ if (!ownsLane(current, host, request.ownershipToken)) return [failure(ownershipLost(current, host)), current];
576
576
  const later = [...current.submissions.values()].filter((stored) => stored.row.threadId === request.threadId && stored.row.queueSequence > host.row.queueSequence).sort((left, right) => left.row.queueSequence - right.row.queueSequence);
577
577
  const claims = [];
578
578
  const submissions = new Map(current.submissions);
@@ -611,7 +611,7 @@ const makeSubmissionLedger = (options = {}) => Effect.gen(function* () {
611
611
  if (stored.joinedHostSubmissionId === void 0) return [failure(ledgerError("markJoined", `Submission ${request.submissionId} was never claimed for joining`)), current];
612
612
  const host = current.submissions.get(stored.joinedHostSubmissionId);
613
613
  if (host === void 0) return [failure(ledgerError("markJoined", `Host Submission ${stored.joinedHostSubmissionId} is missing`)), current];
614
- if (!ownsLane(host, request.ownershipToken)) return [failure(ownershipLost(current, host)), current];
614
+ if (!ownsLane(current, host, request.ownershipToken)) return [failure(ownershipLost(current, host)), current];
615
615
  if (stored.inputApplied !== void 0) {
616
616
  if (stored.inputApplied.recordId === request.recordId && stored.inputApplied.sequence === request.sequence) return [success(void 0), current];
617
617
  return [failure(ledgerError("markJoined", `A different join marker is already recorded for Submission ${request.submissionId}`)), current];
@@ -666,7 +666,7 @@ const makeSubmissionLedger = (options = {}) => Effect.gen(function* () {
666
666
  submissionId: request.submissionId,
667
667
  existingOutcome: stored.reservation.outcome
668
668
  })), current];
669
- if (!ownsLane(stored, request.ownershipToken)) return [failure(ownershipLost(current, stored)), current];
669
+ if (!ownsLane(current, stored, request.ownershipToken)) return [failure(ownershipLost(current, stored)), current];
670
670
  if (request.reason._tag === "ApprovalPending" ? request.reason.toolCallIds.every((toolCallId) => stored.approvalDecisions.has(toolCallId)) : request.reason.children.every((child) => current.submissions.get(child.childSubmissionId)?.row.state === "settled")) return [success("resume-immediately"), current];
671
671
  return [success("suspended"), withSubmission(current, {
672
672
  ...stored,
@@ -852,7 +852,7 @@ const makeSubmissionLedger = (options = {}) => Effect.gen(function* () {
852
852
  })), current];
853
853
  const parent = current.submissions.get(request.parentSubmissionId);
854
854
  if (parent === void 0) return [failure(ledgerError("reserveChildBudget", `Unknown Submission ${request.parentSubmissionId}`)), current];
855
- if (!ownsLane(parent, request.ownershipToken)) return [failure(ownershipLost(current, parent)), current];
855
+ if (!ownsLane(current, parent, request.ownershipToken)) return [failure(ownershipLost(current, parent)), current];
856
856
  const reservation = {
857
857
  reservationId: request.reservationId,
858
858
  parentSubmissionId: request.parentSubmissionId,
@@ -889,7 +889,7 @@ const makeSubmissionLedger = (options = {}) => Effect.gen(function* () {
889
889
  }
890
890
  const parent = current.submissions.get(reservation.parentSubmissionId);
891
891
  if (parent === void 0) return [failure(ledgerError("attachChildToReservation", `Unknown Submission ${reservation.parentSubmissionId}`)), current];
892
- if (!ownsLane(parent, request.ownershipToken)) return [failure(ownershipLost(current, parent)), current];
892
+ if (!ownsLane(current, parent, request.ownershipToken)) return [failure(ownershipLost(current, parent)), current];
893
893
  if (reservation.status !== "reserved") return [failure(ChildReservationConflict.make({
894
894
  reservationId: request.reservationId,
895
895
  status: reservation.status,
@@ -1 +1 @@
1
- {"version":3,"file":"MemorySubmissionLedger.mjs","names":[],"sources":["../src/MemorySubmissionLedger.ts"],"sourcesContent":["import {\n Clock,\n Cause,\n Exit,\n Fiber,\n DateTime,\n Duration,\n Effect,\n Layer,\n Option,\n Ref,\n Schema,\n Stream,\n} from \"effect\";\nimport {\n type ToolCallId,\n AttemptId,\n ReceiptId,\n SubmissionId,\n type AgentId,\n type ThreadId,\n type SettlementId,\n} from \"effect-agent/identifiers\";\nimport { InputMessage } from \"effect-agent/messaging\";\nimport {\n PersistedJson,\n WorkerAdmission,\n ProducerEpoch,\n type DefinitionDigests,\n type DeploymentId,\n type Digest,\n type ProducerId,\n type RecordEnvelope,\n type SettlementOutcome,\n} from \"effect-agent/records\";\nimport {\n type ParentLinkage,\n AbortCommand,\n AdmissionAdmitted,\n AdmissionConflict,\n AdmissionPolicyError,\n AdmissionIndeterminate,\n AdmissionNotAdmitted,\n AdmissionRequest,\n SubmissionAdmissionFence,\n AdmissionResult,\n ApprovalConflict,\n ApprovalDecisionCommand,\n ApprovalDecisionIntent,\n AttachChildToReservationRequest,\n BeginChildBudgetReleaseRequest,\n ChildAttachmentSnapshot,\n ChildBudgetReservationRequest,\n ChildBudgetReservationSnapshot,\n ChildReservationConflict,\n ChildSettledNotification,\n Claim,\n ClaimJoiningRequest,\n ClaimRequest,\n DEFAULT_OWNERSHIP_LEASE_DURATION,\n InputAppliedMarker,\n JoinSnapshot,\n JoinedToHost,\n JoiningClaim,\n LedgerCapabilities,\n LedgerError,\n MarkInputAppliedRequest,\n MarkJoinedRequest,\n MarkReadyRequest,\n MarkUnknownRequest,\n OwnershipLost,\n OwnershipRenewal,\n OwnershipSnapshot,\n OwnershipToken,\n QueueSequence,\n RecoverySnapshot,\n RecoverySnapshotRequest,\n ReleaseChildBudgetRequest,\n ReleaseOwnershipRequest,\n RenewOwnershipRequest,\n ReservedChildBudget,\n ReservedSettlement,\n RevertJoiningRequest,\n Settlement,\n SettlementConflict,\n SettlementFinalization,\n SettlementReservation,\n SettlementReservationSnapshot,\n settlementFailureFromRecord,\n AbortIntent,\n AbortIntentRequest,\n SubmissionLedger,\n SubmissionLookup,\n SubmissionLookupByKey,\n SubmissionSnapshot,\n SuspendRequest,\n SuspensionSnapshot,\n UnknownResolution,\n UnknownResolutionCommand,\n UnknownResolutionConflict,\n UnknownResolutionIntent,\n type ChildReservationId,\n type ChildReservationStatus,\n type ChildSettledOutcome,\n type IdempotencyKey,\n type Principal,\n type SubmissionState,\n type SuspensionOutcome,\n type SuspensionReason,\n} from \"effect-agent/submission-ledger\";\n\nconst MAX_SUBMISSIONS = 65_536;\n\n/**\n * Lifecycle ordering used to advance-but-never-regress the operational state marker: a reclaimed\n * Attempt must not erase progress markers (input-applied, terminalizing) that an earlier Attempt\n * already committed.\n */\nconst STATE_RANK: Record<SubmissionState, number> = {\n admitted: 0,\n ready: 1,\n joining: 2,\n joined: 3,\n running: 4,\n \"input-applied\": 5,\n suspended: 6,\n unknown: 7,\n terminalizing: 8,\n settled: 9,\n};\n\ninterface SubmissionRow {\n readonly submissionId: SubmissionId;\n readonly threadId: ThreadId;\n readonly queueSequence: QueueSequence;\n readonly principal: Principal;\n readonly idempotencyKey: IdempotencyKey;\n readonly agentId: AgentId;\n readonly agentDigests: DefinitionDigests;\n readonly deploymentId: DeploymentId;\n readonly inputPayload: PersistedJson;\n readonly inputDigest: Digest;\n readonly receiptId: ReceiptId;\n readonly state: SubmissionState;\n readonly settledOutcome: SettlementOutcome | undefined;\n readonly createdAtMillis: number;\n readonly readyAtMillis: number | undefined;\n /** Immutable child-side lineage recorded at admission (spec §12 step 5). */\n readonly parentLinkage: ParentLinkage | undefined;\n readonly admissionGroup?: string;\n readonly admissionFence?: AdmissionRequest[\"admissionFence\"];\n readonly workerAdmissionJson?: string;\n readonly messageAdmissionJson?: string;\n}\n\ninterface StoredOwnership {\n readonly attemptId: AttemptId;\n readonly ownershipToken: OwnershipToken;\n readonly producerEpoch: ProducerEpoch;\n readonly ownerProducerId: ProducerId;\n readonly leaseExpiresAtMillis: number;\n}\n\ninterface StoredReservation {\n readonly settlementId: SettlementId;\n readonly outcome: SettlementOutcome;\n readonly record: RecordEnvelope;\n readonly recordDigest: Digest;\n readonly finalizedAtMillis: number | undefined;\n}\n\ninterface StoredSuspension {\n readonly reason: SuspensionReason;\n readonly suspendedAtMillis: number;\n}\n\ninterface StoredUnknownMark {\n readonly reason: MarkUnknownRequest[\"reason\"];\n readonly toolCallIds: ReadonlyArray<ToolCallId>;\n}\n\ninterface StoredUnknownResolution {\n readonly intent: UnknownResolutionIntent;\n}\n\ninterface StoredSubmission {\n readonly row: SubmissionRow;\n readonly ownership: StoredOwnership | undefined;\n readonly inputApplied: InputAppliedMarker | undefined;\n readonly reservation: StoredReservation | undefined;\n readonly abortIntent: AbortIntent | undefined;\n /** Host linkage recorded at `claimJoining` time; cleared by `revertJoining` (DUR-016). */\n readonly joinedHostSubmissionId: SubmissionId | undefined;\n readonly suspension: StoredSuspension | undefined;\n readonly unknownMark: StoredUnknownMark | undefined;\n readonly approvalDecisions: ReadonlyMap<ToolCallId, ApprovalDecisionIntent>;\n readonly unknownResolutions: ReadonlyMap<ToolCallId, StoredUnknownResolution>;\n}\n\n/**\n * States in which `claim` never grants the head: the lane is host-owned (`joining`/`joined`)\n * or durably suspended rather than worker-claimable. Unknown heads are checked against abort\n * intent separately: abort authorizes cleanup and settlement, never ordinary Tool replay.\n */\nconst BLOCKED_HEAD_STATES: ReadonlySet<SubmissionState> = new Set([\n \"joining\",\n \"joined\",\n \"suspended\",\n]);\n\ninterface LaneState {\n readonly nextQueueSequence: number;\n readonly producerEpoch: number;\n}\n\n/** One parent-owned child budget reservation row (spec §12 steps 2 and 6). */\ninterface StoredChildReservation {\n readonly reservationId: ChildReservationId;\n readonly parentSubmissionId: SubmissionId;\n readonly parentToolCallId: ToolCallId;\n readonly childSubmissionId: SubmissionId | undefined;\n readonly status: ChildReservationStatus;\n readonly allocation: PersistedJson;\n readonly allocationDigest: Digest;\n readonly accounting: PersistedJson | undefined;\n readonly reservedAtMillis: number;\n readonly releaseBeganAtMillis: number | undefined;\n readonly releasedAtMillis: number | undefined;\n}\n\ninterface LedgerState {\n readonly submissions: ReadonlyMap<SubmissionId, StoredSubmission>;\n readonly admissionIndex: ReadonlyMap<string, SubmissionId>;\n readonly lanes: ReadonlyMap<ThreadId, LaneState>;\n readonly childReservations: ReadonlyMap<ChildReservationId, StoredChildReservation>;\n readonly mintCounter: number;\n}\n\ntype Decision<A, E> =\n | { readonly _tag: \"failure\"; readonly error: E }\n | { readonly _tag: \"success\"; readonly value: A };\n\nconst failure = <E>(error: E): Decision<never, E> => ({ _tag: \"failure\", error });\nconst success = <A>(value: A): Decision<A, never> => ({ _tag: \"success\", value });\n\nconst ledgerError = (operation: string, message: string, cause?: unknown): LedgerError =>\n cause === undefined\n ? LedgerError.make({ operation, message })\n : LedgerError.make({ operation, message, cause });\n\nconst validate = Effect.fn(\"MemorySubmissionLedger.validate\")(\n <A, I>(\n schema: Schema.Codec<A, I>,\n operation: string,\n value: unknown,\n ): Effect.Effect<A, LedgerError> =>\n Schema.encodeUnknownEffect(schema)(value).pipe(\n Effect.flatMap(Schema.decodeUnknownEffect(schema)),\n Effect.mapError((error) => ledgerError(operation, `Invalid ${operation} request`, error)),\n ),\n);\n\nconst decodeSubmissionId = Schema.decodeSync(SubmissionId);\nconst decodeReceiptId = Schema.decodeSync(ReceiptId);\nconst decodeAttemptId = Schema.decodeSync(AttemptId);\nconst decodeOwnershipToken = Schema.decodeSync(OwnershipToken);\nconst decodeQueueSequence = Schema.decodeSync(QueueSequence);\nconst decodeProducerEpoch = Schema.decodeSync(ProducerEpoch);\nconst equivalentPersistedJson = Schema.toEquivalence(PersistedJson);\nconst equivalentUnknownResolution = Schema.toEquivalence(UnknownResolution);\n\nconst utc = (millis: number): DateTime.Utc => DateTime.toUtc(DateTime.makeUnsafe(millis));\n\nconst admissionKey = (\n threadId: ThreadId,\n principal: Principal,\n idempotencyKey: IdempotencyKey,\n): string => JSON.stringify([threadId, principal, idempotencyKey]);\n\nconst toSnapshot = (row: SubmissionRow): SubmissionSnapshot =>\n SubmissionSnapshot.make({\n submissionId: row.submissionId,\n threadId: row.threadId,\n queueSequence: row.queueSequence,\n principal: row.principal,\n idempotencyKey: row.idempotencyKey,\n agentId: row.agentId,\n agentDigests: row.agentDigests,\n deploymentId: row.deploymentId,\n inputPayload: row.inputPayload,\n inputDigest: row.inputDigest,\n receiptId: row.receiptId,\n state: row.state,\n createdAt: utc(row.createdAtMillis),\n ...(row.admissionGroup === undefined ? {} : { admissionGroup: row.admissionGroup }),\n ...(row.admissionFence === undefined ? {} : { admissionFence: row.admissionFence }),\n ...(row.workerAdmissionJson === undefined\n ? {}\n : {\n workerAdmission: Schema.decodeSync(Schema.fromJsonString(WorkerAdmission))(\n row.workerAdmissionJson,\n ),\n }),\n ...(row.messageAdmissionJson === undefined\n ? {}\n : {\n messageAdmission: Schema.decodeSync(Schema.fromJsonString(InputMessage))(\n row.messageAdmissionJson,\n ),\n }),\n ...(row.settledOutcome === undefined ? {} : { settledOutcome: row.settledOutcome }),\n ...(row.readyAtMillis === undefined ? {} : { readyAt: utc(row.readyAtMillis) }),\n ...(row.parentLinkage === undefined ? {} : { parentLinkage: row.parentLinkage }),\n });\n\nconst toReservationSnapshot = (row: StoredChildReservation): ChildBudgetReservationSnapshot =>\n ChildBudgetReservationSnapshot.make({\n reservationId: row.reservationId,\n parentSubmissionId: row.parentSubmissionId,\n parentToolCallId: row.parentToolCallId,\n status: row.status,\n allocation: row.allocation,\n allocationDigest: row.allocationDigest,\n reservedAt: utc(row.reservedAtMillis),\n ...(row.childSubmissionId === undefined ? {} : { childSubmissionId: row.childSubmissionId }),\n ...(row.accounting === undefined ? {} : { accounting: row.accounting }),\n ...(row.releaseBeganAtMillis === undefined\n ? {}\n : { releaseBeganAt: utc(row.releaseBeganAtMillis) }),\n ...(row.releasedAtMillis === undefined ? {} : { releasedAt: utc(row.releasedAtMillis) }),\n });\n\n/** Linkage equality: both absent, or both present naming the same parent Tool Call. */\nconst sameParentLinkage = (\n left: ParentLinkage | undefined,\n right: ParentLinkage | undefined,\n): boolean =>\n left === undefined\n ? right === undefined\n : right !== undefined &&\n left.parentSubmissionId === right.parentSubmissionId &&\n left.parentToolCallId === right.parentToolCallId;\n\nconst laneEpoch = (state: LedgerState, threadId: ThreadId): number =>\n state.lanes.get(threadId)?.producerEpoch ?? 0;\n\nconst ownershipLost = (state: LedgerState, stored: StoredSubmission): OwnershipLost =>\n OwnershipLost.make({\n submissionId: stored.row.submissionId,\n actualEpoch: decodeProducerEpoch(laneEpoch(state, stored.row.threadId)),\n });\n\n/** The presented token owns the lane only while it matches the live ownership record. */\nconst ownsLane = (stored: StoredSubmission, ownershipToken: OwnershipToken): boolean =>\n stored.ownership !== undefined && stored.ownership.ownershipToken === ownershipToken;\n\nconst withSubmission = (state: LedgerState, stored: StoredSubmission): LedgerState => ({\n ...state,\n submissions: new Map(state.submissions).set(stored.row.submissionId, stored),\n});\n\nconst withChildReservation = (\n state: LedgerState,\n reservation: StoredChildReservation,\n): LedgerState => ({\n ...state,\n childReservations: new Map(state.childReservations).set(reservation.reservationId, reservation),\n});\n\nconst findHead = (state: LedgerState, threadId: ThreadId): StoredSubmission | undefined => {\n let head: StoredSubmission | undefined;\n\n for (const stored of state.submissions.values()) {\n if (stored.row.threadId !== threadId || stored.row.state === \"settled\") continue;\n if (head === undefined || stored.row.queueSequence < head.row.queueSequence) head = stored;\n }\n\n return head;\n};\n\n/**\n * Reference in-memory SubmissionLedger. It implements the full port contract — atomic idempotent\n * admission, FIFO-head claims, producer-epoch fencing, Clock-driven ownership leases, idempotent\n * settlement reservation/finalization, and durable abort intent — with every transition applied\n * as one atomic `Ref.modify`, but its state does not survive the process (`non-durable`).\n *\n * Adapter-specific semantics within the port's latitude:\n *\n * - Time comes exclusively from the Effect `Clock` service, so `TestClock` drives lease expiry\n * deterministically; no wall clock is consulted.\n * - The ownership lease is pinned to `DEFAULT_OWNERSHIP_LEASE_DURATION` (D5); durable adapters\n * own the configuration seam.\n * - A live lease blocks claims from other producers only: the same `producerId` may reclaim its\n * own live lease (restart recovery), which supersedes and fences the prior Attempt's token.\n * - Claiming advances `ready` to `running` and otherwise preserves the recorded state, so\n * progress markers from an earlier Attempt survive a reclaim.\n * - `renewOwnership` keeps the token stable (the port allows rotation); a replayed admission\n * reports the Submission's current state alongside the original identities.\n * - `claimJoining` walks the strictly-later queue: rows already `joining`/`joined` to the\n * SAME host extend the claimed prefix and are skipped, and an aborted-settled row is a\n * closed obligation that is also skipped (P7 §7(c)); any other non-`ready` row (an\n * `admitted` gap, a non-aborted settled row, foreign-host linkage) breaks the prefix\n * conservatively.\n * - `markJoined` verifies the token against the HOST's live ownership (the lane is\n * host-owned), so a later host Attempt can repair a lost marker from history (DUR-016). The\n * join marker reuses the input-applied marker: the joined input IS `input:{sid}`.\n * - `suspend` and `markUnknown` refuse when an exact settlement is already reserved\n * (`SettlementConflict` with the reserved outcome) — DUR-011's reservation wins.\n * - `resolveAdmission` derives its answer from the single strongly consistent store, so it\n * never answers `Indeterminate` on its own; the test-only `resolveAdmissionFault` option\n * injects the `Indeterminate` classification so SUB-031 callers can be conformance-tested.\n * - `recordChildSettled` and `suspend(WaitingForChild)` observe child settlement directly from\n * the child rows (single-store latitude); no separate notification marker is stored.\n */\nconst makeSubmissionLedger = (options: MemorySubmissionLedgerOptions = {}) =>\n Effect.gen(function* () {\n const state = yield* Ref.make<LedgerState>({\n submissions: new Map(),\n admissionIndex: new Map(),\n lanes: new Map(),\n childReservations: new Map(),\n mintCounter: 0,\n });\n\n const admissionFence = yield* SubmissionAdmissionFence;\n const leaseMillis = Duration.toMillis(DEFAULT_OWNERSHIP_LEASE_DURATION);\n\n const capabilities = Effect.succeed(LedgerCapabilities.make({ durability: \"non-durable\" }));\n\n const admit: SubmissionLedger[\"Service\"][\"admit\"] = Effect.fn(\"MemorySubmissionLedger.admit\")(\n (unvalidated) =>\n Effect.gen(function* () {\n const request = yield* validate(AdmissionRequest, \"admit\", unvalidated);\n\n const workerAdmissionJson =\n request.workerAdmission === undefined\n ? undefined\n : yield* Schema.encodeEffect(Schema.fromJsonString(WorkerAdmission))(\n request.workerAdmission,\n ).pipe(\n Effect.mapError(() => ledgerError(\"admit\", \"Invalid worker admission metadata\")),\n );\n\n const messageAdmissionJson =\n request.messageAdmission === undefined\n ? undefined\n : yield* Schema.encodeEffect(Schema.fromJsonString(InputMessage))(\n request.messageAdmission,\n ).pipe(\n Effect.mapError(() => ledgerError(\"admit\", \"Invalid message admission metadata\")),\n );\n\n const nowMillis = yield* Clock.currentTimeMillis;\n const services = yield* Effect.context<never>();\n\n const decision = yield* Ref.modify(\n state,\n (\n current,\n ): readonly [\n (\n | Decision<AdmissionResult, AdmissionConflict | AdmissionPolicyError | LedgerError>\n | { readonly _tag: \"cause\"; readonly cause: Cause.Cause<AdmissionPolicyError> }\n ),\n LedgerState,\n ] => {\n const key = admissionKey(request.threadId, request.principal, request.idempotencyKey);\n const existingId = current.admissionIndex.get(key);\n\n if (existingId !== undefined) {\n const existing = current.submissions.get(existingId);\n\n if (existing === undefined) {\n return [\n failure(\n ledgerError(\"admit\", \"Admission index references a missing Submission\"),\n ),\n current,\n ];\n }\n // A replay must repeat the exact canonical input AND the exact parent linkage\n // (or its absence): linkage is immutable lineage (spec §12 step 5, SUB-016).\n if (\n existing.row.inputDigest !== request.inputDigest ||\n !sameParentLinkage(existing.row.parentLinkage, request.parentLinkage) ||\n existing.row.admissionGroup !== request.admissionGroup ||\n !Schema.toEquivalence(Schema.optional(WorkerAdmission))(\n existing.row.workerAdmissionJson === undefined\n ? undefined\n : Schema.decodeSync(Schema.fromJsonString(WorkerAdmission))(\n existing.row.workerAdmissionJson,\n ),\n request.workerAdmission,\n ) ||\n !Schema.toEquivalence(Schema.optional(InputMessage))(\n existing.row.messageAdmissionJson === undefined\n ? undefined\n : Schema.decodeSync(Schema.fromJsonString(InputMessage))(\n existing.row.messageAdmissionJson,\n ),\n request.messageAdmission,\n ) ||\n !Schema.toEquivalence(Schema.optional(Schema.Json))(\n existing.row.admissionFence,\n request.admissionFence,\n )\n ) {\n return [\n failure(\n AdmissionConflict.make({\n threadId: request.threadId,\n principal: request.principal,\n idempotencyKey: request.idempotencyKey,\n existingInputDigest: existing.row.inputDigest,\n attemptedInputDigest: request.inputDigest,\n }),\n ),\n current,\n ];\n }\n\n return [\n success(\n AdmissionResult.make({\n submissionId: existing.row.submissionId,\n receiptId: existing.row.receiptId,\n queueSequence: existing.row.queueSequence,\n state: existing.row.state,\n replayed: true,\n }),\n ),\n current,\n ];\n }\n\n // A Thread's first admission fixes its worker origin before canonical materialization.\n const first = [...current.submissions.values()].find(\n ({ row }) => row.threadId === request.threadId,\n );\n\n if (first !== undefined) {\n const previous =\n first.row.workerAdmissionJson === undefined\n ? undefined\n : Schema.decodeSync(Schema.fromJsonString(WorkerAdmission))(\n first.row.workerAdmissionJson,\n );\n\n if (\n !Schema.toEquivalence(Schema.optional(WorkerAdmission.fields.origin))(\n previous?.origin,\n request.workerAdmission?.origin,\n )\n )\n return [\n failure(\n AdmissionPolicyError.make({\n reason: \"refused\",\n code: \"worker-origin-conflict\",\n }),\n ),\n current,\n ];\n }\n // A memory policy and the ledger mutation share one synchronous critical section.\n // An asynchronous policy cannot fence this Ref and therefore fails closed.\n const checked = Effect.runSyncExitWith(services)(admissionFence.check(request));\n\n if (Exit.isFailure(checked)) {\n return [{ _tag: \"cause\", cause: checked.cause }, current];\n }\n if (\n request.admissionGroup !== undefined &&\n [...current.submissions.values()].some(\n ({ row }) =>\n row.threadId === request.threadId &&\n row.admissionGroup === request.admissionGroup &&\n row.state !== \"settled\",\n )\n )\n return [\n failure(\n AdmissionPolicyError.make({ reason: \"occupied\", code: \"admission-group\" }),\n ),\n current,\n ];\n if (current.submissions.size >= MAX_SUBMISSIONS) {\n return [\n failure(\n ledgerError(\"admit\", `In-memory submission limit ${MAX_SUBMISSIONS} exceeded`),\n ),\n current,\n ];\n }\n\n const lane = current.lanes.get(request.threadId) ?? {\n nextQueueSequence: 1,\n producerEpoch: 0,\n };\n\n const mintCounter = current.mintCounter + 1;\n\n const row: SubmissionRow = {\n submissionId: decodeSubmissionId(`submission-memory-${mintCounter}`),\n threadId: request.threadId,\n queueSequence: decodeQueueSequence(lane.nextQueueSequence),\n principal: request.principal,\n idempotencyKey: request.idempotencyKey,\n agentId: request.agentId,\n agentDigests: request.agentDigests,\n deploymentId: request.deploymentId,\n inputPayload: request.inputPayload,\n inputDigest: request.inputDigest,\n receiptId: decodeReceiptId(`receipt-memory-${mintCounter}`),\n state: \"admitted\",\n settledOutcome: undefined,\n createdAtMillis: nowMillis,\n readyAtMillis: undefined,\n parentLinkage: request.parentLinkage,\n ...(workerAdmissionJson === undefined ? {} : { workerAdmissionJson }),\n ...(messageAdmissionJson === undefined ? {} : { messageAdmissionJson }),\n ...(request.admissionGroup === undefined\n ? {}\n : { admissionGroup: request.admissionGroup }),\n ...(request.admissionFence === undefined\n ? {}\n : { admissionFence: request.admissionFence }),\n };\n\n const submissions = new Map(current.submissions).set(row.submissionId, {\n row,\n ownership: undefined,\n inputApplied: undefined,\n reservation: undefined,\n abortIntent: undefined,\n joinedHostSubmissionId: undefined,\n suspension: undefined,\n unknownMark: undefined,\n approvalDecisions: new Map<ToolCallId, ApprovalDecisionIntent>(),\n unknownResolutions: new Map<ToolCallId, StoredUnknownResolution>(),\n });\n\n const admissionIndex = new Map(current.admissionIndex).set(key, row.submissionId);\n\n const lanes = new Map(current.lanes).set(request.threadId, {\n nextQueueSequence: lane.nextQueueSequence + 1,\n producerEpoch: lane.producerEpoch,\n });\n\n return [\n success(\n AdmissionResult.make({\n submissionId: row.submissionId,\n receiptId: row.receiptId,\n queueSequence: row.queueSequence,\n state: row.state,\n replayed: false,\n }),\n ),\n { ...current, submissions, admissionIndex, lanes, mintCounter },\n ];\n },\n );\n\n if (decision._tag === \"failure\") return yield* decision.error;\n if (decision._tag === \"cause\") {\n for (const reason of decision.cause.reasons) {\n if (Cause.isDieReason(reason) && Cause.isAsyncFiberError(reason.defect)) {\n yield* Fiber.interrupt(reason.defect.fiber);\n\n return yield* AdmissionPolicyError.make({\n reason: \"unavailable\",\n code: \"synchronous-memory-policy-required\",\n });\n }\n }\n\n return yield* Effect.failCause(decision.cause);\n }\n\n return decision.value;\n }),\n Effect.uninterruptible,\n );\n\n const markReady: SubmissionLedger[\"Service\"][\"markReady\"] = Effect.fn(\n \"MemorySubmissionLedger.markReady\",\n )((unvalidated) =>\n Effect.gen(function* () {\n const request = yield* validate(MarkReadyRequest, \"markReady\", unvalidated);\n const nowMillis = yield* Clock.currentTimeMillis;\n\n const decision = yield* Ref.modify(\n state,\n (current): readonly [Decision<void, LedgerError>, LedgerState] => {\n const stored = current.submissions.get(request.submissionId);\n\n if (stored === undefined) {\n return [\n failure(ledgerError(\"markReady\", `Unknown Submission ${request.submissionId}`)),\n current,\n ];\n }\n if (stored.row.state !== \"admitted\") return [success(undefined), current];\n\n return [\n success(undefined),\n withSubmission(current, {\n ...stored,\n row: { ...stored.row, state: \"ready\", readyAtMillis: nowMillis },\n }),\n ];\n },\n );\n\n if (decision._tag === \"failure\") return yield* decision.error;\n }),\n );\n\n const lookup: SubmissionLedger[\"Service\"][\"lookup\"] = Effect.fn(\n \"MemorySubmissionLedger.lookup\",\n )((unvalidated) =>\n Effect.gen(function* () {\n const request = yield* validate(SubmissionLookup, \"lookup\", unvalidated);\n const current = yield* Ref.get(state);\n\n const submissionId =\n request._tag === \"SubmissionLookupById\"\n ? request.submissionId\n : current.admissionIndex.get(\n admissionKey(request.threadId, request.principal, request.idempotencyKey),\n );\n\n const stored =\n submissionId === undefined ? undefined : current.submissions.get(submissionId);\n\n return stored === undefined ? Option.none() : Option.some(toSnapshot(stored.row));\n }),\n );\n\n const resolveAdmission: SubmissionLedger[\"Service\"][\"resolveAdmission\"] = Effect.fn(\n \"MemorySubmissionLedger.resolveAdmission\",\n )((unvalidated) =>\n Effect.gen(function* () {\n const request = yield* validate(SubmissionLookupByKey, \"resolveAdmission\", unvalidated);\n\n // Test-only fault seam: lets suites exercise the Indeterminate classification that a\n // single strongly consistent store never produces on its own (SUB-031, P6 honesty).\n if (options.resolveAdmissionFault !== undefined) {\n const fault = yield* options.resolveAdmissionFault;\n\n if (Option.isSome(fault)) {\n return AdmissionIndeterminate.make({ reason: fault.value });\n }\n }\n const current = yield* Ref.get(state);\n\n const submissionId = current.admissionIndex.get(\n admissionKey(request.threadId, request.principal, request.idempotencyKey),\n );\n\n const stored =\n submissionId === undefined ? undefined : current.submissions.get(submissionId);\n\n return stored === undefined\n ? AdmissionNotAdmitted.make()\n : AdmissionAdmitted.make({ submission: toSnapshot(stored.row) });\n }),\n );\n\n const claim: SubmissionLedger[\"Service\"][\"claim\"] = Effect.fn(\"MemorySubmissionLedger.claim\")(\n (unvalidated) =>\n Effect.gen(function* () {\n const request = yield* validate(ClaimRequest, \"claim\", unvalidated);\n const nowMillis = yield* Clock.currentTimeMillis;\n\n const decision = yield* Ref.modify(\n state,\n (current): readonly [Decision<Option.Option<Claim>, LedgerError>, LedgerState] => {\n const head = findHead(current, request.threadId);\n\n if (head === undefined) return [success(Option.none()), current];\n if (\n BLOCKED_HEAD_STATES.has(head.row.state) ||\n (head.row.state === \"unknown\" && head.abortIntent === undefined)\n )\n return [success(Option.none()), current];\n if (\n head.ownership !== undefined &&\n head.ownership.leaseExpiresAtMillis > nowMillis &&\n head.ownership.ownerProducerId !== request.producerId\n ) {\n return [success(Option.none()), current];\n }\n const lane = current.lanes.get(request.threadId);\n\n if (lane === undefined) {\n return [\n failure(ledgerError(\"claim\", \"Claimable head without a Thread lane\")),\n current,\n ];\n }\n const producerEpoch = decodeProducerEpoch(lane.producerEpoch + 1);\n const mintCounter = current.mintCounter + 1;\n\n const ownership: StoredOwnership = {\n attemptId: decodeAttemptId(`attempt-memory-${mintCounter}`),\n ownershipToken: decodeOwnershipToken(`ownership-memory-${mintCounter}`),\n producerEpoch,\n ownerProducerId: request.producerId,\n leaseExpiresAtMillis: nowMillis + leaseMillis,\n };\n\n const row: SubmissionRow =\n head.row.state === \"ready\" ? { ...head.row, state: \"running\" } : head.row;\n\n const next = withSubmission(current, { ...head, row, ownership });\n\n const lanes = new Map(next.lanes).set(request.threadId, {\n nextQueueSequence: lane.nextQueueSequence,\n producerEpoch: lane.producerEpoch + 1,\n });\n\n return [\n success(\n Option.some(\n Claim.make({\n submissionId: row.submissionId,\n attemptId: ownership.attemptId,\n ownershipToken: ownership.ownershipToken,\n producerEpoch,\n leaseExpiresAt: utc(ownership.leaseExpiresAtMillis),\n inputPayload: row.inputPayload,\n }),\n ),\n ),\n { ...next, lanes, mintCounter },\n ];\n },\n );\n\n if (decision._tag === \"failure\") return yield* decision.error;\n\n return decision.value;\n }),\n );\n\n const renewOwnership: SubmissionLedger[\"Service\"][\"renewOwnership\"] = Effect.fn(\n \"MemorySubmissionLedger.renewOwnership\",\n )((unvalidated) =>\n Effect.gen(function* () {\n const request = yield* validate(RenewOwnershipRequest, \"renewOwnership\", unvalidated);\n const nowMillis = yield* Clock.currentTimeMillis;\n\n const decision = yield* Ref.modify(\n state,\n (\n current,\n ): readonly [Decision<OwnershipRenewal, OwnershipLost | LedgerError>, LedgerState] => {\n const stored = current.submissions.get(request.submissionId);\n\n if (stored === undefined) {\n return [\n failure(\n ledgerError(\"renewOwnership\", `Unknown Submission ${request.submissionId}`),\n ),\n current,\n ];\n }\n if (stored.ownership === undefined || !ownsLane(stored, request.ownershipToken)) {\n return [failure(ownershipLost(current, stored)), current];\n }\n\n const ownership: StoredOwnership = {\n ...stored.ownership,\n leaseExpiresAtMillis: nowMillis + leaseMillis,\n };\n\n return [\n success(\n OwnershipRenewal.make({\n ownershipToken: ownership.ownershipToken,\n leaseExpiresAt: utc(ownership.leaseExpiresAtMillis),\n }),\n ),\n withSubmission(current, { ...stored, ownership }),\n ];\n },\n );\n\n if (decision._tag === \"failure\") return yield* decision.error;\n\n return decision.value;\n }),\n );\n\n const releaseOwnership: SubmissionLedger[\"Service\"][\"releaseOwnership\"] = Effect.fn(\n \"MemorySubmissionLedger.releaseOwnership\",\n )((unvalidated) =>\n Effect.gen(function* () {\n const request = yield* validate(ReleaseOwnershipRequest, \"releaseOwnership\", unvalidated);\n\n const decision = yield* Ref.modify(\n state,\n (current): readonly [Decision<void, OwnershipLost | LedgerError>, LedgerState] => {\n const stored = current.submissions.get(request.submissionId);\n\n if (stored === undefined) {\n return [\n failure(\n ledgerError(\"releaseOwnership\", `Unknown Submission ${request.submissionId}`),\n ),\n current,\n ];\n }\n if (!ownsLane(stored, request.ownershipToken)) {\n return [failure(ownershipLost(current, stored)), current];\n }\n\n return [\n success(undefined),\n withSubmission(current, { ...stored, ownership: undefined }),\n ];\n },\n );\n\n if (decision._tag === \"failure\") return yield* decision.error;\n }),\n );\n\n const markInputApplied: SubmissionLedger[\"Service\"][\"markInputApplied\"] = Effect.fn(\n \"MemorySubmissionLedger.markInputApplied\",\n )((unvalidated) =>\n Effect.gen(function* () {\n const request = yield* validate(MarkInputAppliedRequest, \"markInputApplied\", unvalidated);\n\n const decision = yield* Ref.modify(\n state,\n (current): readonly [Decision<void, OwnershipLost | LedgerError>, LedgerState] => {\n const stored = current.submissions.get(request.submissionId);\n\n if (stored === undefined) {\n return [\n failure(\n ledgerError(\"markInputApplied\", `Unknown Submission ${request.submissionId}`),\n ),\n current,\n ];\n }\n if (!ownsLane(stored, request.ownershipToken)) {\n return [failure(ownershipLost(current, stored)), current];\n }\n\n if (stored.inputApplied !== undefined) {\n if (\n stored.inputApplied.recordId === request.recordId &&\n stored.inputApplied.sequence === request.sequence\n ) {\n return [success(undefined), current];\n }\n\n return [\n failure(\n ledgerError(\n \"markInputApplied\",\n `A different canonical input marker is already recorded for Submission ${request.submissionId}`,\n ),\n ),\n current,\n ];\n }\n\n const marker = InputAppliedMarker.make({\n recordId: request.recordId,\n sequence: request.sequence,\n });\n\n const row: SubmissionRow =\n STATE_RANK[stored.row.state] < STATE_RANK[\"input-applied\"]\n ? { ...stored.row, state: \"input-applied\" }\n : stored.row;\n\n return [\n success(undefined),\n withSubmission(current, { ...stored, row, inputApplied: marker }),\n ];\n },\n );\n\n if (decision._tag === \"failure\") return yield* decision.error;\n }),\n );\n\n const reserveSettlement: SubmissionLedger[\"Service\"][\"reserveSettlement\"] = Effect.fn(\n \"MemorySubmissionLedger.reserveSettlement\",\n )((unvalidated) =>\n Effect.gen(function* () {\n const request = yield* validate(SettlementReservation, \"reserveSettlement\", unvalidated);\n\n const decision = yield* Ref.modify(\n state,\n (\n current,\n ): readonly [\n Decision<ReservedSettlement, SettlementConflict | OwnershipLost | LedgerError>,\n LedgerState,\n ] => {\n const stored = current.submissions.get(request.submissionId);\n\n if (stored === undefined) {\n return [\n failure(\n ledgerError(\"reserveSettlement\", `Unknown Submission ${request.submissionId}`),\n ),\n current,\n ];\n }\n\n // A `joined` Submission settles WITH its host (plan §2.5) and its lane is never\n // worker-claimable, so no ownership token can exist for it: the recorded host\n // linkage authorizes the reservation and the presented token is not consulted.\n const joinedSettlement =\n stored.row.state === \"joined\" && stored.joinedHostSubmissionId !== undefined;\n\n // P7 §7(c): an aborted, never-claimed, still-queued Submission likewise has no\n // live ownership to fence against — its durable abort intent authorizes exactly\n // its ABORTED settlement (`terminalizing` is the same pass's crash replay). Every\n // other reservation stays fenced by the target lane's live ownership.\n const queuedAbortSettlement =\n request.outcome === \"aborted\" &&\n stored.abortIntent !== undefined &&\n stored.ownership === undefined &&\n (stored.row.state === \"ready\" || stored.row.state === \"terminalizing\");\n\n if (\n !joinedSettlement &&\n !queuedAbortSettlement &&\n !ownsLane(stored, request.ownershipToken)\n ) {\n return [failure(ownershipLost(current, stored)), current];\n }\n const existing = stored.reservation;\n\n if (existing !== undefined) {\n if (\n existing.settlementId !== request.settlementId ||\n existing.outcome !== request.outcome ||\n existing.recordDigest !== request.recordDigest\n ) {\n return [\n failure(\n SettlementConflict.make({\n submissionId: request.submissionId,\n existingOutcome: existing.outcome,\n }),\n ),\n current,\n ];\n }\n\n return [\n success(\n ReservedSettlement.make({\n submissionId: request.submissionId,\n settlementId: existing.settlementId,\n outcome: existing.outcome,\n record: existing.record,\n recordDigest: existing.recordDigest,\n replayed: true,\n }),\n ),\n current,\n ];\n }\n\n const reservation: StoredReservation = {\n settlementId: request.settlementId,\n outcome: request.outcome,\n record: request.record,\n recordDigest: request.recordDigest,\n finalizedAtMillis: undefined,\n };\n\n const row: SubmissionRow =\n STATE_RANK[stored.row.state] < STATE_RANK.terminalizing\n ? { ...stored.row, state: \"terminalizing\" }\n : stored.row;\n\n return [\n success(\n ReservedSettlement.make({\n submissionId: request.submissionId,\n settlementId: reservation.settlementId,\n outcome: reservation.outcome,\n record: reservation.record,\n recordDigest: reservation.recordDigest,\n replayed: false,\n }),\n ),\n withSubmission(current, { ...stored, row, reservation }),\n ];\n },\n );\n\n if (decision._tag === \"failure\") return yield* decision.error;\n\n return decision.value;\n }),\n );\n\n const finalizeSettlement: SubmissionLedger[\"Service\"][\"finalizeSettlement\"] = Effect.fn(\n \"MemorySubmissionLedger.finalizeSettlement\",\n )((unvalidated) =>\n Effect.gen(function* () {\n const request = yield* validate(SettlementFinalization, \"finalizeSettlement\", unvalidated);\n const nowMillis = yield* Clock.currentTimeMillis;\n\n const decision = yield* Ref.modify(\n state,\n (\n current,\n ): readonly [Decision<Settlement, SettlementConflict | LedgerError>, LedgerState] => {\n const stored = current.submissions.get(request.submissionId);\n\n if (stored === undefined) {\n return [\n failure(\n ledgerError(\"finalizeSettlement\", `Unknown Submission ${request.submissionId}`),\n ),\n current,\n ];\n }\n const reservation = stored.reservation;\n\n if (reservation === undefined) {\n return [\n failure(\n ledgerError(\n \"finalizeSettlement\",\n `No settlement reservation for Submission ${request.submissionId}`,\n ),\n ),\n current,\n ];\n }\n const settlementFailure = settlementFailureFromRecord(reservation.record);\n\n if ((reservation.outcome === \"failed\") !== (settlementFailure !== undefined)) {\n return [\n failure(\n ledgerError(\n \"finalizeSettlement\",\n `Settlement reservation for Submission ${request.submissionId} has contradictory failure evidence`,\n ),\n ),\n current,\n ];\n }\n if (reservation.settlementId !== request.settlementId) {\n return [\n failure(\n SettlementConflict.make({\n submissionId: request.submissionId,\n existingOutcome: reservation.outcome,\n }),\n ),\n current,\n ];\n }\n if (reservation.finalizedAtMillis !== undefined) {\n return [\n success(\n Settlement.make({\n submissionId: stored.row.submissionId,\n settlementId: reservation.settlementId,\n receiptId: stored.row.receiptId,\n outcome: reservation.outcome,\n ...(settlementFailure === undefined ? {} : { failure: settlementFailure }),\n settledAt: utc(reservation.finalizedAtMillis),\n }),\n ),\n current,\n ];\n }\n\n const next = withSubmission(current, {\n ...stored,\n row: { ...stored.row, state: \"settled\", settledOutcome: reservation.outcome },\n ownership: undefined,\n reservation: { ...reservation, finalizedAtMillis: nowMillis },\n });\n\n return [\n success(\n Settlement.make({\n submissionId: stored.row.submissionId,\n settlementId: reservation.settlementId,\n receiptId: stored.row.receiptId,\n outcome: reservation.outcome,\n ...(settlementFailure === undefined ? {} : { failure: settlementFailure }),\n settledAt: utc(nowMillis),\n }),\n ),\n next,\n ];\n },\n );\n\n if (decision._tag === \"failure\") return yield* decision.error;\n\n return decision.value;\n }),\n );\n\n const requestAbort: SubmissionLedger[\"Service\"][\"requestAbort\"] = Effect.fn(\n \"MemorySubmissionLedger.requestAbort\",\n )((unvalidated) =>\n Effect.gen(function* () {\n const request = yield* validate(AbortCommand, \"requestAbort\", unvalidated);\n const nowMillis = yield* Clock.currentTimeMillis;\n\n const decision = yield* Ref.modify(\n state,\n (\n current,\n ): readonly [\n Decision<AbortIntent, SettlementConflict | JoinedToHost | LedgerError>,\n LedgerState,\n ] => {\n const stored = current.submissions.get(request.submissionId);\n\n if (stored === undefined) {\n return [\n failure(ledgerError(\"requestAbort\", `Unknown Submission ${request.submissionId}`)),\n current,\n ];\n }\n // A joined Submission settles WITH its host; the abort target is the host (plan\n // §2.5). A joining Submission still records the intent: it is honored only if the\n // host has not consumed the input (revert-then-abort).\n if (stored.row.state === \"joined\") {\n if (stored.joinedHostSubmissionId === undefined) {\n return [\n failure(\n ledgerError(\n \"requestAbort\",\n `Joined Submission ${request.submissionId} is missing its host linkage`,\n ),\n ),\n current,\n ];\n }\n\n return [\n failure(\n JoinedToHost.make({\n submissionId: request.submissionId,\n hostSubmissionId: stored.joinedHostSubmissionId,\n }),\n ),\n current,\n ];\n }\n if (stored.row.state === \"settled\") {\n if (stored.row.settledOutcome === undefined) {\n return [\n failure(\n ledgerError(\n \"requestAbort\",\n `Settled Submission ${request.submissionId} is missing its outcome`,\n ),\n ),\n current,\n ];\n }\n\n return [\n failure(\n SettlementConflict.make({\n submissionId: request.submissionId,\n existingOutcome: stored.row.settledOutcome,\n }),\n ),\n current,\n ];\n }\n if (stored.abortIntent !== undefined) return [success(stored.abortIntent), current];\n\n const intent = AbortIntent.make({\n submissionId: request.submissionId,\n author: request.author,\n reason: request.reason,\n requestedAt: utc(nowMillis),\n });\n\n return [success(intent), withSubmission(current, { ...stored, abortIntent: intent })];\n },\n );\n\n if (decision._tag === \"failure\") return yield* decision.error;\n\n return decision.value;\n }),\n );\n\n const claimJoining: SubmissionLedger[\"Service\"][\"claimJoining\"] = Effect.fn(\n \"MemorySubmissionLedger.claimJoining\",\n )((unvalidated) =>\n Effect.gen(function* () {\n const request = yield* validate(ClaimJoiningRequest, \"claimJoining\", unvalidated);\n\n const decision = yield* Ref.modify(\n state,\n (\n current,\n ): readonly [\n Decision<ReadonlyArray<JoiningClaim>, OwnershipLost | LedgerError>,\n LedgerState,\n ] => {\n const host = current.submissions.get(request.hostSubmissionId);\n\n if (host === undefined) {\n return [\n failure(\n ledgerError(\"claimJoining\", `Unknown Submission ${request.hostSubmissionId}`),\n ),\n current,\n ];\n }\n if (host.row.threadId !== request.threadId) {\n return [\n failure(\n ledgerError(\n \"claimJoining\",\n `Host Submission ${request.hostSubmissionId} does not belong to Thread ${request.threadId}`,\n ),\n ),\n current,\n ];\n }\n if (!ownsLane(host, request.ownershipToken)) {\n return [failure(ownershipLost(current, host)), current];\n }\n\n const later = [...current.submissions.values()]\n .filter(\n (stored) =>\n stored.row.threadId === request.threadId &&\n stored.row.queueSequence > host.row.queueSequence,\n )\n .sort((left, right) => left.row.queueSequence - right.row.queueSequence);\n\n const claims: Array<JoiningClaim> = [];\n const submissions = new Map(current.submissions);\n\n for (const stored of later) {\n if (claims.length >= request.maxCount) break;\n // Rows already claimed by THIS host extend its contiguous prefix and are skipped;\n // the coordinator re-delivers already-joined input through the coverage rule.\n if (\n (stored.row.state === \"joining\" || stored.row.state === \"joined\") &&\n stored.joinedHostSubmissionId === request.hostSubmissionId\n ) {\n continue;\n }\n // P7 §7(c): an aborted-settled row is a CLOSED obligation, not a gap — recovery\n // settles aborted never-claimed queued work immediately, and settlement order of\n // never-run work is not execution order (DUR-004 bounds execution).\n if (stored.row.state === \"settled\" && stored.row.settledOutcome === \"aborted\") {\n continue;\n }\n // Any other non-ready row — an admitted-not-ready gap in particular — breaks the\n // contiguous ready prefix (plan §2.5); later ready work stays queued (DUR-004).\n if (stored.row.state !== \"ready\") break;\n submissions.set(stored.row.submissionId, {\n ...stored,\n row: { ...stored.row, state: \"joining\" },\n joinedHostSubmissionId: request.hostSubmissionId,\n });\n claims.push(\n JoiningClaim.make({\n submissionId: stored.row.submissionId,\n queueSequence: stored.row.queueSequence,\n inputPayload: stored.row.inputPayload,\n }),\n );\n }\n\n return [success(claims), { ...current, submissions }];\n },\n );\n\n if (decision._tag === \"failure\") return yield* decision.error;\n\n return decision.value;\n }),\n );\n\n const markJoined: SubmissionLedger[\"Service\"][\"markJoined\"] = Effect.fn(\n \"MemorySubmissionLedger.markJoined\",\n )((unvalidated) =>\n Effect.gen(function* () {\n const request = yield* validate(MarkJoinedRequest, \"markJoined\", unvalidated);\n\n const decision = yield* Ref.modify(\n state,\n (current): readonly [Decision<void, OwnershipLost | LedgerError>, LedgerState] => {\n const stored = current.submissions.get(request.submissionId);\n\n if (stored === undefined) {\n return [\n failure(ledgerError(\"markJoined\", `Unknown Submission ${request.submissionId}`)),\n current,\n ];\n }\n if (stored.joinedHostSubmissionId === undefined) {\n return [\n failure(\n ledgerError(\n \"markJoined\",\n `Submission ${request.submissionId} was never claimed for joining`,\n ),\n ),\n current,\n ];\n }\n const host = current.submissions.get(stored.joinedHostSubmissionId);\n\n if (host === undefined) {\n return [\n failure(\n ledgerError(\n \"markJoined\",\n `Host Submission ${stored.joinedHostSubmissionId} is missing`,\n ),\n ),\n current,\n ];\n }\n // The lane is host-owned: the presented token must own the HOST's ownership period,\n // which also lets a later host Attempt repair a lost marker from history (DUR-016).\n if (!ownsLane(host, request.ownershipToken)) {\n return [failure(ownershipLost(current, host)), current];\n }\n if (stored.inputApplied !== undefined) {\n if (\n stored.inputApplied.recordId === request.recordId &&\n stored.inputApplied.sequence === request.sequence\n ) {\n return [success(undefined), current];\n }\n\n return [\n failure(\n ledgerError(\n \"markJoined\",\n `A different join marker is already recorded for Submission ${request.submissionId}`,\n ),\n ),\n current,\n ];\n }\n if (stored.row.state !== \"joining\" && stored.row.state !== \"joined\") {\n return [\n failure(\n ledgerError(\n \"markJoined\",\n `Cannot mark Submission ${request.submissionId} joined from state ${stored.row.state}`,\n ),\n ),\n current,\n ];\n }\n\n const marker = InputAppliedMarker.make({\n recordId: request.recordId,\n sequence: request.sequence,\n });\n\n return [\n success(undefined),\n withSubmission(current, {\n ...stored,\n row: { ...stored.row, state: \"joined\" },\n inputApplied: marker,\n }),\n ];\n },\n );\n\n if (decision._tag === \"failure\") return yield* decision.error;\n }),\n );\n\n const revertJoining: SubmissionLedger[\"Service\"][\"revertJoining\"] = Effect.fn(\n \"MemorySubmissionLedger.revertJoining\",\n )((unvalidated) =>\n Effect.gen(function* () {\n const request = yield* validate(RevertJoiningRequest, \"revertJoining\", unvalidated);\n\n const decision = yield* Ref.modify(\n state,\n (current): readonly [Decision<void, LedgerError>, LedgerState] => {\n const stored = current.submissions.get(request.submissionId);\n\n if (stored === undefined) {\n return [\n failure(ledgerError(\"revertJoining\", `Unknown Submission ${request.submissionId}`)),\n current,\n ];\n }\n // Idempotent and recovery-only: only a still-`joining` Submission reverts; an\n // already-joined (or already-reverted) Submission is a no-op (DUR-016).\n if (stored.row.state !== \"joining\") return [success(undefined), current];\n\n return [\n success(undefined),\n withSubmission(current, {\n ...stored,\n row: { ...stored.row, state: \"ready\" },\n joinedHostSubmissionId: undefined,\n }),\n ];\n },\n );\n\n if (decision._tag === \"failure\") return yield* decision.error;\n }),\n );\n\n const suspend: SubmissionLedger[\"Service\"][\"suspend\"] = Effect.fn(\n \"MemorySubmissionLedger.suspend\",\n )((unvalidated) =>\n Effect.gen(function* () {\n const request = yield* validate(SuspendRequest, \"suspend\", unvalidated);\n const nowMillis = yield* Clock.currentTimeMillis;\n\n const decision = yield* Ref.modify(\n state,\n (\n current,\n ): readonly [\n Decision<SuspensionOutcome, OwnershipLost | SettlementConflict | LedgerError>,\n LedgerState,\n ] => {\n const stored = current.submissions.get(request.submissionId);\n\n if (stored === undefined) {\n return [\n failure(ledgerError(\"suspend\", `Unknown Submission ${request.submissionId}`)),\n current,\n ];\n }\n if (stored.row.state === \"settled\") {\n if (stored.row.settledOutcome === undefined) {\n return [\n failure(\n ledgerError(\n \"suspend\",\n `Settled Submission ${request.submissionId} is missing its outcome`,\n ),\n ),\n current,\n ];\n }\n\n return [\n failure(\n SettlementConflict.make({\n submissionId: request.submissionId,\n existingOutcome: stored.row.settledOutcome,\n }),\n ),\n current,\n ];\n }\n // An exact terminal outcome is already reserved (DUR-011); suspension would\n // contradict it, so the reservation wins.\n if (stored.reservation !== undefined) {\n return [\n failure(\n SettlementConflict.make({\n submissionId: request.submissionId,\n existingOutcome: stored.reservation.outcome,\n }),\n ),\n current,\n ];\n }\n if (!ownsLane(stored, request.ownershipToken)) {\n return [failure(ownershipLost(current, stored)), current];\n }\n\n // A covering event that raced ahead of the suspend transaction (an approval decision,\n // or a child settlement observed directly from the child's row in this single store)\n // resumes the caller immediately WITHOUT releasing the lane (plan §2.6, spec §12).\n const alreadyCovered =\n request.reason._tag === \"ApprovalPending\"\n ? request.reason.toolCallIds.every((toolCallId) =>\n stored.approvalDecisions.has(toolCallId),\n )\n : request.reason.children.every(\n (child) =>\n current.submissions.get(child.childSubmissionId)?.row.state === \"settled\",\n );\n\n if (alreadyCovered) {\n return [success(\"resume-immediately\" as const), current];\n }\n\n return [\n success(\"suspended\" as const),\n withSubmission(current, {\n ...stored,\n row: { ...stored.row, state: \"suspended\" },\n ownership: undefined,\n suspension: { reason: request.reason, suspendedAtMillis: nowMillis },\n }),\n ];\n },\n );\n\n if (decision._tag === \"failure\") return yield* decision.error;\n\n return decision.value;\n }),\n );\n\n const recordApprovalDecision: SubmissionLedger[\"Service\"][\"recordApprovalDecision\"] = Effect.fn(\n \"MemorySubmissionLedger.recordApprovalDecision\",\n )((unvalidated) =>\n Effect.gen(function* () {\n const command = yield* validate(\n ApprovalDecisionCommand,\n \"recordApprovalDecision\",\n unvalidated,\n );\n\n const nowMillis = yield* Clock.currentTimeMillis;\n\n const decision = yield* Ref.modify(\n state,\n (\n current,\n ): readonly [\n Decision<ApprovalDecisionIntent, ApprovalConflict | SettlementConflict | LedgerError>,\n LedgerState,\n ] => {\n const stored = current.submissions.get(command.submissionId);\n\n if (stored === undefined) {\n return [\n failure(\n ledgerError(\n \"recordApprovalDecision\",\n `Unknown Submission ${command.submissionId}`,\n ),\n ),\n current,\n ];\n }\n if (stored.row.state === \"settled\") {\n if (stored.row.settledOutcome === undefined) {\n return [\n failure(\n ledgerError(\n \"recordApprovalDecision\",\n `Settled Submission ${command.submissionId} is missing its outcome`,\n ),\n ),\n current,\n ];\n }\n\n return [\n failure(\n SettlementConflict.make({\n submissionId: command.submissionId,\n existingOutcome: stored.row.settledOutcome,\n }),\n ),\n current,\n ];\n }\n const existing = stored.approvalDecisions.get(command.toolCallId);\n\n if (existing !== undefined) {\n if (existing.decision !== command.decision) {\n return [\n failure(\n ApprovalConflict.make({\n submissionId: command.submissionId,\n toolCallId: command.toolCallId,\n existingDecision: existing.decision,\n }),\n ),\n current,\n ];\n }\n\n return [success(existing), current];\n }\n\n const intent = ApprovalDecisionIntent.make({\n submissionId: command.submissionId,\n toolCallId: command.toolCallId,\n decision: command.decision,\n resolver: command.resolver,\n reason: command.reason,\n decidedAt: utc(nowMillis),\n });\n\n const approvalDecisions = new Map(stored.approvalDecisions).set(\n command.toolCallId,\n intent,\n );\n\n // Once every pending call of an ApprovalPending suspension is decided, the lane\n // wakes: suspended → input-applied (plan §2.6). A WaitingForChild suspension wakes\n // only through recordChildSettled.\n const wakes =\n stored.row.state === \"suspended\" &&\n stored.suspension !== undefined &&\n stored.suspension.reason._tag === \"ApprovalPending\" &&\n stored.suspension.reason.toolCallIds.every((toolCallId) =>\n approvalDecisions.has(toolCallId),\n );\n\n return [\n success(intent),\n withSubmission(current, {\n ...stored,\n row: wakes ? { ...stored.row, state: \"input-applied\" } : stored.row,\n suspension: wakes ? undefined : stored.suspension,\n approvalDecisions,\n }),\n ];\n },\n );\n\n if (decision._tag === \"failure\") return yield* decision.error;\n\n return decision.value;\n }),\n );\n\n const markUnknown: SubmissionLedger[\"Service\"][\"markUnknown\"] = Effect.fn(\n \"MemorySubmissionLedger.markUnknown\",\n )((unvalidated) =>\n Effect.gen(function* () {\n const request = yield* validate(MarkUnknownRequest, \"markUnknown\", unvalidated);\n\n const decision = yield* Ref.modify(\n state,\n (current): readonly [Decision<void, SettlementConflict | LedgerError>, LedgerState] => {\n const stored = current.submissions.get(request.submissionId);\n\n if (stored === undefined) {\n return [\n failure(ledgerError(\"markUnknown\", `Unknown Submission ${request.submissionId}`)),\n current,\n ];\n }\n if (stored.row.state === \"settled\") {\n if (stored.row.settledOutcome === undefined) {\n return [\n failure(\n ledgerError(\n \"markUnknown\",\n `Settled Submission ${request.submissionId} is missing its outcome`,\n ),\n ),\n current,\n ];\n }\n\n return [\n failure(\n SettlementConflict.make({\n submissionId: request.submissionId,\n existingOutcome: stored.row.settledOutcome,\n }),\n ),\n current,\n ];\n }\n // A reserved exact outcome wins over a late Unknown marking (DUR-011); the recovery\n // classifier orders reservation ahead of MarkUnknown for the same reason.\n if (stored.reservation !== undefined) {\n return [\n failure(\n SettlementConflict.make({\n submissionId: request.submissionId,\n existingOutcome: stored.reservation.outcome,\n }),\n ),\n current,\n ];\n }\n // Idempotent merge: repeating is a no-op; additional open calls extend the marked\n // set while the first recorded reason is kept.\n const existing = stored.unknownMark;\n const known = new Set(existing?.toolCallIds ?? []);\n\n const merged = [\n ...(existing?.toolCallIds ?? []),\n ...request.toolCallIds.filter((toolCallId) => !known.has(toolCallId)),\n ];\n\n return [\n success(undefined),\n withSubmission(current, {\n ...stored,\n row:\n stored.row.state === \"unknown\" ? stored.row : { ...stored.row, state: \"unknown\" },\n unknownMark: { reason: existing?.reason ?? request.reason, toolCallIds: merged },\n }),\n ];\n },\n );\n\n if (decision._tag === \"failure\") return yield* decision.error;\n }),\n );\n\n const recordUnknownResolution: SubmissionLedger[\"Service\"][\"recordUnknownResolution\"] =\n Effect.fn(\"MemorySubmissionLedger.recordUnknownResolution\")((unvalidated) =>\n Effect.gen(function* () {\n const command = yield* validate(\n UnknownResolutionCommand,\n \"recordUnknownResolution\",\n unvalidated,\n );\n\n const nowMillis = yield* Clock.currentTimeMillis;\n\n const decision = yield* Ref.modify(\n state,\n (\n current,\n ): readonly [\n Decision<\n UnknownResolutionIntent,\n UnknownResolutionConflict | SettlementConflict | LedgerError\n >,\n LedgerState,\n ] => {\n const stored = current.submissions.get(command.submissionId);\n\n if (stored === undefined) {\n return [\n failure(\n ledgerError(\n \"recordUnknownResolution\",\n `Unknown Submission ${command.submissionId}`,\n ),\n ),\n current,\n ];\n }\n if (stored.row.state === \"settled\") {\n if (stored.row.settledOutcome === undefined) {\n return [\n failure(\n ledgerError(\n \"recordUnknownResolution\",\n `Settled Submission ${command.submissionId} is missing its outcome`,\n ),\n ),\n current,\n ];\n }\n\n return [\n failure(\n SettlementConflict.make({\n submissionId: command.submissionId,\n existingOutcome: stored.row.settledOutcome,\n }),\n ),\n current,\n ];\n }\n const existing = stored.unknownResolutions.get(command.toolCallId);\n\n if (\n existing !== undefined &&\n !equivalentUnknownResolution(existing.intent.resolution, command.resolution)\n ) {\n return [\n failure(\n UnknownResolutionConflict.make({\n submissionId: command.submissionId,\n toolCallId: command.toolCallId,\n }),\n ),\n current,\n ];\n }\n\n const intent =\n existing?.intent ??\n UnknownResolutionIntent.make({\n submissionId: command.submissionId,\n toolCallId: command.toolCallId,\n author: command.author,\n reason: command.reason,\n resolution: command.resolution,\n resolvedAt: utc(nowMillis),\n });\n\n const unknownResolutions =\n existing !== undefined\n ? stored.unknownResolutions\n : new Map(stored.unknownResolutions).set(command.toolCallId, {\n intent,\n });\n\n // The lane reopens only when EVERY marked open call has a durable resolution\n // intent: unknown → input-applied (DUR-017). Replays re-run the coverage check so\n // a recovering caller can wake the lane idempotently.\n const wakes =\n stored.row.state === \"unknown\" &&\n stored.unknownMark !== undefined &&\n stored.unknownMark.toolCallIds.every((toolCallId) =>\n unknownResolutions.has(toolCallId),\n );\n\n return [\n success(intent),\n withSubmission(current, {\n ...stored,\n row: wakes ? { ...stored.row, state: \"input-applied\" } : stored.row,\n unknownMark: wakes ? undefined : stored.unknownMark,\n unknownResolutions,\n }),\n ];\n },\n );\n\n if (decision._tag === \"failure\") return yield* decision.error;\n\n return decision.value;\n }),\n );\n\n const recordChildSettled: SubmissionLedger[\"Service\"][\"recordChildSettled\"] = Effect.fn(\n \"MemorySubmissionLedger.recordChildSettled\",\n )((unvalidated) =>\n Effect.gen(function* () {\n const request = yield* validate(\n ChildSettledNotification,\n \"recordChildSettled\",\n unvalidated,\n );\n\n const decision = yield* Ref.modify(\n state,\n (current): readonly [Decision<ChildSettledOutcome, LedgerError>, LedgerState] => {\n const parent = current.submissions.get(request.parentSubmissionId);\n\n if (parent === undefined) {\n return [\n failure(\n ledgerError(\n \"recordChildSettled\",\n `Unknown Submission ${request.parentSubmissionId}`,\n ),\n ),\n current,\n ];\n }\n // The caller may notify after the canonical Settlement append but before ledger\n // finalization. In a single store, an exact reservation plus `terminalizing` is the\n // narrow durable prefix that makes that ordering admissible; earlier states remain\n // a caller error.\n const child = current.submissions.get(request.childSubmissionId);\n\n const announced =\n child !== undefined &&\n (child.row.state === \"settled\" ||\n (child.row.state === \"terminalizing\" && child.reservation !== undefined));\n\n if (!announced) {\n return [\n failure(\n ledgerError(\n \"recordChildSettled\",\n `Child Submission ${request.childSubmissionId} has no recorded settlement`,\n ),\n ),\n current,\n ];\n }\n if (\n parent.row.state !== \"suspended\" ||\n parent.suspension === undefined ||\n parent.suspension.reason._tag !== \"WaitingForChild\"\n ) {\n return [success(\"not-waiting\" as const), current];\n }\n const children = parent.suspension.reason.children;\n\n if (!children.some((entry) => entry.childSubmissionId === request.childSubmissionId)) {\n return [success(\"not-waiting\" as const), current];\n }\n\n // Every listed child must be either finalized or canonically announced from the\n // exact terminalizing reservation. Replays re-run this coverage check idempotently.\n const allSettled = children.every((entry) => {\n const listed = current.submissions.get(entry.childSubmissionId);\n\n return (\n listed?.row.state === \"settled\" ||\n (listed?.row.state === \"terminalizing\" && listed.reservation !== undefined)\n );\n });\n\n if (!allSettled) return [success(\"still-waiting\" as const), current];\n\n return [\n success(\"woken\" as const),\n withSubmission(current, {\n ...parent,\n row: { ...parent.row, state: \"input-applied\" },\n suspension: undefined,\n }),\n ];\n },\n );\n\n if (decision._tag === \"failure\") return yield* decision.error;\n\n return decision.value;\n }),\n );\n\n const reserveChildBudget: SubmissionLedger[\"Service\"][\"reserveChildBudget\"] = Effect.fn(\n \"MemorySubmissionLedger.reserveChildBudget\",\n )((unvalidated) =>\n Effect.gen(function* () {\n const request = yield* validate(\n ChildBudgetReservationRequest,\n \"reserveChildBudget\",\n unvalidated,\n );\n\n const nowMillis = yield* Clock.currentTimeMillis;\n\n const decision = yield* Ref.modify(\n state,\n (\n current,\n ): readonly [\n Decision<ReservedChildBudget, ChildReservationConflict | OwnershipLost | LedgerError>,\n LedgerState,\n ] => {\n const existing = current.childReservations.get(request.reservationId);\n\n if (existing !== undefined) {\n // Identical replays short-circuit before the fence, mirroring reserveSettlement:\n // a replay creates nothing, so a recovering caller resumes rather than duplicates.\n const identical =\n existing.parentSubmissionId === request.parentSubmissionId &&\n existing.parentToolCallId === request.parentToolCallId &&\n existing.allocationDigest === request.allocationDigest &&\n equivalentPersistedJson(existing.allocation, request.allocation);\n\n if (!identical) {\n return [\n failure(\n ChildReservationConflict.make({\n reservationId: request.reservationId,\n status: existing.status,\n message:\n \"A reservation with this identity exists with a different parent Tool Call or allocation.\",\n }),\n ),\n current,\n ];\n }\n\n return [\n success(\n ReservedChildBudget.make({\n reservation: toReservationSnapshot(existing),\n replayed: true,\n }),\n ),\n current,\n ];\n }\n for (const reservation of current.childReservations.values()) {\n if (\n reservation.parentSubmissionId === request.parentSubmissionId &&\n reservation.parentToolCallId === request.parentToolCallId\n ) {\n return [\n failure(\n ChildReservationConflict.make({\n reservationId: request.reservationId,\n status: reservation.status,\n message: `Parent Tool Call ${request.parentToolCallId} already owns reservation ${reservation.reservationId}.`,\n }),\n ),\n current,\n ];\n }\n }\n const parent = current.submissions.get(request.parentSubmissionId);\n\n if (parent === undefined) {\n return [\n failure(\n ledgerError(\n \"reserveChildBudget\",\n `Unknown Submission ${request.parentSubmissionId}`,\n ),\n ),\n current,\n ];\n }\n // Creation is fenced by the parent lane's live ownership (spec §12 step 2): a stale\n // parent Attempt can never create new reservation state.\n if (!ownsLane(parent, request.ownershipToken)) {\n return [failure(ownershipLost(current, parent)), current];\n }\n\n const reservation: StoredChildReservation = {\n reservationId: request.reservationId,\n parentSubmissionId: request.parentSubmissionId,\n parentToolCallId: request.parentToolCallId,\n childSubmissionId: undefined,\n status: \"reserved\",\n allocation: request.allocation,\n allocationDigest: request.allocationDigest,\n accounting: undefined,\n reservedAtMillis: nowMillis,\n releaseBeganAtMillis: undefined,\n releasedAtMillis: undefined,\n };\n\n return [\n success(\n ReservedChildBudget.make({\n reservation: toReservationSnapshot(reservation),\n replayed: false,\n }),\n ),\n withChildReservation(current, reservation),\n ];\n },\n );\n\n if (decision._tag === \"failure\") return yield* decision.error;\n\n return decision.value;\n }),\n );\n\n const attachChildToReservation: SubmissionLedger[\"Service\"][\"attachChildToReservation\"] =\n Effect.fn(\"MemorySubmissionLedger.attachChildToReservation\")((unvalidated) =>\n Effect.gen(function* () {\n const request = yield* validate(\n AttachChildToReservationRequest,\n \"attachChildToReservation\",\n unvalidated,\n );\n\n const decision = yield* Ref.modify(\n state,\n (\n current,\n ): readonly [\n Decision<\n ChildBudgetReservationSnapshot,\n ChildReservationConflict | OwnershipLost | LedgerError\n >,\n LedgerState,\n ] => {\n const reservation = current.childReservations.get(request.reservationId);\n\n if (reservation === undefined) {\n return [\n failure(\n ledgerError(\n \"attachChildToReservation\",\n `Unknown child reservation ${request.reservationId}`,\n ),\n ),\n current,\n ];\n }\n if (reservation.childSubmissionId !== undefined) {\n // Idempotent replay of the recorded attachment (unfenced — it mutates nothing).\n if (reservation.childSubmissionId === request.childSubmissionId) {\n return [success(toReservationSnapshot(reservation)), current];\n }\n\n return [\n failure(\n ChildReservationConflict.make({\n reservationId: request.reservationId,\n status: reservation.status,\n message: `Reservation ${request.reservationId} already records child ${reservation.childSubmissionId}.`,\n }),\n ),\n current,\n ];\n }\n const parent = current.submissions.get(reservation.parentSubmissionId);\n\n if (parent === undefined) {\n return [\n failure(\n ledgerError(\n \"attachChildToReservation\",\n `Unknown Submission ${reservation.parentSubmissionId}`,\n ),\n ),\n current,\n ];\n }\n if (!ownsLane(parent, request.ownershipToken)) {\n return [failure(ownershipLost(current, parent)), current];\n }\n if (reservation.status !== \"reserved\") {\n return [\n failure(\n ChildReservationConflict.make({\n reservationId: request.reservationId,\n status: reservation.status,\n message: `Cannot attach a child to a ${reservation.status} reservation.`,\n }),\n ),\n current,\n ];\n }\n // Single-store latitude: the admitted child must exist here, so a dangling\n // attachment can never enter the recovery view.\n if (!current.submissions.has(request.childSubmissionId)) {\n return [\n failure(\n ledgerError(\n \"attachChildToReservation\",\n `Unknown child Submission ${request.childSubmissionId}`,\n ),\n ),\n current,\n ];\n }\n\n const attached: StoredChildReservation = {\n ...reservation,\n childSubmissionId: request.childSubmissionId,\n };\n\n return [\n success(toReservationSnapshot(attached)),\n withChildReservation(current, attached),\n ];\n },\n );\n\n if (decision._tag === \"failure\") return yield* decision.error;\n\n return decision.value;\n }),\n );\n\n const beginChildBudgetRelease: SubmissionLedger[\"Service\"][\"beginChildBudgetRelease\"] =\n Effect.fn(\"MemorySubmissionLedger.beginChildBudgetRelease\")((unvalidated) =>\n Effect.gen(function* () {\n const request = yield* validate(\n BeginChildBudgetReleaseRequest,\n \"beginChildBudgetRelease\",\n unvalidated,\n );\n\n const nowMillis = yield* Clock.currentTimeMillis;\n\n const decision = yield* Ref.modify(\n state,\n (\n current,\n ): readonly [\n Decision<ChildBudgetReservationSnapshot, ChildReservationConflict | LedgerError>,\n LedgerState,\n ] => {\n const reservation = current.childReservations.get(request.reservationId);\n\n if (reservation === undefined) {\n return [\n failure(\n ledgerError(\n \"beginChildBudgetRelease\",\n `Unknown child reservation ${request.reservationId}`,\n ),\n ),\n current,\n ];\n }\n if (reservation.status !== \"reserved\") {\n // The accounting decision was already frozen exactly once; an identical replay is\n // a no-op and a divergent decision conflicts (spec §12 join step 6).\n if (\n reservation.accounting !== undefined &&\n equivalentPersistedJson(reservation.accounting, request.accounting)\n ) {\n return [success(toReservationSnapshot(reservation)), current];\n }\n\n return [\n failure(\n ChildReservationConflict.make({\n reservationId: request.reservationId,\n status: reservation.status,\n message:\n \"A different accounting decision is already frozen for this reservation.\",\n }),\n ),\n current,\n ];\n }\n\n const frozen: StoredChildReservation = {\n ...reservation,\n status: \"releasePending\",\n accounting: request.accounting,\n releaseBeganAtMillis: nowMillis,\n };\n\n return [\n success(toReservationSnapshot(frozen)),\n withChildReservation(current, frozen),\n ];\n },\n );\n\n if (decision._tag === \"failure\") return yield* decision.error;\n\n return decision.value;\n }),\n );\n\n const releaseChildBudget: SubmissionLedger[\"Service\"][\"releaseChildBudget\"] = Effect.fn(\n \"MemorySubmissionLedger.releaseChildBudget\",\n )((unvalidated) =>\n Effect.gen(function* () {\n const request = yield* validate(\n ReleaseChildBudgetRequest,\n \"releaseChildBudget\",\n unvalidated,\n );\n\n const nowMillis = yield* Clock.currentTimeMillis;\n\n const decision = yield* Ref.modify(\n state,\n (\n current,\n ): readonly [\n Decision<ChildBudgetReservationSnapshot, ChildReservationConflict | LedgerError>,\n LedgerState,\n ] => {\n const reservation = current.childReservations.get(request.reservationId);\n\n if (reservation === undefined) {\n return [\n failure(\n ledgerError(\n \"releaseChildBudget\",\n `Unknown child reservation ${request.reservationId}`,\n ),\n ),\n current,\n ];\n }\n // Applied exactly once: replaying a released reservation returns the stored row\n // unchanged (spec §12: \"never available twice\").\n if (reservation.status === \"released\") {\n return [success(toReservationSnapshot(reservation)), current];\n }\n if (reservation.status !== \"releasePending\") {\n return [\n failure(\n ChildReservationConflict.make({\n reservationId: request.reservationId,\n status: reservation.status,\n message:\n \"Cannot release a reservation whose accounting decision is not frozen.\",\n }),\n ),\n current,\n ];\n }\n\n const released: StoredChildReservation = {\n ...reservation,\n status: \"released\",\n releasedAtMillis: nowMillis,\n };\n\n return [\n success(toReservationSnapshot(released)),\n withChildReservation(current, released),\n ];\n },\n );\n\n if (decision._tag === \"failure\") return yield* decision.error;\n\n return decision.value;\n }),\n );\n\n const scanNonterminal: SubmissionLedger[\"Service\"][\"scanNonterminal\"] = Stream.unwrap(\n Ref.get(state).pipe(\n Effect.map((current) => {\n const snapshots = [...current.submissions.values()]\n .filter((stored) => stored.row.state !== \"settled\")\n .sort((left, right) =>\n left.row.threadId < right.row.threadId\n ? -1\n : left.row.threadId > right.row.threadId\n ? 1\n : left.row.queueSequence - right.row.queueSequence,\n )\n .map((stored) => toSnapshot(stored.row));\n\n return Stream.fromIterable(snapshots);\n }),\n ),\n );\n\n const readAbortIntent: SubmissionLedger[\"Service\"][\"readAbortIntent\"] = Effect.fn(\n \"MemorySubmissionLedger.readAbortIntent\",\n )(function* (unvalidated) {\n const request = yield* validate(AbortIntentRequest, \"readAbortIntent\", unvalidated);\n const stored = (yield* Ref.get(state)).submissions.get(request.submissionId);\n\n if (stored === undefined) {\n return yield* ledgerError(\"readAbortIntent\", `Unknown Submission ${request.submissionId}`);\n }\n\n return stored.abortIntent;\n });\n\n const loadRecoverySnapshot: SubmissionLedger[\"Service\"][\"loadRecoverySnapshot\"] = Effect.fn(\n \"MemorySubmissionLedger.loadRecoverySnapshot\",\n )((unvalidated) =>\n Effect.gen(function* () {\n const request = yield* validate(\n RecoverySnapshotRequest,\n \"loadRecoverySnapshot\",\n unvalidated,\n );\n\n const current = yield* Ref.get(state);\n const stored = current.submissions.get(request.submissionId);\n\n if (stored === undefined) {\n return yield* ledgerError(\n \"loadRecoverySnapshot\",\n `Unknown Submission ${request.submissionId}`,\n );\n }\n\n const joins = [...current.submissions.values()]\n .filter((candidate) => candidate.joinedHostSubmissionId === request.submissionId)\n .sort((left, right) => left.row.queueSequence - right.row.queueSequence)\n .map((candidate) =>\n JoinSnapshot.make({\n submissionId: candidate.row.submissionId,\n state: candidate.row.state,\n hostSubmissionId: request.submissionId,\n }),\n );\n\n const byToolCallId = <A extends { readonly toolCallId: ToolCallId }>(\n left: A,\n right: A,\n ): number =>\n left.toolCallId < right.toolCallId ? -1 : left.toolCallId > right.toolCallId ? 1 : 0;\n\n // Parent-side subagent view: this Submission's child budget reservations in parent Tool\n // Call order, plus each attached child's current lane state (a disposable derived view;\n // the canonical records stay the recovery truth, DUR-015).\n const childReservations = [...current.childReservations.values()]\n .filter((reservation) => reservation.parentSubmissionId === request.submissionId)\n .sort((left, right) =>\n left.parentToolCallId < right.parentToolCallId\n ? -1\n : left.parentToolCallId > right.parentToolCallId\n ? 1\n : 0,\n );\n\n const childAttachments: Array<ChildAttachmentSnapshot> = [];\n\n for (const reservation of childReservations) {\n if (reservation.childSubmissionId === undefined) continue;\n const child = current.submissions.get(reservation.childSubmissionId);\n\n if (child === undefined) continue;\n childAttachments.push(\n ChildAttachmentSnapshot.make({\n toolCallId: reservation.parentToolCallId,\n childSubmissionId: reservation.childSubmissionId,\n childState: child.row.state,\n ...(child.row.settledOutcome === undefined\n ? {}\n : { childOutcome: child.row.settledOutcome }),\n }),\n );\n }\n\n return RecoverySnapshot.make({\n submission: toSnapshot(stored.row),\n joins,\n approvalDecisions: [...stored.approvalDecisions.values()].sort(byToolCallId),\n unknownResolutions: [...stored.unknownResolutions.values()]\n .map((resolution) => resolution.intent)\n .sort(byToolCallId),\n childReservations: childReservations.map(toReservationSnapshot),\n childAttachments,\n ...(stored.row.parentLinkage === undefined\n ? {}\n : { parentLinkage: stored.row.parentLinkage }),\n ...(stored.joinedHostSubmissionId === undefined\n ? {}\n : { hostSubmissionId: stored.joinedHostSubmissionId }),\n ...(stored.suspension === undefined\n ? {}\n : {\n suspension: SuspensionSnapshot.make({\n reason: stored.suspension.reason,\n suspendedAt: utc(stored.suspension.suspendedAtMillis),\n }),\n }),\n ...(stored.ownership === undefined\n ? {}\n : {\n ownership: OwnershipSnapshot.make({\n attemptId: stored.ownership.attemptId,\n ownerProducerId: stored.ownership.ownerProducerId,\n producerEpoch: stored.ownership.producerEpoch,\n leaseExpiresAt: utc(stored.ownership.leaseExpiresAtMillis),\n }),\n }),\n ...(stored.inputApplied === undefined ? {} : { inputApplied: stored.inputApplied }),\n ...(stored.reservation === undefined\n ? {}\n : {\n reservation: SettlementReservationSnapshot.make({\n settlementId: stored.reservation.settlementId,\n outcome: stored.reservation.outcome,\n record: stored.reservation.record,\n recordDigest: stored.reservation.recordDigest,\n finalized: stored.reservation.finalizedAtMillis !== undefined,\n }),\n }),\n ...(stored.abortIntent === undefined ? {} : { abortIntent: stored.abortIntent }),\n });\n }),\n );\n\n return SubmissionLedger.of({\n capabilities,\n admit,\n markReady,\n lookup,\n resolveAdmission,\n claim,\n renewOwnership,\n releaseOwnership,\n markInputApplied,\n reserveSettlement,\n finalizeSettlement,\n requestAbort,\n claimJoining,\n markJoined,\n revertJoining,\n suspend,\n recordApprovalDecision,\n markUnknown,\n recordUnknownResolution,\n recordChildSettled,\n reserveChildBudget,\n attachChildToReservation,\n beginChildBudgetRelease,\n releaseChildBudget,\n scanNonterminal,\n loadRecoverySnapshot,\n readAbortIntent,\n });\n });\n\n/** Construction options for the in-memory reference SubmissionLedger. */\nexport interface MemorySubmissionLedgerOptions {\n /**\n * Test-only fault seam for `resolveAdmission` (SUB-031): when the effect yields a reason,\n * the resolution answers `Indeterminate` with it instead of consulting the store — modelling\n * an authoritative child owner that is temporarily unreachable. `Option.none()` restores the\n * store-derived answer. Ledger state is never mutated by the fault.\n */\n readonly resolveAdmissionFault?: Effect.Effect<Option.Option<string>>;\n}\n\n/**\n * In-memory reference SubmissionLedger Layer (durability `non-durable`). All state lives in one\n * `Ref` owned by the Layer's Scope; no daemon fibers are spawned and no wall clock is consulted.\n */\nexport const memorySubmissionLedgerLayer = (\n options: MemorySubmissionLedgerOptions = {},\n): Layer.Layer<SubmissionLedger> => Layer.effect(SubmissionLedger, makeSubmissionLedger(options));\n\nexport const MemorySubmissionLedgerLive: Layer.Layer<SubmissionLedger> =\n memorySubmissionLedgerLayer();\n"],"mappings":";;;;;;;;;;;AA+GA,MAAM,kBAAkB;;;;;;AAOxB,MAAM,aAA8C;CAClD,UAAU;CACV,OAAO;CACP,SAAS;CACT,QAAQ;CACR,SAAS;CACT,iBAAiB;CACjB,WAAW;CACX,SAAS;CACT,eAAe;CACf,SAAS;AACX;;;;;;AA2EA,MAAM,sCAAoD,IAAI,IAAI;CAChE;CACA;CACA;AACF,CAAC;AAkCD,MAAM,WAAc,WAAkC;CAAE,MAAM;CAAW;AAAM;AAC/E,MAAM,WAAc,WAAkC;CAAE,MAAM;CAAW;AAAM;AAE/E,MAAM,eAAe,WAAmB,S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,OAAO,YAAY;IAC5B,QAAQ,OAAO,YAAY;IAC3B,cAAc,OAAO,YAAY;IACjC,WAAW,OAAO,YAAY,sBAAsB,KAAA;GACtD,CAAC,EACH;GACJ,GAAI,OAAO,gBAAgB,KAAA,IAAY,CAAC,IAAI,EAAE,aAAa,OAAO,YAAY;EAChF,CAAC;CACH,CAAC,CACH;CAEA,OAAO,iBAAiB,GAAG;EACzB;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;CACF,CAAC;AACH,CAAC;;;;;AAiBH,MAAa,+BACX,UAAyC,CAAC,MACR,MAAM,OAAO,kBAAkB,qBAAqB,OAAO,CAAC;AAEhG,MAAa,6BACX,4BAA4B"}
1
+ {"version":3,"file":"MemorySubmissionLedger.mjs","names":[],"sources":["../src/MemorySubmissionLedger.ts"],"sourcesContent":["import {\n Clock,\n Cause,\n Exit,\n Fiber,\n DateTime,\n Duration,\n Effect,\n Layer,\n Option,\n Ref,\n Schema,\n Stream,\n} from \"effect\";\nimport {\n type ToolCallId,\n AttemptId,\n ReceiptId,\n SubmissionId,\n type AgentId,\n type ThreadId,\n type SettlementId,\n} from \"effect-agent/identifiers\";\nimport { InputMessage } from \"effect-agent/messaging\";\nimport {\n PersistedJson,\n WorkerAdmission,\n ProducerEpoch,\n type DefinitionDigests,\n type DeploymentId,\n type Digest,\n type ProducerId,\n type RecordEnvelope,\n type SettlementOutcome,\n} from \"effect-agent/records\";\nimport {\n type ParentLinkage,\n AbortCommand,\n AdmissionAdmitted,\n AdmissionConflict,\n AdmissionPolicyError,\n AdmissionIndeterminate,\n AdmissionNotAdmitted,\n AdmissionRequest,\n SubmissionAdmissionFence,\n AdmissionResult,\n ApprovalConflict,\n ApprovalDecisionCommand,\n ApprovalDecisionIntent,\n AttachChildToReservationRequest,\n BeginChildBudgetReleaseRequest,\n ChildAttachmentSnapshot,\n ChildBudgetReservationRequest,\n ChildBudgetReservationSnapshot,\n ChildReservationConflict,\n ChildSettledNotification,\n Claim,\n ClaimJoiningRequest,\n ClaimRequest,\n DEFAULT_OWNERSHIP_LEASE_DURATION,\n InputAppliedMarker,\n JoinSnapshot,\n JoinedToHost,\n JoiningClaim,\n LedgerCapabilities,\n LedgerError,\n MarkInputAppliedRequest,\n MarkJoinedRequest,\n MarkReadyRequest,\n MarkUnknownRequest,\n OwnershipLost,\n OwnershipRenewal,\n OwnershipSnapshot,\n OwnershipToken,\n QueueSequence,\n RecoverySnapshot,\n RecoverySnapshotRequest,\n ReleaseChildBudgetRequest,\n ReleaseOwnershipRequest,\n RenewOwnershipRequest,\n ReservedChildBudget,\n ReservedSettlement,\n RevertJoiningRequest,\n Settlement,\n SettlementConflict,\n SettlementFinalization,\n SettlementReservation,\n SettlementReservationSnapshot,\n settlementFailureFromRecord,\n AbortIntent,\n AbortIntentRequest,\n SubmissionLedger,\n SubmissionLookup,\n SubmissionLookupByKey,\n SubmissionSnapshot,\n SuspendRequest,\n SuspensionSnapshot,\n UnknownResolution,\n UnknownResolutionCommand,\n UnknownResolutionConflict,\n UnknownResolutionIntent,\n type ChildReservationId,\n type ChildReservationStatus,\n type ChildSettledOutcome,\n type IdempotencyKey,\n type Principal,\n type SubmissionState,\n type SuspensionOutcome,\n type SuspensionReason,\n} from \"effect-agent/submission-ledger\";\n\nconst MAX_SUBMISSIONS = 65_536;\n\n/**\n * Lifecycle ordering used to advance-but-never-regress the operational state marker: a reclaimed\n * Attempt must not erase progress markers (input-applied, terminalizing) that an earlier Attempt\n * already committed.\n */\nconst STATE_RANK: Record<SubmissionState, number> = {\n admitted: 0,\n ready: 1,\n joining: 2,\n joined: 3,\n running: 4,\n \"input-applied\": 5,\n suspended: 6,\n unknown: 7,\n terminalizing: 8,\n settled: 9,\n};\n\ninterface SubmissionRow {\n readonly submissionId: SubmissionId;\n readonly threadId: ThreadId;\n readonly queueSequence: QueueSequence;\n readonly principal: Principal;\n readonly idempotencyKey: IdempotencyKey;\n readonly agentId: AgentId;\n readonly agentDigests: DefinitionDigests;\n readonly deploymentId: DeploymentId;\n readonly inputPayload: PersistedJson;\n readonly inputDigest: Digest;\n readonly receiptId: ReceiptId;\n readonly state: SubmissionState;\n readonly settledOutcome: SettlementOutcome | undefined;\n readonly createdAtMillis: number;\n readonly readyAtMillis: number | undefined;\n /** Immutable child-side lineage recorded at admission (spec §12 step 5). */\n readonly parentLinkage: ParentLinkage | undefined;\n readonly admissionGroup?: string;\n readonly admissionFence?: AdmissionRequest[\"admissionFence\"];\n readonly workerAdmissionJson?: string;\n readonly messageAdmissionJson?: string;\n}\n\ninterface StoredOwnership {\n readonly attemptId: AttemptId;\n readonly ownershipToken: OwnershipToken;\n readonly producerEpoch: ProducerEpoch;\n readonly ownerProducerId: ProducerId;\n readonly leaseExpiresAtMillis: number;\n}\n\ninterface StoredReservation {\n readonly settlementId: SettlementId;\n readonly outcome: SettlementOutcome;\n readonly record: RecordEnvelope;\n readonly recordDigest: Digest;\n readonly finalizedAtMillis: number | undefined;\n}\n\ninterface StoredSuspension {\n readonly reason: SuspensionReason;\n readonly suspendedAtMillis: number;\n}\n\ninterface StoredUnknownMark {\n readonly reason: MarkUnknownRequest[\"reason\"];\n readonly toolCallIds: ReadonlyArray<ToolCallId>;\n}\n\ninterface StoredUnknownResolution {\n readonly intent: UnknownResolutionIntent;\n}\n\ninterface StoredSubmission {\n readonly row: SubmissionRow;\n readonly ownership: StoredOwnership | undefined;\n readonly inputApplied: InputAppliedMarker | undefined;\n readonly reservation: StoredReservation | undefined;\n readonly abortIntent: AbortIntent | undefined;\n /** Host linkage recorded at `claimJoining` time; cleared by `revertJoining` (DUR-016). */\n readonly joinedHostSubmissionId: SubmissionId | undefined;\n readonly suspension: StoredSuspension | undefined;\n readonly unknownMark: StoredUnknownMark | undefined;\n readonly approvalDecisions: ReadonlyMap<ToolCallId, ApprovalDecisionIntent>;\n readonly unknownResolutions: ReadonlyMap<ToolCallId, StoredUnknownResolution>;\n}\n\n/**\n * States in which `claim` never grants the head: the lane is host-owned (`joining`/`joined`)\n * or durably suspended rather than worker-claimable. Unknown heads are checked against abort\n * intent separately: abort authorizes cleanup and settlement, never ordinary Tool replay.\n */\nconst BLOCKED_HEAD_STATES: ReadonlySet<SubmissionState> = new Set([\n \"joining\",\n \"joined\",\n \"suspended\",\n]);\n\ninterface LaneState {\n readonly nextQueueSequence: number;\n readonly producerEpoch: number;\n}\n\n/** One parent-owned child budget reservation row (spec §12 steps 2 and 6). */\ninterface StoredChildReservation {\n readonly reservationId: ChildReservationId;\n readonly parentSubmissionId: SubmissionId;\n readonly parentToolCallId: ToolCallId;\n readonly childSubmissionId: SubmissionId | undefined;\n readonly status: ChildReservationStatus;\n readonly allocation: PersistedJson;\n readonly allocationDigest: Digest;\n readonly accounting: PersistedJson | undefined;\n readonly reservedAtMillis: number;\n readonly releaseBeganAtMillis: number | undefined;\n readonly releasedAtMillis: number | undefined;\n}\n\ninterface LedgerState {\n readonly submissions: ReadonlyMap<SubmissionId, StoredSubmission>;\n readonly admissionIndex: ReadonlyMap<string, SubmissionId>;\n readonly lanes: ReadonlyMap<ThreadId, LaneState>;\n readonly childReservations: ReadonlyMap<ChildReservationId, StoredChildReservation>;\n readonly mintCounter: number;\n}\n\ntype Decision<A, E> =\n | { readonly _tag: \"failure\"; readonly error: E }\n | { readonly _tag: \"success\"; readonly value: A };\n\nconst failure = <E>(error: E): Decision<never, E> => ({ _tag: \"failure\", error });\nconst success = <A>(value: A): Decision<A, never> => ({ _tag: \"success\", value });\n\nconst ledgerError = (operation: string, message: string, cause?: unknown): LedgerError =>\n cause === undefined\n ? LedgerError.make({ operation, message })\n : LedgerError.make({ operation, message, cause });\n\nconst validate = Effect.fn(\"MemorySubmissionLedger.validate\")(\n <A, I>(\n schema: Schema.Codec<A, I>,\n operation: string,\n value: unknown,\n ): Effect.Effect<A, LedgerError> =>\n Schema.encodeUnknownEffect(schema)(value).pipe(\n Effect.flatMap(Schema.decodeUnknownEffect(schema)),\n Effect.mapError((error) => ledgerError(operation, `Invalid ${operation} request`, error)),\n ),\n);\n\nconst decodeSubmissionId = Schema.decodeSync(SubmissionId);\nconst decodeReceiptId = Schema.decodeSync(ReceiptId);\nconst decodeAttemptId = Schema.decodeSync(AttemptId);\nconst decodeOwnershipToken = Schema.decodeSync(OwnershipToken);\nconst decodeQueueSequence = Schema.decodeSync(QueueSequence);\nconst decodeProducerEpoch = Schema.decodeSync(ProducerEpoch);\nconst equivalentPersistedJson = Schema.toEquivalence(PersistedJson);\nconst equivalentUnknownResolution = Schema.toEquivalence(UnknownResolution);\n\nconst utc = (millis: number): DateTime.Utc => DateTime.toUtc(DateTime.makeUnsafe(millis));\n\nconst admissionKey = (\n threadId: ThreadId,\n principal: Principal,\n idempotencyKey: IdempotencyKey,\n): string => JSON.stringify([threadId, principal, idempotencyKey]);\n\nconst toSnapshot = (row: SubmissionRow): SubmissionSnapshot =>\n SubmissionSnapshot.make({\n submissionId: row.submissionId,\n threadId: row.threadId,\n queueSequence: row.queueSequence,\n principal: row.principal,\n idempotencyKey: row.idempotencyKey,\n agentId: row.agentId,\n agentDigests: row.agentDigests,\n deploymentId: row.deploymentId,\n inputPayload: row.inputPayload,\n inputDigest: row.inputDigest,\n receiptId: row.receiptId,\n state: row.state,\n createdAt: utc(row.createdAtMillis),\n ...(row.admissionGroup === undefined ? {} : { admissionGroup: row.admissionGroup }),\n ...(row.admissionFence === undefined ? {} : { admissionFence: row.admissionFence }),\n ...(row.workerAdmissionJson === undefined\n ? {}\n : {\n workerAdmission: Schema.decodeSync(Schema.fromJsonString(WorkerAdmission))(\n row.workerAdmissionJson,\n ),\n }),\n ...(row.messageAdmissionJson === undefined\n ? {}\n : {\n messageAdmission: Schema.decodeSync(Schema.fromJsonString(InputMessage))(\n row.messageAdmissionJson,\n ),\n }),\n ...(row.settledOutcome === undefined ? {} : { settledOutcome: row.settledOutcome }),\n ...(row.readyAtMillis === undefined ? {} : { readyAt: utc(row.readyAtMillis) }),\n ...(row.parentLinkage === undefined ? {} : { parentLinkage: row.parentLinkage }),\n });\n\nconst toReservationSnapshot = (row: StoredChildReservation): ChildBudgetReservationSnapshot =>\n ChildBudgetReservationSnapshot.make({\n reservationId: row.reservationId,\n parentSubmissionId: row.parentSubmissionId,\n parentToolCallId: row.parentToolCallId,\n status: row.status,\n allocation: row.allocation,\n allocationDigest: row.allocationDigest,\n reservedAt: utc(row.reservedAtMillis),\n ...(row.childSubmissionId === undefined ? {} : { childSubmissionId: row.childSubmissionId }),\n ...(row.accounting === undefined ? {} : { accounting: row.accounting }),\n ...(row.releaseBeganAtMillis === undefined\n ? {}\n : { releaseBeganAt: utc(row.releaseBeganAtMillis) }),\n ...(row.releasedAtMillis === undefined ? {} : { releasedAt: utc(row.releasedAtMillis) }),\n });\n\n/** Linkage equality: both absent, or both present naming the same parent Tool Call. */\nconst sameParentLinkage = (\n left: ParentLinkage | undefined,\n right: ParentLinkage | undefined,\n): boolean =>\n left === undefined\n ? right === undefined\n : right !== undefined &&\n left.parentSubmissionId === right.parentSubmissionId &&\n left.parentToolCallId === right.parentToolCallId;\n\nconst laneEpoch = (state: LedgerState, threadId: ThreadId): number =>\n state.lanes.get(threadId)?.producerEpoch ?? 0;\n\nconst ownershipLost = (state: LedgerState, stored: StoredSubmission): OwnershipLost =>\n OwnershipLost.make({\n submissionId: stored.row.submissionId,\n actualEpoch: decodeProducerEpoch(laneEpoch(state, stored.row.threadId)),\n });\n\n/** A retained row token cannot outlive a newer owner of the same Thread. */\nconst ownsLane = (\n state: LedgerState,\n stored: StoredSubmission,\n ownershipToken: OwnershipToken,\n): boolean =>\n stored.ownership !== undefined &&\n stored.ownership.ownershipToken === ownershipToken &&\n stored.ownership.producerEpoch === laneEpoch(state, stored.row.threadId);\n\nconst withSubmission = (state: LedgerState, stored: StoredSubmission): LedgerState => ({\n ...state,\n submissions: new Map(state.submissions).set(stored.row.submissionId, stored),\n});\n\nconst withChildReservation = (\n state: LedgerState,\n reservation: StoredChildReservation,\n): LedgerState => ({\n ...state,\n childReservations: new Map(state.childReservations).set(reservation.reservationId, reservation),\n});\n\nconst findHead = (state: LedgerState, threadId: ThreadId): StoredSubmission | undefined => {\n let head: StoredSubmission | undefined;\n\n for (const stored of state.submissions.values()) {\n if (\n stored.row.threadId !== threadId ||\n stored.row.state === \"settled\" ||\n (stored.row.state === \"unknown\" && stored.abortIntent === undefined)\n )\n continue;\n if (head === undefined || stored.row.queueSequence < head.row.queueSequence) head = stored;\n }\n\n return head;\n};\n\n/**\n * Reference in-memory SubmissionLedger. It implements the full port contract — atomic idempotent\n * admission, eligible FIFO claims, producer-epoch fencing, Clock-driven ownership leases, idempotent\n * settlement reservation/finalization, and durable abort intent — with every transition applied\n * as one atomic `Ref.modify`, but its state does not survive the process (`non-durable`).\n *\n * Adapter-specific semantics within the port's latitude:\n *\n * - Time comes exclusively from the Effect `Clock` service, so `TestClock` drives lease expiry\n * deterministically; no wall clock is consulted.\n * - The ownership lease is pinned to `DEFAULT_OWNERSHIP_LEASE_DURATION` (D5); durable adapters\n * own the configuration seam.\n * - Any live lease in the Thread blocks every new claim, including the same `producerId`.\n * Unresolved unknown work is skipped only after ownership is released or expires.\n * - Claiming advances `ready` to `running` and otherwise preserves the recorded state, so\n * progress markers from an earlier Attempt survive a reclaim.\n * - `renewOwnership` keeps the token stable (the port allows rotation); a replayed admission\n * reports the Submission's current state alongside the original identities.\n * - `claimJoining` walks the strictly-later queue: rows already `joining`/`joined` to the\n * SAME host extend the claimed prefix and are skipped, and an aborted-settled row is a\n * closed obligation that is also skipped (P7 §7(c)); any other non-`ready` row (an\n * `admitted` gap, a non-aborted settled row, foreign-host linkage) breaks the prefix\n * conservatively.\n * - `markJoined` verifies the token against the HOST's live ownership (the lane is\n * host-owned), so a later host Attempt can repair a lost marker from history (DUR-016). The\n * join marker reuses the input-applied marker: the joined input IS `input:{sid}`.\n * - `suspend` and `markUnknown` refuse when an exact settlement is already reserved\n * (`SettlementConflict` with the reserved outcome) — DUR-011's reservation wins.\n * - `resolveAdmission` derives its answer from the single strongly consistent store, so it\n * never answers `Indeterminate` on its own; the test-only `resolveAdmissionFault` option\n * injects the `Indeterminate` classification so SUB-031 callers can be conformance-tested.\n * - `recordChildSettled` and `suspend(WaitingForChild)` observe child settlement directly from\n * the child rows (single-store latitude); no separate notification marker is stored.\n */\nconst makeSubmissionLedger = (options: MemorySubmissionLedgerOptions = {}) =>\n Effect.gen(function* () {\n const state = yield* Ref.make<LedgerState>({\n submissions: new Map(),\n admissionIndex: new Map(),\n lanes: new Map(),\n childReservations: new Map(),\n mintCounter: 0,\n });\n\n const admissionFence = yield* SubmissionAdmissionFence;\n const leaseMillis = Duration.toMillis(DEFAULT_OWNERSHIP_LEASE_DURATION);\n\n const capabilities = Effect.succeed(LedgerCapabilities.make({ durability: \"non-durable\" }));\n\n const admit: SubmissionLedger[\"Service\"][\"admit\"] = Effect.fn(\"MemorySubmissionLedger.admit\")(\n (unvalidated) =>\n Effect.gen(function* () {\n const request = yield* validate(AdmissionRequest, \"admit\", unvalidated);\n\n const workerAdmissionJson =\n request.workerAdmission === undefined\n ? undefined\n : yield* Schema.encodeEffect(Schema.fromJsonString(WorkerAdmission))(\n request.workerAdmission,\n ).pipe(\n Effect.mapError(() => ledgerError(\"admit\", \"Invalid worker admission metadata\")),\n );\n\n const messageAdmissionJson =\n request.messageAdmission === undefined\n ? undefined\n : yield* Schema.encodeEffect(Schema.fromJsonString(InputMessage))(\n request.messageAdmission,\n ).pipe(\n Effect.mapError(() => ledgerError(\"admit\", \"Invalid message admission metadata\")),\n );\n\n const nowMillis = yield* Clock.currentTimeMillis;\n const services = yield* Effect.context<never>();\n\n const decision = yield* Ref.modify(\n state,\n (\n current,\n ): readonly [\n (\n | Decision<AdmissionResult, AdmissionConflict | AdmissionPolicyError | LedgerError>\n | { readonly _tag: \"cause\"; readonly cause: Cause.Cause<AdmissionPolicyError> }\n ),\n LedgerState,\n ] => {\n const key = admissionKey(request.threadId, request.principal, request.idempotencyKey);\n const existingId = current.admissionIndex.get(key);\n\n if (existingId !== undefined) {\n const existing = current.submissions.get(existingId);\n\n if (existing === undefined) {\n return [\n failure(\n ledgerError(\"admit\", \"Admission index references a missing Submission\"),\n ),\n current,\n ];\n }\n // A replay must repeat the exact canonical input AND the exact parent linkage\n // (or its absence): linkage is immutable lineage (spec §12 step 5, SUB-016).\n if (\n existing.row.inputDigest !== request.inputDigest ||\n !sameParentLinkage(existing.row.parentLinkage, request.parentLinkage) ||\n existing.row.admissionGroup !== request.admissionGroup ||\n !Schema.toEquivalence(Schema.optional(WorkerAdmission))(\n existing.row.workerAdmissionJson === undefined\n ? undefined\n : Schema.decodeSync(Schema.fromJsonString(WorkerAdmission))(\n existing.row.workerAdmissionJson,\n ),\n request.workerAdmission,\n ) ||\n !Schema.toEquivalence(Schema.optional(InputMessage))(\n existing.row.messageAdmissionJson === undefined\n ? undefined\n : Schema.decodeSync(Schema.fromJsonString(InputMessage))(\n existing.row.messageAdmissionJson,\n ),\n request.messageAdmission,\n ) ||\n !Schema.toEquivalence(Schema.optional(Schema.Json))(\n existing.row.admissionFence,\n request.admissionFence,\n )\n ) {\n return [\n failure(\n AdmissionConflict.make({\n threadId: request.threadId,\n principal: request.principal,\n idempotencyKey: request.idempotencyKey,\n existingInputDigest: existing.row.inputDigest,\n attemptedInputDigest: request.inputDigest,\n }),\n ),\n current,\n ];\n }\n\n return [\n success(\n AdmissionResult.make({\n submissionId: existing.row.submissionId,\n receiptId: existing.row.receiptId,\n queueSequence: existing.row.queueSequence,\n state: existing.row.state,\n replayed: true,\n }),\n ),\n current,\n ];\n }\n\n // A Thread's first admission fixes its worker origin before canonical materialization.\n const first = [...current.submissions.values()].find(\n ({ row }) => row.threadId === request.threadId,\n );\n\n if (first !== undefined) {\n const previous =\n first.row.workerAdmissionJson === undefined\n ? undefined\n : Schema.decodeSync(Schema.fromJsonString(WorkerAdmission))(\n first.row.workerAdmissionJson,\n );\n\n if (\n !Schema.toEquivalence(Schema.optional(WorkerAdmission.fields.origin))(\n previous?.origin,\n request.workerAdmission?.origin,\n )\n )\n return [\n failure(\n AdmissionPolicyError.make({\n reason: \"refused\",\n code: \"worker-origin-conflict\",\n }),\n ),\n current,\n ];\n }\n // A memory policy and the ledger mutation share one synchronous critical section.\n // An asynchronous policy cannot fence this Ref and therefore fails closed.\n const checked = Effect.runSyncExitWith(services)(admissionFence.check(request));\n\n if (Exit.isFailure(checked)) {\n return [{ _tag: \"cause\", cause: checked.cause }, current];\n }\n if (\n request.admissionGroup !== undefined &&\n [...current.submissions.values()].some(\n ({ row }) =>\n row.threadId === request.threadId &&\n row.admissionGroup === request.admissionGroup &&\n row.state !== \"settled\",\n )\n )\n return [\n failure(\n AdmissionPolicyError.make({ reason: \"occupied\", code: \"admission-group\" }),\n ),\n current,\n ];\n if (current.submissions.size >= MAX_SUBMISSIONS) {\n return [\n failure(\n ledgerError(\"admit\", `In-memory submission limit ${MAX_SUBMISSIONS} exceeded`),\n ),\n current,\n ];\n }\n\n const lane = current.lanes.get(request.threadId) ?? {\n nextQueueSequence: 1,\n producerEpoch: 0,\n };\n\n const mintCounter = current.mintCounter + 1;\n\n const row: SubmissionRow = {\n submissionId: decodeSubmissionId(`submission-memory-${mintCounter}`),\n threadId: request.threadId,\n queueSequence: decodeQueueSequence(lane.nextQueueSequence),\n principal: request.principal,\n idempotencyKey: request.idempotencyKey,\n agentId: request.agentId,\n agentDigests: request.agentDigests,\n deploymentId: request.deploymentId,\n inputPayload: request.inputPayload,\n inputDigest: request.inputDigest,\n receiptId: decodeReceiptId(`receipt-memory-${mintCounter}`),\n state: \"admitted\",\n settledOutcome: undefined,\n createdAtMillis: nowMillis,\n readyAtMillis: undefined,\n parentLinkage: request.parentLinkage,\n ...(workerAdmissionJson === undefined ? {} : { workerAdmissionJson }),\n ...(messageAdmissionJson === undefined ? {} : { messageAdmissionJson }),\n ...(request.admissionGroup === undefined\n ? {}\n : { admissionGroup: request.admissionGroup }),\n ...(request.admissionFence === undefined\n ? {}\n : { admissionFence: request.admissionFence }),\n };\n\n const submissions = new Map(current.submissions).set(row.submissionId, {\n row,\n ownership: undefined,\n inputApplied: undefined,\n reservation: undefined,\n abortIntent: undefined,\n joinedHostSubmissionId: undefined,\n suspension: undefined,\n unknownMark: undefined,\n approvalDecisions: new Map<ToolCallId, ApprovalDecisionIntent>(),\n unknownResolutions: new Map<ToolCallId, StoredUnknownResolution>(),\n });\n\n const admissionIndex = new Map(current.admissionIndex).set(key, row.submissionId);\n\n const lanes = new Map(current.lanes).set(request.threadId, {\n nextQueueSequence: lane.nextQueueSequence + 1,\n producerEpoch: lane.producerEpoch,\n });\n\n return [\n success(\n AdmissionResult.make({\n submissionId: row.submissionId,\n receiptId: row.receiptId,\n queueSequence: row.queueSequence,\n state: row.state,\n replayed: false,\n }),\n ),\n { ...current, submissions, admissionIndex, lanes, mintCounter },\n ];\n },\n );\n\n if (decision._tag === \"failure\") return yield* decision.error;\n if (decision._tag === \"cause\") {\n for (const reason of decision.cause.reasons) {\n if (Cause.isDieReason(reason) && Cause.isAsyncFiberError(reason.defect)) {\n yield* Fiber.interrupt(reason.defect.fiber);\n\n return yield* AdmissionPolicyError.make({\n reason: \"unavailable\",\n code: \"synchronous-memory-policy-required\",\n });\n }\n }\n\n return yield* Effect.failCause(decision.cause);\n }\n\n return decision.value;\n }),\n Effect.uninterruptible,\n );\n\n const markReady: SubmissionLedger[\"Service\"][\"markReady\"] = Effect.fn(\n \"MemorySubmissionLedger.markReady\",\n )((unvalidated) =>\n Effect.gen(function* () {\n const request = yield* validate(MarkReadyRequest, \"markReady\", unvalidated);\n const nowMillis = yield* Clock.currentTimeMillis;\n\n const decision = yield* Ref.modify(\n state,\n (current): readonly [Decision<void, LedgerError>, LedgerState] => {\n const stored = current.submissions.get(request.submissionId);\n\n if (stored === undefined) {\n return [\n failure(ledgerError(\"markReady\", `Unknown Submission ${request.submissionId}`)),\n current,\n ];\n }\n if (stored.row.state !== \"admitted\") return [success(undefined), current];\n\n return [\n success(undefined),\n withSubmission(current, {\n ...stored,\n row: { ...stored.row, state: \"ready\", readyAtMillis: nowMillis },\n }),\n ];\n },\n );\n\n if (decision._tag === \"failure\") return yield* decision.error;\n }),\n );\n\n const lookup: SubmissionLedger[\"Service\"][\"lookup\"] = Effect.fn(\n \"MemorySubmissionLedger.lookup\",\n )((unvalidated) =>\n Effect.gen(function* () {\n const request = yield* validate(SubmissionLookup, \"lookup\", unvalidated);\n const current = yield* Ref.get(state);\n\n const submissionId =\n request._tag === \"SubmissionLookupById\"\n ? request.submissionId\n : current.admissionIndex.get(\n admissionKey(request.threadId, request.principal, request.idempotencyKey),\n );\n\n const stored =\n submissionId === undefined ? undefined : current.submissions.get(submissionId);\n\n return stored === undefined ? Option.none() : Option.some(toSnapshot(stored.row));\n }),\n );\n\n const resolveAdmission: SubmissionLedger[\"Service\"][\"resolveAdmission\"] = Effect.fn(\n \"MemorySubmissionLedger.resolveAdmission\",\n )((unvalidated) =>\n Effect.gen(function* () {\n const request = yield* validate(SubmissionLookupByKey, \"resolveAdmission\", unvalidated);\n\n // Test-only fault seam: lets suites exercise the Indeterminate classification that a\n // single strongly consistent store never produces on its own (SUB-031, P6 honesty).\n if (options.resolveAdmissionFault !== undefined) {\n const fault = yield* options.resolveAdmissionFault;\n\n if (Option.isSome(fault)) {\n return AdmissionIndeterminate.make({ reason: fault.value });\n }\n }\n const current = yield* Ref.get(state);\n\n const submissionId = current.admissionIndex.get(\n admissionKey(request.threadId, request.principal, request.idempotencyKey),\n );\n\n const stored =\n submissionId === undefined ? undefined : current.submissions.get(submissionId);\n\n return stored === undefined\n ? AdmissionNotAdmitted.make()\n : AdmissionAdmitted.make({ submission: toSnapshot(stored.row) });\n }),\n );\n\n const claim: SubmissionLedger[\"Service\"][\"claim\"] = Effect.fn(\"MemorySubmissionLedger.claim\")(\n (unvalidated) =>\n Effect.gen(function* () {\n const request = yield* validate(ClaimRequest, \"claim\", unvalidated);\n const nowMillis = yield* Clock.currentTimeMillis;\n\n const decision = yield* Ref.modify(\n state,\n (current): readonly [Decision<Option.Option<Claim>, LedgerError>, LedgerState] => {\n for (const stored of current.submissions.values()) {\n if (\n stored.row.threadId === request.threadId &&\n stored.ownership !== undefined &&\n stored.ownership.leaseExpiresAtMillis > nowMillis\n ) {\n return [success(Option.none()), current];\n }\n }\n const head = findHead(current, request.threadId);\n\n if (head === undefined) return [success(Option.none()), current];\n if (BLOCKED_HEAD_STATES.has(head.row.state)) return [success(Option.none()), current];\n const lane = current.lanes.get(request.threadId);\n\n if (lane === undefined) {\n return [\n failure(ledgerError(\"claim\", \"Claimable head without a Thread lane\")),\n current,\n ];\n }\n const producerEpoch = decodeProducerEpoch(lane.producerEpoch + 1);\n const mintCounter = current.mintCounter + 1;\n\n const ownership: StoredOwnership = {\n attemptId: decodeAttemptId(`attempt-memory-${mintCounter}`),\n ownershipToken: decodeOwnershipToken(`ownership-memory-${mintCounter}`),\n producerEpoch,\n ownerProducerId: request.producerId,\n leaseExpiresAtMillis: nowMillis + leaseMillis,\n };\n\n const row: SubmissionRow =\n head.row.state === \"ready\" ? { ...head.row, state: \"running\" } : head.row;\n\n const next = withSubmission(current, { ...head, row, ownership });\n\n const lanes = new Map(next.lanes).set(request.threadId, {\n nextQueueSequence: lane.nextQueueSequence,\n producerEpoch: lane.producerEpoch + 1,\n });\n\n return [\n success(\n Option.some(\n Claim.make({\n submissionId: row.submissionId,\n attemptId: ownership.attemptId,\n ownershipToken: ownership.ownershipToken,\n producerEpoch,\n leaseExpiresAt: utc(ownership.leaseExpiresAtMillis),\n inputPayload: row.inputPayload,\n }),\n ),\n ),\n { ...next, lanes, mintCounter },\n ];\n },\n );\n\n if (decision._tag === \"failure\") return yield* decision.error;\n\n return decision.value;\n }),\n );\n\n const renewOwnership: SubmissionLedger[\"Service\"][\"renewOwnership\"] = Effect.fn(\n \"MemorySubmissionLedger.renewOwnership\",\n )((unvalidated) =>\n Effect.gen(function* () {\n const request = yield* validate(RenewOwnershipRequest, \"renewOwnership\", unvalidated);\n const nowMillis = yield* Clock.currentTimeMillis;\n\n const decision = yield* Ref.modify(\n state,\n (\n current,\n ): readonly [Decision<OwnershipRenewal, OwnershipLost | LedgerError>, LedgerState] => {\n const stored = current.submissions.get(request.submissionId);\n\n if (stored === undefined) {\n return [\n failure(\n ledgerError(\"renewOwnership\", `Unknown Submission ${request.submissionId}`),\n ),\n current,\n ];\n }\n if (\n stored.ownership === undefined ||\n !ownsLane(current, stored, request.ownershipToken)\n ) {\n return [failure(ownershipLost(current, stored)), current];\n }\n\n const ownership: StoredOwnership = {\n ...stored.ownership,\n leaseExpiresAtMillis: nowMillis + leaseMillis,\n };\n\n return [\n success(\n OwnershipRenewal.make({\n ownershipToken: ownership.ownershipToken,\n leaseExpiresAt: utc(ownership.leaseExpiresAtMillis),\n }),\n ),\n withSubmission(current, { ...stored, ownership }),\n ];\n },\n );\n\n if (decision._tag === \"failure\") return yield* decision.error;\n\n return decision.value;\n }),\n );\n\n const releaseOwnership: SubmissionLedger[\"Service\"][\"releaseOwnership\"] = Effect.fn(\n \"MemorySubmissionLedger.releaseOwnership\",\n )((unvalidated) =>\n Effect.gen(function* () {\n const request = yield* validate(ReleaseOwnershipRequest, \"releaseOwnership\", unvalidated);\n\n const decision = yield* Ref.modify(\n state,\n (current): readonly [Decision<void, OwnershipLost | LedgerError>, LedgerState] => {\n const stored = current.submissions.get(request.submissionId);\n\n if (stored === undefined) {\n return [\n failure(\n ledgerError(\"releaseOwnership\", `Unknown Submission ${request.submissionId}`),\n ),\n current,\n ];\n }\n if (!ownsLane(current, stored, request.ownershipToken)) {\n return [failure(ownershipLost(current, stored)), current];\n }\n\n return [\n success(undefined),\n withSubmission(current, { ...stored, ownership: undefined }),\n ];\n },\n );\n\n if (decision._tag === \"failure\") return yield* decision.error;\n }),\n );\n\n const markInputApplied: SubmissionLedger[\"Service\"][\"markInputApplied\"] = Effect.fn(\n \"MemorySubmissionLedger.markInputApplied\",\n )((unvalidated) =>\n Effect.gen(function* () {\n const request = yield* validate(MarkInputAppliedRequest, \"markInputApplied\", unvalidated);\n\n const decision = yield* Ref.modify(\n state,\n (current): readonly [Decision<void, OwnershipLost | LedgerError>, LedgerState] => {\n const stored = current.submissions.get(request.submissionId);\n\n if (stored === undefined) {\n return [\n failure(\n ledgerError(\"markInputApplied\", `Unknown Submission ${request.submissionId}`),\n ),\n current,\n ];\n }\n if (!ownsLane(current, stored, request.ownershipToken)) {\n return [failure(ownershipLost(current, stored)), current];\n }\n\n if (stored.inputApplied !== undefined) {\n if (\n stored.inputApplied.recordId === request.recordId &&\n stored.inputApplied.sequence === request.sequence\n ) {\n return [success(undefined), current];\n }\n\n return [\n failure(\n ledgerError(\n \"markInputApplied\",\n `A different canonical input marker is already recorded for Submission ${request.submissionId}`,\n ),\n ),\n current,\n ];\n }\n\n const marker = InputAppliedMarker.make({\n recordId: request.recordId,\n sequence: request.sequence,\n });\n\n const row: SubmissionRow =\n STATE_RANK[stored.row.state] < STATE_RANK[\"input-applied\"]\n ? { ...stored.row, state: \"input-applied\" }\n : stored.row;\n\n return [\n success(undefined),\n withSubmission(current, { ...stored, row, inputApplied: marker }),\n ];\n },\n );\n\n if (decision._tag === \"failure\") return yield* decision.error;\n }),\n );\n\n const reserveSettlement: SubmissionLedger[\"Service\"][\"reserveSettlement\"] = Effect.fn(\n \"MemorySubmissionLedger.reserveSettlement\",\n )((unvalidated) =>\n Effect.gen(function* () {\n const request = yield* validate(SettlementReservation, \"reserveSettlement\", unvalidated);\n\n const decision = yield* Ref.modify(\n state,\n (\n current,\n ): readonly [\n Decision<ReservedSettlement, SettlementConflict | OwnershipLost | LedgerError>,\n LedgerState,\n ] => {\n const stored = current.submissions.get(request.submissionId);\n\n if (stored === undefined) {\n return [\n failure(\n ledgerError(\"reserveSettlement\", `Unknown Submission ${request.submissionId}`),\n ),\n current,\n ];\n }\n\n // A `joined` Submission settles WITH its host (plan §2.5) and its lane is never\n // worker-claimable, so no ownership token can exist for it: the recorded host\n // linkage authorizes the reservation and the presented token is not consulted.\n const joinedSettlement =\n stored.row.state === \"joined\" && stored.joinedHostSubmissionId !== undefined;\n\n // P7 §7(c): an aborted, never-claimed, still-queued Submission likewise has no\n // live ownership to fence against — its durable abort intent authorizes exactly\n // its ABORTED settlement (`terminalizing` is the same pass's crash replay). Every\n // other reservation stays fenced by the target lane's live ownership.\n const queuedAbortSettlement =\n request.outcome === \"aborted\" &&\n stored.abortIntent !== undefined &&\n stored.ownership === undefined &&\n (stored.row.state === \"ready\" || stored.row.state === \"terminalizing\");\n\n if (\n !joinedSettlement &&\n !queuedAbortSettlement &&\n !ownsLane(current, stored, request.ownershipToken)\n ) {\n return [failure(ownershipLost(current, stored)), current];\n }\n const existing = stored.reservation;\n\n if (existing !== undefined) {\n if (\n existing.settlementId !== request.settlementId ||\n existing.outcome !== request.outcome ||\n existing.recordDigest !== request.recordDigest\n ) {\n return [\n failure(\n SettlementConflict.make({\n submissionId: request.submissionId,\n existingOutcome: existing.outcome,\n }),\n ),\n current,\n ];\n }\n\n return [\n success(\n ReservedSettlement.make({\n submissionId: request.submissionId,\n settlementId: existing.settlementId,\n outcome: existing.outcome,\n record: existing.record,\n recordDigest: existing.recordDigest,\n replayed: true,\n }),\n ),\n current,\n ];\n }\n\n const reservation: StoredReservation = {\n settlementId: request.settlementId,\n outcome: request.outcome,\n record: request.record,\n recordDigest: request.recordDigest,\n finalizedAtMillis: undefined,\n };\n\n const row: SubmissionRow =\n STATE_RANK[stored.row.state] < STATE_RANK.terminalizing\n ? { ...stored.row, state: \"terminalizing\" }\n : stored.row;\n\n return [\n success(\n ReservedSettlement.make({\n submissionId: request.submissionId,\n settlementId: reservation.settlementId,\n outcome: reservation.outcome,\n record: reservation.record,\n recordDigest: reservation.recordDigest,\n replayed: false,\n }),\n ),\n withSubmission(current, { ...stored, row, reservation }),\n ];\n },\n );\n\n if (decision._tag === \"failure\") return yield* decision.error;\n\n return decision.value;\n }),\n );\n\n const finalizeSettlement: SubmissionLedger[\"Service\"][\"finalizeSettlement\"] = Effect.fn(\n \"MemorySubmissionLedger.finalizeSettlement\",\n )((unvalidated) =>\n Effect.gen(function* () {\n const request = yield* validate(SettlementFinalization, \"finalizeSettlement\", unvalidated);\n const nowMillis = yield* Clock.currentTimeMillis;\n\n const decision = yield* Ref.modify(\n state,\n (\n current,\n ): readonly [Decision<Settlement, SettlementConflict | LedgerError>, LedgerState] => {\n const stored = current.submissions.get(request.submissionId);\n\n if (stored === undefined) {\n return [\n failure(\n ledgerError(\"finalizeSettlement\", `Unknown Submission ${request.submissionId}`),\n ),\n current,\n ];\n }\n const reservation = stored.reservation;\n\n if (reservation === undefined) {\n return [\n failure(\n ledgerError(\n \"finalizeSettlement\",\n `No settlement reservation for Submission ${request.submissionId}`,\n ),\n ),\n current,\n ];\n }\n const settlementFailure = settlementFailureFromRecord(reservation.record);\n\n if ((reservation.outcome === \"failed\") !== (settlementFailure !== undefined)) {\n return [\n failure(\n ledgerError(\n \"finalizeSettlement\",\n `Settlement reservation for Submission ${request.submissionId} has contradictory failure evidence`,\n ),\n ),\n current,\n ];\n }\n if (reservation.settlementId !== request.settlementId) {\n return [\n failure(\n SettlementConflict.make({\n submissionId: request.submissionId,\n existingOutcome: reservation.outcome,\n }),\n ),\n current,\n ];\n }\n if (reservation.finalizedAtMillis !== undefined) {\n return [\n success(\n Settlement.make({\n submissionId: stored.row.submissionId,\n settlementId: reservation.settlementId,\n receiptId: stored.row.receiptId,\n outcome: reservation.outcome,\n ...(settlementFailure === undefined ? {} : { failure: settlementFailure }),\n settledAt: utc(reservation.finalizedAtMillis),\n }),\n ),\n current,\n ];\n }\n\n const next = withSubmission(current, {\n ...stored,\n row: { ...stored.row, state: \"settled\", settledOutcome: reservation.outcome },\n ownership: undefined,\n reservation: { ...reservation, finalizedAtMillis: nowMillis },\n });\n\n return [\n success(\n Settlement.make({\n submissionId: stored.row.submissionId,\n settlementId: reservation.settlementId,\n receiptId: stored.row.receiptId,\n outcome: reservation.outcome,\n ...(settlementFailure === undefined ? {} : { failure: settlementFailure }),\n settledAt: utc(nowMillis),\n }),\n ),\n next,\n ];\n },\n );\n\n if (decision._tag === \"failure\") return yield* decision.error;\n\n return decision.value;\n }),\n );\n\n const requestAbort: SubmissionLedger[\"Service\"][\"requestAbort\"] = Effect.fn(\n \"MemorySubmissionLedger.requestAbort\",\n )((unvalidated) =>\n Effect.gen(function* () {\n const request = yield* validate(AbortCommand, \"requestAbort\", unvalidated);\n const nowMillis = yield* Clock.currentTimeMillis;\n\n const decision = yield* Ref.modify(\n state,\n (\n current,\n ): readonly [\n Decision<AbortIntent, SettlementConflict | JoinedToHost | LedgerError>,\n LedgerState,\n ] => {\n const stored = current.submissions.get(request.submissionId);\n\n if (stored === undefined) {\n return [\n failure(ledgerError(\"requestAbort\", `Unknown Submission ${request.submissionId}`)),\n current,\n ];\n }\n // A joined Submission settles WITH its host; the abort target is the host (plan\n // §2.5). A joining Submission still records the intent: it is honored only if the\n // host has not consumed the input (revert-then-abort).\n if (stored.row.state === \"joined\") {\n if (stored.joinedHostSubmissionId === undefined) {\n return [\n failure(\n ledgerError(\n \"requestAbort\",\n `Joined Submission ${request.submissionId} is missing its host linkage`,\n ),\n ),\n current,\n ];\n }\n\n return [\n failure(\n JoinedToHost.make({\n submissionId: request.submissionId,\n hostSubmissionId: stored.joinedHostSubmissionId,\n }),\n ),\n current,\n ];\n }\n if (stored.row.state === \"settled\") {\n if (stored.row.settledOutcome === undefined) {\n return [\n failure(\n ledgerError(\n \"requestAbort\",\n `Settled Submission ${request.submissionId} is missing its outcome`,\n ),\n ),\n current,\n ];\n }\n\n return [\n failure(\n SettlementConflict.make({\n submissionId: request.submissionId,\n existingOutcome: stored.row.settledOutcome,\n }),\n ),\n current,\n ];\n }\n if (stored.abortIntent !== undefined) return [success(stored.abortIntent), current];\n\n const intent = AbortIntent.make({\n submissionId: request.submissionId,\n author: request.author,\n reason: request.reason,\n requestedAt: utc(nowMillis),\n });\n\n return [success(intent), withSubmission(current, { ...stored, abortIntent: intent })];\n },\n );\n\n if (decision._tag === \"failure\") return yield* decision.error;\n\n return decision.value;\n }),\n );\n\n const claimJoining: SubmissionLedger[\"Service\"][\"claimJoining\"] = Effect.fn(\n \"MemorySubmissionLedger.claimJoining\",\n )((unvalidated) =>\n Effect.gen(function* () {\n const request = yield* validate(ClaimJoiningRequest, \"claimJoining\", unvalidated);\n\n const decision = yield* Ref.modify(\n state,\n (\n current,\n ): readonly [\n Decision<ReadonlyArray<JoiningClaim>, OwnershipLost | LedgerError>,\n LedgerState,\n ] => {\n const host = current.submissions.get(request.hostSubmissionId);\n\n if (host === undefined) {\n return [\n failure(\n ledgerError(\"claimJoining\", `Unknown Submission ${request.hostSubmissionId}`),\n ),\n current,\n ];\n }\n if (host.row.threadId !== request.threadId) {\n return [\n failure(\n ledgerError(\n \"claimJoining\",\n `Host Submission ${request.hostSubmissionId} does not belong to Thread ${request.threadId}`,\n ),\n ),\n current,\n ];\n }\n if (!ownsLane(current, host, request.ownershipToken)) {\n return [failure(ownershipLost(current, host)), current];\n }\n\n const later = [...current.submissions.values()]\n .filter(\n (stored) =>\n stored.row.threadId === request.threadId &&\n stored.row.queueSequence > host.row.queueSequence,\n )\n .sort((left, right) => left.row.queueSequence - right.row.queueSequence);\n\n const claims: Array<JoiningClaim> = [];\n const submissions = new Map(current.submissions);\n\n for (const stored of later) {\n if (claims.length >= request.maxCount) break;\n // Rows already claimed by THIS host extend its contiguous prefix and are skipped;\n // the coordinator re-delivers already-joined input through the coverage rule.\n if (\n (stored.row.state === \"joining\" || stored.row.state === \"joined\") &&\n stored.joinedHostSubmissionId === request.hostSubmissionId\n ) {\n continue;\n }\n // P7 §7(c): an aborted-settled row is a CLOSED obligation, not a gap — recovery\n // settles aborted never-claimed queued work immediately, and settlement order of\n // never-run work is not execution order (DUR-004 bounds execution).\n if (stored.row.state === \"settled\" && stored.row.settledOutcome === \"aborted\") {\n continue;\n }\n // Any other non-ready row — an admitted-not-ready gap in particular — breaks the\n // contiguous ready prefix (plan §2.5); later ready work stays queued (DUR-004).\n if (stored.row.state !== \"ready\") break;\n submissions.set(stored.row.submissionId, {\n ...stored,\n row: { ...stored.row, state: \"joining\" },\n joinedHostSubmissionId: request.hostSubmissionId,\n });\n claims.push(\n JoiningClaim.make({\n submissionId: stored.row.submissionId,\n queueSequence: stored.row.queueSequence,\n inputPayload: stored.row.inputPayload,\n }),\n );\n }\n\n return [success(claims), { ...current, submissions }];\n },\n );\n\n if (decision._tag === \"failure\") return yield* decision.error;\n\n return decision.value;\n }),\n );\n\n const markJoined: SubmissionLedger[\"Service\"][\"markJoined\"] = Effect.fn(\n \"MemorySubmissionLedger.markJoined\",\n )((unvalidated) =>\n Effect.gen(function* () {\n const request = yield* validate(MarkJoinedRequest, \"markJoined\", unvalidated);\n\n const decision = yield* Ref.modify(\n state,\n (current): readonly [Decision<void, OwnershipLost | LedgerError>, LedgerState] => {\n const stored = current.submissions.get(request.submissionId);\n\n if (stored === undefined) {\n return [\n failure(ledgerError(\"markJoined\", `Unknown Submission ${request.submissionId}`)),\n current,\n ];\n }\n if (stored.joinedHostSubmissionId === undefined) {\n return [\n failure(\n ledgerError(\n \"markJoined\",\n `Submission ${request.submissionId} was never claimed for joining`,\n ),\n ),\n current,\n ];\n }\n const host = current.submissions.get(stored.joinedHostSubmissionId);\n\n if (host === undefined) {\n return [\n failure(\n ledgerError(\n \"markJoined\",\n `Host Submission ${stored.joinedHostSubmissionId} is missing`,\n ),\n ),\n current,\n ];\n }\n // The lane is host-owned: the presented token must own the HOST's ownership period,\n // which also lets a later host Attempt repair a lost marker from history (DUR-016).\n if (!ownsLane(current, host, request.ownershipToken)) {\n return [failure(ownershipLost(current, host)), current];\n }\n if (stored.inputApplied !== undefined) {\n if (\n stored.inputApplied.recordId === request.recordId &&\n stored.inputApplied.sequence === request.sequence\n ) {\n return [success(undefined), current];\n }\n\n return [\n failure(\n ledgerError(\n \"markJoined\",\n `A different join marker is already recorded for Submission ${request.submissionId}`,\n ),\n ),\n current,\n ];\n }\n if (stored.row.state !== \"joining\" && stored.row.state !== \"joined\") {\n return [\n failure(\n ledgerError(\n \"markJoined\",\n `Cannot mark Submission ${request.submissionId} joined from state ${stored.row.state}`,\n ),\n ),\n current,\n ];\n }\n\n const marker = InputAppliedMarker.make({\n recordId: request.recordId,\n sequence: request.sequence,\n });\n\n return [\n success(undefined),\n withSubmission(current, {\n ...stored,\n row: { ...stored.row, state: \"joined\" },\n inputApplied: marker,\n }),\n ];\n },\n );\n\n if (decision._tag === \"failure\") return yield* decision.error;\n }),\n );\n\n const revertJoining: SubmissionLedger[\"Service\"][\"revertJoining\"] = Effect.fn(\n \"MemorySubmissionLedger.revertJoining\",\n )((unvalidated) =>\n Effect.gen(function* () {\n const request = yield* validate(RevertJoiningRequest, \"revertJoining\", unvalidated);\n\n const decision = yield* Ref.modify(\n state,\n (current): readonly [Decision<void, LedgerError>, LedgerState] => {\n const stored = current.submissions.get(request.submissionId);\n\n if (stored === undefined) {\n return [\n failure(ledgerError(\"revertJoining\", `Unknown Submission ${request.submissionId}`)),\n current,\n ];\n }\n // Idempotent and recovery-only: only a still-`joining` Submission reverts; an\n // already-joined (or already-reverted) Submission is a no-op (DUR-016).\n if (stored.row.state !== \"joining\") return [success(undefined), current];\n\n return [\n success(undefined),\n withSubmission(current, {\n ...stored,\n row: { ...stored.row, state: \"ready\" },\n joinedHostSubmissionId: undefined,\n }),\n ];\n },\n );\n\n if (decision._tag === \"failure\") return yield* decision.error;\n }),\n );\n\n const suspend: SubmissionLedger[\"Service\"][\"suspend\"] = Effect.fn(\n \"MemorySubmissionLedger.suspend\",\n )((unvalidated) =>\n Effect.gen(function* () {\n const request = yield* validate(SuspendRequest, \"suspend\", unvalidated);\n const nowMillis = yield* Clock.currentTimeMillis;\n\n const decision = yield* Ref.modify(\n state,\n (\n current,\n ): readonly [\n Decision<SuspensionOutcome, OwnershipLost | SettlementConflict | LedgerError>,\n LedgerState,\n ] => {\n const stored = current.submissions.get(request.submissionId);\n\n if (stored === undefined) {\n return [\n failure(ledgerError(\"suspend\", `Unknown Submission ${request.submissionId}`)),\n current,\n ];\n }\n if (stored.row.state === \"settled\") {\n if (stored.row.settledOutcome === undefined) {\n return [\n failure(\n ledgerError(\n \"suspend\",\n `Settled Submission ${request.submissionId} is missing its outcome`,\n ),\n ),\n current,\n ];\n }\n\n return [\n failure(\n SettlementConflict.make({\n submissionId: request.submissionId,\n existingOutcome: stored.row.settledOutcome,\n }),\n ),\n current,\n ];\n }\n // An exact terminal outcome is already reserved (DUR-011); suspension would\n // contradict it, so the reservation wins.\n if (stored.reservation !== undefined) {\n return [\n failure(\n SettlementConflict.make({\n submissionId: request.submissionId,\n existingOutcome: stored.reservation.outcome,\n }),\n ),\n current,\n ];\n }\n if (!ownsLane(current, stored, request.ownershipToken)) {\n return [failure(ownershipLost(current, stored)), current];\n }\n\n // A covering event that raced ahead of the suspend transaction (an approval decision,\n // or a child settlement observed directly from the child's row in this single store)\n // resumes the caller immediately WITHOUT releasing the lane (plan §2.6, spec §12).\n const alreadyCovered =\n request.reason._tag === \"ApprovalPending\"\n ? request.reason.toolCallIds.every((toolCallId) =>\n stored.approvalDecisions.has(toolCallId),\n )\n : request.reason.children.every(\n (child) =>\n current.submissions.get(child.childSubmissionId)?.row.state === \"settled\",\n );\n\n if (alreadyCovered) {\n return [success(\"resume-immediately\" as const), current];\n }\n\n return [\n success(\"suspended\" as const),\n withSubmission(current, {\n ...stored,\n row: { ...stored.row, state: \"suspended\" },\n ownership: undefined,\n suspension: { reason: request.reason, suspendedAtMillis: nowMillis },\n }),\n ];\n },\n );\n\n if (decision._tag === \"failure\") return yield* decision.error;\n\n return decision.value;\n }),\n );\n\n const recordApprovalDecision: SubmissionLedger[\"Service\"][\"recordApprovalDecision\"] = Effect.fn(\n \"MemorySubmissionLedger.recordApprovalDecision\",\n )((unvalidated) =>\n Effect.gen(function* () {\n const command = yield* validate(\n ApprovalDecisionCommand,\n \"recordApprovalDecision\",\n unvalidated,\n );\n\n const nowMillis = yield* Clock.currentTimeMillis;\n\n const decision = yield* Ref.modify(\n state,\n (\n current,\n ): readonly [\n Decision<ApprovalDecisionIntent, ApprovalConflict | SettlementConflict | LedgerError>,\n LedgerState,\n ] => {\n const stored = current.submissions.get(command.submissionId);\n\n if (stored === undefined) {\n return [\n failure(\n ledgerError(\n \"recordApprovalDecision\",\n `Unknown Submission ${command.submissionId}`,\n ),\n ),\n current,\n ];\n }\n if (stored.row.state === \"settled\") {\n if (stored.row.settledOutcome === undefined) {\n return [\n failure(\n ledgerError(\n \"recordApprovalDecision\",\n `Settled Submission ${command.submissionId} is missing its outcome`,\n ),\n ),\n current,\n ];\n }\n\n return [\n failure(\n SettlementConflict.make({\n submissionId: command.submissionId,\n existingOutcome: stored.row.settledOutcome,\n }),\n ),\n current,\n ];\n }\n const existing = stored.approvalDecisions.get(command.toolCallId);\n\n if (existing !== undefined) {\n if (existing.decision !== command.decision) {\n return [\n failure(\n ApprovalConflict.make({\n submissionId: command.submissionId,\n toolCallId: command.toolCallId,\n existingDecision: existing.decision,\n }),\n ),\n current,\n ];\n }\n\n return [success(existing), current];\n }\n\n const intent = ApprovalDecisionIntent.make({\n submissionId: command.submissionId,\n toolCallId: command.toolCallId,\n decision: command.decision,\n resolver: command.resolver,\n reason: command.reason,\n decidedAt: utc(nowMillis),\n });\n\n const approvalDecisions = new Map(stored.approvalDecisions).set(\n command.toolCallId,\n intent,\n );\n\n // Once every pending call of an ApprovalPending suspension is decided, the lane\n // wakes: suspended → input-applied (plan §2.6). A WaitingForChild suspension wakes\n // only through recordChildSettled.\n const wakes =\n stored.row.state === \"suspended\" &&\n stored.suspension !== undefined &&\n stored.suspension.reason._tag === \"ApprovalPending\" &&\n stored.suspension.reason.toolCallIds.every((toolCallId) =>\n approvalDecisions.has(toolCallId),\n );\n\n return [\n success(intent),\n withSubmission(current, {\n ...stored,\n row: wakes ? { ...stored.row, state: \"input-applied\" } : stored.row,\n suspension: wakes ? undefined : stored.suspension,\n approvalDecisions,\n }),\n ];\n },\n );\n\n if (decision._tag === \"failure\") return yield* decision.error;\n\n return decision.value;\n }),\n );\n\n const markUnknown: SubmissionLedger[\"Service\"][\"markUnknown\"] = Effect.fn(\n \"MemorySubmissionLedger.markUnknown\",\n )((unvalidated) =>\n Effect.gen(function* () {\n const request = yield* validate(MarkUnknownRequest, \"markUnknown\", unvalidated);\n\n const decision = yield* Ref.modify(\n state,\n (current): readonly [Decision<void, SettlementConflict | LedgerError>, LedgerState] => {\n const stored = current.submissions.get(request.submissionId);\n\n if (stored === undefined) {\n return [\n failure(ledgerError(\"markUnknown\", `Unknown Submission ${request.submissionId}`)),\n current,\n ];\n }\n if (stored.row.state === \"settled\") {\n if (stored.row.settledOutcome === undefined) {\n return [\n failure(\n ledgerError(\n \"markUnknown\",\n `Settled Submission ${request.submissionId} is missing its outcome`,\n ),\n ),\n current,\n ];\n }\n\n return [\n failure(\n SettlementConflict.make({\n submissionId: request.submissionId,\n existingOutcome: stored.row.settledOutcome,\n }),\n ),\n current,\n ];\n }\n // A reserved exact outcome wins over a late Unknown marking (DUR-011); the recovery\n // classifier orders reservation ahead of MarkUnknown for the same reason.\n if (stored.reservation !== undefined) {\n return [\n failure(\n SettlementConflict.make({\n submissionId: request.submissionId,\n existingOutcome: stored.reservation.outcome,\n }),\n ),\n current,\n ];\n }\n // Idempotent merge: repeating is a no-op; additional open calls extend the marked\n // set while the first recorded reason is kept.\n const existing = stored.unknownMark;\n const known = new Set(existing?.toolCallIds ?? []);\n\n const merged = [\n ...(existing?.toolCallIds ?? []),\n ...request.toolCallIds.filter((toolCallId) => !known.has(toolCallId)),\n ];\n\n return [\n success(undefined),\n withSubmission(current, {\n ...stored,\n row:\n stored.row.state === \"unknown\" ? stored.row : { ...stored.row, state: \"unknown\" },\n unknownMark: { reason: existing?.reason ?? request.reason, toolCallIds: merged },\n }),\n ];\n },\n );\n\n if (decision._tag === \"failure\") return yield* decision.error;\n }),\n );\n\n const recordUnknownResolution: SubmissionLedger[\"Service\"][\"recordUnknownResolution\"] =\n Effect.fn(\"MemorySubmissionLedger.recordUnknownResolution\")((unvalidated) =>\n Effect.gen(function* () {\n const command = yield* validate(\n UnknownResolutionCommand,\n \"recordUnknownResolution\",\n unvalidated,\n );\n\n const nowMillis = yield* Clock.currentTimeMillis;\n\n const decision = yield* Ref.modify(\n state,\n (\n current,\n ): readonly [\n Decision<\n UnknownResolutionIntent,\n UnknownResolutionConflict | SettlementConflict | LedgerError\n >,\n LedgerState,\n ] => {\n const stored = current.submissions.get(command.submissionId);\n\n if (stored === undefined) {\n return [\n failure(\n ledgerError(\n \"recordUnknownResolution\",\n `Unknown Submission ${command.submissionId}`,\n ),\n ),\n current,\n ];\n }\n if (stored.row.state === \"settled\") {\n if (stored.row.settledOutcome === undefined) {\n return [\n failure(\n ledgerError(\n \"recordUnknownResolution\",\n `Settled Submission ${command.submissionId} is missing its outcome`,\n ),\n ),\n current,\n ];\n }\n\n return [\n failure(\n SettlementConflict.make({\n submissionId: command.submissionId,\n existingOutcome: stored.row.settledOutcome,\n }),\n ),\n current,\n ];\n }\n const existing = stored.unknownResolutions.get(command.toolCallId);\n\n if (\n existing !== undefined &&\n !equivalentUnknownResolution(existing.intent.resolution, command.resolution)\n ) {\n return [\n failure(\n UnknownResolutionConflict.make({\n submissionId: command.submissionId,\n toolCallId: command.toolCallId,\n }),\n ),\n current,\n ];\n }\n\n const intent =\n existing?.intent ??\n UnknownResolutionIntent.make({\n submissionId: command.submissionId,\n toolCallId: command.toolCallId,\n author: command.author,\n reason: command.reason,\n resolution: command.resolution,\n resolvedAt: utc(nowMillis),\n });\n\n const unknownResolutions =\n existing !== undefined\n ? stored.unknownResolutions\n : new Map(stored.unknownResolutions).set(command.toolCallId, {\n intent,\n });\n\n // The lane reopens only when EVERY marked open call has a durable resolution\n // intent: unknown → input-applied (DUR-017). Replays re-run the coverage check so\n // a recovering caller can wake the lane idempotently.\n const wakes =\n stored.row.state === \"unknown\" &&\n stored.unknownMark !== undefined &&\n stored.unknownMark.toolCallIds.every((toolCallId) =>\n unknownResolutions.has(toolCallId),\n );\n\n return [\n success(intent),\n withSubmission(current, {\n ...stored,\n row: wakes ? { ...stored.row, state: \"input-applied\" } : stored.row,\n unknownMark: wakes ? undefined : stored.unknownMark,\n unknownResolutions,\n }),\n ];\n },\n );\n\n if (decision._tag === \"failure\") return yield* decision.error;\n\n return decision.value;\n }),\n );\n\n const recordChildSettled: SubmissionLedger[\"Service\"][\"recordChildSettled\"] = Effect.fn(\n \"MemorySubmissionLedger.recordChildSettled\",\n )((unvalidated) =>\n Effect.gen(function* () {\n const request = yield* validate(\n ChildSettledNotification,\n \"recordChildSettled\",\n unvalidated,\n );\n\n const decision = yield* Ref.modify(\n state,\n (current): readonly [Decision<ChildSettledOutcome, LedgerError>, LedgerState] => {\n const parent = current.submissions.get(request.parentSubmissionId);\n\n if (parent === undefined) {\n return [\n failure(\n ledgerError(\n \"recordChildSettled\",\n `Unknown Submission ${request.parentSubmissionId}`,\n ),\n ),\n current,\n ];\n }\n // The caller may notify after the canonical Settlement append but before ledger\n // finalization. In a single store, an exact reservation plus `terminalizing` is the\n // narrow durable prefix that makes that ordering admissible; earlier states remain\n // a caller error.\n const child = current.submissions.get(request.childSubmissionId);\n\n const announced =\n child !== undefined &&\n (child.row.state === \"settled\" ||\n (child.row.state === \"terminalizing\" && child.reservation !== undefined));\n\n if (!announced) {\n return [\n failure(\n ledgerError(\n \"recordChildSettled\",\n `Child Submission ${request.childSubmissionId} has no recorded settlement`,\n ),\n ),\n current,\n ];\n }\n if (\n parent.row.state !== \"suspended\" ||\n parent.suspension === undefined ||\n parent.suspension.reason._tag !== \"WaitingForChild\"\n ) {\n return [success(\"not-waiting\" as const), current];\n }\n const children = parent.suspension.reason.children;\n\n if (!children.some((entry) => entry.childSubmissionId === request.childSubmissionId)) {\n return [success(\"not-waiting\" as const), current];\n }\n\n // Every listed child must be either finalized or canonically announced from the\n // exact terminalizing reservation. Replays re-run this coverage check idempotently.\n const allSettled = children.every((entry) => {\n const listed = current.submissions.get(entry.childSubmissionId);\n\n return (\n listed?.row.state === \"settled\" ||\n (listed?.row.state === \"terminalizing\" && listed.reservation !== undefined)\n );\n });\n\n if (!allSettled) return [success(\"still-waiting\" as const), current];\n\n return [\n success(\"woken\" as const),\n withSubmission(current, {\n ...parent,\n row: { ...parent.row, state: \"input-applied\" },\n suspension: undefined,\n }),\n ];\n },\n );\n\n if (decision._tag === \"failure\") return yield* decision.error;\n\n return decision.value;\n }),\n );\n\n const reserveChildBudget: SubmissionLedger[\"Service\"][\"reserveChildBudget\"] = Effect.fn(\n \"MemorySubmissionLedger.reserveChildBudget\",\n )((unvalidated) =>\n Effect.gen(function* () {\n const request = yield* validate(\n ChildBudgetReservationRequest,\n \"reserveChildBudget\",\n unvalidated,\n );\n\n const nowMillis = yield* Clock.currentTimeMillis;\n\n const decision = yield* Ref.modify(\n state,\n (\n current,\n ): readonly [\n Decision<ReservedChildBudget, ChildReservationConflict | OwnershipLost | LedgerError>,\n LedgerState,\n ] => {\n const existing = current.childReservations.get(request.reservationId);\n\n if (existing !== undefined) {\n // Identical replays short-circuit before the fence, mirroring reserveSettlement:\n // a replay creates nothing, so a recovering caller resumes rather than duplicates.\n const identical =\n existing.parentSubmissionId === request.parentSubmissionId &&\n existing.parentToolCallId === request.parentToolCallId &&\n existing.allocationDigest === request.allocationDigest &&\n equivalentPersistedJson(existing.allocation, request.allocation);\n\n if (!identical) {\n return [\n failure(\n ChildReservationConflict.make({\n reservationId: request.reservationId,\n status: existing.status,\n message:\n \"A reservation with this identity exists with a different parent Tool Call or allocation.\",\n }),\n ),\n current,\n ];\n }\n\n return [\n success(\n ReservedChildBudget.make({\n reservation: toReservationSnapshot(existing),\n replayed: true,\n }),\n ),\n current,\n ];\n }\n for (const reservation of current.childReservations.values()) {\n if (\n reservation.parentSubmissionId === request.parentSubmissionId &&\n reservation.parentToolCallId === request.parentToolCallId\n ) {\n return [\n failure(\n ChildReservationConflict.make({\n reservationId: request.reservationId,\n status: reservation.status,\n message: `Parent Tool Call ${request.parentToolCallId} already owns reservation ${reservation.reservationId}.`,\n }),\n ),\n current,\n ];\n }\n }\n const parent = current.submissions.get(request.parentSubmissionId);\n\n if (parent === undefined) {\n return [\n failure(\n ledgerError(\n \"reserveChildBudget\",\n `Unknown Submission ${request.parentSubmissionId}`,\n ),\n ),\n current,\n ];\n }\n // Creation is fenced by the parent lane's live ownership (spec §12 step 2): a stale\n // parent Attempt can never create new reservation state.\n if (!ownsLane(current, parent, request.ownershipToken)) {\n return [failure(ownershipLost(current, parent)), current];\n }\n\n const reservation: StoredChildReservation = {\n reservationId: request.reservationId,\n parentSubmissionId: request.parentSubmissionId,\n parentToolCallId: request.parentToolCallId,\n childSubmissionId: undefined,\n status: \"reserved\",\n allocation: request.allocation,\n allocationDigest: request.allocationDigest,\n accounting: undefined,\n reservedAtMillis: nowMillis,\n releaseBeganAtMillis: undefined,\n releasedAtMillis: undefined,\n };\n\n return [\n success(\n ReservedChildBudget.make({\n reservation: toReservationSnapshot(reservation),\n replayed: false,\n }),\n ),\n withChildReservation(current, reservation),\n ];\n },\n );\n\n if (decision._tag === \"failure\") return yield* decision.error;\n\n return decision.value;\n }),\n );\n\n const attachChildToReservation: SubmissionLedger[\"Service\"][\"attachChildToReservation\"] =\n Effect.fn(\"MemorySubmissionLedger.attachChildToReservation\")((unvalidated) =>\n Effect.gen(function* () {\n const request = yield* validate(\n AttachChildToReservationRequest,\n \"attachChildToReservation\",\n unvalidated,\n );\n\n const decision = yield* Ref.modify(\n state,\n (\n current,\n ): readonly [\n Decision<\n ChildBudgetReservationSnapshot,\n ChildReservationConflict | OwnershipLost | LedgerError\n >,\n LedgerState,\n ] => {\n const reservation = current.childReservations.get(request.reservationId);\n\n if (reservation === undefined) {\n return [\n failure(\n ledgerError(\n \"attachChildToReservation\",\n `Unknown child reservation ${request.reservationId}`,\n ),\n ),\n current,\n ];\n }\n if (reservation.childSubmissionId !== undefined) {\n // Idempotent replay of the recorded attachment (unfenced — it mutates nothing).\n if (reservation.childSubmissionId === request.childSubmissionId) {\n return [success(toReservationSnapshot(reservation)), current];\n }\n\n return [\n failure(\n ChildReservationConflict.make({\n reservationId: request.reservationId,\n status: reservation.status,\n message: `Reservation ${request.reservationId} already records child ${reservation.childSubmissionId}.`,\n }),\n ),\n current,\n ];\n }\n const parent = current.submissions.get(reservation.parentSubmissionId);\n\n if (parent === undefined) {\n return [\n failure(\n ledgerError(\n \"attachChildToReservation\",\n `Unknown Submission ${reservation.parentSubmissionId}`,\n ),\n ),\n current,\n ];\n }\n if (!ownsLane(current, parent, request.ownershipToken)) {\n return [failure(ownershipLost(current, parent)), current];\n }\n if (reservation.status !== \"reserved\") {\n return [\n failure(\n ChildReservationConflict.make({\n reservationId: request.reservationId,\n status: reservation.status,\n message: `Cannot attach a child to a ${reservation.status} reservation.`,\n }),\n ),\n current,\n ];\n }\n // Single-store latitude: the admitted child must exist here, so a dangling\n // attachment can never enter the recovery view.\n if (!current.submissions.has(request.childSubmissionId)) {\n return [\n failure(\n ledgerError(\n \"attachChildToReservation\",\n `Unknown child Submission ${request.childSubmissionId}`,\n ),\n ),\n current,\n ];\n }\n\n const attached: StoredChildReservation = {\n ...reservation,\n childSubmissionId: request.childSubmissionId,\n };\n\n return [\n success(toReservationSnapshot(attached)),\n withChildReservation(current, attached),\n ];\n },\n );\n\n if (decision._tag === \"failure\") return yield* decision.error;\n\n return decision.value;\n }),\n );\n\n const beginChildBudgetRelease: SubmissionLedger[\"Service\"][\"beginChildBudgetRelease\"] =\n Effect.fn(\"MemorySubmissionLedger.beginChildBudgetRelease\")((unvalidated) =>\n Effect.gen(function* () {\n const request = yield* validate(\n BeginChildBudgetReleaseRequest,\n \"beginChildBudgetRelease\",\n unvalidated,\n );\n\n const nowMillis = yield* Clock.currentTimeMillis;\n\n const decision = yield* Ref.modify(\n state,\n (\n current,\n ): readonly [\n Decision<ChildBudgetReservationSnapshot, ChildReservationConflict | LedgerError>,\n LedgerState,\n ] => {\n const reservation = current.childReservations.get(request.reservationId);\n\n if (reservation === undefined) {\n return [\n failure(\n ledgerError(\n \"beginChildBudgetRelease\",\n `Unknown child reservation ${request.reservationId}`,\n ),\n ),\n current,\n ];\n }\n if (reservation.status !== \"reserved\") {\n // The accounting decision was already frozen exactly once; an identical replay is\n // a no-op and a divergent decision conflicts (spec §12 join step 6).\n if (\n reservation.accounting !== undefined &&\n equivalentPersistedJson(reservation.accounting, request.accounting)\n ) {\n return [success(toReservationSnapshot(reservation)), current];\n }\n\n return [\n failure(\n ChildReservationConflict.make({\n reservationId: request.reservationId,\n status: reservation.status,\n message:\n \"A different accounting decision is already frozen for this reservation.\",\n }),\n ),\n current,\n ];\n }\n\n const frozen: StoredChildReservation = {\n ...reservation,\n status: \"releasePending\",\n accounting: request.accounting,\n releaseBeganAtMillis: nowMillis,\n };\n\n return [\n success(toReservationSnapshot(frozen)),\n withChildReservation(current, frozen),\n ];\n },\n );\n\n if (decision._tag === \"failure\") return yield* decision.error;\n\n return decision.value;\n }),\n );\n\n const releaseChildBudget: SubmissionLedger[\"Service\"][\"releaseChildBudget\"] = Effect.fn(\n \"MemorySubmissionLedger.releaseChildBudget\",\n )((unvalidated) =>\n Effect.gen(function* () {\n const request = yield* validate(\n ReleaseChildBudgetRequest,\n \"releaseChildBudget\",\n unvalidated,\n );\n\n const nowMillis = yield* Clock.currentTimeMillis;\n\n const decision = yield* Ref.modify(\n state,\n (\n current,\n ): readonly [\n Decision<ChildBudgetReservationSnapshot, ChildReservationConflict | LedgerError>,\n LedgerState,\n ] => {\n const reservation = current.childReservations.get(request.reservationId);\n\n if (reservation === undefined) {\n return [\n failure(\n ledgerError(\n \"releaseChildBudget\",\n `Unknown child reservation ${request.reservationId}`,\n ),\n ),\n current,\n ];\n }\n // Applied exactly once: replaying a released reservation returns the stored row\n // unchanged (spec §12: \"never available twice\").\n if (reservation.status === \"released\") {\n return [success(toReservationSnapshot(reservation)), current];\n }\n if (reservation.status !== \"releasePending\") {\n return [\n failure(\n ChildReservationConflict.make({\n reservationId: request.reservationId,\n status: reservation.status,\n message:\n \"Cannot release a reservation whose accounting decision is not frozen.\",\n }),\n ),\n current,\n ];\n }\n\n const released: StoredChildReservation = {\n ...reservation,\n status: \"released\",\n releasedAtMillis: nowMillis,\n };\n\n return [\n success(toReservationSnapshot(released)),\n withChildReservation(current, released),\n ];\n },\n );\n\n if (decision._tag === \"failure\") return yield* decision.error;\n\n return decision.value;\n }),\n );\n\n const scanNonterminal: SubmissionLedger[\"Service\"][\"scanNonterminal\"] = Stream.unwrap(\n Ref.get(state).pipe(\n Effect.map((current) => {\n const snapshots = [...current.submissions.values()]\n .filter((stored) => stored.row.state !== \"settled\")\n .sort((left, right) =>\n left.row.threadId < right.row.threadId\n ? -1\n : left.row.threadId > right.row.threadId\n ? 1\n : left.row.queueSequence - right.row.queueSequence,\n )\n .map((stored) => toSnapshot(stored.row));\n\n return Stream.fromIterable(snapshots);\n }),\n ),\n );\n\n const readAbortIntent: SubmissionLedger[\"Service\"][\"readAbortIntent\"] = Effect.fn(\n \"MemorySubmissionLedger.readAbortIntent\",\n )(function* (unvalidated) {\n const request = yield* validate(AbortIntentRequest, \"readAbortIntent\", unvalidated);\n const stored = (yield* Ref.get(state)).submissions.get(request.submissionId);\n\n if (stored === undefined) {\n return yield* ledgerError(\"readAbortIntent\", `Unknown Submission ${request.submissionId}`);\n }\n\n return stored.abortIntent;\n });\n\n const loadRecoverySnapshot: SubmissionLedger[\"Service\"][\"loadRecoverySnapshot\"] = Effect.fn(\n \"MemorySubmissionLedger.loadRecoverySnapshot\",\n )((unvalidated) =>\n Effect.gen(function* () {\n const request = yield* validate(\n RecoverySnapshotRequest,\n \"loadRecoverySnapshot\",\n unvalidated,\n );\n\n const current = yield* Ref.get(state);\n const stored = current.submissions.get(request.submissionId);\n\n if (stored === undefined) {\n return yield* ledgerError(\n \"loadRecoverySnapshot\",\n `Unknown Submission ${request.submissionId}`,\n );\n }\n\n const joins = [...current.submissions.values()]\n .filter((candidate) => candidate.joinedHostSubmissionId === request.submissionId)\n .sort((left, right) => left.row.queueSequence - right.row.queueSequence)\n .map((candidate) =>\n JoinSnapshot.make({\n submissionId: candidate.row.submissionId,\n state: candidate.row.state,\n hostSubmissionId: request.submissionId,\n }),\n );\n\n const byToolCallId = <A extends { readonly toolCallId: ToolCallId }>(\n left: A,\n right: A,\n ): number =>\n left.toolCallId < right.toolCallId ? -1 : left.toolCallId > right.toolCallId ? 1 : 0;\n\n // Parent-side subagent view: this Submission's child budget reservations in parent Tool\n // Call order, plus each attached child's current lane state (a disposable derived view;\n // the canonical records stay the recovery truth, DUR-015).\n const childReservations = [...current.childReservations.values()]\n .filter((reservation) => reservation.parentSubmissionId === request.submissionId)\n .sort((left, right) =>\n left.parentToolCallId < right.parentToolCallId\n ? -1\n : left.parentToolCallId > right.parentToolCallId\n ? 1\n : 0,\n );\n\n const childAttachments: Array<ChildAttachmentSnapshot> = [];\n\n for (const reservation of childReservations) {\n if (reservation.childSubmissionId === undefined) continue;\n const child = current.submissions.get(reservation.childSubmissionId);\n\n if (child === undefined) continue;\n childAttachments.push(\n ChildAttachmentSnapshot.make({\n toolCallId: reservation.parentToolCallId,\n childSubmissionId: reservation.childSubmissionId,\n childState: child.row.state,\n ...(child.row.settledOutcome === undefined\n ? {}\n : { childOutcome: child.row.settledOutcome }),\n }),\n );\n }\n\n return RecoverySnapshot.make({\n submission: toSnapshot(stored.row),\n joins,\n approvalDecisions: [...stored.approvalDecisions.values()].sort(byToolCallId),\n unknownResolutions: [...stored.unknownResolutions.values()]\n .map((resolution) => resolution.intent)\n .sort(byToolCallId),\n childReservations: childReservations.map(toReservationSnapshot),\n childAttachments,\n ...(stored.row.parentLinkage === undefined\n ? {}\n : { parentLinkage: stored.row.parentLinkage }),\n ...(stored.joinedHostSubmissionId === undefined\n ? {}\n : { hostSubmissionId: stored.joinedHostSubmissionId }),\n ...(stored.suspension === undefined\n ? {}\n : {\n suspension: SuspensionSnapshot.make({\n reason: stored.suspension.reason,\n suspendedAt: utc(stored.suspension.suspendedAtMillis),\n }),\n }),\n ...(stored.ownership === undefined\n ? {}\n : {\n ownership: OwnershipSnapshot.make({\n attemptId: stored.ownership.attemptId,\n ownerProducerId: stored.ownership.ownerProducerId,\n producerEpoch: stored.ownership.producerEpoch,\n leaseExpiresAt: utc(stored.ownership.leaseExpiresAtMillis),\n }),\n }),\n ...(stored.inputApplied === undefined ? {} : { inputApplied: stored.inputApplied }),\n ...(stored.reservation === undefined\n ? {}\n : {\n reservation: SettlementReservationSnapshot.make({\n settlementId: stored.reservation.settlementId,\n outcome: stored.reservation.outcome,\n record: stored.reservation.record,\n recordDigest: stored.reservation.recordDigest,\n finalized: stored.reservation.finalizedAtMillis !== undefined,\n }),\n }),\n ...(stored.abortIntent === undefined ? {} : { abortIntent: stored.abortIntent }),\n });\n }),\n );\n\n return SubmissionLedger.of({\n capabilities,\n admit,\n markReady,\n lookup,\n resolveAdmission,\n claim,\n renewOwnership,\n releaseOwnership,\n markInputApplied,\n reserveSettlement,\n finalizeSettlement,\n requestAbort,\n claimJoining,\n markJoined,\n revertJoining,\n suspend,\n recordApprovalDecision,\n markUnknown,\n recordUnknownResolution,\n recordChildSettled,\n reserveChildBudget,\n attachChildToReservation,\n beginChildBudgetRelease,\n releaseChildBudget,\n scanNonterminal,\n loadRecoverySnapshot,\n readAbortIntent,\n });\n });\n\n/** Construction options for the in-memory reference SubmissionLedger. */\nexport interface MemorySubmissionLedgerOptions {\n /**\n * Test-only fault seam for `resolveAdmission` (SUB-031): when the effect yields a reason,\n * the resolution answers `Indeterminate` with it instead of consulting the store — modelling\n * an authoritative child owner that is temporarily unreachable. `Option.none()` restores the\n * store-derived answer. Ledger state is never mutated by the fault.\n */\n readonly resolveAdmissionFault?: Effect.Effect<Option.Option<string>>;\n}\n\n/**\n * In-memory reference SubmissionLedger Layer (durability `non-durable`). All state lives in one\n * `Ref` owned by the Layer's Scope; no daemon fibers are spawned and no wall clock is consulted.\n */\nexport const memorySubmissionLedgerLayer = (\n options: MemorySubmissionLedgerOptions = {},\n): Layer.Layer<SubmissionLedger> => Layer.effect(SubmissionLedger, makeSubmissionLedger(options));\n\nexport const MemorySubmissionLedgerLive: Layer.Layer<SubmissionLedger> =\n memorySubmissionLedgerLayer();\n"],"mappings":";;;;;;;;;;;AA+GA,MAAM,kBAAkB;;;;;;AAOxB,MAAM,aAA8C;CAClD,UAAU;CACV,OAAO;CACP,SAAS;CACT,QAAQ;CACR,SAAS;CACT,iBAAiB;CACjB,WAAW;CACX,SAAS;CACT,eAAe;CACf,SAAS;AACX;;;;;;AA2EA,MAAM,sCAAoD,IAAI,IAAI;CAChE;CACA;CACA;AACF,CAAC;AAkCD,MAAM,WAAc,WAAkC;CAAE,MAAM;CAAW;AAAM;AAC/E,MAAM,WAAc,WAAkC;CAAE,MAAM;CAAW;AAAM;AAE/E,MAAM,eAAe,WAAmB,SAAiB,UACvD,UAAU,KAAA,IACN,YAAY,KAAK;CAAE;CAAW;AAAQ,CAAC,IACvC,YAAY,KAAK;CAAE;CAAW;CAAS;AAAM,CAAC;AAEpD,MAAM,WAAW,OAAO,GAAG,iCAAiC,CAAC,EAEzD,QACA,WACA,UAEA,OAAO,oBAAoB,MAAM,CAAC,CAAC,KAAK,CAAC,CAAC,KACxC,OAAO,QAAQ,OAAO,oBAAoB,MAAM,CAAC,GACjD,OAAO,UAAU,UAAU,YAAY,WAAW,WAAW,UAAU,WAAW,KAAK,CAAC,CAC1F,CACJ;AAEA,MAAM,qBAAqB,OAAO,WAAW,YAAY;AACzD,MAAM,kBAAkB,OAAO,WAAW,SAAS;AACnD,MAAM,kBAAkB,OAAO,WAAW,SAAS;AACnD,MAAM,uBAAuB,OAAO,WAAW,cAAc;AAC7D,MAAM,sBAAsB,OAAO,WAAW,aAAa;AAC3D,MAAM,sBAAsB,OAAO,WAAW,aAAa;AAC3D,MAAM,0BAA0B,OAAO,cAAc,aAAa;AAClE,MAAM,8BAA8B,OAAO,cAAc,iBAAiB;AAE1E,MAA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 +1 @@
1
- {"name":"@effect-agent/storage-memory","version":"0.1.0-beta.97","dependencies":{"effect-agent":"0.1.0-beta.97"},"devDependencies":{"@effect/platform-node":"4.0.0-rc.115","@effect/vitest":"4.0.0-rc.115","effect":"4.0.0-rc.115","typescript":"7.0.2","vite-plus":"0.3.0"},"peerDependencies":{"effect":"^4.0.0-rc.115"},"exports":{".":{"types":"./dist/index.d.mts","default":"./dist/index.mjs"},"./memory-message-delivery-store":{"types":"./dist/MemoryMessageDeliveryStore.d.mts","default":"./dist/MemoryMessageDeliveryStore.mjs"},"./memory-schedule-store":{"types":"./dist/MemoryScheduleStore.d.mts","default":"./dist/MemoryScheduleStore.mjs"},"./memory-semantic-index":{"types":"./dist/MemorySemanticIndex.d.mts","default":"./dist/MemorySemanticIndex.mjs"},"./memory-submission-ledger":{"types":"./dist/MemorySubmissionLedger.d.mts","default":"./dist/MemorySubmissionLedger.mjs"},"./memory-subscription-store":{"types":"./dist/MemorySubscriptionStore.d.mts","default":"./dist/MemorySubscriptionStore.mjs"},"./memory-thread-store":{"types":"./dist/MemoryThreadStore.d.mts","default":"./dist/MemoryThreadStore.mjs"}},"description":"In-memory Thread store and submission ledger reference adapters for Effect Agent tests and conformance suites.","license":"MIT","repository":{"type":"git","url":"git+https://github.com/danieljvdm/effect-agent.git","directory":"packages/storage-memory"},"files":["dist","src"],"type":"module","sideEffects":[],"publishConfig":{"access":"public"},"scripts":{"build":"vp pack","check":"tsc --noEmit -p tsconfig.json","test":"vp test --passWithNoTests"}}
1
+ {"name":"@effect-agent/storage-memory","version":"0.1.0-beta.98","dependencies":{"effect-agent":"0.1.0-beta.98"},"devDependencies":{"@effect/platform-node":"4.0.0-rc.115","@effect/vitest":"4.0.0-rc.115","effect":"4.0.0-rc.115","typescript":"7.0.2","vite-plus":"0.3.0"},"peerDependencies":{"effect":"^4.0.0-rc.115"},"exports":{".":{"types":"./dist/index.d.mts","default":"./dist/index.mjs"},"./memory-message-delivery-store":{"types":"./dist/MemoryMessageDeliveryStore.d.mts","default":"./dist/MemoryMessageDeliveryStore.mjs"},"./memory-schedule-store":{"types":"./dist/MemoryScheduleStore.d.mts","default":"./dist/MemoryScheduleStore.mjs"},"./memory-semantic-index":{"types":"./dist/MemorySemanticIndex.d.mts","default":"./dist/MemorySemanticIndex.mjs"},"./memory-submission-ledger":{"types":"./dist/MemorySubmissionLedger.d.mts","default":"./dist/MemorySubmissionLedger.mjs"},"./memory-subscription-store":{"types":"./dist/MemorySubscriptionStore.d.mts","default":"./dist/MemorySubscriptionStore.mjs"},"./memory-thread-store":{"types":"./dist/MemoryThreadStore.d.mts","default":"./dist/MemoryThreadStore.mjs"}},"description":"In-memory Thread store and submission ledger reference adapters for Effect Agent tests and conformance suites.","license":"MIT","repository":{"type":"git","url":"git+https://github.com/danieljvdm/effect-agent.git","directory":"packages/storage-memory"},"files":["dist","src"],"type":"module","sideEffects":[],"publishConfig":{"access":"public"},"scripts":{"build":"vp pack","check":"tsc --noEmit -p tsconfig.json","test":"vp test --passWithNoTests"}}
@@ -350,9 +350,15 @@ const ownershipLost = (state: LedgerState, stored: StoredSubmission): OwnershipL
350
350
  actualEpoch: decodeProducerEpoch(laneEpoch(state, stored.row.threadId)),
351
351
  });
352
352
 
353
- /** The presented token owns the lane only while it matches the live ownership record. */
354
- const ownsLane = (stored: StoredSubmission, ownershipToken: OwnershipToken): boolean =>
355
- stored.ownership !== undefined && stored.ownership.ownershipToken === ownershipToken;
353
+ /** A retained row token cannot outlive a newer owner of the same Thread. */
354
+ const ownsLane = (
355
+ state: LedgerState,
356
+ stored: StoredSubmission,
357
+ ownershipToken: OwnershipToken,
358
+ ): boolean =>
359
+ stored.ownership !== undefined &&
360
+ stored.ownership.ownershipToken === ownershipToken &&
361
+ stored.ownership.producerEpoch === laneEpoch(state, stored.row.threadId);
356
362
 
357
363
  const withSubmission = (state: LedgerState, stored: StoredSubmission): LedgerState => ({
358
364
  ...state,
@@ -371,7 +377,12 @@ const findHead = (state: LedgerState, threadId: ThreadId): StoredSubmission | un
371
377
  let head: StoredSubmission | undefined;
372
378
 
373
379
  for (const stored of state.submissions.values()) {
374
- if (stored.row.threadId !== threadId || stored.row.state === "settled") continue;
380
+ if (
381
+ stored.row.threadId !== threadId ||
382
+ stored.row.state === "settled" ||
383
+ (stored.row.state === "unknown" && stored.abortIntent === undefined)
384
+ )
385
+ continue;
375
386
  if (head === undefined || stored.row.queueSequence < head.row.queueSequence) head = stored;
376
387
  }
377
388
 
@@ -380,7 +391,7 @@ const findHead = (state: LedgerState, threadId: ThreadId): StoredSubmission | un
380
391
 
381
392
  /**
382
393
  * Reference in-memory SubmissionLedger. It implements the full port contract — atomic idempotent
383
- * admission, FIFO-head claims, producer-epoch fencing, Clock-driven ownership leases, idempotent
394
+ * admission, eligible FIFO claims, producer-epoch fencing, Clock-driven ownership leases, idempotent
384
395
  * settlement reservation/finalization, and durable abort intent — with every transition applied
385
396
  * as one atomic `Ref.modify`, but its state does not survive the process (`non-durable`).
386
397
  *
@@ -390,8 +401,8 @@ const findHead = (state: LedgerState, threadId: ThreadId): StoredSubmission | un
390
401
  * deterministically; no wall clock is consulted.
391
402
  * - The ownership lease is pinned to `DEFAULT_OWNERSHIP_LEASE_DURATION` (D5); durable adapters
392
403
  * own the configuration seam.
393
- * - A live lease blocks claims from other producers only: the same `producerId` may reclaim its
394
- * own live lease (restart recovery), which supersedes and fences the prior Attempt's token.
404
+ * - Any live lease in the Thread blocks every new claim, including the same `producerId`.
405
+ * Unresolved unknown work is skipped only after ownership is released or expires.
395
406
  * - Claiming advances `ready` to `running` and otherwise preserves the recorded state, so
396
407
  * progress markers from an earlier Attempt survive a reclaim.
397
408
  * - `renewOwnership` keeps the token stable (the port allows rotation); a replayed admission
@@ -777,21 +788,19 @@ const makeSubmissionLedger = (options: MemorySubmissionLedgerOptions = {}) =>
777
788
  const decision = yield* Ref.modify(
778
789
  state,
779
790
  (current): readonly [Decision<Option.Option<Claim>, LedgerError>, LedgerState] => {
791
+ for (const stored of current.submissions.values()) {
792
+ if (
793
+ stored.row.threadId === request.threadId &&
794
+ stored.ownership !== undefined &&
795
+ stored.ownership.leaseExpiresAtMillis > nowMillis
796
+ ) {
797
+ return [success(Option.none()), current];
798
+ }
799
+ }
780
800
  const head = findHead(current, request.threadId);
781
801
 
782
802
  if (head === undefined) return [success(Option.none()), current];
783
- if (
784
- BLOCKED_HEAD_STATES.has(head.row.state) ||
785
- (head.row.state === "unknown" && head.abortIntent === undefined)
786
- )
787
- return [success(Option.none()), current];
788
- if (
789
- head.ownership !== undefined &&
790
- head.ownership.leaseExpiresAtMillis > nowMillis &&
791
- head.ownership.ownerProducerId !== request.producerId
792
- ) {
793
- return [success(Option.none()), current];
794
- }
803
+ if (BLOCKED_HEAD_STATES.has(head.row.state)) return [success(Option.none()), current];
795
804
  const lane = current.lanes.get(request.threadId);
796
805
 
797
806
  if (lane === undefined) {
@@ -867,7 +876,10 @@ const makeSubmissionLedger = (options: MemorySubmissionLedgerOptions = {}) =>
867
876
  current,
868
877
  ];
869
878
  }
870
- if (stored.ownership === undefined || !ownsLane(stored, request.ownershipToken)) {
879
+ if (
880
+ stored.ownership === undefined ||
881
+ !ownsLane(current, stored, request.ownershipToken)
882
+ ) {
871
883
  return [failure(ownershipLost(current, stored)), current];
872
884
  }
873
885
 
@@ -913,7 +925,7 @@ const makeSubmissionLedger = (options: MemorySubmissionLedgerOptions = {}) =>
913
925
  current,
914
926
  ];
915
927
  }
916
- if (!ownsLane(stored, request.ownershipToken)) {
928
+ if (!ownsLane(current, stored, request.ownershipToken)) {
917
929
  return [failure(ownershipLost(current, stored)), current];
918
930
  }
919
931
 
@@ -947,7 +959,7 @@ const makeSubmissionLedger = (options: MemorySubmissionLedgerOptions = {}) =>
947
959
  current,
948
960
  ];
949
961
  }
950
- if (!ownsLane(stored, request.ownershipToken)) {
962
+ if (!ownsLane(current, stored, request.ownershipToken)) {
951
963
  return [failure(ownershipLost(current, stored)), current];
952
964
  }
953
965
 
@@ -1035,7 +1047,7 @@ const makeSubmissionLedger = (options: MemorySubmissionLedgerOptions = {}) =>
1035
1047
  if (
1036
1048
  !joinedSettlement &&
1037
1049
  !queuedAbortSettlement &&
1038
- !ownsLane(stored, request.ownershipToken)
1050
+ !ownsLane(current, stored, request.ownershipToken)
1039
1051
  ) {
1040
1052
  return [failure(ownershipLost(current, stored)), current];
1041
1053
  }
@@ -1338,7 +1350,7 @@ const makeSubmissionLedger = (options: MemorySubmissionLedgerOptions = {}) =>
1338
1350
  current,
1339
1351
  ];
1340
1352
  }
1341
- if (!ownsLane(host, request.ownershipToken)) {
1353
+ if (!ownsLane(current, host, request.ownershipToken)) {
1342
1354
  return [failure(ownershipLost(current, host)), current];
1343
1355
  }
1344
1356
 
@@ -1439,7 +1451,7 @@ const makeSubmissionLedger = (options: MemorySubmissionLedgerOptions = {}) =>
1439
1451
  }
1440
1452
  // The lane is host-owned: the presented token must own the HOST's ownership period,
1441
1453
  // which also lets a later host Attempt repair a lost marker from history (DUR-016).
1442
- if (!ownsLane(host, request.ownershipToken)) {
1454
+ if (!ownsLane(current, host, request.ownershipToken)) {
1443
1455
  return [failure(ownershipLost(current, host)), current];
1444
1456
  }
1445
1457
  if (stored.inputApplied !== undefined) {
@@ -1587,7 +1599,7 @@ const makeSubmissionLedger = (options: MemorySubmissionLedgerOptions = {}) =>
1587
1599
  current,
1588
1600
  ];
1589
1601
  }
1590
- if (!ownsLane(stored, request.ownershipToken)) {
1602
+ if (!ownsLane(current, stored, request.ownershipToken)) {
1591
1603
  return [failure(ownershipLost(current, stored)), current];
1592
1604
  }
1593
1605
 
@@ -2122,7 +2134,7 @@ const makeSubmissionLedger = (options: MemorySubmissionLedgerOptions = {}) =>
2122
2134
  }
2123
2135
  // Creation is fenced by the parent lane's live ownership (spec §12 step 2): a stale
2124
2136
  // parent Attempt can never create new reservation state.
2125
- if (!ownsLane(parent, request.ownershipToken)) {
2137
+ if (!ownsLane(current, parent, request.ownershipToken)) {
2126
2138
  return [failure(ownershipLost(current, parent)), current];
2127
2139
  }
2128
2140
 
@@ -2221,7 +2233,7 @@ const makeSubmissionLedger = (options: MemorySubmissionLedgerOptions = {}) =>
2221
2233
  current,
2222
2234
  ];
2223
2235
  }
2224
- if (!ownsLane(parent, request.ownershipToken)) {
2236
+ if (!ownsLane(current, parent, request.ownershipToken)) {
2225
2237
  return [failure(ownershipLost(current, parent)), current];
2226
2238
  }
2227
2239
  if (reservation.status !== "reserved") {