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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (48) hide show
  1. package/LICENSE +21 -0
  2. package/dist/MemoryMessageDeliveryStore-B50JDqxF.mjs +609 -0
  3. package/dist/MemoryMessageDeliveryStore-B50JDqxF.mjs.map +1 -0
  4. package/dist/MemoryMessageDeliveryStore-BmLntoBA.d.mts +18 -0
  5. package/dist/MemoryMessageDeliveryStore.d.mts +2 -0
  6. package/dist/MemoryMessageDeliveryStore.mjs +1 -0
  7. package/dist/MemoryScheduleStore-Bb85CXg1.mjs +163 -0
  8. package/dist/MemoryScheduleStore-Bb85CXg1.mjs.map +1 -0
  9. package/dist/MemoryScheduleStore-C_ll7Xyr.d.mts +8 -0
  10. package/dist/MemoryScheduleStore.d.mts +2 -0
  11. package/dist/MemoryScheduleStore.mjs +1 -0
  12. package/dist/MemorySemanticIndex-DYljUBy4.mjs +224 -0
  13. package/dist/MemorySemanticIndex-DYljUBy4.mjs.map +1 -0
  14. package/dist/MemorySemanticIndex-DrcJ7UG4.d.mts +20 -0
  15. package/dist/MemorySemanticIndex.d.mts +2 -0
  16. package/dist/MemorySemanticIndex.mjs +1 -0
  17. package/dist/MemorySubmissionLedger-DO-F22Gu.d.mts +28 -0
  18. package/dist/MemorySubmissionLedger-lc4VJ_vq.mjs +1566 -0
  19. package/dist/MemorySubmissionLedger-lc4VJ_vq.mjs.map +1 -0
  20. package/dist/MemorySubmissionLedger.d.mts +2 -0
  21. package/dist/MemorySubmissionLedger.mjs +1 -0
  22. package/dist/MemorySubscriptionStore-BWZ9lcIY.d.mts +7 -0
  23. package/dist/MemorySubscriptionStore-CFuGVxFD.mjs +929 -0
  24. package/dist/MemorySubscriptionStore-CFuGVxFD.mjs.map +1 -0
  25. package/dist/MemorySubscriptionStore.d.mts +2 -0
  26. package/dist/MemorySubscriptionStore.mjs +1 -0
  27. package/dist/MemoryThreadStore-BX3sRYhE.d.mts +21 -0
  28. package/dist/MemoryThreadStore-Dtwe-7h4.mjs +1415 -0
  29. package/dist/MemoryThreadStore-Dtwe-7h4.mjs.map +1 -0
  30. package/dist/MemoryThreadStore.d.mts +2 -0
  31. package/dist/MemoryThreadStore.mjs +1 -0
  32. package/dist/MemoryThreadStoreKernel-5ya9AJvL.d.mts +85 -0
  33. package/dist/WorkSelection-Xr9mCon_.mjs +29 -0
  34. package/dist/WorkSelection-Xr9mCon_.mjs.map +1 -0
  35. package/dist/index.d.mts +7 -0
  36. package/dist/index.mjs +7 -0
  37. package/dist/rolldown-runtime-D3KUYPsf.mjs +12 -0
  38. package/package.json +67 -5
  39. package/src/MemoryMessageDeliveryStore.ts +1004 -0
  40. package/src/MemoryScheduleStore.ts +324 -0
  41. package/src/MemorySemanticIndex.ts +360 -0
  42. package/src/MemorySubmissionLedger.ts +3590 -0
  43. package/src/MemorySubscriptionStore.ts +1762 -0
  44. package/src/MemoryThreadStore.ts +2810 -0
  45. package/src/index.ts +6 -0
  46. package/src/internal/MemoryThreadStoreKernel.ts +156 -0
  47. package/src/internal/WorkSelection.ts +29 -0
  48. package/README.md +0 -3
