@effect-agent/storage-cloudflare 0.1.0-beta.9 → 0.1.0-beta.90

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 (73) hide show
  1. package/dist/DoMemoryStore.d.mts +29 -0
  2. package/dist/DoMemoryStore.mjs +55 -0
  3. package/dist/DoMemoryStore.mjs.map +1 -0
  4. package/dist/DoMessageDeliveryStore.d.mts +17 -0
  5. package/dist/DoMessageDeliveryStore.mjs +32 -0
  6. package/dist/DoMessageDeliveryStore.mjs.map +1 -0
  7. package/dist/DoScheduleStore.d.mts +36 -0
  8. package/dist/DoScheduleStore.mjs +388 -0
  9. package/dist/DoScheduleStore.mjs.map +1 -0
  10. package/dist/DoStorageConfig.d.mts +45 -0
  11. package/dist/DoStorageConfig.mjs +52 -0
  12. package/dist/DoStorageConfig.mjs.map +1 -0
  13. package/dist/DoStorageError-Cmhvl4TQ.d.mts +98 -0
  14. package/dist/DoStorageError.d.mts +2 -0
  15. package/dist/DoStorageError.mjs +164 -0
  16. package/dist/DoStorageError.mjs.map +1 -0
  17. package/dist/DoStorageFailpoint.d.mts +17 -0
  18. package/dist/DoStorageFailpoint.mjs +14 -0
  19. package/dist/DoStorageFailpoint.mjs.map +1 -0
  20. package/dist/DoStorageFailpointTesting.d.mts +34 -0
  21. package/dist/DoStorageFailpointTesting.mjs +35 -0
  22. package/dist/DoStorageFailpointTesting.mjs.map +1 -0
  23. package/dist/DoStorageVersion-x5OOurvZ.d.mts +12 -0
  24. package/dist/DoStorageVersion.d.mts +2 -0
  25. package/dist/DoStorageVersion.mjs +8 -0
  26. package/dist/DoStorageVersion.mjs.map +1 -0
  27. package/dist/DoSubmissionLedger.d.mts +23 -0
  28. package/dist/DoSubmissionLedger.mjs +1849 -0
  29. package/dist/DoSubmissionLedger.mjs.map +1 -0
  30. package/dist/DoSubscriptionStore.d.mts +25 -0
  31. package/dist/DoSubscriptionStore.mjs +183 -0
  32. package/dist/DoSubscriptionStore.mjs.map +1 -0
  33. package/dist/DoThreadStore.d.mts +59 -0
  34. package/dist/DoThreadStore.mjs +465 -0
  35. package/dist/DoThreadStore.mjs.map +1 -0
  36. package/dist/MemoryProtocol.d.mts +38160 -0
  37. package/dist/MemoryProtocol.mjs +219 -0
  38. package/dist/MemoryProtocol.mjs.map +1 -0
  39. package/dist/PortProtocol.d.mts +3804 -0
  40. package/dist/PortProtocol.mjs +176 -0
  41. package/dist/PortProtocol.mjs.map +1 -0
  42. package/dist/PortRouting.d.mts +83 -0
  43. package/dist/PortRouting.mjs +410 -0
  44. package/dist/PortRouting.mjs.map +1 -0
  45. package/dist/do-journal-dJ01KSKf.mjs +991 -0
  46. package/dist/do-journal-dJ01KSKf.mjs.map +1 -0
  47. package/dist/index.d.mts +14 -1525
  48. package/dist/index.mjs +14 -3695
  49. package/dist/migrations-Ba_kOrSx.mjs +287 -0
  50. package/dist/migrations-Ba_kOrSx.mjs.map +1 -0
  51. package/dist/rolldown-runtime-D7D4PA-g.mjs +13 -0
  52. package/package.json +1 -45
  53. package/src/DoMemoryStore.ts +56 -0
  54. package/src/DoMessageDeliveryStore.ts +53 -0
  55. package/src/DoScheduleStore.ts +622 -0
  56. package/src/{errors.ts → DoStorageError.ts} +10 -3
  57. package/src/DoStorageFailpoint.ts +20 -0
  58. package/src/{do-storage-failpoint.ts → DoStorageFailpointTesting.ts} +5 -18
  59. package/src/DoStorageVersion.ts +2 -0
  60. package/src/{do-ledger.ts → DoSubmissionLedger.ts} +924 -225
  61. package/src/DoSubscriptionStore.ts +329 -0
  62. package/src/DoThreadStore.ts +1012 -0
  63. package/src/MemoryProtocol.ts +351 -0
  64. package/src/{port-protocol.ts → PortProtocol.ts} +45 -38
  65. package/src/{routing.ts → PortRouting.ts} +292 -264
  66. package/src/index.ts +13 -32
  67. package/src/{do-journal.ts → internal/do-journal.ts} +718 -234
  68. package/src/internal/message-delivery-schema.ts +24 -0
  69. package/src/{migrations.ts → internal/migrations.ts} +51 -35
  70. package/src/internal/recovery-checkpoint-schema.ts +17 -0
  71. package/dist/index.mjs.map +0 -1
  72. package/src/do-conversation-store.ts +0 -850
  73. /package/src/{do-storage-config.ts → DoStorageConfig.ts} +0 -0
