effect-durable-agent 0.1.0-alpha.22 → 0.1.0-alpha.23

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (56) hide show
  1. package/dist/domain/command-queues.d.ts +1 -1
  2. package/dist/domain/message-transcript.d.ts +1 -1
  3. package/dist/domain/reduced-state.d.ts +1 -1
  4. package/dist/domain/run-scheduling.d.ts +1 -1
  5. package/dist/index.d.ts +1 -1
  6. package/dist/records-DWKEjuqb.js +675 -0
  7. package/dist/records-DWKEjuqb.js.map +1 -0
  8. package/dist/{reduced-state-PJdig48e.d.ts → reduced-state-B5WxKSM5.d.ts} +4206 -4206
  9. package/dist/{reducer-registry-BAbhZs6d.d.ts → reducer-registry-CPObI3cs.d.ts} +2 -2
  10. package/dist/{run-scheduling-wakeup-QLK87OqG.d.ts → run-scheduling-wakeup-B19JTeyq.d.ts} +2 -2
  11. package/dist/services/compaction.d.ts +1 -1
  12. package/dist/services/model-call.d.ts +1 -1
  13. package/dist/services/prompt-projector.d.ts +1 -1
  14. package/dist/services/reducer-registry.d.ts +1 -1
  15. package/dist/services/reducer-registry.js +1 -1
  16. package/dist/services/run-scheduler.d.ts +1 -1
  17. package/dist/services/run-scheduling-wakeup.d.ts +1 -1
  18. package/dist/services/runtime-layer.d.ts +6 -6
  19. package/dist/services/runtime-layer.js +3 -3
  20. package/dist/services/runtime.d.ts +1 -1
  21. package/dist/services/runtime.js +1 -1
  22. package/dist/services/session-query.d.ts +1 -1
  23. package/dist/services/session-query.js +2 -2
  24. package/dist/services/session-state.d.ts +1 -1
  25. package/dist/services/session-state.js +1 -1
  26. package/dist/services/session-store.d.ts +1 -1
  27. package/dist/services/session-store.js +1 -1
  28. package/dist/services/sink-checkpoint-store.d.ts +1 -1
  29. package/dist/services/sink-registry.d.ts +1 -1
  30. package/dist/services/sink-registry.js +1 -1
  31. package/dist/services/tool-registry.d.ts +1 -1
  32. package/dist/{session-state-StlO5B2N.js → session-state-C6SyphC0.js} +3 -3
  33. package/dist/{session-state-StlO5B2N.js.map → session-state-C6SyphC0.js.map} +1 -1
  34. package/dist/{session-store-ByDjS03N.d.ts → session-store-CWYZ29CV.d.ts} +163 -45
  35. package/dist/{session-store-DcJjs4Fd.js → session-store-DuEhcqIC.js} +3 -2
  36. package/dist/{session-store-DcJjs4Fd.js.map → session-store-DuEhcqIC.js.map} +1 -1
  37. package/dist/{sink-checkpoint-store-BHb8YRTw.d.ts → sink-checkpoint-store-B8Ky5nfW.d.ts} +2 -2
  38. package/dist/{sink-registry-DEneTH8u.js → sink-registry-DtrssBxF.js} +2 -2
  39. package/dist/{sink-registry-DEneTH8u.js.map → sink-registry-DtrssBxF.js.map} +1 -1
  40. package/dist/subscription-DelB8L87.d.ts +958 -0
  41. package/dist/subscription-g5W0Ggqx.js +498 -0
  42. package/dist/subscription-g5W0Ggqx.js.map +1 -0
  43. package/dist/testkit/layers.d.ts +9 -6
  44. package/dist/testkit/layers.js +4 -4
  45. package/dist/testkit/layers.js.map +1 -1
  46. package/dist/{tool-registry-CxZ0iuYb.d.ts → tool-registry-B_WE2ZwK.d.ts} +2 -2
  47. package/dist/transcript.d.ts +44 -4
  48. package/dist/transcript.js +98 -170
  49. package/dist/transcript.js.map +1 -1
  50. package/dist/websocket.d.ts +2209 -2
  51. package/dist/websocket.js +704 -18
  52. package/dist/websocket.js.map +1 -1
  53. package/dist/{window-read-B8aF_hDq.js → window-read-BDayZf7O.js} +74 -683
  54. package/dist/window-read-BDayZf7O.js.map +1 -0
  55. package/package.json +1 -1
  56. package/dist/window-read-B8aF_hDq.js.map +0 -1