@@ -0,0 +1,1566 @@
1
+ import { t as __exportAll } from "./rolldown-runtime-D3KUYPsf.mjs";
2
+ import { canonicalJson, utf8ByteLength } from "@systemfsoftware/agent/digest";
3
+ import { AttemptId, ReceiptId, SubmissionId } from "@systemfsoftware/agent/identifiers";
4
+ import { InputMessage } from "@systemfsoftware/agent/messaging";
5
+ import { MAX_RUN_EVIDENCE_BYTES, MAX_RUN_EVIDENCE_RECORDS, PersistedJson, WorkerAdmission } from "@systemfsoftware/agent/records";
6
+ import { runIdForSubmission } from "@systemfsoftware/agent/run-journal";
7
+ import { SettlementPublicationResult, SettlementPublisher, validateCanonicalSettlement, validateJoinedSettlement, validatePublication } from "@systemfsoftware/agent/settlement-publisher";
8
+ import { AbortCommand, AbortIntent, AbortIntentRequest, AdmissionAdmitted, AdmissionConflict, AdmissionIndeterminate, AdmissionNotAdmitted, AdmissionPolicyError, AdmissionRequest, AdmissionResult, ApprovalConflict, ApprovalDecisionCommand, ApprovalDecisionIntent, AttachChildToReservationRequest, BeginChildBudgetReleaseRequest, ChildAttachmentSnapshot, ChildBudgetReservationRequest, ChildBudgetReservationSnapshot, ChildReservationConflict, ChildSettledNotification, Claim, ClaimJoiningRequest, ClaimRequest, FundingOwner, FundingOwnerRequest, InputAppliedMarker, JoinSnapshot, JoinedToHost, JoiningClaim, LedgerCapabilities, LedgerError, MarkInputAppliedRequest, MarkJoinedRequest, MarkReadyRequest, MarkUnknownRequest, OwnershipLost, QueueSequence, RecoverySnapshot, RecoverySnapshotRequest, ReleaseChildBudgetRequest, ReservedChildBudget, RevertJoiningRequest, Settlement, SettlementConflict, SettlementFinalization, SubmissionAdmissionFence, SubmissionLedger, SubmissionLookup, SubmissionLookupByKey, SubmissionSnapshot, SubmissionWorkItem, SuspendRequest, SuspensionSnapshot, UnknownResolution, UnknownResolutionCommand, UnknownResolutionConflict, UnknownResolutionIntent, WorkerLedgerState, WorkerStopCommand, approvalDecisionsCover, settlementFailureFromRecord, submissionSettlementRecordId, unknownResolutionKind, unknownResolutionMatchesResult, workerTerminalFromRecord } from "@systemfsoftware/agent/submission-ledger";
9
+ import { RebuiltSubmission, ThreadImportRejected, invalidThreadArchive, rebuildClosedSubmission } from "@systemfsoftware/agent/thread-import";
10
+ import { ThreadAbortFact, ThreadAdmission, ThreadApprovalFact, ThreadResolutionFact, ThreadStoreError, makeTransferFactCheck, transferPageFits } from "@systemfsoftware/agent/thread-store";
11
+ import { admissionWork } from "@systemfsoftware/agent/thread-work";
12
+ import * as Cause from "effect/Cause";
13
+ import * as Clock from "effect/Clock";
14
+ import * as Context from "effect/Context";
15
+ import * as SecureRandom from "effect/crypto/SecureRandom";
16
+ import * as DateTime from "effect/DateTime";
17
+ import * as Effect from "effect/Effect";
18
+ import * as Exit from "effect/Exit";
19
+ import * as Fiber from "effect/Fiber";
20
+ import * as Layer from "effect/Layer";
21
+ import * as MutableRef from "effect/MutableRef";
22
+ import * as Option from "effect/Option";
23
+ import * as Ref from "effect/Ref";
24
+ import * as Result from "effect/Result";
25
+ import * as Schema from "effect/Schema";
26
+ import * as Stream from "effect/Stream";
27
+ import { n as MemoryThreadStoreKernel, t as boundedWorkSelection } from "./WorkSelection-Xr9mCon_.mjs";
28
+ // src/MemorySubmissionLedger.ts
29
+ var MemorySubmissionLedger_exports = /* @__PURE__ */ __exportAll({
30
+ MemorySubmissionLedgerLive: () => MemorySubmissionLedgerLive,
31
+ memorySubmissionLedgerLayer: () => memorySubmissionLedgerLayer
32
+ });
33
+ /**
34
+ * Lifecycle ordering used to advance-but-never-regress the operational state marker: a reclaimed
35
+ * Attempt must not erase progress markers (input-applied) that an earlier Attempt
36
+ * already committed.
37
+ */
38
+ const STATE_RANK = {
39
+ admitted: 0,
40
+ ready: 1,
41
+ joining: 2,
42
+ joined: 3,
43
+ "input-applied": 5,
44
+ suspended: 6,
45
+ unknown: 7,
46
+ settled: 8
47
+ };
48
+ /**
49
+ * States in which `claim` never grants the head: the lane is host-owned (`joining`/`joined`)
50
+ * or durably suspended rather than worker-claimable. Unknown heads are checked against abort
51
+ * intent separately: abort authorizes cleanup and settlement, never ordinary Tool replay.
52
+ */
53
+ const BLOCKED_HEAD_STATES = /* @__PURE__ */ new Set([
54
+ "joining",
55
+ "joined",
56
+ "suspended"
57
+ ]);
58
+ const commandPosition = (entries, key) => {
59
+ let low = 0;
60
+ let high = entries.length;
61
+ while (low < high) {
62
+ const middle = Math.floor((low + high) / 2);
63
+ if (entries[middle].key < key) low = middle + 1;
64
+ else high = middle;
65
+ }
66
+ return low;
67
+ };
68
+ const retainCommand = (entries, submissionId, toolCallId, resolutionKey) => {
69
+ const key = String(entries.length + 1).padStart(16, "0");
70
+ entries.push({
71
+ key,
72
+ submissionId,
73
+ ...toolCallId === void 0 ? {} : { toolCallId },
74
+ ...resolutionKey === void 0 ? {} : { resolutionKey }
75
+ });
76
+ };
77
+ const failure = (error) => ({
78
+ _tag: "failure",
79
+ error
80
+ });
81
+ const success = (value) => ({
82
+ _tag: "success",
83
+ value
84
+ });
85
+ const ledgerError = (operation, message, cause) => cause === void 0 ? LedgerError.make({
86
+ operation,
87
+ message
88
+ }) : LedgerError.make({
89
+ operation,
90
+ message,
91
+ cause
92
+ });
93
+ const validate = (schema, operation, value) => Schema.encodeUnknownEffect(schema)(value).pipe(Effect.flatMap(Schema.decodeUnknownEffect(schema)), Effect.mapError((error) => ledgerError(operation, `Invalid ${operation} request`, error)));
94
+ const decodeSubmissionId = Schema.decodeSync(SubmissionId);
95
+ const decodeReceiptId = Schema.decodeSync(ReceiptId);
96
+ const decodeAttemptId = Schema.decodeSync(AttemptId);
97
+ const MemoryIdentityNonce = Schema.String.check(Schema.isUUID(4));
98
+ const decodeQueueSequence = Schema.decodeSync(QueueSequence);
99
+ const equivalentPersistedJson = Schema.toEquivalence(PersistedJson);
100
+ const equivalentUnknownResolution = Schema.toEquivalence(UnknownResolution);
101
+ const admissionFitsTransfer = makeTransferFactCheck(ThreadAdmission);
102
+ const abortFitsTransfer = makeTransferFactCheck(ThreadAbortFact);
103
+ const approvalFitsTransfer = makeTransferFactCheck(ThreadApprovalFact);
104
+ const resolutionFitsTransfer = makeTransferFactCheck(ThreadResolutionFact);
105
+ const transferCapacityError = (operation) => ledgerError(operation, "Accepted fact exceeds its bounded transfer representation");
106
+ const utc = (millis) => DateTime.toUtc(DateTime.makeUnsafe(millis));
107
+ const admissionKey = (threadId, principal, idempotencyKey) => JSON.stringify([
108
+ threadId,
109
+ principal,
110
+ idempotencyKey
111
+ ]);
112
+ const toSnapshot = (row) => SubmissionSnapshot.make({
113
+ submissionId: row.submissionId,
114
+ threadId: row.threadId,
115
+ queueSequence: row.queueSequence,
116
+ principal: row.principal,
117
+ idempotencyKey: row.idempotencyKey,
118
+ agentId: row.agentId,
119
+ agentDigests: row.agentDigests,
120
+ deploymentId: row.deploymentId,
121
+ inputPayload: row.inputPayload,
122
+ inputDigest: row.inputDigest,
123
+ receiptId: row.receiptId,
124
+ state: row.state,
125
+ createdAt: utc(row.createdAtMillis),
126
+ ...row.admissionGroup === void 0 ? {} : { admissionGroup: row.admissionGroup },
127
+ ...row.admissionFence === void 0 ? {} : { admissionFence: row.admissionFence },
128
+ ...row.workerAdmissionJson === void 0 ? {} : { workerAdmission: Schema.decodeSync(Schema.fromJsonString(WorkerAdmission))(row.workerAdmissionJson) },
129
+ ...row.messageAdmissionJson === void 0 ? {} : { messageAdmission: Schema.decodeSync(Schema.fromJsonString(InputMessage))(row.messageAdmissionJson) },
130
+ ...row.settledOutcome === void 0 ? {} : { settledOutcome: row.settledOutcome },
131
+ ...row.readyAtMillis === void 0 ? {} : { readyAt: utc(row.readyAtMillis) },
132
+ ...row.parentLinkage === void 0 ? {} : { parentLinkage: row.parentLinkage }
133
+ });
134
+ const toReservationSnapshot = (row) => ChildBudgetReservationSnapshot.make({
135
+ reservationId: row.reservationId,
136
+ parentSubmissionId: row.parentSubmissionId,
137
+ parentToolCallId: row.parentToolCallId,
138
+ status: row.status,
139
+ allocation: row.allocation,
140
+ allocationDigest: row.allocationDigest,
141
+ reservedAt: utc(row.reservedAtMillis),
142
+ ...row.childSubmissionId === void 0 ? {} : { childSubmissionId: row.childSubmissionId },
143
+ ...row.accounting === void 0 ? {} : { accounting: row.accounting },
144
+ ...row.releaseBeganAtMillis === void 0 ? {} : { releaseBeganAt: utc(row.releaseBeganAtMillis) },
145
+ ...row.releasedAtMillis === void 0 ? {} : { releasedAt: utc(row.releasedAtMillis) }
146
+ });
147
+ const fromRebuilt = (rebuilt) => {
148
+ const admission = rebuilt.admission;
149
+ const threadId = admission.threadId;
150
+ const canonicalSettlement = rebuilt.settlement?.payload;
151
+ const settlement = canonicalSettlement?._tag === "SubmissionSettled" ? canonicalSettlement : void 0;
152
+ return {
153
+ row: {
154
+ submissionId: admission.submissionId,
155
+ threadId,
156
+ queueSequence: admission.queueSequence,
157
+ principal: admission.principal,
158
+ idempotencyKey: admission.idempotencyKey,
159
+ agentId: admission.agentId,
160
+ agentDigests: admission.agentDigests,
161
+ deploymentId: admission.deploymentId,
162
+ inputPayload: admission.inputPayload,
163
+ inputDigest: admission.inputDigest,
164
+ receiptId: admission.receiptId,
165
+ state: rebuilt.state,
166
+ settledOutcome: settlement?.outcome,
167
+ createdAtMillis: DateTime.toEpochMillis(admission.createdAt),
168
+ readyAtMillis: rebuilt.state === "ready" ? DateTime.toEpochMillis(admission.createdAt) : void 0,
169
+ parentLinkage: admission.parentLinkage,
170
+ ...admission.workerAdmission === void 0 ? {} : { workerAdmissionJson: Schema.encodeSync(Schema.fromJsonString(WorkerAdmission))(admission.workerAdmission) },
171
+ ...admission.messageAdmission === void 0 ? {} : { messageAdmissionJson: Schema.encodeSync(Schema.fromJsonString(InputMessage))(admission.messageAdmission) },
172
+ ...admission.admissionGroup === void 0 ? {} : { admissionGroup: admission.admissionGroup },
173
+ ...admission.admissionFence === void 0 ? {} : { admissionFence: admission.admissionFence }
174
+ },
175
+ inputApplied: rebuilt.inputApplied,
176
+ finalization: settlement === void 0 || rebuilt.settlement === void 0 || admission.settledAt === void 0 ? void 0 : {
177
+ settlementId: settlement.settlementId,
178
+ recordId: rebuilt.settlement.recordId,
179
+ finalizedAtMillis: DateTime.toEpochMillis(admission.settledAt)
180
+ },
181
+ abortIntent: rebuilt.abort,
182
+ joinedHostSubmissionId: rebuilt.joinedHostSubmissionId,
183
+ suspension: rebuilt.suspension === void 0 ? void 0 : {
184
+ reason: rebuilt.suspension.reason,
185
+ suspendedAtMillis: DateTime.toEpochMillis(rebuilt.suspension.suspendedAt)
186
+ },
187
+ unknownMark: rebuilt.unknownToolCallIds.length === 0 ? void 0 : {
188
+ reason: "Unresolved Tool execution recovered from the canonical log",
189
+ toolCallIds: rebuilt.unknownToolCallIds
190
+ },
191
+ approvalDecisions: new Map(rebuilt.approvals.map((intent) => [intent.toolCallId, intent])),
192
+ unknownResolutions: new Map(rebuilt.resolutions.map((intent) => [JSON.stringify([intent.toolCallId, unknownResolutionKind(intent.resolution)]), { intent }]))
193
+ };
194
+ };
195
+ /** Linkage equality: both absent, or both present naming the same parent Tool Call. */
196
+ const sameParentLinkage = (left, right) => left === void 0 ? right === void 0 : right !== void 0 && left.parentSubmissionId === right.parentSubmissionId && left.parentToolCallId === right.parentToolCallId;
197
+ const ownershipLost = (stored) => OwnershipLost.make({ submissionId: stored.row.submissionId });
198
+ const withSubmission = (state, stored) => {
199
+ const row = stored.row;
200
+ const previous = state.submissions.get(row.submissionId);
201
+ let directory = state.byThread.get(row.threadId);
202
+ if (directory === void 0) {
203
+ directory = {
204
+ ordered: [],
205
+ commands: {
206
+ aborts: [],
207
+ approvals: [],
208
+ resolutions: []
209
+ },
210
+ children: 0,
211
+ workers: 0,
212
+ reservations: 0
213
+ };
214
+ state.byThread.set(row.threadId, directory);
215
+ }
216
+ if (previous === void 0) {
217
+ let low = 0;
218
+ let high = directory.ordered.length;
219
+ while (low < high) {
220
+ const middle = Math.floor((low + high) / 2);
221
+ const candidate = state.submissions.get(directory.ordered[middle]);
222
+ if (candidate !== void 0 && candidate.row.queueSequence < row.queueSequence) low = middle + 1;
223
+ else high = middle;
224
+ }
225
+ directory.ordered.splice(low, 0, row.submissionId);
226
+ state.receipts.set(row.receiptId, row.submissionId);
227
+ state.admissionIndex.set(admissionKey(row.threadId, row.principal, row.idempotencyKey), row.submissionId);
228
+ const latest = state.latestByThread.get(row.threadId);
229
+ if (latest === void 0 || (state.submissions.get(latest)?.row.queueSequence ?? -1) < row.queueSequence) state.latestByThread.set(row.threadId, row.submissionId);
230
+ }
231
+ directory.children += Number(row.state !== "settled" && row.parentLinkage !== void 0) - Number(previous !== void 0 && previous.row.state !== "settled" && previous.row.parentLinkage !== void 0);
232
+ directory.workers += Number(row.state !== "settled" && row.workerAdmissionJson !== void 0) - Number(previous !== void 0 && previous.row.state !== "settled" && previous.row.workerAdmissionJson !== void 0);
233
+ if (stored.abortIntent !== void 0 && previous?.abortIntent === void 0) retainCommand(directory.commands.aborts, row.submissionId);
234
+ if (stored.approvalDecisions !== previous?.approvalDecisions) {
235
+ for (const id of stored.approvalDecisions.keys()) if (!previous?.approvalDecisions.has(id)) retainCommand(directory.commands.approvals, row.submissionId, id);
236
+ }
237
+ if (stored.unknownResolutions !== previous?.unknownResolutions) {
238
+ for (const [id, value] of stored.unknownResolutions) if (!previous?.unknownResolutions.has(id)) retainCommand(directory.commands.resolutions, row.submissionId, value.intent.toolCallId, id);
239
+ }
240
+ if (previous?.joinedHostSubmissionId !== void 0 && previous.joinedHostSubmissionId !== stored.joinedHostSubmissionId) state.joinsByHost.get(previous.joinedHostSubmissionId)?.delete(row.submissionId);
241
+ if (stored.joinedHostSubmissionId !== void 0) {
242
+ let joins = state.joinsByHost.get(stored.joinedHostSubmissionId);
243
+ if (joins === void 0) state.joinsByHost.set(stored.joinedHostSubmissionId, joins = /* @__PURE__ */ new Set());
244
+ joins.add(row.submissionId);
245
+ }
246
+ let active = state.activeByThread.get(row.threadId);
247
+ if (active === void 0) state.activeByThread.set(row.threadId, active = /* @__PURE__ */ new Set());
248
+ if (row.state === "settled") active.delete(row.submissionId);
249
+ else active.add(row.submissionId);
250
+ state.submissions.set(row.submissionId, stored);
251
+ return state;
252
+ };
253
+ const withChildReservation = (state, reservation) => {
254
+ const previous = state.childReservations.get(reservation.reservationId);
255
+ state.childReservations.set(reservation.reservationId, reservation);
256
+ let children = state.childrenByParent.get(reservation.parentSubmissionId);
257
+ if (children === void 0) state.childrenByParent.set(reservation.parentSubmissionId, children = /* @__PURE__ */ new Set());
258
+ children.add(reservation.reservationId);
259
+ const parent = state.submissions.get(reservation.parentSubmissionId);
260
+ if (parent !== void 0) {
261
+ const directory = state.byThread.get(parent.row.threadId);
262
+ if (directory !== void 0) directory.reservations += Number(reservation.status !== "released") - Number(previous !== void 0 && previous.status !== "released");
263
+ }
264
+ return state;
265
+ };
266
+ const findHead = (state, threadId) => {
267
+ let head;
268
+ for (const id of state.activeByThread.get(threadId) ?? []) {
269
+ const stored = state.submissions.get(id);
270
+ if (stored === void 0 || stored.row.state === "unknown" && stored.abortIntent === void 0) continue;
271
+ if (head === void 0 || stored.row.queueSequence < head.row.queueSequence) head = stored;
272
+ }
273
+ return head;
274
+ };
275
+ function* threadRows(state, threadId, after = -1) {
276
+ const ordered = state.byThread.get(threadId)?.ordered ?? [];
277
+ let low = 0;
278
+ let high = ordered.length;
279
+ while (low < high) {
280
+ const middle = Math.floor((low + high) / 2);
281
+ if ((state.submissions.get(ordered[middle])?.row.queueSequence ?? -1) <= after) low = middle + 1;
282
+ else high = middle;
283
+ }
284
+ for (let index = low; index < ordered.length; index++) {
285
+ const stored = state.submissions.get(ordered[index]);
286
+ if (stored !== void 0) yield stored;
287
+ }
288
+ }
289
+ const makeSubmissionLedger = Effect.fnUntraced(
290
+ /**
291
+ * Reference in-memory SubmissionLedger. Admission, ordered selection and canonical settlement
292
+ * share the Memory kernel's mutation gate. The kernel Scope owns local Run capabilities;
293
+ * selecting work does not write execution ownership into the ledger.
294
+ *
295
+ * Joining retains the contiguous ready prefix and exact host linkage. Canonical settlement
296
+ * authorizes finalization and child wake repair, while bound sessions reject late commands.
297
+ * Child wake checks read the child rows directly, without a separate notification marker.
298
+ * Admission resolution is strongly consistent; resolveAdmissionFault injects the
299
+ * Indeterminate outcome for existing caller conformance workflows.
300
+ */
301
+ function* (options = {}) {
302
+ const journal = yield* MemoryThreadStoreKernel;
303
+ const crypto = yield* SecureRandom.SecureRandom;
304
+ const mintIdentity = (operation) => crypto.uuidV4().pipe(Effect.flatMap(Schema.decodeEffect(MemoryIdentityNonce)), Effect.mapError((cause) => ledgerError(operation, "Cannot mint a Memory identity", cause)));
305
+ const state = yield* Ref.make({
306
+ byThread: /* @__PURE__ */ new Map(),
307
+ receipts: /* @__PURE__ */ new Map(),
308
+ joinsByHost: /* @__PURE__ */ new Map(),
309
+ childrenByParent: /* @__PURE__ */ new Map(),
310
+ submissions: /* @__PURE__ */ new Map(),
311
+ admissionIndex: /* @__PURE__ */ new Map(),
312
+ lanes: /* @__PURE__ */ new Map(),
313
+ childReservations: /* @__PURE__ */ new Map(),
314
+ freshAdmissionSequence: 0,
315
+ stoppedWorkers: /* @__PURE__ */ new Map(),
316
+ latestByThread: /* @__PURE__ */ new Map(),
317
+ activeByThread: /* @__PURE__ */ new Map()
318
+ });
319
+ yield* journal.registerWorkOwner("admissions", {
320
+ threads: (request) => Ref.get(state).pipe(Effect.map((current) => {
321
+ const candidates = boundedWorkSelection(request.limit, (id) => id, request.afterThreadId);
322
+ for (const [threadId, ids] of current.activeByThread) if (ids.size > 0) candidates.add(threadId);
323
+ const threadIds = candidates.values;
324
+ const afterThreadId = threadIds.length === request.limit ? threadIds.at(-1) : void 0;
325
+ return {
326
+ threadIds,
327
+ ...afterThreadId === void 0 ? {} : { afterThreadId }
328
+ };
329
+ })),
330
+ page: Effect.fnUntraced(function* (threadId, after, limit) {
331
+ const current = yield* Ref.get(state);
332
+ const candidates = boundedWorkSelection(limit + 1, (id) => id, after);
333
+ for (const id of current.activeByThread.get(threadId) ?? []) candidates.add(id);
334
+ const ids = candidates.values;
335
+ const entries = [];
336
+ for (const id of ids.slice(0, limit)) {
337
+ const stored = current.submissions.get(id);
338
+ if (stored === void 0 || stored.row.threadId !== threadId || stored.row.state === "settled") return yield* ThreadStoreError.make({
339
+ operation: "admission work",
340
+ message: "Active admission index is incomplete or corrupt"
341
+ });
342
+ const entry = admissionWork(stored.row);
343
+ entries.push(stored.suspension === void 0 ? entry : {
344
+ ...entry,
345
+ wait: stored.suspension.reason._tag === "WaitingForChild" ? "child" : "approval"
346
+ });
347
+ }
348
+ const next = ids.length > limit ? ids[limit - 1] : void 0;
349
+ return {
350
+ entries,
351
+ ...next === void 0 ? {} : { after: next }
352
+ };
353
+ })
354
+ });
355
+ const admissionFence = yield* SubmissionAdmissionFence;
356
+ const capabilities = Effect.succeed(LedgerCapabilities.make({ durability: "non-durable" }));
357
+ const admit = Effect.fnUntraced(function* (unvalidated) {
358
+ const request = yield* validate(AdmissionRequest, "admit", unvalidated);
359
+ const workerAdmissionJson = request.workerAdmission === void 0 ? void 0 : yield* Schema.encodeEffect(Schema.fromJsonString(WorkerAdmission))(request.workerAdmission).pipe(Effect.mapError(() => ledgerError("admit", "Invalid worker admission metadata")));
360
+ const messageAdmissionJson = request.messageAdmission === void 0 ? void 0 : yield* Schema.encodeEffect(Schema.fromJsonString(InputMessage))(request.messageAdmission).pipe(Effect.mapError(() => ledgerError("admit", "Invalid message admission metadata")));
361
+ yield* journal.checkThreadCapacity(request.threadId).pipe(Effect.mapError((cause) => ledgerError("admit", cause.message, cause)));
362
+ const nowMillis = yield* Clock.currentTimeMillis;
363
+ const identity = (yield* Ref.get(state)).admissionIndex.has(admissionKey(request.threadId, request.principal, request.idempotencyKey)) ? Result.fail(ledgerError("admit", "Retained admission disappeared")) : yield* Effect.result(mintIdentity("admit"));
364
+ const services = yield* Effect.context();
365
+ const decision = yield* Ref.modify(state, (current) => {
366
+ const key = admissionKey(request.threadId, request.principal, request.idempotencyKey);
367
+ const existingId = current.admissionIndex.get(key);
368
+ if (existingId !== void 0) {
369
+ const existing = current.submissions.get(existingId);
370
+ if (existing === void 0) return [failure(ledgerError("admit", "Admission index references a missing Submission")), current];
371
+ if (existing.row.inputDigest !== request.inputDigest || !sameParentLinkage(existing.row.parentLinkage, request.parentLinkage) || existing.row.admissionGroup !== request.admissionGroup || !Schema.toEquivalence(Schema.optional(WorkerAdmission))(existing.row.workerAdmissionJson === void 0 ? void 0 : Schema.decodeSync(Schema.fromJsonString(WorkerAdmission))(existing.row.workerAdmissionJson), request.workerAdmission) || !Schema.toEquivalence(Schema.optional(InputMessage))(existing.row.messageAdmissionJson === void 0 ? void 0 : Schema.decodeSync(Schema.fromJsonString(InputMessage))(existing.row.messageAdmissionJson), request.messageAdmission) || !Schema.toEquivalence(Schema.optional(Schema.Json))(existing.row.admissionFence, request.admissionFence)) return [failure(AdmissionConflict.make({
372
+ threadId: request.threadId,
373
+ principal: request.principal,
374
+ idempotencyKey: request.idempotencyKey,
375
+ existingInputDigest: existing.row.inputDigest,
376
+ attemptedInputDigest: request.inputDigest
377
+ })), current];
378
+ return [success(AdmissionResult.make({
379
+ submissionId: existing.row.submissionId,
380
+ receiptId: existing.row.receiptId,
381
+ queueSequence: existing.row.queueSequence,
382
+ state: existing.row.state,
383
+ replayed: true
384
+ })), current];
385
+ }
386
+ if (current.stoppedWorkers.has(request.threadId)) return [failure(AdmissionPolicyError.make({
387
+ reason: "refused",
388
+ code: "worker-stopped"
389
+ })), current];
390
+ const first = threadRows(current, request.threadId).next().value;
391
+ if (first !== void 0) {
392
+ const previous = first.row.workerAdmissionJson === void 0 ? void 0 : Schema.decodeSync(Schema.fromJsonString(WorkerAdmission))(first.row.workerAdmissionJson);
393
+ if (!Schema.toEquivalence(Schema.optional(WorkerAdmission.fields.origin))(previous?.origin, request.workerAdmission?.origin)) return [failure(AdmissionPolicyError.make({
394
+ reason: "refused",
395
+ code: "worker-origin-conflict"
396
+ })), current];
397
+ }
398
+ const checked = Effect.runSyncExitWith(services)(admissionFence.check(request));
399
+ if (Exit.isFailure(checked)) return [{
400
+ _tag: "cause",
401
+ cause: checked.cause
402
+ }, current];
403
+ if (request.admissionGroup !== void 0 && Array.from(current.activeByThread.get(request.threadId) ?? []).some((id) => current.submissions.get(id)?.row.admissionGroup === request.admissionGroup)) return [failure(AdmissionPolicyError.make({
404
+ reason: "occupied",
405
+ code: "admission-group"
406
+ })), current];
407
+ if (Result.isFailure(identity)) return [failure(identity.failure), current];
408
+ const lane = current.lanes.get(request.threadId) ?? { nextQueueSequence: 1 };
409
+ const freshAdmissionSequence = current.freshAdmissionSequence + 1;
410
+ if (!Number.isSafeInteger(freshAdmissionSequence)) return [failure(ledgerError("admit", "Fresh admission sequence is exhausted")), current];
411
+ const orderedIdentity = `${String(freshAdmissionSequence).padStart(16, "0")}-${identity.success}`;
412
+ const submissionId = decodeSubmissionId(`submission-memory-${orderedIdentity}`);
413
+ const receiptId = decodeReceiptId(`receipt-memory-${orderedIdentity}`);
414
+ if (current.submissions.has(submissionId) || current.receipts.has(receiptId)) return [failure(ledgerError("admit", "Fresh admission identity already exists")), current];
415
+ const row = {
416
+ submissionId,
417
+ threadId: request.threadId,
418
+ queueSequence: decodeQueueSequence(lane.nextQueueSequence),
419
+ principal: request.principal,
420
+ idempotencyKey: request.idempotencyKey,
421
+ agentId: request.agentId,
422
+ agentDigests: request.agentDigests,
423
+ deploymentId: request.deploymentId,
424
+ inputPayload: request.inputPayload,
425
+ inputDigest: request.inputDigest,
426
+ receiptId,
427
+ state: "admitted",
428
+ settledOutcome: void 0,
429
+ createdAtMillis: nowMillis,
430
+ readyAtMillis: void 0,
431
+ parentLinkage: request.parentLinkage,
432
+ ...workerAdmissionJson === void 0 ? {} : { workerAdmissionJson },
433
+ ...messageAdmissionJson === void 0 ? {} : { messageAdmissionJson },
434
+ ...request.admissionGroup === void 0 ? {} : { admissionGroup: request.admissionGroup },
435
+ ...request.admissionFence === void 0 ? {} : { admissionFence: request.admissionFence }
436
+ };
437
+ const stored = {
438
+ row,
439
+ inputApplied: void 0,
440
+ finalization: void 0,
441
+ abortIntent: void 0,
442
+ joinedHostSubmissionId: void 0,
443
+ suspension: void 0,
444
+ unknownMark: void 0,
445
+ approvalDecisions: /* @__PURE__ */ new Map(),
446
+ unknownResolutions: /* @__PURE__ */ new Map()
447
+ };
448
+ if (!admissionFitsTransfer(request.threadId, toAdmission(row))) return [failure(transferCapacityError("admit")), current];
449
+ journal.initializeWork(request.threadId);
450
+ const admissionIndex = current.admissionIndex;
451
+ const lanes = current.lanes.set(request.threadId, { nextQueueSequence: lane.nextQueueSequence + 1 });
452
+ return [success(AdmissionResult.make({
453
+ submissionId: row.submissionId,
454
+ receiptId: row.receiptId,
455
+ queueSequence: row.queueSequence,
456
+ state: row.state,
457
+ replayed: false
458
+ })), {
459
+ ...withSubmission(current, stored),
460
+ admissionIndex,
461
+ lanes,
462
+ freshAdmissionSequence
463
+ }];
464
+ });
465
+ if (decision._tag === "failure") return yield* decision.error;
466
+ if (decision._tag === "cause") {
467
+ for (const reason of decision.cause.reasons) if (Cause.isDieReason(reason) && Cause.isAsyncFiberError(reason.defect)) {
468
+ yield* Fiber.interrupt(reason.defect.fiber);
469
+ return yield* AdmissionPolicyError.make({
470
+ reason: "unavailable",
471
+ code: "synchronous-memory-policy-required"
472
+ });
473
+ }
474
+ return yield* Effect.failCause(decision.cause);
475
+ }
476
+ return decision.value;
477
+ }, Effect.uninterruptible);
478
+ const markReady = Effect.fnUntraced(function* (unvalidated) {
479
+ const request = yield* validate(MarkReadyRequest, "markReady", unvalidated);
480
+ const nowMillis = yield* Clock.currentTimeMillis;
481
+ const decision = yield* Ref.modify(state, (current) => {
482
+ const stored = current.submissions.get(request.submissionId);
483
+ if (stored === void 0) return [failure(ledgerError("markReady", `Unknown Submission ${request.submissionId}`)), current];
484
+ if (stored.row.state !== "admitted") return [success(void 0), current];
485
+ return [success(void 0), withSubmission(current, {
486
+ ...stored,
487
+ row: {
488
+ ...stored.row,
489
+ state: "ready",
490
+ readyAtMillis: nowMillis
491
+ }
492
+ })];
493
+ });
494
+ if (decision._tag === "failure") return yield* decision.error;
495
+ });
496
+ const lookup = Effect.fnUntraced(function* (unvalidated) {
497
+ const request = yield* validate(SubmissionLookup, "lookup", unvalidated);
498
+ const current = yield* Ref.get(state);
499
+ const submissionId = request._tag === "SubmissionLookupById" ? request.submissionId : current.admissionIndex.get(admissionKey(request.threadId, request.principal, request.idempotencyKey));
500
+ const stored = submissionId === void 0 ? void 0 : current.submissions.get(submissionId);
501
+ return stored === void 0 ? Option.none() : Option.some(toSnapshot(stored.row));
502
+ });
503
+ const resolveAdmission = Effect.fnUntraced(function* (unvalidated) {
504
+ const request = yield* validate(SubmissionLookupByKey, "resolveAdmission", unvalidated);
505
+ if (options.resolveAdmissionFault !== void 0) {
506
+ const fault = yield* options.resolveAdmissionFault;
507
+ if (Option.isSome(fault)) return AdmissionIndeterminate.make({ reason: fault.value });
508
+ }
509
+ const current = yield* Ref.get(state);
510
+ const submissionId = current.admissionIndex.get(admissionKey(request.threadId, request.principal, request.idempotencyKey));
511
+ const stored = submissionId === void 0 ? void 0 : current.submissions.get(submissionId);
512
+ return stored === void 0 ? AdmissionNotAdmitted.make() : AdmissionAdmitted.make({ submission: toSnapshot(stored.row) });
513
+ });
514
+ const selectHead = Effect.fn("MemorySubmissionLedger.selectHead")((unvalidated) => Effect.gen(function* () {
515
+ const request = yield* validate(ClaimRequest, "claim", unvalidated);
516
+ const identity = yield* mintIdentity("claim");
517
+ const decision = yield* Ref.modify(state, (current) => {
518
+ if (journal.owner.hasOwner(request.threadId)) return [success(Option.none()), current];
519
+ let head = findHead(current, request.threadId);
520
+ if (request.handoff !== void 0) {
521
+ const handoff = request.handoff;
522
+ const candidates = Array.from(current.activeByThread.get(request.threadId) ?? [], (id) => current.submissions.get(id)).filter((entry) => entry !== void 0 && !(entry.row.state === "unknown" && entry.abortIntent === void 0)).sort((a, b) => a.row.queueSequence - b.row.queueSequence);
523
+ for (const candidate of candidates) {
524
+ if (candidate.row.submissionId === handoff.submissionId) {
525
+ head = candidate;
526
+ break;
527
+ }
528
+ if (!handoff.deferredSubmissionIds.includes(candidate.row.submissionId) || candidate.row.state !== "input-applied" || candidate.abortIntent !== void 0) return [success(Option.none()), current];
529
+ }
530
+ if (head?.row.submissionId !== handoff.submissionId || head.row.state !== "ready" && head.row.state !== "input-applied") return [success(Option.none()), current];
531
+ }
532
+ if (head === void 0) return [success(Option.none()), current];
533
+ if (BLOCKED_HEAD_STATES.has(head.row.state)) return [success(Option.none()), current];
534
+ return [success(Option.some(Claim.make({
535
+ submissionId: head.row.submissionId,
536
+ attemptId: decodeAttemptId(`attempt-memory-${identity}`),
537
+ inputPayload: head.row.inputPayload
538
+ }))), current];
539
+ });
540
+ if (decision._tag === "failure") return yield* decision.error;
541
+ return decision.value;
542
+ }));
543
+ const markInputApplied = Effect.fnUntraced(function* (unvalidated) {
544
+ const request = yield* validate(MarkInputAppliedRequest, "markInputApplied", unvalidated);
545
+ const decision = yield* Ref.modify(state, (current) => {
546
+ const stored = current.submissions.get(request.submissionId);
547
+ if (stored === void 0) return [failure(ledgerError("markInputApplied", `Unknown Submission ${request.submissionId}`)), current];
548
+ if (!journal.owner.hasOwner(stored.row.threadId, stored.row.submissionId)) return [failure(ownershipLost(stored)), current];
549
+ if (stored.inputApplied !== void 0) {
550
+ if (stored.inputApplied.recordId === request.recordId && stored.inputApplied.sequence === request.sequence) return [success(void 0), current];
551
+ return [failure(ledgerError("markInputApplied", `A different canonical input marker is already recorded for Submission ${request.submissionId}`)), current];
552
+ }
553
+ const marker = InputAppliedMarker.make({
554
+ recordId: request.recordId,
555
+ sequence: request.sequence
556
+ });
557
+ const row = STATE_RANK[stored.row.state] < STATE_RANK["input-applied"] ? {
558
+ ...stored.row,
559
+ state: "input-applied"
560
+ } : stored.row;
561
+ return [success(void 0), withSubmission(current, {
562
+ ...stored,
563
+ row,
564
+ inputApplied: marker
565
+ })];
566
+ });
567
+ if (decision._tag === "failure") return yield* decision.error;
568
+ });
569
+ const canonicalSettlement = Effect.fnUntraced(function* (submission) {
570
+ const record = yield* journal.record(submission.threadId, submissionSettlementRecordId(submission.submissionId));
571
+ if (record === void 0) return void 0;
572
+ return {
573
+ record,
574
+ settlement: yield* validateCanonicalSettlement(record, submission)
575
+ };
576
+ });
577
+ const publish = Effect.fn("MemorySettlementPublisher.publish")(function* (input) {
578
+ const { request, record, settlement } = yield* validatePublication(input);
579
+ const prepared = yield* journal.prepareAppend(request.append);
580
+ return yield* journal.owner.withProgress(request.append.threadId, journal.withMutation(Effect.gen(function* () {
581
+ const current = yield* Ref.get(state);
582
+ const stored = current.submissions.get(request.submissionId);
583
+ if (stored === void 0) return yield* ledgerError("publish settlement", "Unknown Submission");
584
+ if (stored.row.threadId !== prepared.request.threadId) return yield* ledgerError("publish settlement", "Publication targets another Thread");
585
+ yield* validateCanonicalSettlement(record, stored.row);
586
+ const existing = yield* canonicalSettlement(stored.row);
587
+ const tail = yield* journal.tail(stored.row.threadId);
588
+ switch (request.authority._tag) {
589
+ case "Owned":
590
+ if (!journal.owner.hasOwner(stored.row.threadId, stored.row.submissionId)) return yield* ownershipLost(stored);
591
+ yield* validateCanonicalSettlement(record, {
592
+ submissionId: request.submissionId,
593
+ receiptId: stored.row.receiptId,
594
+ ...settlement.outcome === "aborted" && settlement.runId === void 0 ? {} : { runId: runIdForSubmission(request.submissionId) }
595
+ });
596
+ break;
597
+ case "Joined": {
598
+ if (stored.row.state !== "joined" && !(stored.row.state === "settled" && existing !== void 0) || stored.joinedHostSubmissionId !== request.authority.hostSubmissionId) return yield* ledgerError("publish settlement", "Submission is not joined to this host");
599
+ const host = current.submissions.get(request.authority.hostSubmissionId);
600
+ const canonicalHost = host === void 0 || host.row.threadId !== stored.row.threadId ? void 0 : yield* canonicalSettlement(host.row);
601
+ if (canonicalHost === void 0) return yield* ledgerError("publish settlement", "Joined host has no canonical settlement");
602
+ yield* validateJoinedSettlement(settlement, canonicalHost.settlement);
603
+ break;
604
+ }
605
+ case "QueuedAbort":
606
+ if (stored.row.state !== "ready" && !(stored.row.state === "settled" && existing !== void 0) || stored.abortIntent === void 0 || journal.owner.hasOwner(stored.row.threadId, stored.row.submissionId) || settlement.outcome !== "aborted") return yield* ledgerError("publish settlement", "Submission is not an unclaimed queued abort");
607
+ yield* validateCanonicalSettlement(record, {
608
+ submissionId: request.submissionId,
609
+ receiptId: stored.row.receiptId,
610
+ runId: void 0
611
+ });
612
+ }
613
+ if (existing !== void 0) return SettlementPublicationResult.make({
614
+ record: existing.record,
615
+ tailSequence: tail.tailSequence,
616
+ replayed: true
617
+ });
618
+ if (stored.row.state === "settled") return yield* ledgerError("publish settlement", "Finalized Submission has no canonical settlement");
619
+ const appended = yield* journal.appendPrepared(prepared);
620
+ return SettlementPublicationResult.make({
621
+ record,
622
+ tailSequence: appended.lastSequence,
623
+ replayed: false
624
+ });
625
+ })));
626
+ });
627
+ const finalizeSettlement = Effect.fn("MemorySubmissionLedger.finalizeSettlement")((unvalidated) => Effect.gen(function* () {
628
+ const request = yield* validate(SettlementFinalization, "finalizeSettlement", unvalidated);
629
+ const before = (yield* Ref.get(state)).submissions.get(request.submissionId);
630
+ const canonical = before === void 0 ? void 0 : yield* canonicalSettlement(before.row);
631
+ if (canonical === void 0) return yield* ledgerError("finalizeSettlement", "Submission has no canonical settlement");
632
+ const { record, settlement } = canonical;
633
+ const nowMillis = yield* Clock.currentTimeMillis;
634
+ const decision = yield* Ref.modify(state, (current) => {
635
+ const stored = current.submissions.get(request.submissionId);
636
+ if (stored === void 0) return [failure(ledgerError("finalizeSettlement", `Unknown Submission ${request.submissionId}`)), current];
637
+ const settlementFailure = settlementFailureFromRecord(record);
638
+ if (settlement.settlementId !== request.settlementId) return [failure(SettlementConflict.make({
639
+ submissionId: request.submissionId,
640
+ existingOutcome: settlement.outcome
641
+ })), current];
642
+ if (stored.finalization !== void 0) {
643
+ if (stored.row.state !== "settled" || stored.row.settledOutcome !== settlement.outcome || stored.finalization.settlementId !== request.settlementId || stored.finalization.recordId !== record.recordId) return [failure(ledgerError("finalizeSettlement", "Finalized identity disagrees with canonical settlement")), current];
644
+ return [success(Settlement.make({
645
+ submissionId: stored.row.submissionId,
646
+ settlementId: settlement.settlementId,
647
+ receiptId: stored.row.receiptId,
648
+ outcome: settlement.outcome,
649
+ ...settlementFailure === void 0 ? {} : { failure: settlementFailure },
650
+ settledAt: utc(stored.finalization.finalizedAtMillis)
651
+ })), current];
652
+ }
653
+ if (stored.row.state === "settled") return [failure(ledgerError("finalizeSettlement", "Finalized timestamp is missing")), current];
654
+ const terminal = stored.row.workerAdmissionJson === void 0 ? void 0 : workerTerminalFromRecord(toSnapshot(stored.row), record);
655
+ const latestId = current.latestByThread.get(stored.row.threadId);
656
+ const latest = latestId === void 0 ? void 0 : current.submissions.get(latestId);
657
+ const pendingNewer = terminal === "completed" && latest !== void 0 && latest.row.queueSequence > stored.row.queueSequence && !(latest.joinedHostSubmissionId === stored.row.submissionId && latest.inputApplied !== void 0);
658
+ let sealed = current;
659
+ if (terminal !== void 0 && !pendingNewer && !current.stoppedWorkers.has(stored.row.threadId)) {
660
+ const submissions = current.submissions;
661
+ if (!transferPageFits(stored.row.threadId)) return [failure(transferCapacityError("finalizeSettlement")), current];
662
+ for (const apply of [false, true]) for (const id of current.activeByThread.get(stored.row.threadId) ?? []) {
663
+ const other = submissions.get(id);
664
+ if (other === void 0) continue;
665
+ if (id !== stored.row.submissionId && !(other.joinedHostSubmissionId === stored.row.submissionId && other.inputApplied !== void 0) && other.abortIntent === void 0) {
666
+ const abortIntent = AbortIntent.make({
667
+ submissionId: id,
668
+ author: stored.row.principal,
669
+ reason: `Worker assignment ${terminal}`,
670
+ requestedAt: utc(nowMillis)
671
+ });
672
+ if (!apply && !abortFitsTransfer(other.row.threadId, abortIntent)) return [failure(transferCapacityError("finalizeSettlement")), current];
673
+ if (apply) withSubmission(current, {
674
+ ...other,
675
+ abortIntent
676
+ });
677
+ }
678
+ }
679
+ sealed = {
680
+ ...current,
681
+ submissions,
682
+ stoppedWorkers: current.stoppedWorkers.set(stored.row.threadId, terminal)
683
+ };
684
+ }
685
+ const next = withSubmission(sealed, {
686
+ ...stored,
687
+ row: {
688
+ ...stored.row,
689
+ state: "settled",
690
+ settledOutcome: settlement.outcome
691
+ },
692
+ finalization: {
693
+ settlementId: settlement.settlementId,
694
+ recordId: record.recordId,
695
+ finalizedAtMillis: nowMillis
696
+ }
697
+ });
698
+ return [success(Settlement.make({
699
+ submissionId: stored.row.submissionId,
700
+ settlementId: settlement.settlementId,
701
+ receiptId: stored.row.receiptId,
702
+ outcome: settlement.outcome,
703
+ ...settlementFailure === void 0 ? {} : { failure: settlementFailure },
704
+ settledAt: utc(nowMillis)
705
+ })), next];
706
+ });
707
+ if (decision._tag === "failure") return yield* decision.error;
708
+ if (before !== void 0) journal.owner.closeSubmission(before.row.threadId, request.submissionId);
709
+ return decision.value;
710
+ }));
711
+ const inspectWorker = Effect.fnUntraced(function* (threadId) {
712
+ const current = yield* Ref.get(state);
713
+ const latestId = current.latestByThread.get(threadId);
714
+ const latest = latestId === void 0 ? void 0 : current.submissions.get(latestId);
715
+ const active = [...current.activeByThread.get(threadId) ?? []].flatMap((id) => {
716
+ const row = current.submissions.get(id);
717
+ return row === void 0 ? [] : [row];
718
+ }).sort((a, b) => a.row.queueSequence - b.row.queueSequence)[0];
719
+ const terminal = current.stoppedWorkers.get(threadId);
720
+ return WorkerLedgerState.make({
721
+ latest: latest === void 0 ? null : toSnapshot(latest.row),
722
+ active: active === void 0 ? null : toSnapshot(active.row),
723
+ stopped: current.stoppedWorkers.has(threadId),
724
+ ...terminal === void 0 ? {} : { terminal }
725
+ });
726
+ });
727
+ const stopWorker = Effect.fnUntraced(function* (unvalidated) {
728
+ const request = yield* validate(WorkerStopCommand, "stopWorker", unvalidated);
729
+ const now = yield* Clock.currentTimeMillis;
730
+ const decision = yield* Ref.modify(state, (current) => {
731
+ const submissions = current.submissions;
732
+ let owned = 0;
733
+ if (!current.stoppedWorkers.has(request.threadId) && !transferPageFits(request.threadId)) return [failure(transferCapacityError("stopWorker")), current];
734
+ for (const apply of [false, true]) for (const id of current.activeByThread.get(request.threadId) ?? []) {
735
+ const stored = submissions.get(id);
736
+ if (stored === void 0) continue;
737
+ if (!apply && journal.owner.hasOwner(stored.row.threadId, stored.row.submissionId)) owned++;
738
+ if (stored.abortIntent === void 0) {
739
+ const abortIntent = AbortIntent.make({
740
+ submissionId: id,
741
+ author: request.author,
742
+ reason: "Worker owner stopped the worker",
743
+ requestedAt: utc(now)
744
+ });
745
+ if (!apply && !abortFitsTransfer(stored.row.threadId, abortIntent)) return [failure(transferCapacityError("stopWorker")), current];
746
+ if (apply) withSubmission(current, {
747
+ ...stored,
748
+ abortIntent
749
+ });
750
+ }
751
+ }
752
+ return [success(owned), {
753
+ ...current,
754
+ submissions,
755
+ stoppedWorkers: current.stoppedWorkers.has(request.threadId) ? current.stoppedWorkers : current.stoppedWorkers.set(request.threadId, void 0)
756
+ }];
757
+ });
758
+ if (decision._tag === "failure") return yield* decision.error;
759
+ return decision.value;
760
+ });
761
+ const requestAbort = Effect.fnUntraced(function* (unvalidated) {
762
+ const request = yield* validate(AbortCommand, "requestAbort", unvalidated);
763
+ const nowMillis = yield* Clock.currentTimeMillis;
764
+ const decision = yield* Ref.modify(state, (current) => {
765
+ const stored = current.submissions.get(request.submissionId);
766
+ if (stored === void 0) return [failure(ledgerError("requestAbort", `Unknown Submission ${request.submissionId}`)), current];
767
+ if (stored.row.state === "joined") {
768
+ if (stored.joinedHostSubmissionId === void 0) return [failure(ledgerError("requestAbort", `Joined Submission ${request.submissionId} is missing its host linkage`)), current];
769
+ return [failure(JoinedToHost.make({
770
+ submissionId: request.submissionId,
771
+ hostSubmissionId: stored.joinedHostSubmissionId
772
+ })), current];
773
+ }
774
+ if (stored.row.state === "settled") {
775
+ if (stored.row.settledOutcome === void 0) return [failure(ledgerError("requestAbort", `Settled Submission ${request.submissionId} is missing its outcome`)), current];
776
+ return [failure(SettlementConflict.make({
777
+ submissionId: request.submissionId,
778
+ existingOutcome: stored.row.settledOutcome
779
+ })), current];
780
+ }
781
+ if (stored.abortIntent !== void 0) return [success(stored.abortIntent), current];
782
+ const intent = AbortIntent.make({
783
+ submissionId: request.submissionId,
784
+ author: request.author,
785
+ reason: request.reason,
786
+ requestedAt: utc(nowMillis)
787
+ });
788
+ if (!abortFitsTransfer(stored.row.threadId, intent)) return [failure(transferCapacityError("requestAbort")), current];
789
+ return [success(intent), withSubmission(current, {
790
+ ...stored,
791
+ abortIntent: intent
792
+ })];
793
+ });
794
+ if (decision._tag === "failure") return yield* decision.error;
795
+ return decision.value;
796
+ });
797
+ const claimJoining = Effect.fnUntraced(function* (unvalidated) {
798
+ const request = yield* validate(ClaimJoiningRequest, "claimJoining", unvalidated);
799
+ const published = /* @__PURE__ */ new Map();
800
+ const before = yield* Ref.get(state);
801
+ for (const id of before.activeByThread.get(request.threadId) ?? []) {
802
+ const stored = before.submissions.get(id);
803
+ if (stored === void 0 || stored.row.state !== "ready") continue;
804
+ const canonical = yield* canonicalSettlement(stored.row);
805
+ if (canonical !== void 0) published.set(stored.row.submissionId, canonical.settlement.outcome);
806
+ }
807
+ const decision = yield* Ref.modify(state, (current) => {
808
+ if (current.stoppedWorkers.has(request.threadId)) return [success([]), current];
809
+ const host = current.submissions.get(request.hostSubmissionId);
810
+ if (host === void 0) return [failure(ledgerError("claimJoining", `Unknown Submission ${request.hostSubmissionId}`)), current];
811
+ if (host.row.threadId !== request.threadId) return [failure(ledgerError("claimJoining", `Host Submission ${request.hostSubmissionId} does not belong to Thread ${request.threadId}`)), current];
812
+ if (!journal.owner.hasOwner(host.row.threadId, host.row.submissionId)) return [failure(ownershipLost(host)), current];
813
+ const later = threadRows(current, request.threadId, host.row.queueSequence);
814
+ const claims = [];
815
+ const submissions = current.submissions;
816
+ for (const stored of later) {
817
+ if (claims.length >= request.maxCount) break;
818
+ if ((stored.row.state === "joining" || stored.row.state === "joined") && stored.joinedHostSubmissionId === request.hostSubmissionId) continue;
819
+ if (stored.row.state === "settled" && stored.row.settledOutcome === "aborted") continue;
820
+ if (stored.row.state !== "ready") break;
821
+ const terminal = published.get(stored.row.submissionId);
822
+ if (terminal === "aborted") continue;
823
+ if (terminal !== void 0) break;
824
+ withSubmission(current, {
825
+ ...stored,
826
+ row: {
827
+ ...stored.row,
828
+ state: "joining"
829
+ },
830
+ joinedHostSubmissionId: request.hostSubmissionId
831
+ });
832
+ claims.push(JoiningClaim.make({
833
+ submissionId: stored.row.submissionId,
834
+ queueSequence: stored.row.queueSequence,
835
+ inputPayload: stored.row.inputPayload
836
+ }));
837
+ }
838
+ return [success(claims), {
839
+ ...current,
840
+ submissions
841
+ }];
842
+ });
843
+ if (decision._tag === "failure") return yield* decision.error;
844
+ return decision.value;
845
+ });
846
+ const markJoined = Effect.fnUntraced(function* (unvalidated) {
847
+ const request = yield* validate(MarkJoinedRequest, "markJoined", unvalidated);
848
+ const decision = yield* Ref.modify(state, (current) => {
849
+ const stored = current.submissions.get(request.submissionId);
850
+ if (stored === void 0) return [failure(ledgerError("markJoined", `Unknown Submission ${request.submissionId}`)), current];
851
+ if (stored.joinedHostSubmissionId === void 0) return [failure(ledgerError("markJoined", `Submission ${request.submissionId} was never claimed for joining`)), current];
852
+ const host = current.submissions.get(stored.joinedHostSubmissionId);
853
+ if (host === void 0) return [failure(ledgerError("markJoined", `Host Submission ${stored.joinedHostSubmissionId} is missing`)), current];
854
+ if (!journal.owner.hasOwner(host.row.threadId, host.row.submissionId)) return [failure(ownershipLost(host)), current];
855
+ if (stored.inputApplied !== void 0) {
856
+ if (stored.inputApplied.recordId === request.recordId && stored.inputApplied.sequence === request.sequence) return [success(void 0), current];
857
+ return [failure(ledgerError("markJoined", `A different join marker is already recorded for Submission ${request.submissionId}`)), current];
858
+ }
859
+ if (stored.row.state !== "joining" && stored.row.state !== "joined") return [failure(ledgerError("markJoined", `Cannot mark Submission ${request.submissionId} joined from state ${stored.row.state}`)), current];
860
+ const marker = InputAppliedMarker.make({
861
+ recordId: request.recordId,
862
+ sequence: request.sequence
863
+ });
864
+ return [success(void 0), withSubmission(current, {
865
+ ...stored,
866
+ row: {
867
+ ...stored.row,
868
+ state: "joined"
869
+ },
870
+ inputApplied: marker
871
+ })];
872
+ });
873
+ if (decision._tag === "failure") return yield* decision.error;
874
+ });
875
+ const revertJoining = Effect.fnUntraced(function* (unvalidated) {
876
+ const request = yield* validate(RevertJoiningRequest, "revertJoining", unvalidated);
877
+ const decision = yield* Ref.modify(state, (current) => {
878
+ const stored = current.submissions.get(request.submissionId);
879
+ if (stored === void 0) return [failure(ledgerError("revertJoining", `Unknown Submission ${request.submissionId}`)), current];
880
+ if (stored.row.state !== "joining") return [success(void 0), current];
881
+ const guard = request.guard;
882
+ if (guard !== void 0) {
883
+ if (stored.joinedHostSubmissionId !== guard.hostSubmissionId) return [success(void 0), current];
884
+ const host = current.submissions.get(guard.hostSubmissionId);
885
+ if (host === void 0 || host.row.threadId !== stored.row.threadId) return [failure(ledgerError("revertJoining", `Host Submission ${guard.hostSubmissionId} is missing or belongs to another Thread`)), current];
886
+ if (host.row.state !== "settled" && !journal.owner.hasOwner(host.row.threadId, host.row.submissionId)) return [failure(ledgerError("revertJoining", "The linked host has no active local session")), current];
887
+ }
888
+ return [success(void 0), withSubmission(current, {
889
+ ...stored,
890
+ row: {
891
+ ...stored.row,
892
+ state: "ready"
893
+ },
894
+ joinedHostSubmissionId: void 0
895
+ })];
896
+ });
897
+ if (decision._tag === "failure") return yield* decision.error;
898
+ });
899
+ const suspend = Effect.fnUntraced(function* (unvalidated) {
900
+ const request = yield* validate(SuspendRequest, "suspend", unvalidated);
901
+ const nowMillis = yield* Clock.currentTimeMillis;
902
+ const target = (yield* Ref.get(state)).submissions.get(request.submissionId);
903
+ const canonical = target === void 0 ? void 0 : yield* canonicalSettlement(target.row);
904
+ const announcedChildren = /* @__PURE__ */ new Set();
905
+ if (request.reason._tag === "WaitingForChild") {
906
+ const current = yield* Ref.get(state);
907
+ for (const { childSubmissionId } of request.reason.children) {
908
+ const child = current.submissions.get(childSubmissionId);
909
+ if (child !== void 0 && (yield* canonicalSettlement(child.row)) !== void 0) announcedChildren.add(childSubmissionId);
910
+ }
911
+ }
912
+ const decision = yield* Ref.modify(state, (current) => {
913
+ const stored = current.submissions.get(request.submissionId);
914
+ if (stored === void 0) return [failure(ledgerError("suspend", `Unknown Submission ${request.submissionId}`)), current];
915
+ if (stored.row.state === "settled") {
916
+ if (stored.row.settledOutcome === void 0) return [failure(ledgerError("suspend", `Settled Submission ${request.submissionId} is missing its outcome`)), current];
917
+ return [failure(SettlementConflict.make({
918
+ submissionId: request.submissionId,
919
+ existingOutcome: stored.row.settledOutcome
920
+ })), current];
921
+ }
922
+ if (canonical !== void 0) return [failure(SettlementConflict.make({
923
+ submissionId: request.submissionId,
924
+ existingOutcome: canonical.settlement.outcome
925
+ })), current];
926
+ if (!journal.owner.hasOwner(stored.row.threadId, stored.row.submissionId)) return [failure(ownershipLost(stored)), current];
927
+ if (request.reason._tag === "ApprovalPending" ? approvalDecisionsCover(request.reason.toolCallIds, (toolCallId) => stored.approvalDecisions.get(toolCallId)?.decision) : request.reason.children.every((child) => announcedChildren.has(child.childSubmissionId))) return [success("resume-immediately"), current];
928
+ return [success("suspended"), withSubmission(current, {
929
+ ...stored,
930
+ row: {
931
+ ...stored.row,
932
+ state: "suspended"
933
+ },
934
+ suspension: {
935
+ reason: request.reason,
936
+ suspendedAtMillis: nowMillis
937
+ }
938
+ })];
939
+ });
940
+ if (decision._tag === "failure") return yield* decision.error;
941
+ if (decision.value === "suspended" && target !== void 0) journal.owner.closeSubmission(target.row.threadId, request.submissionId);
942
+ return decision.value;
943
+ });
944
+ const recordApprovalDecision = Effect.fnUntraced(function* (unvalidated) {
945
+ const command = yield* validate(ApprovalDecisionCommand, "recordApprovalDecision", unvalidated);
946
+ const nowMillis = yield* Clock.currentTimeMillis;
947
+ const decision = yield* Ref.modify(state, (current) => {
948
+ const stored = current.submissions.get(command.submissionId);
949
+ if (stored === void 0) return [failure(ledgerError("recordApprovalDecision", `Unknown Submission ${command.submissionId}`)), current];
950
+ if (stored.row.state === "settled") {
951
+ if (stored.row.settledOutcome === void 0) return [failure(ledgerError("recordApprovalDecision", `Settled Submission ${command.submissionId} is missing its outcome`)), current];
952
+ return [failure(SettlementConflict.make({
953
+ submissionId: command.submissionId,
954
+ existingOutcome: stored.row.settledOutcome
955
+ })), current];
956
+ }
957
+ const existing = stored.approvalDecisions.get(command.toolCallId);
958
+ if (existing !== void 0) {
959
+ if (existing.decision !== command.decision) return [failure(ApprovalConflict.make({
960
+ submissionId: command.submissionId,
961
+ toolCallId: command.toolCallId,
962
+ existingDecision: existing.decision
963
+ })), current];
964
+ return [success(existing), current];
965
+ }
966
+ const intent = ApprovalDecisionIntent.make({
967
+ submissionId: command.submissionId,
968
+ toolCallId: command.toolCallId,
969
+ decision: command.decision,
970
+ resolver: command.resolver,
971
+ reason: command.reason,
972
+ decidedAt: utc(nowMillis)
973
+ });
974
+ if (!approvalFitsTransfer(stored.row.threadId, intent)) return [failure(transferCapacityError("recordApprovalDecision")), current];
975
+ const approvalDecisions = new Map(stored.approvalDecisions).set(command.toolCallId, intent);
976
+ const wakes = stored.row.state === "suspended" && stored.suspension !== void 0 && stored.suspension.reason._tag === "ApprovalPending" && approvalDecisionsCover(stored.suspension.reason.toolCallIds, (toolCallId) => approvalDecisions.get(toolCallId)?.decision);
977
+ return [success(intent), withSubmission(current, {
978
+ ...stored,
979
+ row: wakes ? {
980
+ ...stored.row,
981
+ state: "input-applied"
982
+ } : stored.row,
983
+ suspension: wakes ? void 0 : stored.suspension,
984
+ approvalDecisions
985
+ })];
986
+ });
987
+ if (decision._tag === "failure") return yield* decision.error;
988
+ return decision.value;
989
+ });
990
+ const markUnknown = Effect.fnUntraced(function* (unvalidated) {
991
+ const request = yield* validate(MarkUnknownRequest, "markUnknown", unvalidated);
992
+ const target = (yield* Ref.get(state)).submissions.get(request.submissionId);
993
+ const canonical = target === void 0 ? void 0 : yield* canonicalSettlement(target.row);
994
+ const decision = yield* Ref.modify(state, (current) => {
995
+ const stored = current.submissions.get(request.submissionId);
996
+ if (stored === void 0) return [failure(ledgerError("markUnknown", `Unknown Submission ${request.submissionId}`)), current];
997
+ if (stored.row.state === "settled") {
998
+ if (stored.row.settledOutcome === void 0) return [failure(ledgerError("markUnknown", `Settled Submission ${request.submissionId} is missing its outcome`)), current];
999
+ return [failure(SettlementConflict.make({
1000
+ submissionId: request.submissionId,
1001
+ existingOutcome: stored.row.settledOutcome
1002
+ })), current];
1003
+ }
1004
+ if (canonical !== void 0) return [failure(SettlementConflict.make({
1005
+ submissionId: request.submissionId,
1006
+ existingOutcome: canonical.settlement.outcome
1007
+ })), current];
1008
+ const existing = stored.unknownMark;
1009
+ const known = new Set(existing?.toolCallIds ?? []);
1010
+ const merged = [...existing?.toolCallIds ?? [], ...request.toolCallIds.filter((toolCallId) => !known.has(toolCallId))];
1011
+ return [success(void 0), withSubmission(current, {
1012
+ ...stored,
1013
+ row: stored.row.state === "unknown" ? stored.row : {
1014
+ ...stored.row,
1015
+ state: "unknown"
1016
+ },
1017
+ unknownMark: {
1018
+ reason: existing?.reason ?? request.reason,
1019
+ toolCallIds: merged
1020
+ }
1021
+ })];
1022
+ });
1023
+ if (decision._tag === "failure") return yield* decision.error;
1024
+ });
1025
+ const recordUnknownResolution = Effect.fnUntraced(function* (unvalidated) {
1026
+ const command = yield* validate(UnknownResolutionCommand, "recordUnknownResolution", unvalidated);
1027
+ const nowMillis = yield* Clock.currentTimeMillis;
1028
+ const before = (yield* Ref.get(state)).submissions.get(command.submissionId);
1029
+ const kind = unknownResolutionKind(command.resolution);
1030
+ if (before !== void 0 && kind === "factual" && !before.unknownResolutions.has(JSON.stringify([command.toolCallId, kind]))) {
1031
+ const runId = runIdForSubmission(before.row.submissionId);
1032
+ const outcomes = yield* journal.toolCallResults(before.row.threadId, runId, command.toolCallId);
1033
+ const result = outcomes[0]?.payload;
1034
+ if (outcomes.length > 1 || result !== void 0 && (result._tag !== "ToolCallSettled" || result.runId !== runId || result.toolCallId !== command.toolCallId)) return yield* ledgerError("recordUnknownResolution", "Canonical Tool result identity is inconsistent");
1035
+ if (result?._tag === "ToolCallSettled" && !unknownResolutionMatchesResult(command.resolution, result)) return yield* UnknownResolutionConflict.make({
1036
+ submissionId: command.submissionId,
1037
+ toolCallId: command.toolCallId
1038
+ });
1039
+ }
1040
+ const decision = yield* Ref.modify(state, (current) => {
1041
+ const stored = current.submissions.get(command.submissionId);
1042
+ if (stored === void 0) return [failure(ledgerError("recordUnknownResolution", `Unknown Submission ${command.submissionId}`)), current];
1043
+ if (stored.row.state === "settled") {
1044
+ if (stored.row.settledOutcome === void 0) return [failure(ledgerError("recordUnknownResolution", `Settled Submission ${command.submissionId} is missing its outcome`)), current];
1045
+ if (command.resolution._tag !== "CompletedWithResult" && command.resolution._tag !== "NeverHappened") return [failure(SettlementConflict.make({
1046
+ submissionId: command.submissionId,
1047
+ existingOutcome: stored.row.settledOutcome
1048
+ })), current];
1049
+ }
1050
+ const key = JSON.stringify([command.toolCallId, kind]);
1051
+ const existing = stored.unknownResolutions.get(key);
1052
+ if (existing !== void 0 && !equivalentUnknownResolution(existing.intent.resolution, command.resolution) || existing === void 0 && kind === "execution" && stored.unknownResolutions.has(JSON.stringify([command.toolCallId, "factual"]))) return [failure(UnknownResolutionConflict.make({
1053
+ submissionId: command.submissionId,
1054
+ toolCallId: command.toolCallId
1055
+ })), current];
1056
+ const intent = existing?.intent ?? UnknownResolutionIntent.make({
1057
+ submissionId: command.submissionId,
1058
+ toolCallId: command.toolCallId,
1059
+ author: command.author,
1060
+ reason: command.reason,
1061
+ resolution: command.resolution,
1062
+ resolvedAt: utc(nowMillis)
1063
+ });
1064
+ if (existing === void 0 && !resolutionFitsTransfer(stored.row.threadId, intent)) return [failure(transferCapacityError("recordUnknownResolution")), current];
1065
+ const unknownResolutions = existing !== void 0 ? stored.unknownResolutions : new Map(stored.unknownResolutions).set(key, { intent });
1066
+ const wakes = stored.row.state === "unknown" && stored.unknownMark !== void 0 && stored.unknownMark.toolCallIds.every((toolCallId) => unknownResolutions.has(JSON.stringify([toolCallId, "execution"])) || unknownResolutions.has(JSON.stringify([toolCallId, "factual"])));
1067
+ return [success(intent), withSubmission(current, {
1068
+ ...stored,
1069
+ row: wakes ? {
1070
+ ...stored.row,
1071
+ state: "input-applied"
1072
+ } : stored.row,
1073
+ unknownMark: wakes ? void 0 : stored.unknownMark,
1074
+ unknownResolutions
1075
+ })];
1076
+ });
1077
+ if (decision._tag === "failure") return yield* decision.error;
1078
+ return decision.value;
1079
+ });
1080
+ const recordChildSettled = Effect.fnUntraced(function* (unvalidated) {
1081
+ const request = yield* validate(ChildSettledNotification, "recordChildSettled", unvalidated);
1082
+ const before = yield* Ref.get(state);
1083
+ const waiting = before.submissions.get(request.parentSubmissionId)?.suspension?.reason;
1084
+ const ids = /* @__PURE__ */ new Set([request.childSubmissionId, ...waiting?._tag === "WaitingForChild" ? waiting.children.map((child) => child.childSubmissionId) : []]);
1085
+ const announcedChildren = /* @__PURE__ */ new Set();
1086
+ for (const id of ids) {
1087
+ const child = before.submissions.get(id);
1088
+ if (child !== void 0 && (yield* canonicalSettlement(child.row)) !== void 0) announcedChildren.add(id);
1089
+ }
1090
+ const decision = yield* Ref.modify(state, (current) => {
1091
+ const parent = current.submissions.get(request.parentSubmissionId);
1092
+ if (parent === void 0) return [failure(ledgerError("recordChildSettled", `Unknown Submission ${request.parentSubmissionId}`)), current];
1093
+ if (!announcedChildren.has(request.childSubmissionId)) return [failure(ledgerError("recordChildSettled", `Child Submission ${request.childSubmissionId} has no recorded settlement`)), current];
1094
+ if (parent.row.state !== "suspended" || parent.suspension === void 0 || parent.suspension.reason._tag !== "WaitingForChild") return [success("not-waiting"), current];
1095
+ const children = parent.suspension.reason.children;
1096
+ if (!children.some((entry) => entry.childSubmissionId === request.childSubmissionId)) return [success("not-waiting"), current];
1097
+ if (!children.every((entry) => announcedChildren.has(entry.childSubmissionId))) return [success("still-waiting"), current];
1098
+ return [success("woken"), withSubmission(current, {
1099
+ ...parent,
1100
+ row: {
1101
+ ...parent.row,
1102
+ state: "input-applied"
1103
+ },
1104
+ suspension: void 0
1105
+ })];
1106
+ });
1107
+ if (decision._tag === "failure") return yield* decision.error;
1108
+ return decision.value;
1109
+ });
1110
+ const reserveChildBudget = Effect.fnUntraced(function* (unvalidated) {
1111
+ const request = yield* validate(ChildBudgetReservationRequest, "reserveChildBudget", unvalidated);
1112
+ const nowMillis = yield* Clock.currentTimeMillis;
1113
+ const decision = yield* Ref.modify(state, (current) => {
1114
+ const existing = current.childReservations.get(request.reservationId);
1115
+ if (existing !== void 0) {
1116
+ if (!(existing.parentSubmissionId === request.parentSubmissionId && existing.parentToolCallId === request.parentToolCallId && existing.allocationDigest === request.allocationDigest && equivalentPersistedJson(existing.allocation, request.allocation))) return [failure(ChildReservationConflict.make({
1117
+ reservationId: request.reservationId,
1118
+ status: existing.status,
1119
+ message: "A reservation with this identity exists with a different parent Tool Call or allocation."
1120
+ })), current];
1121
+ return [success(ReservedChildBudget.make({
1122
+ reservation: toReservationSnapshot(existing),
1123
+ replayed: true
1124
+ })), current];
1125
+ }
1126
+ for (const id of current.childrenByParent.get(request.parentSubmissionId) ?? []) {
1127
+ const reservation = current.childReservations.get(id);
1128
+ if (reservation === void 0) continue;
1129
+ if (reservation.parentSubmissionId === request.parentSubmissionId && reservation.parentToolCallId === request.parentToolCallId) return [failure(ChildReservationConflict.make({
1130
+ reservationId: request.reservationId,
1131
+ status: reservation.status,
1132
+ message: `Parent Tool Call ${request.parentToolCallId} already owns reservation ${reservation.reservationId}.`
1133
+ })), current];
1134
+ }
1135
+ const parent = current.submissions.get(request.parentSubmissionId);
1136
+ if (parent === void 0) return [failure(ledgerError("reserveChildBudget", `Unknown Submission ${request.parentSubmissionId}`)), current];
1137
+ if (!journal.owner.hasOwner(parent.row.threadId, parent.row.submissionId)) return [failure(ownershipLost(parent)), current];
1138
+ const reservation = {
1139
+ reservationId: request.reservationId,
1140
+ parentSubmissionId: request.parentSubmissionId,
1141
+ parentToolCallId: request.parentToolCallId,
1142
+ childSubmissionId: void 0,
1143
+ status: "reserved",
1144
+ allocation: request.allocation,
1145
+ allocationDigest: request.allocationDigest,
1146
+ accounting: void 0,
1147
+ reservedAtMillis: nowMillis,
1148
+ releaseBeganAtMillis: void 0,
1149
+ releasedAtMillis: void 0
1150
+ };
1151
+ return [success(ReservedChildBudget.make({
1152
+ reservation: toReservationSnapshot(reservation),
1153
+ replayed: false
1154
+ })), withChildReservation(current, reservation)];
1155
+ });
1156
+ if (decision._tag === "failure") return yield* decision.error;
1157
+ return decision.value;
1158
+ });
1159
+ const attachChildToReservation = Effect.fnUntraced(function* (unvalidated) {
1160
+ const request = yield* validate(AttachChildToReservationRequest, "attachChildToReservation", unvalidated);
1161
+ const decision = yield* Ref.modify(state, (current) => {
1162
+ const reservation = current.childReservations.get(request.reservationId);
1163
+ if (reservation === void 0) return [failure(ledgerError("attachChildToReservation", `Unknown child reservation ${request.reservationId}`)), current];
1164
+ if (reservation.childSubmissionId !== void 0) {
1165
+ if (reservation.childSubmissionId === request.childSubmissionId) return [success(toReservationSnapshot(reservation)), current];
1166
+ return [failure(ChildReservationConflict.make({
1167
+ reservationId: request.reservationId,
1168
+ status: reservation.status,
1169
+ message: `Reservation ${request.reservationId} already records child ${reservation.childSubmissionId}.`
1170
+ })), current];
1171
+ }
1172
+ const parent = current.submissions.get(reservation.parentSubmissionId);
1173
+ if (parent === void 0) return [failure(ledgerError("attachChildToReservation", `Unknown Submission ${reservation.parentSubmissionId}`)), current];
1174
+ if (!journal.owner.hasOwner(parent.row.threadId, parent.row.submissionId)) return [failure(ownershipLost(parent)), current];
1175
+ if (reservation.status !== "reserved") return [failure(ChildReservationConflict.make({
1176
+ reservationId: request.reservationId,
1177
+ status: reservation.status,
1178
+ message: `Cannot attach a child to a ${reservation.status} reservation.`
1179
+ })), current];
1180
+ if (!current.submissions.has(request.childSubmissionId)) return [failure(ledgerError("attachChildToReservation", `Unknown child Submission ${request.childSubmissionId}`)), current];
1181
+ const attached = {
1182
+ ...reservation,
1183
+ childSubmissionId: request.childSubmissionId
1184
+ };
1185
+ return [success(toReservationSnapshot(attached)), withChildReservation(current, attached)];
1186
+ });
1187
+ if (decision._tag === "failure") return yield* decision.error;
1188
+ return decision.value;
1189
+ });
1190
+ const beginChildBudgetRelease = Effect.fnUntraced(function* (unvalidated) {
1191
+ const request = yield* validate(BeginChildBudgetReleaseRequest, "beginChildBudgetRelease", unvalidated);
1192
+ const nowMillis = yield* Clock.currentTimeMillis;
1193
+ const decision = yield* Ref.modify(state, (current) => {
1194
+ const reservation = current.childReservations.get(request.reservationId);
1195
+ if (reservation === void 0) return [failure(ledgerError("beginChildBudgetRelease", `Unknown child reservation ${request.reservationId}`)), current];
1196
+ if (reservation.status !== "reserved") {
1197
+ if (reservation.accounting !== void 0 && equivalentPersistedJson(reservation.accounting, request.accounting)) return [success(toReservationSnapshot(reservation)), current];
1198
+ return [failure(ChildReservationConflict.make({
1199
+ reservationId: request.reservationId,
1200
+ status: reservation.status,
1201
+ message: "A different accounting decision is already frozen for this reservation."
1202
+ })), current];
1203
+ }
1204
+ const frozen = {
1205
+ ...reservation,
1206
+ status: "releasePending",
1207
+ accounting: request.accounting,
1208
+ releaseBeganAtMillis: nowMillis
1209
+ };
1210
+ return [success(toReservationSnapshot(frozen)), withChildReservation(current, frozen)];
1211
+ });
1212
+ if (decision._tag === "failure") return yield* decision.error;
1213
+ return decision.value;
1214
+ });
1215
+ const releaseChildBudget = Effect.fnUntraced(function* (unvalidated) {
1216
+ const request = yield* validate(ReleaseChildBudgetRequest, "releaseChildBudget", unvalidated);
1217
+ const nowMillis = yield* Clock.currentTimeMillis;
1218
+ const decision = yield* Ref.modify(state, (current) => {
1219
+ const reservation = current.childReservations.get(request.reservationId);
1220
+ if (reservation === void 0) return [failure(ledgerError("releaseChildBudget", `Unknown child reservation ${request.reservationId}`)), current];
1221
+ if (reservation.status === "released") return [success(toReservationSnapshot(reservation)), current];
1222
+ if (reservation.status !== "releasePending") return [failure(ChildReservationConflict.make({
1223
+ reservationId: request.reservationId,
1224
+ status: reservation.status,
1225
+ message: "Cannot release a reservation whose accounting decision is not frozen."
1226
+ })), current];
1227
+ const released = {
1228
+ ...reservation,
1229
+ status: "released",
1230
+ releasedAtMillis: nowMillis
1231
+ };
1232
+ return [success(toReservationSnapshot(released)), withChildReservation(current, released)];
1233
+ });
1234
+ if (decision._tag === "failure") return yield* decision.error;
1235
+ return decision.value;
1236
+ });
1237
+ const scanNonterminal = Stream.paginate(void 0, (after) => Effect.sync(() => {
1238
+ const current = MutableRef.get(state.ref);
1239
+ const candidates = boundedWorkSelection(8, (stored) => `${stored.row.threadId}\u0000${String(stored.row.queueSequence).padStart(16, "0")}`, after);
1240
+ for (const ids of current.activeByThread.values()) for (const id of ids) {
1241
+ const stored = current.submissions.get(id);
1242
+ if (stored !== void 0) candidates.add(stored);
1243
+ }
1244
+ const items = candidates.values.map(({ row }) => SubmissionWorkItem.make(row));
1245
+ const last = candidates.values.at(-1)?.row;
1246
+ return [items, last === void 0 ? Option.none() : Option.some(`${last.threadId}\u0000${String(last.queueSequence).padStart(16, "0")}`)];
1247
+ }));
1248
+ const readAbortIntent = Effect.fnUntraced(function* (unvalidated) {
1249
+ const request = yield* validate(AbortIntentRequest, "readAbortIntent", unvalidated);
1250
+ const stored = (yield* Ref.get(state)).submissions.get(request.submissionId);
1251
+ if (stored === void 0) return yield* ledgerError("readAbortIntent", `Unknown Submission ${request.submissionId}`);
1252
+ return stored.abortIntent;
1253
+ });
1254
+ const loadRecoverySnapshot = Effect.fnUntraced(function* (unvalidated) {
1255
+ const request = yield* validate(RecoverySnapshotRequest, "loadRecoverySnapshot", unvalidated);
1256
+ const current = yield* Ref.get(state);
1257
+ const stored = current.submissions.get(request.submissionId);
1258
+ if (stored === void 0) return yield* ledgerError("loadRecoverySnapshot", `Unknown Submission ${request.submissionId}`);
1259
+ const joins = Array.from(current.joinsByHost.get(request.submissionId) ?? [], (id) => current.submissions.get(id)).filter((candidate) => candidate !== void 0).sort((left, right) => left.row.queueSequence - right.row.queueSequence).map((candidate) => JoinSnapshot.make({
1260
+ submissionId: candidate.row.submissionId,
1261
+ state: candidate.row.state,
1262
+ hostSubmissionId: request.submissionId
1263
+ }));
1264
+ const byToolCallId = (left, right) => left.toolCallId < right.toolCallId ? -1 : left.toolCallId > right.toolCallId ? 1 : 0;
1265
+ const childReservations = Array.from(current.childrenByParent.get(request.submissionId) ?? [], (id) => current.childReservations.get(id)).filter((reservation) => reservation !== void 0).sort((left, right) => left.parentToolCallId < right.parentToolCallId ? -1 : left.parentToolCallId > right.parentToolCallId ? 1 : 0);
1266
+ const childAttachments = [];
1267
+ for (const reservation of childReservations) {
1268
+ if (reservation.childSubmissionId === void 0) continue;
1269
+ const child = current.submissions.get(reservation.childSubmissionId);
1270
+ if (child === void 0) continue;
1271
+ childAttachments.push(ChildAttachmentSnapshot.make({
1272
+ toolCallId: reservation.parentToolCallId,
1273
+ childSubmissionId: reservation.childSubmissionId,
1274
+ childState: child.row.state,
1275
+ ...child.row.settledOutcome === void 0 ? {} : { childOutcome: child.row.settledOutcome }
1276
+ }));
1277
+ }
1278
+ return RecoverySnapshot.make({
1279
+ submission: toSnapshot(stored.row),
1280
+ joins,
1281
+ approvalDecisions: [...stored.approvalDecisions.values()].sort(byToolCallId),
1282
+ unknownResolutions: [...stored.unknownResolutions.values()].map((resolution) => resolution.intent).sort(byToolCallId),
1283
+ childReservations: childReservations.map(toReservationSnapshot),
1284
+ childAttachments,
1285
+ ...stored.row.parentLinkage === void 0 ? {} : { parentLinkage: stored.row.parentLinkage },
1286
+ ...stored.joinedHostSubmissionId === void 0 ? {} : { hostSubmissionId: stored.joinedHostSubmissionId },
1287
+ ...stored.suspension === void 0 ? {} : { suspension: SuspensionSnapshot.make({
1288
+ reason: stored.suspension.reason,
1289
+ suspendedAt: utc(stored.suspension.suspendedAtMillis)
1290
+ }) },
1291
+ hasOwner: journal.owner.hasOwner(stored.row.threadId, stored.row.submissionId),
1292
+ ...stored.inputApplied === void 0 ? {} : { inputApplied: stored.inputApplied },
1293
+ ...stored.abortIntent === void 0 ? {} : { abortIntent: stored.abortIntent }
1294
+ });
1295
+ });
1296
+ const ledger = SubmissionLedger.of({
1297
+ capabilities,
1298
+ resolveFundingOwner: Effect.fnUntraced(function* (unvalidated) {
1299
+ const request = yield* validate(FundingOwnerRequest, "funding owner", unvalidated);
1300
+ const current = MutableRef.get(state.ref);
1301
+ const selected = current.submissions.get(request.submissionId);
1302
+ if (selected === void 0 || selected.row.threadId !== request.threadId) return yield* ledgerError("funding owner", "Selected admission belongs to another Thread or is missing");
1303
+ if (selected.row.state === "joining" || selected.joinedHostSubmissionId !== void 0 && selected.inputApplied === void 0) return yield* ledgerError("funding owner", "Joining funding owner is not yet frozen by exact applied input evidence");
1304
+ const owner = selected.joinedHostSubmissionId === void 0 ? selected : current.submissions.get(selected.joinedHostSubmissionId);
1305
+ if (owner === void 0 || owner.row.threadId !== request.threadId || owner !== selected && owner.row.queueSequence >= selected.row.queueSequence) return yield* ledgerError("funding owner", "Exact joined funding owner is missing or inconsistent");
1306
+ return FundingOwner.make({
1307
+ selected: toSnapshot(selected.row),
1308
+ owner: toSnapshot(owner.row)
1309
+ });
1310
+ }),
1311
+ admit: (request) => journal.withMutation(admit(request)),
1312
+ markReady: (request) => journal.withMutation(markReady(request)),
1313
+ lookup,
1314
+ resolveAdmission,
1315
+ selectHead: (request) => journal.withMutation(selectHead(request)),
1316
+ markInputApplied: (request) => journal.withMutation(markInputApplied(request)),
1317
+ finalizeSettlement: (request) => journal.withMutation(finalizeSettlement(request)),
1318
+ requestAbort: (request) => journal.withMutation(requestAbort(request)),
1319
+ stopWorker: (request) => journal.withMutation(stopWorker(request)),
1320
+ inspectWorker,
1321
+ claimJoining: (request) => journal.withMutation(claimJoining(request)),
1322
+ markJoined: (request) => journal.withMutation(markJoined(request)),
1323
+ revertJoining: (request) => journal.withMutation(revertJoining(request)),
1324
+ suspend: (request) => journal.withMutation(suspend(request)),
1325
+ recordApprovalDecision: (request) => journal.withMutation(recordApprovalDecision(request)),
1326
+ markUnknown: (request) => journal.withMutation(markUnknown(request)),
1327
+ recordUnknownResolution: (request) => journal.withMutation(recordUnknownResolution(request)),
1328
+ recordChildSettled: (request) => journal.withMutation(recordChildSettled(request)),
1329
+ reserveChildBudget: (request) => journal.withMutation(reserveChildBudget(request)),
1330
+ attachChildToReservation: (request) => journal.withMutation(attachChildToReservation(request)),
1331
+ beginChildBudgetRelease: (request) => journal.withMutation(beginChildBudgetRelease(request)),
1332
+ releaseChildBudget: (request) => journal.withMutation(releaseChildBudget(request)),
1333
+ scanNonterminal,
1334
+ loadRecoverySnapshot,
1335
+ readAbortIntent
1336
+ });
1337
+ const toAdmission = (row, settledAtMillis) => ThreadAdmission.make({
1338
+ ...toSnapshot(row),
1339
+ ...settledAtMillis === void 0 ? {} : { settledAt: utc(settledAtMillis) }
1340
+ });
1341
+ const cleanCommand = (value) => {
1342
+ const { canonicalRecordId: _, ...fact } = value;
1343
+ return fact;
1344
+ };
1345
+ const commands = (stored) => {
1346
+ return {
1347
+ aborts: stored?.abortIntent === void 0 ? [] : [cleanCommand(stored.abortIntent)],
1348
+ approvals: Array.from(stored?.approvalDecisions.values() ?? [], cleanCommand),
1349
+ resolutions: Array.from(stored?.unknownResolutions.values() ?? [], ({ intent }) => cleanCommand(intent))
1350
+ };
1351
+ };
1352
+ const readCommands = Effect.fnUntraced(function* (stored) {
1353
+ if ((stored?.approvalDecisions.size ?? 0) > MAX_RUN_EVIDENCE_RECORDS || (stored?.unknownResolutions.size ?? 0) > MAX_RUN_EVIDENCE_RECORDS) return yield* ThreadStoreError.make({
1354
+ operation: "read commands",
1355
+ message: "Accepted commands exceed Run record bounds"
1356
+ });
1357
+ let bytes = 0;
1358
+ const add = (schema, value) => Schema.encodeEffect(Schema.toCodecJson(schema))(value).pipe(Effect.mapError(() => ThreadStoreError.make({
1359
+ operation: "read commands",
1360
+ message: "Invalid accepted command wire"
1361
+ })), Effect.flatMap((wire) => {
1362
+ bytes += utf8ByteLength(canonicalJson(wire));
1363
+ return bytes > MAX_RUN_EVIDENCE_BYTES ? Effect.fail(ThreadStoreError.make({
1364
+ operation: "read commands",
1365
+ message: "Accepted commands exceed Run byte bounds"
1366
+ })) : Effect.void;
1367
+ }));
1368
+ if (stored?.abortIntent !== void 0) yield* add(AbortIntent, stored.abortIntent);
1369
+ for (const value of stored?.approvalDecisions.values() ?? []) yield* add(ApprovalDecisionIntent, value);
1370
+ for (const { intent } of stored?.unknownResolutions.values() ?? []) yield* add(UnknownResolutionIntent, intent);
1371
+ return commands(stored);
1372
+ });
1373
+ const lookupAdmission = (threadId, submissionId) => Effect.sync(() => {
1374
+ const stored = MutableRef.get(state.ref).submissions.get(submissionId);
1375
+ return stored?.row.threadId === threadId ? toAdmission(stored.row, stored.finalization?.finalizedAtMillis) : void 0;
1376
+ });
1377
+ yield* journal.registerLedgerTransfer({
1378
+ admission: lookupAdmission,
1379
+ commands: (id) => readCommands(MutableRef.get(state.ref).submissions.get(id)),
1380
+ snapshot: (threadId) => Effect.sync(() => {
1381
+ const current = MutableRef.get(state.ref);
1382
+ const directory = current.byThread.get(threadId);
1383
+ return {
1384
+ idle: (current.activeByThread.get(threadId)?.size ?? 0) === 0 && (directory?.reservations ?? 0) === 0,
1385
+ admissions: directory?.ordered.length ?? 0,
1386
+ aborts: directory?.commands.aborts.length ?? 0,
1387
+ approvals: directory?.commands.approvals.length ?? 0,
1388
+ resolutions: directory?.commands.resolutions.length ?? 0,
1389
+ ...current.stoppedWorkers.has(threadId) ? { workerSeal: current.stoppedWorkers.get(threadId) === void 0 ? {} : { terminal: current.stoppedWorkers.get(threadId) } } : {}
1390
+ };
1391
+ }),
1392
+ facts: (threadId, section, after) => Effect.sync(() => {
1393
+ const current = MutableRef.get(state.ref);
1394
+ const facts = {
1395
+ admissions: new Array(),
1396
+ commands: commands(void 0),
1397
+ deliveries: []
1398
+ };
1399
+ let next = after ?? "";
1400
+ if (section === "admissions") {
1401
+ const stored = threadRows(current, threadId, after === void 0 ? -1 : Number(after)).next().value;
1402
+ if (stored !== void 0) {
1403
+ facts.admissions.push(toAdmission(stored.row, stored.finalization?.finalizedAtMillis));
1404
+ next = String(stored.row.queueSequence);
1405
+ }
1406
+ } else {
1407
+ const entries = current.byThread.get(threadId)?.commands[section] ?? [];
1408
+ const at = after === void 0 ? 0 : commandPosition(entries, after);
1409
+ const choice = entries[at + Number(after !== void 0 && entries[at]?.key === after)];
1410
+ if (choice !== void 0) {
1411
+ next = choice.key;
1412
+ const stored = current.submissions.get(choice.submissionId);
1413
+ if (section === "aborts" && stored?.abortIntent !== void 0) facts.commands.aborts.push(cleanCommand(stored.abortIntent));
1414
+ else if (section === "approvals" && choice.toolCallId !== void 0) {
1415
+ const value = stored?.approvalDecisions.get(choice.toolCallId);
1416
+ if (value !== void 0) facts.commands.approvals.push(cleanCommand(value));
1417
+ } else if (section === "resolutions" && choice.resolutionKey !== void 0) {
1418
+ const value = stored?.unknownResolutions.get(choice.resolutionKey);
1419
+ if (value !== void 0) facts.commands.resolutions.push(cleanCommand(value.intent));
1420
+ }
1421
+ }
1422
+ }
1423
+ return {
1424
+ facts,
1425
+ after: next
1426
+ };
1427
+ }),
1428
+ submissions: (threadId) => Stream.paginate(-1, (after) => Effect.sync(() => {
1429
+ const stored = threadRows(MutableRef.get(state.ref), threadId, after).next().value;
1430
+ return [stored === void 0 ? [] : [toSnapshot(stored.row)], stored === void 0 ? Option.none() : Option.some(stored.row.queueSequence)];
1431
+ })),
1432
+ startImport: Effect.fnUntraced(function* (threadId) {
1433
+ const current = yield* Ref.get(state);
1434
+ if (current.lanes.has(threadId) || current.byThread.has(threadId) || current.stoppedWorkers.has(threadId)) return yield* ThreadImportRejected.make({
1435
+ threadId,
1436
+ reason: "target-not-empty",
1437
+ message: "Destination ledger contains Thread data"
1438
+ });
1439
+ const staged = {
1440
+ submissions: /* @__PURE__ */ new Map(),
1441
+ admissionIndex: /* @__PURE__ */ new Map(),
1442
+ lanes: /* @__PURE__ */ new Map(),
1443
+ childReservations: /* @__PURE__ */ new Map(),
1444
+ freshAdmissionSequence: current.freshAdmissionSequence,
1445
+ stoppedWorkers: /* @__PURE__ */ new Map(),
1446
+ latestByThread: /* @__PURE__ */ new Map(),
1447
+ activeByThread: /* @__PURE__ */ new Map(),
1448
+ byThread: /* @__PURE__ */ new Map(),
1449
+ receipts: /* @__PURE__ */ new Map(),
1450
+ joinsByHost: /* @__PURE__ */ new Map(),
1451
+ childrenByParent: /* @__PURE__ */ new Map()
1452
+ };
1453
+ const commandBytes = /* @__PURE__ */ new Map();
1454
+ const settledTimes = /* @__PURE__ */ new Map();
1455
+ const retainCommandBytes = Effect.fnUntraced(function* (schema, value, id) {
1456
+ const wire = yield* Schema.encodeEffect(Schema.toCodecJson(schema))(value).pipe(Effect.mapError(() => invalidThreadArchive("Invalid accepted command wire", threadId)));
1457
+ const bytes = (commandBytes.get(id) ?? 0) + utf8ByteLength(canonicalJson(wire));
1458
+ if (bytes > MAX_RUN_EVIDENCE_BYTES) return yield* invalidThreadArchive("Accepted commands exceed Run byte bounds", threadId);
1459
+ commandBytes.set(id, bytes);
1460
+ });
1461
+ return {
1462
+ reader: {
1463
+ admission: (id) => Effect.sync(() => {
1464
+ const stored = staged.submissions.get(id);
1465
+ return stored === void 0 ? void 0 : toAdmission(stored.row, settledTimes.get(id));
1466
+ }),
1467
+ runOwner: Effect.fnUntraced(function* (runId) {
1468
+ if (!runId.startsWith("run:")) return void 0;
1469
+ const id = yield* Schema.decodeEffect(SubmissionId)(runId.slice(4)).pipe(Effect.orDie);
1470
+ const stored = staged.submissions.get(id);
1471
+ return stored === void 0 ? void 0 : toAdmission(stored.row, settledTimes.get(id));
1472
+ }),
1473
+ commands: (id) => readCommands(staged.submissions.get(id))
1474
+ },
1475
+ stage: Effect.fnUntraced(function* (page) {
1476
+ for (const a of page.archive.admissions) {
1477
+ const key = admissionKey(threadId, a.principal, a.idempotencyKey);
1478
+ if (current.submissions.has(a.submissionId) || staged.submissions.has(a.submissionId) || current.receipts.has(a.receiptId) || staged.receipts.has(a.receiptId) || current.admissionIndex.has(key) || staged.admissionIndex.has(key)) return yield* ThreadImportRejected.make({
1479
+ threadId,
1480
+ reason: "destination-conflict",
1481
+ message: "Admission, receipt, or immutable admission key already exists"
1482
+ });
1483
+ if (threadRows(staged, threadId, a.queueSequence - 1).next().value?.row.queueSequence === a.queueSequence) return yield* invalidThreadArchive("Duplicate admission queue position", threadId);
1484
+ if (a.settledAt !== void 0) settledTimes.set(a.submissionId, DateTime.toEpochMillis(a.settledAt));
1485
+ withSubmission(staged, fromRebuilt(RebuiltSubmission.make({
1486
+ admission: a,
1487
+ state: "admitted",
1488
+ unknownToolCallIds: [],
1489
+ approvals: [],
1490
+ resolutions: []
1491
+ })));
1492
+ }
1493
+ for (const fact of page.archive.commands.aborts) {
1494
+ const stored = staged.submissions.get(fact.submissionId);
1495
+ if (stored === void 0 || stored.abortIntent !== void 0) return yield* invalidThreadArchive("Missing admission or duplicate abort", threadId);
1496
+ const intent = AbortIntent.make(fact);
1497
+ yield* retainCommandBytes(AbortIntent, intent, fact.submissionId);
1498
+ withSubmission(staged, {
1499
+ ...stored,
1500
+ abortIntent: intent
1501
+ });
1502
+ }
1503
+ for (const fact of page.archive.commands.approvals) {
1504
+ const stored = staged.submissions.get(fact.submissionId);
1505
+ if (stored === void 0 || stored.approvalDecisions.has(fact.toolCallId)) return yield* invalidThreadArchive("Missing admission or duplicate approval", threadId);
1506
+ if (stored.approvalDecisions.size >= MAX_RUN_EVIDENCE_RECORDS) return yield* invalidThreadArchive("Accepted approvals exceed Run record bounds", threadId);
1507
+ const intent = ApprovalDecisionIntent.make(fact);
1508
+ yield* retainCommandBytes(ApprovalDecisionIntent, intent, fact.submissionId);
1509
+ const approvals = new Map(stored.approvalDecisions).set(fact.toolCallId, intent);
1510
+ withSubmission(staged, {
1511
+ ...stored,
1512
+ approvalDecisions: approvals
1513
+ });
1514
+ }
1515
+ for (const fact of page.archive.commands.resolutions) {
1516
+ const stored = staged.submissions.get(fact.submissionId);
1517
+ const key = JSON.stringify([fact.toolCallId, unknownResolutionKind(fact.resolution)]);
1518
+ if (stored === void 0 || stored.unknownResolutions.has(key)) return yield* invalidThreadArchive("Missing admission or duplicate resolution", threadId);
1519
+ if (stored.unknownResolutions.size >= MAX_RUN_EVIDENCE_RECORDS) return yield* invalidThreadArchive("Accepted resolutions exceed Run record bounds", threadId);
1520
+ const intent = UnknownResolutionIntent.make(fact);
1521
+ yield* retainCommandBytes(UnknownResolutionIntent, intent, fact.submissionId);
1522
+ const resolutions = new Map(stored.unknownResolutions).set(key, { intent });
1523
+ withSubmission(staged, {
1524
+ ...stored,
1525
+ unknownResolutions: resolutions
1526
+ });
1527
+ }
1528
+ }),
1529
+ prepareCommit: Effect.fnUntraced(function* (workerSeal) {
1530
+ let lastQueue = 0;
1531
+ let terminalEvidence = workerSeal?.terminal === void 0;
1532
+ for (const stored of threadRows(staged, threadId)) {
1533
+ const a = toAdmission(stored.row, settledTimes.get(stored.row.submissionId));
1534
+ const rebuilt = yield* rebuildClosedSubmission(a);
1535
+ if (rebuilt.settlement !== void 0 && workerTerminalFromRecord(toSnapshot(stored.row), rebuilt.settlement) === workerSeal?.terminal) terminalEvidence = true;
1536
+ withSubmission(staged, fromRebuilt(rebuilt));
1537
+ lastQueue = Math.max(lastQueue, a.queueSequence);
1538
+ }
1539
+ if (!terminalEvidence) return yield* invalidThreadArchive("Worker seal terminal has no exact completed input evidence", threadId);
1540
+ if (!Number.isSafeInteger(lastQueue + 1)) return yield* ThreadImportRejected.make({
1541
+ threadId,
1542
+ reason: "unsupported-capacity",
1543
+ message: "Admission queue sequence is exhausted"
1544
+ });
1545
+ return () => {
1546
+ for (const stored of staged.submissions.values()) withSubmission(current, stored);
1547
+ current.lanes.set(threadId, { nextQueueSequence: lastQueue + 1 });
1548
+ if (workerSeal !== void 0) current.stoppedWorkers.set(threadId, workerSeal.terminal);
1549
+ };
1550
+ })
1551
+ };
1552
+ })
1553
+ });
1554
+ return Context.make(SubmissionLedger, ledger).pipe(Context.add(SettlementPublisher, { publish }));
1555
+ }
1556
+ );
1557
+ /**
1558
+ * In-memory reference SubmissionLedger Layer (durability `non-durable`). All state lives in one
1559
+ * `Ref` owned by the Layer's Scope. Fresh identities use the supplied `SecureRandom` service;
1560
+ * imported identities remain unchanged. No daemon fibers are spawned and no wall clock is consulted.
1561
+ */
1562
+ const memorySubmissionLedgerLayer = (options = {}) => Layer.effectContext(makeSubmissionLedger(options));
1563
+ const MemorySubmissionLedgerLive = memorySubmissionLedgerLayer();
1564
+ export { MemorySubmissionLedger_exports as n, memorySubmissionLedgerLayer as r, MemorySubmissionLedgerLive as t };
1565
+
1566
+ //# sourceMappingURL=MemorySubmissionLedger-lc4VJ_vq.mjs.map