@@ -0,0 +1,410 @@
1
+ import { t as __exportAll } from "./rolldown-runtime-D7D4PA-g.mjs";
2
+ import { LedgerAdmitCall, LedgerAdmitResult, LedgerLookupCall, LedgerLookupResult, LedgerMarkReadyCall, LedgerMarkReadyResult, LedgerRecordChildSettledCall, LedgerRecordChildSettledResult, LedgerRequestAbortCall, LedgerRequestAbortResult, LedgerResolveAdmissionCall, LedgerResolveAdmissionResult, PortFailed, PortProtocolError, PortSucceeded, StoreAppendCall, StoreAppendResult, StoreExportCall, StoreExportResult, StoreInspectTailCall, StoreInspectTailResult, StoreMaterializeCall, StoreMaterializeResult, StoreReadPageCall, StoreReadPageResult, boundPortDiagnostic, decodePortRequest, decodePortResponse, encodePortRequest, encodePortResponse } from "./PortProtocol.mjs";
3
+ import { Context, Effect, Layer, Option, Predicate, Schema, Stream } from "effect";
4
+ import { AppendConflict, FenceRejected, ThreadMaterialization, ThreadNotMaterialized, ThreadStore, ThreadStoreError } from "effect-agent/thread-store";
5
+ import { AdmissionConflict, AdmissionIndeterminate, AdmissionPolicyError, ChildAttachmentSnapshot, JoinedToHost, LedgerError, RecoverySnapshot, SettlementConflict, SubmissionLedger, SubmissionLookupById } from "effect-agent/submission-ledger";
6
+ //#region src/PortRouting.ts
7
+ var PortRouting_exports = /* @__PURE__ */ __exportAll({
8
+ PortTransportError: () => PortTransportError,
9
+ ThreadPortTransport: () => ThreadPortTransport,
10
+ executePortRequest: () => executePortRequest,
11
+ handleEncodedPortRequest: () => handleEncodedPortRequest,
12
+ portTransportFailure: () => portTransportFailure,
13
+ routedSubmissionLedgerLayer: () => routedSubmissionLedgerLayer,
14
+ routedThreadStoreLayer: () => routedThreadStoreLayer
15
+ });
16
+ const ThreadIdSchema = ThreadMaterialization.fields.threadId;
17
+ const decodeThreadId = Schema.decodeUnknownEffect(ThreadIdSchema);
18
+ /**
19
+ * The ledger row bound routable Submission identities must respect (mirrors the local
20
+ * facet's `MAX_IDENTIFIER_LENGTH`; the minting side already refuses longer identities typed
21
+ * at admission, so a longer identity presented here cannot name any stored row).
22
+ */
23
+ const MAX_ROUTABLE_SUBMISSION_ID_LENGTH = 1024;
24
+ /** The `{uuidv7}` head of a DC-minted routable Submission identity. */
25
+ const UUID_HEAD_PATTERN = /^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$/;
26
+ /**
27
+ * A transport could not deliver a port request to (or an answer from) the owning
28
+ * Thread's Durable Object. `retryable` carries the platform's own stub signal when one
29
+ * exists. This error never crosses the wire — it is the CALLER-side evidence that the
30
+ * authority was unreachable, which is exactly the case `AdmissionIndeterminate` was
31
+ * specified for (SUB-031).
32
+ */
33
+ var PortTransportError = class extends Schema.TaggedError()("PortTransportError", {
34
+ target: Schema.String,
35
+ message: Schema.String,
36
+ retryable: Schema.optionalKey(Schema.Boolean),
37
+ cause: Schema.optionalKey(Schema.Defect())
38
+ }) {};
39
+ const safeTransportDiagnostic = (cause) => {
40
+ try {
41
+ const message = cause instanceof Error ? cause.message : cause;
42
+ return boundPortDiagnostic(typeof message === "string" ? message : String(message));
43
+ } catch {
44
+ return "[unavailable transport diagnostic]";
45
+ }
46
+ };
47
+ const transportRetryableSignal = (cause) => {
48
+ if (!Predicate.isObjectKeyword(cause)) return void 0;
49
+ try {
50
+ const signal = Reflect.get(cause, "retryable");
51
+ return typeof signal === "boolean" ? signal : void 0;
52
+ } catch {
53
+ return;
54
+ }
55
+ };
56
+ /**
57
+ * Build a `PortTransportError` from an arbitrary thrown transport cause, preserving the
58
+ * platform stub's own `retryable` signal when present.
59
+ */
60
+ const portTransportFailure = (target, cause) => {
61
+ const retryable = transportRetryableSignal(cause);
62
+ return PortTransportError.make({
63
+ target,
64
+ message: safeTransportDiagnostic(cause),
65
+ ...retryable === void 0 ? {} : { retryable },
66
+ cause
67
+ });
68
+ };
69
+ /**
70
+ * Delivery of Schema-encoded port envelopes to the Durable Object that owns a FOREIGN
71
+ * Thread (plan §1.3, D-P6-3). The shipped implementation (platform-cloudflare, WP3)
72
+ * calls the owner's `portCall` over native Durable Object JS RPC via
73
+ * `namespace.idFromName(threadId)`; the protocol is transport-agnostic and any carrier
74
+ * that moves the encoded envelopes verbatim satisfies this service. Implementations MUST
75
+ * surface every delivery problem as `PortTransportError` and must never fabricate an answer.
76
+ */
77
+ var ThreadPortTransport = class extends Context.Service()("@effect-agent/storage-cloudflare/ThreadPortTransport") {};
78
+ const LOCAL = { _tag: "local" };
79
+ /**
80
+ * Parse a DC-minted routable Submission identity — `{uuidv7}:{threadId}`, split at the
81
+ * FIRST `:` because the Thread tail may itself contain colons (D-P6-5). This adapter
82
+ * minted the format at admission and is the ONLY component that parses it; identities that do
83
+ * not carry the minted shape (no separator, non-UUID head, empty tail) fall back to the local
84
+ * facet, which is the only authority this Object can consult without inventing an owner.
85
+ * Identities beyond the ledger's 1,024-character row bound fail typed: the minting side
86
+ * refused them at admission, so they cannot name any stored row anywhere.
87
+ */
88
+ const routableSubmissionTarget = (ownsThread) => Effect.fn("DoPortRouting.routableSubmissionTarget")(function* (operation, submissionId) {
89
+ if (submissionId.length > MAX_ROUTABLE_SUBMISSION_ID_LENGTH) return yield* LedgerError.make({
90
+ operation,
91
+ message: `A Submission identity of ${submissionId.length} characters exceeds the ${MAX_ROUTABLE_SUBMISSION_ID_LENGTH}-character routable identity bound; admission refuses such identities, so it cannot name any stored row.`
92
+ });
93
+ const separator = submissionId.indexOf(":");
94
+ if (separator === -1) return LOCAL;
95
+ if (!UUID_HEAD_PATTERN.test(submissionId.slice(0, separator))) return LOCAL;
96
+ const tail = submissionId.slice(separator + 1);
97
+ return yield* decodeThreadId(tail).pipe(Effect.map((threadId) => ownsThread(threadId) ? LOCAL : {
98
+ _tag: "foreign",
99
+ threadId
100
+ }), Effect.orElseSucceed(() => LOCAL));
101
+ });
102
+ const NoAdditionalPortFailure = Schema.Never;
103
+ const AbortPortFailure = Schema.Union([SettlementConflict, JoinedToHost]);
104
+ const AppendPortFailure = Schema.Union([
105
+ ThreadNotMaterialized,
106
+ AppendConflict,
107
+ FenceRejected
108
+ ]);
109
+ /**
110
+ * The fail-fast refusal for any foreign operation OUTSIDE the closed route-capable subset
111
+ * (plan §1.3): honesty over accidental distribution.
112
+ */
113
+ const crossThreadLedgerError = (operation, target) => LedgerError.make({
114
+ operation,
115
+ message: `${operation} addressed to foreign Thread ${target} is not route-capable; the closed cross-Object subset is admit, markReady, lookup, resolveAdmission, requestAbort, and recordChildSettled. Every other ledger operation is lane-local by construction and must execute inside the owning Thread's Durable Object.`
116
+ });
117
+ const crossThreadStoreError = (operation, target) => ThreadStoreError.make({
118
+ operation,
119
+ message: `${operation} addressed to foreign Thread ${target} is not route-capable; the closed cross-Object subset is materialize, append, read (paged), inspectTail, and export. Observation and checkpoints are lane-local by construction and must execute inside the owning Thread's Durable Object.`
120
+ });
121
+ const makeTransportCall = (transport) => Effect.fn("DoPortRouting.transportCall")(function* (target, call) {
122
+ const encoded = yield* encodePortRequest(call).pipe(Effect.mapError((error) => PortProtocolError.make({ message: boundPortDiagnostic(`The port request could not be encoded: ${error.message}`) })));
123
+ const raw = yield* transport.call(target, encoded);
124
+ return yield* decodePortResponse(raw).pipe(Effect.mapError((error) => PortProtocolError.make({ message: boundPortDiagnostic(`The port response could not be decoded: ${error.message}`) })));
125
+ });
126
+ const makeRoutedLedgerServices = Effect.fn("DoPortRouting.makeRoutedLedgerServices")(function* (options) {
127
+ const local = yield* SubmissionLedger;
128
+ const transport = yield* ThreadPortTransport;
129
+ const transportCall = makeTransportCall(transport);
130
+ const submissionTarget = routableSubmissionTarget(options.ownsThread);
131
+ const routeFailure = (operation, target) => (error) => LedgerError.make({
132
+ operation,
133
+ message: boundPortDiagnostic(`Routed ${operation} to the Thread Object owning ${target} failed: ${error.message}`),
134
+ cause: error
135
+ });
136
+ /**
137
+ * One routed ledger call: encode, deliver, decode, then narrow the uniform envelope to the
138
+ * operation's own result and failure surface. A foreign `LedgerError` is always in-channel;
139
+ * any failure outside the operation's declared surface — including protocol anomalies — is
140
+ * folded into a `LedgerError` naming the anomaly instead of being erased or re-thrown raw.
141
+ */
142
+ const foreignLedgerCall = (operation, target, call, resultSchema, failureSchema) => {
143
+ const isExpectedResult = Schema.is(resultSchema);
144
+ const isExpectedFailure = Schema.is(failureSchema);
145
+ return transportCall(target, call).pipe(Effect.mapError(routeFailure(operation, target)), Effect.flatMap((response) => {
146
+ if (response._tag === "PortFailed") {
147
+ const failure = response.failure;
148
+ if (isExpectedFailure(failure)) return Effect.fail(failure);
149
+ if (failure._tag === "LedgerError") return Effect.fail(failure);
150
+ return Effect.fail(LedgerError.make({
151
+ operation,
152
+ message: boundPortDiagnostic(`The Thread Object owning ${target} answered ${operation} with the out-of-contract failure ${failure._tag}: ${failure.message}`),
153
+ cause: failure
154
+ }));
155
+ }
156
+ const result = response.result;
157
+ if (!isExpectedResult(result)) return Effect.fail(LedgerError.make({
158
+ operation,
159
+ message: `The Thread Object owning ${target} answered ${operation} with the mismatched result ${result._tag}.`
160
+ }));
161
+ return Effect.succeed(result);
162
+ }), Effect.withSpan("DoPortRouting.foreignLedgerCall", { attributes: {
163
+ operation,
164
+ target
165
+ } }));
166
+ };
167
+ /**
168
+ * Routed `resolveAdmission` — where the S2 tri-state becomes real (plan §1.3): when the
169
+ * owning Object cannot be reached, or its answer cannot be understood, the routed adapter
170
+ * answers `AdmissionIndeterminate{reason}` and NEVER `NotAdmitted` — an unreachable
171
+ * authority proves nothing, and only `NotAdmitted` permits an admission attempt (SUB-031).
172
+ * A typed `LedgerError` answered BY the authority still fails typed: the authority was
173
+ * reached and reported its own storage failure.
174
+ */
175
+ const resolveForeignAdmission = (target, request) => transportCall(target, LedgerResolveAdmissionCall.make({ request })).pipe(Effect.flatMap((response) => {
176
+ if (response._tag === "PortFailed") {
177
+ if (response.failure._tag === "LedgerError") return Effect.fail(response.failure);
178
+ return Effect.succeed(AdmissionIndeterminate.make({ reason: boundPortDiagnostic(`The Thread Object owning ${target} answered resolveAdmission with the out-of-contract failure ${response.failure._tag}: ${response.failure.message}`) }));
179
+ }
180
+ if (response.result._tag !== "LedgerResolveAdmissionResult") return Effect.succeed(AdmissionIndeterminate.make({ reason: boundPortDiagnostic(`The Thread Object owning ${target} answered resolveAdmission with the mismatched result ${response.result._tag}.`) }));
181
+ return Effect.succeed(response.result.resolution);
182
+ }), Effect.catchTags({
183
+ PortTransportError: (error) => Effect.succeed(AdmissionIndeterminate.make({ reason: boundPortDiagnostic(`The Thread Object owning ${target} is unreachable: ${error.message}`) })),
184
+ PortProtocolError: (error) => Effect.succeed(AdmissionIndeterminate.make({ reason: boundPortDiagnostic(`The answer of the Thread Object owning ${target} could not be understood: ${error.message}`) }))
185
+ }), Effect.withSpan("DoPortRouting.resolveForeignAdmission", { attributes: { target } }));
186
+ const foreignLookupById = (operation, target, submissionId) => foreignLedgerCall(operation, target, LedgerLookupCall.make({ request: SubmissionLookupById.make({ submissionId }) }), LedgerLookupResult, NoAdditionalPortFailure).pipe(Effect.map((result) => result.submission === void 0 ? Option.none() : Option.some(result.submission)));
187
+ /**
188
+ * Enrich a LOCAL parent's recovery snapshot with the lane state of attached children whose
189
+ * rows live in other Durable Objects (plan §1.3): markers first (the local facet already
190
+ * consulted them), then a routed per-child `lookup` for any attached child that is neither
191
+ * local nor marker-settled. A transport failure surfaces as `LedgerError` so the alarm
192
+ * pass retries; the child's canonical Settlement remains the only authority (DUR-015).
193
+ */
194
+ const enrichChildAttachments = Effect.fn("DoPortRouting.enrichChildAttachments")(function* (snapshot) {
195
+ const operation = "ledger load recovery snapshot";
196
+ const attachments = new Map(snapshot.childAttachments.map((attachment) => [attachment.childSubmissionId, attachment]));
197
+ let enriched = false;
198
+ for (const reservation of snapshot.childReservations) {
199
+ const childSubmissionId = reservation.childSubmissionId;
200
+ if (childSubmissionId === void 0 || attachments.has(childSubmissionId)) continue;
201
+ const target = yield* submissionTarget(operation, childSubmissionId);
202
+ if (target._tag !== "foreign") continue;
203
+ const child = yield* foreignLookupById(operation, target.threadId, childSubmissionId);
204
+ if (Option.isNone(child)) continue;
205
+ attachments.set(childSubmissionId, ChildAttachmentSnapshot.make({
206
+ toolCallId: reservation.parentToolCallId,
207
+ childSubmissionId,
208
+ childState: child.value.state,
209
+ ...child.value.settledOutcome === void 0 ? {} : { childOutcome: child.value.settledOutcome }
210
+ }));
211
+ enriched = true;
212
+ }
213
+ if (!enriched) return snapshot;
214
+ const ordered = [];
215
+ for (const reservation of snapshot.childReservations) {
216
+ if (reservation.childSubmissionId === void 0) continue;
217
+ const attachment = attachments.get(reservation.childSubmissionId);
218
+ if (attachment !== void 0) ordered.push(attachment);
219
+ }
220
+ return RecoverySnapshot.make({
221
+ ...snapshot,
222
+ childAttachments: ordered
223
+ });
224
+ });
225
+ const routed = SubmissionLedger.of({
226
+ capabilities: local.capabilities,
227
+ admit: (request) => options.ownsThread(request.threadId) ? local.admit(request) : foreignLedgerCall("ledger admit", request.threadId, LedgerAdmitCall.make({ request }), LedgerAdmitResult, Schema.Union([AdmissionConflict, AdmissionPolicyError])).pipe(Effect.map((reply) => reply.result)),
228
+ markReady: (request) => submissionTarget("ledger mark ready", request.submissionId).pipe(Effect.flatMap((target) => target._tag === "local" ? local.markReady(request) : foreignLedgerCall("ledger mark ready", target.threadId, LedgerMarkReadyCall.make({ request }), LedgerMarkReadyResult, NoAdditionalPortFailure).pipe(Effect.asVoid))),
229
+ lookup: (request) => request._tag === "SubmissionLookupById" ? submissionTarget("ledger lookup", request.submissionId).pipe(Effect.flatMap((target) => target._tag === "local" ? local.lookup(request) : foreignLookupById("ledger lookup", target.threadId, request.submissionId))) : options.ownsThread(request.threadId) ? local.lookup(request) : foreignLedgerCall("ledger lookup", request.threadId, LedgerLookupCall.make({ request }), LedgerLookupResult, NoAdditionalPortFailure).pipe(Effect.map((result) => result.submission === void 0 ? Option.none() : Option.some(result.submission))),
230
+ resolveAdmission: (request) => options.ownsThread(request.threadId) ? local.resolveAdmission(request) : resolveForeignAdmission(request.threadId, request),
231
+ requestAbort: (request) => submissionTarget("ledger request abort", request.submissionId).pipe(Effect.flatMap((target) => target._tag === "local" ? local.requestAbort(request) : foreignLedgerCall("ledger request abort", target.threadId, LedgerRequestAbortCall.make({ request }), LedgerRequestAbortResult, AbortPortFailure).pipe(Effect.map((reply) => reply.intent)))),
232
+ recordChildSettled: (request) => submissionTarget("ledger record child settled", request.parentSubmissionId).pipe(Effect.flatMap((target) => target._tag === "local" ? local.recordChildSettled(request) : foreignLedgerCall("ledger record child settled", target.threadId, LedgerRecordChildSettledCall.make({ request }), LedgerRecordChildSettledResult, NoAdditionalPortFailure).pipe(Effect.map((reply) => reply.outcome)))),
233
+ claim: (request) => options.ownsThread(request.threadId) ? local.claim(request) : Effect.fail(crossThreadLedgerError("ledger claim", request.threadId)),
234
+ claimJoining: (request) => options.ownsThread(request.threadId) ? local.claimJoining(request) : Effect.fail(crossThreadLedgerError("ledger claim joining", request.threadId)),
235
+ renewOwnership: (request) => submissionTarget("ledger renew ownership", request.submissionId).pipe(Effect.flatMap((target) => target._tag === "local" ? local.renewOwnership(request) : Effect.fail(crossThreadLedgerError("ledger renew ownership", target.threadId)))),
236
+ releaseOwnership: (request) => submissionTarget("ledger release ownership", request.submissionId).pipe(Effect.flatMap((target) => target._tag === "local" ? local.releaseOwnership(request) : Effect.fail(crossThreadLedgerError("ledger release ownership", target.threadId)))),
237
+ markInputApplied: (request) => submissionTarget("ledger mark input applied", request.submissionId).pipe(Effect.flatMap((target) => target._tag === "local" ? local.markInputApplied(request) : Effect.fail(crossThreadLedgerError("ledger mark input applied", target.threadId)))),
238
+ reserveSettlement: (request) => submissionTarget("ledger reserve settlement", request.submissionId).pipe(Effect.flatMap((target) => target._tag === "local" ? local.reserveSettlement(request) : Effect.fail(crossThreadLedgerError("ledger reserve settlement", target.threadId)))),
239
+ finalizeSettlement: (request) => submissionTarget("ledger finalize settlement", request.submissionId).pipe(Effect.flatMap((target) => target._tag === "local" ? local.finalizeSettlement(request) : Effect.fail(crossThreadLedgerError("ledger finalize settlement", target.threadId)))),
240
+ markJoined: (request) => submissionTarget("ledger mark joined", request.submissionId).pipe(Effect.flatMap((target) => target._tag === "local" ? local.markJoined(request) : Effect.fail(crossThreadLedgerError("ledger mark joined", target.threadId)))),
241
+ revertJoining: (request) => submissionTarget("ledger revert joining", request.submissionId).pipe(Effect.flatMap((target) => target._tag === "local" ? local.revertJoining(request) : Effect.fail(crossThreadLedgerError("ledger revert joining", target.threadId)))),
242
+ suspend: (request) => submissionTarget("ledger suspend", request.submissionId).pipe(Effect.flatMap((target) => target._tag === "local" ? local.suspend(request) : Effect.fail(crossThreadLedgerError("ledger suspend", target.threadId)))),
243
+ recordApprovalDecision: (command) => submissionTarget("ledger record approval decision", command.submissionId).pipe(Effect.flatMap((target) => target._tag === "local" ? local.recordApprovalDecision(command) : Effect.fail(crossThreadLedgerError("ledger record approval decision", target.threadId)))),
244
+ markUnknown: (request) => submissionTarget("ledger mark unknown", request.submissionId).pipe(Effect.flatMap((target) => target._tag === "local" ? local.markUnknown(request) : Effect.fail(crossThreadLedgerError("ledger mark unknown", target.threadId)))),
245
+ recordUnknownResolution: (command) => submissionTarget("ledger record unknown resolution", command.submissionId).pipe(Effect.flatMap((target) => target._tag === "local" ? local.recordUnknownResolution(command) : Effect.fail(crossThreadLedgerError("ledger record unknown resolution", target.threadId)))),
246
+ reserveChildBudget: (request) => submissionTarget("ledger reserve child budget", request.parentSubmissionId).pipe(Effect.flatMap((target) => target._tag === "local" ? local.reserveChildBudget(request) : Effect.fail(crossThreadLedgerError("ledger reserve child budget", target.threadId)))),
247
+ attachChildToReservation: local.attachChildToReservation,
248
+ beginChildBudgetRelease: local.beginChildBudgetRelease,
249
+ releaseChildBudget: local.releaseChildBudget,
250
+ scanNonterminal: local.scanNonterminal,
251
+ readAbortIntent: (request) => submissionTarget("ledger read abort intent", request.submissionId).pipe(Effect.flatMap((target) => target._tag === "local" ? local.readAbortIntent(request) : Effect.fail(crossThreadLedgerError("ledger read abort intent", target.threadId)))),
252
+ loadRecoverySnapshot: (request) => submissionTarget("ledger load recovery snapshot", request.submissionId).pipe(Effect.flatMap((target) => target._tag === "local" ? local.loadRecoverySnapshot(request).pipe(Effect.flatMap(enrichChildAttachments)) : Effect.fail(crossThreadLedgerError("ledger load recovery snapshot", target.threadId))))
253
+ });
254
+ return Context.make(SubmissionLedger, routed);
255
+ });
256
+ const makeRoutedStoreServices = Effect.fn("DoPortRouting.makeRoutedStoreServices")(function* (options) {
257
+ const local = yield* ThreadStore;
258
+ const checkpoints = local.checkpoints;
259
+ const recoveryCheckpoints = local.recoveryCheckpoints;
260
+ const transport = yield* ThreadPortTransport;
261
+ const transportCall = makeTransportCall(transport);
262
+ const routeFailure = (operation, target) => (error) => ThreadStoreError.make({
263
+ operation,
264
+ message: boundPortDiagnostic(`Routed ${operation} to the Thread Object owning ${target} failed: ${error.message}`),
265
+ cause: error
266
+ });
267
+ /** The store twin of `foreignLedgerCall` with `ThreadStoreError` as the base error. */
268
+ const foreignStoreCall = (operation, target, call, resultSchema, failureSchema) => {
269
+ const isExpectedResult = Schema.is(resultSchema);
270
+ const isExpectedFailure = Schema.is(failureSchema);
271
+ return transportCall(target, call).pipe(Effect.mapError(routeFailure(operation, target)), Effect.flatMap((response) => {
272
+ if (response._tag === "PortFailed") {
273
+ const failure = response.failure;
274
+ if (isExpectedFailure(failure)) return Effect.fail(failure);
275
+ if (failure._tag === "ThreadStoreError") return Effect.fail(failure);
276
+ return Effect.fail(ThreadStoreError.make({
277
+ operation,
278
+ message: boundPortDiagnostic(`The Thread Object owning ${target} answered ${operation} with the out-of-contract failure ${failure._tag}: ${failure.message}`),
279
+ cause: failure
280
+ }));
281
+ }
282
+ const result = response.result;
283
+ if (!isExpectedResult(result)) return Effect.fail(ThreadStoreError.make({
284
+ operation,
285
+ message: `The Thread Object owning ${target} answered ${operation} with the mismatched result ${result._tag}.`
286
+ }));
287
+ return Effect.succeed(result);
288
+ }), Effect.withSpan("DoPortRouting.foreignStoreCall", { attributes: {
289
+ operation,
290
+ target
291
+ } }));
292
+ };
293
+ const routed = ThreadStore.of({
294
+ materialize: (request) => options.ownsThread(request.threadId) ? local.materialize(request) : foreignStoreCall("thread materialize", request.threadId, StoreMaterializeCall.make({ request }), StoreMaterializeResult, FenceRejected).pipe(Effect.asVoid),
295
+ append: (request) => options.ownsThread(request.threadId) ? local.append(request) : foreignStoreCall("thread append", request.threadId, StoreAppendCall.make({ request }), StoreAppendResult, AppendPortFailure).pipe(Effect.map((reply) => reply.result)),
296
+ read: (request) => options.ownsThread(request.threadId) ? local.read(request) : Stream.unwrap(foreignStoreCall("thread read", request.threadId, StoreReadPageCall.make({ request }), StoreReadPageResult, ThreadNotMaterialized).pipe(Effect.map((reply) => Stream.fromIterable(reply.records)))),
297
+ inspectTail: (request) => options.ownsThread(request.threadId) ? local.inspectTail(request) : foreignStoreCall("thread inspect tail", request.threadId, StoreInspectTailCall.make({ request }), StoreInspectTailResult, ThreadNotMaterialized).pipe(Effect.map((reply) => reply.tail)),
298
+ export: (request) => options.ownsThread(request.threadId) ? local.export(request) : foreignStoreCall("thread export", request.threadId, StoreExportCall.make({ request }), StoreExportResult, ThreadNotMaterialized).pipe(Effect.map((reply) => reply.export)),
299
+ observe: (request) => options.ownsThread(request.threadId) ? local.observe(request) : Stream.unwrap(Effect.fail(crossThreadStoreError("thread observe", request.threadId))),
300
+ ...recoveryCheckpoints === void 0 ? {} : { recoveryCheckpoints: {
301
+ save: (request) => options.ownsThread(request.checkpoint.threadId) ? recoveryCheckpoints.save(request) : Effect.fail(crossThreadStoreError("thread save recovery checkpoint", request.checkpoint.threadId)),
302
+ load: (request) => options.ownsThread(request.threadId) ? recoveryCheckpoints.load(request) : Effect.succeed(Option.none())
303
+ } },
304
+ ...checkpoints === void 0 ? {} : { checkpoints: {
305
+ save: (request) => options.ownsThread(request.checkpoint.threadId) ? checkpoints.save(request) : Effect.fail(crossThreadStoreError("thread save checkpoint", request.checkpoint.threadId)),
306
+ load: (request) => options.ownsThread(request.threadId) ? checkpoints.load(request) : Effect.fail(crossThreadStoreError("thread load checkpoint", request.threadId))
307
+ } }
308
+ });
309
+ return Context.make(ThreadStore, routed);
310
+ });
311
+ /**
312
+ * Routing decorator over the LOCAL `SubmissionLedger` facet (plan §1.3): a request addressing
313
+ * this Object's Thread executes locally; a route-capable request addressing another
314
+ * Thread is Schema-encoded onto the `ThreadPortTransport` and executed by the
315
+ * owning Object's local facet; any other foreign request fails fast typed. Provide the WP1
316
+ * local facet (`submissionLedgerLayer`/`ledgerLayer`) and a transport to close it.
317
+ */
318
+ const routedSubmissionLedgerLayer = (options) => Layer.effectContext(makeRoutedLedgerServices(options));
319
+ /**
320
+ * Routing decorator over the LOCAL `ThreadStore` facet (plan §1.3): this-thread
321
+ * requests execute locally; foreign materialize/append/read/inspectTail/export travel the
322
+ * transport. Foreign recovery-cache loads return none for canonical replay; other foreign
323
+ * checkpoint operations and observation fail fast typed.
324
+ */
325
+ const routedThreadStoreLayer = (options) => Layer.effectContext(makeRoutedStoreServices(options));
326
+ /** Fold one port operation's typed failures into the uniform response envelope. */
327
+ const capture = (effect) => effect.pipe(Effect.map((result) => PortSucceeded.make({ result })), Effect.catch((failure) => Effect.succeed(PortFailed.make({ failure }))));
328
+ /**
329
+ * Execute one decoded port request against THIS Object's LOCAL facets — the owner-side half
330
+ * of the routed ports (plan §1.3). Callers must provide the WP1 local facets, never the
331
+ * routed decorators: the routing layer already established that this Object owns the
332
+ * addressed Thread, and re-routing here could bounce a request between Objects.
333
+ * Failures never escape — every typed port failure becomes a `PortFailed` envelope that
334
+ * re-decodes on the caller side.
335
+ */
336
+ const executePortRequest = Effect.fn("DoPortRouting.executePortRequest")(function* (request) {
337
+ switch (request._tag) {
338
+ case "LedgerAdmit": {
339
+ const ledger = yield* SubmissionLedger;
340
+ return yield* capture(ledger.admit(request.request).pipe(Effect.map((result) => LedgerAdmitResult.make({ result }))));
341
+ }
342
+ case "LedgerMarkReady": {
343
+ const ledger = yield* SubmissionLedger;
344
+ return yield* capture(ledger.markReady(request.request).pipe(Effect.map(() => LedgerMarkReadyResult.make({}))));
345
+ }
346
+ case "LedgerLookup": {
347
+ const ledger = yield* SubmissionLedger;
348
+ return yield* capture(ledger.lookup(request.request).pipe(Effect.map((submission) => Option.isSome(submission) ? LedgerLookupResult.make({ submission: submission.value }) : LedgerLookupResult.make({}))));
349
+ }
350
+ case "LedgerResolveAdmission": {
351
+ const ledger = yield* SubmissionLedger;
352
+ return yield* capture(ledger.resolveAdmission(request.request).pipe(Effect.map((resolution) => LedgerResolveAdmissionResult.make({ resolution }))));
353
+ }
354
+ case "LedgerRequestAbort": {
355
+ const ledger = yield* SubmissionLedger;
356
+ return yield* capture(ledger.requestAbort(request.request).pipe(Effect.map((intent) => LedgerRequestAbortResult.make({ intent }))));
357
+ }
358
+ case "LedgerRecordChildSettled": {
359
+ const ledger = yield* SubmissionLedger;
360
+ return yield* capture(ledger.recordChildSettled(request.request).pipe(Effect.map((outcome) => LedgerRecordChildSettledResult.make({ outcome }))));
361
+ }
362
+ case "StoreMaterialize": {
363
+ const store = yield* ThreadStore;
364
+ return yield* capture(store.materialize(request.request).pipe(Effect.map(() => StoreMaterializeResult.make({}))));
365
+ }
366
+ case "StoreAppend": {
367
+ const store = yield* ThreadStore;
368
+ return yield* capture(store.append(request.request).pipe(Effect.map((result) => StoreAppendResult.make({ result }))));
369
+ }
370
+ case "StoreReadPage": {
371
+ const store = yield* ThreadStore;
372
+ return yield* capture(store.read(request.request).pipe(Stream.runCollect, Effect.map((records) => StoreReadPageResult.make({ records: [...records] }))));
373
+ }
374
+ case "StoreInspectTail": {
375
+ const store = yield* ThreadStore;
376
+ return yield* capture(store.inspectTail(request.request).pipe(Effect.map((tail) => StoreInspectTailResult.make({ tail }))));
377
+ }
378
+ case "StoreExport": {
379
+ const store = yield* ThreadStore;
380
+ return yield* capture(store.export(request.request).pipe(Effect.map((threadExport) => StoreExportResult.make({ export: threadExport }))));
381
+ }
382
+ }
383
+ });
384
+ /**
385
+ * The last-resort wire fallback when even encoding a response fails: the literal encoded
386
+ * form of `PortFailed(PortProtocolError)` — tagged classes of bounded strings encode to
387
+ * exactly this shape, so no Schema round trip is needed to produce it.
388
+ */
389
+ const encodedProtocolFailure = (message) => ({
390
+ _tag: "PortFailed",
391
+ failure: {
392
+ _tag: "PortProtocolError",
393
+ message: boundPortDiagnostic(message)
394
+ }
395
+ });
396
+ /**
397
+ * The complete owner-side endpoint body for `portCall` (D-P6-3): decode the wire request,
398
+ * execute it against this Object's LOCAL facets, and answer with the encoded response
399
+ * envelope. Total by construction — a request that cannot be decoded, or a response that
400
+ * cannot be encoded, answers `PortFailed(PortProtocolError)` instead of throwing, so the
401
+ * transport never has to interpret exceptions as protocol answers.
402
+ */
403
+ const handleEncodedPortRequest = Effect.fn("DoPortRouting.handleEncodedPortRequest")(function* (encoded) {
404
+ const response = yield* decodePortRequest(encoded).pipe(Effect.flatMap(executePortRequest), Effect.catch((error) => Effect.succeed(PortFailed.make({ failure: PortProtocolError.make({ message: boundPortDiagnostic(`The port request could not be decoded: ${error.message}`) }) }))));
405
+ return yield* encodePortResponse(response).pipe(Effect.catch((error) => Effect.succeed(encodedProtocolFailure(`The port response could not be encoded: ${error.message}`))));
406
+ });
407
+ //#endregion
408
+ export { PortTransportError, ThreadPortTransport, executePortRequest, handleEncodedPortRequest, portTransportFailure, routedSubmissionLedgerLayer, routedThreadStoreLayer, PortRouting_exports as t };
409
+
410
+ //# sourceMappingURL=PortRouting.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"PortRouting.mjs","names":[],"sources":["../src/PortRouting.ts"],"sourcesContent":["import { Context, Effect, Layer, Option, Predicate, Schema, Stream } from \"effect\";\nimport {\n AdmissionIndeterminate,\n AdmissionConflict,\n AdmissionPolicyError,\n ChildAttachmentSnapshot,\n JoinedToHost,\n LedgerError,\n RecoverySnapshot,\n SettlementConflict,\n SubmissionLedger,\n SubmissionLookupById,\n type SubmissionLookupByKey,\n type SubmissionSnapshot,\n} from \"effect-agent/submission-ledger\";\nimport {\n AppendConflict,\n ThreadMaterialization,\n ThreadNotMaterialized,\n ThreadStore,\n ThreadStoreError,\n FenceRejected,\n} from \"effect-agent/thread-store\";\n\nimport {\n boundPortDiagnostic,\n decodePortRequest,\n decodePortResponse,\n encodePortRequest,\n encodePortResponse,\n LedgerAdmitCall,\n LedgerAdmitResult,\n LedgerLookupCall,\n LedgerLookupResult,\n LedgerMarkReadyCall,\n LedgerMarkReadyResult,\n LedgerRecordChildSettledCall,\n LedgerRecordChildSettledResult,\n LedgerRequestAbortCall,\n LedgerRequestAbortResult,\n LedgerResolveAdmissionCall,\n LedgerResolveAdmissionResult,\n PortFailed,\n PortProtocolError,\n PortSucceeded,\n StoreAppendCall,\n StoreAppendResult,\n StoreExportCall,\n StoreExportResult,\n StoreInspectTailCall,\n StoreInspectTailResult,\n StoreMaterializeCall,\n StoreMaterializeResult,\n StoreReadPageCall,\n StoreReadPageResult,\n type PortFailure,\n type PortRequest,\n type PortRequestEnvelope,\n type PortResponse,\n type PortResult,\n} from \"./PortProtocol.ts\";\n\ntype ThreadId = ThreadMaterialization[\"threadId\"];\ntype SubmissionId = SubmissionSnapshot[\"submissionId\"];\n\nconst ThreadIdSchema = ThreadMaterialization.fields.threadId;\nconst decodeThreadId = Schema.decodeUnknownEffect(ThreadIdSchema);\n\n/**\n * The ledger row bound routable Submission identities must respect (mirrors the local\n * facet's `MAX_IDENTIFIER_LENGTH`; the minting side already refuses longer identities typed\n * at admission, so a longer identity presented here cannot name any stored row).\n */\nconst MAX_ROUTABLE_SUBMISSION_ID_LENGTH = 1_024;\n\n/** The `{uuidv7}` head of a DC-minted routable Submission identity. */\nconst UUID_HEAD_PATTERN =\n /^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$/;\n\n/**\n * A transport could not deliver a port request to (or an answer from) the owning\n * Thread's Durable Object. `retryable` carries the platform's own stub signal when one\n * exists. This error never crosses the wire — it is the CALLER-side evidence that the\n * authority was unreachable, which is exactly the case `AdmissionIndeterminate` was\n * specified for (SUB-031).\n */\nexport class PortTransportError extends Schema.TaggedError<PortTransportError>()(\n \"PortTransportError\",\n {\n target: Schema.String,\n message: Schema.String,\n retryable: Schema.optionalKey(Schema.Boolean),\n cause: Schema.optionalKey(Schema.Defect()),\n },\n) {}\n\nconst safeTransportDiagnostic = (cause: unknown): string => {\n try {\n const message = cause instanceof Error ? cause.message : cause;\n\n return boundPortDiagnostic(typeof message === \"string\" ? message : String(message));\n } catch {\n return \"[unavailable transport diagnostic]\";\n }\n};\n\nconst transportRetryableSignal = (cause: unknown): boolean | undefined => {\n if (!Predicate.isObjectKeyword(cause)) return undefined;\n try {\n const signal = Reflect.get(cause, \"retryable\");\n\n return typeof signal === \"boolean\" ? signal : undefined;\n } catch {\n return undefined;\n }\n};\n\n/**\n * Build a `PortTransportError` from an arbitrary thrown transport cause, preserving the\n * platform stub's own `retryable` signal when present.\n */\nexport const portTransportFailure = (target: string, cause: unknown): PortTransportError => {\n const retryable = transportRetryableSignal(cause);\n\n return PortTransportError.make({\n target,\n message: safeTransportDiagnostic(cause),\n ...(retryable === undefined ? {} : { retryable }),\n cause,\n });\n};\n\n/**\n * Delivery of Schema-encoded port envelopes to the Durable Object that owns a FOREIGN\n * Thread (plan §1.3, D-P6-3). The shipped implementation (platform-cloudflare, WP3)\n * calls the owner's `portCall` over native Durable Object JS RPC via\n * `namespace.idFromName(threadId)`; the protocol is transport-agnostic and any carrier\n * that moves the encoded envelopes verbatim satisfies this service. Implementations MUST\n * surface every delivery problem as `PortTransportError` and must never fabricate an answer.\n */\nexport class ThreadPortTransport extends Context.Service<\n ThreadPortTransport,\n {\n readonly call: (\n threadId: ThreadId,\n request: PortRequestEnvelope,\n ) => Effect.Effect<unknown, PortTransportError>;\n }\n>()(\"@effect-agent/storage-cloudflare/ThreadPortTransport\") {}\n\n/** Construction options shared by both routed port Layers. */\nexport interface RoutedPortOptions {\n /**\n * Decide whether this physical owner stores the addressed logical Thread. Local\n * requests use the same SQLite facets; foreign requests use the transport or fail\n * fast typed. The predicate determines placement, never caller authorization.\n */\n readonly ownsThread: (threadId: ThreadId) => boolean;\n}\n\n/** Where one port request must execute. */\ntype RouteTarget =\n | { readonly _tag: \"local\" }\n | { readonly _tag: \"foreign\"; readonly threadId: ThreadId };\n\nconst LOCAL: RouteTarget = { _tag: \"local\" };\n\n/**\n * Parse a DC-minted routable Submission identity — `{uuidv7}:{threadId}`, split at the\n * FIRST `:` because the Thread tail may itself contain colons (D-P6-5). This adapter\n * minted the format at admission and is the ONLY component that parses it; identities that do\n * not carry the minted shape (no separator, non-UUID head, empty tail) fall back to the local\n * facet, which is the only authority this Object can consult without inventing an owner.\n * Identities beyond the ledger's 1,024-character row bound fail typed: the minting side\n * refused them at admission, so they cannot name any stored row anywhere.\n */\nconst routableSubmissionTarget = (\n ownsThread: RoutedPortOptions[\"ownsThread\"],\n): ((operation: string, submissionId: string) => Effect.Effect<RouteTarget, LedgerError>) =>\n Effect.fn(\"DoPortRouting.routableSubmissionTarget\")(function* (\n operation: string,\n submissionId: string,\n ): Effect.fn.Return<RouteTarget, LedgerError> {\n if (submissionId.length > MAX_ROUTABLE_SUBMISSION_ID_LENGTH) {\n return yield* LedgerError.make({\n operation,\n message:\n `A Submission identity of ${submissionId.length} characters exceeds the ` +\n `${MAX_ROUTABLE_SUBMISSION_ID_LENGTH}-character routable identity bound; admission ` +\n \"refuses such identities, so it cannot name any stored row.\",\n });\n }\n const separator = submissionId.indexOf(\":\");\n\n if (separator === -1) return LOCAL;\n if (!UUID_HEAD_PATTERN.test(submissionId.slice(0, separator))) return LOCAL;\n const tail = submissionId.slice(separator + 1);\n\n return yield* decodeThreadId(tail).pipe(\n Effect.map((threadId): RouteTarget =>\n ownsThread(threadId) ? LOCAL : { _tag: \"foreign\", threadId },\n ),\n Effect.orElseSucceed(() => LOCAL),\n );\n });\n\nconst NoAdditionalPortFailure = Schema.Never;\nconst AbortPortFailure = Schema.Union([SettlementConflict, JoinedToHost]);\nconst AppendPortFailure = Schema.Union([ThreadNotMaterialized, AppendConflict, FenceRejected]);\n\n/**\n * The fail-fast refusal for any foreign operation OUTSIDE the closed route-capable subset\n * (plan §1.3): honesty over accidental distribution.\n */\nconst crossThreadLedgerError = (operation: string, target: string): LedgerError =>\n LedgerError.make({\n operation,\n message:\n `${operation} addressed to foreign Thread ${target} is not route-capable; the ` +\n \"closed cross-Object subset is admit, markReady, lookup, resolveAdmission, \" +\n \"requestAbort, and recordChildSettled. Every other ledger operation is lane-local by \" +\n \"construction and must execute inside the owning Thread's Durable Object.\",\n });\n\nconst crossThreadStoreError = (operation: string, target: string): ThreadStoreError =>\n ThreadStoreError.make({\n operation,\n message:\n `${operation} addressed to foreign Thread ${target} is not route-capable; the ` +\n \"closed cross-Object subset is materialize, append, read (paged), inspectTail, and \" +\n \"export. Observation and checkpoints are lane-local by construction and must execute \" +\n \"inside the owning Thread's Durable Object.\",\n });\n\nconst makeTransportCall = (transport: ThreadPortTransport[\"Service\"]) =>\n Effect.fn(\"DoPortRouting.transportCall\")(function* (target: ThreadId, call: PortRequest) {\n const encoded = yield* encodePortRequest(call).pipe(\n Effect.mapError((error) =>\n PortProtocolError.make({\n message: boundPortDiagnostic(`The port request could not be encoded: ${error.message}`),\n }),\n ),\n );\n\n const raw = yield* transport.call(target, encoded);\n\n return yield* decodePortResponse(raw).pipe(\n Effect.mapError((error) =>\n PortProtocolError.make({\n message: boundPortDiagnostic(`The port response could not be decoded: ${error.message}`),\n }),\n ),\n );\n });\n\ntype TransportCall = ReturnType<typeof makeTransportCall>;\n\nconst makeRoutedLedgerServices = Effect.fn(\"DoPortRouting.makeRoutedLedgerServices\")(function* (\n options: RoutedPortOptions,\n) {\n const local = yield* SubmissionLedger;\n const transport = yield* ThreadPortTransport;\n const transportCall: TransportCall = makeTransportCall(transport);\n const submissionTarget = routableSubmissionTarget(options.ownsThread);\n\n const routeFailure =\n (operation: string, target: string) =>\n (error: PortTransportError | PortProtocolError): LedgerError =>\n LedgerError.make({\n operation,\n message: boundPortDiagnostic(\n `Routed ${operation} to the Thread Object owning ${target} failed: ${error.message}`,\n ),\n cause: error,\n });\n\n /**\n * One routed ledger call: encode, deliver, decode, then narrow the uniform envelope to the\n * operation's own result and failure surface. A foreign `LedgerError` is always in-channel;\n * any failure outside the operation's declared surface — including protocol anomalies — is\n * folded into a `LedgerError` naming the anomaly instead of being erased or re-thrown raw.\n */\n const foreignLedgerCall = <ResultSchema extends Schema.Top, FailureSchema extends Schema.Top>(\n operation: string,\n target: ThreadId,\n call: PortRequest,\n resultSchema: ResultSchema,\n failureSchema: FailureSchema,\n ): Effect.Effect<ResultSchema[\"Type\"], FailureSchema[\"Type\"] | LedgerError> => {\n const isExpectedResult = Schema.is(resultSchema);\n const isExpectedFailure = Schema.is(failureSchema);\n\n return transportCall(target, call).pipe(\n Effect.mapError(routeFailure(operation, target)),\n Effect.flatMap(\n (response): Effect.Effect<ResultSchema[\"Type\"], FailureSchema[\"Type\"] | LedgerError> => {\n if (response._tag === \"PortFailed\") {\n const failure = response.failure;\n\n if (isExpectedFailure(failure)) return Effect.fail(failure);\n if (failure._tag === \"LedgerError\") return Effect.fail(failure);\n\n return Effect.fail(\n LedgerError.make({\n operation,\n message: boundPortDiagnostic(\n `The Thread Object owning ${target} answered ${operation} with the ` +\n `out-of-contract failure ${failure._tag}: ${failure.message}`,\n ),\n cause: failure,\n }),\n );\n }\n const result = response.result;\n\n if (!isExpectedResult(result)) {\n return Effect.fail(\n LedgerError.make({\n operation,\n message:\n `The Thread Object owning ${target} answered ${operation} with the ` +\n `mismatched result ${result._tag}.`,\n }),\n );\n }\n\n return Effect.succeed(result);\n },\n ),\n Effect.withSpan(\"DoPortRouting.foreignLedgerCall\", {\n attributes: { operation, target },\n }),\n );\n };\n\n /**\n * Routed `resolveAdmission` — where the S2 tri-state becomes real (plan §1.3): when the\n * owning Object cannot be reached, or its answer cannot be understood, the routed adapter\n * answers `AdmissionIndeterminate{reason}` and NEVER `NotAdmitted` — an unreachable\n * authority proves nothing, and only `NotAdmitted` permits an admission attempt (SUB-031).\n * A typed `LedgerError` answered BY the authority still fails typed: the authority was\n * reached and reported its own storage failure.\n */\n const resolveForeignAdmission = (\n target: ThreadId,\n request: SubmissionLookupByKey,\n ): Effect.Effect<\n | AdmissionIndeterminate\n | Extract<PortResult, { readonly _tag: \"LedgerResolveAdmissionResult\" }>[\"resolution\"],\n LedgerError\n > =>\n transportCall(target, LedgerResolveAdmissionCall.make({ request })).pipe(\n Effect.flatMap((response) => {\n if (response._tag === \"PortFailed\") {\n if (response.failure._tag === \"LedgerError\") return Effect.fail(response.failure);\n\n return Effect.succeed(\n AdmissionIndeterminate.make({\n reason: boundPortDiagnostic(\n `The Thread Object owning ${target} answered resolveAdmission with the ` +\n `out-of-contract failure ${response.failure._tag}: ${response.failure.message}`,\n ),\n }),\n );\n }\n if (response.result._tag !== \"LedgerResolveAdmissionResult\") {\n return Effect.succeed(\n AdmissionIndeterminate.make({\n reason: boundPortDiagnostic(\n `The Thread Object owning ${target} answered resolveAdmission with the ` +\n `mismatched result ${response.result._tag}.`,\n ),\n }),\n );\n }\n\n return Effect.succeed(response.result.resolution);\n }),\n Effect.catchTags({\n PortTransportError: (error) =>\n Effect.succeed(\n AdmissionIndeterminate.make({\n reason: boundPortDiagnostic(\n `The Thread Object owning ${target} is unreachable: ${error.message}`,\n ),\n }),\n ),\n PortProtocolError: (error) =>\n Effect.succeed(\n AdmissionIndeterminate.make({\n reason: boundPortDiagnostic(\n `The answer of the Thread Object owning ${target} could not be ` +\n `understood: ${error.message}`,\n ),\n }),\n ),\n }),\n Effect.withSpan(\"DoPortRouting.resolveForeignAdmission\", { attributes: { target } }),\n );\n\n const foreignLookupById = (\n operation: string,\n target: ThreadId,\n submissionId: SubmissionId,\n ): Effect.Effect<Option.Option<SubmissionSnapshot>, LedgerError> =>\n foreignLedgerCall(\n operation,\n target,\n LedgerLookupCall.make({ request: SubmissionLookupById.make({ submissionId }) }),\n LedgerLookupResult,\n NoAdditionalPortFailure,\n ).pipe(\n Effect.map((result) =>\n result.submission === undefined ? Option.none() : Option.some(result.submission),\n ),\n );\n\n /**\n * Enrich a LOCAL parent's recovery snapshot with the lane state of attached children whose\n * rows live in other Durable Objects (plan §1.3): markers first (the local facet already\n * consulted them), then a routed per-child `lookup` for any attached child that is neither\n * local nor marker-settled. A transport failure surfaces as `LedgerError` so the alarm\n * pass retries; the child's canonical Settlement remains the only authority (DUR-015).\n */\n const enrichChildAttachments = Effect.fn(\"DoPortRouting.enrichChildAttachments\")(function* (\n snapshot: RecoverySnapshot,\n ): Effect.fn.Return<RecoverySnapshot, LedgerError> {\n const operation = \"ledger load recovery snapshot\";\n\n const attachments = new Map(\n snapshot.childAttachments.map((attachment) => [attachment.childSubmissionId, attachment]),\n );\n\n let enriched = false;\n\n for (const reservation of snapshot.childReservations) {\n const childSubmissionId = reservation.childSubmissionId;\n\n if (childSubmissionId === undefined || attachments.has(childSubmissionId)) continue;\n const target = yield* submissionTarget(operation, childSubmissionId);\n\n // A local or opaque child identity was already answered authoritatively by the local\n // facet; absence there means the child admission never committed.\n if (target._tag !== \"foreign\") continue;\n const child = yield* foreignLookupById(operation, target.threadId, childSubmissionId);\n\n if (Option.isNone(child)) continue;\n attachments.set(\n childSubmissionId,\n ChildAttachmentSnapshot.make({\n toolCallId: reservation.parentToolCallId,\n childSubmissionId,\n childState: child.value.state,\n ...(child.value.settledOutcome === undefined\n ? {}\n : { childOutcome: child.value.settledOutcome }),\n }),\n );\n enriched = true;\n }\n if (!enriched) return snapshot;\n // Rebuild in reservation (parent Tool Call) order, the order the local facet documents.\n const ordered: Array<ChildAttachmentSnapshot> = [];\n\n for (const reservation of snapshot.childReservations) {\n if (reservation.childSubmissionId === undefined) continue;\n const attachment = attachments.get(reservation.childSubmissionId);\n\n if (attachment !== undefined) ordered.push(attachment);\n }\n\n return RecoverySnapshot.make({ ...snapshot, childAttachments: ordered });\n });\n\n const routed = SubmissionLedger.of({\n capabilities: local.capabilities,\n\n admit: (request) =>\n options.ownsThread(request.threadId)\n ? local.admit(request)\n : foreignLedgerCall(\n \"ledger admit\",\n request.threadId,\n LedgerAdmitCall.make({ request }),\n LedgerAdmitResult,\n Schema.Union([AdmissionConflict, AdmissionPolicyError]),\n ).pipe(Effect.map((reply) => reply.result)),\n\n markReady: (request) =>\n submissionTarget(\"ledger mark ready\", request.submissionId).pipe(\n Effect.flatMap((target) =>\n target._tag === \"local\"\n ? local.markReady(request)\n : foreignLedgerCall(\n \"ledger mark ready\",\n target.threadId,\n LedgerMarkReadyCall.make({ request }),\n LedgerMarkReadyResult,\n NoAdditionalPortFailure,\n ).pipe(Effect.asVoid),\n ),\n ),\n\n lookup: (request) =>\n request._tag === \"SubmissionLookupById\"\n ? submissionTarget(\"ledger lookup\", request.submissionId).pipe(\n Effect.flatMap((target) =>\n target._tag === \"local\"\n ? local.lookup(request)\n : foreignLookupById(\"ledger lookup\", target.threadId, request.submissionId),\n ),\n )\n : options.ownsThread(request.threadId)\n ? local.lookup(request)\n : foreignLedgerCall(\n \"ledger lookup\",\n request.threadId,\n LedgerLookupCall.make({ request }),\n LedgerLookupResult,\n NoAdditionalPortFailure,\n ).pipe(\n Effect.map((result) =>\n result.submission === undefined ? Option.none() : Option.some(result.submission),\n ),\n ),\n\n resolveAdmission: (request) =>\n options.ownsThread(request.threadId)\n ? local.resolveAdmission(request)\n : resolveForeignAdmission(request.threadId, request),\n\n requestAbort: (request) =>\n submissionTarget(\"ledger request abort\", request.submissionId).pipe(\n Effect.flatMap((target) =>\n target._tag === \"local\"\n ? local.requestAbort(request)\n : foreignLedgerCall(\n \"ledger request abort\",\n target.threadId,\n LedgerRequestAbortCall.make({ request }),\n LedgerRequestAbortResult,\n AbortPortFailure,\n ).pipe(Effect.map((reply) => reply.intent)),\n ),\n ),\n\n recordChildSettled: (request) =>\n submissionTarget(\"ledger record child settled\", request.parentSubmissionId).pipe(\n Effect.flatMap((target) =>\n target._tag === \"local\"\n ? local.recordChildSettled(request)\n : foreignLedgerCall(\n \"ledger record child settled\",\n target.threadId,\n LedgerRecordChildSettledCall.make({ request }),\n LedgerRecordChildSettledResult,\n NoAdditionalPortFailure,\n ).pipe(Effect.map((reply) => reply.outcome)),\n ),\n ),\n\n // Every operation below is lane-local by construction (plan §1.3): a foreign address is\n // an out-of-contract call and fails fast typed instead of being quietly distributed.\n claim: (request) =>\n options.ownsThread(request.threadId)\n ? local.claim(request)\n : Effect.fail(crossThreadLedgerError(\"ledger claim\", request.threadId)),\n\n claimJoining: (request) =>\n options.ownsThread(request.threadId)\n ? local.claimJoining(request)\n : Effect.fail(crossThreadLedgerError(\"ledger claim joining\", request.threadId)),\n\n renewOwnership: (request) =>\n submissionTarget(\"ledger renew ownership\", request.submissionId).pipe(\n Effect.flatMap((target) =>\n target._tag === \"local\"\n ? local.renewOwnership(request)\n : Effect.fail(crossThreadLedgerError(\"ledger renew ownership\", target.threadId)),\n ),\n ),\n\n releaseOwnership: (request) =>\n submissionTarget(\"ledger release ownership\", request.submissionId).pipe(\n Effect.flatMap((target) =>\n target._tag === \"local\"\n ? local.releaseOwnership(request)\n : Effect.fail(crossThreadLedgerError(\"ledger release ownership\", target.threadId)),\n ),\n ),\n\n markInputApplied: (request) =>\n submissionTarget(\"ledger mark input applied\", request.submissionId).pipe(\n Effect.flatMap((target) =>\n target._tag === \"local\"\n ? local.markInputApplied(request)\n : Effect.fail(crossThreadLedgerError(\"ledger mark input applied\", target.threadId)),\n ),\n ),\n\n reserveSettlement: (request) =>\n submissionTarget(\"ledger reserve settlement\", request.submissionId).pipe(\n Effect.flatMap((target) =>\n target._tag === \"local\"\n ? local.reserveSettlement(request)\n : Effect.fail(crossThreadLedgerError(\"ledger reserve settlement\", target.threadId)),\n ),\n ),\n\n finalizeSettlement: (request) =>\n submissionTarget(\"ledger finalize settlement\", request.submissionId).pipe(\n Effect.flatMap((target) =>\n target._tag === \"local\"\n ? local.finalizeSettlement(request)\n : Effect.fail(crossThreadLedgerError(\"ledger finalize settlement\", target.threadId)),\n ),\n ),\n\n markJoined: (request) =>\n submissionTarget(\"ledger mark joined\", request.submissionId).pipe(\n Effect.flatMap((target) =>\n target._tag === \"local\"\n ? local.markJoined(request)\n : Effect.fail(crossThreadLedgerError(\"ledger mark joined\", target.threadId)),\n ),\n ),\n\n revertJoining: (request) =>\n submissionTarget(\"ledger revert joining\", request.submissionId).pipe(\n Effect.flatMap((target) =>\n target._tag === \"local\"\n ? local.revertJoining(request)\n : Effect.fail(crossThreadLedgerError(\"ledger revert joining\", target.threadId)),\n ),\n ),\n\n suspend: (request) =>\n submissionTarget(\"ledger suspend\", request.submissionId).pipe(\n Effect.flatMap((target) =>\n target._tag === \"local\"\n ? local.suspend(request)\n : Effect.fail(crossThreadLedgerError(\"ledger suspend\", target.threadId)),\n ),\n ),\n\n recordApprovalDecision: (command) =>\n submissionTarget(\"ledger record approval decision\", command.submissionId).pipe(\n Effect.flatMap((target) =>\n target._tag === \"local\"\n ? local.recordApprovalDecision(command)\n : Effect.fail(\n crossThreadLedgerError(\"ledger record approval decision\", target.threadId),\n ),\n ),\n ),\n\n markUnknown: (request) =>\n submissionTarget(\"ledger mark unknown\", request.submissionId).pipe(\n Effect.flatMap((target) =>\n target._tag === \"local\"\n ? local.markUnknown(request)\n : Effect.fail(crossThreadLedgerError(\"ledger mark unknown\", target.threadId)),\n ),\n ),\n\n recordUnknownResolution: (command) =>\n submissionTarget(\"ledger record unknown resolution\", command.submissionId).pipe(\n Effect.flatMap((target) =>\n target._tag === \"local\"\n ? local.recordUnknownResolution(command)\n : Effect.fail(\n crossThreadLedgerError(\"ledger record unknown resolution\", target.threadId),\n ),\n ),\n ),\n\n reserveChildBudget: (request) =>\n submissionTarget(\"ledger reserve child budget\", request.parentSubmissionId).pipe(\n Effect.flatMap((target) =>\n target._tag === \"local\"\n ? local.reserveChildBudget(request)\n : Effect.fail(crossThreadLedgerError(\"ledger reserve child budget\", target.threadId)),\n ),\n ),\n\n // Reservation identities carry no Thread address; the reservation row lives in the\n // parent's own Object and these transitions are parent-lane-local by construction, so\n // they always execute on the local facet (which fails typed for an unknown row).\n attachChildToReservation: local.attachChildToReservation,\n beginChildBudgetRelease: local.beginChildBudgetRelease,\n releaseChildBudget: local.releaseChildBudget,\n\n // The local scan IS the whole worklist: one Thread per Object (durability §5).\n scanNonterminal: local.scanNonterminal,\n\n readAbortIntent: (request) =>\n submissionTarget(\"ledger read abort intent\", request.submissionId).pipe(\n Effect.flatMap((target) =>\n target._tag === \"local\"\n ? local.readAbortIntent(request)\n : Effect.fail(crossThreadLedgerError(\"ledger read abort intent\", target.threadId)),\n ),\n ),\n\n loadRecoverySnapshot: (request) =>\n submissionTarget(\"ledger load recovery snapshot\", request.submissionId).pipe(\n Effect.flatMap((target) =>\n target._tag === \"local\"\n ? local.loadRecoverySnapshot(request).pipe(Effect.flatMap(enrichChildAttachments))\n : Effect.fail(crossThreadLedgerError(\"ledger load recovery snapshot\", target.threadId)),\n ),\n ),\n });\n\n return Context.make(SubmissionLedger, routed);\n});\n\nconst makeRoutedStoreServices = Effect.fn(\"DoPortRouting.makeRoutedStoreServices\")(function* (\n options: RoutedPortOptions,\n) {\n const local = yield* ThreadStore;\n const checkpoints = local.checkpoints;\n const recoveryCheckpoints = local.recoveryCheckpoints;\n const transport = yield* ThreadPortTransport;\n const transportCall: TransportCall = makeTransportCall(transport);\n\n const routeFailure =\n (operation: string, target: string) =>\n (error: PortTransportError | PortProtocolError): ThreadStoreError =>\n ThreadStoreError.make({\n operation,\n message: boundPortDiagnostic(\n `Routed ${operation} to the Thread Object owning ${target} failed: ${error.message}`,\n ),\n cause: error,\n });\n\n /** The store twin of `foreignLedgerCall` with `ThreadStoreError` as the base error. */\n const foreignStoreCall = <ResultSchema extends Schema.Top, FailureSchema extends Schema.Top>(\n operation: string,\n target: ThreadId,\n call: PortRequest,\n resultSchema: ResultSchema,\n failureSchema: FailureSchema,\n ): Effect.Effect<ResultSchema[\"Type\"], FailureSchema[\"Type\"] | ThreadStoreError> => {\n const isExpectedResult = Schema.is(resultSchema);\n const isExpectedFailure = Schema.is(failureSchema);\n\n return transportCall(target, call).pipe(\n Effect.mapError(routeFailure(operation, target)),\n Effect.flatMap(\n (\n response,\n ): Effect.Effect<ResultSchema[\"Type\"], FailureSchema[\"Type\"] | ThreadStoreError> => {\n if (response._tag === \"PortFailed\") {\n const failure = response.failure;\n\n if (isExpectedFailure(failure)) return Effect.fail(failure);\n if (failure._tag === \"ThreadStoreError\") return Effect.fail(failure);\n\n return Effect.fail(\n ThreadStoreError.make({\n operation,\n message: boundPortDiagnostic(\n `The Thread Object owning ${target} answered ${operation} with the ` +\n `out-of-contract failure ${failure._tag}: ${failure.message}`,\n ),\n cause: failure,\n }),\n );\n }\n const result = response.result;\n\n if (!isExpectedResult(result)) {\n return Effect.fail(\n ThreadStoreError.make({\n operation,\n message:\n `The Thread Object owning ${target} answered ${operation} with the ` +\n `mismatched result ${result._tag}.`,\n }),\n );\n }\n\n return Effect.succeed(result);\n },\n ),\n Effect.withSpan(\"DoPortRouting.foreignStoreCall\", {\n attributes: { operation, target },\n }),\n );\n };\n\n const routed = ThreadStore.of({\n materialize: (request) =>\n options.ownsThread(request.threadId)\n ? local.materialize(request)\n : foreignStoreCall(\n \"thread materialize\",\n request.threadId,\n StoreMaterializeCall.make({ request }),\n StoreMaterializeResult,\n FenceRejected,\n ).pipe(Effect.asVoid),\n\n append: (request) =>\n options.ownsThread(request.threadId)\n ? local.append(request)\n : foreignStoreCall(\n \"thread append\",\n request.threadId,\n StoreAppendCall.make({ request }),\n StoreAppendResult,\n AppendPortFailure,\n ).pipe(Effect.map((reply) => reply.result)),\n\n read: (request) =>\n options.ownsThread(request.threadId)\n ? local.read(request)\n : Stream.unwrap(\n foreignStoreCall(\n \"thread read\",\n request.threadId,\n StoreReadPageCall.make({ request }),\n StoreReadPageResult,\n ThreadNotMaterialized,\n ).pipe(Effect.map((reply) => Stream.fromIterable(reply.records))),\n ),\n\n inspectTail: (request) =>\n options.ownsThread(request.threadId)\n ? local.inspectTail(request)\n : foreignStoreCall(\n \"thread inspect tail\",\n request.threadId,\n StoreInspectTailCall.make({ request }),\n StoreInspectTailResult,\n ThreadNotMaterialized,\n ).pipe(Effect.map((reply) => reply.tail)),\n\n export: (request) =>\n options.ownsThread(request.threadId)\n ? local.export(request)\n : foreignStoreCall(\n \"thread export\",\n request.threadId,\n StoreExportCall.make({ request }),\n StoreExportResult,\n ThreadNotMaterialized,\n ).pipe(Effect.map((reply) => reply.export)),\n\n // Observation and checkpoints are lane-local: the closed route-capable store subset\n // is materialize/append/read/inspectTail/export. Recovery cache misses can fall back\n // to those canonical reads, including when the cache belongs to a foreign Object.\n observe: (request) =>\n options.ownsThread(request.threadId)\n ? local.observe(request)\n : Stream.unwrap(Effect.fail(crossThreadStoreError(\"thread observe\", request.threadId))),\n\n ...(recoveryCheckpoints === undefined\n ? {}\n : {\n recoveryCheckpoints: {\n save: (request) =>\n options.ownsThread(request.checkpoint.threadId)\n ? recoveryCheckpoints.save(request)\n : Effect.fail(\n crossThreadStoreError(\n \"thread save recovery checkpoint\",\n request.checkpoint.threadId,\n ),\n ),\n load: (request) =>\n options.ownsThread(request.threadId)\n ? recoveryCheckpoints.load(request)\n : Effect.succeed(Option.none()),\n },\n }),\n ...(checkpoints === undefined\n ? {}\n : {\n checkpoints: {\n save: (request) =>\n options.ownsThread(request.checkpoint.threadId)\n ? checkpoints.save(request)\n : Effect.fail(\n crossThreadStoreError(\"thread save checkpoint\", request.checkpoint.threadId),\n ),\n load: (request) =>\n options.ownsThread(request.threadId)\n ? checkpoints.load(request)\n : Effect.fail(crossThreadStoreError(\"thread load checkpoint\", request.threadId)),\n },\n }),\n });\n\n return Context.make(ThreadStore, routed);\n});\n\n/**\n * Routing decorator over the LOCAL `SubmissionLedger` facet (plan §1.3): a request addressing\n * this Object's Thread executes locally; a route-capable request addressing another\n * Thread is Schema-encoded onto the `ThreadPortTransport` and executed by the\n * owning Object's local facet; any other foreign request fails fast typed. Provide the WP1\n * local facet (`submissionLedgerLayer`/`ledgerLayer`) and a transport to close it.\n */\nexport const routedSubmissionLedgerLayer = (\n options: RoutedPortOptions,\n): Layer.Layer<SubmissionLedger, never, SubmissionLedger | ThreadPortTransport> =>\n Layer.effectContext(makeRoutedLedgerServices(options));\n\n/**\n * Routing decorator over the LOCAL `ThreadStore` facet (plan §1.3): this-thread\n * requests execute locally; foreign materialize/append/read/inspectTail/export travel the\n * transport. Foreign recovery-cache loads return none for canonical replay; other foreign\n * checkpoint operations and observation fail fast typed.\n */\nexport const routedThreadStoreLayer = (\n options: RoutedPortOptions,\n): Layer.Layer<ThreadStore, never, ThreadStore | ThreadPortTransport> =>\n Layer.effectContext(makeRoutedStoreServices(options));\n\n// ---------------------------------------------------------------------------\n// Owner-side execution\n// ---------------------------------------------------------------------------\n\n/** Fold one port operation's typed failures into the uniform response envelope. */\nconst capture = <Failure extends PortFailure>(\n effect: Effect.Effect<PortResult, Failure>,\n): Effect.Effect<PortResponse> =>\n effect.pipe(\n Effect.map((result): PortResponse => PortSucceeded.make({ result })),\n Effect.catch((failure) => Effect.succeed<PortResponse>(PortFailed.make({ failure }))),\n );\n\n/**\n * Execute one decoded port request against THIS Object's LOCAL facets — the owner-side half\n * of the routed ports (plan §1.3). Callers must provide the WP1 local facets, never the\n * routed decorators: the routing layer already established that this Object owns the\n * addressed Thread, and re-routing here could bounce a request between Objects.\n * Failures never escape — every typed port failure becomes a `PortFailed` envelope that\n * re-decodes on the caller side.\n */\nexport const executePortRequest = Effect.fn(\"DoPortRouting.executePortRequest\")(function* (\n request: PortRequest,\n): Effect.fn.Return<PortResponse, never, SubmissionLedger | ThreadStore> {\n switch (request._tag) {\n case \"LedgerAdmit\": {\n const ledger = yield* SubmissionLedger;\n\n return yield* capture(\n ledger\n .admit(request.request)\n .pipe(Effect.map((result) => LedgerAdmitResult.make({ result }))),\n );\n }\n case \"LedgerMarkReady\": {\n const ledger = yield* SubmissionLedger;\n\n return yield* capture(\n ledger.markReady(request.request).pipe(Effect.map(() => LedgerMarkReadyResult.make({}))),\n );\n }\n case \"LedgerLookup\": {\n const ledger = yield* SubmissionLedger;\n\n return yield* capture(\n ledger\n .lookup(request.request)\n .pipe(\n Effect.map((submission) =>\n Option.isSome(submission)\n ? LedgerLookupResult.make({ submission: submission.value })\n : LedgerLookupResult.make({}),\n ),\n ),\n );\n }\n case \"LedgerResolveAdmission\": {\n const ledger = yield* SubmissionLedger;\n\n return yield* capture(\n ledger\n .resolveAdmission(request.request)\n .pipe(Effect.map((resolution) => LedgerResolveAdmissionResult.make({ resolution }))),\n );\n }\n case \"LedgerRequestAbort\": {\n const ledger = yield* SubmissionLedger;\n\n return yield* capture(\n ledger\n .requestAbort(request.request)\n .pipe(Effect.map((intent) => LedgerRequestAbortResult.make({ intent }))),\n );\n }\n case \"LedgerRecordChildSettled\": {\n const ledger = yield* SubmissionLedger;\n\n return yield* capture(\n ledger\n .recordChildSettled(request.request)\n .pipe(Effect.map((outcome) => LedgerRecordChildSettledResult.make({ outcome }))),\n );\n }\n case \"StoreMaterialize\": {\n const store = yield* ThreadStore;\n\n return yield* capture(\n store.materialize(request.request).pipe(Effect.map(() => StoreMaterializeResult.make({}))),\n );\n }\n case \"StoreAppend\": {\n const store = yield* ThreadStore;\n\n return yield* capture(\n store\n .append(request.request)\n .pipe(Effect.map((result) => StoreAppendResult.make({ result }))),\n );\n }\n case \"StoreReadPage\": {\n const store = yield* ThreadStore;\n\n return yield* capture(\n store.read(request.request).pipe(\n Stream.runCollect,\n Effect.map((records) => StoreReadPageResult.make({ records: [...records] })),\n ),\n );\n }\n case \"StoreInspectTail\": {\n const store = yield* ThreadStore;\n\n return yield* capture(\n store\n .inspectTail(request.request)\n .pipe(Effect.map((tail) => StoreInspectTailResult.make({ tail }))),\n );\n }\n case \"StoreExport\": {\n const store = yield* ThreadStore;\n\n return yield* capture(\n store\n .export(request.request)\n .pipe(Effect.map((threadExport) => StoreExportResult.make({ export: threadExport }))),\n );\n }\n }\n});\n\n/**\n * The last-resort wire fallback when even encoding a response fails: the literal encoded\n * form of `PortFailed(PortProtocolError)` — tagged classes of bounded strings encode to\n * exactly this shape, so no Schema round trip is needed to produce it.\n */\nconst encodedProtocolFailure = (message: string): unknown => ({\n _tag: \"PortFailed\",\n failure: { _tag: \"PortProtocolError\", message: boundPortDiagnostic(message) },\n});\n\n/**\n * The complete owner-side endpoint body for `portCall` (D-P6-3): decode the wire request,\n * execute it against this Object's LOCAL facets, and answer with the encoded response\n * envelope. Total by construction — a request that cannot be decoded, or a response that\n * cannot be encoded, answers `PortFailed(PortProtocolError)` instead of throwing, so the\n * transport never has to interpret exceptions as protocol answers.\n */\nexport const handleEncodedPortRequest = Effect.fn(\"DoPortRouting.handleEncodedPortRequest\")(\n function* (encoded: unknown): Effect.fn.Return<unknown, never, SubmissionLedger | ThreadStore> {\n const response = yield* decodePortRequest(encoded).pipe(\n Effect.flatMap(executePortRequest),\n Effect.catch((error) =>\n Effect.succeed<PortResponse>(\n PortFailed.make({\n failure: PortProtocolError.make({\n message: boundPortDiagnostic(\n `The port request could not be decoded: ${error.message}`,\n ),\n }),\n }),\n ),\n ),\n );\n\n return yield* encodePortResponse(response).pipe(\n Effect.catch((error) =>\n Effect.succeed(\n encodedProtocolFailure(`The port response could not be encoded: ${error.message}`),\n ),\n ),\n );\n },\n);\n"],"mappings":";;;;;;;;;;;;;;;AAiEA,MAAM,iBAAiB,sBAAsB,OAAO;AACpD,MAAM,iBAAiB,OAAO,oBAAoB,cAAc;;;;;;AAOhE,MAAM,oCAAoC;;AAG1C,MAAM,oBACJ;;;;;;;;AASF,IAAa,qBAAb,cAAwC,OAAO,YAAgC,CAAC,CAC9E,sBACA;CACE,QAAQ,O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