@@ -1 +1 @@
1
- {"version":3,"file":"session-store-DcJjs4Fd.js","names":[],"sources":["../src/transcript/in-memory.ts","../src/services/session-store.ts"],"sourcesContent":["import type { CommittedDurableEvent } from \"../services/session-store\";\nimport { SequenceNumber } from \"../types/core\";\nimport { planTranscriptBatch } from \"./interpreter\";\nimport type { TranscriptDefinition } from \"./mapping\";\nimport type { TranscriptAliasNamespace, TranscriptChangePlan, TranscriptLookup } from \"./plan\";\nimport {\n TranscriptOrder,\n isPendingTranscriptUserRecord,\n isTopLevelTranscriptRecord,\n type TranscriptLogIncarnation,\n type TranscriptOrderKey,\n type TranscriptRecord,\n type TranscriptRecordId,\n type TranscriptTopLevelRecord,\n type TranscriptVersion,\n} from \"./records\";\nimport type { TranscriptMaintenanceConfig } from \"./store\";\nimport type { TranscriptVersionMeta } from \"./window\";\nimport type { TranscriptWindowSource } from \"./window-read\";\n\n/**\n * The in-memory store's transcript state: the semantic model of the adapter's tables\n * (`transcript_records`, `transcript_aliases`, `transcript_meta`), kept inside the store's\n * `Ref.modify` critical section so maintenance commits atomically with the appended events.\n */\nexport interface InMemoryTranscriptVersion {\n readonly meta: TranscriptVersionMeta;\n readonly records: ReadonlyMap<TranscriptRecordId, TranscriptRecord>;\n readonly aliases: ReadonlyMap<string, TranscriptRecordId>;\n readonly ordinals: ReadonlyMap<number, number>;\n}\n\nexport interface InMemoryTranscriptState {\n readonly incarnation: TranscriptLogIncarnation;\n readonly config: TranscriptMaintenanceConfig;\n readonly versions: ReadonlyArray<InMemoryTranscriptVersion>;\n}\n\nconst aliasKey = (namespace: TranscriptAliasNamespace, key: string) => `${namespace}\\u0000${key}`;\n\n/** The carried definition for a stored version, if this release still carries it. */\nexport const carriedTranscriptDefinition = (\n config: TranscriptMaintenanceConfig,\n version: TranscriptVersion,\n): TranscriptDefinition | undefined =>\n config.current.version === version\n ? config.current\n : config.previous?.version === version\n ? config.previous\n : undefined;\n\n/** An empty version before any event is projected. */\nexport const emptyTranscriptVersion = (\n version: TranscriptVersion,\n role: TranscriptVersionMeta[\"role\"],\n): InMemoryTranscriptVersion => ({\n meta: { version, role, cursor: SequenceNumber.make(0), status: { _tag: \"Ok\" } },\n records: new Map(),\n aliases: new Map(),\n ordinals: new Map(),\n});\n\nconst lookupOf = (version: InMemoryTranscriptVersion): TranscriptLookup => ({\n cursor: version.meta.cursor,\n record: (id) => version.records.get(id),\n alias: (namespace, key) => version.aliases.get(aliasKey(namespace, key)),\n nextOrdinal: (anchorSeq) => version.ordinals.get(anchorSeq) ?? 0,\n});\n\nconst applyPlan = (\n version: InMemoryTranscriptVersion,\n plan: TranscriptChangePlan,\n): InMemoryTranscriptVersion => {\n const records = new Map(version.records);\n const aliases = new Map(version.aliases);\n const ordinals = new Map(version.ordinals);\n for (const record of plan.records) {\n records.set(record.id, record);\n if (\"position\" in record && record.position !== undefined) {\n const { anchorSeq, ordinal } = record.position;\n ordinals.set(anchorSeq, Math.max(ordinals.get(anchorSeq) ?? 0, ordinal + 1));\n }\n }\n for (const alias of plan.aliases) {\n const key = aliasKey(alias.namespace, alias.key);\n if (!aliases.has(key)) aliases.set(key, alias.recordId);\n }\n return { meta: { ...version.meta, cursor: plan.throughSeq }, records, aliases, ordinals };\n};\n\n/**\n * Project committed events into one version, or freeze it.\n *\n * A projection failure marks only this version failed at its unchanged cursor and leaves its\n * rows exactly as they were, so it remains a consistent last-good cut.\n */\nexport const advanceTranscriptVersion = (\n version: InMemoryTranscriptVersion,\n definition: TranscriptDefinition,\n committed: ReadonlyArray<CommittedDurableEvent>,\n): InMemoryTranscriptVersion => {\n const fresh = committed.filter((entry) => entry.position.seq > version.meta.cursor);\n const first = fresh[0];\n if (first === undefined || version.meta.status._tag === \"Failed\") return version;\n try {\n return applyPlan(version, planTranscriptBatch(lookupOf(version), fresh, definition));\n } catch (error) {\n return {\n ...version,\n meta: {\n ...version.meta,\n status: {\n _tag: \"Failed\",\n failedAtSeq: first.position.seq,\n error: error instanceof Error ? error.message : String(error),\n },\n },\n };\n }\n};\n\n/** Maintain every carried, healthy version for a committed append; others stay frozen. */\nexport const maintainTranscripts = (\n state: InMemoryTranscriptState,\n committed: ReadonlyArray<CommittedDurableEvent>,\n): InMemoryTranscriptState => ({\n ...state,\n versions: state.versions.map((version) => {\n const definition = carriedTranscriptDefinition(state.config, version.meta.version);\n return definition === undefined\n ? version\n : advanceTranscriptVersion(version, definition, committed);\n }),\n});\n\n/**\n * Converge a session to the current definition, as the adapter's builder does in slices.\n *\n * A building version that is not `current` is discarded. If the active version is not `current`,\n * `current` is built from the log (never from old rows) and, once it reaches the head, becomes\n * active and the old version is deleted. A failed build leaves the active version serving; only a\n * new definition repairs it. A brand-new log simply initializes `current`.\n */\nexport const convergeTranscripts = (\n state: InMemoryTranscriptState,\n log: ReadonlyArray<CommittedDurableEvent>,\n): InMemoryTranscriptState => {\n const current = state.config.current;\n const versions = state.versions.filter(\n (version) => version.meta.role === \"active\" || version.meta.version === current.version,\n );\n const active = versions.find((version) => version.meta.role === \"active\");\n if (active?.meta.version === current.version) return { ...state, versions };\n\n const building =\n versions.find((version) => version.meta.role === \"building\") ??\n emptyTranscriptVersion(current.version, \"building\");\n const built = advanceTranscriptVersion(building, current, log);\n if (built.meta.status._tag === \"Failed\") {\n return { ...state, versions: [...versions.filter((version) => version !== building), built] };\n }\n return { ...state, versions: [{ ...built, meta: { ...built.meta, role: \"active\" } }] };\n};\n\n/** Initial transcript state for a store whose log already holds `log`. */\nexport const initialTranscriptState = (\n incarnation: TranscriptLogIncarnation,\n config: TranscriptMaintenanceConfig,\n log: ReadonlyArray<CommittedDurableEvent>,\n): InMemoryTranscriptState => convergeTranscripts({ incarnation, config, versions: [] }, log);\n\nconst topLevelOrder = (record: TranscriptTopLevelRecord): TranscriptOrderKey => ({\n anchorSeq: record.position?.anchorSeq ?? 0,\n ordinal: record.position?.ordinal ?? 0,\n recordId: record.id,\n});\n\n/** Window reads over the active version, or undefined while nothing is servable. */\nexport const inMemoryTranscriptWindowSource = (\n state: InMemoryTranscriptState,\n): TranscriptWindowSource | undefined => {\n const active = state.versions.find((version) => version.meta.role === \"active\");\n if (active === undefined) return undefined;\n const records = Array.from(active.records.values());\n const ordered = records\n .filter(isTopLevelTranscriptRecord)\n .sort((left, right) => TranscriptOrder(topLevelOrder(left), topLevelOrder(right)));\n const compare = (record: TranscriptTopLevelRecord, key: TranscriptOrderKey) =>\n TranscriptOrder(topLevelOrder(record), key);\n return {\n incarnation: state.incarnation,\n meta: active.meta,\n carried: carriedTranscriptDefinition(state.config, active.meta.version) !== undefined,\n topLevelBefore: (key, limit, inclusive) =>\n ordered\n .filter(\n (record) =>\n key === undefined || (inclusive ? compare(record, key) <= 0 : compare(record, key) < 0),\n )\n .reverse()\n .slice(0, limit),\n topLevelAfter: (key, limit, inclusive) =>\n ordered\n .filter(\n (record) =>\n key === undefined || (inclusive ? compare(record, key) >= 0 : compare(record, key) > 0),\n )\n .slice(0, limit),\n record: (id) => active.records.get(id),\n alias: (namespace, key) => active.aliases.get(aliasKey(namespace, key)),\n toolsOf: (assistantId) =>\n records.flatMap((record) =>\n record.kind === \"tool\" && record.assistantId === assistantId ? [record] : [],\n ),\n pendingUsers: () => records.filter(isPendingTranscriptUserRecord),\n };\n};\n","import * as Cause from \"effect/Cause\";\nimport * as Context from \"effect/Context\";\nimport * as Effect from \"effect/Effect\";\nimport * as Layer from \"effect/Layer\";\nimport * as Ref from \"effect/Ref\";\nimport * as Result from \"effect/Result\";\nimport * as Schema from \"effect/Schema\";\nimport * as SchemaGetter from \"effect/SchemaGetter\";\nimport type * as SchemaAST from \"effect/SchemaAST\";\nimport * as Stream from \"effect/Stream\";\n\nimport {\n DecodedDurableEvent,\n decodeDurableEventSync,\n durableEventEnvelope,\n} from \"../types/events/durable\";\n\nimport { type CommandIdempotencyKey } from \"../types/commands\";\nimport { CompactionSummaryArtifact } from \"../domain/context-projection\";\nimport {\n CommandId,\n DurablePosition,\n SequenceNumber,\n SessionId,\n SummaryId,\n durablePosition,\n} from \"../types/core\";\nimport {\n DurableEventEnvelope,\n commandAdmittedEventType,\n contextRebasedEventType,\n summaryCreatedEventType,\n} from \"../types/events\";\nimport { decodeRetainingExcess } from \"../types/events/internal\";\nimport {\n initialTranscriptState,\n inMemoryTranscriptWindowSource,\n maintainTranscripts,\n type InMemoryTranscriptState,\n} from \"../transcript/in-memory\";\nimport { emptyTranscriptMappings, makeTranscriptDefinition } from \"../transcript/mapping\";\nimport { TranscriptLogIncarnation } from \"../transcript/records\";\nimport {\n EDATranscriptStore,\n type EDATranscriptStoreShape,\n type TranscriptMaintenanceConfig,\n} from \"../transcript/store\";\nimport { buildingTranscriptWindow, readTranscriptWindowFrom } from \"../transcript/window-read\";\n\nexport type CommittedDurableEvent<E = DecodedDurableEvent> = {\n readonly position: typeof DurablePosition.Type;\n readonly event: E;\n};\n\n/** A durable event after the store has assigned its replay position. */\nexport const CommittedDurableEvent: Schema.Codec<\n CommittedDurableEvent,\n {\n readonly position: typeof DurablePosition.Encoded;\n readonly event: typeof DurableEventEnvelope.Encoded;\n },\n never,\n never\n> = Schema.Struct({\n position: DurablePosition,\n event: DurableEventEnvelope.pipe(\n Schema.decodeTo(Schema.declare<DecodedDurableEvent>(Schema.is(DecodedDurableEvent)), {\n decode: SchemaGetter.transform(decodeDurableEventSync),\n encode: SchemaGetter.transform(durableEventEnvelope),\n }),\n ),\n});\n/**\n * Store-level failure surfaced by durable append, replay, and hydration APIs.\n *\n * The error intentionally stays storage-semantic rather than SQL-specific so\n * framework services can treat SQL-backed hosts, in-memory tests, and future adapters\n * as the same durability boundary.\n */\nexport class EDASessionStoreError extends Schema.TaggedError<EDASessionStoreError>()(\n \"EDASessionStoreError\",\n {\n message: Schema.String,\n },\n) {}\n\n/** True when a Cause contains an escaped durable-store failure. */\nexport const hasEDASessionStoreError = (cause: Cause.Cause<unknown>): boolean =>\n cause.reasons.some(\n (reason) => Cause.isFailReason(reason) && reason.error instanceof EDASessionStoreError,\n );\n\n/**\n * One logical event to persist in the durable session log.\n *\n * Store adapters may split large logical payload fields into sidecar rows after\n * the event insert assigns `seq`, but callers still provide one fat event.\n */\nexport const DurableAppendEntry = Schema.Struct({\n event: DurableEventEnvelope,\n});\nexport type DurableAppendEntry = typeof DurableAppendEntry.Type;\n\n/**\n * Ordered durable append intent. Adapters assign positions in entry order.\n *\n * This is the single write shape exposed to framework services. It avoids raw\n * SQL and public transaction callbacks while still expressing the full atomic\n * transition EDA needs for events, normalized bodies, and metadata.\n */\nexport const DurableAppendBatch = Schema.Struct({\n entries: Schema.Array(DurableAppendEntry),\n});\nexport type DurableAppendBatch = typeof DurableAppendBatch.Type;\n\n/** Durable reducer checkpoint row used to hydrate framework and app projections cheaply. */\nexport interface EDAReducerCheckpoint {\n readonly name: string;\n readonly schemaVersion: number;\n readonly throughSeq: SequenceNumber;\n readonly payload: unknown;\n readonly updatedAtMs: number;\n}\n\n/** Input for writing one durable reducer checkpoint. */\nexport interface SaveReducerCheckpointInput {\n readonly name: string;\n readonly schemaVersion: number;\n readonly throughSeq: SequenceNumber;\n readonly payload: unknown;\n readonly updatedAtMs: number;\n}\n\n/** Indexed command-admission lookup used for idempotent ingress. */\nexport const FindCommandAdmissionInput = Schema.Struct({\n commandId: Schema.optionalKey(CommandId),\n idempotencyKey: Schema.optionalKey(Schema.String),\n});\n/** Typed command-admission lookup accepted by the semantic store port. */\nexport interface FindCommandAdmissionInput {\n readonly commandId?: CommandId;\n readonly idempotencyKey?: CommandIdempotencyKey;\n}\n\n/** Semantic durable store contract for one EDA session. */\nexport interface EDASessionStoreShape {\n /**\n * Append durable logical events atomically, preserving input order.\n *\n * Implementations must be idempotent by `eventId`: duplicates return the\n * original committed position and do not advance the durable head. Live publish\n * remains outside the store and is owned by `SessionState` after this succeeds.\n */\n readonly append: (\n batch: DurableAppendBatch,\n ) => Effect.Effect<ReadonlyArray<CommittedDurableEvent>, EDASessionStoreError>;\n /** Replay committed durable events with `seq > afterSeq`. */\n readonly eventsAfter: (\n afterSeq: SequenceNumber,\n ) => Stream.Stream<CommittedDurableEvent, EDASessionStoreError>;\n /** Load committed durable events by exact sequence number for checkpoint pointer hydration. */\n readonly loadCommittedEventsBySeq: (\n seqs: ReadonlyArray<SequenceNumber>,\n ) => Effect.Effect<ReadonlyArray<CommittedDurableEvent>, EDASessionStoreError>;\n /** Lookup an admitted command without replaying the full journal. */\n readonly findCommandAdmission: (\n input: FindCommandAdmissionInput,\n ) => Effect.Effect<CommittedDurableEvent | undefined, EDASessionStoreError>;\n /** Load one compacted summary artifact body by id, if it has been saved. */\n readonly loadSummaryArtifact: (\n summaryId: SummaryId,\n ) => Effect.Effect<CompactionSummaryArtifact | undefined, EDASessionStoreError>;\n /** Load one framework or app reducer checkpoint, if it has been saved. */\n readonly loadReducerCheckpoint: (\n name: string,\n ) => Effect.Effect<EDAReducerCheckpoint | undefined, EDASessionStoreError>;\n /** Persist one framework or app reducer checkpoint as a derived cache. */\n readonly saveReducerCheckpoint: (\n checkpoint: SaveReducerCheckpointInput,\n ) => Effect.Effect<void, EDASessionStoreError>;\n /** Persist a reducer checkpoint snapshot atomically across framework and app reducers. */\n readonly saveReducerCheckpoints: (\n checkpoints: ReadonlyArray<SaveReducerCheckpointInput>,\n ) => Effect.Effect<void, EDASessionStoreError>;\n}\n\n/**\n * SQL-agnostic durable storage port for one EDA session.\n *\n * Framework services depend on this semantic port rather than raw SQL. Host\n * adapters own physical tables and synchronous transaction mechanics; callers\n * only express durable append/replay/lookup intent.\n */\nexport class EDASessionStore extends Context.Service<EDASessionStore, EDASessionStoreShape>()(\n \"@effect-durable-agent/EDASessionStore\",\n) {\n /**\n * Deterministic in-memory implementation used by runtime and recovery tests.\n *\n * It also provides `EDATranscriptStore`, maintaining the transcript inside the same append\n * critical section. Without `options.transcript` it maintains the definition with no host\n * mappings.\n */\n static readonly InMemory = (sessionId: SessionId, options?: InMemoryStoreOptions) =>\n inMemoryStoreLayer(sessionId, () => [], options);\n\n /** In-memory store seeded with a durable prefix; its transcript is built from that prefix. */\n static readonly InMemorySeeded = (\n sessionId: SessionId,\n events: ReadonlyArray<DurableEventEnvelope>,\n options?: InMemoryStoreOptions,\n ) => inMemoryStoreLayer(sessionId, () => seedCommittedEvents(sessionId, events), options);\n}\n\n/** Construction options for the in-memory store. */\nexport interface InMemoryStoreOptions {\n /** Transcript definitions to maintain; defaults to the definition with no host mappings. */\n readonly transcript?: TranscriptMaintenanceConfig;\n}\n\nconst inMemoryStoreLayer = (\n sessionId: SessionId,\n seed: () => ReadonlyArray<CommittedDurableEvent>,\n options: InMemoryStoreOptions | undefined,\n) =>\n Layer.effectContext(\n Effect.gen(function* () {\n const committed = seed();\n const config = options?.transcript ?? {\n current: yield* makeTranscriptDefinition(emptyTranscriptMappings).pipe(Effect.orDie),\n };\n const data = yield* Ref.make<InMemoryStoreData>({\n committed,\n summaries: summariesFromCommittedEvents(committed),\n reducerCheckpoints: new Map(),\n transcript: initialTranscriptState(\n TranscriptLogIncarnation.make(`memory:${sessionId}`),\n config,\n committed,\n ),\n });\n return Context.make(EDASessionStore, makeInMemoryStore(sessionId, data)).pipe(\n Context.add(EDATranscriptStore, makeInMemoryTranscriptStore(data)),\n );\n }),\n );\n\ninterface InMemoryStoreData {\n readonly committed: ReadonlyArray<CommittedDurableEvent>;\n readonly summaries: ReadonlyMap<SummaryId, CompactionSummaryArtifact>;\n readonly reducerCheckpoints: ReadonlyMap<string, EDAReducerCheckpoint>;\n readonly transcript: InMemoryTranscriptState;\n}\n\nconst seedCommittedEvents = (\n sessionId: SessionId,\n events: ReadonlyArray<DurableEventEnvelope>,\n): ReadonlyArray<CommittedDurableEvent> => {\n const seen = new Set<string>();\n return events.map((event, index) => {\n if (event.sessionId !== sessionId) {\n throw new Error(\n `EDASessionStore.InMemorySeeded is scoped to session ${sessionId}; received ${event.sessionId}`,\n );\n }\n if (seen.has(event.eventId)) {\n throw new Error(`Duplicate seed eventId ${event.eventId}`);\n }\n seen.add(event.eventId);\n return {\n position: durablePosition(SequenceNumber.make(index + 1)),\n event: decodeDurableEventSync(DurableEventEnvelope.make(event)),\n };\n });\n};\n\nconst summariesFromCommittedEvents = (\n events: ReadonlyArray<CommittedDurableEvent>,\n): ReadonlyMap<SummaryId, CompactionSummaryArtifact> => {\n const summaries = new Map<SummaryId, CompactionSummaryArtifact>();\n for (const { event } of events) {\n if (event.type !== summaryCreatedEventType) {\n continue;\n }\n const payload = event.payload;\n if (payload.summary !== undefined) {\n const summary = Schema.decodeUnknownSync(CompactionSummaryArtifact)(payload.summary);\n summaries.set(summary.summaryId, summary);\n }\n }\n return summaries;\n};\n\n/**\n * Build an in-memory store with one `Ref.modify` append critical section.\n *\n * The fake models the semantic atomicity of the production adapter without\n * exposing SQL, so runtime tests exercise the same store contract.\n */\nconst makeInMemoryStore = (\n sessionId: SessionId,\n data: Ref.Ref<InMemoryStoreData>,\n): EDASessionStoreShape => {\n const ensureSession = (event: DurableEventEnvelope): Effect.Effect<void, EDASessionStoreError> =>\n Effect.gen(function* () {\n if (event.sessionId === sessionId) {\n return;\n }\n return yield* new EDASessionStoreError({\n message: `EDASessionStore.InMemory is scoped to session ${sessionId}; received ${event.sessionId}`,\n });\n });\n\n const append = (batch: DurableAppendBatch) =>\n Effect.gen(function* () {\n for (const entry of batch.entries) {\n yield* ensureSession(entry.event);\n }\n\n return yield* Ref.modify(data, (current) => {\n const nextEntries: Array<CommittedDurableEvent> = [...current.committed];\n const nextSummaries = new Map(current.summaries);\n const committedEvents: Array<CommittedDurableEvent> = [];\n const appended: Array<CommittedDurableEvent> = [];\n\n for (const entry of batch.entries) {\n const { event } = entry;\n const existing = nextEntries.find((entry) => entry.event.eventId === event.eventId);\n if (existing !== undefined) {\n committedEvents.push(existing);\n continue;\n }\n\n const committed: CommittedDurableEvent = {\n position: durablePosition(SequenceNumber.make(nextEntries.length + 1)),\n event: decodeDurableEventSync(DurableEventEnvelope.make(event)),\n };\n nextEntries.push(committed);\n committedEvents.push(committed);\n appended.push(committed);\n\n if (committed.event.type === summaryCreatedEventType) {\n const payload = committed.event.payload;\n if (payload.summary === undefined) {\n throw new Error(\"SummaryCreated requires summary payload\");\n }\n const summary = Schema.decodeUnknownSync(CompactionSummaryArtifact)(payload.summary);\n if (payload.summaryId !== undefined && summary.summaryId !== payload.summaryId) {\n throw new Error(\"SummaryCreated summaryId does not match summary payload\");\n }\n nextSummaries.set(summary.summaryId, summary);\n }\n\n if (committed.event.type === contextRebasedEventType) {\n const payload = committed.event.payload;\n if (payload.summaryId === undefined || !nextSummaries.has(payload.summaryId)) {\n throw new Error(\n `ContextRebased references unknown summaryId ${String(payload.summaryId)}`,\n );\n }\n }\n }\n\n return [\n committedEvents,\n {\n committed: nextEntries,\n summaries: nextSummaries,\n reducerCheckpoints: current.reducerCheckpoints,\n // Projection staging commits with the events; a projection failure freezes only\n // the failed version and never fails the append.\n transcript:\n appended.length === 0\n ? current.transcript\n : maintainTranscripts(current.transcript, appended),\n },\n ];\n });\n });\n\n return {\n append,\n eventsAfter: (afterSeq) =>\n Stream.fromIterableEffect(\n Ref.get(data).pipe(\n Effect.map(({ committed }) => committed.filter((entry) => entry.position.seq > afterSeq)),\n ),\n ),\n loadCommittedEventsBySeq: (seqs) =>\n Ref.get(data).pipe(\n Effect.map(({ committed }) => {\n const requested = new Set(seqs.map((seq) => Number(seq)));\n return committed.filter((entry) => requested.has(Number(entry.position.seq)));\n }),\n ),\n findCommandAdmission: (input) =>\n Ref.get(data).pipe(\n Effect.map(({ committed }) =>\n committed.find((entry) => commandAdmissionMatches(entry, input)),\n ),\n ),\n loadSummaryArtifact: (summaryId) =>\n Ref.get(data).pipe(Effect.map(({ summaries }) => summaries.get(summaryId))),\n loadReducerCheckpoint: (name) =>\n Ref.get(data).pipe(Effect.map(({ reducerCheckpoints }) => reducerCheckpoints.get(name))),\n saveReducerCheckpoint: (checkpoint) =>\n Ref.update(data, (current) => ({\n ...current,\n reducerCheckpoints: new Map(current.reducerCheckpoints).set(checkpoint.name, checkpoint),\n })),\n saveReducerCheckpoints: (checkpoints) =>\n Ref.update(data, (current) => {\n const reducerCheckpoints = new Map(current.reducerCheckpoints);\n for (const checkpoint of checkpoints) {\n reducerCheckpoints.set(checkpoint.name, checkpoint);\n }\n return { ...current, reducerCheckpoints };\n }),\n };\n};\n\n/** Transcript reads over the in-memory store's active version, at one `Ref` snapshot. */\nconst makeInMemoryTranscriptStore = (\n data: Ref.Ref<InMemoryStoreData>,\n): EDATranscriptStoreShape => ({\n readTranscriptWindow: (selector, limits) =>\n Effect.gen(function* () {\n const { transcript } = yield* Ref.get(data);\n const source = inMemoryTranscriptWindowSource(transcript);\n if (source === undefined) {\n return buildingTranscriptWindow(transcript.incarnation, transcript.config.current.version);\n }\n const window = readTranscriptWindowFrom(source, selector, limits);\n return Result.isSuccess(window) ? window.success : yield* window.failure;\n }),\n readTranscriptMeta: Ref.get(data).pipe(\n Effect.map(({ transcript }) => transcript.versions.map((version) => version.meta)),\n ),\n});\n\nconst commandAdmissionMatches = (\n entry: CommittedDurableEvent,\n input: FindCommandAdmissionInput,\n): boolean => {\n if (entry.event.type !== commandAdmittedEventType) {\n return false;\n }\n const admitted = entry.event.payload.command;\n if (admitted === undefined) {\n return false;\n }\n if (input.idempotencyKey !== undefined && admitted.idempotencyKey === input.idempotencyKey) {\n return true;\n }\n return input.commandId !== undefined && admitted.commandId === input.commandId;\n};\n\n/** App schemas are registered once; known namespaces fail at the store boundary when malformed. */\nexport type EDAAppEvents = Schema.Codec<DurableEventEnvelope, unknown, never, never>;\n\nconst eventNamespaces = (ast: SchemaAST.AST): ReadonlyArray<string> => {\n if (ast._tag === \"Union\") return ast.types.flatMap(eventNamespaces);\n if (ast._tag === \"Objects\") {\n const namespace = ast.propertySignatures.find((field) => field.name === \"namespace\")?.type;\n if (namespace?._tag === \"Literal\" && typeof namespace.literal === \"string\")\n return [namespace.literal];\n }\n throw new Error(\"App event schemas must be a union of structs with literal namespaces\");\n};\n\n/** Attach the app decoder to every event-returning store operation without changing storage bytes. */\nexport const registerAppEvents = (\n store: EDASessionStoreShape,\n schema: EDAAppEvents,\n): EDASessionStoreShape => {\n const namespaces = new Set(eventNamespaces(schema.ast));\n const decode = decodeRetainingExcess(schema);\n const envelopeKey = (event: DurableEventEnvelope): string =>\n JSON.stringify(Schema.encodeSync(DurableEventEnvelope)(event));\n const decodeEntry = (\n entry: CommittedDurableEvent,\n prepared?: ReadonlyMap<string, DurableEventEnvelope>,\n ): CommittedDurableEvent => {\n if (entry.event.namespace !== \"__foreign\" || !namespaces.has(entry.event.envelope.namespace))\n return entry;\n return {\n ...entry,\n event: {\n ...entry.event,\n decoded: prepared?.get(envelopeKey(entry.event.envelope)) ?? decode(entry.event.envelope),\n },\n };\n };\n const decodeEntryEffect = (entry: CommittedDurableEvent) =>\n Effect.try({\n try: () => decodeEntry(entry),\n catch: (cause) =>\n new EDASessionStoreError({\n message: `Registered app event decode failed: ${String(cause)}`,\n }),\n });\n const decodeEntries = (entries: ReadonlyArray<CommittedDurableEvent>) =>\n Effect.forEach(entries, decodeEntryEffect);\n return {\n ...store,\n append: (batch) =>\n Effect.gen(function* () {\n // Idempotent append can return different retained bytes for the same event id.\n // Reuse a prepared decode only when the complete persisted envelope matches.\n const prepared = yield* Effect.try({\n try: () => {\n const decoded = new Map<string, DurableEventEnvelope>();\n for (const { event } of batch.entries) {\n if (!namespaces.has(event.namespace)) continue;\n const key = envelopeKey(event);\n if (!decoded.has(key)) {\n decoded.set(key, decode(event));\n }\n }\n return decoded;\n },\n catch: (cause) =>\n new EDASessionStoreError({\n message: `Registered app event decode failed: ${String(cause)}`,\n }),\n });\n const committed = yield* store.append(batch);\n return yield* Effect.forEach(committed, (entry) =>\n Effect.try({\n try: () => decodeEntry(entry, prepared),\n catch: (cause) =>\n new EDASessionStoreError({\n message: `Registered app event decode failed: ${String(cause)}`,\n }),\n }),\n );\n }),\n eventsAfter: (seq) => store.eventsAfter(seq).pipe(Stream.mapEffect(decodeEntryEffect)),\n loadCommittedEventsBySeq: (seqs) =>\n store.loadCommittedEventsBySeq(seqs).pipe(Effect.flatMap(decodeEntries)),\n findCommandAdmission: (input) =>\n store\n .findCommandAdmission(input)\n .pipe(\n Effect.flatMap((entry) =>\n entry === undefined ? Effect.succeed(undefined) : decodeEntryEffect(entry),\n ),\n ),\n };\n};\n\n/** Narrow an already decoded fact from one schema, without decoding its payload again. */\nexport const selectCommittedEvent = <E extends DurableEventEnvelope>(\n schema: Schema.Codec<E, unknown, never, never>,\n entry: CommittedDurableEvent,\n): CommittedDurableEvent<E> | undefined => {\n const event =\n entry.event.namespace === \"__foreign\"\n ? (entry.event.decoded ?? entry.event.envelope)\n : entry.event;\n return Schema.is(schema)(event) ? { position: entry.position, event } : undefined;\n};\n\n/** Typed journal read available to tools and application services without private SQL access. */\nexport const queryCommittedEvents = <E extends DurableEventEnvelope>(\n store: EDASessionStoreShape,\n schema: Schema.Codec<E, unknown, never, never>,\n options: { readonly afterSeq?: SequenceNumber; readonly limit?: number } = {},\n): Effect.Effect<ReadonlyArray<CommittedDurableEvent<E>>, EDASessionStoreError> =>\n store.eventsAfter(options.afterSeq ?? SequenceNumber.make(0)).pipe(\n Stream.map((entry) => selectCommittedEvent(schema, entry)),\n Stream.filter((entry): entry is CommittedDurableEvent<E> => entry !== undefined),\n Stream.take(options.limit ?? Number.MAX_SAFE_INTEGER),\n Stream.runCollect,\n );\n"],"mappings":";;;;;;;;;;;;;;;AAsCA,MAAM,YAAY,WAAqC,QAAgB,GAAG,UAAU,QAAQ;;AAG5F,MAAa,+BACX,QACA,YAEA,OAAO,QAAQ,YAAY,UACvB,OAAO,UACP,OAAO,UAAU,YAAY,UAC3B,OAAO,WACP,KAAA;;AAGR,MAAa,0BACX,SACA,UAC+B;CAC/B,MAAM;EAAE;EAAS;EAAM,QAAQ,eAAe,KAAK,CAAC;EAAG,QAAQ,EAAE,MAAM,KAAK;CAAE;CAC9E,yBAAS,IAAI,IAAI;CACjB,yBAAS,IAAI,IAAI;CACjB,0BAAU,IAAI,IAAI;AACpB;AAEA,MAAM,YAAY,aAA0D;CAC1E,QAAQ,QAAQ,KAAK;CACrB,SAAS,OAAO,QAAQ,QAAQ,IAAI,EAAE;CACtC,QAAQ,WAAW,QAAQ,QAAQ,QAAQ,IAAI,SAAS,WAAW,GAAG,CAAC;CACvE,cAAc,cAAc,QAAQ,SAAS,IAAI,SAAS,KAAK;AACjE;AAEA,MAAM,aACJ,SACA,SAC8B;CAC9B,MAAM,UA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,wBACX,QACA,UACyC;CACzC,MAAM,QACJ,MAAM,MAAM,cAAc,cACrB,MAAM,MAAM,WAAW,MAAM,MAAM,WACpC,MAAM;CACZ,OAAO,OAAO,GAAG,MAAM,CAAC,CAAC,KAAK,IAAI;EAAE,UAAU,MAAM;EAAU;CAAM,IAAI,KAAA;AAC1E;;AAGA,MAAa,wBACX,OACA,QACA,UAA2E,CAAC,MAE5E,MAAM,YAAY,QAAQ,YAAY,eAAe,KAAK,CAAC,CAAC,CAAC,CAAC,KAC5D,OAAO,KAAK,UAAU,qBAAqB,QAAQ,KAAK,CAAC,GACzD,OAAO,QAAQ,UAA6C,UAAU,KAAA,CAAS,GAC/E,OAAO,KAAK,QAAQ,SAAS,OAAO,gBAAgB,GACpD,OAAO,UACT"}
1
+ {"version":3,"file":"session-store-DuEhcqIC.js","names":[],"sources":["../src/transcript/in-memory.ts","../src/services/session-store.ts"],"sourcesContent":["import type { CommittedDurableEvent } from \"../services/session-store\";\nimport { SequenceNumber } from \"../types/core\";\nimport { planTranscriptBatch } from \"./interpreter\";\nimport type { TranscriptDefinition } from \"./mapping\";\nimport type { TranscriptAliasNamespace, TranscriptChangePlan, TranscriptLookup } from \"./plan\";\nimport {\n TranscriptOrder,\n isPendingTranscriptUserRecord,\n isTopLevelTranscriptRecord,\n type TranscriptLogIncarnation,\n type TranscriptOrderKey,\n type TranscriptRecord,\n type TranscriptRecordId,\n type TranscriptTopLevelRecord,\n type TranscriptVersion,\n} from \"./records\";\nimport type { TranscriptMaintenanceConfig } from \"./store\";\nimport type { TranscriptVersionMeta } from \"./window\";\nimport type { TranscriptWindowSource } from \"./window-read\";\n\n/**\n * The in-memory store's transcript state: the semantic model of the adapter's tables\n * (`transcript_records`, `transcript_aliases`, `transcript_meta`), kept inside the store's\n * `Ref.modify` critical section so maintenance commits atomically with the appended events.\n */\nexport interface InMemoryTranscriptVersion {\n readonly meta: TranscriptVersionMeta;\n readonly records: ReadonlyMap<TranscriptRecordId, TranscriptRecord>;\n readonly aliases: ReadonlyMap<string, TranscriptRecordId>;\n readonly ordinals: ReadonlyMap<number, number>;\n}\n\nexport interface InMemoryTranscriptState {\n readonly incarnation: TranscriptLogIncarnation;\n readonly config: TranscriptMaintenanceConfig;\n readonly versions: ReadonlyArray<InMemoryTranscriptVersion>;\n}\n\nconst aliasKey = (namespace: TranscriptAliasNamespace, key: string) => `${namespace}\\u0000${key}`;\n\n/** The carried definition for a stored version, if this release still carries it. */\nexport const carriedTranscriptDefinition = (\n config: TranscriptMaintenanceConfig,\n version: TranscriptVersion,\n): TranscriptDefinition | undefined =>\n config.current.version === version\n ? config.current\n : config.previous?.version === version\n ? config.previous\n : undefined;\n\n/** An empty version before any event is projected. */\nexport const emptyTranscriptVersion = (\n version: TranscriptVersion,\n role: TranscriptVersionMeta[\"role\"],\n): InMemoryTranscriptVersion => ({\n meta: { version, role, cursor: SequenceNumber.make(0), status: { _tag: \"Ok\" } },\n records: new Map(),\n aliases: new Map(),\n ordinals: new Map(),\n});\n\nconst lookupOf = (version: InMemoryTranscriptVersion): TranscriptLookup => ({\n cursor: version.meta.cursor,\n record: (id) => version.records.get(id),\n alias: (namespace, key) => version.aliases.get(aliasKey(namespace, key)),\n nextOrdinal: (anchorSeq) => version.ordinals.get(anchorSeq) ?? 0,\n});\n\nconst applyPlan = (\n version: InMemoryTranscriptVersion,\n plan: TranscriptChangePlan,\n): InMemoryTranscriptVersion => {\n const records = new Map(version.records);\n const aliases = new Map(version.aliases);\n const ordinals = new Map(version.ordinals);\n for (const record of plan.records) {\n records.set(record.id, record);\n if (\"position\" in record && record.position !== undefined) {\n const { anchorSeq, ordinal } = record.position;\n ordinals.set(anchorSeq, Math.max(ordinals.get(anchorSeq) ?? 0, ordinal + 1));\n }\n }\n for (const alias of plan.aliases) {\n const key = aliasKey(alias.namespace, alias.key);\n if (!aliases.has(key)) aliases.set(key, alias.recordId);\n }\n return { meta: { ...version.meta, cursor: plan.throughSeq }, records, aliases, ordinals };\n};\n\n/**\n * Project committed events into one version, or freeze it.\n *\n * A projection failure marks only this version failed at its unchanged cursor and leaves its\n * rows exactly as they were, so it remains a consistent last-good cut.\n */\nexport const advanceTranscriptVersion = (\n version: InMemoryTranscriptVersion,\n definition: TranscriptDefinition,\n committed: ReadonlyArray<CommittedDurableEvent>,\n): InMemoryTranscriptVersion => {\n const fresh = committed.filter((entry) => entry.position.seq > version.meta.cursor);\n const first = fresh[0];\n if (first === undefined || version.meta.status._tag === \"Failed\") return version;\n try {\n return applyPlan(version, planTranscriptBatch(lookupOf(version), fresh, definition));\n } catch (error) {\n return {\n ...version,\n meta: {\n ...version.meta,\n status: {\n _tag: \"Failed\",\n failedAtSeq: first.position.seq,\n error: error instanceof Error ? error.message : String(error),\n },\n },\n };\n }\n};\n\n/** Maintain every carried, healthy version for a committed append; others stay frozen. */\nexport const maintainTranscripts = (\n state: InMemoryTranscriptState,\n committed: ReadonlyArray<CommittedDurableEvent>,\n): InMemoryTranscriptState => ({\n ...state,\n versions: state.versions.map((version) => {\n const definition = carriedTranscriptDefinition(state.config, version.meta.version);\n return definition === undefined\n ? version\n : advanceTranscriptVersion(version, definition, committed);\n }),\n});\n\n/**\n * Converge a session to the current definition, as the adapter's builder does in slices.\n *\n * A building version that is not `current` is discarded. If the active version is not `current`,\n * `current` is built from the log (never from old rows) and, once it reaches the head, becomes\n * active and the old version is deleted. A failed build leaves the active version serving; only a\n * new definition repairs it. A brand-new log simply initializes `current`.\n */\nexport const convergeTranscripts = (\n state: InMemoryTranscriptState,\n log: ReadonlyArray<CommittedDurableEvent>,\n): InMemoryTranscriptState => {\n const current = state.config.current;\n const versions = state.versions.filter(\n (version) => version.meta.role === \"active\" || version.meta.version === current.version,\n );\n const active = versions.find((version) => version.meta.role === \"active\");\n if (active?.meta.version === current.version) return { ...state, versions };\n\n const building =\n versions.find((version) => version.meta.role === \"building\") ??\n emptyTranscriptVersion(current.version, \"building\");\n const built = advanceTranscriptVersion(building, current, log);\n if (built.meta.status._tag === \"Failed\") {\n return { ...state, versions: [...versions.filter((version) => version !== building), built] };\n }\n return { ...state, versions: [{ ...built, meta: { ...built.meta, role: \"active\" } }] };\n};\n\n/** Initial transcript state for a store whose log already holds `log`. */\nexport const initialTranscriptState = (\n incarnation: TranscriptLogIncarnation,\n config: TranscriptMaintenanceConfig,\n log: ReadonlyArray<CommittedDurableEvent>,\n): InMemoryTranscriptState => convergeTranscripts({ incarnation, config, versions: [] }, log);\n\nconst topLevelOrder = (record: TranscriptTopLevelRecord): TranscriptOrderKey => ({\n anchorSeq: record.position?.anchorSeq ?? 0,\n ordinal: record.position?.ordinal ?? 0,\n recordId: record.id,\n});\n\n/** Window reads over the active version, or undefined while nothing is servable. */\nexport const inMemoryTranscriptWindowSource = (\n state: InMemoryTranscriptState,\n): TranscriptWindowSource | undefined => {\n const active = state.versions.find((version) => version.meta.role === \"active\");\n if (active === undefined) return undefined;\n const records = Array.from(active.records.values());\n const ordered = records\n .filter(isTopLevelTranscriptRecord)\n .sort((left, right) => TranscriptOrder(topLevelOrder(left), topLevelOrder(right)));\n const compare = (record: TranscriptTopLevelRecord, key: TranscriptOrderKey) =>\n TranscriptOrder(topLevelOrder(record), key);\n return {\n incarnation: state.incarnation,\n meta: active.meta,\n carried: carriedTranscriptDefinition(state.config, active.meta.version) !== undefined,\n topLevelBefore: (key, limit, inclusive) =>\n ordered\n .filter(\n (record) =>\n key === undefined || (inclusive ? compare(record, key) <= 0 : compare(record, key) < 0),\n )\n .reverse()\n .slice(0, limit),\n topLevelAfter: (key, limit, inclusive) =>\n ordered\n .filter(\n (record) =>\n key === undefined || (inclusive ? compare(record, key) >= 0 : compare(record, key) > 0),\n )\n .slice(0, limit),\n record: (id) => active.records.get(id),\n alias: (namespace, key) => active.aliases.get(aliasKey(namespace, key)),\n toolsOf: (assistantId) =>\n records.flatMap((record) =>\n record.kind === \"tool\" && record.assistantId === assistantId ? [record] : [],\n ),\n pendingUsers: () => records.filter(isPendingTranscriptUserRecord),\n };\n};\n","import * as Cause from \"effect/Cause\";\nimport * as Context from \"effect/Context\";\nimport * as Effect from \"effect/Effect\";\nimport * as Layer from \"effect/Layer\";\nimport * as Ref from \"effect/Ref\";\nimport * as Result from \"effect/Result\";\nimport * as Schema from \"effect/Schema\";\nimport * as SchemaGetter from \"effect/SchemaGetter\";\nimport type * as SchemaAST from \"effect/SchemaAST\";\nimport * as Stream from \"effect/Stream\";\n\nimport {\n DecodedDurableEvent,\n decodeDurableEventSync,\n durableEventEnvelope,\n} from \"../types/events/durable\";\n\nimport { type CommandIdempotencyKey } from \"../types/commands\";\nimport { CompactionSummaryArtifact } from \"../domain/context-projection\";\nimport {\n CommandId,\n DurablePosition,\n SequenceNumber,\n SessionId,\n SummaryId,\n durablePosition,\n} from \"../types/core\";\nimport {\n DurableEventEnvelope,\n commandAdmittedEventType,\n contextRebasedEventType,\n summaryCreatedEventType,\n} from \"../types/events\";\nimport { decodeRetainingExcess } from \"../types/events/internal\";\nimport {\n initialTranscriptState,\n inMemoryTranscriptWindowSource,\n maintainTranscripts,\n type InMemoryTranscriptState,\n} from \"../transcript/in-memory\";\nimport { emptyTranscriptMappings, makeTranscriptDefinition } from \"../transcript/mapping\";\nimport { TranscriptLogIncarnation } from \"../transcript/records\";\nimport {\n EDATranscriptStore,\n type EDATranscriptStoreShape,\n type TranscriptMaintenanceConfig,\n} from \"../transcript/store\";\nimport { buildingTranscriptWindow, readTranscriptWindowFrom } from \"../transcript/window-read\";\n\nexport type CommittedDurableEvent<E = DecodedDurableEvent> = {\n readonly position: typeof DurablePosition.Type;\n readonly event: E;\n};\n\n/** A durable event after the store has assigned its replay position. */\nexport const CommittedDurableEvent: Schema.Codec<\n CommittedDurableEvent,\n {\n readonly position: typeof DurablePosition.Encoded;\n readonly event: typeof DurableEventEnvelope.Encoded;\n },\n never,\n never\n> = Schema.Struct({\n position: DurablePosition,\n event: DurableEventEnvelope.pipe(\n Schema.decodeTo(Schema.declare<DecodedDurableEvent>(Schema.is(DecodedDurableEvent)), {\n decode: SchemaGetter.transform(decodeDurableEventSync),\n encode: SchemaGetter.transform(durableEventEnvelope),\n }),\n ),\n});\n/**\n * Store-level failure surfaced by durable append, replay, and hydration APIs.\n *\n * The error intentionally stays storage-semantic rather than SQL-specific so\n * framework services can treat SQL-backed hosts, in-memory tests, and future adapters\n * as the same durability boundary.\n */\nexport class EDASessionStoreError extends Schema.TaggedError<EDASessionStoreError>()(\n \"EDASessionStoreError\",\n {\n message: Schema.String,\n },\n) {}\n\n/** True when a Cause contains an escaped durable-store failure. */\nexport const hasEDASessionStoreError = (cause: Cause.Cause<unknown>): boolean =>\n cause.reasons.some(\n (reason) => Cause.isFailReason(reason) && reason.error instanceof EDASessionStoreError,\n );\n\n/**\n * One logical event to persist in the durable session log.\n *\n * Store adapters may split large logical payload fields into sidecar rows after\n * the event insert assigns `seq`, but callers still provide one fat event.\n */\nexport const DurableAppendEntry = Schema.Struct({\n event: DurableEventEnvelope,\n});\nexport type DurableAppendEntry = typeof DurableAppendEntry.Type;\n\n/**\n * Ordered durable append intent. Adapters assign positions in entry order.\n *\n * This is the single write shape exposed to framework services. It avoids raw\n * SQL and public transaction callbacks while still expressing the full atomic\n * transition EDA needs for events, normalized bodies, and metadata.\n */\nexport const DurableAppendBatch = Schema.Struct({\n entries: Schema.Array(DurableAppendEntry),\n});\nexport type DurableAppendBatch = typeof DurableAppendBatch.Type;\n\n/** Durable reducer checkpoint row used to hydrate framework and app projections cheaply. */\nexport interface EDAReducerCheckpoint {\n readonly name: string;\n readonly schemaVersion: number;\n readonly throughSeq: SequenceNumber;\n readonly payload: unknown;\n readonly updatedAtMs: number;\n}\n\n/** Input for writing one durable reducer checkpoint. */\nexport interface SaveReducerCheckpointInput {\n readonly name: string;\n readonly schemaVersion: number;\n readonly throughSeq: SequenceNumber;\n readonly payload: unknown;\n readonly updatedAtMs: number;\n}\n\n/** Indexed command-admission lookup used for idempotent ingress. */\nexport const FindCommandAdmissionInput = Schema.Struct({\n commandId: Schema.optionalKey(CommandId),\n idempotencyKey: Schema.optionalKey(Schema.String),\n});\n/** Typed command-admission lookup accepted by the semantic store port. */\nexport interface FindCommandAdmissionInput {\n readonly commandId?: CommandId;\n readonly idempotencyKey?: CommandIdempotencyKey;\n}\n\n/** Semantic durable store contract for one EDA session. */\nexport interface EDASessionStoreShape {\n /**\n * Append durable logical events atomically, preserving input order.\n *\n * Implementations must be idempotent by `eventId`: duplicates return the\n * original committed position and do not advance the durable head. Live publish\n * remains outside the store and is owned by `SessionState` after this succeeds.\n */\n readonly append: (\n batch: DurableAppendBatch,\n ) => Effect.Effect<ReadonlyArray<CommittedDurableEvent>, EDASessionStoreError>;\n /** Replay committed durable events with `seq > afterSeq`. */\n readonly eventsAfter: (\n afterSeq: SequenceNumber,\n ) => Stream.Stream<CommittedDurableEvent, EDASessionStoreError>;\n /** Load committed durable events by exact sequence number for checkpoint pointer hydration. */\n readonly loadCommittedEventsBySeq: (\n seqs: ReadonlyArray<SequenceNumber>,\n ) => Effect.Effect<ReadonlyArray<CommittedDurableEvent>, EDASessionStoreError>;\n /** Lookup an admitted command without replaying the full journal. */\n readonly findCommandAdmission: (\n input: FindCommandAdmissionInput,\n ) => Effect.Effect<CommittedDurableEvent | undefined, EDASessionStoreError>;\n /** Load one compacted summary artifact body by id, if it has been saved. */\n readonly loadSummaryArtifact: (\n summaryId: SummaryId,\n ) => Effect.Effect<CompactionSummaryArtifact | undefined, EDASessionStoreError>;\n /** Load one framework or app reducer checkpoint, if it has been saved. */\n readonly loadReducerCheckpoint: (\n name: string,\n ) => Effect.Effect<EDAReducerCheckpoint | undefined, EDASessionStoreError>;\n /** Persist one framework or app reducer checkpoint as a derived cache. */\n readonly saveReducerCheckpoint: (\n checkpoint: SaveReducerCheckpointInput,\n ) => Effect.Effect<void, EDASessionStoreError>;\n /** Persist a reducer checkpoint snapshot atomically across framework and app reducers. */\n readonly saveReducerCheckpoints: (\n checkpoints: ReadonlyArray<SaveReducerCheckpointInput>,\n ) => Effect.Effect<void, EDASessionStoreError>;\n}\n\n/**\n * SQL-agnostic durable storage port for one EDA session.\n *\n * Framework services depend on this semantic port rather than raw SQL. Host\n * adapters own physical tables and synchronous transaction mechanics; callers\n * only express durable append/replay/lookup intent.\n */\nexport class EDASessionStore extends Context.Service<EDASessionStore, EDASessionStoreShape>()(\n \"@effect-durable-agent/EDASessionStore\",\n) {\n /**\n * Deterministic in-memory implementation used by runtime and recovery tests.\n *\n * It also provides `EDATranscriptStore`, maintaining the transcript inside the same append\n * critical section. Without `options.transcript` it maintains the definition with no host\n * mappings.\n */\n static readonly InMemory = (sessionId: SessionId, options?: InMemoryStoreOptions) =>\n inMemoryStoreLayer(sessionId, () => [], options);\n\n /** In-memory store seeded with a durable prefix; its transcript is built from that prefix. */\n static readonly InMemorySeeded = (\n sessionId: SessionId,\n events: ReadonlyArray<DurableEventEnvelope>,\n options?: InMemoryStoreOptions,\n ) => inMemoryStoreLayer(sessionId, () => seedCommittedEvents(sessionId, events), options);\n}\n\n/** Construction options for the in-memory store. */\nexport interface InMemoryStoreOptions {\n /** Transcript definitions to maintain; defaults to the definition with no host mappings. */\n readonly transcript?: TranscriptMaintenanceConfig;\n}\n\nconst inMemoryStoreLayer = (\n sessionId: SessionId,\n seed: () => ReadonlyArray<CommittedDurableEvent>,\n options: InMemoryStoreOptions | undefined,\n) =>\n Layer.effectContext(\n Effect.gen(function* () {\n const committed = seed();\n const config = options?.transcript ?? {\n current: yield* makeTranscriptDefinition(emptyTranscriptMappings).pipe(Effect.orDie),\n };\n const data = yield* Ref.make<InMemoryStoreData>({\n committed,\n summaries: summariesFromCommittedEvents(committed),\n reducerCheckpoints: new Map(),\n transcript: initialTranscriptState(\n TranscriptLogIncarnation.make(`memory:${sessionId}`),\n config,\n committed,\n ),\n });\n return Context.make(EDASessionStore, makeInMemoryStore(sessionId, data)).pipe(\n Context.add(EDATranscriptStore, makeInMemoryTranscriptStore(data)),\n );\n }),\n );\n\ninterface InMemoryStoreData {\n readonly committed: ReadonlyArray<CommittedDurableEvent>;\n readonly summaries: ReadonlyMap<SummaryId, CompactionSummaryArtifact>;\n readonly reducerCheckpoints: ReadonlyMap<string, EDAReducerCheckpoint>;\n readonly transcript: InMemoryTranscriptState;\n}\n\nconst seedCommittedEvents = (\n sessionId: SessionId,\n events: ReadonlyArray<DurableEventEnvelope>,\n): ReadonlyArray<CommittedDurableEvent> => {\n const seen = new Set<string>();\n return events.map((event, index) => {\n if (event.sessionId !== sessionId) {\n throw new Error(\n `EDASessionStore.InMemorySeeded is scoped to session ${sessionId}; received ${event.sessionId}`,\n );\n }\n if (seen.has(event.eventId)) {\n throw new Error(`Duplicate seed eventId ${event.eventId}`);\n }\n seen.add(event.eventId);\n return {\n position: durablePosition(SequenceNumber.make(index + 1)),\n event: decodeDurableEventSync(DurableEventEnvelope.make(event)),\n };\n });\n};\n\nconst summariesFromCommittedEvents = (\n events: ReadonlyArray<CommittedDurableEvent>,\n): ReadonlyMap<SummaryId, CompactionSummaryArtifact> => {\n const summaries = new Map<SummaryId, CompactionSummaryArtifact>();\n for (const { event } of events) {\n if (event.type !== summaryCreatedEventType) {\n continue;\n }\n const payload = event.payload;\n if (payload.summary !== undefined) {\n const summary = Schema.decodeUnknownSync(CompactionSummaryArtifact)(payload.summary);\n summaries.set(summary.summaryId, summary);\n }\n }\n return summaries;\n};\n\n/**\n * Build an in-memory store with one `Ref.modify` append critical section.\n *\n * The fake models the semantic atomicity of the production adapter without\n * exposing SQL, so runtime tests exercise the same store contract.\n */\nconst makeInMemoryStore = (\n sessionId: SessionId,\n data: Ref.Ref<InMemoryStoreData>,\n): EDASessionStoreShape => {\n const ensureSession = (event: DurableEventEnvelope): Effect.Effect<void, EDASessionStoreError> =>\n Effect.gen(function* () {\n if (event.sessionId === sessionId) {\n return;\n }\n return yield* new EDASessionStoreError({\n message: `EDASessionStore.InMemory is scoped to session ${sessionId}; received ${event.sessionId}`,\n });\n });\n\n const append = (batch: DurableAppendBatch) =>\n Effect.gen(function* () {\n for (const entry of batch.entries) {\n yield* ensureSession(entry.event);\n }\n\n return yield* Ref.modify(data, (current) => {\n const nextEntries: Array<CommittedDurableEvent> = [...current.committed];\n const nextSummaries = new Map(current.summaries);\n const committedEvents: Array<CommittedDurableEvent> = [];\n const appended: Array<CommittedDurableEvent> = [];\n\n for (const entry of batch.entries) {\n const { event } = entry;\n const existing = nextEntries.find((entry) => entry.event.eventId === event.eventId);\n if (existing !== undefined) {\n committedEvents.push(existing);\n continue;\n }\n\n const committed: CommittedDurableEvent = {\n position: durablePosition(SequenceNumber.make(nextEntries.length + 1)),\n event: decodeDurableEventSync(DurableEventEnvelope.make(event)),\n };\n nextEntries.push(committed);\n committedEvents.push(committed);\n appended.push(committed);\n\n if (committed.event.type === summaryCreatedEventType) {\n const payload = committed.event.payload;\n if (payload.summary === undefined) {\n throw new Error(\"SummaryCreated requires summary payload\");\n }\n const summary = Schema.decodeUnknownSync(CompactionSummaryArtifact)(payload.summary);\n if (payload.summaryId !== undefined && summary.summaryId !== payload.summaryId) {\n throw new Error(\"SummaryCreated summaryId does not match summary payload\");\n }\n nextSummaries.set(summary.summaryId, summary);\n }\n\n if (committed.event.type === contextRebasedEventType) {\n const payload = committed.event.payload;\n if (payload.summaryId === undefined || !nextSummaries.has(payload.summaryId)) {\n throw new Error(\n `ContextRebased references unknown summaryId ${String(payload.summaryId)}`,\n );\n }\n }\n }\n\n return [\n committedEvents,\n {\n committed: nextEntries,\n summaries: nextSummaries,\n reducerCheckpoints: current.reducerCheckpoints,\n // Projection staging commits with the events; a projection failure freezes only\n // the failed version and never fails the append.\n transcript:\n appended.length === 0\n ? current.transcript\n : maintainTranscripts(current.transcript, appended),\n },\n ];\n });\n });\n\n return {\n append,\n eventsAfter: (afterSeq) =>\n Stream.fromIterableEffect(\n Ref.get(data).pipe(\n Effect.map(({ committed }) => committed.filter((entry) => entry.position.seq > afterSeq)),\n ),\n ),\n loadCommittedEventsBySeq: (seqs) =>\n Ref.get(data).pipe(\n Effect.map(({ committed }) => {\n const requested = new Set(seqs.map((seq) => Number(seq)));\n return committed.filter((entry) => requested.has(Number(entry.position.seq)));\n }),\n ),\n findCommandAdmission: (input) =>\n Ref.get(data).pipe(\n Effect.map(({ committed }) =>\n committed.find((entry) => commandAdmissionMatches(entry, input)),\n ),\n ),\n loadSummaryArtifact: (summaryId) =>\n Ref.get(data).pipe(Effect.map(({ summaries }) => summaries.get(summaryId))),\n loadReducerCheckpoint: (name) =>\n Ref.get(data).pipe(Effect.map(({ reducerCheckpoints }) => reducerCheckpoints.get(name))),\n saveReducerCheckpoint: (checkpoint) =>\n Ref.update(data, (current) => ({\n ...current,\n reducerCheckpoints: new Map(current.reducerCheckpoints).set(checkpoint.name, checkpoint),\n })),\n saveReducerCheckpoints: (checkpoints) =>\n Ref.update(data, (current) => {\n const reducerCheckpoints = new Map(current.reducerCheckpoints);\n for (const checkpoint of checkpoints) {\n reducerCheckpoints.set(checkpoint.name, checkpoint);\n }\n return { ...current, reducerCheckpoints };\n }),\n };\n};\n\n/** Transcript reads over the in-memory store's active version, at one `Ref` snapshot. */\nconst makeInMemoryTranscriptStore = (\n data: Ref.Ref<InMemoryStoreData>,\n): EDATranscriptStoreShape => ({\n readTranscriptWindow: (selector, limits) =>\n Effect.gen(function* () {\n const { transcript } = yield* Ref.get(data);\n const source = inMemoryTranscriptWindowSource(transcript);\n if (source === undefined) {\n return buildingTranscriptWindow(transcript.incarnation, transcript.config.current.version);\n }\n const window = readTranscriptWindowFrom(source, selector, limits);\n return Result.isSuccess(window) ? window.success : yield* window.failure;\n }),\n readTranscriptMeta: Ref.get(data).pipe(\n Effect.map(({ transcript }) => transcript.versions.map((version) => version.meta)),\n ),\n});\n\nconst commandAdmissionMatches = (\n entry: CommittedDurableEvent,\n input: FindCommandAdmissionInput,\n): boolean => {\n if (entry.event.type !== commandAdmittedEventType) {\n return false;\n }\n const admitted = entry.event.payload.command;\n if (admitted === undefined) {\n return false;\n }\n if (input.idempotencyKey !== undefined && admitted.idempotencyKey === input.idempotencyKey) {\n return true;\n }\n return input.commandId !== undefined && admitted.commandId === input.commandId;\n};\n\n/** App schemas are registered once; known namespaces fail at the store boundary when malformed. */\nexport type EDAAppEvents = Schema.Codec<DurableEventEnvelope, unknown, never, never>;\n\nconst eventNamespaces = (ast: SchemaAST.AST): ReadonlyArray<string> => {\n if (ast._tag === \"Union\") return ast.types.flatMap(eventNamespaces);\n if (ast._tag === \"Objects\") {\n const namespace = ast.propertySignatures.find((field) => field.name === \"namespace\")?.type;\n if (namespace?._tag === \"Literal\" && typeof namespace.literal === \"string\")\n return [namespace.literal];\n }\n throw new Error(\"App event schemas must be a union of structs with literal namespaces\");\n};\n\n/** Attach the app decoder to every event-returning store operation without changing storage bytes. */\nexport const registerAppEvents = (\n store: EDASessionStoreShape,\n schema: EDAAppEvents,\n): EDASessionStoreShape => {\n const namespaces = new Set(eventNamespaces(schema.ast));\n const decode = decodeRetainingExcess(schema);\n const envelopeKey = (event: DurableEventEnvelope): string =>\n JSON.stringify(Schema.encodeSync(DurableEventEnvelope)(event));\n const decodeEntry = (\n entry: CommittedDurableEvent,\n prepared?: ReadonlyMap<string, DurableEventEnvelope>,\n ): CommittedDurableEvent => {\n if (entry.event.namespace !== \"__foreign\" || !namespaces.has(entry.event.envelope.namespace))\n return entry;\n return {\n ...entry,\n event: {\n ...entry.event,\n decoded: prepared?.get(envelopeKey(entry.event.envelope)) ?? decode(entry.event.envelope),\n },\n };\n };\n const decodeEntryEffect = (entry: CommittedDurableEvent) =>\n Effect.try({\n try: () => decodeEntry(entry),\n catch: (cause) =>\n new EDASessionStoreError({\n message: `Registered app event decode failed: ${String(cause)}`,\n }),\n });\n const decodeEntries = (entries: ReadonlyArray<CommittedDurableEvent>) =>\n Effect.forEach(entries, decodeEntryEffect);\n return {\n ...store,\n append: (batch) =>\n Effect.gen(function* () {\n // Idempotent append can return different retained bytes for the same event id.\n // Reuse a prepared decode only when the complete persisted envelope matches.\n const prepared = yield* Effect.try({\n try: () => {\n const decoded = new Map<string, DurableEventEnvelope>();\n for (const { event } of batch.entries) {\n if (!namespaces.has(event.namespace)) continue;\n const key = envelopeKey(event);\n if (!decoded.has(key)) {\n decoded.set(key, decode(event));\n }\n }\n return decoded;\n },\n catch: (cause) =>\n new EDASessionStoreError({\n message: `Registered app event decode failed: ${String(cause)}`,\n }),\n });\n const committed = yield* store.append(batch);\n return yield* Effect.forEach(committed, (entry) =>\n Effect.try({\n try: () => decodeEntry(entry, prepared),\n catch: (cause) =>\n new EDASessionStoreError({\n message: `Registered app event decode failed: ${String(cause)}`,\n }),\n }),\n );\n }),\n eventsAfter: (seq) => store.eventsAfter(seq).pipe(Stream.mapEffect(decodeEntryEffect)),\n loadCommittedEventsBySeq: (seqs) =>\n store.loadCommittedEventsBySeq(seqs).pipe(Effect.flatMap(decodeEntries)),\n findCommandAdmission: (input) =>\n store\n .findCommandAdmission(input)\n .pipe(\n Effect.flatMap((entry) =>\n entry === undefined ? Effect.succeed(undefined) : decodeEntryEffect(entry),\n ),\n ),\n };\n};\n\n/** Narrow an already decoded fact from one schema, without decoding its payload again. */\nexport const selectCommittedEvent = <E extends DurableEventEnvelope>(\n schema: Schema.Codec<E, unknown, never, never>,\n entry: CommittedDurableEvent,\n): CommittedDurableEvent<E> | undefined => {\n const event =\n entry.event.namespace === \"__foreign\"\n ? (entry.event.decoded ?? entry.event.envelope)\n : entry.event;\n return Schema.is(schema)(event) ? { position: entry.position, event } : undefined;\n};\n\n/** Typed journal read available to tools and application services without private SQL access. */\nexport const queryCommittedEvents = <E extends DurableEventEnvelope>(\n store: EDASessionStoreShape,\n schema: Schema.Codec<E, unknown, never, never>,\n options: { readonly afterSeq?: SequenceNumber; readonly limit?: number } = {},\n): Effect.Effect<ReadonlyArray<CommittedDurableEvent<E>>, EDASessionStoreError> =>\n store.eventsAfter(options.afterSeq ?? SequenceNumber.make(0)).pipe(\n Stream.map((entry) => selectCommittedEvent(schema, entry)),\n Stream.filter((entry): entry is CommittedDurableEvent<E> => entry !== undefined),\n Stream.take(options.limit ?? Number.MAX_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Iv.js";
2
- import { s as EDASessionStoreError } from "./session-store-ByDjS03N.js";
2
+ import { s as EDASessionStoreError } from "./session-store-CWYZ29CV.js";
3
3
  import * as Context from "effect/Context";
4
4
  import * as Effect from "effect/Effect";
5
5
  import * as Layer from "effect/Layer";
@@ -36,4 +36,4 @@ declare class SinkCheckpointStore extends SinkCheckpointStore_base {
36
36
  }
37
37
  //#endregion
38
38
  export { StoredSinkCheckpoint as i, SinkCheckpointStore as n, SinkCheckpointStoreShape as r, EDASinkName as t };
39
- //# sourceMappingURL=sink-checkpoint-store-BHb8YRTw.d.ts.map
39
+ //# sourceMappingURL=sink-checkpoint-store-B8Ky5nfW.d.ts.map
@@ -1,6 +1,6 @@
1
1
  import { SequenceNumber } from "./types/core.js";
2
2
  import { foldReducedState, initialReducedState } from "./domain/reduced-state.js";
3
- import { a as EDASessionStoreError, i as EDASessionStore, u as selectCommittedEvent } from "./session-store-DcJjs4Fd.js";
3
+ import { a as EDASessionStoreError, i as EDASessionStore, u as selectCommittedEvent } from "./session-store-DuEhcqIC.js";
4
4
  import { n as SessionContext, t as EventFactory } from "./event-factory-VAci3NJb.js";
5
5
  import { IdGenerator } from "./services/id-generator.js";
6
6
  import { annotateEdaSpan } from "./services/tracing.js";
@@ -342,4 +342,4 @@ const matchesInterest = (event, interests) => interests === void 0 || interests
342
342
  //#endregion
343
343
  export { EDASinkRegistry as n, EDASink as t };
344
344
 
345
- //# sourceMappingURL=sink-registry-DEneTH8u.js.map
345
+ //# sourceMappingURL=sink-registry-DtrssBxF.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"sink-registry-DEneTH8u.js","names":[],"sources":["../src/services/sink-inbox.ts","../src/services/sink-registry.ts"],"sourcesContent":["import * as Effect from \"effect/Effect\";\nimport * as Queue from \"effect/Queue\";\nimport * as Schema from \"effect/Schema\";\n\nimport { SequenceNumber } from \"../types/core\";\nimport type { PositionedEvent } from \"../types/events\";\n\n/** Durable payloads stay in the log; only bounded best-effort ephemeral work is retained. */\nconst ephemeralCapacity = 128;\nconst ephemeralByteCapacity = 256 * 1024;\n\n/** An ephemeral update could not be measured as a JSON wire value. */\nexport class SinkEphemeralEncodingError extends Schema.TaggedError<SinkEphemeralEncodingError>()(\n \"SinkEphemeralEncodingError\",\n { cause: Schema.Defect() },\n) {}\n\n/** One ordered step on a sink's serialized delivery lane. */\ntype SinkWork =\n | { readonly _tag: \"Durable\"; readonly throughSeq: SequenceNumber }\n | { readonly _tag: \"Ephemeral\"; readonly event: PositionedEvent };\n\n/**\n * Coalesces durable heads without losing ephemeral ordering barriers. Publication never\n * waits for delivery. Overflow drops the newest ephemeral update, never durable work.\n */\nexport const makeSinkInbox = Effect.fnUntraced(function* (initialHead: SequenceNumber) {\n const wake = yield* Effect.acquireRelease(Queue.sliding<void>(1), Queue.shutdown);\n let head = initialHead;\n const pending: Array<{ readonly event: PositionedEvent; readonly bytes: number }> = [];\n let pendingBytes = 0;\n\n const notify = (throughSeq: SequenceNumber) =>\n Effect.sync(() => {\n head = SequenceNumber.make(Math.max(head, throughSeq));\n Queue.offerUnsafe(wake, undefined);\n });\n\n const offerEphemeral = (event: PositionedEvent) =>\n Effect.try({\n try: () => {\n const bytes = new TextEncoder().encode(JSON.stringify(event)).byteLength;\n if (pending.length >= ephemeralCapacity || bytes > ephemeralByteCapacity - pendingBytes) {\n return false;\n }\n pending.push({ event, bytes });\n pendingBytes += bytes;\n Queue.offerUnsafe(wake, undefined);\n return true;\n },\n catch: (cause) => new SinkEphemeralEncodingError({ cause }),\n });\n\n const poll = (cursor: SequenceNumber): Effect.Effect<SinkWork | undefined> =>\n Effect.sync(() => {\n while (pending.length > 0) {\n const first = pending[0];\n if (first === undefined) break;\n if (first.event.position.seq > cursor) {\n return { _tag: \"Durable\", throughSeq: first.event.position.seq };\n }\n pending.shift();\n pendingBytes -= first.bytes;\n if (first.event.position.seq === cursor) {\n return { _tag: \"Ephemeral\", event: first.event };\n }\n }\n return cursor < head ? { _tag: \"Durable\", throughSeq: head } : undefined;\n });\n\n return { notify, offerEphemeral, poll, awaitWork: Queue.take(wake) };\n});\n","import * as Cause from \"effect/Cause\";\nimport * as Context from \"effect/Context\";\nimport * as Effect from \"effect/Effect\";\nimport * as Layer from \"effect/Layer\";\nimport * as Ref from \"effect/Ref\";\nimport * as Schema from \"effect/Schema\";\nimport { type DecodedDurableEvent } from \"../types/events/durable\";\nimport { selectCommittedEvent } from \"./session-store\";\nimport * as Scope from \"effect/Scope\";\nimport * as Semaphore from \"effect/Semaphore\";\nimport * as Stream from \"effect/Stream\";\nimport * as SynchronizedRef from \"effect/SynchronizedRef\";\n\nimport { foldReducedState, initialReducedState, type ReducedState } from \"../domain/reduced-state\";\nimport { EDAReducerRegistry, type EDAReducerStateSnapshot } from \"./reducer-registry\";\nimport { EventId, SessionId, SequenceNumber } from \"../types/core\";\nimport type {\n DurableEventEnvelope,\n EphemeralEventEnvelope,\n PositionedEvent,\n} from \"../types/events\";\nimport type { EDASessionStoreShape } from \"./session-store\";\nimport { type CommittedDurableEvent, EDASessionStore, EDASessionStoreError } from \"./session-store\";\nimport { EventFactory } from \"./event-factory\";\nimport type { EventFactoryShape } from \"./event-factory\";\nimport { IdGenerator } from \"./id-generator\";\nimport { EDAKeepAlive } from \"./keep-alive\";\nimport { makeSinkInbox } from \"./sink-inbox\";\nimport { SessionContext } from \"./session-context\";\nimport {\n EDASinkName,\n SinkCheckpointStore,\n type SinkCheckpointStoreShape,\n type StoredSinkCheckpoint,\n} from \"./sink-checkpoint-store\";\nimport { annotateEdaSpan } from \"./tracing\";\n\n/** Cursor-window input delivered to one durable sink drain. */\nexport interface EDASinkRawDurableBatch<E = DecodedDurableEvent> {\n /** All durable events replayed for this cursor window, including uninterested events. */\n readonly allEvents: ReadonlyArray<CommittedDurableEvent>;\n /** Events matching the sink's durable interests. */\n readonly events: ReadonlyArray<CommittedDurableEvent<E>>;\n /** Durable sequence through which the sink may advance after success. */\n readonly throughSeq: SequenceNumber;\n}\n\n/** Cursor window with framework and app projections, enabled by default. */\nexport interface EDASinkDurableBatch<E = DecodedDurableEvent> extends EDASinkRawDurableBatch<E> {\n /** Authoritative reduced state folded exactly through `throughSeq`. */\n readonly stateAfter: ReducedState;\n /** App-specific durable reducer states folded exactly through `throughSeq`. */\n readonly reducerStates: EDAReducerStateSnapshot;\n}\n\n/** Typed, sink-owned durable state stored independently from cursor advancement. */\nexport interface EDASinkCheckpoint {\n /** Decode current durable state, or return `initial` for a new or legacy cursor row. */\n readonly get: <State>(\n schema: Schema.Codec<State, unknown, never, never>,\n initial: State,\n ) => Effect.Effect<State, EDASessionStoreError>;\n /** Validate, encode, and durably save state without advancing the sink cursor. */\n readonly save: <State>(\n schema: Schema.Codec<State, unknown, never, never>,\n state: State,\n ) => Effect.Effect<void, EDASessionStoreError>;\n}\n\n/** Capabilities exposed to sink processors without granting raw store or bus access. */\nexport interface EDASinkContext {\n readonly sessionId: SessionId;\n /** Sink-owned checkpoint state, serialized with cursor commits and background writes. */\n readonly checkpoint: EDASinkCheckpoint;\n /** Build a framework durable event if the sink needs to emit one. */\n readonly events: EventFactoryShape;\n /** Mint an app durable event id for staged custom events. */\n readonly makeEventId: () => Effect.Effect<EventId>;\n /** Publish a best-effort live-only event. */\n readonly emitEphemeral: (\n event: EphemeralEventEnvelope,\n ) => Effect.Effect<PositionedEvent, EDASessionStoreError>;\n /** Stage durable events; the runner commits them after the sink succeeds. */\n readonly stageDurable: (event: DurableEventEnvelope) => Effect.Effect<void>;\n /** Fork background sink work into the session scope. */\n readonly forkScoped: (effect: Effect.Effect<unknown, unknown>) => Effect.Effect<void>;\n}\n\n/** `\"*\"` and omission select every fact; a schema selects and narrows matching envelopes. */\nexport type EDASinkInterests = \"*\" | Schema.Codec<DurableEventEnvelope, unknown, never, never>;\n\n/** Delivery policy shared by raw and projected durable consumers. */\ninterface EDADurableSinkOptions {\n readonly interests?: EDASinkInterests;\n readonly batchSize?: number;\n}\n\n/** Default durable consumer with framework and app projections at each cursor window. */\nexport interface EDAProjectedDurableSinkDefinition extends EDADurableSinkOptions {\n readonly process: (batch: EDASinkDurableBatch, ctx: EDASinkContext) => Effect.Effect<void, never>;\n}\n\n/** Raw consumer that never hydrates, folds, or retains a session projection. */\nexport interface EDARawDurableSinkDefinition extends EDADurableSinkOptions {\n readonly process: (\n batch: EDASinkRawDurableBatch,\n ctx: EDASinkContext,\n ) => Effect.Effect<void, never>;\n}\n\n/** Durable sink definition backed by a checkpoint and an app-owned delivery policy. */\nexport type EDADurableSinkDefinition = EDAProjectedDurableSinkDefinition;\n\n/** Best-effort live-only sink definition. */\nexport interface EDAEphemeralSinkDefinition {\n readonly interests?:\n | \"*\"\n | Schema.Codec<import(\"../types/events\").EventEnvelope, unknown, never, never>;\n readonly process: (event: PositionedEvent, ctx: EDASinkContext) => Effect.Effect<void, never>;\n}\n\n/**\n * Named app integration hook with optional durable and ephemeral filters.\n *\n * Every sink runs on one serialized position-ordered lane. Sinks own retry and\n * terminal failure handling, so callbacks must have an infallible typed error\n * channel. An unexpected defect is logged and skipped before the durable checkpoint\n * advances. Ephemeral callbacks are best-effort and are only processed after the\n * durable prefix at their anchor sequence has been projected.\n */\ninterface EDASinkOptions {\n readonly name: string;\n readonly ephemeral?: EDAEphemeralSinkDefinition;\n}\n\n/** Existing consumers receive framework and app projections unless explicitly opted out. */\nexport interface EDAProjectedSink extends EDASinkOptions {\n readonly state?: \"projected\";\n readonly durable?: EDAProjectedDurableSinkDefinition;\n}\n\n/** Raw consumers retain only their cursor and sink-owned checkpoint payload. */\nexport interface EDARawSink extends EDASinkOptions {\n readonly state: \"none\";\n readonly durable?: EDARawDurableSinkDefinition;\n}\n\n/** The outer discriminant preserves contextual callback typing for inline default sinks. */\nexport type EDASink = EDAProjectedSink | EDARawSink;\n\n/** Projected and raw overloads preserve contextual callback inference and literal names. */\nfunction makeSink<const Sink extends EDAProjectedSink>(sink: Sink): Sink;\nfunction makeSink<const Sink extends EDARawSink>(sink: Sink): Sink;\nfunction makeSink<const Sink extends EDASink>(sink: Sink): Sink;\nfunction makeSink(sink: EDASink): EDASink {\n return sink;\n}\n\n/** Convenience constructor preserving a sink's literal name/type information. */\nexport const EDASink = {\n make: makeSink,\n /** The live-event schema owns both subscription filtering and callback typing. */\n forEphemeralEvents: <E extends import(\"../types/events\").EventEnvelope>(\n interests: Schema.Codec<E, unknown, never, never>,\n process: (event: PositionedEvent<E>, ctx: EDASinkContext) => Effect.Effect<void, never>,\n ): EDAEphemeralSinkDefinition => ({\n interests,\n process: (entry, ctx) =>\n Schema.is(interests)(entry.event)\n ? process({ position: entry.position, event: entry.event }, ctx)\n : Effect.void,\n }),\n /** One schema selects and narrows the facts delivered to a projected durable consumer. */\n forEvents: <E extends DurableEventEnvelope>(\n interests: Schema.Codec<E, unknown, never, never>,\n sink: Omit<EDAProjectedSink, \"durable\"> & {\n readonly durable: {\n readonly batchSize?: number;\n readonly process: (\n batch: EDASinkDurableBatch<E>,\n ctx: EDASinkContext,\n ) => Effect.Effect<void, never>;\n };\n },\n ): EDAProjectedSink => ({\n ...sink,\n durable: {\n ...sink.durable,\n interests,\n process: (batch, ctx) =>\n sink.durable.process(\n {\n ...batch,\n events: batch.events.flatMap((entry) => {\n const selected = selectCommittedEvent(interests, entry);\n return selected === undefined ? [] : [selected];\n }),\n },\n ctx,\n ),\n },\n }),\n};\n\n/** Session-owned capabilities needed to start all registered sink runners. */\nexport interface EDASinkRunnerStartInput {\n readonly appendDurableBatch: (\n events: ReadonlyArray<DurableEventEnvelope>,\n ) => Effect.Effect<ReadonlyArray<CommittedDurableEvent>, EDASessionStoreError>;\n /** Immutable framework and app projections at one common durable head. */\n readonly initialProjection: {\n readonly reduced: ReducedState;\n readonly reducerStates: EDAReducerStateSnapshot;\n };\n readonly publishEphemeral: (\n event: EphemeralEventEnvelope,\n ) => Effect.Effect<PositionedEvent, EDASessionStoreError>;\n readonly scope: Scope.Scope;\n}\n\n/** Registry service coordinating durable checkpoints and live sink delivery. */\nexport interface EDASinkRegistryShape {\n readonly sinks: ReadonlyArray<EDASink>;\n /** Start long-lived sink runners. Safe to call once during session-state acquisition. */\n readonly startSinkRunners: (\n input: EDASinkRunnerStartInput,\n ) => Effect.Effect<void, EDASessionStoreError>;\n /** Coalesced non-blocking nudge that the durable log head advanced. */\n readonly notifyDurableHeadAdvanced: (head: SequenceNumber) => Effect.Effect<void>;\n /** Best-effort non-blocking delivery to ephemeral sink workers. */\n readonly publishEphemeralToSinks: (event: PositionedEvent) => Effect.Effect<void>;\n}\n\n/** Registry and runner for app-provided EDA sinks. */\nexport class EDASinkRegistry extends Context.Service<EDASinkRegistry, EDASinkRegistryShape>()(\n \"@effect-durable-agent/EDASinkRegistry\",\n) {\n static readonly Empty = Layer.succeed(EDASinkRegistry, {\n sinks: [],\n startSinkRunners: () => Effect.void,\n notifyDurableHeadAdvanced: () => Effect.void,\n publishEphemeralToSinks: () => Effect.void,\n } satisfies EDASinkRegistryShape);\n\n static readonly Live = (sinks: ReadonlyArray<EDASink>) =>\n Layer.effect(EDASinkRegistry, makeSinkRegistry(sinks));\n}\n\nconst defaultBatchSize = 100;\nconst sinkCheckpointFormatVersion = 1;\n\ninterface SinkProjection {\n readonly reduced: ReducedState;\n readonly reducerStates: EDAReducerStateSnapshot;\n}\n\ninterface SerializedSinkState {\n readonly formatVersion: typeof sinkCheckpointFormatVersion;\n readonly state: unknown;\n readonly updatedAtMs: number;\n}\n\nconst makeSinkRegistry = (sinks: ReadonlyArray<EDASink>) =>\n Effect.gen(function* () {\n const session = yield* SessionContext;\n const store = yield* EDASessionStore;\n const checkpointStore = yield* SinkCheckpointStore;\n const eventFactory = yield* EventFactory;\n const ids = yield* IdGenerator;\n const reducerRegistry = yield* EDAReducerRegistry;\n const keepAlive = yield* EDAKeepAlive;\n const started = yield* Ref.make(false);\n const hydrationGate = yield* Semaphore.make(1);\n const deliveries: Array<{\n readonly sink: EDASink;\n readonly inbox: Effect.Success<ReturnType<typeof makeSinkInbox>>;\n }> = [];\n\n const baseContext = (\n staged: Array<DurableEventEnvelope>,\n publishEphemeral: (\n event: EphemeralEventEnvelope,\n ) => Effect.Effect<PositionedEvent, EDASessionStoreError>,\n scope: Scope.Scope,\n checkpoint: EDASinkCheckpoint,\n ): EDASinkContext => ({\n sessionId: session.sessionId,\n checkpoint,\n events: eventFactory,\n makeEventId: ids.makeEventId,\n emitEphemeral: publishEphemeral,\n stageDurable: (event) => Effect.sync(() => staged.push(event)),\n forkScoped: (effect) => effect.pipe(Effect.forkIn(scope), Effect.asVoid),\n });\n\n const makeSinkRunner = Effect.fnUntraced(function* (\n sink: EDASink,\n { initialProjection, appendDurableBatch, publishEphemeral, scope }: EDASinkRunnerStartInput,\n ) {\n // Long-lived fibers capture the head and capabilities, not the initial projection.\n const initialHead = initialProjection.reduced.lastSeq;\n const sinkName = EDASinkName.make(sink.name);\n const storedCheckpoint = yield* checkpointStore.load(sinkName);\n const checkpointRef = yield* SynchronizedRef.make(storedCheckpoint);\n const checkpoint = makeSinkCheckpoint(checkpointStore, sinkName, checkpointRef);\n const cursor = storedCheckpoint.afterSeq;\n const cursorRef = yield* Ref.make(cursor);\n if (cursor > initialHead) {\n return yield* new EDASessionStoreError({\n message: `Sink ${sink.name} cursor exceeds session head`,\n });\n }\n // Keep only an exact projection seed; lagging workers reconstruct in their own scope.\n const state = yield* Ref.make<SinkProjection | undefined>(\n sink.state === \"none\"\n ? undefined\n : cursor === initialHead\n ? {\n reduced: initialProjection.reduced,\n reducerStates: initialProjection.reducerStates,\n }\n : cursor === 0\n ? { reduced: initialReducedState, reducerStates: reducerRegistry.initial }\n : undefined,\n );\n const inbox = yield* makeSinkInbox(initialHead).pipe(Scope.provide(scope));\n deliveries.push({ sink, inbox });\n const ensureProjection = Effect.fnUntraced(function* () {\n const existing = yield* Ref.get(state);\n if (existing !== undefined) return existing;\n const hydrated = yield* store.eventsAfter(SequenceNumber.make(0)).pipe(\n Stream.takeWhile((event) => event.position.seq <= cursor),\n Stream.chunks,\n Stream.runFold(\n (): SinkProjection => ({\n reduced: initialReducedState,\n reducerStates: reducerRegistry.initial,\n }),\n (current, page): SinkProjection => ({\n reduced: foldReducedState(current.reduced, page),\n reducerStates: reducerRegistry.reduce(current.reducerStates, page),\n }),\n ),\n Effect.withSpan(\"agent.sink.hydrate\", {\n attributes: {\n \"eda.sink.name\": sink.name,\n \"eda.session.id\": session.sessionId,\n \"eda.seq.through\": cursor,\n },\n }),\n hydrationGate.withPermits(1),\n );\n if (hydrated.reduced.lastSeq !== cursor) {\n return yield* new EDASessionStoreError({\n message: `Sink ${sink.name} could not reconstruct its cursor`,\n });\n }\n yield* Ref.set(state, hydrated);\n return hydrated;\n });\n\n const processDurableBatch = Effect.fnUntraced(function* (\n allEvents: ReadonlyArray<CommittedDurableEvent>,\n ) {\n if (allEvents.length === 0) {\n return;\n }\n\n const currentCursor = yield* Ref.get(cursorRef);\n const fresh = allEvents.filter((entry) => entry.position.seq > currentCursor);\n if (fresh.length === 0) {\n return;\n }\n\n const durable = sink.durable;\n const last = fresh.at(-1);\n if (last === undefined) return;\n const throughSeq = last.position.seq;\n const nextProjection =\n sink.state === \"none\"\n ? undefined\n : yield* Effect.gen(function* () {\n const current = yield* ensureProjection();\n return {\n reduced: foldReducedState(current.reduced, fresh),\n reducerStates: reducerRegistry.reduce(current.reducerStates, fresh),\n };\n });\n const eventsForSink =\n durable === undefined ? [] : filterInterested(fresh, durable.interests);\n\n if (durable !== undefined && eventsForSink.length > 0) {\n yield* Effect.gen(function* () {\n const staged: Array<DurableEventEnvelope> = [];\n const rawBatch: EDASinkRawDurableBatch = {\n allEvents: fresh,\n events: eventsForSink,\n throughSeq,\n };\n const context = baseContext(staged, publishEphemeral, scope, checkpoint);\n const delivery = Effect.gen(function* () {\n if (sink.durable === undefined) return;\n if (sink.state === \"none\") return yield* sink.durable.process(rawBatch, context);\n // The projected branch owns both construction and delivery of these fields.\n if (nextProjection === undefined)\n return yield* Effect.die(\"Projected sink missing its projection\");\n return yield* sink.durable.process(\n {\n ...rawBatch,\n stateAfter: nextProjection.reduced,\n reducerStates: nextProjection.reducerStates,\n },\n context,\n );\n });\n const completed = yield* delivery.pipe(\n Effect.as(true),\n Effect.catchCause((cause) =>\n Cause.hasInterruptsOnly(cause)\n ? Effect.failCause(cause)\n : Effect.logError(\"EDA durable sink violated its infallible contract\", {\n cause: Cause.pretty(cause),\n sink: sink.name,\n }).pipe(Effect.as(false)),\n ),\n );\n if (completed && staged.length > 0) {\n yield* annotateEdaSpan({ \"eda.sink.staged_events\": staged.length });\n yield* appendDurableBatch(staged);\n }\n }).pipe(\n Effect.withSpan(\"agent.sink.drain\", {\n attributes: {\n \"eda.sink.name\": sink.name,\n \"eda.sink.cursor.before\": currentCursor,\n \"eda.sink.events.read\": fresh.length,\n \"eda.sink.events.interested\": eventsForSink.length,\n \"eda.sink.cursor.after\": throughSeq,\n },\n }),\n );\n }\n\n yield* commitSinkCheckpoint(checkpointStore, sinkName, checkpointRef, throughSeq);\n yield* Ref.set(cursorRef, throughSeq);\n yield* Ref.set(state, nextProjection);\n });\n\n const drainDurablesThrough = Effect.fnUntraced(function* (targetHead: SequenceNumber) {\n const currentCursor = yield* Ref.get(cursorRef);\n if (currentCursor >= targetHead) return;\n const allEvents = yield* readCursorBatchThrough(\n store,\n currentCursor,\n targetHead,\n sink.durable?.batchSize,\n );\n if (allEvents.length === 0) {\n return yield* new EDASessionStoreError({\n message: `Sink ${sink.name} could not read its durable backlog`,\n });\n }\n yield* processDurableBatch(allEvents);\n });\n\n const processEphemeral = Effect.fnUntraced(function* (event: PositionedEvent) {\n if (sink.ephemeral === undefined) return;\n if (sink.state !== \"none\") yield* ensureProjection();\n yield* sink.ephemeral\n .process(event, baseContext([], publishEphemeral, scope, checkpoint))\n .pipe(\n Effect.catchCause((cause) =>\n Cause.hasInterruptsOnly(cause)\n ? Effect.failCause(cause)\n : Effect.logError(\"EDA sink ephemeral projection failed\", {\n cause: Cause.pretty(cause),\n sink: sink.name,\n }),\n ),\n );\n });\n\n const runLoop = Effect.forever(\n Effect.gen(function* () {\n const currentCursor = yield* Ref.get(cursorRef);\n const work = yield* inbox.poll(currentCursor);\n if (work === undefined) {\n yield* inbox.awaitWork;\n return;\n }\n yield* keepAlive.withActiveWork(\n `sink:${sink.name}`,\n work._tag === \"Durable\"\n ? drainDurablesThrough(work.throughSeq)\n : processEphemeral(work.event),\n );\n yield* Effect.yieldNow;\n }),\n ).pipe(\n Effect.catchCause((cause) =>\n Cause.hasInterruptsOnly(cause)\n ? Effect.failCause(cause)\n : Effect.logError(\"EDA sink runner failed\", {\n cause: Cause.pretty(cause),\n sink: sink.name,\n }),\n ),\n );\n\n return {\n runLoop,\n initialization:\n sink.state === \"none\"\n ? \"raw\"\n : cursor === initialHead\n ? \"reused\"\n : cursor > 0\n ? \"deferred\"\n : \"empty\",\n };\n });\n\n return {\n sinks,\n startSinkRunners: Effect.fnUntraced(function* (input: EDASinkRunnerStartInput) {\n const wasStarted = yield* Ref.getAndSet(started, true);\n if (wasStarted) {\n return;\n }\n const runners = yield* Effect.gen(function* () {\n const runners = yield* Effect.forEach(sinks, (sink) => makeSinkRunner(sink, input), {\n concurrency: 1,\n });\n yield* Effect.annotateCurrentSpan({\n \"eda.sinks.raw\": runners.filter((runner) => runner.initialization === \"raw\").length,\n \"eda.sinks.reused\": runners.filter((runner) => runner.initialization === \"reused\")\n .length,\n \"eda.sinks.deferred\": runners.filter((runner) => runner.initialization === \"deferred\")\n .length,\n \"eda.sinks.empty\": runners.filter((runner) => runner.initialization === \"empty\").length,\n });\n return runners;\n }).pipe(\n Effect.withSpan(\"agent.sinks.initialize\", {\n attributes: {\n sessionId: session.sessionId,\n \"eda.session.id\": session.sessionId,\n \"eda.seq.head\": input.initialProjection.reduced.lastSeq,\n \"eda.sinks.count\": sinks.length,\n },\n }),\n );\n // Catch-up can append events. Register every inbox before starting any delivery fiber.\n yield* Effect.forEach(\n runners,\n (runner) => runner.runLoop.pipe(Effect.forkIn(input.scope)),\n {\n discard: true,\n },\n );\n }),\n notifyDurableHeadAdvanced: (head) =>\n Effect.forEach(deliveries, ({ inbox }) => inbox.notify(head), { discard: true }),\n publishEphemeralToSinks: (event) =>\n Effect.forEach(\n deliveries,\n ({ sink, inbox }) => {\n if (\n sink.ephemeral === undefined ||\n !matchesInterest(event.event, sink.ephemeral.interests)\n )\n return Effect.void;\n return Effect.gen(function* () {\n const accepted = yield* inbox.offerEphemeral(event);\n if (!accepted) {\n yield* Effect.logWarning(\"EDA sink ephemeral buffer full\", { sink: sink.name });\n }\n }).pipe(\n Effect.catchTag(\"SinkEphemeralEncodingError\", (error) =>\n Effect.logWarning(\"EDA sink ephemeral serialization failed\", {\n cause: error.cause,\n sink: sink.name,\n }),\n ),\n );\n },\n { discard: true },\n ),\n } satisfies EDASinkRegistryShape;\n });\n\nconst makeSinkCheckpoint = (\n store: SinkCheckpointStoreShape,\n sinkName: EDASinkName,\n checkpointRef: SynchronizedRef.SynchronizedRef<StoredSinkCheckpoint>,\n): EDASinkCheckpoint => ({\n get: (schema, initial) =>\n SynchronizedRef.get(checkpointRef).pipe(\n Effect.flatMap((checkpoint) => {\n const serialized = serializedSinkState(checkpoint.payload);\n return serialized === undefined\n ? Effect.succeed(initial)\n : decodeSinkState(schema, serialized.state);\n }),\n ),\n save: (schema, state) =>\n encodeSinkState(schema, state).pipe(\n Effect.flatMap((encoded) => {\n const payload: SerializedSinkState = {\n formatVersion: sinkCheckpointFormatVersion,\n state: encoded,\n updatedAtMs: Date.now(),\n };\n return SynchronizedRef.modifyEffect(checkpointRef, (checkpoint) =>\n store.saveState(sinkName, payload).pipe(\n Effect.as([\n undefined,\n {\n afterSeq: checkpoint.afterSeq,\n payload,\n },\n ] as const),\n ),\n );\n }),\n ),\n});\n\nconst commitSinkCheckpoint = (\n store: SinkCheckpointStoreShape,\n sinkName: EDASinkName,\n checkpointRef: SynchronizedRef.SynchronizedRef<StoredSinkCheckpoint>,\n afterSeq: SequenceNumber,\n): Effect.Effect<void, EDASessionStoreError> =>\n SynchronizedRef.modifyEffect(checkpointRef, (checkpoint) =>\n store.commit(sinkName, afterSeq, checkpoint.payload).pipe(\n Effect.as([\n undefined,\n {\n afterSeq,\n payload: checkpoint.payload,\n },\n ] as const),\n ),\n );\n\nconst serializedSinkState = (payload: unknown): SerializedSinkState | undefined => {\n if (\n typeof payload !== \"object\" ||\n payload === null ||\n !(\"formatVersion\" in payload) ||\n payload.formatVersion !== sinkCheckpointFormatVersion ||\n !(\"state\" in payload) ||\n !(\"updatedAtMs\" in payload) ||\n typeof payload.updatedAtMs !== \"number\"\n ) {\n return undefined;\n }\n return {\n formatVersion: sinkCheckpointFormatVersion,\n state: payload.state,\n updatedAtMs: payload.updatedAtMs,\n };\n};\n\nconst decodeSinkState = <State>(\n schema: Schema.Codec<State, unknown, never, never>,\n encoded: unknown,\n): Effect.Effect<State, EDASessionStoreError> =>\n Effect.try({\n try: () => Schema.decodeUnknownSync(schema)(encoded),\n catch: (cause) => sinkCheckpointCodecError(\"decoding\", cause),\n });\n\nconst encodeSinkState = <State>(\n schema: Schema.Codec<State, unknown, never, never>,\n state: State,\n): Effect.Effect<unknown, EDASessionStoreError> =>\n Effect.try({\n try: () => Schema.encodeUnknownSync(schema)(state),\n catch: (cause) => sinkCheckpointCodecError(\"encoding\", cause),\n });\n\nconst sinkCheckpointCodecError = (operation: string, cause: unknown) =>\n new EDASessionStoreError({\n message:\n cause instanceof Error\n ? `${operation} sink checkpoint: ${cause.message}`\n : `${operation} sink checkpoint: ${String(cause)}`,\n });\n\nconst readCursorBatchThrough = (\n store: EDASessionStoreShape,\n afterSeq: SequenceNumber,\n throughSeq: SequenceNumber,\n batchSize = defaultBatchSize,\n) =>\n store.eventsAfter(afterSeq).pipe(\n Stream.takeWhile((event) => event.position.seq <= throughSeq),\n Stream.take(batchSize),\n Stream.runCollect,\n Effect.map((events) => Array.from(events)),\n );\n\nconst filterInterested = (\n events: ReadonlyArray<CommittedDurableEvent>,\n interests: EDASinkInterests | undefined,\n): ReadonlyArray<CommittedDurableEvent> =>\n events.filter(\n (entry) =>\n interests === undefined ||\n interests === \"*\" ||\n selectCommittedEvent(interests, entry) !== undefined,\n );\n\nconst matchesInterest = (\n event: import(\"../types/events\").EventEnvelope,\n interests:\n | \"*\"\n | Schema.Codec<import(\"../types/events\").EventEnvelope, unknown, never, never>\n | undefined,\n): boolean => interests === undefined || interests === \"*\" || Schema.is(interests)(event);\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;AAQA,MAAM,oBAAoB;AAC1B,MAAM,wBAAwB;;AAG9B,IAAa,6BAAb,cAAgD,OAAO,YAAwC,CAAC,CAC9F,8BACA,EAAE,OAAO,OAAO,OAAO,EAAE,CAC3B,CAAC,CAAC,CAAC;;;;;AAWH,MAAa,gBAAgB,OAAO,WAAW,WAAW,aAA6B;CACrF,MAAM,OAAO,OAAO,OAAO,eAAe,MAAM,QAAc,CAAC,GAAG,MAAM,QAAQ;CAChF,IAAI,OAAO;CACX,MAAM,UAA8E,CAAC;CACrF,IAAI,eAAe;CAEnB,MAAM,UAAU,eACd,OAAO,WAAW;EAChB,OAAO,eAAe,KAAK,KAAK,IAAI,MAAM,UAAU,CAAC;EACrD,MAAM,YAAY,MAAM,KAAA,CAAS;CACnC,CAAC;CAEH,MAAM,kBAAkB,UACtB,OAAO,IAAI;EACT,WAAW;GACT,MAAM,QAAQ,IAAI,YAAY,CAAC,CAAC,OAAO,KAAK,UAAU,KAAK,CAAC,CAAC,CAAC;GAC9D,IAAI,QAAQ,UAAU,qBAAqB,QAAQ,wBAAwB,cACzE,OAAO;GAET,QAAQ,KAAK;IAAE;IAAO;GAAM,CAAC;GAC7B,gBAAgB;GAChB,MAAM,YAAY,MAAM,KAAA,CAAS;GACjC,OAAO;EACT;EACA,QAAQ,UAAU,IAAI,2BAA2B,EAAE,MAAM,CAAC;CAC5D,CAAC;CAEH,MAAM,QAAQ,WACZ,OAAO,WAAW;EAChB,OAAO,QAAQ,SAAS,GAAG;GACzB,MAAM,QAAQ,QAAQ;GACtB,IAAI,UAAU,KAAA,GAAW;GAC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"file":"sink-registry-DtrssBxF.js","names":[],"sources":["../src/services/sink-inbox.ts","../src/services/sink-registry.ts"],"sourcesContent":["import * as Effect from \"effect/Effect\";\nimport * as Queue from \"effect/Queue\";\nimport * as Schema from \"effect/Schema\";\n\nimport { SequenceNumber } from \"../types/core\";\nimport type { PositionedEvent } from \"../types/events\";\n\n/** Durable payloads stay in the log; only bounded best-effort ephemeral work is retained. */\nconst ephemeralCapacity = 128;\nconst ephemeralByteCapacity = 256 * 1024;\n\n/** An ephemeral update could not be measured as a JSON wire value. */\nexport class SinkEphemeralEncodingError extends Schema.TaggedError<SinkEphemeralEncodingError>()(\n \"SinkEphemeralEncodingError\",\n { cause: Schema.Defect() },\n) {}\n\n/** One ordered step on a sink's serialized delivery lane. */\ntype SinkWork =\n | { readonly _tag: \"Durable\"; readonly throughSeq: SequenceNumber }\n | { readonly _tag: \"Ephemeral\"; readonly event: PositionedEvent };\n\n/**\n * Coalesces durable heads without losing ephemeral ordering barriers. Publication never\n * waits for delivery. Overflow drops the newest ephemeral update, never durable work.\n */\nexport const makeSinkInbox = Effect.fnUntraced(function* (initialHead: SequenceNumber) {\n const wake = yield* Effect.acquireRelease(Queue.sliding<void>(1), Queue.shutdown);\n let head = initialHead;\n const pending: Array<{ readonly event: PositionedEvent; readonly bytes: number }> = [];\n let pendingBytes = 0;\n\n const notify = (throughSeq: SequenceNumber) =>\n Effect.sync(() => {\n head = SequenceNumber.make(Math.max(head, throughSeq));\n Queue.offerUnsafe(wake, undefined);\n });\n\n const offerEphemeral = (event: PositionedEvent) =>\n Effect.try({\n try: () => {\n const bytes = new TextEncoder().encode(JSON.stringify(event)).byteLength;\n if (pending.length >= ephemeralCapacity || bytes > ephemeralByteCapacity - pendingBytes) {\n return false;\n }\n pending.push({ event, bytes });\n pendingBytes += bytes;\n Queue.offerUnsafe(wake, undefined);\n return true;\n },\n catch: (cause) => new SinkEphemeralEncodingError({ cause }),\n });\n\n const poll = (cursor: SequenceNumber): Effect.Effect<SinkWork | undefined> =>\n Effect.sync(() => {\n while (pending.length > 0) {\n const first = pending[0];\n if (first === undefined) break;\n if (first.event.position.seq > cursor) {\n return { _tag: \"Durable\", throughSeq: first.event.position.seq };\n }\n pending.shift();\n pendingBytes -= first.bytes;\n if (first.event.position.seq === cursor) {\n return { _tag: \"Ephemeral\", event: first.event };\n }\n }\n return cursor < head ? { _tag: \"Durable\", throughSeq: head } : undefined;\n });\n\n return { notify, offerEphemeral, poll, awaitWork: Queue.take(wake) };\n});\n","import * as Cause from \"effect/Cause\";\nimport * as Context from \"effect/Context\";\nimport * as Effect from \"effect/Effect\";\nimport * as Layer from \"effect/Layer\";\nimport * as Ref from \"effect/Ref\";\nimport * as Schema from \"effect/Schema\";\nimport { type DecodedDurableEvent } from \"../types/events/durable\";\nimport { selectCommittedEvent } from \"./session-store\";\nimport * as Scope from \"effect/Scope\";\nimport * as Semaphore from \"effect/Semaphore\";\nimport * as Stream from \"effect/Stream\";\nimport * as SynchronizedRef from \"effect/SynchronizedRef\";\n\nimport { foldReducedState, initialReducedState, type ReducedState } from \"../domain/reduced-state\";\nimport { EDAReducerRegistry, type EDAReducerStateSnapshot } from \"./reducer-registry\";\nimport { EventId, SessionId, SequenceNumber } from \"../types/core\";\nimport type {\n DurableEventEnvelope,\n EphemeralEventEnvelope,\n PositionedEvent,\n} from \"../types/events\";\nimport type { EDASessionStoreShape } from \"./session-store\";\nimport { type CommittedDurableEvent, EDASessionStore, EDASessionStoreError } from \"./session-store\";\nimport { EventFactory } from \"./event-factory\";\nimport type { EventFactoryShape } from \"./event-factory\";\nimport { IdGenerator } from \"./id-generator\";\nimport { EDAKeepAlive } from \"./keep-alive\";\nimport { makeSinkInbox } from \"./sink-inbox\";\nimport { SessionContext } from \"./session-context\";\nimport {\n EDASinkName,\n SinkCheckpointStore,\n type SinkCheckpointStoreShape,\n type StoredSinkCheckpoint,\n} from \"./sink-checkpoint-store\";\nimport { annotateEdaSpan } from \"./tracing\";\n\n/** Cursor-window input delivered to one durable sink drain. */\nexport interface EDASinkRawDurableBatch<E = DecodedDurableEvent> {\n /** All durable events replayed for this cursor window, including uninterested events. */\n readonly allEvents: ReadonlyArray<CommittedDurableEvent>;\n /** Events matching the sink's durable interests. */\n readonly events: ReadonlyArray<CommittedDurableEvent<E>>;\n /** Durable sequence through which the sink may advance after success. */\n readonly throughSeq: SequenceNumber;\n}\n\n/** Cursor window with framework and app projections, enabled by default. */\nexport interface EDASinkDurableBatch<E = DecodedDurableEvent> extends EDASinkRawDurableBatch<E> {\n /** Authoritative reduced state folded exactly through `throughSeq`. */\n readonly stateAfter: ReducedState;\n /** App-specific durable reducer states folded exactly through `throughSeq`. */\n readonly reducerStates: EDAReducerStateSnapshot;\n}\n\n/** Typed, sink-owned durable state stored independently from cursor advancement. */\nexport interface EDASinkCheckpoint {\n /** Decode current durable state, or return `initial` for a new or legacy cursor row. */\n readonly get: <State>(\n schema: Schema.Codec<State, unknown, never, never>,\n initial: State,\n ) => Effect.Effect<State, EDASessionStoreError>;\n /** Validate, encode, and durably save state without advancing the sink cursor. */\n readonly save: <State>(\n schema: Schema.Codec<State, unknown, never, never>,\n state: State,\n ) => Effect.Effect<void, EDASessionStoreError>;\n}\n\n/** Capabilities exposed to sink processors without granting raw store or bus access. */\nexport interface EDASinkContext {\n readonly sessionId: SessionId;\n /** Sink-owned checkpoint state, serialized with cursor commits and background writes. */\n readonly checkpoint: EDASinkCheckpoint;\n /** Build a framework durable event if the sink needs to emit one. */\n readonly events: EventFactoryShape;\n /** Mint an app durable event id for staged custom events. */\n readonly makeEventId: () => Effect.Effect<EventId>;\n /** Publish a best-effort live-only event. */\n readonly emitEphemeral: (\n event: EphemeralEventEnvelope,\n ) => Effect.Effect<PositionedEvent, EDASessionStoreError>;\n /** Stage durable events; the runner commits them after the sink succeeds. */\n readonly stageDurable: (event: DurableEventEnvelope) => Effect.Effect<void>;\n /** Fork background sink work into the session scope. */\n readonly forkScoped: (effect: Effect.Effect<unknown, unknown>) => Effect.Effect<void>;\n}\n\n/** `\"*\"` and omission select every fact; a schema selects and narrows matching envelopes. */\nexport type EDASinkInterests = \"*\" | Schema.Codec<DurableEventEnvelope, unknown, never, never>;\n\n/** Delivery policy shared by raw and projected durable consumers. */\ninterface EDADurableSinkOptions {\n readonly interests?: EDASinkInterests;\n readonly batchSize?: number;\n}\n\n/** Default durable consumer with framework and app projections at each cursor window. */\nexport interface EDAProjectedDurableSinkDefinition extends EDADurableSinkOptions {\n readonly process: (batch: EDASinkDurableBatch, ctx: EDASinkContext) => Effect.Effect<void, never>;\n}\n\n/** Raw consumer that never hydrates, folds, or retains a session projection. */\nexport interface EDARawDurableSinkDefinition extends EDADurableSinkOptions {\n readonly process: (\n batch: EDASinkRawDurableBatch,\n ctx: EDASinkContext,\n ) => Effect.Effect<void, never>;\n}\n\n/** Durable sink definition backed by a checkpoint and an app-owned delivery policy. */\nexport type EDADurableSinkDefinition = EDAProjectedDurableSinkDefinition;\n\n/** Best-effort live-only sink definition. */\nexport interface EDAEphemeralSinkDefinition {\n readonly interests?:\n | \"*\"\n | Schema.Codec<import(\"../types/events\").EventEnvelope, unknown, never, never>;\n readonly process: (event: PositionedEvent, ctx: EDASinkContext) => Effect.Effect<void, never>;\n}\n\n/**\n * Named app integration hook with optional durable and ephemeral filters.\n *\n * Every sink runs on one serialized position-ordered lane. Sinks own retry and\n * terminal failure handling, so callbacks must have an infallible typed error\n * channel. An unexpected defect is logged and skipped before the durable checkpoint\n * advances. Ephemeral callbacks are best-effort and are only processed after the\n * durable prefix at their anchor sequence has been projected.\n */\ninterface EDASinkOptions {\n readonly name: string;\n readonly ephemeral?: EDAEphemeralSinkDefinition;\n}\n\n/** Existing consumers receive framework and app projections unless explicitly opted out. */\nexport interface EDAProjectedSink extends EDASinkOptions {\n readonly state?: \"projected\";\n readonly durable?: EDAProjectedDurableSinkDefinition;\n}\n\n/** Raw consumers retain only their cursor and sink-owned checkpoint payload. */\nexport interface EDARawSink extends EDASinkOptions {\n readonly state: \"none\";\n readonly durable?: EDARawDurableSinkDefinition;\n}\n\n/** The outer discriminant preserves contextual callback typing for inline default sinks. */\nexport type EDASink = EDAProjectedSink | EDARawSink;\n\n/** Projected and raw overloads preserve contextual callback inference and literal names. */\nfunction makeSink<const Sink extends EDAProjectedSink>(sink: Sink): Sink;\nfunction makeSink<const Sink extends EDARawSink>(sink: Sink): Sink;\nfunction makeSink<const Sink extends EDASink>(sink: Sink): Sink;\nfunction makeSink(sink: EDASink): EDASink {\n return sink;\n}\n\n/** Convenience constructor preserving a sink's literal name/type information. */\nexport const EDASink = {\n make: makeSink,\n /** The live-event schema owns both subscription filtering and callback typing. */\n forEphemeralEvents: <E extends import(\"../types/events\").EventEnvelope>(\n interests: Schema.Codec<E, unknown, never, never>,\n process: (event: PositionedEvent<E>, ctx: EDASinkContext) => Effect.Effect<void, never>,\n ): EDAEphemeralSinkDefinition => ({\n interests,\n process: (entry, ctx) =>\n Schema.is(interests)(entry.event)\n ? process({ position: entry.position, event: entry.event }, ctx)\n : Effect.void,\n }),\n /** One schema selects and narrows the facts delivered to a projected durable consumer. */\n forEvents: <E extends DurableEventEnvelope>(\n interests: Schema.Codec<E, unknown, never, never>,\n sink: Omit<EDAProjectedSink, \"durable\"> & {\n readonly durable: {\n readonly batchSize?: number;\n readonly process: (\n batch: EDASinkDurableBatch<E>,\n ctx: EDASinkContext,\n ) => Effect.Effect<void, never>;\n };\n },\n ): EDAProjectedSink => ({\n ...sink,\n durable: {\n ...sink.durable,\n interests,\n process: (batch, ctx) =>\n sink.durable.process(\n {\n ...batch,\n events: batch.events.flatMap((entry) => {\n const selected = selectCommittedEvent(interests, entry);\n return selected === undefined ? [] : [selected];\n }),\n },\n ctx,\n ),\n },\n }),\n};\n\n/** Session-owned capabilities needed to start all registered sink runners. */\nexport interface EDASinkRunnerStartInput {\n readonly appendDurableBatch: (\n events: ReadonlyArray<DurableEventEnvelope>,\n ) => Effect.Effect<ReadonlyArray<CommittedDurableEvent>, EDASessionStoreError>;\n /** Immutable framework and app projections at one common durable head. */\n readonly initialProjection: {\n readonly reduced: ReducedState;\n readonly reducerStates: EDAReducerStateSnapshot;\n };\n readonly publishEphemeral: (\n event: EphemeralEventEnvelope,\n ) => Effect.Effect<PositionedEvent, EDASessionStoreError>;\n readonly scope: Scope.Scope;\n}\n\n/** Registry service coordinating durable checkpoints and live sink delivery. */\nexport interface EDASinkRegistryShape {\n readonly sinks: ReadonlyArray<EDASink>;\n /** Start long-lived sink runners. Safe to call once during session-state acquisition. */\n readonly startSinkRunners: (\n input: EDASinkRunnerStartInput,\n ) => Effect.Effect<void, EDASessionStoreError>;\n /** Coalesced non-blocking nudge that the durable log head advanced. */\n readonly notifyDurableHeadAdvanced: (head: SequenceNumber) => Effect.Effect<void>;\n /** Best-effort non-blocking delivery to ephemeral sink workers. */\n readonly publishEphemeralToSinks: (event: PositionedEvent) => Effect.Effect<void>;\n}\n\n/** Registry and runner for app-provided EDA sinks. */\nexport class EDASinkRegistry extends Context.Service<EDASinkRegistry, EDASinkRegistryShape>()(\n \"@effect-durable-agent/EDASinkRegistry\",\n) {\n static readonly Empty = Layer.succeed(EDASinkRegistry, {\n sinks: [],\n startSinkRunners: () => Effect.void,\n notifyDurableHeadAdvanced: () => Effect.void,\n publishEphemeralToSinks: () => Effect.void,\n } satisfies EDASinkRegistryShape);\n\n static readonly Live = (sinks: ReadonlyArray<EDASink>) =>\n Layer.effect(EDASinkRegistry, makeSinkRegistry(sinks));\n}\n\nconst defaultBatchSize = 100;\nconst sinkCheckpointFormatVersion = 1;\n\ninterface SinkProjection {\n readonly reduced: ReducedState;\n readonly reducerStates: EDAReducerStateSnapshot;\n}\n\ninterface SerializedSinkState {\n readonly formatVersion: typeof sinkCheckpointFormatVersion;\n readonly state: unknown;\n readonly updatedAtMs: number;\n}\n\nconst makeSinkRegistry = (sinks: ReadonlyArray<EDASink>) =>\n Effect.gen(function* () {\n const session = yield* SessionContext;\n const store = yield* EDASessionStore;\n const checkpointStore = yield* SinkCheckpointStore;\n const eventFactory = yield* EventFactory;\n const ids = yield* IdGenerator;\n const reducerRegistry = yield* EDAReducerRegistry;\n const keepAlive = yield* EDAKeepAlive;\n const started = yield* Ref.make(false);\n const hydrationGate = yield* Semaphore.make(1);\n const deliveries: Array<{\n readonly sink: EDASink;\n readonly inbox: Effect.Success<ReturnType<typeof makeSinkInbox>>;\n }> = [];\n\n const baseContext = (\n staged: Array<DurableEventEnvelope>,\n publishEphemeral: (\n event: EphemeralEventEnvelope,\n ) => Effect.Effect<PositionedEvent, EDASessionStoreError>,\n scope: Scope.Scope,\n checkpoint: EDASinkCheckpoint,\n ): EDASinkContext => ({\n sessionId: session.sessionId,\n checkpoint,\n events: eventFactory,\n makeEventId: ids.makeEventId,\n emitEphemeral: publishEphemeral,\n stageDurable: (event) => Effect.sync(() => staged.push(event)),\n forkScoped: (effect) => effect.pipe(Effect.forkIn(scope), Effect.asVoid),\n });\n\n const makeSinkRunner = Effect.fnUntraced(function* (\n sink: EDASink,\n { initialProjection, appendDurableBatch, publishEphemeral, scope }: EDASinkRunnerStartInput,\n ) {\n // Long-lived fibers capture the head and capabilities, not the initial projection.\n const initialHead = initialProjection.reduced.lastSeq;\n const sinkName = EDASinkName.make(sink.name);\n const storedCheckpoint = yield* checkpointStore.load(sinkName);\n const checkpointRef = yield* SynchronizedRef.make(storedCheckpoint);\n const checkpoint = makeSinkCheckpoint(checkpointStore, sinkName, checkpointRef);\n const cursor = storedCheckpoint.afterSeq;\n const cursorRef = yield* Ref.make(cursor);\n if (cursor > initialHead) {\n return yield* new EDASessionStoreError({\n message: `Sink ${sink.name} cursor exceeds session head`,\n });\n }\n // Keep only an exact projection seed; lagging workers reconstruct in their own scope.\n const state = yield* Ref.make<SinkProjection | undefined>(\n sink.state === \"none\"\n ? undefined\n : cursor === initialHead\n ? {\n reduced: initialProjection.reduced,\n reducerStates: initialProjection.reducerStates,\n }\n : cursor === 0\n ? { reduced: initialReducedState, reducerStates: reducerRegistry.initial }\n : undefined,\n );\n const inbox = yield* makeSinkInbox(initialHead).pipe(Scope.provide(scope));\n deliveries.push({ sink, inbox });\n const ensureProjection = Effect.fnUntraced(function* () {\n const existing = yield* Ref.get(state);\n if (existing !== undefined) return existing;\n const hydrated = yield* store.eventsAfter(SequenceNumber.make(0)).pipe(\n Stream.takeWhile((event) => event.position.seq <= cursor),\n Stream.chunks,\n Stream.runFold(\n (): SinkProjection => ({\n reduced: initialReducedState,\n reducerStates: reducerRegistry.initial,\n }),\n (current, page): SinkProjection => ({\n reduced: foldReducedState(current.reduced, page),\n reducerStates: reducerRegistry.reduce(current.reducerStates, page),\n }),\n ),\n Effect.withSpan(\"agent.sink.hydrate\", {\n attributes: {\n \"eda.sink.name\": sink.name,\n \"eda.session.id\": session.sessionId,\n \"eda.seq.through\": cursor,\n },\n }),\n hydrationGate.withPermits(1),\n );\n if (hydrated.reduced.lastSeq !== cursor) {\n return yield* new EDASessionStoreError({\n message: `Sink ${sink.name} could not reconstruct its cursor`,\n });\n }\n yield* Ref.set(state, hydrated);\n return hydrated;\n });\n\n const processDurableBatch = Effect.fnUntraced(function* (\n allEvents: ReadonlyArray<CommittedDurableEvent>,\n ) {\n if (allEvents.length === 0) {\n return;\n }\n\n const currentCursor = yield* Ref.get(cursorRef);\n const fresh = allEvents.filter((entry) => entry.position.seq > currentCursor);\n if (fresh.length === 0) {\n return;\n }\n\n const durable = sink.durable;\n const last = fresh.at(-1);\n if (last === undefined) return;\n const throughSeq = last.position.seq;\n const nextProjection =\n sink.state === \"none\"\n ? undefined\n : yield* Effect.gen(function* () {\n const current = yield* ensureProjection();\n return {\n reduced: foldReducedState(current.reduced, fresh),\n reducerStates: reducerRegistry.reduce(current.reducerStates, fresh),\n };\n });\n const eventsForSink =\n durable === undefined ? [] : filterInterested(fresh, durable.interests);\n\n if (durable !== undefined && eventsForSink.length > 0) {\n yield* Effect.gen(function* () {\n const staged: Array<DurableEventEnvelope> = [];\n const rawBatch: EDASinkRawDurableBatch = {\n allEvents: fresh,\n events: eventsForSink,\n throughSeq,\n };\n const context = baseContext(staged, publishEphemeral, scope, checkpoint);\n const delivery = Effect.gen(function* () {\n if (sink.durable === undefined) return;\n if (sink.state === \"none\") return yield* sink.durable.process(rawBatch, context);\n // The projected branch owns both construction and delivery of these fields.\n if (nextProjection === undefined)\n return yield* Effect.die(\"Projected sink missing its projection\");\n return yield* sink.durable.process(\n {\n ...rawBatch,\n stateAfter: nextProjection.reduced,\n reducerStates: nextProjection.reducerStates,\n },\n context,\n );\n });\n const completed = yield* delivery.pipe(\n Effect.as(true),\n Effect.catchCause((cause) =>\n Cause.hasInterruptsOnly(cause)\n ? Effect.failCause(cause)\n : Effect.logError(\"EDA durable sink violated its infallible contract\", {\n cause: Cause.pretty(cause),\n sink: sink.name,\n }).pipe(Effect.as(false)),\n ),\n );\n if (completed && staged.length > 0) {\n yield* annotateEdaSpan({ \"eda.sink.staged_events\": staged.length });\n yield* appendDurableBatch(staged);\n }\n }).pipe(\n Effect.withSpan(\"agent.sink.drain\", {\n attributes: {\n \"eda.sink.name\": sink.name,\n \"eda.sink.cursor.before\": currentCursor,\n \"eda.sink.events.read\": fresh.length,\n \"eda.sink.events.interested\": eventsForSink.length,\n \"eda.sink.cursor.after\": throughSeq,\n },\n }),\n );\n }\n\n yield* commitSinkCheckpoint(checkpointStore, sinkName, checkpointRef, throughSeq);\n yield* Ref.set(cursorRef, throughSeq);\n yield* Ref.set(state, nextProjection);\n });\n\n const drainDurablesThrough = Effect.fnUntraced(function* (targetHead: SequenceNumber) {\n const currentCursor = yield* Ref.get(cursorRef);\n if (currentCursor >= targetHead) return;\n const allEvents = yield* readCursorBatchThrough(\n store,\n currentCursor,\n targetHead,\n sink.durable?.batchSize,\n );\n if (allEvents.length === 0) {\n return yield* new EDASessionStoreError({\n message: `Sink ${sink.name} could not read its durable backlog`,\n });\n }\n yield* processDurableBatch(allEvents);\n });\n\n const processEphemeral = Effect.fnUntraced(function* (event: PositionedEvent) {\n if (sink.ephemeral === undefined) return;\n if (sink.state !== \"none\") yield* ensureProjection();\n yield* sink.ephemeral\n .process(event, baseContext([], publishEphemeral, scope, checkpoint))\n .pipe(\n Effect.catchCause((cause) =>\n Cause.hasInterruptsOnly(cause)\n ? Effect.failCause(cause)\n : Effect.logError(\"EDA sink ephemeral projection failed\", {\n cause: Cause.pretty(cause),\n sink: sink.name,\n }),\n ),\n );\n });\n\n const runLoop = Effect.forever(\n Effect.gen(function* () {\n const currentCursor = yield* Ref.get(cursorRef);\n const work = yield* inbox.poll(currentCursor);\n if (work === undefined) {\n yield* inbox.awaitWork;\n return;\n }\n yield* keepAlive.withActiveWork(\n `sink:${sink.name}`,\n work._tag === \"Durable\"\n ? drainDurablesThrough(work.throughSeq)\n : processEphemeral(work.event),\n );\n yield* Effect.yieldNow;\n }),\n ).pipe(\n Effect.catchCause((cause) =>\n Cause.hasInterruptsOnly(cause)\n ? Effect.failCause(cause)\n : Effect.logError(\"EDA sink runner failed\", {\n cause: Cause.pretty(cause),\n sink: sink.name,\n }),\n ),\n );\n\n return {\n runLoop,\n initialization:\n sink.state === \"none\"\n ? \"raw\"\n : cursor === initialHead\n ? \"reused\"\n : cursor > 0\n ? \"deferred\"\n : \"empty\",\n };\n });\n\n return {\n sinks,\n startSinkRunners: Effect.fnUntraced(function* (input: EDASinkRunnerStartInput) {\n const wasStarted = yield* Ref.getAndSet(started, true);\n if (wasStarted) {\n return;\n }\n const runners = yield* Effect.gen(function* () {\n const runners = yield* Effect.forEach(sinks, (sink) => makeSinkRunner(sink, input), {\n concurrency: 1,\n });\n yield* Effect.annotateCurrentSpan({\n \"eda.sinks.raw\": runners.filter((runner) => runner.initialization === \"raw\").length,\n \"eda.sinks.reused\": runners.filter((runner) => runner.initialization === \"reused\")\n .length,\n \"eda.sinks.deferred\": runners.filter((runner) => runner.initialization === \"deferred\")\n .length,\n \"eda.sinks.empty\": runners.filter((runner) => runner.initialization === \"empty\").length,\n });\n return runners;\n }).pipe(\n Effect.withSpan(\"agent.sinks.initialize\", {\n attributes: {\n sessionId: session.sessionId,\n \"eda.session.id\": session.sessionId,\n \"eda.seq.head\": input.initialProjection.reduced.lastSeq,\n \"eda.sinks.count\": sinks.length,\n },\n }),\n );\n // Catch-up can append events. Register every inbox before starting any delivery fiber.\n yield* Effect.forEach(\n runners,\n (runner) => runner.runLoop.pipe(Effect.forkIn(input.scope)),\n {\n discard: true,\n },\n );\n }),\n notifyDurableHeadAdvanced: (head) =>\n Effect.forEach(deliveries, ({ inbox }) => inbox.notify(head), { discard: true }),\n publishEphemeralToSinks: (event) =>\n Effect.forEach(\n deliveries,\n ({ sink, inbox }) => {\n if (\n sink.ephemeral === undefined ||\n !matchesInterest(event.event, sink.ephemeral.interests)\n )\n return Effect.void;\n return Effect.gen(function* () {\n const accepted = yield* inbox.offerEphemeral(event);\n if (!accepted) {\n yield* Effect.logWarning(\"EDA sink ephemeral buffer full\", { sink: sink.name });\n }\n }).pipe(\n Effect.catchTag(\"SinkEphemeralEncodingError\", (error) =>\n Effect.logWarning(\"EDA sink ephemeral serialization failed\", {\n cause: error.cause,\n sink: sink.name,\n }),\n ),\n );\n },\n { discard: true },\n ),\n } satisfies EDASinkRegistryShape;\n });\n\nconst makeSinkCheckpoint = (\n store: SinkCheckpointStoreShape,\n sinkName: EDASinkName,\n checkpointRef: SynchronizedRef.SynchronizedRef<StoredSinkCheckpoint>,\n): EDASinkCheckpoint => ({\n get: (schema, initial) =>\n SynchronizedRef.get(checkpointRef).pipe(\n Effect.flatMap((checkpoint) => {\n const serialized = serializedSinkState(checkpoint.payload);\n return serialized === undefined\n ? Effect.succeed(initial)\n : decodeSinkState(schema, serialized.state);\n }),\n ),\n save: (schema, state) =>\n encodeSinkState(schema, state).pipe(\n Effect.flatMap((encoded) => {\n const payload: SerializedSinkState = {\n formatVersion: sinkCheckpointFormatVersion,\n state: encoded,\n updatedAtMs: Date.now(),\n };\n return SynchronizedRef.modifyEffect(checkpointRef, (checkpoint) =>\n store.saveState(sinkName, payload).pipe(\n Effect.as([\n undefined,\n {\n afterSeq: checkpoint.afterSeq,\n payload,\n },\n ] as const),\n ),\n );\n }),\n ),\n});\n\nconst commitSinkCheckpoint = (\n store: SinkCheckpointStoreShape,\n sinkName: EDASinkName,\n checkpointRef: SynchronizedRef.SynchronizedRef<StoredSinkCheckpoint>,\n afterSeq: SequenceNumber,\n): Effect.Effect<void, EDASessionStoreError> =>\n SynchronizedRef.modifyEffect(checkpointRef, (checkpoint) =>\n store.commit(sinkName, afterSeq, checkpoint.payload).pipe(\n Effect.as([\n undefined,\n {\n afterSeq,\n payload: checkpoint.payload,\n },\n ] as const),\n ),\n );\n\nconst serializedSinkState = (payload: unknown): SerializedSinkState | undefined => {\n if (\n typeof payload !== \"object\" ||\n payload === null ||\n !(\"formatVersion\" in payload) ||\n payload.formatVersion !== sinkCheckpointFormatVersion ||\n !(\"state\" in payload) ||\n !(\"updatedAtMs\" in payload) ||\n typeof payload.updatedAtMs !== \"number\"\n ) {\n return undefined;\n }\n return {\n formatVersion: sinkCheckpointFormatVersion,\n state: payload.state,\n updatedAtMs: payload.updatedAtMs,\n };\n};\n\nconst decodeSinkState = <State>(\n schema: Schema.Codec<State, unknown, never, never>,\n encoded: unknown,\n): Effect.Effect<State, EDASessionStoreError> =>\n Effect.try({\n try: () => Schema.decodeUnknownSync(schema)(encoded),\n catch: (cause) => sinkCheckpointCodecError(\"decoding\", cause),\n });\n\nconst encodeSinkState = <State>(\n schema: Schema.Codec<State, unknown, never, never>,\n state: State,\n): Effect.Effect<unknown, EDASessionStoreError> =>\n Effect.try({\n try: () => Schema.encodeUnknownSync(schema)(state),\n catch: (cause) => sinkCheckpointCodecError(\"encoding\", cause),\n });\n\nconst sinkCheckpointCodecError = (operation: string, cause: unknown) =>\n new EDASessionStoreError({\n message:\n cause instanceof Error\n ? `${operation} sink checkpoint: ${cause.message}`\n : `${operation} sink checkpoint: ${String(cause)}`,\n });\n\nconst readCursorBatchThrough = (\n store: EDASessionStoreShape,\n afterSeq: SequenceNumber,\n throughSeq: SequenceNumber,\n batchSize = defaultBatchSize,\n) =>\n store.eventsAfter(afterSeq).pipe(\n Stream.takeWhile((event) => event.position.seq <= throughSeq),\n Stream.take(batchSize),\n Stream.runCollect,\n Effect.map((events) => Array.from(events)),\n );\n\nconst filterInterested = (\n events: ReadonlyArray<CommittedDurableEvent>,\n interests: EDASinkInterests | undefined,\n): ReadonlyArray<CommittedDurableEvent> =>\n events.filter(\n (entry) =>\n interests === undefined ||\n interests === \"*\" ||\n selectCommittedEvent(interests, entry) !== undefined,\n );\n\nconst matchesInterest = (\n event: import(\"../types/events\").EventEnvelope,\n interests:\n | \"*\"\n | Schema.Codec<import(\"../types/events\").EventEnvelope, unknown, never, never>\n | undefined,\n): boolean => interests === undefined || interests === \"*\" || Schema.is(interests)(event);\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;AAQA,MAAM,oBAAoB;AAC1B,MAAM,wBAAwB;;AAG9B,IAAa,6BAAb,cAAgD,OAAO,YAAwC,CAAC,CAC9F,8BACA,EAAE,OAAO,OAAO,OAAO,EAAE,CAC3B,CAAC,CAAC,CAAC;;;;;AAWH,MAAa,gBAAgB,OAAO,WAAW,WAAW,aAA6B;CACrF,MAAM,OAAO,OAAO,OAAO,eAAe,MAAM,QAAc,CAAC,GAAG,MAAM,QAAQ;CAChF,IAAI,OAAO;CACX,MAAM,UAA8E,CAAC;CACrF,IAAI,eAAe;CAEnB,MAAM,UAAU,eACd,OAAO,WAAW;EAChB,OAAO,eAAe,KAAK,KAAK,IAAI,MAAM,UAAU,CAAC;EACrD,MAAM,YAAY,MAAM,KAAA,CAAS;CACnC,CAAC;CAEH,MAAM,kBAAkB,UACtB,OAAO,IAAI;EACT,WAAW;GACT,MAAM,QAAQ,IAAI,YAAY,CAAC,CAAC,OAAO,KAAK,UAAU,KAAK,CAAC,CAAC,CAAC;GAC9D,IAAI,QAAQ,UAAU,qBAAqB,QAAQ,wBAAwB,cACzE,OAAO;GAET,QAAQ,KAAK;IAAE;IAAO;GAAM,CAAC;GAC7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