@systemfsoftware/agent-storage-cloudflare 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (101) hide show
  1. package/LICENSE +21 -0
  2. package/dist/DoMemoryStore-AaGtt8CZ.d.mts +29 -0
  3. package/dist/DoMemoryStore-DVun329p.mjs +67 -0
  4. package/dist/DoMemoryStore-DVun329p.mjs.map +1 -0
  5. package/dist/DoMemoryStore.d.mts +2 -0
  6. package/dist/DoMemoryStore.mjs +1 -0
  7. package/dist/DoMessageDeliveryStore-BvB6OPI1.mjs +34 -0
  8. package/dist/DoMessageDeliveryStore-BvB6OPI1.mjs.map +1 -0
  9. package/dist/DoMessageDeliveryStore-Cb-DNN5s.d.mts +16 -0
  10. package/dist/DoMessageDeliveryStore.d.mts +2 -0
  11. package/dist/DoMessageDeliveryStore.mjs +1 -0
  12. package/dist/DoScheduleStore-BiTgDvX1.d.mts +36 -0
  13. package/dist/DoScheduleStore-C7GkSReF.mjs +167 -0
  14. package/dist/DoScheduleStore-C7GkSReF.mjs.map +1 -0
  15. package/dist/DoScheduleStore.d.mts +2 -0
  16. package/dist/DoScheduleStore.mjs +1 -0
  17. package/dist/DoStorageConfig-BqezsbD6.mjs +43 -0
  18. package/dist/DoStorageConfig-BqezsbD6.mjs.map +1 -0
  19. package/dist/DoStorageConfig-CuB6ZOtX.d.mts +36 -0
  20. package/dist/DoStorageConfig.d.mts +2 -0
  21. package/dist/DoStorageConfig.mjs +1 -0
  22. package/dist/DoStorageError-C-F5Z_FZ.d.mts +82 -0
  23. package/dist/DoStorageError-DSQzuCb0.mjs +138 -0
  24. package/dist/DoStorageError-DSQzuCb0.mjs.map +1 -0
  25. package/dist/DoStorageError.d.mts +2 -0
  26. package/dist/DoStorageError.mjs +1 -0
  27. package/dist/DoStorageFailpoint-C7zLUULu.d.mts +19 -0
  28. package/dist/DoStorageFailpoint-WO3B_DQl.mjs +20 -0
  29. package/dist/DoStorageFailpoint-WO3B_DQl.mjs.map +1 -0
  30. package/dist/DoStorageFailpoint.d.mts +2 -0
  31. package/dist/DoStorageFailpoint.mjs +1 -0
  32. package/dist/DoStorageFailpointTesting.d.mts +21 -0
  33. package/dist/DoStorageFailpointTesting.mjs +18 -0
  34. package/dist/DoStorageFailpointTesting.mjs.map +1 -0
  35. package/dist/DoStorageVersion-BrolfBDS.mjs +7 -0
  36. package/dist/DoStorageVersion-BrolfBDS.mjs.map +1 -0
  37. package/dist/DoStorageVersion-D7CIxFc_.d.mts +8 -0
  38. package/dist/DoStorageVersion.d.mts +3 -0
  39. package/dist/DoStorageVersion.mjs +2 -0
  40. package/dist/DoSubmissionLedger-Oq5OstxL.mjs +1878 -0
  41. package/dist/DoSubmissionLedger-Oq5OstxL.mjs.map +1 -0
  42. package/dist/DoSubmissionLedger-tLjwidUn.d.mts +25 -0
  43. package/dist/DoSubmissionLedger.d.mts +2 -0
  44. package/dist/DoSubmissionLedger.mjs +1 -0
  45. package/dist/DoSubscriptionStore-BMJiFxt3.mjs +185 -0
  46. package/dist/DoSubscriptionStore-BMJiFxt3.mjs.map +1 -0
  47. package/dist/DoSubscriptionStore-zx6nfbbh.d.mts +25 -0
  48. package/dist/DoSubscriptionStore.d.mts +2 -0
  49. package/dist/DoSubscriptionStore.mjs +1 -0
  50. package/dist/DoThreadStore-2zTSfui-.d.mts +81 -0
  51. package/dist/DoThreadStore-CeYHcRR9.mjs +411 -0
  52. package/dist/DoThreadStore-CeYHcRR9.mjs.map +1 -0
  53. package/dist/DoThreadStore.d.mts +2 -0
  54. package/dist/DoThreadStore.mjs +5 -0
  55. package/dist/MemoryProtocol-CtCFYe4s.mjs +221 -0
  56. package/dist/MemoryProtocol-CtCFYe4s.mjs.map +1 -0
  57. package/dist/MemoryProtocol-DXV77CcJ.d.mts +38160 -0
  58. package/dist/MemoryProtocol.d.mts +2 -0
  59. package/dist/MemoryProtocol.mjs +1 -0
  60. package/dist/PortProtocol-4xvMyCgP.mjs +322 -0
  61. package/dist/PortProtocol-4xvMyCgP.mjs.map +1 -0
  62. package/dist/PortProtocol-DXuguAgD.d.mts +966 -0
  63. package/dist/PortProtocol.d.mts +2 -0
  64. package/dist/PortProtocol.mjs +1 -0
  65. package/dist/PortRouting-B9302ouX.mjs +683 -0
  66. package/dist/PortRouting-B9302ouX.mjs.map +1 -0
  67. package/dist/PortRouting-DsoI6soW.d.mts +105 -0
  68. package/dist/PortRouting.d.mts +2 -0
  69. package/dist/PortRouting.mjs +1 -0
  70. package/dist/do-journal-nPNEAjV5.mjs +769 -0
  71. package/dist/do-journal-nPNEAjV5.mjs.map +1 -0
  72. package/dist/index.d.mts +14 -0
  73. package/dist/index.mjs +14 -0
  74. package/dist/migrations-BRTvj8Ue.mjs +233 -0
  75. package/dist/migrations-BRTvj8Ue.mjs.map +1 -0
  76. package/dist/owned-state-DrOD9s0c.mjs +157 -0
  77. package/dist/owned-state-DrOD9s0c.mjs.map +1 -0
  78. package/dist/rolldown-runtime-D3KUYPsf.mjs +12 -0
  79. package/package.json +106 -3
  80. package/src/DoMemoryStore.ts +71 -0
  81. package/src/DoMessageDeliveryStore.ts +46 -0
  82. package/src/DoScheduleStore.ts +276 -0
  83. package/src/DoStorageConfig.ts +45 -0
  84. package/src/DoStorageError.ts +146 -0
  85. package/src/DoStorageFailpoint.ts +25 -0
  86. package/src/DoStorageFailpointTesting.ts +42 -0
  87. package/src/DoStorageVersion.ts +2 -0
  88. package/src/DoSubmissionLedger.ts +3980 -0
  89. package/src/DoSubscriptionStore.ts +331 -0
  90. package/src/DoThreadStore.ts +602 -0
  91. package/src/MemoryProtocol.ts +357 -0
  92. package/src/PortProtocol.ts +626 -0
  93. package/src/PortRouting.ts +1888 -0
  94. package/src/index.ts +13 -0
  95. package/src/internal/canonical-append.ts +15 -0
  96. package/src/internal/do-journal.ts +1449 -0
  97. package/src/internal/migrations.ts +395 -0
  98. package/src/internal/owned-state.ts +300 -0
  99. package/src/internal/prompt-checkpoint.ts +170 -0
  100. package/src/internal/storage-span.ts +54 -0
  101. package/README.md +0 -3
