@yielded/agent-storage-cloudflare 0.1.0-beta.179 → 0.1.0-beta.182

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.
@@ -312,9 +312,9 @@ var PortSucceeded = class extends Schema.TaggedClass("@effect-agent/storage-clou
312
312
  var PortFailed = class extends Schema.TaggedClass("@effect-agent/storage-cloudflare/PortFailed")("PortFailed", { failure: PortFailure }) {};
313
313
  /** The uniform answer of one `portCall`: op-specific success or a re-decodable typed failure. */
314
314
  const PortResponse = Schema.Union([PortSucceeded, PortFailed]);
315
- const encodePortRequest = Schema.encodeEffect(PortRequest);
315
+ const encodePortRequest = (...args) => Schema.encodeEffect(PortRequest)(...args);
316
316
  const decodePortRequest = Schema.decodeUnknownEffect(PortRequest);
317
- const encodePortResponse = Schema.encodeEffect(PortResponse);
317
+ const encodePortResponse = (...args) => Schema.encodeEffect(PortResponse)(...args);
318
318
  const decodePortResponse = Schema.decodeUnknownEffect(PortResponse);
319
319
  //#endregion
320
320
  export { LedgerAdmitCall, LedgerAdmitResult, LedgerFundingOwnerCall, LedgerFundingOwnerResult, LedgerInspectWorkerCall, LedgerInspectWorkerResult, LedgerLookupCall, LedgerLookupResult, LedgerMarkReadyCall, LedgerMarkReadyResult, LedgerRecordChildSettledCall, LedgerRecordChildSettledResult, LedgerRequestAbortCall, LedgerRequestAbortResult, LedgerResolveAdmissionCall, LedgerResolveAdmissionResult, LedgerStopWorkerCall, LedgerStopWorkerResult, MAX_PORT_DIAGNOSTIC_LENGTH, MessageDeliveryCompleteCall, MessageDeliveryCompleteResult, MessageDeliveryListCall, MessageDeliveryListResult, PortFailed, PortFailure, PortProtocolError, PortRequest, PortResponse, PortResult, PortSucceeded, SettlementPublishCall, SettlementPublishResult, StoreAppendCall, StoreAppendResult, StoreCountPeerMessagesCall, StoreCountPeerMessagesResult, StoreExportCall, StoreExportResult, StoreInspectTailCall, StoreInspectTailResult, StoreMaterializeCall, StoreMaterializeResult, StoreRangeArchiveCall, StoreRangeArchiveResult, StoreRangePageCall, StoreRangePageResult, StoreRangeSealCall, StoreRangeSealResult, StoreRangeVerifyCall, StoreRangeVerifyResult, StoreReadExecutionCall, StoreReadExecutionResult, StoreReadIdentityCall, StoreReadIdentityResult, StoreReadPageCall, StoreReadPageResult, StoreReadPromptCall, StoreReadPromptResult, StoreVerificationCall, StoreVerificationResult, StoreWorkPageCall, StoreWorkPageResult, StoreWorkRebuildCall, StoreWorkRebuildResult, StoreWorkerCapacityCall, StoreWorkerCapacityResult, WorkerAdmitCall, WorkerAdmitResult, boundPortDiagnostic, decodePortRequest, decodePortResponse, encodePortRequest, encodePortResponse, PortProtocol_exports as t };
@@ -1 +1 @@
1
- {"version":3,"file":"PortProtocol.mjs","names":[],"sources":["../src/PortProtocol.ts"],"sourcesContent":["import { IntegrityReport } from \"@yielded/agent/admin\";\nimport { DurableRuntimeFailpointError } from \"@yielded/agent/durable-failpoint\";\nimport { ThreadId } from \"@yielded/agent/identifiers\";\nimport {\n MessageDeliveryError,\n MessageDeliveryFailpointError,\n MessageDeliveryKey,\n MessageDeliveryCompletion,\n MessageDeliveryRecord,\n MessageDeliveryPageRequest,\n MessageDeliveryPage,\n} from \"@yielded/agent/message-delivery\";\nimport { ReadEnvelope } from \"@yielded/agent/record-format\";\nimport { PromptRecordEnvelope } from \"@yielded/agent/records\";\nimport {\n SettlementPublication,\n SettlementPublicationResult,\n} from \"@yielded/agent/settlement-publisher\";\nimport {\n AbortCommand,\n WorkerStopCommand,\n WorkerLedgerState,\n AbortIntent,\n AdmissionConflict,\n AdmissionPolicyError,\n AdmissionRequest,\n AdmissionResolution,\n AdmissionResult,\n ChildSettledNotification,\n ChildSettledOutcome,\n JoinedToHost,\n LedgerError,\n OwnershipLost,\n MarkReadyRequest,\n SettlementConflict,\n SubmissionLookup,\n SubmissionLookupByKey,\n SubmissionSnapshot,\n FundingOwnerRequest,\n FundingOwner,\n} from \"@yielded/agent/submission-ledger\";\nimport {\n ThreadArchiveRange,\n ThreadArchiveRangePage,\n ThreadArchiveRangeRead,\n ThreadArchiveRangeRequest,\n ThreadArchiveRangeSeal,\n ThreadArchiveRangePublish,\n} from \"@yielded/agent/thread-archive-range\";\nimport {\n AppendConflict,\n ExecutionRead,\n ExecutionCheckpoint,\n AppendResult,\n ThreadExport,\n ThreadPeerCountRequest,\n ThreadExportRequest,\n ThreadIdentity,\n ThreadIdentityRequest,\n ThreadWorkerCapacityRequest,\n ThreadWorkerCapacity,\n ThreadVerificationRequest,\n ThreadMaterialization,\n ThreadNotMaterialized,\n ThreadExportRejected,\n ThreadReadRequest,\n ThreadPromptRead,\n ThreadStoreError,\n ThreadTail,\n ThreadTailRequest,\n AppendRequest,\n} from \"@yielded/agent/thread-store\";\nimport {\n ThreadWorkRequest,\n ThreadWorkPage,\n WorkIndexRebuildRequest,\n WorkIndexProgress,\n WorkDiscoveryUnavailable,\n} from \"@yielded/agent/thread-work\";\nimport { WorkerAdmissionRequest } from \"@yielded/agent/worker-admission\";\nimport { Schema, SchemaGetter } from \"effect\";\n\n/**\n * The cross-Durable-Object port protocol (plan §1.3, D-P6-3): Schema request/response/error\n * envelopes for the CLOSED route-capable subset of the thread ports. One Thread's\n * Durable Object executes another Thread's request against its OWN local facets; the\n * envelopes here are the only values that cross the Object boundary, and they are\n * transport-agnostic — native Durable Object JS RPC is the shipped carrier, fetch-with-JSON\n * the documented fallback, and both move the same Schema-encoded JSON.\n *\n * The closed subset is exactly the set of operations the durable coordinator performs against\n * a FOREIGN Thread (parent/child establishment, status checks, abort propagation,\n * child-settlement notification, and the child-thread store operations used by\n * establishment, `verifySettledChild`, and result projection):\n *\n * - worker: `admitWorker` (ledger admission, materialization, creation, origin, readiness);\n * - ledger: `admit`, `markReady`, `lookup`, `resolveAdmission`, `requestAbort`,\n * `recordChildSettled`;\n * - publisher: `publish`;\n * - store: `materialize`, `append`, `read` and `readPrompt` (one page), `readIdentity`,\n * `inspectTail`, `export`, `countPeerMessages`, `work.page`, `work.rebuild`.\n *\n * Every other port operation is lane-local and has no envelope. Foreign operations\n * fail fast and typed instead of widening the distributed surface.\n *\n * Failures cross the boundary as the `PortFailure` union and re-decode on the caller side to\n * the SAME tagged error types the local facet would have produced, so routed calls keep\n * error-tag fidelity. `cause` chains inside `LedgerError`/`ThreadStoreError` travel as\n * Schema defects and do not claim instance fidelity across Objects (plan §2.8).\n */\n\n/** Ceiling for protocol diagnostic strings; matches `AdmissionIndeterminate.reason`. */\nexport const MAX_PORT_DIAGNOSTIC_LENGTH = 4_096;\n\nconst BoundedDiagnostic = Schema.String.check(Schema.isMaxLength(MAX_PORT_DIAGNOSTIC_LENGTH));\n\n/** Truncate a diagnostic string to the protocol's bounded diagnostic length. */\nexport const boundPortDiagnostic = (value: string): string =>\n value.length > MAX_PORT_DIAGNOSTIC_LENGTH\n ? `${value.slice(0, MAX_PORT_DIAGNOSTIC_LENGTH - 3)}...`\n : value;\n\n/**\n * The envelope itself could not be honored: the receiving Object could not decode the\n * request, or a response could not be encoded/decoded. It never carries port semantics —\n * callers fold it into the operation's base error (`LedgerError`/`ThreadStoreError`),\n * except `resolveAdmission`, which folds it into `AdmissionIndeterminate` because a\n * non-answer is never proof of absence (SUB-031).\n */\nexport class PortProtocolError extends Schema.TaggedError<PortProtocolError>()(\n \"PortProtocolError\",\n {\n message: BoundedDiagnostic,\n },\n) {}\n\n// ---------------------------------------------------------------------------\n// Requests\n// ---------------------------------------------------------------------------\n\n/** One destination-owned worker admission, including canonical initialization and readiness. */\nexport class WorkerAdmitCall extends Schema.TaggedClass<WorkerAdmitCall>()(\"WorkerAdmit\", {\n request: WorkerAdmissionRequest,\n}) {}\n\n/** Routed `SubmissionLedger.admit` — child establishment admits INTO the owning Object. */\nexport class LedgerAdmitCall extends Schema.TaggedClass<LedgerAdmitCall>(\n \"@effect-agent/storage-cloudflare/LedgerAdmitCall\",\n)(\"LedgerAdmit\", {\n request: AdmissionRequest,\n}) {}\n\n/** Routed `SubmissionLedger.markReady` for a Submission owned by another Object. */\nexport class LedgerMarkReadyCall extends Schema.TaggedClass<LedgerMarkReadyCall>(\n \"@effect-agent/storage-cloudflare/LedgerMarkReadyCall\",\n)(\"LedgerMarkReady\", {\n request: MarkReadyRequest,\n}) {}\n\n/** Routed `SubmissionLedger.lookup` (by identity or scoped idempotency key). */\nexport class LedgerLookupCall extends Schema.TaggedClass<LedgerLookupCall>(\n \"@effect-agent/storage-cloudflare/LedgerLookupCall\",\n)(\"LedgerLookup\", {\n request: SubmissionLookup,\n}) {}\n\nexport class LedgerFundingOwnerCall extends Schema.TaggedClass<LedgerFundingOwnerCall>()(\n \"LedgerFundingOwner\",\n { request: FundingOwnerRequest },\n) {}\n\n/** Routed `SubmissionLedger.resolveAdmission` — the SUB-031 tri-state authority call. */\nexport class LedgerResolveAdmissionCall extends Schema.TaggedClass<LedgerResolveAdmissionCall>(\n \"@effect-agent/storage-cloudflare/LedgerResolveAdmissionCall\",\n)(\"LedgerResolveAdmission\", {\n request: SubmissionLookupByKey,\n}) {}\n\nexport class LedgerInspectWorkerCall extends Schema.TaggedClass<LedgerInspectWorkerCall>()(\n \"LedgerInspectWorker\",\n { request: Schema.Struct({ threadId: ThreadId }) },\n) {}\n\nexport class LedgerInspectWorkerResult extends Schema.TaggedClass<LedgerInspectWorkerResult>()(\n \"LedgerInspectWorkerResult\",\n { state: WorkerLedgerState },\n) {}\n\nexport class LedgerStopWorkerCall extends Schema.TaggedClass<LedgerStopWorkerCall>()(\n \"LedgerStopWorker\",\n { request: WorkerStopCommand },\n) {}\n\nexport class LedgerStopWorkerResult extends Schema.TaggedClass<LedgerStopWorkerResult>()(\n \"LedgerStopWorkerResult\",\n { owned: Schema.Natural },\n) {}\n\n/** Routed `SubmissionLedger.requestAbort` — abort propagation across Objects. */\nexport class LedgerRequestAbortCall extends Schema.TaggedClass<LedgerRequestAbortCall>(\n \"@effect-agent/storage-cloudflare/LedgerRequestAbortCall\",\n)(\"LedgerRequestAbort\", {\n request: AbortCommand,\n}) {}\n\n/** Routed `SubmissionLedger.recordChildSettled` — the child→parent durable notification. */\nexport class LedgerRecordChildSettledCall extends Schema.TaggedClass<LedgerRecordChildSettledCall>(\n \"@effect-agent/storage-cloudflare/LedgerRecordChildSettledCall\",\n)(\"LedgerRecordChildSettled\", {\n request: ChildSettledNotification,\n}) {}\n\n/** Publish canonical settlement intent at the owning Thread. */\nexport class SettlementPublishCall extends Schema.TaggedClass<SettlementPublishCall>()(\n \"SettlementPublish\",\n { request: SettlementPublication },\n) {}\n\nexport class SettlementPublishResult extends Schema.TaggedClass<SettlementPublishResult>()(\n \"SettlementPublishResult\",\n { result: SettlementPublicationResult },\n) {}\n\n/** Routed `ThreadStore.materialize` against the owning Object. */\nexport class StoreMaterializeCall extends Schema.TaggedClass<StoreMaterializeCall>(\n \"@effect-agent/storage-cloudflare/StoreMaterializeCall\",\n)(\"StoreMaterialize\", {\n request: ThreadMaterialization,\n}) {}\n\n/** Routed `ThreadStore.append` against the owning Object. */\nexport class StoreAppendCall extends Schema.TaggedClass<StoreAppendCall>(\n \"@effect-agent/storage-cloudflare/StoreAppendCall\",\n)(\"StoreAppend\", {\n request: AppendRequest,\n}) {}\n\n/** Routed one-page `ThreadStore.read`; the page bound is the request's own `limit`. */\nexport class StoreReadPageCall extends Schema.TaggedClass<StoreReadPageCall>(\n \"@effect-agent/storage-cloudflare/StoreReadPageCall\",\n)(\"StoreReadPage\", {\n request: ThreadReadRequest,\n}) {}\n\nexport class StoreReadPromptCall extends Schema.TaggedClass<StoreReadPromptCall>()(\n \"StoreReadPrompt\",\n { request: ThreadPromptRead },\n) {}\n\n/** Routed `ThreadStore.inspectTail` against the owning Object. */\nexport class StoreInspectTailCall extends Schema.TaggedClass<StoreInspectTailCall>(\n \"@effect-agent/storage-cloudflare/StoreInspectTailCall\",\n)(\"StoreInspectTail\", {\n request: ThreadTailRequest,\n}) {}\n\n/** Routed bounded `ThreadStore.readIdentity` against the owning Object. */\nexport class StoreReadIdentityCall extends Schema.TaggedClass<StoreReadIdentityCall>(\n \"@effect-agent/storage-cloudflare/StoreReadIdentityCall\",\n)(\"StoreReadIdentity\", {\n request: ThreadIdentityRequest,\n}) {}\n\nexport class StoreReadExecutionCall extends Schema.TaggedClass<StoreReadExecutionCall>()(\n \"StoreReadExecution\",\n { request: ExecutionRead },\n) {}\n\nexport class StoreWorkerCapacityCall extends Schema.TaggedClass<StoreWorkerCapacityCall>()(\n \"StoreWorkerCapacity\",\n { request: ThreadWorkerCapacityRequest },\n) {}\n\nexport class StoreVerificationCall extends Schema.TaggedClass<StoreVerificationCall>()(\n \"StoreVerification\",\n { request: ThreadVerificationRequest },\n) {}\n\n/** Routed `ThreadStore.export` against the owning Object. */\nexport class StoreExportCall extends Schema.TaggedClass<StoreExportCall>(\n \"@effect-agent/storage-cloudflare/StoreExportCall\",\n)(\"StoreExport\", {\n request: ThreadExportRequest,\n}) {}\n\nexport class StoreCountPeerMessagesCall extends Schema.TaggedClass<StoreCountPeerMessagesCall>()(\n \"StoreCountPeerMessages\",\n { request: ThreadPeerCountRequest },\n) {}\n\n/** Work maintenance is routed to the exact Thread's authoritative owner. */\nexport class StoreWorkPageCall extends Schema.TaggedClass<StoreWorkPageCall>()(\"StoreWorkPage\", {\n request: ThreadWorkRequest,\n}) {}\n\nexport class StoreWorkRebuildCall extends Schema.TaggedClass<StoreWorkRebuildCall>()(\n \"StoreWorkRebuild\",\n { request: WorkIndexRebuildRequest },\n) {}\n\nexport class MessageDeliveryListCall extends Schema.TaggedClass<MessageDeliveryListCall>()(\n \"MessageDeliveryList\",\n { request: MessageDeliveryPageRequest },\n) {}\n\nexport class MessageDeliveryCompleteCall extends Schema.TaggedClass<MessageDeliveryCompleteCall>()(\n \"MessageDeliveryComplete\",\n { key: MessageDeliveryKey, completion: MessageDeliveryCompletion },\n) {}\n\nexport class StoreRangePageCall extends Schema.TaggedClass<StoreRangePageCall>()(\"StoreRangePage\", {\n request: ThreadArchiveRangeRead,\n}) {}\n\nexport class StoreRangeSealCall extends Schema.TaggedClass<StoreRangeSealCall>()(\"StoreRangeSeal\", {\n request: ThreadArchiveRangeSeal,\n}) {}\n\nexport class StoreRangeArchiveCall extends Schema.TaggedClass<StoreRangeArchiveCall>()(\n \"StoreRangeArchive\",\n { request: ThreadArchiveRangePublish },\n) {}\n\nexport class StoreRangeVerifyCall extends Schema.TaggedClass<StoreRangeVerifyCall>()(\n \"StoreRangeVerify\",\n { request: ThreadArchiveRangeRequest },\n) {}\n\n/** Every request that may cross a Durable Object boundary — the CLOSED route-capable subset. */\nexport const PortRequest = Schema.Union([\n SettlementPublishCall,\n WorkerAdmitCall,\n MessageDeliveryListCall,\n MessageDeliveryCompleteCall,\n LedgerAdmitCall,\n LedgerMarkReadyCall,\n LedgerLookupCall,\n LedgerFundingOwnerCall,\n LedgerResolveAdmissionCall,\n LedgerRequestAbortCall,\n LedgerStopWorkerCall,\n LedgerInspectWorkerCall,\n LedgerRecordChildSettledCall,\n StoreRangePageCall,\n StoreRangeSealCall,\n StoreRangeArchiveCall,\n StoreRangeVerifyCall,\n StoreMaterializeCall,\n StoreAppendCall,\n StoreReadPageCall,\n StoreReadPromptCall,\n StoreInspectTailCall,\n StoreReadIdentityCall,\n StoreReadExecutionCall,\n StoreWorkerCapacityCall,\n StoreVerificationCall,\n StoreExportCall,\n StoreCountPeerMessagesCall,\n StoreWorkPageCall,\n StoreWorkRebuildCall,\n]);\n\nexport type PortRequest = typeof PortRequest.Type;\n\n/** The wire form of one port request (what a transport actually carries). */\nexport type PortRequestEnvelope = typeof PortRequest.Encoded;\n\n// ---------------------------------------------------------------------------\n// Results\n// ---------------------------------------------------------------------------\n\nexport class WorkerAdmitResult extends Schema.TaggedClass<WorkerAdmitResult>()(\n \"WorkerAdmitResult\",\n {\n result: AdmissionResult,\n },\n) {}\n\nexport class LedgerAdmitResult extends Schema.TaggedClass<LedgerAdmitResult>(\n \"@effect-agent/storage-cloudflare/LedgerAdmitResult\",\n)(\"LedgerAdmitResult\", {\n result: AdmissionResult,\n}) {}\n\nexport class LedgerMarkReadyResult extends Schema.TaggedClass<LedgerMarkReadyResult>(\n \"@effect-agent/storage-cloudflare/LedgerMarkReadyResult\",\n)(\"LedgerMarkReadyResult\", {}) {}\n\n/** `submission` is absent exactly when the lookup answered `Option.none`. */\nexport class LedgerLookupResult extends Schema.TaggedClass<LedgerLookupResult>(\n \"@effect-agent/storage-cloudflare/LedgerLookupResult\",\n)(\"LedgerLookupResult\", {\n submission: Schema.optionalKey(SubmissionSnapshot),\n}) {}\n\nexport class LedgerResolveAdmissionResult extends Schema.TaggedClass<LedgerResolveAdmissionResult>(\n \"@effect-agent/storage-cloudflare/LedgerResolveAdmissionResult\",\n)(\"LedgerResolveAdmissionResult\", {\n resolution: AdmissionResolution,\n}) {}\n\nexport class LedgerRequestAbortResult extends Schema.TaggedClass<LedgerRequestAbortResult>(\n \"@effect-agent/storage-cloudflare/LedgerRequestAbortResult\",\n)(\"LedgerRequestAbortResult\", {\n intent: AbortIntent,\n}) {}\n\nexport class LedgerRecordChildSettledResult extends Schema.TaggedClass<LedgerRecordChildSettledResult>(\n \"@effect-agent/storage-cloudflare/LedgerRecordChildSettledResult\",\n)(\"LedgerRecordChildSettledResult\", {\n outcome: ChildSettledOutcome,\n}) {}\n\nexport class StoreMaterializeResult extends Schema.TaggedClass<StoreMaterializeResult>(\n \"@effect-agent/storage-cloudflare/StoreMaterializeResult\",\n)(\"StoreMaterializeResult\", {}) {}\n\nexport class StoreAppendResult extends Schema.TaggedClass<StoreAppendResult>(\n \"@effect-agent/storage-cloudflare/StoreAppendResult\",\n)(\"StoreAppendResult\", {\n result: AppendResult,\n}) {}\n\n/** One page of canonical records, bounded by the request's `limit` (≤ 1,024). */\nexport class StoreReadPageResult extends Schema.TaggedClass<StoreReadPageResult>(\n \"@effect-agent/storage-cloudflare/StoreReadPageResult\",\n)(\"StoreReadPageResult\", {\n records: Schema.Array(ReadEnvelope).check(Schema.isMaxLength(1_024)),\n}) {}\n\nexport class StoreReadPromptResult extends Schema.TaggedClass<StoreReadPromptResult>()(\n \"StoreReadPromptResult\",\n {\n records: Schema.Array(PromptRecordEnvelope).check(Schema.isMaxLength(1_024)),\n },\n) {}\n\nexport class StoreInspectTailResult extends Schema.TaggedClass<StoreInspectTailResult>(\n \"@effect-agent/storage-cloudflare/StoreInspectTailResult\",\n)(\"StoreInspectTailResult\", {\n tail: ThreadTail,\n}) {}\n\nexport class StoreReadExecutionResult extends Schema.TaggedClass<StoreReadExecutionResult>()(\n \"StoreReadExecutionResult\",\n { checkpoint: Schema.OptionFromNullOr(ExecutionCheckpoint) },\n) {}\n\nexport class StoreReadIdentityResult extends Schema.TaggedClass<StoreReadIdentityResult>(\n \"@effect-agent/storage-cloudflare/StoreReadIdentityResult\",\n)(\"StoreReadIdentityResult\", {\n identity: Schema.Struct({\n ...ThreadIdentity.fields,\n records: Schema.Array(ReadEnvelope).check(Schema.isMaxLength(3)),\n }).pipe(\n Schema.decodeTo(Schema.toType(ThreadIdentity), {\n decode: SchemaGetter.transform((fields) => ThreadIdentity.make(fields)),\n encode: SchemaGetter.transform((identity) => identity),\n }),\n ),\n}) {}\n\nexport class LedgerFundingOwnerResult extends Schema.TaggedClass<LedgerFundingOwnerResult>()(\n \"LedgerFundingOwnerResult\",\n { funding: FundingOwner },\n) {}\n\nexport class StoreWorkerCapacityResult extends Schema.TaggedClass<StoreWorkerCapacityResult>()(\n \"StoreWorkerCapacityResult\",\n { capacity: ThreadWorkerCapacity },\n) {}\n\nexport class StoreVerificationResult extends Schema.TaggedClass<StoreVerificationResult>()(\n \"StoreVerificationResult\",\n { report: IntegrityReport },\n) {}\n\nexport class StoreExportResult extends Schema.TaggedClass<StoreExportResult>(\n \"@effect-agent/storage-cloudflare/StoreExportResult\",\n)(\"StoreExportResult\", {\n export: ThreadExport,\n}) {}\n\nexport class StoreCountPeerMessagesResult extends Schema.TaggedClass<StoreCountPeerMessagesResult>()(\n \"StoreCountPeerMessagesResult\",\n { count: Schema.Int.check(Schema.isBetween({ minimum: 0, maximum: 1000 })) },\n) {}\n\nexport class StoreWorkPageResult extends Schema.TaggedClass<StoreWorkPageResult>()(\n \"StoreWorkPageResult\",\n { page: ThreadWorkPage },\n) {}\n\nexport class StoreWorkRebuildResult extends Schema.TaggedClass<StoreWorkRebuildResult>()(\n \"StoreWorkRebuildResult\",\n { progress: WorkIndexProgress },\n) {}\n\nexport class MessageDeliveryListResult extends Schema.TaggedClass<MessageDeliveryListResult>()(\n \"MessageDeliveryListResult\",\n { page: MessageDeliveryPage },\n) {}\n\nexport class MessageDeliveryCompleteResult extends Schema.TaggedClass<MessageDeliveryCompleteResult>()(\n \"MessageDeliveryCompleteResult\",\n { record: MessageDeliveryRecord },\n) {}\n\nexport class StoreRangePageResult extends Schema.TaggedClass<StoreRangePageResult>()(\n \"StoreRangePageResult\",\n { page: ThreadArchiveRangePage },\n) {}\n\nexport class StoreRangeSealResult extends Schema.TaggedClass<StoreRangeSealResult>()(\n \"StoreRangeSealResult\",\n { range: Schema.Option(ThreadArchiveRange) },\n) {}\n\nexport class StoreRangeArchiveResult extends Schema.TaggedClass<StoreRangeArchiveResult>()(\n \"StoreRangeArchiveResult\",\n { range: ThreadArchiveRange },\n) {}\n\nexport class StoreRangeVerifyResult extends Schema.TaggedClass<StoreRangeVerifyResult>()(\n \"StoreRangeVerifyResult\",\n { range: ThreadArchiveRange },\n) {}\n\n/** Every successful routed result. Callers narrow by the tag their request implies. */\nexport const PortResult = Schema.Union([\n SettlementPublishResult,\n WorkerAdmitResult,\n MessageDeliveryListResult,\n MessageDeliveryCompleteResult,\n LedgerAdmitResult,\n LedgerMarkReadyResult,\n LedgerLookupResult,\n LedgerFundingOwnerResult,\n LedgerResolveAdmissionResult,\n LedgerRequestAbortResult,\n LedgerStopWorkerResult,\n LedgerInspectWorkerResult,\n LedgerRecordChildSettledResult,\n StoreRangePageResult,\n StoreRangeSealResult,\n StoreRangeArchiveResult,\n StoreRangeVerifyResult,\n StoreMaterializeResult,\n StoreAppendResult,\n StoreReadPageResult,\n StoreReadPromptResult,\n StoreInspectTailResult,\n StoreReadIdentityResult,\n StoreReadExecutionResult,\n StoreWorkerCapacityResult,\n StoreVerificationResult,\n StoreExportResult,\n StoreCountPeerMessagesResult,\n StoreWorkPageResult,\n StoreWorkRebuildResult,\n]);\n\nexport type PortResult = typeof PortResult.Type;\n\n// ---------------------------------------------------------------------------\n// Failures and the response envelope\n// ---------------------------------------------------------------------------\n\n/**\n * Every typed failure a route-capable operation can produce on its owning Object, plus the\n * protocol's own `PortProtocolError`. Members re-decode to the SAME tagged classes the\n * thread ports declare, so a routed caller observes identical error tags and fields.\n */\nexport const PortFailure = Schema.Union([\n OwnershipLost,\n DurableRuntimeFailpointError,\n MessageDeliveryError,\n MessageDeliveryFailpointError,\n AdmissionConflict,\n AdmissionPolicyError,\n SettlementConflict,\n JoinedToHost,\n LedgerError,\n ThreadStoreError,\n WorkDiscoveryUnavailable,\n ThreadNotMaterialized,\n ThreadExportRejected,\n AppendConflict,\n PortProtocolError,\n]);\n\nexport type PortFailure = typeof PortFailure.Type;\n\n/** The routed operation succeeded on its owning Object. */\nexport class PortSucceeded extends Schema.TaggedClass<PortSucceeded>(\n \"@effect-agent/storage-cloudflare/PortSucceeded\",\n)(\"PortSucceeded\", {\n result: PortResult,\n}) {}\n\n/** The routed operation failed TYPED on its owning Object; the failure re-decodes verbatim. */\nexport class PortFailed extends Schema.TaggedClass<PortFailed>(\n \"@effect-agent/storage-cloudflare/PortFailed\",\n)(\"PortFailed\", {\n failure: PortFailure,\n}) {}\n\n/** The uniform answer of one `portCall`: op-specific success or a re-decodable typed failure. */\nexport const PortResponse = Schema.Union([PortSucceeded, PortFailed]);\nexport type PortResponse = typeof PortResponse.Type;\n\n/** The wire form of one port response (what a transport actually carries). */\nexport type PortResponseEnvelope = typeof PortResponse.Encoded;\n\n// ---------------------------------------------------------------------------\n// Codecs\n// ---------------------------------------------------------------------------\n\nexport const encodePortRequest = Schema.encodeEffect(PortRequest);\nexport const decodePortRequest = Schema.decodeUnknownEffect(PortRequest);\nexport const encodePortResponse = Schema.encodeEffect(PortResponse);\nexport const decodePortResponse = Schema.decodeUnknownEffect(PortResponse);\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAgHA,MAAa,6BAA6B;AAE1C,MAAM,oBAAoB,OAAO,OAAO,MAAM,OAAO,YAAY,0BAA0B,CAAC;;AAG5F,MAAa,uBAAuB,UAClC,MAAM,SAAA,OACF,GAAG,MAAM,MAAM,GAAG,IAA8B,EAAE,OAClD;;;;;;;;AASN,IAAa,oBAAb,cAAuC,OAAO,YAA+B,CAAC,CAC5E,qBACA,EACE,SAAS,kBACX,CACF,CAAC,CAAC,CAAC;;AAOH,IAAa,kBAAb,cAAqC,OAAO,YAA6B,CAAC,CAAC,eAAe,EACxF,SAAS,uBACX,CAAC,CAAC,CAAC,CAAC;;AAGJ,IAAa,kBAAb,cAAqC,OAAO,YAC1C,kDACF,CAAC,CAAC,eAAe,EACf,SAAS,iBACX,CAAC,CAAC,CAAC,CAAC;;AAGJ,IAAa,sBAAb,cAAyC,OAAO,YAC9C,sDACF,CAAC,CAAC,mBAAmB,EACnB,SAAS,iBACX,CAAC,CAAC,CAAC,CAAC;;AAGJ,IAAa,mBAAb,cAAsC,OAAO,YAC3C,mDACF,CAAC,CAAC,gBAAgB,EAChB,SAAS,iBACX,CAAC,CAAC,CAAC,CAAC;AAEJ,IAAa,yBAAb,cAA4C,OAAO,YAAoC,CAAC,CACtF,sBACA,EAAE,SAAS,oBAAoB,CACjC,CAAC,CAAC,CAAC;;AAGH,IAAa,6BAAb,cAAgD,OAAO,YACrD,6DACF,CAAC,CAAC,0BAA0B,EAC1B,SAAS,sBACX,CAAC,CAAC,CAAC,CAAC;AAEJ,IAAa,0BAAb,cAA6C,OAAO,YAAqC,CAAC,CAC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AAC,CAAC;AAEH,IAAa,0BAAb,cAA6C,OAAO,YAAqC,CAAC,CACxF,2BACA,EAAE,OAAO,mBAAmB,CAC9B,CAAC,CAAC,CAAC;AAEH,IAAa,yBAAb,cAA4C,OAAO,YAAoC,CAAC,CACtF,0BACA,EAAE,OAAO,mBAAmB,CAC9B,CAAC,CAAC,CAAC;;AAGH,MAAa,aAAa,OAAO,MAAM;CACrC;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;AACF,CAAC;;;;;;AAaD,MAAa,cAAc,OAAO,MAAM;CACtC;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;AACF,CAAC;;AAKD,IAAa,gBAAb,cAAmC,OAAO,YACxC,gDACF,CAAC,CAAC,iBAAiB,EACjB,QAAQ,WACV,CAAC,CAAC,CAAC,CAAC;;AAGJ,IAAa,aAAb,cAAgC,OAAO,YACrC,6CACF,CAAC,CAAC,cAAc,EACd,SAAS,YACX,CAAC,CAAC,CAAC,CAAC;;AAGJ,MAAa,eAAe,OAAO,MAAM,CAAC,eAAe,UAAU,CAAC;AAUpE,MAAa,oBAAoB,OAAO,aAAa,WAAW;AAChE,MAAa,oBAAoB,OAAO,oBAAoB,WAAW;AACvE,MAAa,qBAAqB,OAAO,aAAa,YAAY;AAClE,MAAa,qBAAqB,OAAO,oBAAoB,YAAY"}
1
+ {"version":3,"file":"PortProtocol.mjs","names":[],"sources":["../src/PortProtocol.ts"],"sourcesContent":["import { IntegrityReport } from \"@yielded/agent/admin\";\nimport { DurableRuntimeFailpointError } from \"@yielded/agent/durable-failpoint\";\nimport { ThreadId } from \"@yielded/agent/identifiers\";\nimport {\n MessageDeliveryError,\n MessageDeliveryFailpointError,\n MessageDeliveryKey,\n MessageDeliveryCompletion,\n MessageDeliveryRecord,\n MessageDeliveryPageRequest,\n MessageDeliveryPage,\n} from \"@yielded/agent/message-delivery\";\nimport { ReadEnvelope } from \"@yielded/agent/record-format\";\nimport { PromptRecordEnvelope } from \"@yielded/agent/records\";\nimport {\n SettlementPublication,\n SettlementPublicationResult,\n} from \"@yielded/agent/settlement-publisher\";\nimport {\n AbortCommand,\n WorkerStopCommand,\n WorkerLedgerState,\n AbortIntent,\n AdmissionConflict,\n AdmissionPolicyError,\n AdmissionRequest,\n AdmissionResolution,\n AdmissionResult,\n ChildSettledNotification,\n ChildSettledOutcome,\n JoinedToHost,\n LedgerError,\n OwnershipLost,\n MarkReadyRequest,\n SettlementConflict,\n SubmissionLookup,\n SubmissionLookupByKey,\n SubmissionSnapshot,\n FundingOwnerRequest,\n FundingOwner,\n} from \"@yielded/agent/submission-ledger\";\nimport {\n ThreadArchiveRange,\n ThreadArchiveRangePage,\n ThreadArchiveRangeRead,\n ThreadArchiveRangeRequest,\n ThreadArchiveRangeSeal,\n ThreadArchiveRangePublish,\n} from \"@yielded/agent/thread-archive-range\";\nimport {\n AppendConflict,\n ExecutionRead,\n ExecutionCheckpoint,\n AppendResult,\n ThreadExport,\n ThreadPeerCountRequest,\n ThreadExportRequest,\n ThreadIdentity,\n ThreadIdentityRequest,\n ThreadWorkerCapacityRequest,\n ThreadWorkerCapacity,\n ThreadVerificationRequest,\n ThreadMaterialization,\n ThreadNotMaterialized,\n ThreadExportRejected,\n ThreadReadRequest,\n ThreadPromptRead,\n ThreadStoreError,\n ThreadTail,\n ThreadTailRequest,\n AppendRequest,\n} from \"@yielded/agent/thread-store\";\nimport {\n ThreadWorkRequest,\n ThreadWorkPage,\n WorkIndexRebuildRequest,\n WorkIndexProgress,\n WorkDiscoveryUnavailable,\n} from \"@yielded/agent/thread-work\";\nimport { WorkerAdmissionRequest } from \"@yielded/agent/worker-admission\";\nimport { Schema, SchemaGetter } from \"effect\";\n\n/**\n * The cross-Durable-Object port protocol (plan §1.3, D-P6-3): Schema request/response/error\n * envelopes for the CLOSED route-capable subset of the thread ports. One Thread's\n * Durable Object executes another Thread's request against its OWN local facets; the\n * envelopes here are the only values that cross the Object boundary, and they are\n * transport-agnostic — native Durable Object JS RPC is the shipped carrier, fetch-with-JSON\n * the documented fallback, and both move the same Schema-encoded JSON.\n *\n * The closed subset is exactly the set of operations the durable coordinator performs against\n * a FOREIGN Thread (parent/child establishment, status checks, abort propagation,\n * child-settlement notification, and the child-thread store operations used by\n * establishment, `verifySettledChild`, and result projection):\n *\n * - worker: `admitWorker` (ledger admission, materialization, creation, origin, readiness);\n * - ledger: `admit`, `markReady`, `lookup`, `resolveAdmission`, `requestAbort`,\n * `recordChildSettled`;\n * - publisher: `publish`;\n * - store: `materialize`, `append`, `read` and `readPrompt` (one page), `readIdentity`,\n * `inspectTail`, `export`, `countPeerMessages`, `work.page`, `work.rebuild`.\n *\n * Every other port operation is lane-local and has no envelope. Foreign operations\n * fail fast and typed instead of widening the distributed surface.\n *\n * Failures cross the boundary as the `PortFailure` union and re-decode on the caller side to\n * the SAME tagged error types the local facet would have produced, so routed calls keep\n * error-tag fidelity. `cause` chains inside `LedgerError`/`ThreadStoreError` travel as\n * Schema defects and do not claim instance fidelity across Objects (plan §2.8).\n */\n\n/** Ceiling for protocol diagnostic strings; matches `AdmissionIndeterminate.reason`. */\nexport const MAX_PORT_DIAGNOSTIC_LENGTH = 4_096;\n\nconst BoundedDiagnostic = Schema.String.check(Schema.isMaxLength(MAX_PORT_DIAGNOSTIC_LENGTH));\n\n/** Truncate a diagnostic string to the protocol's bounded diagnostic length. */\nexport const boundPortDiagnostic = (value: string): string =>\n value.length > MAX_PORT_DIAGNOSTIC_LENGTH\n ? `${value.slice(0, MAX_PORT_DIAGNOSTIC_LENGTH - 3)}...`\n : value;\n\n/**\n * The envelope itself could not be honored: the receiving Object could not decode the\n * request, or a response could not be encoded/decoded. It never carries port semantics —\n * callers fold it into the operation's base error (`LedgerError`/`ThreadStoreError`),\n * except `resolveAdmission`, which folds it into `AdmissionIndeterminate` because a\n * non-answer is never proof of absence (SUB-031).\n */\nexport class PortProtocolError extends Schema.TaggedError<PortProtocolError>()(\n \"PortProtocolError\",\n {\n message: BoundedDiagnostic,\n },\n) {}\n\n// ---------------------------------------------------------------------------\n// Requests\n// ---------------------------------------------------------------------------\n\n/** One destination-owned worker admission, including canonical initialization and readiness. */\nexport class WorkerAdmitCall extends Schema.TaggedClass<WorkerAdmitCall>()(\"WorkerAdmit\", {\n request: WorkerAdmissionRequest,\n}) {}\n\n/** Routed `SubmissionLedger.admit` — child establishment admits INTO the owning Object. */\nexport class LedgerAdmitCall extends Schema.TaggedClass<LedgerAdmitCall>(\n \"@effect-agent/storage-cloudflare/LedgerAdmitCall\",\n)(\"LedgerAdmit\", {\n request: AdmissionRequest,\n}) {}\n\n/** Routed `SubmissionLedger.markReady` for a Submission owned by another Object. */\nexport class LedgerMarkReadyCall extends Schema.TaggedClass<LedgerMarkReadyCall>(\n \"@effect-agent/storage-cloudflare/LedgerMarkReadyCall\",\n)(\"LedgerMarkReady\", {\n request: MarkReadyRequest,\n}) {}\n\n/** Routed `SubmissionLedger.lookup` (by identity or scoped idempotency key). */\nexport class LedgerLookupCall extends Schema.TaggedClass<LedgerLookupCall>(\n \"@effect-agent/storage-cloudflare/LedgerLookupCall\",\n)(\"LedgerLookup\", {\n request: SubmissionLookup,\n}) {}\n\nexport class LedgerFundingOwnerCall extends Schema.TaggedClass<LedgerFundingOwnerCall>()(\n \"LedgerFundingOwner\",\n { request: FundingOwnerRequest },\n) {}\n\n/** Routed `SubmissionLedger.resolveAdmission` — the SUB-031 tri-state authority call. */\nexport class LedgerResolveAdmissionCall extends Schema.TaggedClass<LedgerResolveAdmissionCall>(\n \"@effect-agent/storage-cloudflare/LedgerResolveAdmissionCall\",\n)(\"LedgerResolveAdmission\", {\n request: SubmissionLookupByKey,\n}) {}\n\nexport class LedgerInspectWorkerCall extends Schema.TaggedClass<LedgerInspectWorkerCall>()(\n \"LedgerInspectWorker\",\n { request: Schema.Struct({ threadId: ThreadId }) },\n) {}\n\nexport class LedgerInspectWorkerResult extends Schema.TaggedClass<LedgerInspectWorkerResult>()(\n \"LedgerInspectWorkerResult\",\n { state: WorkerLedgerState },\n) {}\n\nexport class LedgerStopWorkerCall extends Schema.TaggedClass<LedgerStopWorkerCall>()(\n \"LedgerStopWorker\",\n { request: WorkerStopCommand },\n) {}\n\nexport class LedgerStopWorkerResult extends Schema.TaggedClass<LedgerStopWorkerResult>()(\n \"LedgerStopWorkerResult\",\n { owned: Schema.Natural },\n) {}\n\n/** Routed `SubmissionLedger.requestAbort` — abort propagation across Objects. */\nexport class LedgerRequestAbortCall extends Schema.TaggedClass<LedgerRequestAbortCall>(\n \"@effect-agent/storage-cloudflare/LedgerRequestAbortCall\",\n)(\"LedgerRequestAbort\", {\n request: AbortCommand,\n}) {}\n\n/** Routed `SubmissionLedger.recordChildSettled` — the child→parent durable notification. */\nexport class LedgerRecordChildSettledCall extends Schema.TaggedClass<LedgerRecordChildSettledCall>(\n \"@effect-agent/storage-cloudflare/LedgerRecordChildSettledCall\",\n)(\"LedgerRecordChildSettled\", {\n request: ChildSettledNotification,\n}) {}\n\n/** Publish canonical settlement intent at the owning Thread. */\nexport class SettlementPublishCall extends Schema.TaggedClass<SettlementPublishCall>()(\n \"SettlementPublish\",\n { request: SettlementPublication },\n) {}\n\nexport class SettlementPublishResult extends Schema.TaggedClass<SettlementPublishResult>()(\n \"SettlementPublishResult\",\n { result: SettlementPublicationResult },\n) {}\n\n/** Routed `ThreadStore.materialize` against the owning Object. */\nexport class StoreMaterializeCall extends Schema.TaggedClass<StoreMaterializeCall>(\n \"@effect-agent/storage-cloudflare/StoreMaterializeCall\",\n)(\"StoreMaterialize\", {\n request: ThreadMaterialization,\n}) {}\n\n/** Routed `ThreadStore.append` against the owning Object. */\nexport class StoreAppendCall extends Schema.TaggedClass<StoreAppendCall>(\n \"@effect-agent/storage-cloudflare/StoreAppendCall\",\n)(\"StoreAppend\", {\n request: AppendRequest,\n}) {}\n\n/** Routed one-page `ThreadStore.read`; the page bound is the request's own `limit`. */\nexport class StoreReadPageCall extends Schema.TaggedClass<StoreReadPageCall>(\n \"@effect-agent/storage-cloudflare/StoreReadPageCall\",\n)(\"StoreReadPage\", {\n request: ThreadReadRequest,\n}) {}\n\nexport class StoreReadPromptCall extends Schema.TaggedClass<StoreReadPromptCall>()(\n \"StoreReadPrompt\",\n { request: ThreadPromptRead },\n) {}\n\n/** Routed `ThreadStore.inspectTail` against the owning Object. */\nexport class StoreInspectTailCall extends Schema.TaggedClass<StoreInspectTailCall>(\n \"@effect-agent/storage-cloudflare/StoreInspectTailCall\",\n)(\"StoreInspectTail\", {\n request: ThreadTailRequest,\n}) {}\n\n/** Routed bounded `ThreadStore.readIdentity` against the owning Object. */\nexport class StoreReadIdentityCall extends Schema.TaggedClass<StoreReadIdentityCall>(\n \"@effect-agent/storage-cloudflare/StoreReadIdentityCall\",\n)(\"StoreReadIdentity\", {\n request: ThreadIdentityRequest,\n}) {}\n\nexport class StoreReadExecutionCall extends Schema.TaggedClass<StoreReadExecutionCall>()(\n \"StoreReadExecution\",\n { request: ExecutionRead },\n) {}\n\nexport class StoreWorkerCapacityCall extends Schema.TaggedClass<StoreWorkerCapacityCall>()(\n \"StoreWorkerCapacity\",\n { request: ThreadWorkerCapacityRequest },\n) {}\n\nexport class StoreVerificationCall extends Schema.TaggedClass<StoreVerificationCall>()(\n \"StoreVerification\",\n { request: ThreadVerificationRequest },\n) {}\n\n/** Routed `ThreadStore.export` against the owning Object. */\nexport class StoreExportCall extends Schema.TaggedClass<StoreExportCall>(\n \"@effect-agent/storage-cloudflare/StoreExportCall\",\n)(\"StoreExport\", {\n request: ThreadExportRequest,\n}) {}\n\nexport class StoreCountPeerMessagesCall extends Schema.TaggedClass<StoreCountPeerMessagesCall>()(\n \"StoreCountPeerMessages\",\n { request: ThreadPeerCountRequest },\n) {}\n\n/** Work maintenance is routed to the exact Thread's authoritative owner. */\nexport class StoreWorkPageCall extends Schema.TaggedClass<StoreWorkPageCall>()(\"StoreWorkPage\", {\n request: ThreadWorkRequest,\n}) {}\n\nexport class StoreWorkRebuildCall extends Schema.TaggedClass<StoreWorkRebuildCall>()(\n \"StoreWorkRebuild\",\n { request: WorkIndexRebuildRequest },\n) {}\n\nexport class MessageDeliveryListCall extends Schema.TaggedClass<MessageDeliveryListCall>()(\n \"MessageDeliveryList\",\n { request: MessageDeliveryPageRequest },\n) {}\n\nexport class MessageDeliveryCompleteCall extends Schema.TaggedClass<MessageDeliveryCompleteCall>()(\n \"MessageDeliveryComplete\",\n { key: MessageDeliveryKey, completion: MessageDeliveryCompletion },\n) {}\n\nexport class StoreRangePageCall extends Schema.TaggedClass<StoreRangePageCall>()(\"StoreRangePage\", {\n request: ThreadArchiveRangeRead,\n}) {}\n\nexport class StoreRangeSealCall extends Schema.TaggedClass<StoreRangeSealCall>()(\"StoreRangeSeal\", {\n request: ThreadArchiveRangeSeal,\n}) {}\n\nexport class StoreRangeArchiveCall extends Schema.TaggedClass<StoreRangeArchiveCall>()(\n \"StoreRangeArchive\",\n { request: ThreadArchiveRangePublish },\n) {}\n\nexport class StoreRangeVerifyCall extends Schema.TaggedClass<StoreRangeVerifyCall>()(\n \"StoreRangeVerify\",\n { request: ThreadArchiveRangeRequest },\n) {}\n\n/** Every request that may cross a Durable Object boundary — the CLOSED route-capable subset. */\nexport const PortRequest = Schema.Union([\n SettlementPublishCall,\n WorkerAdmitCall,\n MessageDeliveryListCall,\n MessageDeliveryCompleteCall,\n LedgerAdmitCall,\n LedgerMarkReadyCall,\n LedgerLookupCall,\n LedgerFundingOwnerCall,\n LedgerResolveAdmissionCall,\n LedgerRequestAbortCall,\n LedgerStopWorkerCall,\n LedgerInspectWorkerCall,\n LedgerRecordChildSettledCall,\n StoreRangePageCall,\n StoreRangeSealCall,\n StoreRangeArchiveCall,\n StoreRangeVerifyCall,\n StoreMaterializeCall,\n StoreAppendCall,\n StoreReadPageCall,\n StoreReadPromptCall,\n StoreInspectTailCall,\n StoreReadIdentityCall,\n StoreReadExecutionCall,\n StoreWorkerCapacityCall,\n StoreVerificationCall,\n StoreExportCall,\n StoreCountPeerMessagesCall,\n StoreWorkPageCall,\n StoreWorkRebuildCall,\n]);\n\nexport type PortRequest = typeof PortRequest.Type;\n\n/** The wire form of one port request (what a transport actually carries). */\nexport type PortRequestEnvelope = typeof PortRequest.Encoded;\n\n// ---------------------------------------------------------------------------\n// Results\n// ---------------------------------------------------------------------------\n\nexport class WorkerAdmitResult extends Schema.TaggedClass<WorkerAdmitResult>()(\n \"WorkerAdmitResult\",\n {\n result: AdmissionResult,\n },\n) {}\n\nexport class LedgerAdmitResult extends Schema.TaggedClass<LedgerAdmitResult>(\n \"@effect-agent/storage-cloudflare/LedgerAdmitResult\",\n)(\"LedgerAdmitResult\", {\n result: AdmissionResult,\n}) {}\n\nexport class LedgerMarkReadyResult extends Schema.TaggedClass<LedgerMarkReadyResult>(\n \"@effect-agent/storage-cloudflare/LedgerMarkReadyResult\",\n)(\"LedgerMarkReadyResult\", {}) {}\n\n/** `submission` is absent exactly when the lookup answered `Option.none`. */\nexport class LedgerLookupResult extends Schema.TaggedClass<LedgerLookupResult>(\n \"@effect-agent/storage-cloudflare/LedgerLookupResult\",\n)(\"LedgerLookupResult\", {\n submission: Schema.optionalKey(SubmissionSnapshot),\n}) {}\n\nexport class LedgerResolveAdmissionResult extends Schema.TaggedClass<LedgerResolveAdmissionResult>(\n \"@effect-agent/storage-cloudflare/LedgerResolveAdmissionResult\",\n)(\"LedgerResolveAdmissionResult\", {\n resolution: AdmissionResolution,\n}) {}\n\nexport class LedgerRequestAbortResult extends Schema.TaggedClass<LedgerRequestAbortResult>(\n \"@effect-agent/storage-cloudflare/LedgerRequestAbortResult\",\n)(\"LedgerRequestAbortResult\", {\n intent: AbortIntent,\n}) {}\n\nexport class LedgerRecordChildSettledResult extends Schema.TaggedClass<LedgerRecordChildSettledResult>(\n \"@effect-agent/storage-cloudflare/LedgerRecordChildSettledResult\",\n)(\"LedgerRecordChildSettledResult\", {\n outcome: ChildSettledOutcome,\n}) {}\n\nexport class StoreMaterializeResult extends Schema.TaggedClass<StoreMaterializeResult>(\n \"@effect-agent/storage-cloudflare/StoreMaterializeResult\",\n)(\"StoreMaterializeResult\", {}) {}\n\nexport class StoreAppendResult extends Schema.TaggedClass<StoreAppendResult>(\n \"@effect-agent/storage-cloudflare/StoreAppendResult\",\n)(\"StoreAppendResult\", {\n result: AppendResult,\n}) {}\n\n/** One page of canonical records, bounded by the request's `limit` (≤ 1,024). */\nexport class StoreReadPageResult extends Schema.TaggedClass<StoreReadPageResult>(\n \"@effect-agent/storage-cloudflare/StoreReadPageResult\",\n)(\"StoreReadPageResult\", {\n records: Schema.Array(ReadEnvelope).check(Schema.isMaxLength(1_024)),\n}) {}\n\nexport class StoreReadPromptResult extends Schema.TaggedClass<StoreReadPromptResult>()(\n \"StoreReadPromptResult\",\n {\n records: Schema.Array(PromptRecordEnvelope).check(Schema.isMaxLength(1_024)),\n },\n) {}\n\nexport class StoreInspectTailResult extends Schema.TaggedClass<StoreInspectTailResult>(\n \"@effect-agent/storage-cloudflare/StoreInspectTailResult\",\n)(\"StoreInspectTailResult\", {\n tail: ThreadTail,\n}) {}\n\nexport class StoreReadExecutionResult extends Schema.TaggedClass<StoreReadExecutionResult>()(\n \"StoreReadExecutionResult\",\n { checkpoint: Schema.OptionFromNullOr(ExecutionCheckpoint) },\n) {}\n\nexport class StoreReadIdentityResult extends Schema.TaggedClass<StoreReadIdentityResult>(\n \"@effect-agent/storage-cloudflare/StoreReadIdentityResult\",\n)(\"StoreReadIdentityResult\", {\n identity: Schema.Struct({\n ...ThreadIdentity.fields,\n records: Schema.Array(ReadEnvelope).check(Schema.isMaxLength(3)),\n }).pipe(\n Schema.decodeTo(Schema.toType(ThreadIdentity), {\n decode: SchemaGetter.transform((fields) => ThreadIdentity.make(fields)),\n encode: SchemaGetter.transform((identity) => identity),\n }),\n ),\n}) {}\n\nexport class LedgerFundingOwnerResult extends Schema.TaggedClass<LedgerFundingOwnerResult>()(\n \"LedgerFundingOwnerResult\",\n { funding: FundingOwner },\n) {}\n\nexport class StoreWorkerCapacityResult extends Schema.TaggedClass<StoreWorkerCapacityResult>()(\n \"StoreWorkerCapacityResult\",\n { capacity: ThreadWorkerCapacity },\n) {}\n\nexport class StoreVerificationResult extends Schema.TaggedClass<StoreVerificationResult>()(\n \"StoreVerificationResult\",\n { report: IntegrityReport },\n) {}\n\nexport class StoreExportResult extends Schema.TaggedClass<StoreExportResult>(\n \"@effect-agent/storage-cloudflare/StoreExportResult\",\n)(\"StoreExportResult\", {\n export: ThreadExport,\n}) {}\n\nexport class StoreCountPeerMessagesResult extends Schema.TaggedClass<StoreCountPeerMessagesResult>()(\n \"StoreCountPeerMessagesResult\",\n { count: Schema.Int.check(Schema.isBetween({ minimum: 0, maximum: 1000 })) },\n) {}\n\nexport class StoreWorkPageResult extends Schema.TaggedClass<StoreWorkPageResult>()(\n \"StoreWorkPageResult\",\n { page: ThreadWorkPage },\n) {}\n\nexport class StoreWorkRebuildResult extends Schema.TaggedClass<StoreWorkRebuildResult>()(\n \"StoreWorkRebuildResult\",\n { progress: WorkIndexProgress },\n) {}\n\nexport class MessageDeliveryListResult extends Schema.TaggedClass<MessageDeliveryListResult>()(\n \"MessageDeliveryListResult\",\n { page: MessageDeliveryPage },\n) {}\n\nexport class MessageDeliveryCompleteResult extends Schema.TaggedClass<MessageDeliveryCompleteResult>()(\n \"MessageDeliveryCompleteResult\",\n { record: MessageDeliveryRecord },\n) {}\n\nexport class StoreRangePageResult extends Schema.TaggedClass<StoreRangePageResult>()(\n \"StoreRangePageResult\",\n { page: ThreadArchiveRangePage },\n) {}\n\nexport class StoreRangeSealResult extends Schema.TaggedClass<StoreRangeSealResult>()(\n \"StoreRangeSealResult\",\n { range: Schema.Option(ThreadArchiveRange) },\n) {}\n\nexport class StoreRangeArchiveResult extends Schema.TaggedClass<StoreRangeArchiveResult>()(\n \"StoreRangeArchiveResult\",\n { range: ThreadArchiveRange },\n) {}\n\nexport class StoreRangeVerifyResult extends Schema.TaggedClass<StoreRangeVerifyResult>()(\n \"StoreRangeVerifyResult\",\n { range: ThreadArchiveRange },\n) {}\n\n/** Every successful routed result. Callers narrow by the tag their request implies. */\nexport const PortResult = Schema.Union([\n SettlementPublishResult,\n WorkerAdmitResult,\n MessageDeliveryListResult,\n MessageDeliveryCompleteResult,\n LedgerAdmitResult,\n LedgerMarkReadyResult,\n LedgerLookupResult,\n LedgerFundingOwnerResult,\n LedgerResolveAdmissionResult,\n LedgerRequestAbortResult,\n LedgerStopWorkerResult,\n LedgerInspectWorkerResult,\n LedgerRecordChildSettledResult,\n StoreRangePageResult,\n StoreRangeSealResult,\n StoreRangeArchiveResult,\n StoreRangeVerifyResult,\n StoreMaterializeResult,\n StoreAppendResult,\n StoreReadPageResult,\n StoreReadPromptResult,\n StoreInspectTailResult,\n StoreReadIdentityResult,\n StoreReadExecutionResult,\n StoreWorkerCapacityResult,\n StoreVerificationResult,\n StoreExportResult,\n StoreCountPeerMessagesResult,\n StoreWorkPageResult,\n StoreWorkRebuildResult,\n]);\n\nexport type PortResult = typeof PortResult.Type;\n\n// ---------------------------------------------------------------------------\n// Failures and the response envelope\n// ---------------------------------------------------------------------------\n\n/**\n * Every typed failure a route-capable operation can produce on its owning Object, plus the\n * protocol's own `PortProtocolError`. Members re-decode to the SAME tagged classes the\n * thread ports declare, so a routed caller observes identical error tags and fields.\n */\nexport const PortFailure = Schema.Union([\n OwnershipLost,\n DurableRuntimeFailpointError,\n MessageDeliveryError,\n MessageDeliveryFailpointError,\n AdmissionConflict,\n AdmissionPolicyError,\n SettlementConflict,\n JoinedToHost,\n LedgerError,\n ThreadStoreError,\n WorkDiscoveryUnavailable,\n ThreadNotMaterialized,\n ThreadExportRejected,\n AppendConflict,\n PortProtocolError,\n]);\n\nexport type PortFailure = typeof PortFailure.Type;\n\n/** The routed operation succeeded on its owning Object. */\nexport class PortSucceeded extends Schema.TaggedClass<PortSucceeded>(\n \"@effect-agent/storage-cloudflare/PortSucceeded\",\n)(\"PortSucceeded\", {\n result: PortResult,\n}) {}\n\n/** The routed operation failed TYPED on its owning Object; the failure re-decodes verbatim. */\nexport class PortFailed extends Schema.TaggedClass<PortFailed>(\n \"@effect-agent/storage-cloudflare/PortFailed\",\n)(\"PortFailed\", {\n failure: PortFailure,\n}) {}\n\n/** The uniform answer of one `portCall`: op-specific success or a re-decodable typed failure. */\nexport const PortResponse = Schema.Union([PortSucceeded, PortFailed]);\nexport type PortResponse = typeof PortResponse.Type;\n\n/** The wire form of one port response (what a transport actually carries). */\nexport type PortResponseEnvelope = typeof PortResponse.Encoded;\n\n// ---------------------------------------------------------------------------\n// Codecs\n// ---------------------------------------------------------------------------\n\n// Remote codecs derive their memoized encoding AST only when a port is used.\nexport const encodePortRequest: ReturnType<typeof Schema.encodeEffect<typeof PortRequest>> = (\n ...args\n) => Schema.encodeEffect(PortRequest)(...args);\n\nexport const decodePortRequest = Schema.decodeUnknownEffect(PortRequest);\n\nexport const encodePortResponse: ReturnType<typeof Schema.encodeEffect<typeof PortResponse>> = (\n ...args\n) => Schema.encodeEffect(PortResponse)(...args);\n\nexport const decodePortResponse = Schema.decodeUnknownEffect(PortResponse);\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAgHA,MAAa,6BAA6B;AAE1C,MAAM,oBAAoB,OAAO,OAAO,MAAM,OAAO,YAAY,0BAA0B,CAAC;;AAG5F,MAAa,uBAAuB,UAClC,MAAM,SAAA,OACF,GAAG,MAAM,MAAM,GAAG,IAA8B,EAAE,OAClD;;;;;;;;AASN,IAAa,oBAAb,cAAuC,OAAO,YAA+B,CAAC,CAC5E,qBACA,EACE,SAAS,kBACX,CACF,CAAC,CAAC,CAAC;;AAOH,IAAa,kBAAb,cAAqC,OAA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CAAC,CAAC,iBAAiB,EACjB,QAAQ,WACV,CAAC,CAAC,CAAC,CAAC;;AAGJ,IAAa,aAAb,cAAgC,OAAO,YACrC,6CACF,CAAC,CAAC,cAAc,EACd,SAAS,YACX,CAAC,CAAC,CAAC,CAAC;;AAGJ,MAAa,eAAe,OAAO,MAAM,CAAC,eAAe,UAAU,CAAC;AAWpE,MAAa,qBACX,GAAG,SACA,OAAO,aAAa,WAAW,CAAC,CAAC,GAAG,IAAI;AAE7C,MAAa,oBAAoB,OAAO,oBAAoB,WAAW;AAEvE,MAAa,sBACX,GAAG,SACA,OAAO,aAAa,YAAY,CAAC,CAAC,GAAG,IAAI;AAE9C,MAAa,qBAAqB,OAAO,oBAAoB,YAAY"}
@@ -1,10 +1,10 @@
1
1
  import { DoStorageConfig } from "./DoStorageConfig.mjs";
2
2
  import { DoStorageFailpoint, isDefaultDoStorageFailpoint } from "./DoStorageFailpoint.mjs";
3
3
  import { DoAppendConflict, DoCheckpointConflict, DoStorageCorruptionError, DoStorageError, DoValueBoundExceeded } from "./DoStorageError.mjs";
4
- import { n as ensureDoStorageLayout } from "./migrations-CAO_akhD.mjs";
4
+ import { n as ensureDoStorageLayout } from "./migrations-CJAHO3Y7.mjs";
5
5
  import { n as ownedRows, r as ownedState } from "./owned-state-Tk_KahHn.mjs";
6
6
  import { SqlLifecycleRetainer, SqlLifecycleSource, makeSqlLifecyclePublication } from "@yielded/agent-storage-sql/sql-lifecycle-publication";
7
- import { SqlStorageOwner } from "@yielded/agent/sql-memory-store";
7
+ import { SqlStorageOwner } from "@yielded/agent/sql-storage-owner";
8
8
  import { Cause, Clock, Context, Effect, Layer, Option, Predicate, References, Result, Schema, Stream, Tracer } from "effect";
9
9
  import * as SqlClient$1 from "effect/sql/SqlClient";
10
10
  import { SqliteClient } from "@effect/sql-sqlite-do";
@@ -841,4 +841,4 @@ const initializeDoJournal = (sql, failpoint, maxStoredValueBytes) => Effect.filt
841
841
  //#endregion
842
842
  export { initializedDoJournalLayer as a, initializeDoJournal as i, RawReadRequest as n, isAppendContention as o, decodeRows as r, withStorageSpan as s, RawCheckpoint as t };
843
843
 
844
- //# sourceMappingURL=do-journal-BH10YJoi.mjs.map
844
+ //# sourceMappingURL=do-journal-DkRcQVRY.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"do-journal-DkRcQVRY.mjs","names":["isSqlError","SqlClient"],"sources":["../src/internal/storage-span.ts","../src/internal/do-journal.ts"],"sourcesContent":["import { Effect, Predicate, References, Result, Tracer } from \"effect\";\n\ntype Tagged = { readonly _tag: string; readonly reason?: unknown };\n\nexport const isAppendContention = (error: Tagged): boolean =>\n (error._tag === \"DoAppendConflict\" || error._tag === \"AppendConflict\") && error.reason === \"tail\";\n\n/** Expected refusals remain typed at the port, but are outcomes of the storage operation. */\nexport const storageResult = <A, E extends Tagged, R>(\n effect: Effect.Effect<A, E, R>,\n expected: (error: E) => boolean,\n) =>\n effect.pipe(\n Effect.map(Result.succeed),\n Effect.catchIf(expected, (error) => Effect.succeed(Result.fail(error))),\n );\n\n/** Only error discriminants enter telemetry; messages, SQL, identities and payloads do not. */\nexport const annotateStorageError = (error: Tagged) =>\n Effect.annotateCurrentSpan({\n \"error.type\": error._tag,\n ...(Predicate.hasProperty(error, \"cause\") &&\n Predicate.hasProperty(error.cause, \"_tag\") &&\n typeof error.cause._tag === \"string\"\n ? { \"error.cause.type\": error.cause._tag }\n : {}),\n });\n\nexport const withStorageSpan = (\n name: string,\n expected: (error: Tagged) => boolean = () => false,\n) => {\n const span = Effect.withSpan(name);\n\n return <A, E extends Tagged, R>(effect: Effect.Effect<A, E, R>): Effect.Effect<A, E, R> =>\n Effect.withFiber((fiber) =>\n !fiber.getRef(References.TracerEnabled) || fiber.getRef(Tracer.Tracer) === Tracer.nativeTracer\n ? effect\n : storageResult(effect, expected).pipe(\n Effect.tap((result) =>\n Result.isFailure(result)\n ? Effect.annotateCurrentSpan({ \"storage.outcome\": result.failure._tag })\n : Effect.void,\n ),\n Effect.tapError(annotateStorageError),\n span,\n Effect.flatMap(Effect.fromResult),\n ),\n );\n};\n","import { SqliteClient } from \"@effect/sql-sqlite-do\";\nimport {\n makeCanonicalStorage,\n recordBatchId,\n} from \"@yielded/agent-storage-sql/sql-canonical-storage\";\nimport type { RawAppendRequest } from \"@yielded/agent-storage-sql/sql-journal\";\nimport { makeSqlExecutions } from \"@yielded/agent-storage-sql/sql-journal\";\nimport {\n makeSqlLifecyclePublication,\n type SqlLifecycleRetainMany,\n SqlLifecycleSource,\n SqlLifecycleRetainer,\n} from \"@yielded/agent-storage-sql/sql-lifecycle-publication\";\nimport { SqlStorageProgress } from \"@yielded/agent-storage-sql/sql-storage-progress\";\nimport {\n canonicalRecordJson,\n makeSqlThreadArchiveRange,\n} from \"@yielded/agent-storage-sql/sql-thread-archive-range\";\nimport { makeSqlThreadWork } from \"@yielded/agent-storage-sql/sql-thread-work\";\nimport { ThreadId } from \"@yielded/agent/identifiers\";\nimport {\n LifecyclePublicationFact,\n LifecyclePublicationError,\n} from \"@yielded/agent/lifecycle-publication\";\nimport { BatchId, CanonicalRecord, CanonicalSequence } from \"@yielded/agent/records\";\nimport { SqlStorageOwner } from \"@yielded/agent/sql-storage-owner\";\nimport {\n type AppendConflict,\n AppendResult,\n ThreadStoreDiagnostic,\n ThreadStoreError,\n} from \"@yielded/agent/thread-store\";\nimport {\n Cause,\n Clock,\n Context,\n Effect,\n Layer,\n Option,\n Predicate,\n References,\n Result,\n Schema,\n Stream,\n Tracer,\n} from \"effect\";\nimport * as SqlClient from \"effect/sql/SqlClient\";\nimport { classifySqliteError, SqlError } from \"effect/sql/SqlError\";\nimport { CurrentTransformer, type Statement } from \"effect/sql/Statement\";\n\nimport { DoStorageConfig } from \"../DoStorageConfig.ts\";\nimport {\n type DoStorageFailpointError,\n DoAppendConflict,\n DoCheckpointConflict,\n DoStorageCorruptionError,\n DoStorageError,\n DoValueBoundExceeded,\n type DoStorageFailpointLocation,\n} from \"../DoStorageError.ts\";\nimport { DoStorageFailpoint, isDefaultDoStorageFailpoint } from \"../DoStorageFailpoint.ts\";\nimport { ensureDoStorageLayout } from \"./migrations.ts\";\nimport { ownedState, ownedRows, type OwnedState } from \"./owned-state.ts\";\nimport {\n isAppendContention,\n annotateStorageError,\n storageResult,\n withStorageSpan,\n} from \"./storage-span.ts\";\n\n/**\n * Static schema ceiling for stored text columns. Writes are bounded in BYTES by the\n * configured `maxStoredValueBytes` (always ≤ 2,000,000); UTF-8 byte length is never smaller\n * than UTF-16 string length, so any value that passed the byte bound also passes this\n * decode-side character ceiling.\n */\nconst BoundedStoredText = Schema.String.check(Schema.isMaxLength(2_000_000));\nconst BoundedIdentifier = Schema.NonEmptyString.check(Schema.isMaxLength(1024));\nconst MAX_IDENTIFIER_LENGTH = 1_024;\nconst MAX_READ_PAGE_JSON_BYTES = 4 * 1024 * 1024;\n// A shared isolate budget permits multi-page hydration without multiplying its\n// retained payload by the number of resident Durable Object instances.\nconst MAX_RECORD_CACHE_JSON_BYTES = 8 * 1024 * 1024;\nconst MAX_RECORD_CACHE_ENTRIES = 4_096;\n/** Durable Object SQL storage allows at most 100 bound parameters per statement. */\nconst MAX_BOUND_PARAMETERS = 100;\nconst isSqlError = Schema.is(SqlError);\n\nconst isNativeClient = Schema.is(\n Schema.declare<SqliteClient.SqliteClient>((value): value is SqliteClient.SqliteClient =>\n Predicate.hasProperty(value, SqliteClient.TypeId),\n ),\n);\n\nconst storedTextBytes = (value: string): number => new TextEncoder().encode(value).byteLength;\n\nconst chunked = <A>(values: ReadonlyArray<A>, size: number): Array<ReadonlyArray<A>> => {\n const chunks: Array<ReadonlyArray<A>> = [];\n\n for (let index = 0; index < values.length; index += size) {\n chunks.push(values.slice(index, index + size));\n }\n\n return chunks;\n};\n\nclass ThreadRow extends Schema.Class<ThreadRow>(\"ThreadRow\")({\n thread_id: BoundedIdentifier,\n created_at: Schema.NullOr(Schema.NonEmptyString.check(Schema.isMaxLength(128))),\n tail_sequence: CanonicalSequence,\n}) {}\n\nconst threadRows = ownedRows(\n ThreadRow,\n \"effect_agent_threads\",\n (row) => row.thread_id,\n \"thread_id\",\n);\n\nclass RecordRow extends Schema.Class<RecordRow>(\"RecordRow\")({\n batch_id: Schema.fromJsonString(BatchId.check(Schema.isMaxLength(MAX_IDENTIFIER_LENGTH))),\n thread_id: ThreadId.check(Schema.isMaxLength(MAX_IDENTIFIER_LENGTH)),\n record_id: Schema.fromJsonString(BoundedIdentifier),\n record_json: BoundedStoredText,\n sequence: CanonicalSequence,\n}) {}\n\ninterface RecordCacheEntry {\n readonly row: RecordRow;\n readonly bytes: number;\n readonly evict: () => void;\n}\n\n// Entries retain only their local row map, never a storage owner or incarnation.\nconst isolateRecords = new Map<RecordCacheEntry, true>();\nlet isolateRecordBytes = 0;\n\nconst releaseRecord = (entry: RecordCacheEntry) => {\n if (!isolateRecords.delete(entry)) return;\n isolateRecordBytes -= entry.bytes;\n entry.evict();\n};\n\nconst recordCaches = new WeakMap<OwnedState, ReturnType<typeof makeRecordCache>>();\n\nconst makeRecordCache = () => {\n const records = new Map<string, RecordCacheEntry>();\n const key = (thread: string, sequence: number) => JSON.stringify([thread, sequence]);\n\n return {\n clear: () => {\n for (const entry of records.values()) releaseRecord(entry);\n },\n get: (thread: string, sequence: number) => records.get(key(thread, sequence))?.row,\n prefix: (thread: string, through: number): ReadonlyArray<RecordRow> | undefined => {\n const prefix: Array<RecordRow> = [];\n\n for (let sequence = 1; sequence <= through; sequence++) {\n const row = records.get(key(thread, sequence));\n\n if (row === undefined) return undefined;\n prefix.push(row.row);\n }\n\n return prefix;\n },\n put: (row: RecordRow, capturedBytes?: number) => {\n const id = key(row.thread_id, row.sequence);\n const prior = records.get(id);\n\n if (prior?.row === row) return;\n const size = capturedBytes ?? storedTextBytes(row.record_json);\n\n if (prior !== undefined) releaseRecord(prior);\n\n const entry: RecordCacheEntry = {\n row,\n bytes: size,\n evict: () => records.delete(id),\n };\n\n records.set(id, entry);\n isolateRecords.set(entry, true);\n isolateRecordBytes += size;\n while (\n isolateRecordBytes > MAX_RECORD_CACHE_JSON_BYTES ||\n isolateRecords.size > MAX_RECORD_CACHE_ENTRIES\n ) {\n const oldest = isolateRecords.keys().next().value;\n\n if (oldest === undefined) break;\n releaseRecord(oldest);\n }\n },\n };\n};\n\nconst ReadPlanRow = Schema.Struct({\n sequence: CanonicalSequence,\n record_json_bytes: Schema.Natural.check(Schema.isLessThanOrEqualTo(MAX_READ_PAGE_JSON_BYTES)),\n});\n\ntype ReadPage = [typeof ReadPlanRow.Type, ...Array<typeof ReadPlanRow.Type>];\n\nclass CheckpointRow extends Schema.Class<CheckpointRow>(\"CheckpointRow\")({\n checkpoint_json: BoundedStoredText,\n thread_id: BoundedIdentifier,\n through_sequence: CanonicalSequence,\n}) {}\n\nconst LifecycleCursorRow = Schema.Struct({\n thread_id: BoundedIdentifier,\n through_sequence: CanonicalSequence,\n});\n\nconst lifecycleCursorRows = ownedRows(\n LifecycleCursorRow,\n \"effect_agent_lifecycle_cursors\",\n (row) => row.thread_id,\n \"thread_id\",\n);\n\nconst initializedLifecycleSources = new WeakSet<OwnedState>();\n\nexport type { RawAppendRequest } from \"@yielded/agent-storage-sql/sql-journal\";\n\nexport class RawReadRequest extends Schema.Class<RawReadRequest>(\n \"@effect-agent/storage-cloudflare/RawReadRequest\",\n)({\n threadId: BoundedIdentifier,\n fromSequenceExclusive: CanonicalSequence,\n limit: Schema.Int.check(Schema.isGreaterThan(0), Schema.isLessThanOrEqualTo(1_024)),\n}) {}\n\nexport class RawCheckpoint extends Schema.Class<RawCheckpoint>(\n \"@effect-agent/storage-cloudflare/RawCheckpoint\",\n)({\n checkpointJson: BoundedStoredText,\n threadId: BoundedIdentifier,\n throughSequence: CanonicalSequence,\n}) {}\n\ntype AppendError =\n | ThreadStoreError\n | DoAppendConflict\n | DoStorageCorruptionError\n | DoStorageError\n | DoStorageFailpointError\n | DoValueBoundExceeded;\n\ntype CheckpointError =\n | DoCheckpointConflict\n | DoStorageCorruptionError\n | DoStorageError\n | DoValueBoundExceeded;\n\ntype DoJournalFailpoint = (\n location: DoStorageFailpointLocation,\n) => Effect.Effect<void, DoStorageFailpointError>;\n\nconst noFailpoint: DoJournalFailpoint = () => Effect.void;\n\nconst storageError =\n (operation: string) =>\n (error: SqlError): DoStorageError =>\n DoStorageError.make({\n cause: error,\n operation,\n message: error.message,\n diagnostic: ThreadStoreDiagnostic.make({\n causeTag: error._tag,\n operation,\n issueTag: error.reason._tag,\n }),\n });\n\n/** Decode raw Durable Object SQLite rows against a Schema, reporting failures as typed corruption. */\nexport const decodeRows = <A, I>(\n schema: Schema.Codec<ReadonlyArray<A>, ReadonlyArray<I>>,\n table: string,\n rowKey: string,\n rows: unknown,\n decoder: string = table,\n): Effect.Effect<ReadonlyArray<A>, DoStorageCorruptionError> =>\n Schema.decodeUnknownEffect(schema)(rows).pipe(\n Effect.mapError((error) =>\n DoStorageCorruptionError.make({\n table,\n rowKey,\n message: \"Stored rows do not satisfy the storage schema\",\n diagnostic: ThreadStoreDiagnostic.make({\n causeTag: error._tag,\n operation: \"decode storage rows\",\n decoder,\n issueTag: error.issue._tag,\n }),\n }),\n ),\n Effect.tapError((error) =>\n Effect.annotateCurrentSpan({\n \"storage.failure.operation\": error.diagnostic?.operation,\n \"storage.failure.cause\": error.diagnostic?.causeTag,\n \"storage.failure.decoder\": decoder,\n \"storage.failure.issue\": error.diagnostic?.issueTag,\n }),\n ),\n );\n\n/** Decode exactly one raw row against a Schema, reporting failures as typed corruption. */\nexport const decodeSingleRow = <A, I>(\n schema: Schema.Codec<ReadonlyArray<A>, ReadonlyArray<I>>,\n table: string,\n rowKey: string,\n rows: unknown,\n): Effect.Effect<A, DoStorageCorruptionError> =>\n decodeRows(schema, table, rowKey, rows).pipe(\n Effect.flatMap((decoded) =>\n decoded.length === 1\n ? Effect.succeed(decoded[0])\n : Effect.fail(\n DoStorageCorruptionError.make({\n table,\n rowKey,\n message: `Expected exactly one row but found ${decoded.length}.`,\n }),\n ),\n ),\n );\n\n/** Open a validated layout and bind this Object's storage owner. */\nconst ensureCurrentStorage = Effect.fnUntraced(function* (\n sql: SqlClient.SqlClient,\n failpoint: DoJournalFailpoint = noFailpoint,\n maxStoredValueBytes: number,\n) {\n const state = yield* ownedState(sql);\n const owner = (yield* SqlStorageOwner) ?? state;\n\n yield* ensureDoStorageLayout().pipe(\n Effect.provideService(SqlStorageOwner, owner),\n Effect.provideService(SqlClient.SqlClient, sql),\n );\n\n let journal: DoJournal | undefined;\n\n const lifecycle = yield* makeSqlLifecyclePublication(undefined, maxStoredValueBytes).pipe(\n Effect.provideService(SqlStorageOwner, owner),\n Effect.provideService(SqlLifecycleSource, {\n beforeRetain: (threadId) =>\n Effect.suspend(() =>\n journal === undefined\n ? Effect.fail(LifecyclePublicationError.make({ reason: \"unavailable\" }))\n : journal.flushCanonical(threadId),\n ),\n beforePending: Effect.suspend(() =>\n journal === undefined\n ? Effect.fail(LifecyclePublicationError.make({ reason: \"unavailable\" }))\n : journal.flushPublications(),\n ),\n }),\n Effect.provideService(SqlClient.SqlClient, sql),\n Effect.mapError((cause) =>\n DoStorageError.make({\n operation: \"initialize lifecycle publication\",\n message: \"Native publication storage unavailable\",\n cause,\n }),\n ),\n );\n\n journal = yield* makeJournal(sql, failpoint, maxStoredValueBytes, lifecycle, state).pipe(\n Effect.provideService(SqlStorageOwner, owner),\n );\n if (lifecycle !== undefined) yield* journal.initializeLifecycleSource();\n\n return journal;\n});\n\nconst makeJournal = Effect.fnUntraced(function* (\n sql: SqlClient.SqlClient,\n failpoint: DoJournalFailpoint,\n maxStoredValueBytes: number,\n lifecycle: Effect.Success<ReturnType<typeof makeSqlLifecyclePublication>>,\n state: OwnedState,\n) {\n const owner = (yield* SqlStorageOwner) ?? state;\n const progress = yield* SqlStorageProgress;\n\n const nativeDb =\n isNativeClient(sql) &&\n sql.config.transformQueryNames === undefined &&\n sql.config.transformResultNames === undefined &&\n isDefaultDoStorageFailpoint(failpoint)\n ? sql.config.storage?.sql\n : undefined;\n\n const work = yield* makeSqlThreadWork({\n read: (body) => state.read(body),\n write: (body) =>\n owner.transaction(body.pipe(Effect.tap(() => state.invalidate))).pipe(\n Effect.provideService(SqlClient.SqlClient, sql),\n Effect.catchTag(\"SqlError\", (cause) =>\n ThreadStoreError.make({\n operation: \"rebuild Thread work\",\n message: \"Thread work transaction failed\",\n cause,\n }),\n ),\n ),\n }).pipe(Effect.provideService(SqlClient.SqlClient, sql));\n\n yield* Effect.acquireRelease(\n Effect.sync(() => state.invalidators.add(work.invalidate)),\n () => Effect.sync(() => state.invalidators.delete(work.invalidate)),\n );\n\n const workFailure = (cause: unknown) =>\n DoStorageError.make({\n operation: \"publish Thread work\",\n message: \"Canonical work metadata could not be published\",\n cause,\n });\n\n const executions = yield* makeSqlExecutions().pipe(\n Effect.provideService(SqlClient.SqlClient, sql),\n );\n\n const executionConflict = <A>(effect: Effect.Effect<A, AppendConflict | ThreadStoreError>) =>\n effect.pipe(\n Effect.catchTag(\"AppendConflict\", (error) =>\n Effect.fail(\n DoAppendConflict.make({\n reason: error.reason,\n message: \"Active execution conflicts with the captured commit\",\n ...(error.actualTailSequence === undefined\n ? {}\n : { actualTailSequence: error.actualTailSequence }),\n }),\n ),\n ),\n );\n\n const threads = threadRows(state, sql);\n const cursors = lifecycleCursorRows(state, sql);\n let records = recordCaches.get(state);\n\n if (records === undefined) {\n records = makeRecordCache();\n recordCaches.set(state, records);\n state.invalidators.add(records.clear);\n }\n const recordCache = records;\n\n const archives = yield* makeSqlThreadArchiveRange({\n read: (body) => state.read(body),\n write: (body) =>\n owner.transaction(body.pipe(Effect.tap(() => state.invalidate))).pipe(\n Effect.provideService(SqlClient.SqlClient, sql),\n Effect.catchTag(\"SqlError\", (cause) =>\n ThreadStoreError.make({\n operation: \"archive write\",\n message: \"Archive transaction failed.\",\n cause,\n }),\n ),\n ),\n }).pipe(Effect.provideService(SqlClient.SqlClient, sql));\n\n const recordJson = canonicalRecordJson(sql);\n\n const physical = yield* makeCanonicalStorage().pipe(\n Effect.provideService(SqlClient.SqlClient, sql),\n );\n\n /** Typed pre-write refusal for any single value over the configured byte bound. */\n const checkValueBound = (\n operation: string,\n value: string,\n actualBytes = storedTextBytes(value),\n ): Effect.Effect<void, DoValueBoundExceeded> => {\n return actualBytes > maxStoredValueBytes\n ? Effect.fail(\n DoValueBoundExceeded.make({\n actualBytes,\n maxBytes: maxStoredValueBytes,\n operation,\n }),\n )\n : Effect.void;\n };\n\n /**\n * Runs one journal write transaction on the Durable Object storage-backed\n * `withTransaction` (`ctx.storage.transaction()` under the hood). Within one Durable\n * Object there is exactly ONE writer, so the Node `BEGIN IMMEDIATE` + busy-retry +\n * `SqliteWriteContention` machinery has no analogue here and is deliberately absent.\n * The shared local owner gate covers the transaction and acknowledgement.\n *\n * Journal write transactions are always top level: the Durable Object client rejects\n * nested transactions, so new journal operations must not wrap this helper inside another\n * transaction. Expected outcomes may be captured only when every such refusal precedes\n * mutation; real faults still roll back. Successful preflight reads never authorize a write.\n */\n const withWriteTransaction = (\n operation: string,\n expected?: (error: { readonly _tag: string }) => boolean,\n ) => {\n const transaction = <A, E extends { readonly _tag: string }>(\n effect: Effect.Effect<A, E>,\n ): Effect.Effect<A, E | DoStorageError> =>\n Effect.withFiber((fiber) => {\n const body = state.owner.withMutation(owner.transaction(effect)).pipe(\n Effect.provideService(SqlClient.SqlClient, sql),\n Effect.mapError((error) => (isSqlError(error) ? storageError(operation)(error) : error)),\n );\n\n const traced =\n fiber.getRef(References.TracerEnabled) &&\n fiber.getRef(Tracer.Tracer) !== Tracer.nativeTracer;\n\n return traced\n ? body.pipe(\n Effect.tapError(annotateStorageError),\n Effect.withSpan(\"DoJournal.withWriteTransaction\", { attributes: { operation } }),\n )\n : body;\n });\n\n return <A, E extends { readonly _tag: string }>(effect: Effect.Effect<A, E>) =>\n expected === undefined\n ? transaction(effect)\n : transaction(storageResult(effect, expected)).pipe(Effect.flatMap(Effect.fromResult));\n };\n\n const materialize = Effect.fnUntraced(function* (\n threadId: string,\n createdAt: string,\n ): Effect.fn.Return<void, DoStorageCorruptionError | DoStorageError | DoValueBoundExceeded> {\n if (threadId.length > MAX_IDENTIFIER_LENGTH) {\n return yield* DoStorageError.make({\n operation: \"materialize thread\",\n message: \"Thread identity exceeds the Durable Object storage bounds.\",\n });\n }\n // Refusals and idempotent materialization need no transaction. Recheck before writes.\n const current = yield* getThread(threadId);\n\n if (current.length === 1) {\n return;\n }\n yield* withWriteTransaction(\"materialize transaction\")(\n Effect.gen(function* () {\n const existingRows = yield* getThread(threadId);\n\n const existing = yield* decodeRows(\n Schema.Array(ThreadRow),\n \"effect_agent_threads\",\n threadId,\n existingRows,\n );\n\n if (existing.length > 1) {\n return yield* DoStorageCorruptionError.make({\n table: \"effect_agent_threads\",\n rowKey: threadId,\n message: \"A thread primary key returned more than one row.\",\n });\n }\n if (existing.length === 0) {\n yield* sql`\n INSERT INTO effect_agent_threads (\n thread_id,\n created_at,\n tail_sequence\n ) VALUES (\n ${threadId},\n ${createdAt},\n 0\n ) ON CONFLICT(thread_id) DO UPDATE SET created_at=excluded.created_at\n WHERE effect_agent_threads.created_at IS NULL\n RETURNING *`.pipe(\n threads.write,\n Effect.mapError((error) =>\n error._tag === \"SqlError\" ? storageError(\"materialize thread\")(error) : error,\n ),\n );\n\n if (lifecycle !== undefined)\n yield* sql`INSERT INTO effect_agent_lifecycle_cursors (thread_id, through_sequence)\n VALUES (${threadId}, 0) RETURNING *`.pipe(\n cursors.write,\n Effect.mapError((error) =>\n error._tag === \"SqlError\"\n ? storageError(\"initialize lifecycle source\")(error)\n : error,\n ),\n );\n\n return;\n }\n }),\n );\n }, withStorageSpan(\"DoJournal.materialize\"));\n\n const getThread = Effect.fnUntraced(function* (threadId: string) {\n return (yield* threads\n .by(\"thread_id\", threadId)\n .pipe(\n Effect.mapError((error) =>\n error._tag === \"SqlError\" ? storageError(\"read thread\")(error) : error,\n ),\n )).filter((row) => row.thread_id === threadId && row.created_at !== null);\n });\n\n const hasRecord = Effect.fnUntraced(function* (threadId: string, recordId: string) {\n const thread = (yield* getThread(threadId))[0];\n const prefix = recordCache.prefix(threadId, thread?.tail_sequence ?? 0);\n\n if (prefix !== undefined) return prefix.some((row) => row.record_id === recordId);\n\n const rows = yield* sql`SELECT record_id FROM effect_agent_canonical_records\n WHERE thread_id = ${threadId} AND record_id = ${JSON.stringify(recordId)}`.pipe(\n Effect.mapError(storageError(\"read canonical record identity\")),\n );\n\n return rows.length > 0;\n });\n\n const prepareAppend = Effect.fnUntraced(function* (request: RawAppendRequest) {\n if (\n request.threadId.length > MAX_IDENTIFIER_LENGTH ||\n request.batchId.length > MAX_IDENTIFIER_LENGTH ||\n request.executionWrites.some(\n ({ update }) => update.checkpoint.progress.runId.length > MAX_IDENTIFIER_LENGTH,\n ) ||\n request.records.some((record) => record.recordId.length > MAX_IDENTIFIER_LENGTH)\n ) {\n return yield* DoStorageError.make({\n operation: \"append canonical batch\",\n message: \"Canonical identifiers exceed the Durable Object storage bounds.\",\n });\n }\n // Archives store the full batch as one value, so their ceiling also bounds hot appends.\n // The trusted append SPI pairs captured JSON with its exact UTF-8 width.\n yield* checkValueBound(\"append canonical batch\", request.batchJson, request.batchBytes);\n for (const record of request.records) {\n if (record.recordBytes > maxStoredValueBytes)\n return yield* DoValueBoundExceeded.make({\n actualBytes: record.recordBytes,\n maxBytes: maxStoredValueBytes,\n operation: \"append canonical record\",\n });\n }\n for (const write of request.executionWrites)\n yield* checkValueBound(\"commit active execution\", write.json, write.bytes);\n\n const recordIds: Array<string> = request.records.map((record) => record.recordId);\n\n if (new Set(recordIds).size !== recordIds.length) {\n return yield* DoAppendConflict.make({\n message: `Batch ${request.batchId} contains duplicate canonical record IDs.`,\n reason: \"record-identity\",\n });\n }\n\n return request;\n });\n\n // Replay and progress validation precede this body in the same owner transaction.\n // A miss makes no native change; the ordinary path reuses any tentative batch.\n // After advancing the frontier, failures must roll back rather than fall back.\n const appendNativeBody = Effect.fnUntraced(function* (\n request: RawAppendRequest,\n first: CanonicalSequence,\n last: CanonicalSequence,\n batchInserted: boolean,\n ) {\n const db = nativeDb;\n\n // Effectful statement transformers and exported SQL spans retain the ordinary path.\n const ordinaryStatement = yield* Effect.withFiber((fiber) =>\n Effect.succeed(\n fiber.getRef(CurrentTransformer) !== undefined ||\n (fiber.getRef(References.TracerEnabled) &&\n fiber.getRef(Tracer.Tracer) !== Tracer.nativeTracer),\n ),\n );\n\n if (ordinaryStatement) return false;\n if (\n db === undefined ||\n request.executionWrites.length !== 1 ||\n request.executionWrites[0]?.update.retire ||\n request.executionWrites[0]?.update.facts.length !== 0\n )\n return false;\n\n const workPlan = yield* work.prepareClosedPair(\n request.threadId,\n first,\n last,\n request.records.map((record) => record.canonical),\n );\n\n if (workPlan === undefined) return false;\n\n const native = yield* Effect.suspend(() => {\n const query = (statement: Statement<object>, operation: string) =>\n Result.try({\n try: () => {\n const [text, parameters] = statement.compile();\n\n return db.exec(text, ...parameters).toArray();\n },\n catch: (cause) =>\n storageError(operation)(\n SqlError.make({\n reason: classifySqliteError(cause, {\n operation,\n message: \"Native canonical statement failed\",\n }),\n }),\n ),\n });\n\n return Effect.fromResult(\n Result.gen(function* () {\n const captured = physical.cachedRecords(request.threadId, first, request.records);\n\n if (captured === undefined) return undefined;\n const physicalRecords = yield* captured;\n const rows = yield* query(workPlan.advance, \"advance native work frontier\");\n\n // A zero-row predicate miss has made no change. A successful update\n // must never fall back: every later refusal rolls back this transaction.\n if (rows.length === 0) return undefined;\n const executionPlans = executions.prepareCommit(request);\n\n if (!batchInserted)\n yield* query(\n sql`INSERT INTO effect_agent_canonical_batches\n (thread_id, batch_id, first_sequence, last_sequence, producer_id_json)\n VALUES (${request.threadId}, ${JSON.stringify(request.batchId)}, ${first}, ${last}, ${request.producerIdJson})`,\n \"insert canonical batch\",\n );\n\n const inserted = yield* query(\n sql`INSERT INTO effect_agent_canonical_records ${sql.insert(physicalRecords.map((row) => row.columns))}\n ON CONFLICT(thread_id, record_id) DO NOTHING RETURNING 1`,\n \"insert canonical records\",\n );\n\n if (inserted.length !== request.records.length)\n return yield* Result.fail(\n DoAppendConflict.make({\n message: \"A canonical record ID already exists.\",\n reason: \"record-identity\",\n }),\n );\n const memberships = physicalRecords.flatMap((row) => row.memberships);\n\n for (const group of chunked(memberships, Math.floor(MAX_BOUND_PARAMETERS / 3)))\n yield* query(\n sql`INSERT INTO effect_agent_record_runs ${sql.insert(group)}`,\n \"index canonical Run membership\",\n );\n for (const pointer of workPlan.pointers)\n yield* query(pointer, \"index canonical pointers\");\n\n for (const plan of executionPlans) {\n const changed = yield* query(plan.statement, \"commit active execution\");\n const accepted = plan.accept(changed);\n\n if (Result.isFailure(accepted))\n return yield* Result.fail(\n DoAppendConflict.make({\n reason: accepted.failure.reason,\n message: \"Active execution conflicts with the captured commit\",\n ...(accepted.failure.actualTailSequence === undefined\n ? {}\n : { actualTailSequence: accepted.failure.actualTailSequence }),\n }),\n );\n }\n for (let index = 0; index < request.records.length; index++) {\n const record = request.records[index]!;\n\n recordCache.put(\n RecordRow.make({\n ...physicalRecords[index]!.columns,\n thread_id: request.threadId,\n record_id: record.recordId,\n batch_id: request.batchId,\n record_json: record.recordJson,\n sequence: CanonicalSequence.make(first + index),\n }),\n record.recordBytes,\n );\n }\n\n return rows;\n }),\n );\n });\n\n if (native === undefined) return false;\n yield* threads.write(Effect.succeed(native));\n\n return true;\n });\n\n const appendPrepared = Effect.fnUntraced(function* (\n request: RawAppendRequest,\n ): Effect.fn.Return<AppendResult, AppendError> {\n const threadRows = yield* getThread(request.threadId);\n\n const thread = threadRows.length === 1 ? threadRows[0] : undefined;\n\n if (thread === undefined)\n return yield* DoStorageCorruptionError.make({\n table: \"effect_agent_threads\",\n rowKey: request.threadId,\n message: `Expected exactly one row but found ${threadRows.length}.`,\n });\n\n // A fresh canonical batch key and absence of an active receipt prove the two\n // negative replay lookups in the same statement that retains the batch header.\n // Keep the read-first path for stale/overflowed coordinates so exact retries\n // still precede sequence and tail refusals.\n const canInsert =\n request.records.length > 0 &&\n request.expectedTailSequence === thread.tail_sequence &&\n Number.isSafeInteger(thread.tail_sequence + request.records.length);\n\n const inserted = canInsert\n ? yield* sql`INSERT INTO effect_agent_canonical_batches\n (thread_id, batch_id, first_sequence, last_sequence, producer_id_json)\n SELECT ${request.threadId}, ${JSON.stringify(request.batchId)},\n ${thread.tail_sequence + 1}, ${thread.tail_sequence + request.records.length},\n ${request.producerIdJson}\n WHERE NOT EXISTS (\n SELECT 1 FROM effect_agent_executions\n WHERE thread_id=${request.threadId} AND last_commit_id=${request.batchId}\n )\n ON CONFLICT(thread_id, batch_id) DO NOTHING RETURNING 1`.pipe(\n Effect.mapError(storageError(\"insert canonical batch\")),\n )\n : [];\n\n if (inserted.length === 0) {\n const replay = yield* executionConflict(executions.replay(request));\n\n if (replay !== undefined) return AppendResult.make(replay);\n\n const prefix = recordCache.prefix(request.threadId, thread.tail_sequence);\n\n const existing =\n prefix !== undefined && !prefix.some((row) => row.batch_id === request.batchId)\n ? undefined\n : yield* archives.replay(request.threadId, request.batchId);\n\n if (existing !== undefined) {\n if (existing.batch_json !== request.batchJson) {\n return yield* DoAppendConflict.make({\n message: `Batch ${request.batchId} already exists with different canonical content.`,\n reason: \"batch-content\",\n });\n }\n\n return AppendResult.make({\n firstSequence: existing.first_sequence,\n lastSequence: existing.last_sequence,\n replayed: true,\n });\n }\n if (canInsert)\n return yield* DoStorageCorruptionError.make({\n table: \"effect_agent_canonical_batches\",\n rowKey: request.threadId,\n message: \"Batch insertion conflicted without a durable replay receipt.\",\n });\n }\n\n yield* executionConflict(executions.rejectSuperseded(request));\n\n if (request.expectedTailSequence !== thread.tail_sequence) {\n return yield* DoAppendConflict.make({\n message:\n `Expected tail ${request.expectedTailSequence} ` + `but found ${thread.tail_sequence}.`,\n reason: \"tail\",\n actualTailSequence: thread.tail_sequence,\n });\n }\n\n const result = yield* Schema.decodeEffect(AppendResult)({\n firstSequence: thread.tail_sequence + (request.records.length === 0 ? 0 : 1),\n lastSequence: thread.tail_sequence + request.records.length,\n replayed: false,\n }).pipe(\n Effect.mapError((error) =>\n DoStorageError.make({\n cause: error,\n operation: \"append canonical batch\",\n message: error.message,\n }),\n ),\n );\n\n const { firstSequence, lastSequence } = result;\n\n yield* executionConflict(executions.validate(request));\n\n if (yield* appendNativeBody(request, firstSequence, lastSequence, inserted.length > 0)) {\n yield* progress.committed(\"canonical\").pipe(\n Effect.catchCause((cause) =>\n Effect.failCause(\n Cause.map(cause, (error) =>\n DoStorageError.make({\n operation: \"enroll canonical progress\",\n message: error.message,\n cause: error,\n }),\n ),\n ),\n ),\n );\n\n return result;\n }\n\n if (request.records.length > 0 && inserted.length === 0) {\n yield* sql`\n INSERT INTO effect_agent_canonical_batches (\n thread_id,\n batch_id,\n first_sequence,\n last_sequence,\n producer_id_json\n ) VALUES (\n ${request.threadId},\n ${JSON.stringify(request.batchId)},\n ${firstSequence},\n ${lastSequence},\n ${request.producerIdJson}\n )\n `.pipe(Effect.mapError(storageError(\"insert canonical batch\")));\n }\n yield* failpoint(\"append:after-batch-insert\");\n\n const physicalRecords = yield* physical.records(\n request.threadId,\n firstSequence,\n request.records,\n );\n\n const records = physicalRecords.map(({ columns, memberships }, index) => ({\n record: request.records[index]!,\n canonical: request.records[index]!.canonical,\n row: columns,\n memberships,\n }));\n\n // Captured scalar locators avoid parsing canonical JSON under the writer.\n // Eighteen bound columns per row stay within workerd's statement limit.\n for (const group of chunked(records, Math.floor(MAX_BOUND_PARAMETERS / 18))) {\n const inserted =\n yield* sql`INSERT INTO effect_agent_canonical_records ${sql.insert(group.map(({ row }) => row))}\n ON CONFLICT(thread_id, record_id) DO NOTHING RETURNING 1`.pipe(\n Effect.mapError(storageError(\"insert canonical records\")),\n );\n\n if (inserted.length !== group.length)\n return yield* DoAppendConflict.make({\n message: \"A canonical record ID already exists.\",\n reason: \"record-identity\",\n });\n\n const memberships = group.flatMap(({ memberships }) => memberships);\n\n for (const members of chunked(memberships, Math.floor(MAX_BOUND_PARAMETERS / 3)))\n yield* sql`INSERT INTO effect_agent_record_runs ${sql.insert(members)}`.pipe(\n Effect.mapError(storageError(\"index canonical Run membership\")),\n );\n for (const { row, record } of group) {\n recordCache.put(\n RecordRow.make({\n ...row,\n thread_id: request.threadId,\n record_id: record.recordId,\n batch_id: request.batchId,\n record_json: record.recordJson,\n sequence: Schema.decodeSync(CanonicalSequence)(row.sequence),\n }),\n record.recordBytes,\n );\n yield* failpoint(\"append:after-record-insert\");\n }\n }\n\n if (request.records.length > 0) {\n const workFields = yield* work\n .apply(\n request.threadId,\n firstSequence,\n request.records.map((record) => record.canonical),\n )\n .pipe(Effect.mapError(workFailure));\n\n yield* sql`UPDATE effect_agent_threads SET ${sql.update({ tail_sequence: lastSequence, ...workFields })}\n WHERE thread_id=${request.threadId} RETURNING *`.pipe(\n threads.write,\n Effect.mapError((error) =>\n error._tag === \"SqlError\" ? storageError(\"advance thread tail\")(error) : error,\n ),\n );\n }\n yield* executionConflict(executions.commit(request, result));\n if (request.executionWrites.length > 0) yield* failpoint(\"append:after-record-insert\");\n if (\n lifecycle !== undefined &&\n request.executionWrites.some(({ update }) =>\n update.facts.some(({ payload }) => payload._tag === \"RunStarted\"),\n )\n )\n yield* flushCanonical(request.threadId).pipe(\n Effect.provideService(SqlLifecycleRetainer, { retainMany: lifecycle.retainMany }),\n Effect.mapError((cause) =>\n DoStorageError.make({\n operation: \"retain lifecycle start prefix\",\n message: \"Lifecycle start intent could not be retained\",\n cause,\n }),\n ),\n );\n for (const { update } of request.executionWrites) {\n for (const fact of update.facts) {\n if (\n lifecycle !== undefined &&\n Schema.is(Schema.toType(LifecyclePublicationFact))(fact.payload)\n )\n yield* lifecycle\n .retain({\n id: JSON.stringify([request.threadId, \"record\", fact.recordId]),\n ownerThreadId: request.threadId,\n canonicalSequence: lastSequence,\n createdAt: fact.createdAt,\n fact: fact.payload,\n })\n .pipe(\n Effect.mapError((cause) =>\n DoStorageError.make({\n operation: \"retain operational lifecycle\",\n message: cause.message,\n cause,\n }),\n ),\n );\n }\n }\n yield* failpoint(\"append:after-tail-update\");\n\n // Retain one start prefix atomically with its canonical proof, before model/tool\n // execution. Later facts stay journal-backed until the settlement publication wave.\n if (\n lifecycle !== undefined &&\n records.some(\n ({ canonical: { payload } }) =>\n payload._tag === \"RunStarted\" || payload._tag === \"SubagentStarted\",\n )\n )\n yield* flushCanonical(request.threadId).pipe(\n Effect.provideService(SqlLifecycleRetainer, { retainMany: lifecycle.retainMany }),\n Effect.mapError((cause) =>\n DoStorageError.make({\n operation: \"retain lifecycle start prefix\",\n message: \"Lifecycle start intent could not be retained\",\n cause,\n }),\n ),\n );\n\n yield* progress.committed(\"canonical\").pipe(\n Effect.catchCause((cause) =>\n Effect.failCause(\n Cause.map(cause, (error) =>\n DoStorageError.make({\n operation: \"enroll canonical progress\",\n message: error.message,\n cause: error,\n }),\n ),\n ),\n ),\n );\n\n return result;\n });\n\n const append = Effect.fnUntraced(\n function* (\n request: RawAppendRequest,\n observed: ThreadRow,\n ): Effect.fn.Return<AppendResult, AppendError> {\n yield* prepareAppend(request);\n // The facade already read this tail. Reject a known stale writer without opening a\n // transaction; a matching tail is still checked atomically below. Replays precede tail\n // conflicts, preserving retry identity even after the log has advanced.\n if (request.records.length > 0 && request.expectedTailSequence !== observed.tail_sequence) {\n const batches = yield* sql`\n SELECT batch_id FROM effect_agent_canonical_batches\n WHERE thread_id = ${request.threadId} AND batch_id = ${JSON.stringify(request.batchId)}\n UNION ALL SELECT last_commit_id FROM effect_agent_executions\n WHERE thread_id = ${request.threadId} AND last_commit_id = ${request.batchId}\n LIMIT 1\n `.pipe(Effect.mapError(storageError(\"preflight append replay\")));\n\n // A possible replay still checks exact content in the transaction.\n if (batches.length === 0) {\n return yield* DoAppendConflict.make({\n reason: \"tail\",\n message: \"The canonical tail has advanced.\",\n actualTailSequence: observed.tail_sequence,\n });\n }\n }\n\n // Receipt arbitration may have tentatively inserted a batch. Even typed\n // contention must roll back before leaving the owner mutation gate.\n return yield* withWriteTransaction(\"append transaction\")(appendPrepared(request));\n },\n withStorageSpan(\"DoJournal.append\", isAppendContention),\n );\n\n const read = Effect.fnUntraced(function* (request: RawReadRequest) {\n const thread = (yield* getThread(request.threadId))[0];\n\n const through = Math.min(\n thread?.tail_sequence ?? 0,\n request.fromSequenceExclusive + request.limit,\n );\n\n const cached: Array<RecordRow> = [];\n\n for (let sequence = request.fromSequenceExclusive + 1; sequence <= through; sequence++) {\n const record = recordCache.get(request.threadId, sequence);\n\n if (record === undefined) break;\n cached.push(record);\n }\n if (cached.length === Math.max(0, through - request.fromSequenceExclusive)) {\n return { count: cached.length, records: Stream.fromIterable(cached) };\n }\n\n // Capture membership without retaining payloads. Append-only sequences keep each later\n // payload query inside this snapshot, even when new records arrive during consumption.\n const planRows = yield* sql<Record<string, unknown>>`\n SELECT\n sequence,\n length(CAST(${recordJson} AS BLOB)) AS record_json_bytes\n FROM effect_agent_canonical_records\n WHERE thread_id = ${request.threadId}\n AND sequence > ${request.fromSequenceExclusive}\n ORDER BY sequence\n LIMIT ${request.limit}\n `.pipe(Effect.mapError(storageError(\"read canonical records\")));\n\n const plan = yield* decodeRows(\n Schema.Array(ReadPlanRow),\n \"effect_agent_canonical_records\",\n `${request.threadId}>${request.fromSequenceExclusive}`,\n planRows,\n \"ReadPlanRow\",\n );\n\n const mismatch = () =>\n DoStorageCorruptionError.make({\n table: \"effect_agent_canonical_records\",\n rowKey: `${request.threadId}>${request.fromSequenceExclusive}`,\n message: \"Canonical read membership, sequence, or payload size changed from its read plan.\",\n });\n\n if (plan.length > request.limit) return yield* mismatch();\n\n const pages: Array<ReadPage> = [];\n let page: ReadPage | undefined;\n let pageBytes = 0;\n let previousSequence = request.fromSequenceExclusive;\n\n for (const row of plan) {\n if (row.sequence !== previousSequence + 1) return yield* mismatch();\n previousSequence = row.sequence;\n if (page === undefined || pageBytes + row.record_json_bytes > MAX_READ_PAGE_JSON_BYTES) {\n page = [row];\n pages.push(page);\n pageBytes = row.record_json_bytes;\n } else {\n page.push(row);\n pageBytes += row.record_json_bytes;\n }\n }\n\n const readPage = Effect.fnUntraced(function* (page: ReadPage) {\n const rows = yield* sql<Record<string, unknown>>`\n SELECT thread_id, sequence, record_id, ${recordBatchId(sql)} AS batch_id, ${recordJson} AS record_json\n FROM effect_agent_canonical_records\n WHERE thread_id = ${request.threadId}\n AND sequence >= ${page[0].sequence}\n AND sequence <= ${page[page.length - 1].sequence}\n ORDER BY sequence\n `.pipe(Effect.mapError(storageError(\"read canonical records\")));\n\n const decoded = yield* decodeRows(\n Schema.Array(RecordRow),\n \"effect_agent_canonical_records\",\n `${request.threadId}/${page[0].sequence}`,\n rows,\n \"RecordRow\",\n );\n\n if (\n decoded.length !== page.length ||\n decoded.some(\n (row, index) =>\n row.thread_id !== request.threadId ||\n row.sequence !== page[index].sequence ||\n storedTextBytes(row.record_json) !== page[index].record_json_bytes,\n )\n ) {\n return yield* mismatch();\n }\n\n for (const row of decoded) recordCache.put(row);\n\n return decoded;\n });\n\n return {\n count: plan.length,\n records: Stream.fromIterable(pages).pipe(\n Stream.flatMap((page) => Stream.fromIterableEffect(state.read(readPage(page)))),\n ),\n };\n });\n\n const saveCheckpoint = Effect.fnUntraced(function* (\n checkpoint: RawCheckpoint,\n ): Effect.fn.Return<void, CheckpointError> {\n if (checkpoint.threadId.length > MAX_IDENTIFIER_LENGTH) {\n return yield* DoStorageError.make({\n operation: \"save checkpoint\",\n message: \"Checkpoint identity exceeds the Durable Object storage bounds.\",\n });\n }\n yield* checkValueBound(\"save checkpoint\", checkpoint.checkpointJson);\n yield* withWriteTransaction(\"checkpoint transaction\")(\n Effect.gen(function* () {\n const threadRows = yield* getThread(checkpoint.threadId);\n\n const thread = yield* decodeSingleRow(\n Schema.Array(ThreadRow),\n \"effect_agent_threads\",\n checkpoint.threadId,\n threadRows,\n );\n\n if (checkpoint.throughSequence > thread.tail_sequence) {\n return yield* DoCheckpointConflict.make({\n reason: \"ahead-of-tail\",\n message:\n `Checkpoint sequence ${checkpoint.throughSequence} is after canonical tail ` +\n `${thread.tail_sequence}.`,\n });\n }\n\n if (!(yield* isBatchBoundary(checkpoint.threadId, checkpoint.throughSequence))) {\n return yield* DoCheckpointConflict.make({\n reason: \"not-batch-boundary\",\n message: \"Checkpoint sequence is not the end of a complete canonical batch.\",\n });\n }\n\n const checkpointRows = yield* sql<Record<string, unknown>>`\n SELECT\n thread_id,\n through_sequence,\n checkpoint_json\n FROM effect_agent_checkpoints\n WHERE thread_id = ${checkpoint.threadId}\n AND through_sequence = ${checkpoint.throughSequence}\n `.pipe(Effect.mapError(storageError(\"read idempotent checkpoint\")));\n\n const existing = yield* decodeRows(\n Schema.Array(CheckpointRow),\n \"effect_agent_checkpoints\",\n `${checkpoint.threadId}/${checkpoint.throughSequence}`,\n checkpointRows,\n );\n\n if (existing.length > 1) {\n return yield* DoStorageCorruptionError.make({\n table: \"effect_agent_checkpoints\",\n rowKey: `${checkpoint.threadId}/${checkpoint.throughSequence}`,\n message: \"A checkpoint primary key returned more than one row.\",\n });\n }\n if (existing.length === 1) {\n if (existing[0].checkpoint_json !== checkpoint.checkpointJson) {\n return yield* DoCheckpointConflict.make({\n reason: \"corrupt\",\n message: \"A different checkpoint already exists at this canonical sequence.\",\n });\n }\n\n return;\n }\n\n yield* sql`\n INSERT INTO effect_agent_checkpoints (\n thread_id,\n through_sequence,\n checkpoint_json\n ) VALUES (\n ${checkpoint.threadId},\n ${checkpoint.throughSequence},\n ${checkpoint.checkpointJson}\n )\n `.pipe(Effect.mapError(storageError(\"insert checkpoint\")));\n }),\n );\n });\n\n const loadCheckpoint = Effect.fnUntraced(function* (\n threadId: string,\n atOrBeforeSequence: CanonicalSequence,\n ) {\n const rows = yield* sql<Record<string, unknown>>`\n SELECT\n thread_id,\n through_sequence,\n checkpoint_json\n FROM effect_agent_checkpoints\n WHERE thread_id = ${threadId}\n AND through_sequence <= ${atOrBeforeSequence}\n ORDER BY through_sequence DESC\n LIMIT 1\n `.pipe(Effect.mapError(storageError(\"load checkpoint\")));\n\n return yield* decodeRows(\n Schema.Array(CheckpointRow),\n \"effect_agent_checkpoints\",\n `${threadId}<=${atOrBeforeSequence}`,\n rows,\n );\n });\n\n const isBatchBoundary = Effect.fnUntraced(function* (\n threadId: string,\n sequence: CanonicalSequence,\n ) {\n if (sequence === 0) return true;\n\n const rows = yield* sql<Record<string, unknown>>`\n SELECT last_sequence FROM effect_agent_canonical_batches\n WHERE thread_id = ${threadId}\n AND batch_id = (\n SELECT ${recordBatchId(sql)} FROM effect_agent_canonical_records\n WHERE thread_id = ${threadId} AND sequence = ${sequence}\n )\n AND last_sequence = ${sequence}\n `.pipe(Effect.mapError(storageError(\"read canonical batch boundary\")));\n\n const batches = yield* decodeRows(\n Schema.Array(Schema.Struct({ last_sequence: CanonicalSequence })),\n \"effect_agent_canonical_batches\",\n `${threadId}/${sequence}`,\n rows,\n );\n\n return batches.length === 1;\n });\n\n const sourceFailure = (cause: unknown) =>\n LifecyclePublicationError.make({ reason: \"unavailable\", cause });\n\n const sourceThreads = Effect.fnUntraced(function* () {\n const all = yield* threads.matching(\n \"lifecycle-owners\",\n (row) => row.created_at !== null,\n sql`SELECT * FROM effect_agent_threads WHERE created_at IS NOT NULL LIMIT 129`,\n 128,\n );\n\n if (all.length <= 128) return all;\n\n // Large custom hosts hydrate only owners whose journal has an unmaterialized suffix.\n return yield* Schema.decodeUnknownEffect(Schema.Array(ThreadRow))(\n yield* sql`SELECT t.* FROM effect_agent_threads t LEFT JOIN effect_agent_lifecycle_cursors c ON c.thread_id=t.thread_id\n WHERE t.created_at IS NOT NULL AND (c.thread_id IS NULL OR t.tail_sequence > c.through_sequence) ORDER BY t.thread_id LIMIT 128`,\n );\n });\n\n const initializeLifecycleSource = Effect.fnUntraced(function* () {\n if (initializedLifecycleSources.has(state)) return;\n yield* state\n .transaction(\n Effect.gen(function* () {\n const existing =\n yield* sql`SELECT name FROM sqlite_master WHERE name='effect_agent_lifecycle_cursors'`;\n\n if (existing.length === 0) {\n yield* sql`CREATE TABLE effect_agent_lifecycle_cursors (\n thread_id TEXT PRIMARY KEY, through_sequence INTEGER NOT NULL\n )`;\n // Existing inline writers already retained their facts. Enabling publication on an\n // old store starts here too; it does not publish historical facts retroactively.\n }\n // New Threads created with publication disabled have no cursor. Never advance\n // existing cursors: they can owe intent from an interrupted Attempt.\n yield* sql`INSERT INTO effect_agent_lifecycle_cursors(thread_id, through_sequence)\n SELECT thread_id, tail_sequence FROM effect_agent_threads WHERE created_at IS NOT NULL\n ON CONFLICT(thread_id) DO NOTHING`;\n yield* sourceThreads();\n }),\n )\n .pipe(\n Effect.provideService(SqlClient.SqlClient, sql),\n Effect.mapError((cause) =>\n DoStorageError.make({\n operation: \"initialize lifecycle source\",\n message: \"Lifecycle source cursor unavailable\",\n cause,\n }),\n ),\n );\n initializedLifecycleSources.add(state);\n });\n\n /** The journal is durable intent; only the bounded publication wave materializes a write set. */\n const flushCanonical = Effect.fnUntraced(function* (threadId: string, maxRecords = Infinity) {\n const { retainMany } = yield* SqlLifecycleRetainer;\n const thread = (yield* getThread(threadId))[0];\n\n if (thread === undefined) return;\n const cursor = (yield* cursors.by(\"thread_id\", threadId))[0];\n\n if (cursor === undefined || cursor.through_sequence > thread.tail_sequence)\n return yield* LifecyclePublicationError.make({ reason: \"corrupt\" });\n let through = cursor.through_sequence;\n const bound = Math.min(thread.tail_sequence, through + maxRecords);\n\n while (through < bound) {\n const page = yield* read(\n RawReadRequest.make({\n threadId,\n fromSequenceExclusive: through,\n limit: Math.min(128, bound - through),\n }),\n );\n\n const facts: Array<Parameters<SqlLifecycleRetainMany>[0][number]> = [];\n let bytes = 0;\n\n yield* Stream.runForEach(page.records, (row) =>\n Effect.gen(function* () {\n const record = yield* Schema.decodeEffect(Schema.fromJsonString(CanonicalRecord))(\n row.record_json,\n );\n\n if (record.recordId !== row.record_id || row.sequence !== through + 1)\n return yield* LifecyclePublicationError.make({ reason: \"corrupt\" });\n if (Schema.is(Schema.toType(LifecyclePublicationFact))(record.payload)) {\n if (\n bytes + storedTextBytes(row.record_json) > MAX_READ_PAGE_JSON_BYTES &&\n facts.length > 0\n ) {\n yield* retainMany(facts);\n facts.length = 0;\n bytes = 0;\n }\n facts.push({\n id: JSON.stringify([threadId, \"record\", record.recordId]),\n ownerThreadId: yield* Schema.decodeEffect(ThreadId)(threadId),\n canonicalSequence: row.sequence,\n createdAt: record.createdAt,\n fact: record.payload,\n });\n bytes += storedTextBytes(row.record_json);\n }\n through = row.sequence;\n }),\n );\n if (page.count === 0) return yield* LifecyclePublicationError.make({ reason: \"corrupt\" });\n yield* retainMany(facts);\n yield* sql`UPDATE effect_agent_lifecycle_cursors SET through_sequence=${through} WHERE thread_id=${threadId} RETURNING *`.pipe(\n cursors.write,\n );\n }\n }, Effect.mapError(sourceFailure));\n\n const flushPublications = Effect.fnUntraced(function* () {\n let owners = 0;\n\n for (const thread of yield* sourceThreads()) {\n const cursor = (yield* cursors.by(\"thread_id\", thread.thread_id))[0];\n\n if (cursor !== undefined && cursor.through_sequence === thread.tail_sequence) continue;\n yield* flushCanonical(thread.thread_id, 1024);\n if (++owners === 4) break;\n }\n }, Effect.mapError(sourceFailure));\n\n const sourcePending = Effect.gen(function* () {\n for (const thread of yield* sourceThreads()) {\n const cursor = (yield* cursors.by(\"thread_id\", thread.thread_id))[0];\n\n if (cursor === undefined || cursor.through_sequence > thread.tail_sequence)\n return yield* LifecyclePublicationError.make({ reason: \"corrupt\" });\n if (cursor.through_sequence < thread.tail_sequence) return true;\n }\n\n return false;\n }).pipe(Effect.mapError(sourceFailure));\n\n const ownedLifecycle =\n lifecycle === undefined\n ? undefined\n : {\n ...lifecycle,\n storage: {\n ...lifecycle.storage,\n retainedPendingDeadline: lifecycle.storage.pendingDeadline,\n pendingDeadline: state.read(\n Effect.gen(function* () {\n const deadline = yield* lifecycle.storage.pendingDeadline;\n\n if (!(yield* sourcePending)) return deadline;\n const now = yield* Clock.currentTimeMillis;\n\n return Option.some(Option.isSome(deadline) ? Math.min(now, deadline.value) : now);\n }),\n ),\n },\n };\n\n return {\n archives: archives.storage,\n archiveRanges: archives,\n work,\n state,\n owner,\n threads,\n lifecycle: ownedLifecycle,\n initializeLifecycleSource,\n flushCanonical,\n flushPublications,\n append,\n prepareAppend,\n appendPrepared,\n checkCommitIntent: (request: RawAppendRequest) =>\n executionConflict(executions.checkCommitIntent(request)),\n readExecution: executions.read,\n checkValueBound,\n getThread,\n hasRecord,\n isBatchBoundary,\n loadCheckpoint,\n materialize,\n read: (request: RawReadRequest) => state.read(read(request)),\n saveCheckpoint,\n withWriteTransaction,\n } as const;\n});\n\nexport type DoJournal = Effect.Success<ReturnType<typeof makeJournal>>;\n\nconst InitializedDoJournal = Context.Reference<DoJournal | undefined>(\n \"@effect-agent/storage-cloudflare/InitializedDoJournal\",\n { defaultValue: () => undefined },\n);\n\n/** Build once in the common owner, SQL, configuration, failpoint and lifecycle context. */\nexport const initializedDoJournalLayer = Layer.effect(InitializedDoJournal)(\n Effect.gen(function* () {\n const sql = yield* SqlClient.SqlClient;\n const config = yield* DoStorageConfig;\n const failpoint = yield* DoStorageFailpoint;\n\n return yield* ensureCurrentStorage(sql, failpoint.hit, config.maxStoredValueBytes);\n }),\n);\n\nexport const initializeDoJournal = (\n sql: SqlClient.SqlClient,\n failpoint: DoJournalFailpoint,\n maxStoredValueBytes: number,\n) =>\n Effect.filterOrElse(InitializedDoJournal, Predicate.isNotUndefined, () =>\n ensureCurrentStorage(sql, failpoint, maxStoredValueBytes),\n );\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;AAIA,MAAa,sBAAsB,WAChC,MAAM,SAAS,sBAAsB,MAAM,SAAS,qBAAqB,MAAM,WAAW;;AAG7F,MAAa,iBACX,QACA,aAEA,OAAO,KACL,OAAO,IAAI,OAAO,OAAO,GACzB,OAAO,QAAQ,WAAW,UAAU,OAAO,QAAQ,OAAO,KAAK,KAAK,CAAC,CAAC,CACxE;;AAGF,MAAa,wBAAwB,UACnC,OAAO,oBAAoB;CACzB,cAAc,MAAM;CACpB,GAA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C7B,MAAM,SAAS,OAAO;CACtB,MAAM,YAAY,OAAO;CAEzB,OAAO,OAAO,qBAAqB,KAAK,UAAU,KAAK,OAAO,mBAAmB;AACnF,CAAC,CACH;AAEA,MAAa,uBACX,KACA,WACA,wBAEA,OAAO,aAAa,sBAAsB,UAAU,sBAClD,qBAAqB,KAAK,WAAW,mBAAmB,CAC1D"}
package/dist/index.d.mts CHANGED
@@ -5,7 +5,7 @@ import { t as DoStorageFailpoint_d_exports } from "./DoStorageFailpoint.mjs";
5
5
  import { t as DoMessageDeliveryStore_d_exports } from "./DoMessageDeliveryStore.mjs";
6
6
  import { t as DoScheduleStore_d_exports } from "./DoScheduleStore.mjs";
7
7
  import { t as DoStorageVersion_d_exports } from "./DoStorageVersion-Mc7CXMdN.mjs";
8
- import { r as DoThreadStore_d_exports } from "./DoThreadStore-BzYJjm4O.mjs";
8
+ import { r as DoThreadStore_d_exports } from "./DoThreadStore-BPSHQZ68.mjs";
9
9
  import { t as DoSubmissionLedger_d_exports } from "./DoSubmissionLedger.mjs";
10
10
  import { t as DoSubscriptionStore_d_exports } from "./DoSubscriptionStore.mjs";
11
11
  import { t as MemoryProtocol_d_exports } from "./MemoryProtocol.mjs";
package/dist/index.mjs CHANGED
@@ -5,7 +5,7 @@ import { t as DoMessageDeliveryStore_exports } from "./DoMessageDeliveryStore.mj
5
5
  import { t as DoMemoryStore_exports } from "./DoMemoryStore.mjs";
6
6
  import { t as DoScheduleStore_exports } from "./DoScheduleStore.mjs";
7
7
  import { t as DoStorageVersion_exports } from "./DoStorageVersion.mjs";
8
- import { t as DoThreadStore_exports } from "./DoThreadStore-Bi7eQuWE.mjs";
8
+ import { t as DoThreadStore_exports } from "./DoThreadStore-DwCQ_kay.mjs";
9
9
  import { t as DoSubmissionLedger_exports } from "./DoSubmissionLedger.mjs";
10
10
  import { t as DoSubscriptionStore_exports } from "./DoSubscriptionStore.mjs";
11
11
  import { t as MemoryProtocol_exports } from "./MemoryProtocol.mjs";
@@ -1,6 +1,6 @@
1
1
  import { DoStorageCompatibilityError, DoStorageCorruptionError, DoStorageError } from "./DoStorageError.mjs";
2
2
  import { backfillPeerMessageRetention } from "@yielded/agent-storage-sql/sql-message-delivery-store";
3
- import { SqlStorageOwner } from "@yielded/agent/sql-memory-store";
3
+ import { SqlStorageOwner } from "@yielded/agent/sql-storage-owner";
4
4
  import { Effect, Option, Schema } from "effect";
5
5
  import * as SqlClient$1 from "effect/sql/SqlClient";
6
6
  import { createSqlThreadWorkTables } from "@yielded/agent-storage-sql/sql-thread-work";
@@ -202,4 +202,4 @@ const ensureDoStorageLayout = Effect.fnUntraced(function* () {
202
202
  //#endregion
203
203
  export { ensureDoStorageLayout as n, readDoStorageHeader as r, CurrentDoStorageVersion as t };
204
204
 
205
- //# sourceMappingURL=migrations-CAO_akhD.mjs.map
205
+ //# sourceMappingURL=migrations-CJAHO3Y7.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"migrations-CJAHO3Y7.mjs","names":["SqlClient"],"sources":["../src/internal/migrations.ts"],"sourcesContent":["import { backfillPeerMessageRetention } from \"@yielded/agent-storage-sql/sql-message-delivery-store\";\nimport {\n SQL_PROMPT_PREDICATE,\n upgradeExecutionCheckpoints,\n} from \"@yielded/agent-storage-sql/sql-thread-native-reads\";\nimport { createSqlThreadWorkTables } from \"@yielded/agent-storage-sql/sql-thread-work\";\nimport { makeSqliteLayoutInspection } from \"@yielded/agent-storage-sql/sqlite-layout-inspection\";\nimport { CURRENT_RECORD_FORMAT } from \"@yielded/agent/records\";\nimport { SqlStorageOwner } from \"@yielded/agent/sql-storage-owner\";\nimport { Effect, Option, Schema } from \"effect\";\nimport * as SqlClient from \"effect/sql/SqlClient\";\nimport type { SqlError } from \"effect/sql/SqlError\";\n\nimport {\n DoStorageCompatibilityError,\n DoStorageCorruptionError,\n DoStorageError,\n} from \"../DoStorageError.ts\";\n\nexport const CurrentDoStorageVersion = 28;\n\n/** Fresh layout only. Unsupported stores are rejected before these statements execute. */\nconst layoutStatements = [\n \"CREATE TABLE effect_agent_threads ( thread_id TEXT PRIMARY KEY NOT NULL, created_at TEXT, tail_sequence INTEGER NOT NULL, work_version INTEGER NOT NULL DEFAULT 3, work_state TEXT NOT NULL DEFAULT 'ready', work_through_sequence INTEGER NOT NULL DEFAULT 0, work_reporting INTEGER NOT NULL DEFAULT 0, work_entry_count INTEGER NOT NULL DEFAULT 0, worker_input_sequence INTEGER, worker_settlement_sequence INTEGER )\",\n \"CREATE TABLE effect_agent_envelopes (envelope_key INTEGER PRIMARY KEY NOT NULL, content_digest TEXT UNIQUE NOT NULL, prefix TEXT NOT NULL, before_payload TEXT NOT NULL, before_record_id TEXT NOT NULL, suffix TEXT NOT NULL)\",\n \"CREATE TABLE effect_agent_run_keys (run_key INTEGER PRIMARY KEY NOT NULL, thread_id TEXT NOT NULL, run_id TEXT NOT NULL, UNIQUE (thread_id, run_id), FOREIGN KEY (thread_id) REFERENCES effect_agent_threads(thread_id) ON DELETE RESTRICT)\",\n \"CREATE TABLE effect_agent_definitions (definition_key INTEGER PRIMARY KEY NOT NULL, content_digest TEXT UNIQUE NOT NULL, value_json TEXT NOT NULL)\",\n \"CREATE TABLE effect_agent_executions (thread_id TEXT NOT NULL, run_id TEXT NOT NULL, input_sequence INTEGER NOT NULL, revision INTEGER NOT NULL, checkpoint_json TEXT NOT NULL, last_commit_id TEXT, last_commit_digest TEXT, PRIMARY KEY (thread_id, run_id), FOREIGN KEY (thread_id) REFERENCES effect_agent_threads(thread_id) ON DELETE RESTRICT)\",\n \"CREATE TABLE effect_agent_canonical_batches ( thread_id TEXT NOT NULL, batch_id TEXT NOT NULL, first_sequence INTEGER NOT NULL, last_sequence INTEGER NOT NULL, producer_id_json TEXT NOT NULL, CONSTRAINT effect_agent_canonical_batches_span CHECK (first_sequence >= 1 AND last_sequence >= first_sequence AND last_sequence - first_sequence < 256), PRIMARY KEY (thread_id, batch_id), FOREIGN KEY (thread_id) REFERENCES effect_agent_threads(thread_id) ON DELETE RESTRICT )\",\n \"CREATE TABLE effect_agent_canonical_records ( thread_id TEXT NOT NULL, sequence INTEGER NOT NULL, record_id TEXT NOT NULL, created_at_json TEXT NOT NULL, envelope_key INTEGER NOT NULL, payload_json TEXT, record_tag INTEGER NOT NULL, run_id INTEGER, tool_call_id TEXT, input_kind TEXT, source_submission_id TEXT, message_id TEXT, submission_id TEXT, application_input INTEGER NOT NULL, context_through INTEGER, context_kind TEXT, worker_thread_id TEXT, handoff INTEGER NOT NULL, PRIMARY KEY (thread_id, sequence), UNIQUE (thread_id, record_id), FOREIGN KEY (thread_id) REFERENCES effect_agent_threads(thread_id) ON DELETE RESTRICT )\",\n 'CREATE TABLE \"effect_agent_record_runs\" ( thread_id TEXT NOT NULL, run_id INTEGER NOT NULL, sequence INTEGER NOT NULL, PRIMARY KEY (thread_id, run_id, sequence), FOREIGN KEY (thread_id, sequence) REFERENCES \"effect_agent_canonical_records\"(thread_id, sequence) ON DELETE RESTRICT ) WITHOUT ROWID',\n \"CREATE TABLE effect_agent_rollover_buckets (thread_id TEXT NOT NULL, height INTEGER NOT NULL, bucket INTEGER NOT NULL, sequence INTEGER NOT NULL, PRIMARY KEY (thread_id, height, bucket, sequence), FOREIGN KEY (thread_id, sequence) REFERENCES effect_agent_canonical_records(thread_id, sequence) ON DELETE RESTRICT) WITHOUT ROWID\",\n \"CREATE TABLE effect_agent_tool_declarations (thread_id TEXT NOT NULL, settlement_record_id TEXT NOT NULL, sequence INTEGER NOT NULL, PRIMARY KEY (thread_id, settlement_record_id, sequence), FOREIGN KEY (thread_id, sequence) REFERENCES effect_agent_canonical_records(thread_id, sequence) ON DELETE RESTRICT)\",\n \"CREATE INDEX effect_agent_tool_declarations_sequence ON effect_agent_tool_declarations(thread_id, sequence)\",\n \"CREATE TABLE effect_agent_record_refusals (thread_id TEXT NOT NULL, reservation_record_id TEXT NOT NULL, sequence INTEGER NOT NULL, PRIMARY KEY (thread_id, reservation_record_id, sequence), FOREIGN KEY (thread_id, sequence) REFERENCES effect_agent_canonical_records(thread_id, sequence) ON DELETE RESTRICT)\",\n \"CREATE INDEX effect_agent_record_refusals_sequence ON effect_agent_record_refusals(thread_id, sequence)\",\n \"CREATE TABLE effect_agent_checkpoints ( thread_id TEXT NOT NULL, through_sequence INTEGER NOT NULL, checkpoint_json TEXT NOT NULL, PRIMARY KEY (thread_id, through_sequence), FOREIGN KEY (thread_id) REFERENCES effect_agent_threads(thread_id) ON DELETE RESTRICT )\",\n \"CREATE TABLE effect_agent_submissions ( submission_id TEXT PRIMARY KEY NOT NULL, thread_id TEXT NOT NULL, queue_sequence INTEGER NOT NULL, principal TEXT NOT NULL, idempotency_key TEXT NOT NULL, agent_id TEXT NOT NULL, definition_key INTEGER NOT NULL, deployment_id TEXT NOT NULL, input_json TEXT NOT NULL, input_digest TEXT NOT NULL, receipt_id TEXT NOT NULL, state TEXT NOT NULL, settled_outcome TEXT, settled_record_id TEXT, finalized_at TEXT, created_at TEXT NOT NULL, ready_at TEXT, input_applied_record_id TEXT, input_applied_sequence INTEGER, joined_host_submission_id TEXT, suspended_reason_json TEXT, suspended_at TEXT, unknown_reason TEXT, unknown_tool_call_ids_json TEXT, parent_submission_id TEXT, parent_tool_call_id TEXT, admission_group TEXT, admission_fence_json TEXT, worker_admission_json TEXT, message_admission_json TEXT, UNIQUE (thread_id, principal, idempotency_key), UNIQUE (thread_id, queue_sequence) )\",\n \"CREATE INDEX effect_agent_submissions_joined_host ON effect_agent_submissions (joined_host_submission_id) WHERE joined_host_submission_id IS NOT NULL\",\n \"CREATE INDEX effect_agent_submissions_parent ON effect_agent_submissions (parent_submission_id) WHERE parent_submission_id IS NOT NULL\",\n \"CREATE INDEX effect_agent_submissions_group ON effect_agent_submissions (thread_id, admission_group) WHERE admission_group IS NOT NULL AND state <> 'settled'\",\n \"CREATE TABLE effect_agent_abort_intents ( submission_id TEXT PRIMARY KEY NOT NULL, author TEXT NOT NULL, reason TEXT NOT NULL, requested_at TEXT NOT NULL, canonical_record_id TEXT, FOREIGN KEY (submission_id) REFERENCES effect_agent_submissions(submission_id) ON DELETE RESTRICT )\",\n \"CREATE TABLE effect_agent_approval_decisions ( submission_id TEXT NOT NULL, tool_call_id TEXT NOT NULL, decision TEXT NOT NULL, resolver TEXT NOT NULL, reason TEXT NOT NULL, decided_at TEXT NOT NULL, PRIMARY KEY (submission_id, tool_call_id), FOREIGN KEY (submission_id) REFERENCES effect_agent_submissions(submission_id) ON DELETE RESTRICT )\",\n \"CREATE TABLE effect_agent_unknown_resolutions ( submission_id TEXT NOT NULL, tool_call_id TEXT NOT NULL, resolution_kind TEXT NOT NULL, author TEXT NOT NULL, reason TEXT NOT NULL, resolution_json TEXT NOT NULL, resolved_at TEXT NOT NULL, PRIMARY KEY (submission_id, tool_call_id, resolution_kind), FOREIGN KEY (submission_id) REFERENCES effect_agent_submissions(submission_id) ON DELETE RESTRICT )\",\n \"CREATE TABLE effect_agent_child_reservations ( reservation_id TEXT PRIMARY KEY NOT NULL, parent_submission_id TEXT NOT NULL, parent_tool_call_id TEXT NOT NULL, child_submission_id TEXT, status TEXT NOT NULL, allocation_json TEXT NOT NULL, allocation_digest TEXT NOT NULL, accounting_json TEXT, reserved_at TEXT NOT NULL, release_began_at TEXT, released_at TEXT, UNIQUE (parent_submission_id, parent_tool_call_id), FOREIGN KEY (parent_submission_id) REFERENCES effect_agent_submissions(submission_id) ON DELETE RESTRICT )\",\n \"CREATE TABLE effect_agent_child_settlements ( parent_submission_id TEXT NOT NULL, child_submission_id TEXT NOT NULL, child_outcome TEXT, recorded_at TEXT NOT NULL, PRIMARY KEY (parent_submission_id, child_submission_id) )\",\n 'CREATE INDEX effect_agent_records_call ON \"effect_agent_canonical_records\"(thread_id, record_tag, run_id, tool_call_id) WHERE tool_call_id IS NOT NULL',\n \"CREATE INDEX effect_agent_records_run_input ON \\\"effect_agent_canonical_records\\\"(thread_id, run_id) WHERE record_tag = 30 AND input_kind = 'user'\",\n 'CREATE INDEX effect_agent_records_subtree ON \"effect_agent_canonical_records\"(thread_id, source_submission_id, sequence) WHERE record_tag = 22',\n 'CREATE INDEX effect_agent_records_worker_input ON \"effect_agent_canonical_records\"(thread_id, message_id) WHERE record_tag = 34',\n \"CREATE INDEX effect_agent_submissions_nonterminal ON effect_agent_submissions (thread_id, queue_sequence) WHERE state <> 'settled'\",\n \"CREATE TABLE effect_agent_message_deliveries ( owner_thread_id TEXT NOT NULL, message_id TEXT NOT NULL, version INTEGER NOT NULL, state TEXT NOT NULL, deadline_at_millis INTEGER, record_json TEXT NOT NULL, peer_retained_until_millis INTEGER, PRIMARY KEY (owner_thread_id, message_id) )\",\n \"CREATE INDEX effect_agent_message_deliveries_due ON effect_agent_message_deliveries (deadline_at_millis, owner_thread_id, message_id) WHERE deadline_at_millis IS NOT NULL\",\n \"CREATE INDEX effect_agent_message_deliveries_pending ON \\\"effect_agent_message_deliveries\\\"(owner_thread_id, message_id) WHERE state NOT IN ('processed', 'refused')\",\n \"CREATE TABLE effect_agent_worker_stops (thread_id TEXT PRIMARY KEY NOT NULL, terminal TEXT)\",\n \"CREATE INDEX effect_agent_worker_starts ON effect_agent_message_deliveries(owner_thread_id, json_extract(record_json, '$.envelope.workerAdmission.origin.worker.delegationId'), json_extract(record_json, '$.envelope.workerAdmission.origin.worker.targetAgentId'), message_id) WHERE message_id = json_extract(record_json, '$.envelope.workerAdmission.origin.firstMessageId')\",\n \"CREATE INDEX effect_agent_worker_pending ON effect_agent_message_deliveries(owner_thread_id, json_extract(record_json, '$.envelope.workerAdmission.origin.worker.threadId'), message_id) WHERE state IN ('pending', 'parked') AND json_extract(record_json, '$.receipt') IS NULL\",\n \"CREATE TABLE effect_agent_meta ( key TEXT PRIMARY KEY NOT NULL, value TEXT NOT NULL )\",\n 'CREATE INDEX effect_agent_records_tag ON \"effect_agent_canonical_records\"(thread_id, record_tag, sequence)',\n 'CREATE INDEX effect_agent_records_handoff ON \"effect_agent_canonical_records\"(thread_id, sequence) WHERE handoff = 1',\n \"CREATE INDEX effect_agent_records_application_input ON effect_agent_canonical_records(thread_id, sequence) WHERE application_input = 1\",\n `CREATE INDEX effect_agent_records_prompt ON effect_agent_canonical_records(thread_id, sequence) WHERE ${SQL_PROMPT_PREDICATE}`,\n \"CREATE INDEX effect_agent_records_admitted_input ON effect_agent_canonical_records(thread_id, sequence) WHERE record_tag = 30 AND submission_id IS NOT NULL\",\n \"CREATE INDEX effect_agent_records_worker_funding ON effect_agent_canonical_records(thread_id, source_submission_id, sequence, message_id) WHERE record_tag = 34\",\n \"CREATE INDEX effect_agent_records_worker_completed ON effect_agent_canonical_records(thread_id, message_id, sequence) WHERE record_tag = 32\",\n \"CREATE INDEX effect_agent_records_worker_stop ON effect_agent_canonical_records(thread_id, worker_thread_id, sequence) WHERE record_tag = 38\",\n \"CREATE INDEX effect_agent_message_deliveries_identity ON effect_agent_message_deliveries(owner_thread_id, json_quote(message_id))\",\n \"CREATE INDEX effect_agent_message_deliveries_peer_retained ON effect_agent_message_deliveries(owner_thread_id, peer_retained_until_millis, message_id) WHERE peer_retained_until_millis IS NOT NULL\",\n \"CREATE INDEX effect_agent_message_deliveries_peer ON effect_agent_message_deliveries(owner_thread_id, message_id) WHERE state NOT IN ('processed', 'refused') AND json_extract(record_json, '$.envelope.messageAdmission.peerName') IS NOT NULL\",\n \"CREATE TABLE effect_agent_journal_ranges (thread_id TEXT NOT NULL, first_sequence INTEGER NOT NULL, last_sequence INTEGER NOT NULL, record_count INTEGER NOT NULL, batch_count INTEGER NOT NULL, byte_count INTEGER NOT NULL, state TEXT NOT NULL, locator TEXT, PRIMARY KEY (thread_id, first_sequence), FOREIGN KEY (thread_id) REFERENCES effect_agent_threads(thread_id) ON DELETE RESTRICT)\",\n \"CREATE TABLE effect_agent_archive_batches (thread_id TEXT NOT NULL, batch_id TEXT NOT NULL, range_first_sequence INTEGER NOT NULL, batch_json TEXT NOT NULL, PRIMARY KEY (thread_id, batch_id), FOREIGN KEY (thread_id, batch_id) REFERENCES effect_agent_canonical_batches(thread_id, batch_id) ON DELETE RESTRICT, CONSTRAINT effect_agent_archive_batches_range_fkey FOREIGN KEY (thread_id, range_first_sequence) REFERENCES effect_agent_journal_ranges(thread_id, first_sequence) ON DELETE RESTRICT)\",\n \"CREATE TABLE effect_agent_archive_records (thread_id TEXT NOT NULL, sequence INTEGER NOT NULL, range_first_sequence INTEGER NOT NULL, record_json TEXT NOT NULL, PRIMARY KEY (thread_id, sequence), FOREIGN KEY (thread_id, sequence) REFERENCES effect_agent_canonical_records(thread_id, sequence) ON DELETE RESTRICT, CONSTRAINT effect_agent_archive_records_range_fkey FOREIGN KEY (thread_id, range_first_sequence) REFERENCES effect_agent_journal_ranges(thread_id, first_sequence) ON DELETE RESTRICT)\",\n \"CREATE UNIQUE INDEX effect_agent_canonical_batches_sequence ON effect_agent_canonical_batches(thread_id, first_sequence)\",\n \"CREATE TABLE effect_agent_live_child_reservations (reservation_id TEXT PRIMARY KEY NOT NULL, thread_id TEXT NOT NULL)\",\n \"CREATE INDEX effect_agent_live_child_reservations_thread ON effect_agent_live_child_reservations(thread_id, reservation_id)\",\n // Compact native positions keep accepted identities out of bounded export cursors.\n // Persistent scalar FIFO derivatives; rebuild from canonical input/settlement boundaries.\n // Writer-local import indexes; rows are removed before publication.\n \"CREATE TABLE effect_agent_import_delivery_visits (thread_id TEXT NOT NULL, message_id TEXT NOT NULL, path_id TEXT NOT NULL, completed INTEGER NOT NULL, PRIMARY KEY (thread_id, message_id))\",\n \"CREATE INDEX effect_agent_import_delivery_visits_path ON effect_agent_import_delivery_visits(thread_id, path_id)\",\n \"CREATE TRIGGER effect_agent_live_child_insert AFTER INSERT ON effect_agent_child_reservations FOR EACH ROW BEGIN INSERT INTO effect_agent_live_child_reservations (reservation_id, thread_id) SELECT NEW.reservation_id, thread_id FROM effect_agent_submissions WHERE submission_id=NEW.parent_submission_id AND NEW.status<>'released'; END\",\n \"CREATE TRIGGER effect_agent_live_child_update AFTER UPDATE ON effect_agent_child_reservations FOR EACH ROW WHEN OLD.reservation_id IS NOT NEW.reservation_id OR OLD.parent_submission_id IS NOT NEW.parent_submission_id OR OLD.parent_tool_call_id IS NOT NEW.parent_tool_call_id OR OLD.child_submission_id IS NOT NEW.child_submission_id OR OLD.status IS NOT NEW.status OR OLD.allocation_json IS NOT NEW.allocation_json OR OLD.allocation_digest IS NOT NEW.allocation_digest OR OLD.accounting_json IS NOT NEW.accounting_json OR OLD.reserved_at IS NOT NEW.reserved_at OR OLD.release_began_at IS NOT NEW.release_began_at OR OLD.released_at IS NOT NEW.released_at BEGIN DELETE FROM effect_agent_live_child_reservations WHERE reservation_id=OLD.reservation_id; INSERT INTO effect_agent_live_child_reservations (reservation_id, thread_id) SELECT NEW.reservation_id, thread_id FROM effect_agent_submissions WHERE submission_id=NEW.parent_submission_id AND NEW.status<>'released'; END\",\n \"CREATE TRIGGER effect_agent_live_child_delete AFTER DELETE ON effect_agent_child_reservations FOR EACH ROW BEGIN DELETE FROM effect_agent_live_child_reservations WHERE reservation_id=OLD.reservation_id; END\",\n \"CREATE INDEX effect_agent_message_deliveries_capacity ON effect_agent_message_deliveries(owner_thread_id, (COALESCE(json_extract(record_json, '$.envelope.messageAdmission._tag'), '') = 'WorkerUpdate'), message_id) WHERE state IN ('pending', 'accepted', 'parked')\",\n] as const;\n\nconst headerStatement =\n \"CREATE TABLE effect_agent_schema (singleton INTEGER PRIMARY KEY NOT NULL CHECK (singleton = 1), layout_version INTEGER NOT NULL CHECK (layout_version > 0), record_format TEXT NOT NULL CHECK (length(record_format) > 0))\";\n\nconst layoutObjects = (statements: ReadonlyArray<string>) =>\n statements.map((statement, index) => {\n const name = /^CREATE (TABLE|(?:UNIQUE )?INDEX|TRIGGER) \"?([a-z_][a-z_0-9]*)\"?/.exec(statement);\n\n // oxlint-disable-next-line effect/no-untyped-throw, effect/no-native-error -- The synchronous SQL layout parser rejects malformed developer-authored declarations before storage mutation.\n if (name === null) throw new Error(\"Invalid fresh layout statement\");\n\n return [name[1].replace(\"UNIQUE \", \"\").toLowerCase(), name[2], index] as const;\n });\n\nconst Legacy = Schema.Tuple([\n Schema.Struct({\n key: Schema.Literal(\"storage_version\"),\n value: Schema.String.check(Schema.isPattern(/^(0|[1-9][0-9]*)$/)).pipe(\n Schema.decodeTo(Schema.FiniteFromString),\n Schema.decodeTo(Schema.Int),\n ),\n }),\n]);\n\nexport interface DoStorageHeader {\n readonly layoutVersion: number;\n readonly recordFormat: string;\n}\n\nconst incompatible = (actualVersion: number, message: string) =>\n DoStorageCompatibilityError.make({\n actualVersion,\n supportedVersion: CurrentDoStorageVersion,\n message: `${message} Keep the original store; the store was not changed.`,\n });\n\nconst storageError = (cause: SqlError) =>\n DoStorageError.make({ operation: \"inspect storage layout\", cause, message: cause.message });\n\nconst inspection = (version: number, statements: ReadonlyArray<string>) =>\n makeSqliteLayoutInspection({\n version,\n statements,\n objects: layoutObjects(statements),\n headerStatement,\n incompatible,\n storageError,\n corruption: (table) =>\n DoStorageCorruptionError.make({\n table,\n rowKey: \"schema\",\n message: \"Malformed storage layout or version header.\",\n }),\n });\n\n// Released predecessors retain the same record format and canonical tables.\nconst addedIndexes = new Set([\"effect_agent_message_deliveries_peer_retained\"]);\n\nconst layout27Statements = [\n ...layoutStatements,\n \"CREATE INDEX effect_agent_canonical_batches_last ON effect_agent_canonical_batches(thread_id, last_sequence)\",\n];\n\nconst layout25Statements = layoutObjects(layout27Statements)\n .filter(([, name]) => !addedIndexes.has(name))\n .map(([, , index]) =>\n layout27Statements[index]\n .replace(\", peer_retained_until_millis INTEGER\", \"\")\n .replace(\n \"'$.envelope.messageAdmission.peerName') IS NOT NULL\",\n \"'$.envelope.messageAdmission.schemaVersion') = 1\",\n ),\n );\n\nconst { decode, readObjects, readHeader } = inspection(CurrentDoStorageVersion, layoutStatements);\nconst layout25 = inspection(25, layout25Statements);\nconst layout26 = inspection(26, layout27Statements);\nconst layout27 = inspection(27, layout27Statements);\n\nconst inspectStorage = Effect.fnUntraced(function* (\n allowUpgrade = false,\n): Effect.fn.Return<\n DoStorageHeader | undefined,\n DoStorageCompatibilityError | DoStorageCorruptionError | DoStorageError,\n SqlClient.SqlClient\n> {\n const sql = (yield* SqlClient.SqlClient).withoutTransforms();\n\n const objects = yield* readObjects();\n\n const meta = objects.find((row) => row.name === \"effect_agent_meta\");\n\n if (meta === undefined) {\n if (objects.length === 0) return undefined;\n\n return yield* incompatible(0, \"Unversioned or incomplete Effect Agent storage.\");\n }\n\n const [legacy] = yield* decode(\n Legacy,\n yield* sql<Record<string, unknown>>`\n SELECT * FROM effect_agent_meta WHERE key = 'storage_version'\n `.pipe(Effect.mapError(storageError)),\n \"effect_agent_meta\",\n );\n\n const version = legacy.value;\n\n if (allowUpgrade && (version === 25 || version === 26 || version === 27)) {\n if (version === 25 && objects.some(({ name }) => addedIndexes.has(name)))\n return yield* incompatible(version, \"Mixed layout 25 and 26 objects.\");\n const predecessor = version === 25 ? layout25 : version === 26 ? layout26 : layout27;\n const header = yield* predecessor.readHeader(objects, version);\n\n yield* predecessor.readManagedTriggers(true);\n\n return header;\n }\n\n return yield* readHeader(objects, version);\n});\n\n/** Read-only inspection. The caller owns a snapshot covering this check and its export reads. */\nexport const readDoStorageHeader = Effect.fnUntraced(function* () {\n const header = yield* inspectStorage();\n\n if (header === undefined)\n return yield* incompatible(0, \"No initialized Thread storage to export.\");\n\n return header;\n});\n\n/** Initialize fresh storage or atomically upgrade the exact released layouts 25–27. */\nconst initializeDoStorageLayout = Effect.fn(\"DoStorage.initializeLayout\")(function* () {\n const sql = (yield* SqlClient.SqlClient).withoutTransforms();\n\n return yield* sql\n .withTransaction(\n Effect.gen(function* () {\n const header = yield* inspectStorage(true);\n\n if (header?.layoutVersion === 25) {\n yield* sql`ALTER TABLE effect_agent_message_deliveries ADD COLUMN peer_retained_until_millis INTEGER`;\n yield* backfillPeerMessageRetention().pipe(\n Effect.catchTag(\"MessageDeliveryError\", () =>\n DoStorageCorruptionError.make({\n table: \"effect_agent_message_deliveries\",\n rowKey: \"upgrade\",\n message: \"Invalid layout-25 delivery evidence; upgrade rolled back.\",\n }),\n ),\n );\n yield* sql`DROP INDEX effect_agent_message_deliveries_peer`;\n for (const [, name, index] of layoutObjects(layoutStatements))\n if (addedIndexes.has(name) || name === \"effect_agent_message_deliveries_peer\")\n yield* sql.unsafe(layoutStatements[index]).withoutTransform;\n }\n if (header?.layoutVersion === 25 || header?.layoutVersion === 26) {\n yield* upgradeExecutionCheckpoints(undefined).pipe(\n Effect.catchTag(\"ThreadStoreError\", (cause) =>\n DoStorageCorruptionError.make({\n table: \"effect_agent_executions\",\n rowKey: \"upgrade\",\n message: `Invalid retained execution; upgrade rolled back: ${cause.message}`,\n }),\n ),\n );\n }\n if (header !== undefined && header.layoutVersion < CurrentDoStorageVersion) {\n yield* sql`DROP INDEX effect_agent_canonical_batches_last`;\n yield* sql`UPDATE effect_agent_schema SET layout_version=${CurrentDoStorageVersion} WHERE singleton=1`;\n yield* sql`UPDATE effect_agent_meta SET value=${String(CurrentDoStorageVersion)} WHERE key='storage_version'`;\n\n return yield* readDoStorageHeader();\n }\n if (header !== undefined) return header;\n for (const statement of layoutStatements) yield* sql.unsafe(statement).withoutTransform;\n yield* createSqlThreadWorkTables().pipe(\n Effect.mapError((cause) =>\n DoStorageError.make({\n operation: \"initialize work catalogue\",\n message: cause.message,\n cause,\n }),\n ),\n );\n yield* sql.unsafe(headerStatement).withoutTransform;\n yield* sql`INSERT INTO effect_agent_schema (singleton, layout_version, record_format) VALUES (1, ${CurrentDoStorageVersion}, ${CURRENT_RECORD_FORMAT})`;\n yield* sql`INSERT INTO effect_agent_meta (key, value) VALUES ('storage_version', ${String(CurrentDoStorageVersion)})`;\n\n return yield* readDoStorageHeader();\n }),\n )\n .pipe(Effect.catchTag(\"SqlError\", storageError));\n});\n\nconst initializedLayouts = new WeakMap<object, DoStorageHeader>();\n\n/** Share committed inspection within one live Object owner; maintenance invalidates it. */\nexport const ensureDoStorageLayout = Effect.fnUntraced(function* () {\n const sql = yield* SqlClient.SqlClient;\n const owner = yield* SqlStorageOwner;\n\n // A caller-owned transaction can still roll back after this initializer returns.\n if (owner === undefined || Option.isSome(yield* Effect.serviceOption(sql.transactionService)))\n return yield* initializeDoStorageLayout();\n\n const identity = owner.identity ?? owner;\n\n return yield* owner.read(\n Effect.gen(function* () {\n const previous = initializedLayouts.get(identity);\n\n if (previous !== undefined) return previous;\n const header = yield* initializeDoStorageLayout();\n\n const invalidate = () => {\n initializedLayouts.delete(identity);\n owner.invalidators.delete(invalidate);\n };\n\n initializedLayouts.set(identity, header);\n owner.invalidators.add(invalidate);\n\n return header;\n }),\n );\n});\n"],"mappings":";;;;;;;;;;AAmBA,MAAa,0BAA0B;;AAGvC,MAAM,mBAAmB;CACvB;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA,yGAAyG;CACzG;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CAIA;CACA;CACA;CACA;CACA;CACA;AACF;AAEA,MAAM,kBACJ;AAEF,MAAM,iBAAiB,eACrB,WAAW,KAAK,WAAW,UAAU;CACnC,MAAM,OAAO,mEAAmE,KAAK,SAAS;CAG9F,IAAI,SAAS,MAAM,MAAM,IAAI,MAAM,gCAAgC;CAEnE,OAAO;EAAC,KAAK,EAAE,CAAC,QAAQ,WAAW,EAAE,CAAC,CAAC,YAAY;EAAG,KAAK;EAAI;CAAK;AACtE,CAAC;AAEH,MAAM,SAAS,OAAO,MAAM,CAC1B,OAAO,OAAO;CACZ,KAAK,OAAO,QAAQ,iBAAiB;CACrC,OAAO,OAAO,OAAO,MAAM,OAAO,UAAU,mBAAmB,CAAC,CAAC,CAAC,KAChE,OAAO,SAAS,OAAO,gBAAgB,GACvC,OAAO,SAAS,OAAO,GAAG,CAC5B;AACF,CAAC,CACH,CA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AO,UAAU;EACtC;EAEA,mBAAmB,IAAI,UAAU,MAAM;EACvC,MAAM,aAAa,IAAI,UAAU;EAEjC,OAAO;CACT,CAAC,CACH;AACF,CAAC"}
package/package.json CHANGED
@@ -1 +1 @@
1
- {"name":"@yielded/agent-storage-cloudflare","version":"0.1.0-beta.179","dependencies":{"@effect/platform-browser":"4.0.4","@effect/sql-sqlite-do":"4.0.4","@yielded/agent":"0.1.0-beta.179","@yielded/agent-storage-sql":"0.1.0-beta.179"},"devDependencies":{"@cloudflare/vitest-plugin":"1.4.0","@cloudflare/workers-types":"5.20260926.1","@effect/vitest":"4.0.4","@yielded/agent-testing":"0.1.0-beta.179","effect":"4.0.4","typescript":"7.0.2","vite":"npm:@voidzero-dev/vite-plus-core@1.1.0","vite-plus":"1.1.0","vitest":"5.0.3"},"peerDependencies":{"effect":"^4.0.3"},"exports":{".":{"types":"./dist/index.d.mts","default":"./dist/index.mjs"},"./do-memory-store":{"types":"./dist/DoMemoryStore.d.mts","default":"./dist/DoMemoryStore.mjs"},"./do-schedule-store":{"types":"./dist/DoScheduleStore.d.mts","default":"./dist/DoScheduleStore.mjs"},"./do-storage-config":{"types":"./dist/DoStorageConfig.d.mts","default":"./dist/DoStorageConfig.mjs"},"./do-storage-error":{"types":"./dist/DoStorageError.d.mts","default":"./dist/DoStorageError.mjs"},"./do-storage-failpoint":{"types":"./dist/DoStorageFailpoint.d.mts","default":"./dist/DoStorageFailpoint.mjs"},"./do-storage-version":{"types":"./dist/DoStorageVersion.d.mts","default":"./dist/DoStorageVersion.mjs"},"./do-submission-ledger":{"types":"./dist/DoSubmissionLedger.d.mts","default":"./dist/DoSubmissionLedger.mjs"},"./do-subscription-store":{"types":"./dist/DoSubscriptionStore.d.mts","default":"./dist/DoSubscriptionStore.mjs"},"./do-thread-store":{"types":"./dist/DoThreadStore.d.mts","default":"./dist/DoThreadStore.mjs"},"./memory-protocol":{"types":"./dist/MemoryProtocol.d.mts","default":"./dist/MemoryProtocol.mjs"},"./port-protocol":{"types":"./dist/PortProtocol.d.mts","default":"./dist/PortProtocol.mjs"},"./port-routing":{"types":"./dist/PortRouting.d.mts","default":"./dist/PortRouting.mjs"},"./testing/do-storage-failpoint-testing":{"types":"./dist/DoStorageFailpointTesting.d.mts","default":"./dist/DoStorageFailpointTesting.mjs"},"./do-message-delivery-store":{"types":"./dist/DoMessageDeliveryStore.d.mts","default":"./dist/DoMessageDeliveryStore.mjs"}},"description":"Durable Object SQLite storage adapters and the routed port protocol for Effect Agent on Cloudflare.","license":"MIT","repository":{"type":"git","url":"git+https://github.com/yielded-dev/agent.git","directory":"packages/storage-cloudflare"},"files":["dist","src"],"type":"module","sideEffects":[],"publishConfig":{"access":"public"},"scripts":{"build":"vp pack","check":"tsc --noEmit -p tsconfig.json"}}
1
+ {"name":"@yielded/agent-storage-cloudflare","version":"0.1.0-beta.182","dependencies":{"@effect/platform-browser":"4.0.4","@effect/sql-sqlite-do":"4.0.4","@yielded/agent":"0.1.0-beta.182","@yielded/agent-storage-sql":"0.1.0-beta.182"},"devDependencies":{"@cloudflare/vitest-plugin":"1.4.0","@cloudflare/workers-types":"5.20260926.1","@effect/vitest":"4.0.4","@yielded/agent-testing":"0.1.0-beta.182","effect":"4.0.4","typescript":"7.0.2","vite":"npm:@voidzero-dev/vite-plus-core@1.1.0","vite-plus":"1.1.0","vitest":"5.0.3"},"peerDependencies":{"effect":"^4.0.3"},"exports":{".":{"types":"./dist/index.d.mts","default":"./dist/index.mjs"},"./do-memory-store":{"types":"./dist/DoMemoryStore.d.mts","default":"./dist/DoMemoryStore.mjs"},"./do-schedule-store":{"types":"./dist/DoScheduleStore.d.mts","default":"./dist/DoScheduleStore.mjs"},"./do-storage-config":{"types":"./dist/DoStorageConfig.d.mts","default":"./dist/DoStorageConfig.mjs"},"./do-storage-error":{"types":"./dist/DoStorageError.d.mts","default":"./dist/DoStorageError.mjs"},"./do-storage-failpoint":{"types":"./dist/DoStorageFailpoint.d.mts","default":"./dist/DoStorageFailpoint.mjs"},"./do-storage-version":{"types":"./dist/DoStorageVersion.d.mts","default":"./dist/DoStorageVersion.mjs"},"./do-submission-ledger":{"types":"./dist/DoSubmissionLedger.d.mts","default":"./dist/DoSubmissionLedger.mjs"},"./do-subscription-store":{"types":"./dist/DoSubscriptionStore.d.mts","default":"./dist/DoSubscriptionStore.mjs"},"./do-thread-store":{"types":"./dist/DoThreadStore.d.mts","default":"./dist/DoThreadStore.mjs"},"./memory-protocol":{"types":"./dist/MemoryProtocol.d.mts","default":"./dist/MemoryProtocol.mjs"},"./port-protocol":{"types":"./dist/PortProtocol.d.mts","default":"./dist/PortProtocol.mjs"},"./port-routing":{"types":"./dist/PortRouting.d.mts","default":"./dist/PortRouting.mjs"},"./testing/do-storage-failpoint-testing":{"types":"./dist/DoStorageFailpointTesting.d.mts","default":"./dist/DoStorageFailpointTesting.mjs"},"./do-message-delivery-store":{"types":"./dist/DoMessageDeliveryStore.d.mts","default":"./dist/DoMessageDeliveryStore.mjs"}},"description":"Durable Object SQLite storage adapters and the routed port protocol for Effect Agent on Cloudflare.","license":"MIT","repository":{"type":"git","url":"git+https://github.com/yielded-dev/agent.git","directory":"packages/storage-cloudflare"},"files":["dist","src"],"type":"module","sideEffects":[],"publishConfig":{"access":"public"},"scripts":{"build":"vp pack","check":"tsc --noEmit -p tsconfig.json"}}
@@ -5,7 +5,7 @@ import {
5
5
  MessageDeliveryStore,
6
6
  type MessageDeliveryStoreLimits,
7
7
  } from "@yielded/agent/message-delivery";
8
- import { SqlStorageOwner } from "@yielded/agent/sql-memory-store";
8
+ import { SqlStorageOwner } from "@yielded/agent/sql-storage-owner";
9
9
  import { Effect, Layer } from "effect";
10
10
  import * as SqlClient from "effect/sql/SqlClient";
11
11
 
@@ -12,7 +12,7 @@ import {
12
12
  ObservationOffset,
13
13
  } from "@yielded/agent/records";
14
14
  import { StorageOwner } from "@yielded/agent/run-storage";
15
- import { SqlStorageOwner } from "@yielded/agent/sql-memory-store";
15
+ import { SqlStorageOwner } from "@yielded/agent/sql-storage-owner";
16
16
  import { MAX_ARCHIVE_RANGE_PAGE } from "@yielded/agent/thread-archive-range";
17
17
  import { ThreadImport } from "@yielded/agent/thread-import";
18
18
  import {
@@ -616,7 +616,15 @@ export type PortResponseEnvelope = typeof PortResponse.Encoded;
616
616
  // Codecs
617
617
  // ---------------------------------------------------------------------------
618
618
 
619
- export const encodePortRequest = Schema.encodeEffect(PortRequest);
619
+ // Remote codecs derive their memoized encoding AST only when a port is used.
620
+ export const encodePortRequest: ReturnType<typeof Schema.encodeEffect<typeof PortRequest>> = (
621
+ ...args
622
+ ) => Schema.encodeEffect(PortRequest)(...args);
623
+
620
624
  export const decodePortRequest = Schema.decodeUnknownEffect(PortRequest);
621
- export const encodePortResponse = Schema.encodeEffect(PortResponse);
625
+
626
+ export const encodePortResponse: ReturnType<typeof Schema.encodeEffect<typeof PortResponse>> = (
627
+ ...args
628
+ ) => Schema.encodeEffect(PortResponse)(...args);
629
+
622
630
  export const decodePortResponse = Schema.decodeUnknownEffect(PortResponse);
@@ -23,7 +23,7 @@ import {
23
23
  LifecyclePublicationError,
24
24
  } from "@yielded/agent/lifecycle-publication";
25
25
  import { BatchId, CanonicalRecord, CanonicalSequence } from "@yielded/agent/records";
26
- import { SqlStorageOwner } from "@yielded/agent/sql-memory-store";
26
+ import { SqlStorageOwner } from "@yielded/agent/sql-storage-owner";
27
27
  import {
28
28
  type AppendConflict,
29
29
  AppendResult,
@@ -6,7 +6,7 @@ import {
6
6
  import { createSqlThreadWorkTables } from "@yielded/agent-storage-sql/sql-thread-work";
7
7
  import { makeSqliteLayoutInspection } from "@yielded/agent-storage-sql/sqlite-layout-inspection";
8
8
  import { CURRENT_RECORD_FORMAT } from "@yielded/agent/records";
9
- import { SqlStorageOwner } from "@yielded/agent/sql-memory-store";
9
+ import { SqlStorageOwner } from "@yielded/agent/sql-storage-owner";
10
10
  import { Effect, Option, Schema } from "effect";
11
11
  import * as SqlClient from "effect/sql/SqlClient";
12
12
  import type { SqlError } from "effect/sql/SqlError";