@@ -0,0 +1,1888 @@
1
+ import type { DurableRuntimeFailpoint } from '@systemfsoftware/agent/durable-failpoint'
2
+ import { LifecyclePublicationError } from '@systemfsoftware/agent/lifecycle-publication'
3
+ import { MessageDeliveryError, MessageDeliveryStore } from '@systemfsoftware/agent/message-delivery'
4
+ import {
5
+ type SettlementPublicationFailure,
6
+ type SettlementPublicationResult,
7
+ SettlementPublisher,
8
+ } from '@systemfsoftware/agent/settlement-publisher'
9
+ import {
10
+ AdmissionConflict,
11
+ AdmissionIndeterminate,
12
+ AdmissionPolicyError,
13
+ ChildAttachmentSnapshot,
14
+ JoinedToHost,
15
+ LedgerError,
16
+ OwnershipLost,
17
+ RecoverySnapshot,
18
+ SettlementConflict,
19
+ SubmissionLedger,
20
+ SubmissionLookupById,
21
+ type SubmissionLookupByKey,
22
+ type SubmissionSnapshot,
23
+ } from '@systemfsoftware/agent/submission-ledger'
24
+ import {
25
+ AppendConflict,
26
+ ThreadExportRejected,
27
+ ThreadMaterialization,
28
+ ThreadNotMaterialized,
29
+ ThreadReader,
30
+ ThreadStore,
31
+ ThreadStoreError,
32
+ } from '@systemfsoftware/agent/thread-store'
33
+ import { checkExportSource } from '@systemfsoftware/agent/thread-transfer'
34
+ import { WorkDiscoveryUnavailable } from '@systemfsoftware/agent/thread-work'
35
+ import type { WakeScheduler } from '@systemfsoftware/agent/wake-scheduler'
36
+ import { admitWorker, WorkerAdmissionFailure, WorkerAdmissionPort } from '@systemfsoftware/agent/worker-admission'
37
+ import * as Cause from 'effect/Cause'
38
+ import * as Clock from 'effect/Clock'
39
+ import * as Context from 'effect/Context'
40
+ import * as Effect from 'effect/Effect'
41
+ import * as Layer from 'effect/Layer'
42
+ import * as Option from 'effect/Option'
43
+ import * as Predicate from 'effect/Predicate'
44
+ import * as Schema from 'effect/Schema'
45
+ import * as Stream from 'effect/Stream'
46
+
47
+ import {
48
+ boundPortDiagnostic,
49
+ decodePortRequest,
50
+ decodePortResponse,
51
+ encodePortRequest,
52
+ encodePortResponse,
53
+ LedgerAdmitCall,
54
+ LedgerAdmitResult,
55
+ LedgerFundingOwnerCall,
56
+ LedgerFundingOwnerResult,
57
+ LedgerInspectWorkerCall,
58
+ LedgerInspectWorkerResult,
59
+ LedgerLookupCall,
60
+ LedgerLookupResult,
61
+ LedgerMarkReadyCall,
62
+ LedgerMarkReadyResult,
63
+ LedgerRecordChildSettledCall,
64
+ LedgerRecordChildSettledResult,
65
+ LedgerRequestAbortCall,
66
+ LedgerRequestAbortResult,
67
+ LedgerResolveAdmissionCall,
68
+ LedgerResolveAdmissionResult,
69
+ LedgerStopWorkerCall,
70
+ LedgerStopWorkerResult,
71
+ MessageDeliveryCompleteCall,
72
+ MessageDeliveryCompleteResult,
73
+ MessageDeliveryListCall,
74
+ MessageDeliveryListResult,
75
+ PortFailed,
76
+ type PortFailure,
77
+ PortProtocolError,
78
+ type PortRequest,
79
+ type PortRequestEnvelope,
80
+ type PortResponse,
81
+ type PortResult,
82
+ PortSucceeded,
83
+ SettlementPublishCall,
84
+ SettlementPublishResult,
85
+ StoreAppendCall,
86
+ StoreAppendResult,
87
+ StoreCountPeerMessagesCall,
88
+ StoreCountPeerMessagesResult,
89
+ StoreExportCall,
90
+ StoreExportResult,
91
+ StoreInspectTailCall,
92
+ StoreInspectTailResult,
93
+ StoreMaterializeCall,
94
+ StoreMaterializeResult,
95
+ StoreRangeArchiveCall,
96
+ StoreRangeArchiveResult,
97
+ StoreRangePageCall,
98
+ StoreRangePageResult,
99
+ StoreRangeSealCall,
100
+ StoreRangeSealResult,
101
+ StoreRangeVerifyCall,
102
+ StoreRangeVerifyResult,
103
+ StoreReadExecutionCall,
104
+ StoreReadExecutionResult,
105
+ StoreReadIdentityCall,
106
+ StoreReadIdentityResult,
107
+ StoreReadPageCall,
108
+ StoreReadPageResult,
109
+ StoreReadPromptCall,
110
+ StoreReadPromptResult,
111
+ StoreVerificationCall,
112
+ StoreVerificationResult,
113
+ StoreWorkerCapacityCall,
114
+ StoreWorkerCapacityResult,
115
+ StoreWorkPageCall,
116
+ StoreWorkPageResult,
117
+ StoreWorkRebuildCall,
118
+ StoreWorkRebuildResult,
119
+ WorkerAdmitCall,
120
+ WorkerAdmitResult,
121
+ } from './PortProtocol'
122
+
123
+ type ThreadId = ThreadMaterialization['threadId']
124
+ type SubmissionId = SubmissionSnapshot['submissionId']
125
+
126
+ const ThreadIdSchema = ThreadMaterialization.fields.threadId
127
+ const decodeThreadId = Schema.decodeUnknownEffect(ThreadIdSchema)
128
+
129
+ /** Owner-local maintenance scope; permits local inventory without global Object enumeration. */
130
+ export const CurrentNativeSource = Context.Reference<boolean>(
131
+ '@effect-agent/storage-cloudflare/CurrentNativeSource',
132
+ { defaultValue: () => false },
133
+ )
134
+
135
+ /**
136
+ * The ledger row bound routable Submission identities must respect (mirrors the local
137
+ * facet's `MAX_IDENTIFIER_LENGTH`; the minting side already refuses longer identities typed
138
+ * at admission, so a longer identity presented here cannot name any stored row).
139
+ */
140
+ const MAX_ROUTABLE_SUBMISSION_ID_LENGTH = 1_024
141
+
142
+ /** The `{uuidv7}` head of a DC-minted routable Submission identity. */
143
+ 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}$/
144
+
145
+ /**
146
+ * A transport could not deliver a port request to (or an answer from) the owning
147
+ * Thread's Durable Object. `retryable` carries the platform's own stub signal when one
148
+ * exists. This error never crosses the wire — it is the CALLER-side evidence that the
149
+ * authority was unreachable, which is exactly the case `AdmissionIndeterminate` was
150
+ * specified for (SUB-031).
151
+ */
152
+ export class PortTransportError extends Schema.TaggedError<PortTransportError>()(
153
+ 'PortTransportError',
154
+ {
155
+ target: Schema.String,
156
+ message: Schema.String,
157
+ retryable: Schema.optionalKey(Schema.Boolean),
158
+ cause: Schema.optionalKey(Schema.Defect()),
159
+ },
160
+ ) {}
161
+
162
+ const safeTransportDiagnostic = (cause: unknown): string => {
163
+ try {
164
+ const message = cause instanceof Error ? cause.message : cause
165
+
166
+ return boundPortDiagnostic(typeof message === 'string' ? message : String(message))
167
+ } catch {
168
+ return '[unavailable transport diagnostic]'
169
+ }
170
+ }
171
+
172
+ const transportRetryableSignal = (cause: unknown): boolean | undefined => {
173
+ if (!Predicate.isObjectKeyword(cause)) return undefined
174
+ try {
175
+ const signal = Reflect.get(cause, 'retryable')
176
+
177
+ return typeof signal === 'boolean' ? signal : undefined
178
+ } catch {
179
+ return undefined
180
+ }
181
+ }
182
+
183
+ /**
184
+ * Build a `PortTransportError` from an arbitrary thrown transport cause, preserving the
185
+ * platform stub's own `retryable` signal when present.
186
+ */
187
+ export const portTransportFailure = (target: string, cause: unknown): PortTransportError => {
188
+ const retryable = transportRetryableSignal(cause)
189
+
190
+ return PortTransportError.make({
191
+ target,
192
+ message: safeTransportDiagnostic(cause),
193
+ ...(retryable === undefined ? {} : { retryable }),
194
+ cause,
195
+ })
196
+ }
197
+
198
+ /**
199
+ * Delivery of Schema-encoded port envelopes to the Durable Object that owns a FOREIGN
200
+ * Thread (plan §1.3, D-P6-3). The shipped implementation (platform-cloudflare, WP3)
201
+ * calls the owner's `portCall` over native Durable Object JS RPC via
202
+ * `namespace.idFromName(threadId)`; the protocol is transport-agnostic and any carrier
203
+ * that moves the encoded envelopes verbatim satisfies this service. Implementations MUST
204
+ * surface every delivery problem as `PortTransportError` and must never fabricate an answer.
205
+ */
206
+ export class ThreadPortTransport extends Context.Service<
207
+ ThreadPortTransport,
208
+ {
209
+ readonly call: (
210
+ threadId: ThreadId,
211
+ request: PortRequestEnvelope,
212
+ ) => Effect.Effect<unknown, PortTransportError>
213
+ }
214
+ >()('@effect-agent/storage-cloudflare/ThreadPortTransport') {}
215
+
216
+ /** Construction options shared by both routed port Layers. */
217
+ export interface RoutedPortOptions {
218
+ /**
219
+ * Decide whether this physical owner stores the addressed logical Thread. Local
220
+ * requests use the same SQLite facets; foreign requests use the transport or fail
221
+ * fast typed. The predicate determines placement, never caller authorization.
222
+ */
223
+ readonly ownsThread: (threadId: ThreadId) => boolean
224
+ }
225
+
226
+ /** Where one port request must execute. */
227
+ type RouteTarget =
228
+ | { readonly _tag: 'local' }
229
+ | { readonly _tag: 'foreign'; readonly threadId: ThreadId }
230
+
231
+ const LOCAL: RouteTarget = { _tag: 'local' }
232
+
233
+ /**
234
+ * Parse a DC-minted routable Submission identity — `{uuidv7}:{threadId}`, split at the
235
+ * FIRST `:` because the Thread tail may itself contain colons (D-P6-5). This adapter
236
+ * minted the format at admission and is the ONLY component that parses it; identities that do
237
+ * not carry the minted shape (no separator, non-UUID head, empty tail) fall back to the local
238
+ * facet, which is the only authority this Object can consult without inventing an owner.
239
+ * Identities beyond the ledger's 1,024-character row bound fail typed: the minting side
240
+ * refused them at admission, so they cannot name any stored row anywhere.
241
+ */
242
+ const routableSubmissionTarget = (
243
+ ownsThread: RoutedPortOptions['ownsThread'],
244
+ ): (operation: string, submissionId: string) => Effect.Effect<RouteTarget, LedgerError> =>
245
+ (operation, submissionId) =>
246
+ Effect.suspend(() => {
247
+ if (submissionId.length > MAX_ROUTABLE_SUBMISSION_ID_LENGTH) {
248
+ return Effect.fail(
249
+ LedgerError.make({
250
+ operation,
251
+ message: `A Submission identity of ${submissionId.length} characters exceeds the ` +
252
+ `${MAX_ROUTABLE_SUBMISSION_ID_LENGTH}-character routable identity bound; admission ` +
253
+ 'refuses such identities, so it cannot name any stored row.',
254
+ }),
255
+ )
256
+ }
257
+ const separator = submissionId.indexOf(':')
258
+
259
+ if (separator === -1 || !UUID_HEAD_PATTERN.test(submissionId.slice(0, separator))) {
260
+ return Effect.succeed(LOCAL)
261
+ }
262
+
263
+ return decodeThreadId(submissionId.slice(separator + 1)).pipe(
264
+ Effect.match({
265
+ onFailure: () => LOCAL,
266
+ onSuccess: (threadId): RouteTarget => ownsThread(threadId) ? LOCAL : { _tag: 'foreign', threadId },
267
+ }),
268
+ )
269
+ })
270
+
271
+ /**
272
+ * Read a Submission only from this physical owner. Encoded foreign identities fail before
273
+ * storage access; opaque identities still use local lookup. A returned row must also belong
274
+ * to an owned Thread. This is placement validation, not caller authorization.
275
+ */
276
+ export const makeLocalSubmissionLookup = (
277
+ options: RoutedPortOptions,
278
+ ): (
279
+ submissionId: SubmissionId,
280
+ ) => Effect.Effect<Option.Option<SubmissionSnapshot>, LedgerError, SubmissionLedger> => {
281
+ const submissionTarget = routableSubmissionTarget(options.ownsThread)
282
+
283
+ return Effect.fnUntraced(function*(submissionId: SubmissionId) {
284
+ const operation = 'local Submission lookup'
285
+ const target = yield* submissionTarget(operation, submissionId)
286
+
287
+ if (target._tag === 'foreign') {
288
+ return yield* LedgerError.make({
289
+ operation,
290
+ message: 'The Submission belongs to another Thread Object',
291
+ })
292
+ }
293
+
294
+ const local = yield* SubmissionLedger
295
+ const submission = yield* local.lookup(SubmissionLookupById.make({ submissionId }))
296
+
297
+ if (Option.isSome(submission) && !options.ownsThread(submission.value.threadId)) {
298
+ return yield* LedgerError.make({
299
+ operation,
300
+ message: 'The stored Submission belongs to another Thread Object',
301
+ })
302
+ }
303
+
304
+ return submission
305
+ })
306
+ }
307
+
308
+ const NoAdditionalPortFailure = Schema.Never
309
+ const AbortPortFailure = Schema.Union([SettlementConflict, JoinedToHost])
310
+ const AppendPortFailure = Schema.Union([ThreadNotMaterialized, AppendConflict, OwnershipLost])
311
+
312
+ /**
313
+ * The fail-fast refusal for any foreign operation OUTSIDE the closed route-capable subset
314
+ * (plan §1.3): honesty over accidental distribution.
315
+ */
316
+ const crossThreadLedgerError = (operation: string, target: string): LedgerError =>
317
+ LedgerError.make({
318
+ operation,
319
+ message: `${operation} addressed to foreign Thread ${target} is not route-capable; the ` +
320
+ 'closed cross-Object subset is admit, markReady, lookup, resolveAdmission, ' +
321
+ 'requestAbort, and recordChildSettled. Every other ledger operation is lane-local by ' +
322
+ "construction and must execute inside the owning Thread's Durable Object.",
323
+ })
324
+
325
+ const crossThreadStoreError = (operation: string, target: string): ThreadStoreError =>
326
+ ThreadStoreError.make({
327
+ operation,
328
+ message: `${operation} addressed to foreign Thread ${target} is not route-capable; the ` +
329
+ 'closed cross-Object subset is materialize, append, read and readPrompt (paged), inspectTail, and ' +
330
+ 'export. Observation and Prompt checkpoints are lane-local by construction and must execute ' +
331
+ "inside the owning Thread's Durable Object.",
332
+ })
333
+
334
+ const makeTransportCall = (transport: ThreadPortTransport['Service']) =>
335
+ Effect.fnUntraced(function*(target: ThreadId, call: PortRequest) {
336
+ const encoded = yield* encodePortRequest(call).pipe(
337
+ Effect.mapError((error) =>
338
+ PortProtocolError.make({
339
+ message: boundPortDiagnostic(`The port request could not be encoded: ${error.message}`),
340
+ })
341
+ ),
342
+ )
343
+
344
+ const raw = yield* transport.call(target, encoded)
345
+
346
+ return yield* decodePortResponse(raw).pipe(
347
+ Effect.mapError((error) =>
348
+ PortProtocolError.make({
349
+ message: boundPortDiagnostic(`The port response could not be decoded: ${error.message}`),
350
+ })
351
+ ),
352
+ )
353
+ })
354
+
355
+ type TransportCall = ReturnType<typeof makeTransportCall>
356
+
357
+ const makeRoutedLedgerServices = Effect.fnUntraced(function*(options: RoutedPortOptions) {
358
+ const local = yield* SubmissionLedger
359
+ const transport = yield* ThreadPortTransport
360
+ const transportCall: TransportCall = makeTransportCall(transport)
361
+ const submissionTarget = routableSubmissionTarget(options.ownsThread)
362
+
363
+ const routeFailure =
364
+ (operation: string, target: string) => (error: PortTransportError | PortProtocolError): LedgerError =>
365
+ LedgerError.make({
366
+ operation,
367
+ message: boundPortDiagnostic(
368
+ `Routed ${operation} to the Thread Object owning ${target} failed: ${error.message}`,
369
+ ),
370
+ cause: error,
371
+ })
372
+
373
+ /**
374
+ * One routed ledger call: encode, deliver, decode, then narrow the uniform envelope to the
375
+ * operation's own result and failure surface. A foreign `LedgerError` is always in-channel;
376
+ * any failure outside the operation's declared surface — including protocol anomalies — is
377
+ * folded into a `LedgerError` naming the anomaly instead of being erased or re-thrown raw.
378
+ */
379
+ const foreignLedgerCall = <ResultSchema extends Schema.Top, FailureSchema extends Schema.Top>(
380
+ operation: string,
381
+ target: ThreadId,
382
+ call: PortRequest,
383
+ resultSchema: ResultSchema,
384
+ failureSchema: FailureSchema,
385
+ ): Effect.Effect<ResultSchema['Type'], FailureSchema['Type'] | LedgerError> => {
386
+ const isExpectedResult = Schema.is(resultSchema)
387
+ const isExpectedFailure = Schema.is(failureSchema)
388
+
389
+ return transportCall(target, call).pipe(
390
+ Effect.mapError(routeFailure(operation, target)),
391
+ Effect.flatMap(
392
+ (response): Effect.Effect<ResultSchema['Type'], FailureSchema['Type'] | LedgerError> => {
393
+ if (response._tag === 'PortFailed') {
394
+ const failure = response.failure
395
+
396
+ if (isExpectedFailure(failure)) return Effect.fail(failure)
397
+ if (failure._tag === 'LedgerError') return Effect.fail(failure)
398
+
399
+ return Effect.fail(
400
+ LedgerError.make({
401
+ operation,
402
+ message: boundPortDiagnostic(
403
+ `The Thread Object owning ${target} answered ${operation} with the ` +
404
+ `out-of-contract failure ${failure._tag}`,
405
+ ),
406
+ cause: failure,
407
+ }),
408
+ )
409
+ }
410
+ const result = response.result
411
+
412
+ if (!isExpectedResult(result)) {
413
+ return Effect.fail(
414
+ LedgerError.make({
415
+ operation,
416
+ message: `The Thread Object owning ${target} answered ${operation} with the ` +
417
+ `mismatched result ${result._tag}.`,
418
+ }),
419
+ )
420
+ }
421
+
422
+ return Effect.succeed(result)
423
+ },
424
+ ),
425
+ Effect.withSpan('DoPortRouting.foreignLedgerCall', {
426
+ attributes: { operation, target },
427
+ }),
428
+ )
429
+ }
430
+
431
+ /**
432
+ * Routed `resolveAdmission` — where the S2 tri-state becomes real (plan §1.3): when the
433
+ * owning Object cannot be reached, or its answer cannot be understood, the routed adapter
434
+ * answers `AdmissionIndeterminate{reason}` and NEVER `NotAdmitted` — an unreachable
435
+ * authority proves nothing, and only `NotAdmitted` permits an admission attempt (SUB-031).
436
+ * A typed `LedgerError` answered BY the authority still fails typed: the authority was
437
+ * reached and reported its own storage failure.
438
+ */
439
+ const resolveForeignAdmission = (
440
+ target: ThreadId,
441
+ request: SubmissionLookupByKey,
442
+ ): Effect.Effect<
443
+ | AdmissionIndeterminate
444
+ | Extract<PortResult, { readonly _tag: 'LedgerResolveAdmissionResult' }>['resolution'],
445
+ LedgerError
446
+ > =>
447
+ transportCall(target, LedgerResolveAdmissionCall.make({ request })).pipe(
448
+ Effect.flatMap((response) => {
449
+ if (response._tag === 'PortFailed') {
450
+ if (response.failure._tag === 'LedgerError') return Effect.fail(response.failure)
451
+
452
+ return Effect.succeed(
453
+ AdmissionIndeterminate.make({
454
+ reason: boundPortDiagnostic(
455
+ `The Thread Object owning ${target} answered resolveAdmission with the ` +
456
+ `out-of-contract failure ${response.failure._tag}: ${response.failure.message}`,
457
+ ),
458
+ }),
459
+ )
460
+ }
461
+ if (response.result._tag !== 'LedgerResolveAdmissionResult') {
462
+ return Effect.succeed(
463
+ AdmissionIndeterminate.make({
464
+ reason: boundPortDiagnostic(
465
+ `The Thread Object owning ${target} answered resolveAdmission with the ` +
466
+ `mismatched result ${response.result._tag}.`,
467
+ ),
468
+ }),
469
+ )
470
+ }
471
+
472
+ return Effect.succeed(response.result.resolution)
473
+ }),
474
+ Effect.catchTags({
475
+ PortTransportError: (error) =>
476
+ Effect.succeed(
477
+ AdmissionIndeterminate.make({
478
+ reason: boundPortDiagnostic(
479
+ `The Thread Object owning ${target} is unreachable: ${error.message}`,
480
+ ),
481
+ }),
482
+ ),
483
+ PortProtocolError: (error) =>
484
+ Effect.succeed(
485
+ AdmissionIndeterminate.make({
486
+ reason: boundPortDiagnostic(
487
+ `The answer of the Thread Object owning ${target} could not be ` +
488
+ `understood: ${error.message}`,
489
+ ),
490
+ }),
491
+ ),
492
+ }),
493
+ Effect.withSpan('DoPortRouting.resolveForeignAdmission', { attributes: { target } }),
494
+ )
495
+
496
+ const foreignLookupById = (
497
+ operation: string,
498
+ target: ThreadId,
499
+ submissionId: SubmissionId,
500
+ ): Effect.Effect<Option.Option<SubmissionSnapshot>, LedgerError> =>
501
+ foreignLedgerCall(
502
+ operation,
503
+ target,
504
+ LedgerLookupCall.make({ request: SubmissionLookupById.make({ submissionId }) }),
505
+ LedgerLookupResult,
506
+ NoAdditionalPortFailure,
507
+ ).pipe(
508
+ Effect.map((result) => result.submission === undefined ? Option.none() : Option.some(result.submission)),
509
+ )
510
+
511
+ /**
512
+ * Enrich a LOCAL parent's recovery snapshot with the lane state of attached children whose
513
+ * rows live in other Durable Objects (plan §1.3): markers first (the local facet already
514
+ * consulted them), then a routed per-child `lookup` for any attached child that is neither
515
+ * local nor marker-settled. A transport failure surfaces as `LedgerError` so the alarm
516
+ * pass retries; the child's canonical Settlement remains the only authority (DUR-015).
517
+ */
518
+ const enrichChildAttachments = Effect.fnUntraced(function*(
519
+ snapshot: RecoverySnapshot,
520
+ ): Effect.fn.Return<RecoverySnapshot, LedgerError> {
521
+ const operation = 'ledger load recovery snapshot'
522
+
523
+ const attachments = new Map(
524
+ snapshot.childAttachments.map((attachment) => [attachment.childSubmissionId, attachment]),
525
+ )
526
+
527
+ let enriched = false
528
+
529
+ for (const reservation of snapshot.childReservations) {
530
+ const childSubmissionId = reservation.childSubmissionId
531
+
532
+ if (childSubmissionId === undefined || attachments.has(childSubmissionId)) continue
533
+ const target = yield* submissionTarget(operation, childSubmissionId)
534
+
535
+ // A local or opaque child identity was already answered authoritatively by the local
536
+ // facet; absence there means the child admission never committed.
537
+ if (target._tag !== 'foreign') continue
538
+ const child = yield* foreignLookupById(operation, target.threadId, childSubmissionId)
539
+
540
+ if (Option.isNone(child)) continue
541
+ attachments.set(
542
+ childSubmissionId,
543
+ ChildAttachmentSnapshot.make({
544
+ toolCallId: reservation.parentToolCallId,
545
+ childSubmissionId,
546
+ childState: child.value.state,
547
+ ...(child.value.settledOutcome === undefined
548
+ ? {}
549
+ : { childOutcome: child.value.settledOutcome }),
550
+ }),
551
+ )
552
+ enriched = true
553
+ }
554
+ if (!enriched) return snapshot
555
+ // Rebuild in reservation (parent Tool Call) order, the order the local facet documents.
556
+ const ordered: Array<ChildAttachmentSnapshot> = []
557
+
558
+ for (const reservation of snapshot.childReservations) {
559
+ if (reservation.childSubmissionId === undefined) continue
560
+ const attachment = attachments.get(reservation.childSubmissionId)
561
+
562
+ if (attachment !== undefined) ordered.push(attachment)
563
+ }
564
+
565
+ return RecoverySnapshot.make({ ...snapshot, childAttachments: ordered })
566
+ })
567
+
568
+ const routed = SubmissionLedger.of({
569
+ capabilities: local.capabilities,
570
+
571
+ admit: (request, admissionOptions) =>
572
+ options.ownsThread(request.threadId)
573
+ ? local.admit(request, admissionOptions)
574
+ : foreignLedgerCall(
575
+ 'ledger admit',
576
+ request.threadId,
577
+ LedgerAdmitCall.make({ request }),
578
+ LedgerAdmitResult,
579
+ Schema.Union([AdmissionConflict, AdmissionPolicyError]),
580
+ ).pipe(Effect.map((reply) => reply.result)),
581
+
582
+ markReady: (request) =>
583
+ submissionTarget('ledger mark ready', request.submissionId).pipe(
584
+ Effect.flatMap((target) =>
585
+ target._tag === 'local'
586
+ ? local.markReady(request)
587
+ : foreignLedgerCall(
588
+ 'ledger mark ready',
589
+ target.threadId,
590
+ LedgerMarkReadyCall.make({ request }),
591
+ LedgerMarkReadyResult,
592
+ NoAdditionalPortFailure,
593
+ ).pipe(Effect.asVoid)
594
+ ),
595
+ ),
596
+
597
+ lookup: (request) =>
598
+ request._tag === 'SubmissionLookupById'
599
+ ? submissionTarget('ledger lookup', request.submissionId).pipe(
600
+ Effect.flatMap((target) =>
601
+ target._tag === 'local'
602
+ ? local.lookup(request)
603
+ : foreignLookupById('ledger lookup', target.threadId, request.submissionId)
604
+ ),
605
+ )
606
+ : options.ownsThread(request.threadId)
607
+ ? local.lookup(request)
608
+ : foreignLedgerCall(
609
+ 'ledger lookup',
610
+ request.threadId,
611
+ LedgerLookupCall.make({ request }),
612
+ LedgerLookupResult,
613
+ NoAdditionalPortFailure,
614
+ ).pipe(
615
+ Effect.map((result) => result.submission === undefined ? Option.none() : Option.some(result.submission)),
616
+ ),
617
+
618
+ resolveFundingOwner: (request) =>
619
+ (options.ownsThread(request.threadId)
620
+ ? local.resolveFundingOwner === undefined
621
+ ? Effect.fail(
622
+ LedgerError.make({
623
+ operation: 'resolve funding owner',
624
+ message: 'Native funding-owner lookup unavailable.',
625
+ }),
626
+ )
627
+ : local.resolveFundingOwner(request)
628
+ : foreignLedgerCall(
629
+ 'resolve funding owner',
630
+ request.threadId,
631
+ LedgerFundingOwnerCall.make({ request }),
632
+ LedgerFundingOwnerResult,
633
+ NoAdditionalPortFailure,
634
+ ).pipe(Effect.map((reply) => reply.funding))).pipe(
635
+ Effect.filterOrFail(
636
+ (funding) =>
637
+ funding.selected.submissionId === request.submissionId &&
638
+ funding.selected.threadId === request.threadId &&
639
+ funding.owner.threadId === request.threadId,
640
+ () =>
641
+ LedgerError.make({
642
+ operation: 'resolve funding owner',
643
+ message: 'Funding-owner response belongs to another input or Thread.',
644
+ }),
645
+ ),
646
+ ),
647
+
648
+ resolveAdmission: (request) =>
649
+ options.ownsThread(request.threadId)
650
+ ? local.resolveAdmission(request)
651
+ : resolveForeignAdmission(request.threadId, request),
652
+
653
+ inspectWorker: (threadId) =>
654
+ options.ownsThread(threadId)
655
+ ? local.inspectWorker === undefined
656
+ ? Effect.fail(
657
+ LedgerError.make({
658
+ operation: 'inspectWorker',
659
+ message: 'Worker inspection unavailable',
660
+ }),
661
+ )
662
+ : local.inspectWorker(threadId)
663
+ : foreignLedgerCall(
664
+ 'inspect worker',
665
+ threadId,
666
+ LedgerInspectWorkerCall.make({ request: { threadId } }),
667
+ LedgerInspectWorkerResult,
668
+ NoAdditionalPortFailure,
669
+ ).pipe(Effect.map((reply) => reply.state)),
670
+
671
+ stopWorker: (request) =>
672
+ options.ownsThread(request.threadId)
673
+ ? local.stopWorker === undefined
674
+ ? Effect.fail(
675
+ LedgerError.make({ operation: 'stopWorker', message: 'Worker stop unavailable' }),
676
+ )
677
+ : local.stopWorker(request)
678
+ : foreignLedgerCall(
679
+ 'ledger stop worker',
680
+ request.threadId,
681
+ LedgerStopWorkerCall.make({ request }),
682
+ LedgerStopWorkerResult,
683
+ NoAdditionalPortFailure,
684
+ ).pipe(Effect.map((reply) => reply.owned)),
685
+
686
+ requestAbort: (request) =>
687
+ submissionTarget('ledger request abort', request.submissionId).pipe(
688
+ Effect.flatMap((target) =>
689
+ target._tag === 'local'
690
+ ? local.requestAbort(request)
691
+ : foreignLedgerCall(
692
+ 'ledger request abort',
693
+ target.threadId,
694
+ LedgerRequestAbortCall.make({ request }),
695
+ LedgerRequestAbortResult,
696
+ AbortPortFailure,
697
+ ).pipe(Effect.map((reply) => reply.intent))
698
+ ),
699
+ ),
700
+
701
+ recordChildSettled: (request) =>
702
+ submissionTarget('ledger record child settled', request.parentSubmissionId).pipe(
703
+ Effect.flatMap((target) =>
704
+ target._tag === 'local'
705
+ ? local.recordChildSettled(request)
706
+ : foreignLedgerCall(
707
+ 'ledger record child settled',
708
+ target.threadId,
709
+ LedgerRecordChildSettledCall.make({ request }),
710
+ LedgerRecordChildSettledResult,
711
+ NoAdditionalPortFailure,
712
+ ).pipe(Effect.map((reply) => reply.outcome))
713
+ ),
714
+ ),
715
+
716
+ // Every operation below is lane-local by construction (plan §1.3): a foreign address is
717
+ // an out-of-contract call and fails fast typed instead of being quietly distributed.
718
+ selectHead: (request) =>
719
+ options.ownsThread(request.threadId)
720
+ ? local.selectHead(request)
721
+ : Effect.fail(crossThreadLedgerError('ledger claim', request.threadId)),
722
+
723
+ claimJoining: (request) =>
724
+ options.ownsThread(request.threadId)
725
+ ? local.claimJoining(request)
726
+ : Effect.fail(crossThreadLedgerError('ledger claim joining', request.threadId)),
727
+
728
+ ...(local.appendInput === undefined
729
+ ? {}
730
+ : {
731
+ appendInput: (
732
+ submissionId: SubmissionSnapshot['submissionId'],
733
+ request: Parameters<NonNullable<SubmissionLedger['Service']['appendInput']>>[1],
734
+ ) =>
735
+ options.ownsThread(request.threadId)
736
+ ? local.appendInput!(submissionId, request)
737
+ : Effect.fail(
738
+ ThreadStoreError.make({
739
+ operation: 'append original input',
740
+ message: 'Original input publication is lane-local',
741
+ }),
742
+ ),
743
+ }),
744
+
745
+ markInputApplied: (request) =>
746
+ submissionTarget('ledger mark input applied', request.submissionId).pipe(
747
+ Effect.flatMap((target) =>
748
+ target._tag === 'local'
749
+ ? local.markInputApplied(request)
750
+ : Effect.fail(crossThreadLedgerError('ledger mark input applied', target.threadId))
751
+ ),
752
+ ),
753
+
754
+ finalizeSettlement: (request) =>
755
+ submissionTarget('ledger finalize settlement', request.submissionId).pipe(
756
+ Effect.flatMap((target) =>
757
+ target._tag === 'local'
758
+ ? local.finalizeSettlement(request)
759
+ : Effect.fail(crossThreadLedgerError('ledger finalize settlement', target.threadId))
760
+ ),
761
+ ),
762
+
763
+ markJoined: (request) =>
764
+ submissionTarget('ledger mark joined', request.submissionId).pipe(
765
+ Effect.flatMap((target) =>
766
+ target._tag === 'local'
767
+ ? local.markJoined(request)
768
+ : Effect.fail(crossThreadLedgerError('ledger mark joined', target.threadId))
769
+ ),
770
+ ),
771
+
772
+ revertJoining: (request) =>
773
+ submissionTarget('ledger revert joining', request.submissionId).pipe(
774
+ Effect.flatMap((target) =>
775
+ target._tag === 'local'
776
+ ? local.revertJoining(request)
777
+ : Effect.fail(crossThreadLedgerError('ledger revert joining', target.threadId))
778
+ ),
779
+ ),
780
+
781
+ suspend: (request) =>
782
+ submissionTarget('ledger suspend', request.submissionId).pipe(
783
+ Effect.flatMap((target) =>
784
+ target._tag === 'local'
785
+ ? local.suspend(request)
786
+ : Effect.fail(crossThreadLedgerError('ledger suspend', target.threadId))
787
+ ),
788
+ ),
789
+
790
+ recordApprovalDecision: (command) =>
791
+ submissionTarget('ledger record approval decision', command.submissionId).pipe(
792
+ Effect.flatMap((target) =>
793
+ target._tag === 'local'
794
+ ? local.recordApprovalDecision(command)
795
+ : Effect.fail(
796
+ crossThreadLedgerError('ledger record approval decision', target.threadId),
797
+ )
798
+ ),
799
+ ),
800
+
801
+ markUnknown: (request) =>
802
+ submissionTarget('ledger mark unknown', request.submissionId).pipe(
803
+ Effect.flatMap((target) =>
804
+ target._tag === 'local'
805
+ ? local.markUnknown(request)
806
+ : Effect.fail(crossThreadLedgerError('ledger mark unknown', target.threadId))
807
+ ),
808
+ ),
809
+
810
+ recordUnknownResolution: (command) =>
811
+ submissionTarget('ledger record unknown resolution', command.submissionId).pipe(
812
+ Effect.flatMap((target) =>
813
+ target._tag === 'local'
814
+ ? local.recordUnknownResolution(command)
815
+ : Effect.fail(
816
+ crossThreadLedgerError('ledger record unknown resolution', target.threadId),
817
+ )
818
+ ),
819
+ ),
820
+
821
+ reserveChildBudget: (request) =>
822
+ submissionTarget('ledger reserve child budget', request.parentSubmissionId).pipe(
823
+ Effect.flatMap((target) =>
824
+ target._tag === 'local'
825
+ ? local.reserveChildBudget(request)
826
+ : Effect.fail(crossThreadLedgerError('ledger reserve child budget', target.threadId))
827
+ ),
828
+ ),
829
+
830
+ // Reservation identities carry no Thread address; the reservation row lives in the
831
+ // parent's own Object and these transitions are parent-lane-local by construction, so
832
+ // they always execute on the local facet (which fails typed for an unknown row).
833
+ attachChildToReservation: local.attachChildToReservation,
834
+ beginChildBudgetRelease: local.beginChildBudgetRelease,
835
+ releaseChildBudget: local.releaseChildBudget,
836
+
837
+ // The local scan IS the whole worklist: one Thread per Object (durability §5).
838
+ scanNonterminal: local.scanNonterminal,
839
+ ...(local.listNonterminal === undefined ? {} : { listNonterminal: local.listNonterminal }),
840
+
841
+ readAbortIntent: (request) =>
842
+ submissionTarget('ledger read abort intent', request.submissionId).pipe(
843
+ Effect.flatMap((target) =>
844
+ target._tag === 'local'
845
+ ? local.readAbortIntent(request)
846
+ : Effect.fail(crossThreadLedgerError('ledger read abort intent', target.threadId))
847
+ ),
848
+ ),
849
+
850
+ loadRecoverySnapshot: (request) =>
851
+ submissionTarget('ledger load recovery snapshot', request.submissionId).pipe(
852
+ Effect.flatMap((target) =>
853
+ target._tag === 'local'
854
+ ? local.loadRecoverySnapshot(request).pipe(Effect.flatMap(enrichChildAttachments))
855
+ : Effect.fail(crossThreadLedgerError('ledger load recovery snapshot', target.threadId))
856
+ ),
857
+ ),
858
+ })
859
+
860
+ return Context.make(SubmissionLedger, routed)
861
+ })
862
+
863
+ /** Route the data-only atomic publication to the same owner as its canonical Thread. */
864
+ export const routedSettlementPublisherLayer = (options: RoutedPortOptions) =>
865
+ Layer.effect(SettlementPublisher)(
866
+ Effect.gen(function*() {
867
+ const local = yield* SettlementPublisher
868
+ const call = makeTransportCall(yield* ThreadPortTransport)
869
+
870
+ const isFailure = Schema.is(
871
+ Schema.Union([
872
+ LedgerError,
873
+ OwnershipLost,
874
+ SettlementConflict,
875
+ ThreadStoreError,
876
+ ThreadNotMaterialized,
877
+ AppendConflict,
878
+ ]),
879
+ )
880
+
881
+ return SettlementPublisher.of({
882
+ publish: (request) => {
883
+ if (options.ownsThread(request.append.threadId)) return local.publish(request)
884
+
885
+ return call(request.append.threadId, SettlementPublishCall.make({ request })).pipe(
886
+ Effect.mapError((cause) =>
887
+ LedgerError.make({
888
+ operation: 'route settlement publication',
889
+ message: cause.message,
890
+ cause,
891
+ })
892
+ ),
893
+ Effect.flatMap(
894
+ (
895
+ response,
896
+ ): Effect.Effect<SettlementPublicationResult, SettlementPublicationFailure> => {
897
+ if (response._tag === 'PortFailed') {
898
+ return isFailure(response.failure)
899
+ ? Effect.fail(response.failure)
900
+ : Effect.fail(
901
+ LedgerError.make({
902
+ operation: 'route settlement publication',
903
+ message: 'Unexpected publication failure',
904
+ cause: response.failure,
905
+ }),
906
+ )
907
+ }
908
+
909
+ return response.result._tag === 'SettlementPublishResult'
910
+ ? Effect.succeed(response.result.result)
911
+ : Effect.fail(
912
+ LedgerError.make({
913
+ operation: 'route settlement publication',
914
+ message: 'Mismatched publication result',
915
+ }),
916
+ )
917
+ },
918
+ ),
919
+ )
920
+ },
921
+ })
922
+ }),
923
+ )
924
+
925
+ const makeRoutedStoreServices = Effect.fnUntraced(function*(options: RoutedPortOptions) {
926
+ const local = yield* ThreadStore
927
+ const promptCheckpoints = local.promptCheckpoints
928
+ const lifecyclePublications = local.lifecyclePublications
929
+ const acknowledgeMany = lifecyclePublications?.acknowledgeMany
930
+ const transport = yield* ThreadPortTransport
931
+ const transportCall: TransportCall = makeTransportCall(transport)
932
+
933
+ const routeFailure =
934
+ (operation: string, target: string) => (error: PortTransportError | PortProtocolError): ThreadStoreError =>
935
+ ThreadStoreError.make({
936
+ operation,
937
+ message: boundPortDiagnostic(
938
+ `Routed ${operation} to the Thread Object owning ${target} failed: ${error.message}`,
939
+ ),
940
+ cause: error,
941
+ })
942
+
943
+ /** The store twin of `foreignLedgerCall` with `ThreadStoreError` as the base error. */
944
+ const foreignStoreCall = <ResultSchema extends Schema.Top, FailureSchema extends Schema.Top>(
945
+ operation: string,
946
+ target: ThreadId,
947
+ call: PortRequest,
948
+ resultSchema: ResultSchema,
949
+ failureSchema: FailureSchema,
950
+ ): Effect.Effect<ResultSchema['Type'], FailureSchema['Type'] | ThreadStoreError> => {
951
+ const isExpectedResult = Schema.is(resultSchema)
952
+ const isExpectedFailure = Schema.is(failureSchema)
953
+
954
+ return transportCall(target, call).pipe(
955
+ Effect.mapError(routeFailure(operation, target)),
956
+ Effect.flatMap(
957
+ (
958
+ response,
959
+ ): Effect.Effect<ResultSchema['Type'], FailureSchema['Type'] | ThreadStoreError> => {
960
+ if (response._tag === 'PortFailed') {
961
+ const failure = response.failure
962
+
963
+ if (isExpectedFailure(failure)) return Effect.fail(failure)
964
+ if (failure._tag === 'ThreadStoreError') return Effect.fail(failure)
965
+
966
+ return Effect.fail(
967
+ ThreadStoreError.make({
968
+ operation,
969
+ message: boundPortDiagnostic(
970
+ `The Thread Object owning ${target} answered ${operation} with the ` +
971
+ `out-of-contract failure ${failure._tag}`,
972
+ ),
973
+ cause: failure,
974
+ }),
975
+ )
976
+ }
977
+ const result = response.result
978
+
979
+ if (!isExpectedResult(result)) {
980
+ return Effect.fail(
981
+ ThreadStoreError.make({
982
+ operation,
983
+ message: `The Thread Object owning ${target} answered ${operation} with the ` +
984
+ `mismatched result ${result._tag}.`,
985
+ }),
986
+ )
987
+ }
988
+
989
+ return Effect.succeed(result)
990
+ },
991
+ ),
992
+ Effect.withSpan('DoPortRouting.foreignStoreCall', {
993
+ attributes: { operation, target },
994
+ }),
995
+ )
996
+ }
997
+
998
+ const routed = ThreadStore.of({
999
+ readFreshRun: (request) =>
1000
+ options.ownsThread(request.threadId) && local.readFreshRun !== undefined
1001
+ ? local.readFreshRun(request)
1002
+ : Effect.succeedNone,
1003
+ readExecution: (request) =>
1004
+ options.ownsThread(request.threadId)
1005
+ ? local.readExecution(request)
1006
+ : foreignStoreCall(
1007
+ 'read execution',
1008
+ request.threadId,
1009
+ StoreReadExecutionCall.make({ request }),
1010
+ StoreReadExecutionResult,
1011
+ ThreadNotMaterialized,
1012
+ ).pipe(Effect.map((reply) => reply.checkpoint)),
1013
+ archives: {
1014
+ page: (request) =>
1015
+ options.ownsThread(request.threadId)
1016
+ ? local.archives === undefined
1017
+ ? Effect.fail(crossThreadStoreError('archive unavailable', request.threadId))
1018
+ : local.archives.page(request)
1019
+ : foreignStoreCall(
1020
+ 'archive page',
1021
+ request.threadId,
1022
+ StoreRangePageCall.make({ request }),
1023
+ StoreRangePageResult,
1024
+ ThreadNotMaterialized,
1025
+ ).pipe(Effect.map((reply) => reply.page)),
1026
+ seal: (request) =>
1027
+ options.ownsThread(request.threadId)
1028
+ ? local.archives === undefined
1029
+ ? Effect.fail(crossThreadStoreError('archive unavailable', request.threadId))
1030
+ : local.archives.seal(request)
1031
+ : foreignStoreCall(
1032
+ 'archive seal',
1033
+ request.threadId,
1034
+ StoreRangeSealCall.make({ request }),
1035
+ StoreRangeSealResult,
1036
+ ThreadNotMaterialized,
1037
+ ).pipe(Effect.map((reply) => reply.range)),
1038
+ archive: (request) =>
1039
+ options.ownsThread(request.threadId)
1040
+ ? local.archives === undefined
1041
+ ? Effect.fail(crossThreadStoreError('archive unavailable', request.threadId))
1042
+ : local.archives.archive(request)
1043
+ : foreignStoreCall(
1044
+ 'archive archive',
1045
+ request.threadId,
1046
+ StoreRangeArchiveCall.make({ request }),
1047
+ StoreRangeArchiveResult,
1048
+ ThreadNotMaterialized,
1049
+ ).pipe(Effect.map((reply) => reply.range)),
1050
+ verify: (request) =>
1051
+ options.ownsThread(request.threadId)
1052
+ ? local.archives === undefined
1053
+ ? Effect.fail(crossThreadStoreError('archive unavailable', request.threadId))
1054
+ : local.archives.verify(request)
1055
+ : foreignStoreCall(
1056
+ 'archive verify',
1057
+ request.threadId,
1058
+ StoreRangeVerifyCall.make({ request }),
1059
+ StoreRangeVerifyResult,
1060
+ ThreadNotMaterialized,
1061
+ ).pipe(Effect.map((reply) => reply.range)),
1062
+ },
1063
+ work: {
1064
+ isOnlyFreshAdmission: (request) => {
1065
+ const prove = local.work?.isOnlyFreshAdmission
1066
+
1067
+ return prove !== undefined && options.ownsThread(request.threadId)
1068
+ ? prove(request)
1069
+ : Effect.succeed(false)
1070
+ },
1071
+ threads: (request) =>
1072
+ Effect.flatMap(CurrentNativeSource, (nativeSource) =>
1073
+ nativeSource && local.work !== undefined
1074
+ ? local.work.threads(request)
1075
+ : Effect.fail(
1076
+ ThreadStoreError.make({
1077
+ operation: 'work threads',
1078
+ message: nativeSource
1079
+ ? 'The local Thread owner does not provide work inventory.'
1080
+ : "Global Thread enumeration is unsupported by the owner-local Durable Object namespace. Use the local owner's work storage.",
1081
+ }),
1082
+ )),
1083
+ page: (request) =>
1084
+ options.ownsThread(request.threadId)
1085
+ ? local.work === undefined
1086
+ ? Effect.fail(
1087
+ WorkDiscoveryUnavailable.make({
1088
+ threadId: request.threadId,
1089
+ reason: 'unsupported',
1090
+ }),
1091
+ )
1092
+ : local.work.page(request)
1093
+ : foreignStoreCall(
1094
+ 'work page',
1095
+ request.threadId,
1096
+ StoreWorkPageCall.make({ request }),
1097
+ StoreWorkPageResult,
1098
+ WorkDiscoveryUnavailable,
1099
+ ).pipe(Effect.map((reply) => reply.page)),
1100
+ rebuild: (request) =>
1101
+ options.ownsThread(request.threadId)
1102
+ ? local.work === undefined
1103
+ ? Effect.fail(
1104
+ WorkDiscoveryUnavailable.make({
1105
+ threadId: request.threadId,
1106
+ reason: 'unsupported',
1107
+ }),
1108
+ )
1109
+ : local.work.rebuild(request)
1110
+ : foreignStoreCall(
1111
+ 'rebuild work',
1112
+ request.threadId,
1113
+ StoreWorkRebuildCall.make({ request }),
1114
+ StoreWorkRebuildResult,
1115
+ WorkDiscoveryUnavailable,
1116
+ ).pipe(
1117
+ Effect.flatMap((reply) =>
1118
+ reply.progress.threadId === request.threadId
1119
+ ? Effect.succeed(reply.progress)
1120
+ : Effect.fail(
1121
+ ThreadStoreError.make({
1122
+ operation: 'rebuild work',
1123
+ message: 'The rebuild progress belongs to another Thread.',
1124
+ }),
1125
+ )
1126
+ ),
1127
+ ),
1128
+ },
1129
+ readWorkerCapacity: (request) =>
1130
+ (options.ownsThread(request.threadId)
1131
+ ? local.readWorkerCapacity === undefined
1132
+ ? Effect.fail(crossThreadStoreError('worker capacity unavailable', request.threadId))
1133
+ : local.readWorkerCapacity(request)
1134
+ : foreignStoreCall(
1135
+ 'worker capacity',
1136
+ request.threadId,
1137
+ StoreWorkerCapacityCall.make({ request }),
1138
+ StoreWorkerCapacityResult,
1139
+ ThreadNotMaterialized,
1140
+ ).pipe(Effect.map((reply) => reply.capacity))).pipe(
1141
+ Effect.filterOrFail(
1142
+ (capacity) =>
1143
+ capacity.threadId === request.threadId &&
1144
+ capacity.tailSequence === request.expectedTailSequence,
1145
+ () => crossThreadStoreError('worker capacity response mismatch', request.threadId),
1146
+ ),
1147
+ ),
1148
+ verification: {
1149
+ verify: (request) =>
1150
+ options.ownsThread(request.threadId)
1151
+ ? local.verification === undefined
1152
+ ? Effect.fail(crossThreadStoreError('verification unavailable', request.threadId))
1153
+ : local.verification.verify(request)
1154
+ : foreignStoreCall(
1155
+ 'thread verification',
1156
+ request.threadId,
1157
+ StoreVerificationCall.make({ request }),
1158
+ StoreVerificationResult,
1159
+ ThreadNotMaterialized,
1160
+ ).pipe(Effect.map((reply) => reply.report)),
1161
+ },
1162
+
1163
+ countPeerMessages: (request) =>
1164
+ options.ownsThread(request.threadId)
1165
+ ? local.countPeerMessages === undefined
1166
+ ? Effect.fail(crossThreadStoreError('peer count unavailable', request.threadId))
1167
+ : local.countPeerMessages(request)
1168
+ : foreignStoreCall(
1169
+ 'thread countPeerMessages',
1170
+ request.threadId,
1171
+ StoreCountPeerMessagesCall.make({ request }),
1172
+ StoreCountPeerMessagesResult,
1173
+ ThreadNotMaterialized,
1174
+ ).pipe(Effect.map((reply) => reply.count)),
1175
+
1176
+ materialize: (request) =>
1177
+ options.ownsThread(request.threadId)
1178
+ ? local.materialize(request)
1179
+ : foreignStoreCall(
1180
+ 'thread materialize',
1181
+ request.threadId,
1182
+ StoreMaterializeCall.make({ request }),
1183
+ StoreMaterializeResult,
1184
+ NoAdditionalPortFailure,
1185
+ ).pipe(Effect.asVoid),
1186
+
1187
+ append: (request) =>
1188
+ options.ownsThread(request.threadId)
1189
+ ? local.append(request)
1190
+ : foreignStoreCall(
1191
+ 'thread append',
1192
+ request.threadId,
1193
+ StoreAppendCall.make({ request }),
1194
+ StoreAppendResult,
1195
+ AppendPortFailure,
1196
+ ).pipe(Effect.map((reply) => reply.result)),
1197
+
1198
+ read: (request) =>
1199
+ options.ownsThread(request.threadId)
1200
+ ? local.read(request)
1201
+ : Stream.unwrap(
1202
+ foreignStoreCall(
1203
+ 'thread read',
1204
+ request.threadId,
1205
+ StoreReadPageCall.make({ request }),
1206
+ StoreReadPageResult,
1207
+ ThreadNotMaterialized,
1208
+ ).pipe(Effect.map((reply) => Stream.fromIterable(reply.records))),
1209
+ ),
1210
+
1211
+ readPrompt: (request) =>
1212
+ options.ownsThread(request.threadId)
1213
+ ? local.readPrompt(request)
1214
+ : Stream.unwrap(
1215
+ foreignStoreCall(
1216
+ 'thread read prompt',
1217
+ request.threadId,
1218
+ StoreReadPromptCall.make({ request }),
1219
+ StoreReadPromptResult,
1220
+ ThreadNotMaterialized,
1221
+ ).pipe(Effect.map((reply) => Stream.fromIterable(reply.records))),
1222
+ ),
1223
+
1224
+ inspectTail: (request) =>
1225
+ options.ownsThread(request.threadId)
1226
+ ? local.inspectTail(request)
1227
+ : foreignStoreCall(
1228
+ 'thread inspect tail',
1229
+ request.threadId,
1230
+ StoreInspectTailCall.make({ request }),
1231
+ StoreInspectTailResult,
1232
+ ThreadNotMaterialized,
1233
+ ).pipe(Effect.map((reply) => reply.tail)),
1234
+
1235
+ readIdentity: (request) =>
1236
+ options.ownsThread(request.threadId)
1237
+ ? local.readIdentity(request)
1238
+ : foreignStoreCall(
1239
+ 'thread read identity',
1240
+ request.threadId,
1241
+ StoreReadIdentityCall.make({ request }),
1242
+ StoreReadIdentityResult,
1243
+ ThreadNotMaterialized,
1244
+ ).pipe(
1245
+ Effect.flatMap((reply) =>
1246
+ reply.identity.threadId === request.threadId
1247
+ ? Effect.succeed(reply.identity)
1248
+ : Effect.fail(
1249
+ ThreadStoreError.make({
1250
+ operation: 'thread read identity',
1251
+ message: 'The identity snapshot belongs to another Thread.',
1252
+ }),
1253
+ )
1254
+ ),
1255
+ ),
1256
+
1257
+ export: (request) =>
1258
+ checkExportSource(request.threadId).pipe(
1259
+ Effect.andThen(
1260
+ options.ownsThread(request.threadId)
1261
+ ? local.export(request)
1262
+ : foreignStoreCall(
1263
+ 'thread export',
1264
+ request.threadId,
1265
+ StoreExportCall.make({ request }),
1266
+ StoreExportResult,
1267
+ Schema.Union([ThreadNotMaterialized, ThreadExportRejected]),
1268
+ ).pipe(Effect.map((reply) => reply.export)),
1269
+ ),
1270
+ ),
1271
+
1272
+ // Observation and Prompt checkpoints are lane-local: the closed route-capable store subset
1273
+ // includes exact-Thread work pages and rebuild, but no global Object enumeration.
1274
+ observe: (request) =>
1275
+ options.ownsThread(request.threadId)
1276
+ ? local.observe(request)
1277
+ : Stream.unwrap(Effect.fail(crossThreadStoreError('thread observe', request.threadId))),
1278
+
1279
+ // Publication obligations and operator retries stay with their native owner.
1280
+ ...(lifecyclePublications === undefined
1281
+ ? {}
1282
+ : {
1283
+ lifecyclePublications: {
1284
+ ...lifecyclePublications,
1285
+ ...(acknowledgeMany === undefined
1286
+ ? {}
1287
+ : {
1288
+ acknowledgeMany: (batches) =>
1289
+ batches.every((batch) => batch.every((publication) => options.ownsThread(publication.ownerThreadId)))
1290
+ ? acknowledgeMany(batches)
1291
+ : Effect.fail(LifecyclePublicationError.make({ reason: 'unavailable' })),
1292
+ }),
1293
+ acknowledge: (batch) =>
1294
+ batch.every((publication) => options.ownsThread(publication.ownerThreadId))
1295
+ ? lifecyclePublications.acknowledge(batch)
1296
+ : Effect.fail(LifecyclePublicationError.make({ reason: 'unavailable' })),
1297
+ claim: (batch, nowMillis, timeoutMillis) =>
1298
+ batch.every((publication) => options.ownsThread(publication.ownerThreadId))
1299
+ ? lifecyclePublications.claim(batch, nowMillis, timeoutMillis)
1300
+ : Effect.fail(LifecyclePublicationError.make({ reason: 'unavailable' })),
1301
+ retryParked: (ownerThreadId, nowMillis) =>
1302
+ options.ownsThread(ownerThreadId)
1303
+ ? lifecyclePublications.retryParked(ownerThreadId, nowMillis)
1304
+ : Effect.fail(LifecyclePublicationError.make({ reason: 'unavailable' })),
1305
+ },
1306
+ }),
1307
+ ...(promptCheckpoints === undefined
1308
+ ? {}
1309
+ : {
1310
+ promptCheckpoints: {
1311
+ save: (request) =>
1312
+ options.ownsThread(request.threadId)
1313
+ ? promptCheckpoints.save(request)
1314
+ : Effect.fail(crossThreadStoreError('save prompt checkpoint', request.threadId)),
1315
+ load: (request) =>
1316
+ options.ownsThread(request.threadId)
1317
+ ? promptCheckpoints.load(request)
1318
+ : Effect.fail(crossThreadStoreError('load prompt checkpoint', request.threadId)),
1319
+ },
1320
+ }),
1321
+ })
1322
+
1323
+ return Context.make(ThreadStore, routed)
1324
+ })
1325
+
1326
+ /**
1327
+ * Routing decorator over the LOCAL `SubmissionLedger` facet (plan §1.3): a request addressing
1328
+ * this Object's Thread executes locally; a route-capable request addressing another
1329
+ * Thread is Schema-encoded onto the `ThreadPortTransport` and executed by the
1330
+ * owning Object's local facet; any other foreign request fails fast typed. Provide the WP1
1331
+ * local facet (`submissionLedgerLayer`/`ledgerLayer`) and a transport to close it.
1332
+ */
1333
+ export const routedSubmissionLedgerLayer = (
1334
+ options: RoutedPortOptions,
1335
+ ): Layer.Layer<SubmissionLedger, never, SubmissionLedger | ThreadPortTransport> =>
1336
+ Layer.effectContext(makeRoutedLedgerServices(options))
1337
+
1338
+ /**
1339
+ * Routing decorator over the LOCAL `ThreadStore` facet (plan §1.3): this-thread
1340
+ * requests execute locally; foreign store reads, writes, and exact-Thread work pages/rebuild
1341
+ * travel the transport. Work enumeration stays local under CurrentNativeSource; global
1342
+ * enumeration, foreign Prompt checkpoints, and observation fail typed.
1343
+ */
1344
+ export const routedThreadStoreLayer = (
1345
+ options: RoutedPortOptions,
1346
+ ): Layer.Layer<ThreadStore | ThreadReader, never, ThreadStore | ThreadPortTransport> =>
1347
+ ThreadReader.layer().pipe(
1348
+ Layer.provideMerge(Layer.effectContext(makeRoutedStoreServices(options))),
1349
+ )
1350
+
1351
+ /** Route validated worker admission as one operation; source policy hooks stay at the caller. */
1352
+ export const routedWorkerAdmissionLayer = (options: RoutedPortOptions) =>
1353
+ Layer.effect(
1354
+ WorkerAdmissionPort,
1355
+ Effect.gen(function*() {
1356
+ const call = makeTransportCall(yield* ThreadPortTransport)
1357
+
1358
+ return WorkerAdmissionPort.of({
1359
+ admit: (request) =>
1360
+ options.ownsThread(request.threadId)
1361
+ ? admitWorker(request)
1362
+ : call(request.threadId, WorkerAdmitCall.make({ request })).pipe(
1363
+ Effect.mapError((cause) =>
1364
+ LedgerError.make({
1365
+ operation: 'admit worker',
1366
+ message: 'Worker admission transport failed',
1367
+ cause,
1368
+ })
1369
+ ),
1370
+ Effect.flatMap((response) => {
1371
+ if (
1372
+ response._tag === 'PortSucceeded' &&
1373
+ response.result._tag === 'WorkerAdmitResult'
1374
+ ) {
1375
+ return Effect.succeed(response.result.result)
1376
+ }
1377
+
1378
+ return Effect.fail(
1379
+ response._tag === 'PortFailed' &&
1380
+ Schema.is(WorkerAdmissionFailure)(response.failure)
1381
+ ? response.failure
1382
+ : LedgerError.make({
1383
+ operation: 'admit worker',
1384
+ message: 'Unexpected worker admission response',
1385
+ cause: response,
1386
+ }),
1387
+ )
1388
+ }),
1389
+ ),
1390
+ })
1391
+ }),
1392
+ )
1393
+
1394
+ /** Route the existing owner-scoped list; delivery mutations remain source local. */
1395
+ export const routedMessageDeliveryStoreLayer = (options: RoutedPortOptions) =>
1396
+ Layer.effect(
1397
+ MessageDeliveryStore,
1398
+ Effect.gen(function*() {
1399
+ const local = yield* MessageDeliveryStore
1400
+ const call = makeTransportCall(yield* ThreadPortTransport)
1401
+
1402
+ return MessageDeliveryStore.of({
1403
+ ...local,
1404
+ change: (key, change) =>
1405
+ options.ownsThread(key.ownerThreadId) || change._tag !== 'Complete'
1406
+ ? local.change(key, change)
1407
+ : call(
1408
+ key.ownerThreadId,
1409
+ MessageDeliveryCompleteCall.make({ key, completion: change }),
1410
+ ).pipe(
1411
+ Effect.catchCause((cause) =>
1412
+ Effect.failCause(
1413
+ Cause.map(cause, (failure) =>
1414
+ MessageDeliveryError.make({
1415
+ reason: 'storage',
1416
+ operation: 'route delivery completion',
1417
+ cause: failure,
1418
+ })),
1419
+ )
1420
+ ),
1421
+ Effect.flatMap((response) => {
1422
+ if (
1423
+ response._tag === 'PortSucceeded' &&
1424
+ response.result._tag === 'MessageDeliveryCompleteResult'
1425
+ ) {
1426
+ return Effect.succeed(response.result.record)
1427
+ }
1428
+ if (
1429
+ response._tag === 'PortFailed' &&
1430
+ (response.failure._tag === 'MessageDeliveryError' ||
1431
+ response.failure._tag === 'MessageDeliveryFailpointError')
1432
+ ) {
1433
+ return Effect.fail(response.failure)
1434
+ }
1435
+
1436
+ return Effect.fail(
1437
+ MessageDeliveryError.make({
1438
+ reason: 'storage',
1439
+ operation: 'route delivery completion',
1440
+ cause: response,
1441
+ }),
1442
+ )
1443
+ }),
1444
+ ),
1445
+ list: (request) =>
1446
+ options.ownsThread(request.ownerThreadId)
1447
+ ? local.list(request)
1448
+ : call(request.ownerThreadId, MessageDeliveryListCall.make({ request })).pipe(
1449
+ Effect.mapError(() =>
1450
+ MessageDeliveryError.make({
1451
+ reason: 'storage',
1452
+ operation: 'route delivery list',
1453
+ })
1454
+ ),
1455
+ Effect.flatMap((response) => {
1456
+ if (
1457
+ response._tag === 'PortSucceeded' &&
1458
+ response.result._tag === 'MessageDeliveryListResult'
1459
+ ) {
1460
+ return Effect.succeed(response.result.page)
1461
+ }
1462
+
1463
+ return Effect.fail(
1464
+ response._tag === 'PortFailed' &&
1465
+ response.failure._tag === 'MessageDeliveryError'
1466
+ ? response.failure
1467
+ : MessageDeliveryError.make({
1468
+ reason: 'storage',
1469
+ operation: 'route delivery list',
1470
+ }),
1471
+ )
1472
+ }),
1473
+ ),
1474
+ })
1475
+ }),
1476
+ )
1477
+
1478
+ // ---------------------------------------------------------------------------
1479
+ // Owner-side execution
1480
+ // ---------------------------------------------------------------------------
1481
+
1482
+ /** Fold one port operation's typed failures into the uniform response envelope. */
1483
+ const capture = <Failure extends PortFailure, R>(
1484
+ effect: Effect.Effect<PortResult, Failure, R>,
1485
+ ): Effect.Effect<PortResponse, never, R> =>
1486
+ effect.pipe(
1487
+ Effect.map((result): PortResponse => PortSucceeded.make({ result })),
1488
+ Effect.catch((failure) => Effect.succeed<PortResponse>(PortFailed.make({ failure }))),
1489
+ )
1490
+
1491
+ /**
1492
+ * Execute one decoded port request against THIS Object's LOCAL facets — the owner-side half
1493
+ * of the routed ports (plan §1.3). Callers must provide the WP1 local facets, never the
1494
+ * routed decorators: the routing layer already established that this Object owns the
1495
+ * addressed Thread, and re-routing here could bounce a request between Objects.
1496
+ * Failures never escape — every typed port failure becomes a `PortFailed` envelope that
1497
+ * re-decodes on the caller side.
1498
+ */
1499
+ export const executePortRequest = Effect.fnUntraced(function*(
1500
+ request: PortRequest,
1501
+ ): Effect.fn.Return<
1502
+ PortResponse,
1503
+ never,
1504
+ | SubmissionLedger
1505
+ | SettlementPublisher
1506
+ | ThreadStore
1507
+ | MessageDeliveryStore
1508
+ | WakeScheduler
1509
+ | DurableRuntimeFailpoint
1510
+ > {
1511
+ switch (request._tag) {
1512
+ case 'StoreRangePage': {
1513
+ const store = yield* ThreadStore
1514
+
1515
+ return yield* capture(
1516
+ store.archives === undefined
1517
+ ? crossThreadStoreError('archive unavailable', request.request.threadId)
1518
+ : store.archives
1519
+ .page(request.request)
1520
+ .pipe(Effect.map((page) => StoreRangePageResult.make({ page }))),
1521
+ )
1522
+ }
1523
+ case 'StoreRangeSeal': {
1524
+ const store = yield* ThreadStore
1525
+
1526
+ return yield* capture(
1527
+ store.archives === undefined
1528
+ ? crossThreadStoreError('archive unavailable', request.request.threadId)
1529
+ : store.archives
1530
+ .seal(request.request)
1531
+ .pipe(Effect.map((range) => StoreRangeSealResult.make({ range }))),
1532
+ )
1533
+ }
1534
+ case 'StoreRangeArchive': {
1535
+ const store = yield* ThreadStore
1536
+
1537
+ return yield* capture(
1538
+ store.archives === undefined
1539
+ ? crossThreadStoreError('archive unavailable', request.request.threadId)
1540
+ : store.archives
1541
+ .archive(request.request)
1542
+ .pipe(Effect.map((range) => StoreRangeArchiveResult.make({ range }))),
1543
+ )
1544
+ }
1545
+ case 'StoreRangeVerify': {
1546
+ const store = yield* ThreadStore
1547
+
1548
+ return yield* capture(
1549
+ store.archives === undefined
1550
+ ? crossThreadStoreError('archive unavailable', request.request.threadId)
1551
+ : store.archives
1552
+ .verify(request.request)
1553
+ .pipe(Effect.map((range) => StoreRangeVerifyResult.make({ range }))),
1554
+ )
1555
+ }
1556
+
1557
+ case 'StoreWorkPage': {
1558
+ const store = yield* ThreadStore
1559
+
1560
+ return yield* capture(
1561
+ store.work === undefined
1562
+ ? Effect.fail(
1563
+ WorkDiscoveryUnavailable.make({
1564
+ threadId: request.request.threadId,
1565
+ reason: 'unsupported',
1566
+ }),
1567
+ )
1568
+ : store.work
1569
+ .page(request.request)
1570
+ .pipe(Effect.map((page) => StoreWorkPageResult.make({ page }))),
1571
+ )
1572
+ }
1573
+ case 'StoreWorkRebuild': {
1574
+ const store = yield* ThreadStore
1575
+
1576
+ return yield* capture(
1577
+ store.work === undefined
1578
+ ? Effect.fail(
1579
+ WorkDiscoveryUnavailable.make({
1580
+ threadId: request.request.threadId,
1581
+ reason: 'unsupported',
1582
+ }),
1583
+ )
1584
+ : store.work
1585
+ .rebuild(request.request)
1586
+ .pipe(Effect.map((progress) => StoreWorkRebuildResult.make({ progress }))),
1587
+ )
1588
+ }
1589
+ case 'SettlementPublish': {
1590
+ const publisher = yield* SettlementPublisher
1591
+
1592
+ return yield* capture(
1593
+ publisher
1594
+ .publish(request.request)
1595
+ .pipe(Effect.map((result) => SettlementPublishResult.make({ result }))),
1596
+ )
1597
+ }
1598
+ case 'MessageDeliveryComplete': {
1599
+ const store = yield* MessageDeliveryStore
1600
+
1601
+ return yield* capture(
1602
+ store
1603
+ .change(request.key, {
1604
+ _tag: 'Complete',
1605
+ ...request.completion,
1606
+ nowMillis: yield* Clock.currentTimeMillis,
1607
+ })
1608
+ .pipe(Effect.map((record) => MessageDeliveryCompleteResult.make({ record }))),
1609
+ )
1610
+ }
1611
+ case 'WorkerAdmit':
1612
+ return yield* capture(
1613
+ admitWorker(request.request).pipe(
1614
+ Effect.map((result) => WorkerAdmitResult.make({ result })),
1615
+ ),
1616
+ )
1617
+ case 'MessageDeliveryList': {
1618
+ const store = yield* MessageDeliveryStore
1619
+
1620
+ return yield* capture(
1621
+ store
1622
+ .list(request.request)
1623
+ .pipe(Effect.map((page) => MessageDeliveryListResult.make({ page }))),
1624
+ )
1625
+ }
1626
+ case 'StoreCountPeerMessages': {
1627
+ const store = yield* ThreadStore
1628
+
1629
+ return yield* capture(
1630
+ store.countPeerMessages === undefined
1631
+ ? Effect.fail(crossThreadStoreError('native read unavailable', request.request.threadId))
1632
+ : store
1633
+ .countPeerMessages(request.request)
1634
+ .pipe(Effect.map((count) => StoreCountPeerMessagesResult.make({ count }))),
1635
+ )
1636
+ }
1637
+ case 'LedgerAdmit': {
1638
+ const ledger = yield* SubmissionLedger
1639
+
1640
+ return yield* capture(
1641
+ ledger
1642
+ .admit(request.request)
1643
+ .pipe(Effect.map((result) => LedgerAdmitResult.make({ result }))),
1644
+ )
1645
+ }
1646
+ case 'LedgerMarkReady': {
1647
+ const ledger = yield* SubmissionLedger
1648
+
1649
+ return yield* capture(
1650
+ ledger.markReady(request.request).pipe(Effect.map(() => LedgerMarkReadyResult.make({}))),
1651
+ )
1652
+ }
1653
+ case 'LedgerLookup': {
1654
+ const ledger = yield* SubmissionLedger
1655
+
1656
+ return yield* capture(
1657
+ ledger
1658
+ .lookup(request.request)
1659
+ .pipe(
1660
+ Effect.map((submission) =>
1661
+ Option.isSome(submission)
1662
+ ? LedgerLookupResult.make({ submission: submission.value })
1663
+ : LedgerLookupResult.make({})
1664
+ ),
1665
+ ),
1666
+ )
1667
+ }
1668
+ case 'LedgerFundingOwner': {
1669
+ const ledger = yield* SubmissionLedger
1670
+
1671
+ return yield* capture(
1672
+ ledger.resolveFundingOwner === undefined
1673
+ ? Effect.fail(
1674
+ LedgerError.make({
1675
+ operation: 'resolve funding owner',
1676
+ message: 'Native funding-owner lookup unavailable.',
1677
+ }),
1678
+ )
1679
+ : ledger
1680
+ .resolveFundingOwner(request.request)
1681
+ .pipe(Effect.map((funding) => LedgerFundingOwnerResult.make({ funding }))),
1682
+ )
1683
+ }
1684
+ case 'LedgerResolveAdmission': {
1685
+ const ledger = yield* SubmissionLedger
1686
+
1687
+ return yield* capture(
1688
+ ledger
1689
+ .resolveAdmission(request.request)
1690
+ .pipe(Effect.map((resolution) => LedgerResolveAdmissionResult.make({ resolution }))),
1691
+ )
1692
+ }
1693
+ case 'LedgerInspectWorker': {
1694
+ const ledger = yield* SubmissionLedger
1695
+
1696
+ return yield* capture(
1697
+ ledger.inspectWorker === undefined
1698
+ ? Effect.fail(
1699
+ LedgerError.make({
1700
+ operation: 'inspectWorker',
1701
+ message: 'Worker inspection unavailable',
1702
+ }),
1703
+ )
1704
+ : ledger
1705
+ .inspectWorker(request.request.threadId)
1706
+ .pipe(Effect.map((state) => LedgerInspectWorkerResult.make({ state }))),
1707
+ )
1708
+ }
1709
+ case 'LedgerStopWorker': {
1710
+ const ledger = yield* SubmissionLedger
1711
+
1712
+ return yield* capture(
1713
+ ledger.stopWorker === undefined
1714
+ ? Effect.fail(
1715
+ LedgerError.make({ operation: 'stopWorker', message: 'Worker stop unavailable' }),
1716
+ )
1717
+ : ledger
1718
+ .stopWorker(request.request)
1719
+ .pipe(Effect.map((owned) => LedgerStopWorkerResult.make({ owned }))),
1720
+ )
1721
+ }
1722
+ case 'LedgerRequestAbort': {
1723
+ const ledger = yield* SubmissionLedger
1724
+
1725
+ return yield* capture(
1726
+ ledger
1727
+ .requestAbort(request.request)
1728
+ .pipe(Effect.map((intent) => LedgerRequestAbortResult.make({ intent }))),
1729
+ )
1730
+ }
1731
+ case 'LedgerRecordChildSettled': {
1732
+ const ledger = yield* SubmissionLedger
1733
+
1734
+ return yield* capture(
1735
+ ledger
1736
+ .recordChildSettled(request.request)
1737
+ .pipe(Effect.map((outcome) => LedgerRecordChildSettledResult.make({ outcome }))),
1738
+ )
1739
+ }
1740
+ case 'StoreMaterialize': {
1741
+ const store = yield* ThreadStore
1742
+
1743
+ return yield* capture(
1744
+ store.materialize(request.request).pipe(Effect.map(() => StoreMaterializeResult.make({}))),
1745
+ )
1746
+ }
1747
+ case 'StoreAppend': {
1748
+ const store = yield* ThreadStore
1749
+
1750
+ return yield* capture(
1751
+ store
1752
+ .append(request.request)
1753
+ .pipe(Effect.map((result) => StoreAppendResult.make({ result }))),
1754
+ )
1755
+ }
1756
+ case 'StoreReadPage': {
1757
+ const store = yield* ThreadStore
1758
+
1759
+ return yield* capture(
1760
+ store.read(request.request).pipe(
1761
+ Stream.runCollect,
1762
+ Effect.map((records) => StoreReadPageResult.make({ records: [...records] })),
1763
+ ),
1764
+ )
1765
+ }
1766
+ case 'StoreReadPrompt': {
1767
+ const store = yield* ThreadStore
1768
+
1769
+ return yield* capture(
1770
+ store.readPrompt(request.request).pipe(
1771
+ Stream.runCollect,
1772
+ Effect.map((records) => StoreReadPromptResult.make({ records })),
1773
+ ),
1774
+ )
1775
+ }
1776
+ case 'StoreInspectTail': {
1777
+ const store = yield* ThreadStore
1778
+
1779
+ return yield* capture(
1780
+ store
1781
+ .inspectTail(request.request)
1782
+ .pipe(Effect.map((tail) => StoreInspectTailResult.make({ tail }))),
1783
+ )
1784
+ }
1785
+ case 'StoreReadExecution': {
1786
+ const store = yield* ThreadStore
1787
+
1788
+ return yield* capture(
1789
+ store
1790
+ .readExecution(request.request)
1791
+ .pipe(Effect.map((checkpoint) => StoreReadExecutionResult.make({ checkpoint }))),
1792
+ )
1793
+ }
1794
+ case 'StoreReadIdentity': {
1795
+ const store = yield* ThreadStore
1796
+
1797
+ return yield* capture(
1798
+ store
1799
+ .readIdentity(request.request)
1800
+ .pipe(Effect.map((identity) => StoreReadIdentityResult.make({ identity }))),
1801
+ )
1802
+ }
1803
+ case 'StoreWorkerCapacity': {
1804
+ const store = yield* ThreadStore
1805
+
1806
+ return yield* capture(
1807
+ store.readWorkerCapacity === undefined
1808
+ ? Effect.fail(
1809
+ crossThreadStoreError('worker capacity unavailable', request.request.threadId),
1810
+ )
1811
+ : store
1812
+ .readWorkerCapacity(request.request)
1813
+ .pipe(Effect.map((capacity) => StoreWorkerCapacityResult.make({ capacity }))),
1814
+ )
1815
+ }
1816
+ case 'StoreVerification': {
1817
+ const store = yield* ThreadStore
1818
+
1819
+ return yield* capture(
1820
+ store.verification === undefined
1821
+ ? Effect.fail(crossThreadStoreError('verification unavailable', request.request.threadId))
1822
+ : store.verification
1823
+ .verify(request.request)
1824
+ .pipe(Effect.map((report) => StoreVerificationResult.make({ report }))),
1825
+ )
1826
+ }
1827
+ case 'StoreExport': {
1828
+ const store = yield* ThreadStore
1829
+
1830
+ return yield* capture(
1831
+ store
1832
+ .export(request.request)
1833
+ .pipe(Effect.map((threadExport) => StoreExportResult.make({ export: threadExport }))),
1834
+ )
1835
+ }
1836
+ }
1837
+ })
1838
+
1839
+ /**
1840
+ * The last-resort wire fallback when even encoding a response fails: the literal encoded
1841
+ * form of `PortFailed(PortProtocolError)` — tagged classes of bounded strings encode to
1842
+ * exactly this shape, so no Schema round trip is needed to produce it.
1843
+ */
1844
+ const encodedProtocolFailure = (message: string): unknown => ({
1845
+ _tag: 'PortFailed',
1846
+ failure: { _tag: 'PortProtocolError', message: boundPortDiagnostic(message) },
1847
+ })
1848
+
1849
+ /**
1850
+ * The complete owner-side endpoint body for `portCall` (D-P6-3): decode the wire request,
1851
+ * execute it against this Object's LOCAL facets, and answer with the encoded response
1852
+ * envelope. Total by construction — a request that cannot be decoded, or a response that
1853
+ * cannot be encoded, answers `PortFailed(PortProtocolError)` instead of throwing, so the
1854
+ * transport never has to interpret exceptions as protocol answers.
1855
+ */
1856
+ export const handleEncodedPortRequest = Effect.fnUntraced(function*(
1857
+ encoded: unknown,
1858
+ ): Effect.fn.Return<
1859
+ unknown,
1860
+ never,
1861
+ | SubmissionLedger
1862
+ | SettlementPublisher
1863
+ | ThreadStore
1864
+ | MessageDeliveryStore
1865
+ | WakeScheduler
1866
+ | DurableRuntimeFailpoint
1867
+ > {
1868
+ const response = yield* decodePortRequest(encoded).pipe(
1869
+ Effect.flatMap(executePortRequest),
1870
+ Effect.catch((error) =>
1871
+ Effect.succeed<PortResponse>(
1872
+ PortFailed.make({
1873
+ failure: PortProtocolError.make({
1874
+ message: boundPortDiagnostic(`The port request could not be decoded: ${error.message}`),
1875
+ }),
1876
+ }),
1877
+ )
1878
+ ),
1879
+ )
1880
+
1881
+ return yield* encodePortResponse(response).pipe(
1882
+ Effect.catch((error) =>
1883
+ Effect.succeed(
1884
+ encodedProtocolFailure(`The port response could not be encoded: ${error.message}`),
1885
+ )
1886
+ ),
1887
+ )
1888
+ })