@rotorsoft/act 2.1.1 → 2.1.2
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.
- package/dist/.tsbuildinfo +1 -1
- package/dist/@types/act.d.ts.map +1 -1
- package/dist/@types/csv.d.ts +2 -1
- package/dist/@types/csv.d.ts.map +1 -1
- package/dist/@types/internal/correlate-cycle.d.ts.map +1 -1
- package/dist/@types/scoped.d.ts +2 -4
- package/dist/@types/scoped.d.ts.map +1 -1
- package/dist/@types/types/action.d.ts +1 -213
- package/dist/@types/types/action.d.ts.map +1 -1
- package/dist/@types/types/index.d.ts +1 -0
- package/dist/@types/types/index.d.ts.map +1 -1
- package/dist/@types/types/ports.d.ts +2 -1
- package/dist/@types/types/ports.d.ts.map +1 -1
- package/dist/@types/types/restore.d.ts +220 -0
- package/dist/@types/types/restore.d.ts.map +1 -0
- package/dist/adapter.cjs +3 -3
- package/dist/adapter.js +2 -2
- package/dist/{chunk-QPVUARKL.js → chunk-ADMH76IO.js} +3 -3
- package/dist/{chunk-QPVUARKL.js.map → chunk-ADMH76IO.js.map} +1 -1
- package/dist/{chunk-W3PHEA5Q.js → chunk-C35J3SNT.js} +1 -1
- package/dist/chunk-C35J3SNT.js.map +1 -0
- package/dist/{chunk-PZQXTGWF.cjs → chunk-D7LQNOEV.cjs} +4 -4
- package/dist/{chunk-PZQXTGWF.cjs.map → chunk-D7LQNOEV.cjs.map} +1 -1
- package/dist/{chunk-7VYSJIXD.cjs → chunk-QFYPSI6P.cjs} +1 -1
- package/dist/chunk-QFYPSI6P.cjs.map +1 -0
- package/dist/{chunk-LN3OP4OL.cjs → chunk-QWYMR7ZP.cjs} +17 -17
- package/dist/{chunk-LN3OP4OL.cjs.map → chunk-QWYMR7ZP.cjs.map} +1 -1
- package/dist/{chunk-UXDNSZAD.js → chunk-TUALNYW2.js} +2 -2
- package/dist/index.cjs +192 -196
- package/dist/index.cjs.map +1 -1
- package/dist/index.js +9 -13
- package/dist/index.js.map +1 -1
- package/dist/test/index.cjs +5 -5
- package/dist/test/index.js +3 -3
- package/dist/types/index.cjs +2 -2
- package/dist/types/index.js +1 -1
- package/package.json +1 -1
- package/dist/chunk-7VYSJIXD.cjs.map +0 -1
- package/dist/chunk-W3PHEA5Q.js.map +0 -1
- /package/dist/{chunk-UXDNSZAD.js.map → chunk-TUALNYW2.js.map} +0 -0
package/dist/index.cjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["/home/runner/work/act-root/act-root/libs/act/dist/index.cjs","../src/signals.ts","../src/act.ts","../src/internal/event-versions.ts","../src/internal/walk-streams.ts","../src/internal/audit.ts","../src/internal/circuit-breaker.ts","../src/internal/classify.ts","../src/internal/autoclose-policy.ts","../src/internal/autoclose-window.ts","../src/internal/defer-config.ts","../src/internal/drain-cycle.ts","../src/internal/backoff.ts","../src/internal/defer-timer.ts","../src/internal/drain-ratio.ts","../src/internal/report-once.ts","../src/internal/correlation-id.ts","../src/internal/drain-ops.ts","../src/internal/event-sourcing.ts","../src/internal/tracing.ts","../src/internal/reaction-dispatch.ts","../src/internal/autoclose-reaction.ts","../src/internal/close-cycle.ts","../src/internal/correlate-cycle.ts","../src/internal/pii.ts","../src/internal/projection-fold.ts","../src/internal/settle.ts","../src/builders/merge.ts","../src/builders/builder-utils.ts","../src/builders/event-builder.ts","../src/internal/date-reviver.ts","../src/builders/act-builder.ts","../src/builders/projection-builder.ts","../src/builders/slice-builder.ts","../src/builders/state-builder.ts","../src/csv.ts","../src/deprecated.ts"],"names":["store","state","sensitive","deps"],"mappings":"AAAA;AACE;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACF,wDAA6B;AAC7B;AACE;AACA;AACA;AACA;AACA;AACA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EnC,IAAA;AACA,IAAA;AAAa,EAAA;AAEjB;AAEA;AACE,EAAA;AACA,EAAA;AACE,IAAA;AACA,IAAA;AACA,IAAA;AACA,IAAA;AACA,IAAA;AAAsB,EAAA;AAE1B;AAEA;AACE,EAAA;AACA,EAAA;AACA,EAAA;AACE,IAAA;AACE,MAAA;AACA,MAAA;AACA,MAAA;AACE,QAAA;AACE,UAAA;AACA,UAAA;AAAK,QAAA;AAEL,UAAA;AACA,UAAA;AAAA,QAAA;AAEA,UAAA;AAAiB,QAAA;AACnB,MAAA;AAEF,MAAA;AACA,MAAA;AAAqB,IAAA;AAErB,MAAA;AACA,MAAA;AACE,QAAA;AACA,QAAA;AAAS,MAAA;AAET,QAAA;AACA,QAAA;AAAW,MAAA;AACb,IAAA;AACF,EAAA;AAEF,EAAA;AACF;AAEA;AACE,EAAA;AACA,EAAA;AACF;AAEA;AACE,EAAA;AACE,IAAA;AAAoB;AAClB,MAAA;AAAmB,MAAA;AACN,IAAA;AACd,EAAA;AAEL;AnCorKA;AACA;AoC12KO;AAEA;AAEA;AAEA;AAEA;AAEA;AAEA;AAGA;AAGA;AAEA;AAEA;AAEA;AAGA;AAGA;AAEA;AAEA;AAEA;AAEA;AAEA;AAGA;AAIA;AAEA;AAEA;AAGA;AAWP;AAIO;ApCg0KP;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA","file":"/home/runner/work/act-root/act-root/libs/act/dist/index.cjs","sourcesContent":[null,"import { disposeAndExit, log } from \"./ports.js\";\n\n// Resolve the logger lazily inside each handler — calling log() here at\n// module load would register the default ConsoleLogger before user code\n// can inject (port singletons are first-call-wins).\nprocess.once(\"SIGINT\", async (arg?: any) => {\n log().info(arg, \"SIGINT\");\n await disposeAndExit(\"EXIT\");\n});\nprocess.once(\"SIGTERM\", async (arg?: any) => {\n log().info(arg, \"SIGTERM\");\n await disposeAndExit(\"EXIT\");\n});\nprocess.once(\"uncaughtException\", async (arg?: any) => {\n log().error(arg, \"Uncaught Exception\");\n await disposeAndExit(\"ERROR\");\n});\nprocess.once(\"unhandledRejection\", async (arg?: any) => {\n log().error(arg, \"Unhandled Rejection\");\n await disposeAndExit(\"ERROR\");\n});\n","import EventEmitter from \"node:events\";\nimport { register_weak_disposer } from \"./disposers.js\";\nimport { type AuditDeps, audit } from \"./internal/audit.js\";\nimport { CircuitBreaker } from \"./internal/circuit-breaker.js\";\nimport {\n ALL_LANES,\n classify_registry,\n type EventLaneSet,\n} from \"./internal/classify.js\";\nimport {\n CloseLock,\n catch_up_correlation,\n run_close_cycle,\n} from \"./internal/close-cycle.js\";\nimport {\n check_store,\n DEFAULT_LEASE_MILLIS,\n MAX_SHUTDOWN_GRACE_MS,\n resolveAutocloseConfig,\n resolveCircuitBreakerConfig,\n resolveDrainConfig,\n resolveSettleConfig,\n resolveShutdownConfig,\n resolveTargetConfig,\n} from \"./internal/config.js\";\nimport {\n CorrelateCycle,\n type CorrelatePass,\n} from \"./internal/correlate-cycle.js\";\nimport {\n close_correlation,\n default_correlator,\n} from \"./internal/correlation-id.js\";\nimport {\n DrainController,\n type Handle,\n type HandleBatch,\n merge_drains,\n} from \"./internal/drain-cycle.js\";\nimport type { DrainOps } from \"./internal/drain-ops.js\";\nimport { bare_patch, type EsOps, scan } from \"./internal/event-sourcing.js\";\nimport {\n FOLD_RESET,\n type ResettableBatchHandler,\n} from \"./internal/projection-fold.js\";\nimport {\n build_handle,\n build_handle_batch,\n} from \"./internal/reaction-dispatch.js\";\nimport { SettleLoop } from \"./internal/settle.js\";\nimport { build_drain, build_es } from \"./internal/tracing.js\";\nimport { walk_streams } from \"./internal/walk-streams.js\";\nimport { cache, log, store, unscoped_ports } from \"./ports.js\";\nimport {\n current_reacting,\n make_reaction_scope,\n make_run_scoped,\n} from \"./scoped.js\";\nimport {\n type ActLifecycleEvents,\n type ActOptions,\n type CircuitState,\n DEFAULT_MAX_SUBSCRIBED_STREAMS,\n DEFAULT_SETTLE_DEBOUNCE_MS,\n type Scoped,\n} from \"./types/act.js\";\nimport { StoreError } from \"./types/errors.js\";\nimport type {\n Actor,\n AsOf,\n AuditCategory,\n AuditFinding,\n AuditOptions,\n BatchHandler,\n CloseResult,\n CloseTarget,\n Committed,\n Correlator,\n DoOptions,\n Drain,\n DrainOptions,\n EventSink,\n EventSource,\n IAct,\n LaneConfig,\n LoadTarget,\n Logger,\n PatchFn,\n Query,\n Registry,\n ScanOptions,\n ScanResult,\n Schema,\n SchemaRegister,\n Schemas,\n SettleOptions,\n ShutdownOptions,\n Snapshot,\n State,\n Store,\n StreamFilter,\n StreamPosition,\n Target,\n} from \"./types/index.js\";\n\n/** Reject `onlyLanes` entries that reference undeclared lanes. */\nfunction validate_only_lanes(\n only: ReadonlyArray<string> | undefined,\n declared: ReadonlyArray<string>\n): void {\n const unknown = (only ?? []).filter((l) => !declared.includes(l));\n if (unknown.length > 0)\n throw new Error(\n `ActOptions.onlyLanes references undeclared lane(s): ${unknown\n .map((l) => `\"${l}\"`)\n .join(\", \")}`\n );\n}\n\n/**\n * @category Orchestrator\n * @see Store\n *\n * The orchestrator: executes actions, loads state, queries events, and runs\n * the reactions each commit frees (on its own, unless `autoSettle: false`).\n *\n * ```typescript\n * const app = act().withState(Counter).build();\n * await app.do(\"increment\", { stream: \"counter1\", actor }, { by: 1 });\n * const snapshot = await app.load(Counter, \"counter1\");\n * ```\n *\n * @template TSchemaReg SchemaRegister for state\n * @template TEvents Schemas for events\n * @template TActions Schemas for actions\n * @template TStateMap Map of state names to state schemas\n * @template TActor Actor type extending base Actor\n */\nexport class Act<\n TSchemaReg extends SchemaRegister<TActions>,\n TEvents extends Schemas,\n TActions extends Schemas,\n TStateMap extends Record<string, Schema> = Record<string, never>,\n TActor extends Actor = Actor,\n> implements IAct<TEvents, TActions, TActor, TSchemaReg>\n{\n private _emitter = new EventEmitter();\n private readonly _breaker: CircuitBreaker;\n private readonly _drain: boolean;\n private readonly _auto_settle: boolean;\n // Whether any event has a reaction; nothing arms without one.\n private readonly _reactive: boolean;\n private readonly _drain_controllers: Map<\n string,\n DrainController<TEvents, TActions, TSchemaReg>\n >;\n private readonly _correlate: CorrelateCycle<TSchemaReg, TEvents, TActions>;\n private readonly _settle: SettleLoop<TEvents>;\n private _poll: ReturnType<typeof setInterval> | undefined;\n // The poll's correlate `limit`, used by every settle pass while it runs.\n private _poll_limit: number | undefined;\n // Wired at construction against the store current then, so a store\n // injected after `build()` is never notified.\n private readonly _notify_disposer: Promise<\n (() => void | Promise<void>) | undefined\n >;\n /** Public registry — kept as-is per the no-prefix-on-public convention. */\n public readonly registry: Registry<\n TSchemaReg,\n TEvents,\n TActions,\n keyof TStateMap & string\n >;\n private readonly _states: Map<string, State<any, any, any>>;\n /**\n * Emit a lifecycle event. The payload type is inferred from the event name\n * via {@link ActLifecycleEvents}.\n *\n * Each listener is contained on its own: a throwing listener is logged,\n * the remaining listeners still run, and the caller (`do()`, `forget()`,\n * `close()`, the drain) never sees the throw, since its durable work has\n * already landed.\n *\n * Uses `rawListeners` so `once` wrappers still de-register themselves, and\n * returns \"had listeners\" to preserve the `EventEmitter.emit` contract.\n */\n emit<E extends keyof ActLifecycleEvents<TSchemaReg, TEvents, TActions>>(\n event: E,\n args: ActLifecycleEvents<TSchemaReg, TEvents, TActions>[E]\n ): boolean {\n return this._notify(event as string, args);\n }\n\n // Run each listener of `key` on its own, logging any that throws.\n private _notify(key: string, args: unknown): boolean {\n const listeners = this._emitter.rawListeners(key);\n for (const listener of listeners) {\n try {\n listener(args);\n } catch (error) {\n this._logger.error(error, `${key} listener threw`);\n }\n }\n return listeners.length > 0;\n }\n\n // The emitter key of one state's `committed` listeners.\n private _committed_key(state: State<any, any, any> | string): string {\n const name = typeof state === \"string\" ? state : state.name;\n if (!this._states.has(name))\n throw new Error(`committed: \"${name}\" is not a state of this app`);\n return `committed:${name}`;\n }\n\n // The one place a store failure is logged and emitted (the breaker's\n // `on_error`). The emit is guarded: an unhandled `\"error\"` emission\n // would crash the process.\n private _emit_error(error: unknown, circuit: CircuitState): void {\n this._logger.error(error);\n if (this._emitter.listenerCount(\"error\") > 0)\n this.emit(\"error\", { error, circuit });\n }\n\n /**\n * Register a listener for a lifecycle event. The listener receives the\n * event-specific payload.\n *\n * `committed` also takes a state, as a `State` or its name: the listener\n * then hears only commits to that state's streams, whichever action\n * appended them, with its snapshots typed from that state.\n *\n * @example\n * ```typescript\n * app.on(\"committed\", Counter, (snapshots) => {\n * console.log(snapshots.at(-1)?.state.count); // typed: number\n * });\n * ```\n */\n on<E extends keyof ActLifecycleEvents<TSchemaReg, TEvents, TActions>>(\n event: E,\n listener: (\n args: ActLifecycleEvents<TSchemaReg, TEvents, TActions>[E]\n ) => void\n ): this;\n on<\n TNewState extends Schema,\n TNewEvents extends Schemas,\n TNewActions extends Schemas,\n >(\n event: \"committed\",\n state: State<TNewState, TNewEvents, TNewActions>,\n listener: (snapshots: Snapshot<TNewState, TNewEvents>[]) => void\n ): this;\n on<TKey extends keyof TStateMap & string>(\n event: \"committed\",\n state: TKey,\n listener: (snapshots: Snapshot<TStateMap[TKey], TEvents>[]) => void\n ): this;\n on(\n event: string,\n state_or_listener: State<any, any, any> | string | ((args: any) => void),\n listener?: (args: any) => void\n ): this {\n if (listener)\n this._emitter.on(\n this._committed_key(state_or_listener as State<any, any, any>),\n listener\n );\n else this._emitter.on(event, state_or_listener as (args: any) => void);\n return this;\n }\n\n /**\n * Remove a previously registered lifecycle listener, with the state it\n * was registered for when it has one.\n */\n off<E extends keyof ActLifecycleEvents<TSchemaReg, TEvents, TActions>>(\n event: E,\n listener: (\n args: ActLifecycleEvents<TSchemaReg, TEvents, TActions>[E]\n ) => void\n ): this;\n off<\n TNewState extends Schema,\n TNewEvents extends Schemas,\n TNewActions extends Schemas,\n >(\n event: \"committed\",\n state: State<TNewState, TNewEvents, TNewActions>,\n listener: (snapshots: Snapshot<TNewState, TNewEvents>[]) => void\n ): this;\n off<TKey extends keyof TStateMap & string>(\n event: \"committed\",\n state: TKey,\n listener: (snapshots: Snapshot<TStateMap[TKey], TEvents>[]) => void\n ): this;\n off(\n event: string,\n state_or_listener: State<any, any, any> | string | ((args: any) => void),\n listener?: (args: any) => void\n ): this {\n if (listener)\n this._emitter.off(\n this._committed_key(state_or_listener as State<any, any, any>),\n listener\n );\n else this._emitter.off(event, state_or_listener as (args: any) => void);\n return this;\n }\n\n private readonly _batch_handlers: Map<string, BatchHandler<TEvents>>;\n private readonly _es: EsOps;\n private readonly _cd: DrainOps<TEvents>;\n // Unambiguous: merge rejects an event name declared by two states.\n private readonly _event_to_state: ReadonlyMap<string, State<any, any, any>>;\n // Lanes to arm per event; `\"all\"` when a dynamic resolver hides the lane.\n private readonly _event_to_lanes: ReadonlyMap<string, EventLaneSet>;\n private readonly _audit_deps: AuditDeps;\n private readonly _logger: Logger = log();\n // This Act's ports: its own bag, or the singleton adapters.\n private readonly _ports: Scoped;\n // Runs a body so internal `store()`/`cache()` calls resolve to `_ports`.\n private readonly _scoped: <T>(fn: () => Promise<T>) => Promise<T>;\n\n private readonly _correlator: Correlator;\n private readonly _lanes: ReadonlyArray<LaneConfig>;\n\n private readonly _close_lock = new CloseLock();\n // Every lane a controller can exist for: `\"default\"` plus each declared one.\n private readonly _declared_lanes: ReadonlyArray<string>;\n\n /** Drain lanes declared via `.withLane(...)`. Implicit default not included. */\n get lanes(): ReadonlyArray<LaneConfig> {\n return this._lanes;\n }\n\n /** Use the {@link act} builder rather than constructing directly. */\n constructor(\n registry: Registry<TSchemaReg, TEvents, TActions, keyof TStateMap & string>,\n states: Map<string, State<any, any, any>> = new Map(),\n batch_handlers: Map<string, BatchHandler<any>> = new Map(),\n options: ActOptions = {},\n lanes: ReadonlyArray<LaneConfig> = [],\n patch_fn: PatchFn = bare_patch\n ) {\n this.registry = registry;\n this._states = states;\n this._batch_handlers = batch_handlers;\n this._lanes = lanes;\n this._declared_lanes = [\"default\", ...lanes.map((l) => l.name)];\n validate_only_lanes(options.onlyLanes, this._declared_lanes);\n // Every Act runs in its own ports frame (the singletons when unscoped),\n // so a shared Act never inherits its caller's frame.\n if (options.scoped) check_store(options.scoped.store);\n this._ports = options.scoped ?? unscoped_ports();\n const ports = this._ports;\n this._scoped = make_run_scoped({\n // Getters, not a spread: the singletons resolve lazily, so a later\n // `store(...)` / `cache(...)` still takes effect.\n get store() {\n return ports.store;\n },\n get cache() {\n return ports.cache;\n },\n // Parsed per build, so a bad window throws on every build.\n autoclose_window: resolveAutocloseConfig(options).autocloseWindow,\n });\n this._correlator = options.correlator ?? default_correlator;\n this._es = build_es(this._logger, this._correlator, patch_fn);\n this._cd = build_drain<TEvents>(this._logger);\n // PII stripping is wrapped around handlers at build time, so the\n // dispatcher is PII-unaware. Bound once, reused by every reaction payload.\n const handle = build_handle<TEvents, TActions, TActor>({\n logger: this._logger,\n reaction_scope: make_reaction_scope({\n do: this.do.bind(this),\n load: this.load.bind(this),\n query: this.query.bind(this),\n query_array: this.query_array.bind(this),\n forget: this.forget.bind(this),\n }),\n });\n const handle_batch = build_handle_batch<TEvents>(this._logger);\n\n const classification = classify_registry(this.registry, this._states);\n this._reactive = classification.event_to_lanes.size > 0;\n this._event_to_state = classification.event_to_state;\n this._event_to_lanes = classification.event_to_lanes;\n this._drain = options.drain !== false;\n this._auto_settle = options.autoSettle !== false;\n\n // Order matters: controllers read the breaker, the audit bag reads the\n // controller set, settle reads the correlate cycle.\n this._breaker = this._build_breaker(options);\n this._drain_controllers = this._build_drain_controllers(\n options,\n lanes,\n handle,\n handle_batch\n );\n this._advise_orphaned_lanes();\n this._audit_deps = this._build_audit_deps();\n this._correlate = this._build_correlate(options, classification);\n this._settle = this._build_settle(options);\n\n // Wire cross-process notify against the store current at construction.\n this._notify_disposer = this._wire_notify(\n this._ports.store,\n options.listen !== false\n );\n\n // Registered weakly, so `dispose()()` reaches a live Act while an\n // unreachable one (per tenant, per test) can still be collected.\n register_weak_disposer(new WeakRef(this), (self) => self.shutdown());\n }\n\n // Shared by drain, settle and autoclose; bad knobs throw at build.\n private _build_breaker(options: ActOptions): CircuitBreaker {\n return new CircuitBreaker(\n resolveCircuitBreakerConfig(options.circuitBreaker),\n {\n on_error: (error, circuit) => this._emit_error(error, circuit),\n // When the cooldown elapses, settle once: its scan or claim is the\n // half-open probe that closes or re-opens the breaker.\n on_retry: () => this._schedule(),\n }\n );\n }\n\n // Apps that declare no lanes pass no lane filter to `claim`.\n private _build_drain_controllers(\n options: ActOptions,\n lanes: ReadonlyArray<LaneConfig>,\n handle: Handle<TEvents>,\n handle_batch: HandleBatch<TEvents>\n ): Map<string, DrainController<TEvents, TActions, TSchemaReg>> {\n const all_lanes = this._declared_lanes;\n const only_set = options.onlyLanes?.length\n ? new Set<string>(options.onlyLanes as readonly string[])\n : undefined;\n const active_lanes = only_set\n ? all_lanes.filter((n) => only_set.has(n))\n : all_lanes;\n // Decided by the declared lanes, not the active ones: a worker narrowed\n // to \"default\" must still filter, or it would claim every lane.\n const single_default_lane = lanes.length === 0;\n const controllers = new Map<\n string,\n DrainController<TEvents, TActions, TSchemaReg>\n >();\n for (const name of active_lanes) {\n const cfg = lanes.find((l) => l.name === name);\n const controller = new DrainController({\n logger: this._logger,\n ops: this._cd,\n registry: this.registry,\n batch_handlers: this._batch_handlers,\n handle,\n handle_batch,\n on_acked: (acked) => this.emit(\"acked\", acked),\n on_blocked: (blocked) => this.emit(\"blocked\", blocked),\n // Reaction-requested close: the same machinery as `app.close`.\n // A store failure reaches the breaker; anything else (the archive\n // callback is app code) is logged here, never counted.\n on_close: async (targets) => {\n try {\n await this._run_close(targets);\n } catch (error) {\n if (error instanceof StoreError) throw error;\n this._logger.error(\n error,\n `Reaction-requested close of ${targets.map((t) => `\"${t.stream}\"`).join(\", \")} failed and was not retried; close it with app.close(...) once the cause is fixed.`\n );\n }\n },\n breaker: this._breaker,\n run_scoped: this._scoped,\n lane: single_default_lane ? undefined : name,\n defaults: cfg && {\n streamLimit: cfg.streamLimit,\n leaseMillis: cfg.leaseMillis,\n },\n });\n // A lane with `cycleMs` drives itself on that timer (not on\n // writer-only instances).\n if (cfg?.cycleMs !== undefined && this._drain)\n controller.start(cfg.cycleMs);\n controllers.set(name, controller);\n }\n return controllers;\n }\n\n // One process can't see the cluster, so it reports its own lane gaps.\n private _advise_orphaned_lanes(): void {\n const active = new Set(this._drain_controllers.keys());\n const orphaned = this._declared_lanes.filter((name) => !active.has(name));\n if (orphaned.length === 0) return;\n const list = orphaned.map((name) => `\"${name}\"`).join(\", \");\n this._logger.info(\n `Act declared ${orphaned.length} orphaned lane(s) on this instance: ${list}. ` +\n `onlyLanes excludes them, so no DrainController claims their streams here — ` +\n `their reactions accumulate un-drained unless a peer worker deploys with these ` +\n `lanes in its onlyLanes. Ensure the cluster invariant holds: the union of every ` +\n `worker's onlyLanes must cover every declared lane. ` +\n `See docs/docs/guides/production-checklist.md § Sizing lanes.`\n );\n }\n\n // Audit deps, built after the controllers so the lane set is final.\n private _build_audit_deps(): AuditDeps {\n return {\n store,\n event_to_state: this._event_to_state,\n // Declared lanes, not this process's controllers: a lane another\n // worker drains is not `unknown-lane`.\n declared_lanes: new Set(this._declared_lanes),\n routed_events: new Set(this._event_to_lanes.keys()),\n };\n }\n\n private _build_correlate(\n options: ActOptions,\n classification: ReturnType<\n typeof classify_registry<TSchemaReg, TEvents, TActions>\n >\n ): CorrelateCycle<TSchemaReg, TEvents, TActions> {\n return new CorrelateCycle({\n registry: this.registry,\n static_targets: classification.static_targets,\n cd: this._cd,\n max_subscribed_streams:\n options.maxSubscribedStreams ?? DEFAULT_MAX_SUBSCRIBED_STREAMS,\n // Declared lanes (not active ones): a lane another process claims is\n // still a valid destination.\n declared_lanes: new Set(this._declared_lanes),\n // Built after the controllers, so their keys are the active lanes.\n shard:\n this._drain_controllers.size < this._declared_lanes.length\n ? [...this._drain_controllers.keys()]\n : undefined,\n // Only reached on a draining app: writer-only ones never correlate.\n on_init: async () => {\n this._arm_all();\n await this._seed_persisted_defers();\n },\n });\n }\n\n // Cold start: an idle deferred stream still fires on time after a restart.\n private async _seed_persisted_defers(): Promise<void> {\n const now = Date.now();\n await walk_streams(store(), (pos) => {\n // A past-due schedule is already claimable.\n if (pos.deferred_at === undefined || pos.deferred_at <= now) return;\n const controller = this._drain_controllers.get(pos.lane ?? \"default\");\n controller?.seed_defer(pos.stream, pos.deferred_at);\n });\n }\n\n private _build_settle(options: ActOptions): SettleLoop<TEvents> {\n return new SettleLoop<TEvents>(\n {\n correlate: (q) =>\n this._correlate_pass(q.limit ?? this._poll_limit ?? 100, true),\n // `settle()` validated the options, and `_schedule` skips writer-only\n // instances, so the loop drains through the internal path.\n drain: (o) => this._scoped(() => this._drain_all(o)),\n on_settled: (drain) => this.emit(\"settled\", drain),\n breaker: this._breaker,\n },\n options.settleDebounceMs ?? DEFAULT_SETTLE_DEBOUNCE_MS\n );\n }\n\n private _shutdown_promise: Promise<void> | undefined;\n\n /**\n * Per-instance teardown: stops scheduling, removes the notify\n * subscription, gives the cycles in flight up to `graceMs` to reach their\n * `ack` (an abandoned handler holds its lease until it expires), then\n * hands back the correlation lease and removes listeners.\n * The budget is a ceiling, not a delay.\n *\n * Idempotent: repeated calls return the same promise, with the first\n * call's `graceMs`. Registered with the global `dispose()` registry, so\n * `dispose()()` covers it; call it directly for prompt cleanup.\n *\n * @param options - See {@link ShutdownOptions}. Defaults the grace budget\n * to the largest lane `leaseMillis` (capped at 30s).\n */\n shutdown(options?: ShutdownOptions): Promise<void> {\n if (!this._shutdown_promise) {\n resolveShutdownConfig(options);\n this._shutdown_promise = (async () => {\n // Stop every scheduler before awaiting anything slow, so nothing\n // starts while the notify subscription comes down.\n this.stop_correlations();\n this._settle.stop(true);\n this._breaker.stop();\n for (const c of this._drain_controllers.values()) c.stop();\n // Never rejects.\n const disposer = await this._notify_disposer;\n if (disposer) await disposer();\n await this._await_inflight(options?.graceMs);\n // Hand the correlation lease back last, after the wait (a settle\n // cycle still running would re-take it), and await it so a\n // successor isn't refused.\n await this._scoped(() => this._correlate.release_correlation());\n this._emitter.removeAllListeners();\n })();\n }\n return this._shutdown_promise;\n }\n\n // The largest `leaseMillis` among lanes with a cycle in flight (the\n // default for none or 0, and for a running settle), capped.\n private _derive_grace_ms(\n running: { readonly lease_millis: number | undefined }[],\n settling: boolean\n ): number {\n // A lane with no lease waits the drain's default lease: as long as its\n // handlers were already allowed to hold a stream.\n let max = settling ? DEFAULT_LEASE_MILLIS : 0;\n for (const c of running)\n max = Math.max(max, c.lease_millis || DEFAULT_LEASE_MILLIS);\n return Math.min(max, MAX_SHUTDOWN_GRACE_MS);\n }\n\n private async _await_inflight(grace_ms?: number): Promise<void> {\n const running = [...this._drain_controllers.values()].filter(\n (c) => c.inflight !== undefined\n );\n // A settle cycle already running keeps going after `stop()`, so wait\n // for it too.\n const settling = this._settle.inflight;\n if (running.length === 0 && !settling) return;\n const grace = grace_ms ?? this._derive_grace_ms(running, !!settling);\n if (grace <= 0) return;\n let timer!: ReturnType<typeof setTimeout>;\n const budget = new Promise<void>((resolve) => {\n timer = setTimeout(resolve, grace);\n timer.unref();\n });\n try {\n await Promise.race([\n Promise.all([...running.map((c) => c.inflight), settling]),\n budget,\n ]);\n } finally {\n // Don't leave the budget timer pending when the cycles won the race.\n clearTimeout(timer);\n }\n }\n\n // Failures are logged, never thrown: `notify` is a hint.\n private async _wire_notify(\n s: Store,\n listen: boolean\n ): Promise<(() => void | Promise<void>) | undefined> {\n if (!this._reactive) return undefined;\n if (!s.notify) return undefined;\n // Only the subscriber side is gated; commits still notify.\n if (!listen) return undefined;\n try {\n return await s.notify((notification) => {\n // Errors are logged and swallowed so the store's listener survives.\n try {\n this.emit(\"notified\", notification);\n this._wake(notification.events.map((e) => e.name));\n } catch (err) {\n this._logger.error(err, \"notified handler threw\");\n }\n });\n } catch (err) {\n this._logger.error(err, \"Store.notify subscription failed\");\n return undefined;\n }\n }\n\n /**\n * Executes an action: validates the payload, loads the state, checks its\n * preconditions, runs the handler, folds the events it emits, checks the\n * state's invariants (its schema) on the result, and commits them with\n * optimistic concurrency on every stream it appends to. The reactions to those events\n * settle on their own (unless `autoSettle: false`).\n *\n * @template TKey - Action name from registered actions\n * @param action - The name of the action to execute\n * @param target - Target specification with stream ID and actor context\n * @param payload - Action payload matching the action's schema\n * @param options - Per-call dispatch options ({@link DoOptions}) —\n * `reactingTo` to thread correlation, `correlator` to override the\n * framework or orchestrator-level correlator for this call only.\n * @returns The snapshots of the action's own stream, one per event appended\n * to it; the loaded snapshot alone when the action commits nothing\n *\n * @throws {ValidationError} If the payload doesn't match the action schema,\n * or the state the action leaves breaks the state schema\n * @throws {PreconditionError} If business rules are violated\n * @throws {ConcurrencyError} If another process modified the stream\n *\n * @example Basic action execution\n * ```typescript\n * const snapshots = await app.do(\n * \"increment\",\n * {\n * stream: \"counter-1\",\n * actor: { id: \"user1\", name: \"Alice\" }\n * },\n * { by: 5 }\n * );\n *\n * console.log(snapshots[0].state.count); // Current count after increment\n * ```\n *\n * @see {@link Target} for target structure\n * @see {@link Snapshot} for return value structure\n * @see {@link ValidationError}, {@link PreconditionError}, {@link ConcurrencyError}\n */\n async do<TKey extends keyof TActions>(\n action: TKey,\n target: Target<TActor>,\n payload: Readonly<TActions[TKey]>,\n options?: DoOptions<TEvents>\n ) {\n // Resolve the ambient reaction context here so `internal/` never reads\n // ambient state. An explicit `reactingTo` wins.\n const reacting_to = options?.reactingTo ?? current_reacting();\n const do_options =\n reacting_to === options?.reactingTo\n ? options\n : { ...options, reactingTo: reacting_to };\n return this._scoped(async () => {\n const snapshots = await this._es.action(\n this.registry.actions[action],\n action,\n target,\n payload,\n do_options\n );\n // An action that emits nothing returns the loaded snapshot, which has\n // no `patch`: nothing committed, so nothing to wake or announce.\n // Snapshots of the streams its loads appended to follow its own.\n if (!snapshots[0].patch) return snapshots;\n // A local commit runs its reactions the way a remote one does.\n this._wake(snapshots.map((s) => s.event!.name as string));\n // `committed` fires once per stream appended to, its own first, so a\n // listener always gets one stream's snapshots, as without loads.\n const by_stream = new Map<string, typeof snapshots>();\n for (const s of snapshots) {\n const of_stream = by_stream.get(s.event!.stream);\n if (of_stream) of_stream.push(s);\n else by_stream.set(s.event!.stream, [s]);\n }\n for (const of_stream of by_stream.values()) {\n const owner = this._event_to_state.get(\n of_stream[0].event!.name as string\n )!;\n this.emit(\"committed\", of_stream);\n this._notify(`committed:${owner.name}`, of_stream);\n }\n return snapshots.filter((s) => s.event!.stream === target.stream);\n });\n }\n\n /**\n * Loads the current state snapshot for a specific stream.\n *\n * Reconstructs the current state by replaying events from the event store.\n * Uses snapshots when available to optimize loading performance.\n *\n * Accepts either a State definition object or a state name string. When\n * using a string, the merged state (from partial states registered via\n * `.withState()`) is resolved by name.\n *\n * @template TNewState - State schema type\n * @template TNewEvents - Event schemas type\n * @template TNewActions - Action schemas type\n * @param state - The state definition or state name to load\n * @param stream - The stream ID (state instance identifier)\n * @param callback - Optional callback invoked with the loaded snapshot\n * @returns The current state snapshot for the stream\n *\n * @example Load by state definition\n * ```typescript\n * const snapshot = await app.load(Counter, \"counter-1\");\n * console.log(snapshot.state.count); // Current count\n * console.log(snapshot.patches); // Events since last snapshot\n * ```\n *\n * @see {@link Snapshot} for snapshot structure\n */\n // Anonymous load (bare stream) — sensitive fields come back as REDACTED.\n async load<\n TNewState extends Schema,\n TNewEvents extends Schemas,\n TNewActions extends Schemas,\n >(\n state: State<TNewState, TNewEvents, TNewActions>,\n stream: string,\n callback?: (snapshot: Snapshot<TNewState, TNewEvents>) => void,\n asOf?: AsOf\n ): Promise<Snapshot<TNewState, TNewEvents>>;\n async load<TKey extends keyof TStateMap & string>(\n name: TKey,\n stream: string,\n callback?: (snapshot: Snapshot<TStateMap[TKey], TEvents>) => void,\n asOf?: AsOf\n ): Promise<Snapshot<TStateMap[TKey], TEvents>>;\n // Auth-aware load — runs `.discloses(predicate)` against the supplied actor.\n async load<\n TNewState extends Schema,\n TNewEvents extends Schemas,\n TNewActions extends Schemas,\n >(\n state: State<TNewState, TNewEvents, TNewActions>,\n target: LoadTarget<TActor>,\n callback?: (snapshot: Snapshot<TNewState, TNewEvents>) => void\n ): Promise<Snapshot<TNewState, TNewEvents>>;\n async load<TKey extends keyof TStateMap & string>(\n name: TKey,\n target: LoadTarget<TActor>,\n callback?: (snapshot: Snapshot<TStateMap[TKey], TEvents>) => void\n ): Promise<Snapshot<TStateMap[TKey], TEvents>>;\n async load<TNewState extends Schema>(\n stateOrName: State<TNewState, any, any> | string,\n streamOrTarget: string | LoadTarget<TActor>,\n callback?: (snapshot: Snapshot<any, any>) => void,\n asOf?: AsOf\n ): Promise<Snapshot<any, any>> {\n return this._scoped(async () => {\n let merged: State<any, any, any>;\n if (typeof stateOrName === \"string\") {\n const found = this._states.get(stateOrName);\n if (!found) throw new Error(`State \"${stateOrName}\" not found`);\n merged = found;\n } else {\n merged = this._states.get(stateOrName.name) || stateOrName;\n }\n // Normalize the two surfaces: bare-stream (default-deny — actor\n // undefined → REDACTED on the discloses check) vs LoadTarget\n // (auth-aware — actor flows into `.discloses(predicate)`).\n const target: LoadTarget<Actor> =\n typeof streamOrTarget === \"string\"\n ? {\n stream: streamOrTarget,\n actor: undefined as unknown as Actor,\n asOf,\n }\n : streamOrTarget;\n return await this._es.load(merged, target, callback);\n });\n }\n\n /**\n * Queries the event store for events matching a filter.\n *\n * Use this for analyzing event streams, generating reports, or debugging.\n * The callback is invoked for each matching event, and the method returns\n * summary information (first event, last event, total count).\n *\n * For small result sets, consider using {@link query_array} instead.\n *\n * @param query - Filter criteria; see {@link Query} for the fields\n * @param callback - Optional callback invoked for each matching event\n * @returns Object with first event, last event, and total count\n *\n * @example Query all events for a stream\n * ```typescript\n * const { first, last, count } = await app.query(\n * { stream: \"counter-1\" },\n * (event) => console.log(event.name, event.data)\n * );\n * console.log(`Found ${count} events from ${first?.id} to ${last?.id}`);\n * ```\n *\n * @see {@link query_array} for loading events into memory\n */\n async query(\n query: Query,\n callback?: (event: Committed<TEvents, keyof TEvents>) => void\n ): Promise<{\n first?: Committed<TEvents, keyof TEvents>;\n last?: Committed<TEvents, keyof TEvents>;\n count: number;\n }> {\n return this._scoped(async () => {\n let first: Committed<TEvents, keyof TEvents> | undefined;\n let last: Committed<TEvents, keyof TEvents> | undefined;\n const count = await store().query<TEvents>((e) => {\n const gated = this.registry.query_gate(e.name as string)(e);\n if (!first) first = gated;\n last = gated;\n callback?.(gated);\n }, query);\n return { first, last, count };\n });\n }\n\n /**\n * Queries the event store and returns all matching events in memory.\n *\n * **Use with caution** - this loads all results into memory. For large result sets,\n * use {@link query} with a callback instead to process events incrementally.\n *\n * @param query - The query filter (same as {@link query})\n * @returns Array of all matching events\n *\n * @example Load all events for a stream\n * ```typescript\n * const events = await app.query_array({ stream: \"counter-1\" });\n * console.log(`Loaded ${events.length} events`);\n * events.forEach(event => console.log(event.name, event.data));\n * ```\n *\n * @see {@link query} for large result sets\n */\n async query_array(\n query: Query\n ): Promise<Committed<TEvents, keyof TEvents>[]> {\n return this._scoped(async () => {\n const events: Committed<TEvents, keyof TEvents>[] = [];\n await store().query<TEvents>((e) => {\n events.push(this.registry.query_gate(e.name as string)(e));\n }, query);\n return events;\n });\n }\n\n /**\n * Wipe the sensitive-data payload for every event on the stream — see\n * {@link IAct.forget}.\n *\n * Throws on adapters without `Store.forget_pii`, invalidates the cache\n * entry for the stream, emits the `forgotten` lifecycle event with the\n * row count. Idempotent: a second call returns `{eventCount: 0}` and\n * does NOT re-emit.\n *\n * @param stream - Target stream.\n * @returns `{eventCount}` — number of events whose PII column was wiped.\n */\n async forget(stream: string): Promise<{ eventCount: number }> {\n return this._scoped(async () => {\n const s = store();\n if (!s.forget_pii) {\n throw new Error(\n `Store does not implement forget_pii — adapter cannot comply with sensitive-data erasure. ` +\n `Use an adapter that declares pii_isolation: true (e.g. @rotorsoft/act on the in-memory store).`\n );\n }\n const eventCount = await s.forget_pii(stream);\n await cache().invalidate(stream);\n if (eventCount > 0) {\n this.emit(\"forgotten\", { stream, at: new Date(), eventCount });\n }\n return { eventCount };\n });\n }\n\n /**\n * Runs one drain cycle: claims streams with marked work (leasing them),\n * fetches their events, runs the matching reactions, and acks or blocks\n * each stream.\n *\n * A stream is claimable only once `correlate()` has marked it, static\n * targets included, so a commit no correlate has seen is not drainable.\n * Apps rarely call this: each commit settles its reactions on its own.\n * With `autoSettle: false`, tests walk the pipeline with `correlate()`\n * then `drain()` (see the testing guide).\n *\n * @param options - Drain configuration — see {@link DrainOptions} for fields\n * (`streamLimit`, `eventLimit`, `leaseMillis`).\n * @returns Drain statistics with fetched, leased, acked, and blocked counts\n *\n * @example Walking the pipeline in a test\n * ```typescript\n * const app = act().withState(User).withProjection(Users).build({ autoSettle: false });\n * await app.do(\"createUser\", target, payload);\n * await app.correlate();\n * await app.drain();\n * ```\n *\n * @see {@link settle} for debounced correlate→drain with lifecycle events\n * @see {@link correlate} for dynamic stream discovery\n */\n async drain(options: DrainOptions = {}): Promise<Drain<TEvents>> {\n // Validate the runtime knobs before anything runs (a bad leaseMillis /\n // streamLimit / eventLimit throws ZodError here, not on the first cycle).\n resolveDrainConfig(options);\n // Writer-only instances run no reactions.\n if (!this._drain)\n return { fetched: [], leased: [], acked: [], blocked: [] };\n return this._scoped(() => this._drain_all(options));\n }\n\n // Arms correlate and every lane; false on an app with no reactions.\n private _arm_all(): boolean {\n if (!this._reactive) return false;\n // A commit may also give the next correlate scan something to find.\n this._correlate.arm();\n for (const c of this._drain_controllers.values()) c.arm();\n return true;\n }\n\n // Wakes what a change freed (a commit, a reset, an unblock, a restore,\n // a notification from another process): arms the lanes these events\n // react on, or every lane without names, and settles them unless the app\n // walks the pipeline itself (`autoSettle: false`).\n private _wake(names?: Iterable<string>): void {\n const armed = names ? this._arm_for_event_names(names) : this._arm_all();\n if (armed && this._auto_settle) this._schedule();\n }\n\n // Schedules a settle pass; writer-only instances (`drain: false`) skip it.\n private _schedule(options?: SettleOptions): void {\n if (this._drain) this._settle.schedule(options);\n }\n\n // Arms only the lanes these events react on; true when any was armed.\n private _arm_for_event_names(names: Iterable<string>): boolean {\n const to_arm = new Set<string>();\n for (const name of names) {\n const set = this._event_to_lanes.get(name);\n if (set === undefined) continue;\n if (set === ALL_LANES) {\n this._arm_all();\n return true;\n }\n for (const lane of set) to_arm.add(lane);\n }\n if (to_arm.size === 0) return false;\n this._correlate.arm();\n for (const lane of to_arm) this._drain_controllers.get(lane)?.arm();\n return true;\n }\n\n // In parallel, so a slow lane never holds up a fast one.\n private async _drain_all(options: DrainOptions): Promise<Drain<TEvents>> {\n const merged = merge_drains(\n await Promise.all(\n [...this._drain_controllers.values()].map((c) => c.drain(options))\n )\n );\n // Actor-less like `query`/`query_array`, so default-deny.\n // Handlers are unaffected — they read through their own strip.\n return {\n ...merged,\n fetched: merged.fetched.map((f) => ({\n ...f,\n events: f.events.map((e) =>\n this.registry.query_gate(e.name as string)(e)\n ),\n })),\n };\n }\n\n /**\n * Scans committed events from the correlation checkpoint, subscribes the\n * target streams their reactions resolve to (static or computed from\n * the event), and marks their work so the next drain can claim it.\n *\n * @param query - Only `limit` is used: the most events the pass reads\n * (10 when the query has none; `0` reads everything). The scan always\n * starts at the correlation checkpoint, which every reaction shares, so\n * filters and `after` are ignored.\n * @returns The number of newly subscribed streams and the last scanned event id\n *\n * @example Manual correlation\n * ```typescript\n * const { subscribed } = await app.correlate({ limit: 100 });\n * ```\n *\n * @see {@link start_correlations} for automatic periodic correlation\n */\n async correlate(\n query: Query = {}\n ): Promise<{ subscribed: number; last_id: number }> {\n const pass = await this._correlate_pass(query.limit ?? 10);\n return {\n subscribed: pass.kind === \"scanned\" ? pass.subscribed : 0,\n last_id: pass.last_id,\n };\n }\n\n // One correlate pass; arms every lane when it found work.\n private async _correlate_pass(\n limit: number,\n /** Honour the correlation lease — settle and the poller only. */\n lease = false\n ): Promise<CorrelatePass> {\n // Writer-only instances don't correlate.\n if (!this._drain) return { kind: \"idle\", last_id: -1 };\n return this._scoped(async () => {\n const pass = await this._correlate.correlate(limit, lease);\n // Only a mark makes a stream claimable. Also re-arms correlate, so a\n // backlog scan keeps going.\n if (pass.kind === \"scanned\" && pass.marked > 0) this._arm_all();\n return pass;\n });\n }\n\n /**\n * Starts a background poll that settles on a timer: each tick looks for\n * new events, subscribes the streams their reactions target, and drains\n * them, along with any stream whose lease a dead worker let expire.\n *\n * Use it when this process can miss commits — another process writes to a\n * store without `notify`, or a notification is lost. It is the safety net\n * under `notify`: a missed wakeup costs at most one `frequency` of latency.\n *\n * Only one poll runs per Act instance. On a writer-only instance\n * (`drain: false`) each tick is a no-op, like `settle()`.\n *\n * @param query - Only `limit` is used: the most events each correlate pass\n * reads. With no limit, or `0`, the passes use the background default\n * (100): a poll never reads the whole log in one tick. The scan always\n * starts at the correlation checkpoint, so `after` is ignored.\n * @param frequency - Milliseconds between ticks (default: 10000)\n * @returns `true` if the poll started, `false` if one is already running\n *\n * @example\n * ```typescript\n * app.start_correlations({ limit: 100 }, 5000);\n * // later\n * app.stop_correlations();\n * ```\n *\n * @see {@link settle} for what each tick runs\n * @see {@link stop_correlations} to stop the poll\n */\n start_correlations(query: Query = {}, frequency = 10_000): boolean {\n if (this._poll) return false;\n this._poll_limit = query.limit || undefined;\n this._poll = setInterval(() => {\n // No local signal says there is work, so look anyway: correlate for\n // new events, and every lane for leases that came free (a dead\n // worker's expired lease is claimable, but no commit will say so).\n this._arm_all();\n this._schedule();\n }, frequency);\n return true;\n }\n\n /**\n * Stops the poll started by {@link start_correlations}. Idempotent, and\n * called by `shutdown()`.\n *\n * @see {@link start_correlations}\n */\n stop_correlations() {\n if (this._poll) {\n clearInterval(this._poll);\n this._poll = undefined;\n this._poll_limit = undefined;\n }\n // Hand the correlation lease back, best-effort and not awaited (this\n // method is synchronous; the lease would expire anyway).\n void this._scoped(() => this._correlate.release_correlation());\n }\n\n /**\n * Drops the settle pass scheduled but not yet started. A cycle already\n * running finishes; later changes schedule new passes.\n *\n * @see {@link settle}\n */\n stop_settling() {\n this._settle.stop();\n }\n\n /**\n * Reset reaction stream watermarks and settle them, replaying their\n * events through their reactions.\n *\n * Use this to replay events through projections (or other reaction targets)\n * after changing handler logic. It rewinds the same watermarks as\n * `store().reset(streams)`, and also wakes the drain and schedules a\n * settle, which loops correlate→drain until the replay catches up;\n * `store().reset(...)` alone leaves a settled app idle. Call\n * `app.settle(options)` right after to give that pass batch options, or,\n * with `autoSettle: false`, `correlate()` / `drain()` to drive the replay\n * by hand.\n *\n * @param input - Reaction target streams (e.g., projection names) to reset, or a {@link StreamFilter} for bulk operations\n * @returns Count of streams that were actually reset\n *\n * @example Rebuild a projection (production)\n * ```typescript\n * await app.reset([\"my-projection\"]);\n * app.settle({ eventLimit: 1000 }); // optional: bigger batches; emits \"settled\"\n * ```\n *\n * @see {@link Store.reset} for the underlying store primitive\n * @see {@link settle} for the debounced full-catch-up loop\n */\n async reset(input: string[] | StreamFilter): Promise<number> {\n return this._scoped(async () => {\n const count = await store().reset(input);\n // Drop every fold cache before the replay, or a warm cache would\n // re-flush stale rows. Cleared for all targets: resolving `input`\n // costs a query, and an extra clear costs one head load per stream.\n for (const handler of this._batch_handlers.values())\n (handler as ResettableBatchHandler<TEvents>)[FOLD_RESET]?.();\n if (count > 0) {\n this._wake();\n }\n return count;\n });\n }\n\n /**\n * Clear the blocked flag on streams without replaying their history.\n *\n * Use this to recover from a poison message after fixing the\n * underlying issue — the stream resumes from the next event after the\n * last successful ack, not from the beginning. Compare with\n * {@link reset}, which rebuilds from event 0 (suitable for projection\n * rebuilds, wrong for \"I fixed the bug, please retry\").\n *\n * Wraps `store().unblock(streams)` and settles the now-free streams on\n * its own. `store().unblock(...)` alone leaves them waiting for the next\n * commit.\n *\n * @param input - Stream names to unblock, or a {@link StreamFilter} for bulk recovery\n * @returns Count of streams that were actually flipped (were blocked)\n *\n * @example Recover from a 4xx webhook after fixing the bug\n * ```typescript\n * await app.unblock([\"webhooks-out-customer-42\"]);\n * // The stream resumes from the next event, not from zero.\n * ```\n *\n * @see {@link Store.unblock} for the underlying store primitive\n * @see {@link reset} for the rebuild-from-zero alternative\n */\n async unblock(input: string[] | StreamFilter): Promise<number> {\n return this._scoped(async () => {\n const count = await store().unblock(input);\n if (count > 0) {\n this._wake();\n }\n return count;\n });\n }\n\n /**\n * Atomically wipe the store and rebuild it from an event source. The\n * framework owns iteration, validation, `drop_snapshots` filtering,\n * `on_progress`, and the per-call `old → new` causation remap; the\n * adapter's {@link Store.restore} driver supplies the transaction\n * lifecycle and per-event insert.\n *\n * Safe in a live process: restoring into this Act's own store waits\n * for its correlate passes in flight, replaces the log, then restarts\n * correlation and settles. A correlate pass that starts meanwhile\n * reads nothing. Other processes on the same store keep their\n * correlation state and must be restarted.\n *\n * Throws if the adapter has no restore capability. Throws on the\n * first invalid event (negative version, malformed `created`) with\n * the running index in the message; atomic transaction rollback in\n * the adapter means a failing restore leaves the store byte-for-byte\n * unchanged.\n *\n * @param source - Any {@link EventSource}: a `CsvFile` backup or\n * another store. Read in batches rather than buffered, so\n * multi-million-event backups don't OOM. Each event's original `id`\n * is used as a causation lookup key but never written through —\n * adapters renumber densely.\n * @param opts - {@link ScanOptions}. `drop_snapshots` skips\n * `__snapshot__` events (counted in the result); `on_progress`\n * fires once per event.\n * @param sink - Where the events land. Defaults to this Act's store.\n * @returns The {@link ScanResult}: what was kept, migrated and dropped,\n * and how long it took.\n *\n * @example Restore a CSV backup into the connected store\n * ```typescript\n * const result = await app.restore(new CsvFile({ path: \"./backup.csv\" }));\n * console.log(`Restored ${result.kept} events in ${result.duration_ms}ms`);\n * await cache().clear(); // operator's responsibility\n * ```\n *\n * @see {@link Store.restore} for the underlying driver-pattern primitive.\n */\n async restore(\n source: EventSource,\n opts: ScanOptions = {},\n sink?: EventSink\n ): Promise<ScanResult> {\n return this._scoped(async () => {\n const started = Date.now();\n // Dry-run: count what a restore would land, touching no sink.\n if (opts.dry_run) {\n const partial = await scan(source, opts);\n return { ...partial, duration_ms: Date.now() - started };\n }\n // Default sink is this Act's store.\n const target: EventSink =\n sink ??\n (() => {\n const s = store();\n if (!s.restore) throw new Error(\"adapter has no restore capability\");\n return s as EventSink;\n })();\n let kept = 0;\n let migrated = 0;\n let dropped = { closed_streams: 0, snapshots: 0 };\n const run = () =>\n target.restore(async (callback) => {\n const partial = await scan(source, opts, callback);\n kept = partial.kept;\n migrated = partial.migrated;\n dropped = partial.dropped;\n });\n if (sink) await run();\n else {\n // Restoring into this app's own store replaces its log (new ids, no\n // subscription rows): restart correlation from cold and arm the drain.\n await this._correlate.restart(run);\n this._wake();\n }\n return { kept, migrated, dropped, duration_ms: Date.now() - started };\n });\n }\n\n /**\n * Return every currently-blocked stream position. Convenience wrapper\n * around `store().query_streams(cb, { blocked: true })` for the common\n * \"show me what's broken\" operational query.\n *\n * Results are ordered by stream name, paginated by `limit` (default\n * 100). Pass `after` to fetch the next page (keyset cursor on the\n * stream name). For richer queries — including blocked + source\n * filters, or full unblocked introspection — drop to\n * `store().query_streams(...)` directly.\n *\n * @returns Array of {@link StreamPosition} for currently-blocked streams.\n *\n * @example Discover and recover\n * ```typescript\n * const blocked = await app.blocked_streams();\n * console.table(blocked.map(({ stream, retry, error }) => ({ stream, retry, error })));\n *\n * // Operator investigates, then bulk-unblocks the family:\n * await app.unblock({ stream: \"^webhooks-out-\" });\n * ```\n */\n async blocked_streams(options?: {\n after?: string;\n limit?: number;\n }): Promise<StreamPosition[]> {\n return this._scoped(async () => {\n const positions: StreamPosition[] = [];\n await store().query_streams(\n (p) => {\n positions.push(p);\n },\n { blocked: true, after: options?.after, limit: options?.limit }\n );\n return positions;\n });\n }\n\n /**\n * Operator-driven store audit: walks the store and yields findings per\n * category, each with the remediation it suggests. Never run by the\n * framework. Pass a subset of categories to scope the work; the iterable\n * can be broken early, and findings stream without buffering the report.\n *\n * @param categories - Subset of categories to run (default: all).\n * @param options - Query window + per-category thresholds.\n * @returns Async iterable of {@link AuditFinding}.\n *\n * @example Schema drift since the last scan\n * ```typescript\n * for await (const f of app.audit([\"schema\"], { query: { created_after: lastScan } }))\n * await escalate(f);\n * ```\n */\n async *audit(\n categories?: AuditCategory[],\n options?: AuditOptions\n ): AsyncIterable<AuditFinding> {\n // Step the generator inside `_scoped`: its body runs lazily in the\n // consumer's frame, which would otherwise resolve the wrong store.\n const it = audit(this._audit_deps, categories, options)[\n Symbol.asyncIterator\n ]();\n while (true) {\n const { value, done } = await this._scoped(() => it.next());\n if (done) break;\n yield value;\n }\n }\n\n /**\n * Sets the scheduling priority of every stream matching `filter`, as-is:\n * unlike build-time priorities (the highest across reactions wins), this\n * overrides them. Useful to let a long replay jump ahead of other lagging\n * streams, or to yield slots back. **An empty filter (`{}`) updates every\n * registered stream.**\n *\n * @param filter - Selection criteria (regex by default, like {@link query}).\n * @param priority - New priority value, a 32-bit integer. Set as-is — no clamp.\n * @returns Count of streams whose priority changed.\n * @throws ZodError when `priority` isn't a 32-bit integer.\n *\n * @example Boost a specific projection mid-replay\n * ```typescript\n * await app.prioritize({ stream: \"^proj-orders$\", stream_exact: false }, 10);\n * ```\n *\n * @see {@link Store.prioritize} for the underlying primitive\n */\n async prioritize(filter: StreamFilter, priority: number): Promise<number> {\n resolveTargetConfig({ priority });\n return this._scoped(() => store().prioritize(filter, priority));\n }\n\n // Shared by `close()` and reaction-requested closes.\n private async _run_close(targets: CloseTarget[]): Promise<CloseResult> {\n const close_actor = { id: \"$close\", name: \"close\" };\n const result = await run_close_cycle(targets, {\n reactive: this._reactive,\n catch_up_correlation: (until) =>\n catch_up_correlation(\n this._correlate,\n (limit) => this.correlate({ limit }),\n until\n ),\n event_to_state: this._event_to_state,\n load: this._es.load,\n tombstone: this._es.tombstone,\n logger: this._logger,\n correlation: close_correlation(this._correlator, close_actor),\n with_stream_lock: (stream, work) => this._close_lock.run(stream, work),\n forget_subscribed: (streams) =>\n this._correlate.forget_subscribed(streams),\n });\n this.emit(\"closed\", result);\n return result;\n }\n\n /**\n * Close the books: guard, archive, truncate, and optionally restart\n * streams. A stream with pending reactions is skipped; an archive\n * failure aborts the whole close while the streams are still guarded.\n * Targets carrying `before` prune a rolling window instead and leave the\n * stream live (needs `.snap(...)`). The phases and their failure\n * semantics are in the close-cycle architecture page.\n *\n * @param targets - Per-stream close options (stream, restart?, archive?, before?)\n * @returns `{ truncated: TruncateResult, skipped: string[] }`\n *\n * @example Archive and close\n * ```typescript\n * await app.close([\n * { stream: \"order-123\", archive: async () => { await archiveToS3(\"order-123\"); } },\n * { stream: \"order-456\" },\n * ]);\n * ```\n */\n async close(targets: CloseTarget[]): Promise<CloseResult> {\n if (!targets.length) return { truncated: new Map(), skipped: [] };\n\n return this._scoped(() => this._run_close(targets));\n }\n\n /**\n * Debounced, non-blocking correlate→drain cycle.\n *\n * A local change that frees reaction work (a commit, `reset()`,\n * `unblock()`, `restore()`) schedules this on its own unless the app\n * sets `autoSettle: false`. Call it at startup, to run what was pending\n * before a restart, or with options for the next pass; the scheduling\n * rule is in the event-sourcing docs (§ settle). Runs correlate→drain\n * passes until one makes no progress (see {@link SettleOptions.maxPasses}),\n * then emits the `\"settled\"` lifecycle event, so one call fully catches\n * up paginated streams without forcing callers to loop.\n *\n * @param options - Settle configuration — see {@link SettleOptions} for fields:\n * `debounceMs` (default 10), `correlate.limit` (default 100, or the\n * poll's limit while `start_correlations` runs; `after` is always the\n * checkpoint),\n * `maxPasses` (default `Infinity`; caps this settle's passes, not the\n * passes a reaction chain's own commits schedule),\n * `streamLimit` (default 10), `eventLimit` (default 10),\n * `leaseMillis` (default 10000).\n *\n * @example Startup\n * ```typescript\n * app.settle(); // run what was pending before the restart\n *\n * app.on(\"settled\", (drain) => {\n * // notify SSE clients, invalidate caches, etc.\n * });\n * ```\n *\n * @see {@link drain} for single synchronous drain cycles\n * @see {@link correlate} for manual correlation\n */\n settle(options?: SettleOptions): void {\n // Validate the runtime knobs before anything runs (a bad debounceMs /\n // leaseMillis / maxPasses throws ZodError here, not on the first pass).\n resolveSettleConfig(options ?? {});\n this._schedule(options);\n }\n}\n","/**\n * Auto-deprecation of legacy event versions via the `_v<digits>` naming\n * convention.\n *\n * Act's schema-evolution pattern keeps the old and new event names alive\n * forever — the old name on the read path (reducers), the new on the write\n * path (emissions). This module reads the convention to identify legacy\n * versions automatically; the framework then enforces \"emit only the\n * current version\" at build time and warns at runtime for dynamic emits.\n *\n * Convention pin: only `_v<digits>` with digits ≥ 2 counts as a version\n * suffix. `Foo_v1` is just a literal event name (the base `Foo` is\n * implicitly v1). Pinning here keeps the contract surface small.\n */\n\nconst VERSION_SUFFIX = /^(.+?)_v(\\d+)$/;\n\ntype Versioned = { version: number; name: string };\n\n/**\n * Splits an event name into (base, version). Names without a `_v<n≥2>`\n * suffix are returned as (name, 1) — the base is its own implicit v1.\n */\nfunction parse(name: string): { base: string; version: number } {\n const m = name.match(VERSION_SUFFIX);\n if (m) {\n const v = Number.parseInt(m[2], 10);\n if (v >= 2) return { base: m[1], version: v };\n }\n return { base: name, version: 1 };\n}\n\n/**\n * Returns the set of event names that are deprecated by virtue of having\n * a higher-numbered sibling in the registry. The highest version in each\n * group is the current version; every lower version is deprecated.\n *\n * Gaps are allowed: `{Foo, Foo_v3}` → `Foo` is deprecated, `Foo_v3` is\n * current. The framework picks the max regardless of contiguity.\n *\n * Single-version groups (no siblings) yield no deprecations.\n */\nexport function deprecated_event_names(names: Iterable<string>): Set<string> {\n const groups = new Map<string, Versioned[]>();\n for (const name of names) {\n const { base, version } = parse(name);\n const list = groups.get(base);\n if (list) list.push({ version, name });\n else groups.set(base, [{ version, name }]);\n }\n const deprecated = new Set<string>();\n for (const list of groups.values()) {\n if (list.length < 2) continue;\n // Two names mapping to the same numeric version (e.g. a leading-zero\n // `Foo_v02` alongside `Foo_v2`) can't both be a distinct version — one\n // is a typo. Left unguarded, the sort below would flag whichever lands\n // second, so declaration order would decide which one is \"current\",\n // and the real current event could be marked deprecated (a static\n // `.emit(...)` on it would then throw at build). Reject the collision\n // with a clear, order-independent error instead.\n const by_version = new Map<number, string>();\n for (const { version, name } of list) {\n const clash = by_version.get(version);\n if (clash)\n throw new Error(\n `duplicate event version: ${clash} and ${name} both map to version ${version} — ` +\n \"leading zeros in a `_v<n>` suffix are not allowed; use a single canonical spelling\"\n );\n by_version.set(version, name);\n }\n list.sort((a, b) => b.version - a.version); // descending\n // index 0 is current; the rest are deprecated\n for (let i = 1; i < list.length; i++) deprecated.add(list[i].name);\n }\n return deprecated;\n}\n\n/**\n * Given a deprecated event name and the full set of event names in its\n * registry, returns the current (highest-version) sibling. Used to build\n * actionable error messages — \"use `Foo_v3` instead.\"\n *\n * Returns `undefined` if the event has no higher-versioned sibling (which\n * means the caller's classification is stale or wrong).\n */\nexport function current_version_of(\n deprecated_name: string,\n all_names: Iterable<string>\n): string | undefined {\n const target = parse(deprecated_name);\n let highest: Versioned | undefined;\n for (const name of all_names) {\n const { base, version } = parse(name);\n if (base !== target.base) continue;\n if (!highest || version > highest.version) highest = { version, name };\n }\n return highest && highest.version > target.version ? highest.name : undefined;\n}\n","import type { QueryStreams, Store, StreamPosition } from \"../types/index.js\";\n\n/** Streams read per page when walking the whole table. */\nconst DEFAULT_STREAM_PAGE = 500;\n\n/**\n * Walks EVERY stream matching `query`, paging with the keyset cursor.\n *\n * `Store.query_streams` defaults to `limit: 100`, so a caller that wants\n * the whole table must page — passing no query silently truncates at the\n * first page, which is a false all-clear for anything that reports on\n * what it found.\n *\n * The cursor is the last stream name the callback saw; results are\n * ordered by stream name, so a short page means the walk is done.\n *\n * @param store - Store to walk.\n * @param callback - Invoked once per matching position, in name order.\n * @param query - Optional filter. A caller-supplied `limit` sets the page\n * size (the walk still visits every match); `after` seeds the cursor.\n * @returns The total number of positions emitted.\n */\nexport async function walk_streams(\n store: Store,\n callback: (position: StreamPosition) => void,\n query?: Omit<QueryStreams, \"after\" | \"limit\"> & {\n after?: string;\n limit?: number;\n }\n): Promise<number> {\n const page_size = query?.limit ?? DEFAULT_STREAM_PAGE;\n let after = query?.after;\n let total = 0;\n for (;;) {\n let last: string | undefined;\n const { count } = await store.query_streams(\n (position) => {\n last = position.stream;\n callback(position);\n },\n { ...query, after, limit: page_size }\n );\n total += count;\n if (count < page_size) return total;\n after = last;\n }\n}\n","/**\n * Operator-driven store audit. Each category is an {@link AuditPass}; the\n * dispatcher runs each needed scan once and broadcasts rows to every pass,\n * so an audit costs at most three scans. Reads only {@link AuditDeps} and\n * the public `Store`, never orchestration internals.\n */\n\nimport { sensitiveFields } from \"../sensitive.js\";\nimport type {\n AuditCategory,\n AuditFinding,\n AuditOptions,\n Committed,\n Query,\n Schemas,\n State,\n Store,\n StreamPosition,\n StreamStats,\n} from \"../types/index.js\";\nimport { SNAP_EVENT, TOMBSTONE_EVENT } from \"../types/index.js\";\nimport {\n current_version_of,\n deprecated_event_names,\n} from \"./event-versions.js\";\nimport { walk_streams } from \"./walk-streams.js\";\n\n/** The orchestrator state the audit reads, built once at `build()`. */\nexport type AuditDeps = {\n readonly store: () => Store;\n /** event-name → state that registers it (for schema validation). */\n readonly event_to_state: ReadonlyMap<string, State<any, any, any>>;\n /** Declared drain lanes (for routing-health unknown-lane). */\n readonly declared_lanes: ReadonlySet<string>;\n /** Event names with at least one reaction (routing-health `unrouted`). */\n readonly routed_events: ReadonlySet<string>;\n};\n\n/** Defaults for {@link AuditOptions.thresholds}. */\nconst DEFAULTS = {\n idle_days: 90,\n restart_min: 10_000,\n stuck_minutes: 30,\n deprecated_min: 0.1,\n drift_min: 500,\n near_block: 3,\n};\n\nconst ALL_CATEGORIES = [\n \"schema\",\n \"close-candidate\",\n \"restart-candidate\",\n \"deprecated-load\",\n \"reaction-health\",\n \"snapshot-drift\",\n \"routing-health\",\n \"correlation-gaps\",\n \"clock-anomalies\",\n \"unreadable-events\",\n] as const satisfies readonly AuditCategory[];\n\n/**\n * One audit category. Which `on_*` callbacks it has decides which shared\n * scans run; `finalize` does targeted follow-up reads; `drain` returns\n * the findings.\n */\ntype AuditPass = {\n category: AuditCategory;\n on_event?: (e: Committed<Schemas, string>) => void;\n on_unreadable?: (row: UnreadableRow) => void;\n on_stream?: (p: StreamPosition) => void;\n on_stat?: (stream: string, s: StreamStats<Schemas>) => void;\n finalize?: (deps: AuditDeps) => Promise<void>;\n drain: () => AuditFinding[];\n};\n\ntype PassFactory = (deps: AuditDeps, options: AuditOptions) => AuditPass;\n\n/** Scans finish before the first yield; bound the work with `options.query`. */\nexport async function* audit(\n deps: AuditDeps,\n categories?: AuditCategory[],\n options: AuditOptions = {}\n): AsyncIterable<AuditFinding> {\n const requested = new Set<AuditCategory>(categories ?? [...ALL_CATEGORIES]);\n // Declaration order, not the caller's.\n const ordered_categories = ALL_CATEGORIES.filter((c) => requested.has(c));\n const passes: AuditPass[] = ordered_categories.map((c) =>\n PASS_FACTORIES[c](deps, options)\n );\n\n const need_stats = passes.some((p) => p.on_stat !== undefined);\n const need_streams = passes.some((p) => p.on_stream !== undefined);\n const need_events = passes.some(\n (p) => p.on_event !== undefined || p.on_unreadable !== undefined\n );\n\n if (need_stats) {\n // Exclude `__snapshot__` so head and count are domain figures; keep\n // `__tombstone__`, which is how a closed stream is recognized.\n const stats = await deps\n .store()\n .query_stats<Schemas>(\n {},\n { count: true, names: true, exclude: [SNAP_EVENT] }\n );\n for (const [stream, s] of stats) {\n for (const p of passes) p.on_stat?.(stream, s);\n }\n }\n\n if (need_streams) {\n // Paged: `query_streams` defaults to 100 rows.\n await walk_streams(deps.store(), (pos) => {\n for (const p of passes) p.on_stream?.(pos);\n });\n }\n\n if (need_events) {\n await scan_events_resiliently(\n deps,\n options.query,\n (event) => {\n for (const p of passes) p.on_event?.(event);\n },\n (row) => {\n for (const p of passes) p.on_unreadable?.(row);\n }\n );\n }\n\n // Serial to avoid pool contention.\n for (const p of passes) await p.finalize?.(deps);\n\n for (const p of passes) {\n for (const f of p.drain()) yield f;\n }\n}\n\n/**\n * A row the store couldn't hand back, located by re-reading it without its\n * payload (`with_pii: false`), which can't fail.\n */\ntype UnreadableRow = {\n stream: string;\n event_id: number;\n error: unknown;\n};\n\n/**\n * Run the event scan so one unreadable row doesn't end it: locate the row\n * it stopped at, report it, and resume past it with the remaining `limit`.\n * Backward scans can't resume, so they rethrow.\n */\nasync function scan_events_resiliently(\n deps: AuditDeps,\n query: Query | undefined,\n on_event: (e: Committed<Schemas, string>) => void,\n on_unreadable: (row: UnreadableRow) => void\n): Promise<void> {\n let cursor = query?.after;\n let remaining = query?.limit;\n for (;;) {\n let seen = 0;\n try {\n await deps.store().query<Schemas>(\n (event) => {\n seen++;\n cursor = event.id;\n on_event(event);\n },\n {\n ...query,\n after: cursor,\n ...(remaining !== undefined && { limit: remaining }),\n }\n );\n return;\n } catch (error) {\n if (query?.backward) throw error;\n let row: UnreadableRow | undefined;\n await deps.store().query<Schemas>(\n (e) => {\n row = { stream: e.stream, event_id: e.id, error };\n },\n { ...query, after: cursor, limit: 1, with_pii: false }\n );\n // Not one unreadable row (a dropped connection, a timeout): rethrow.\n if (!row) throw error;\n on_unreadable(row);\n // The tripping row is never delivered, so `seen` is at most\n // `remaining - 1` and the resumed budget stays at 1 or more.\n if (remaining !== undefined) remaining -= seen;\n cursor = row.event_id;\n }\n }\n}\n\n// =================== Pass factories ===================\n\nconst make_schema_pass: PassFactory = (deps) => {\n const findings: AuditFinding[] = [];\n return {\n category: \"schema\",\n on_event(event) {\n const name = String(event.name);\n const state = deps.event_to_state.get(name);\n if (!state) {\n if (name.startsWith(\"__\")) return;\n findings.push({\n category: \"schema\",\n stream: event.stream,\n event_id: event.id,\n name,\n reason: \"unknown_event_name\",\n });\n return;\n }\n const schema = state.events[name];\n // `sensitive()` keys live in the pii sidecar, so omit them from the parse.\n const sensitive = sensitiveFields(schema);\n let parse_schema = schema;\n if (sensitive.length > 0) {\n const omitter = (\n schema as unknown as {\n omit?: (mask: Record<string, true>) => typeof schema;\n }\n ).omit;\n if (typeof omitter !== \"function\") {\n // A non-object schema with pii can't be masked; any parse is a false positive.\n return;\n }\n parse_schema = omitter.call(\n schema,\n Object.fromEntries(sensitive.map((f) => [f, true as const]))\n );\n }\n const parsed = parse_schema.safeParse(event.data);\n if (!parsed.success) {\n findings.push({\n category: \"schema\",\n stream: event.stream,\n event_id: event.id,\n name,\n reason: \"schema_validation_failed\",\n zod_error: parsed.error,\n });\n }\n },\n drain: () => findings,\n };\n};\n\n/** Deprecated event name → its current sibling, within one state only. */\nconst classify_deprecated_by_state = (\n deps: AuditDeps\n): ReadonlyMap<string, string> => {\n const names_by_state = new Map<State<any, any, any>, Set<string>>();\n for (const [name, state] of deps.event_to_state) {\n let set = names_by_state.get(state);\n if (!set) {\n set = new Set();\n names_by_state.set(state, set);\n }\n set.add(name);\n }\n const deprecated_to_current = new Map<string, string>();\n for (const names of names_by_state.values()) {\n for (const name of deprecated_event_names(names)) {\n deprecated_to_current.set(name, current_version_of(name, names)!);\n }\n }\n return deprecated_to_current;\n};\n\nconst make_deprecated_load_pass: PassFactory = (deps, options) => {\n const share_min =\n options.thresholds?.deprecated_min ?? DEFAULTS.deprecated_min;\n const totals = new Map<string, number>();\n const per_stream = new Map<string, Map<string, number>>();\n return {\n category: \"deprecated-load\",\n on_stat(stream, { names }) {\n for (const [name, count] of Object.entries(names!)) {\n totals.set(name, (totals.get(name) ?? 0) + count!);\n let m = per_stream.get(name);\n if (!m) {\n m = new Map();\n per_stream.set(name, m);\n }\n m.set(stream, count!);\n }\n },\n drain() {\n const findings: AuditFinding[] = [];\n const grand = [...totals.values()].reduce((s, n) => s + n, 0);\n if (grand === 0) return findings;\n const deprecated = classify_deprecated_by_state(deps);\n const sorted = [...deprecated.keys()]\n .map((name) => ({ name, count: totals.get(name) ?? 0 }))\n .sort((a, b) => b.count - a.count);\n for (const { name, count } of sorted) {\n if (count === 0) continue;\n if (count / grand < share_min) continue;\n const current_version = deprecated.get(name)!;\n const top_streams = [...per_stream.get(name)!.entries()]\n .map(([stream, c]) => ({ stream, count: c }))\n .sort((a, b) => b.count - a.count)\n .slice(0, 10);\n findings.push({\n category: \"deprecated-load\",\n name,\n current_version,\n total: count,\n top_streams,\n });\n }\n return findings;\n },\n };\n};\n\nconst make_close_candidate_pass: PassFactory = (deps, options) => {\n const idle_days = options.thresholds?.idle_days ?? DEFAULTS.idle_days;\n const terminal_events = new Set(options.thresholds?.terminal_events ?? []);\n const idle_cutoff = Date.now() - idle_days * 24 * 60 * 60 * 1000;\n const findings: AuditFinding[] = [];\n return {\n category: \"close-candidate\",\n on_stat(stream, { head }) {\n const head_name = String(head.name);\n if (head_name.startsWith(\"__\")) return; // already-closed or mid-truncate\n const head_time = head.created.getTime();\n const is_idle = head_time < idle_cutoff;\n const is_terminal = terminal_events.has(head_name);\n if (!is_idle && !is_terminal) return;\n findings.push({\n category: \"close-candidate\",\n stream,\n last_event_at: head.created.toISOString(),\n reason: is_terminal ? \"terminal\" : \"idle\",\n idle_days: is_idle\n ? Math.floor((Date.now() - head_time) / (24 * 60 * 60 * 1000))\n : undefined,\n restart_supported: restart_is_supported(deps, head_name),\n });\n },\n drain: () => findings,\n };\n};\n\nconst make_restart_candidate_pass: PassFactory = (deps, options) => {\n const threshold = options.thresholds?.restart_min ?? DEFAULTS.restart_min;\n // Snapshot counts are resolved in finalize: the shared stat scan excludes\n // `__snapshot__`, and only a handful of candidates need them.\n const candidates: Array<{ stream: string; count: number }> = [];\n const findings: AuditFinding[] = [];\n return {\n category: \"restart-candidate\",\n on_stat(stream, { head, count }) {\n if (count! < threshold) return;\n const head_name = String(head.name);\n if (head_name.startsWith(\"__\")) return;\n if (!restart_is_supported(deps, head_name)) return;\n candidates.push({ stream, count: count! });\n },\n async finalize(deps) {\n for (const { stream, count } of candidates) {\n let snaps = 0;\n await deps.store().query(\n () => {\n snaps++;\n },\n {\n stream,\n stream_exact: true,\n names: [SNAP_EVENT],\n with_snaps: true,\n // From the start: on its own, `with_snaps` resumes at the latest.\n after: -1,\n }\n );\n findings.push({\n category: \"restart-candidate\",\n stream,\n count,\n snaps,\n });\n }\n },\n drain: () => findings,\n };\n};\n\nconst make_reaction_health_pass: PassFactory = (_deps, options) => {\n const near_block = options.thresholds?.near_block ?? DEFAULTS.near_block;\n const stuck_minutes =\n options.thresholds?.stuck_minutes ?? DEFAULTS.stuck_minutes;\n const stuck_cutoff = Date.now() - stuck_minutes * 60 * 1000;\n const findings: AuditFinding[] = [];\n return {\n category: \"reaction-health\",\n on_stream(p) {\n if (p.blocked) {\n findings.push({\n category: \"reaction-health\",\n stream: p.stream,\n status: \"blocked\",\n retry: p.retry,\n reason: p.error || \"blocked without recorded error\",\n });\n return;\n }\n if (p.retry >= near_block) {\n findings.push({\n category: \"reaction-health\",\n stream: p.stream,\n status: \"near-block\",\n retry: p.retry,\n reason: `retry ${p.retry} ≥ near-block threshold ${near_block}`,\n });\n return;\n }\n if (\n p.leased_by &&\n p.leased_until &&\n p.leased_until.getTime() < stuck_cutoff\n ) {\n const minutes = Math.floor(\n (Date.now() - p.leased_until.getTime()) / (60 * 1000)\n );\n findings.push({\n category: \"reaction-health\",\n stream: p.stream,\n status: \"stuck-backoff\",\n retry: p.retry,\n reason: `lease expired ${minutes}m ago without release`,\n });\n }\n },\n drain: () => findings,\n };\n};\n\nconst make_snapshot_drift_pass: PassFactory = (deps, options) => {\n const drift_min = options.thresholds?.drift_min ?? DEFAULTS.drift_min;\n const candidates: Array<{\n stream: string;\n total: number;\n }> = [];\n const findings: AuditFinding[] = [];\n return {\n category: \"snapshot-drift\",\n on_stat(stream, { head, count }) {\n // Also rejects framework markers, which no user state declares.\n if (!restart_is_supported(deps, String(head.name))) return;\n if (count! < drift_min) return; // upper-bound short-circuit\n candidates.push({\n stream,\n total: count!,\n });\n },\n async finalize(deps) {\n for (const { stream, total } of candidates) {\n let events_since_snap = total;\n let snap_at: number | undefined;\n // The shared stat scan excludes `__snapshot__`, so look it up here.\n const collected: Array<{ id: number }> = [];\n await deps.store().query(\n (e) => {\n collected.push({ id: e.id });\n },\n {\n stream,\n stream_exact: true,\n names: [\"__snapshot__\"],\n backward: true,\n limit: 1,\n with_snaps: true,\n }\n );\n if (collected.length > 0) {\n snap_at = collected[0]!.id;\n let after = 0;\n await deps.store().query(\n () => {\n after++;\n },\n { stream, stream_exact: true, after: snap_at }\n );\n events_since_snap = after;\n }\n if (events_since_snap < drift_min) continue;\n findings.push({\n category: \"snapshot-drift\",\n stream,\n events_since_snap,\n snap_at,\n });\n }\n },\n drain: () => findings,\n };\n};\n\nconst make_routing_health_pass: PassFactory = (deps) => {\n const findings: AuditFinding[] = [];\n const seen_event_names = new Set<string>();\n return {\n category: \"routing-health\",\n on_stream(p) {\n if (!p.lane) return; // default lane — never an unknown-lane finding\n if (deps.declared_lanes.has(p.lane)) return;\n findings.push({\n category: \"routing-health\",\n stream: p.stream,\n reason: \"unknown-lane\",\n lane: p.lane,\n });\n },\n on_stat(_stream, { names }) {\n for (const name of Object.keys(names!)) {\n seen_event_names.add(name);\n }\n },\n finalize() {\n for (const name of seen_event_names) {\n if (name.startsWith(\"__\")) continue;\n if (deps.routed_events.has(name)) continue;\n findings.push({\n category: \"routing-health\",\n stream: \"*\",\n reason: \"unrouted\",\n });\n }\n return Promise.resolve();\n },\n drain: () => findings,\n };\n};\n\nconst make_correlation_gaps_pass: PassFactory = () => {\n const seen_ids = new Set<number>();\n const checks: Array<{ stream: string; id: number; parent_id: number }> = [];\n return {\n category: \"correlation-gaps\",\n on_event(e) {\n seen_ids.add(e.id);\n const causation = (e.meta as Record<string, unknown> | undefined)\n ?.causation as { event?: { id?: number } } | undefined;\n const parent_id = causation?.event?.id;\n // A close's seed names the guard it just deleted, which isn't a gap.\n if (parent_id !== undefined && e.name !== TOMBSTONE_EVENT) {\n checks.push({ stream: e.stream, id: e.id, parent_id });\n }\n },\n drain() {\n const findings: AuditFinding[] = [];\n for (const { stream, id, parent_id } of checks) {\n if (!seen_ids.has(parent_id)) {\n findings.push({\n category: \"correlation-gaps\",\n stream,\n event_id: id,\n reason: \"orphan-parent\",\n });\n }\n }\n return findings;\n },\n };\n};\n\nconst make_clock_anomalies_pass: PassFactory = () => {\n const findings: AuditFinding[] = [];\n const last_per_stream = new Map<string, number>();\n return {\n category: \"clock-anomalies\",\n on_event(e) {\n const created = e.created.getTime();\n if (created > Date.now()) {\n findings.push({\n category: \"clock-anomalies\",\n stream: e.stream,\n event_id: e.id,\n reason: \"future-created\",\n });\n }\n const prev = last_per_stream.get(e.stream);\n if (prev !== undefined && created < prev) {\n findings.push({\n category: \"clock-anomalies\",\n stream: e.stream,\n event_id: e.id,\n reason: \"out-of-order\",\n });\n }\n last_per_stream.set(e.stream, created);\n },\n drain: () => findings,\n };\n};\n\nfunction restart_is_supported(\n deps: AuditDeps,\n head_event_name: string\n): boolean {\n const state = deps.event_to_state.get(head_event_name);\n return state?.snap !== undefined;\n}\n\n/** Fed by the dispatcher with rows the event scan tripped on; never reaches `on_event`. */\nfunction make_unreadable_events_pass(): AuditPass {\n const findings: AuditFinding[] = [];\n return {\n category: \"unreadable-events\",\n on_unreadable({ stream, event_id, error }) {\n findings.push({\n category: \"unreadable-events\",\n stream,\n event_id,\n reason: \"pii_decrypt_failed\",\n error,\n });\n },\n drain: () => findings,\n };\n}\n\nconst PASS_FACTORIES: Record<AuditCategory, PassFactory> = {\n schema: make_schema_pass,\n \"deprecated-load\": make_deprecated_load_pass,\n \"close-candidate\": make_close_candidate_pass,\n \"restart-candidate\": make_restart_candidate_pass,\n \"reaction-health\": make_reaction_health_pass,\n \"snapshot-drift\": make_snapshot_drift_pass,\n \"routing-health\": make_routing_health_pass,\n \"correlation-gaps\": make_correlation_gaps_pass,\n \"clock-anomalies\": make_clock_anomalies_pass,\n \"unreadable-events\": make_unreadable_events_pass,\n};\n","/**\n * Orchestrator-level circuit breaker for store operations. The drain loop\n * polls `claim()` continuously; when the backing store goes down every poll\n * throws a {@link StoreError}, and without a breaker the orchestrator would\n * spin at the cycle cadence hammering a dead database and flooding the logs.\n *\n * The breaker collapses that into three states:\n *\n * - **closed** — normal operation; failures are counted.\n * - **open** — `failureThreshold` consecutive failures tripped it; attempts\n * are skipped for `cooldownMs` so the store gets room to recover.\n * - **half-open** — the cooldown elapsed; a single trial attempt is allowed.\n * Success closes the breaker; failure re-opens it and restarts the clock.\n *\n * Time is passed in (`now`) rather than read from the clock so the state\n * machine is deterministic under test.\n */\n\nimport type { CircuitState } from \"../types/index.js\";\nimport type { CircuitBreakerConfig } from \"./config.js\";\n\n/**\n * Side-effect hooks the orchestrator wires into the breaker so consumers\n * (drain / settle / autoclose) don't each thread their own callbacks.\n */\nexport type CircuitBreakerHooks = {\n /** Invoked on every {@link CircuitBreaker.failed} with the error and state. */\n readonly on_error?: (error: unknown, circuit: CircuitState) => void;\n /**\n * Invoked once, `cooldownMs` after the latest failure, open or not. The\n * orchestrator wires it to a settle, so recovery is automatic even on the\n * default lane, which has no periodic poller.\n */\n readonly on_retry?: () => void;\n};\n\nexport class CircuitBreaker {\n private _failures = 0;\n private _opened_at: number | undefined;\n private _wake: ReturnType<typeof setTimeout> | undefined;\n private readonly _threshold: number;\n private readonly _cooldown_ms: number;\n private readonly _hooks: CircuitBreakerHooks;\n\n constructor(config: CircuitBreakerConfig, hooks: CircuitBreakerHooks = {}) {\n this._threshold = config.failureThreshold;\n this._cooldown_ms = config.cooldownMs;\n this._hooks = hooks;\n }\n\n /**\n * True when the store has failed at least once since the last pass that\n * went all the way through. The breaker can still read \"closed\" here: it\n * only opens after several failures in a row, so this catches the first\n * one, which `state()` cannot.\n */\n get failing(): boolean {\n return this._failures > 0;\n }\n\n /** How long the store is left alone after a failure before a retry. */\n get cooldown_ms(): number {\n return this._cooldown_ms;\n }\n\n /** Current state given the wall-clock `now`. */\n state(now: number): CircuitState {\n if (this._opened_at === undefined) return \"closed\";\n return now - this._opened_at >= this._cooldown_ms ? \"half-open\" : \"open\";\n }\n\n /** A store op passed — reset to closed and cancel any pending retry. */\n passed(): void {\n this._failures = 0;\n this._opened_at = undefined;\n this._clear_wake();\n }\n\n /**\n * A store op failed. Opens the breaker when the consecutive-failure\n * threshold is reached, or immediately re-opens (restarting the cooldown)\n * if a half-open trial just failed. Returns the resulting state.\n *\n * Callers gate on the state directly — `state(now) === \"open\"` means skip.\n * Every failure (re)schedules the `on_retry` wake, so one failed pass on\n * an idle app retries without waiting for the breaker to open; always\n * surfaces the failure via `on_error`.\n */\n failed(now: number, error?: unknown): CircuitState {\n const circuit = this._advance(now);\n this._schedule_wake();\n this._hooks.on_error?.(error, circuit);\n return circuit;\n }\n\n /** Cancel the pending retry timer. Idempotent; call on shutdown. */\n stop(): void {\n this._clear_wake();\n }\n\n // Schedule the `on_retry` wake `cooldownMs` out so the breaker re-trials\n // the store on its own. No-op when no `on_retry` hook is wired (e.g. unit\n // tests of the pure state machine). The timer is `unref`'d so it never\n // keeps the process alive.\n private _schedule_wake(): void {\n if (!this._hooks.on_retry) return;\n this._clear_wake();\n this._wake = setTimeout(() => {\n this._wake = undefined;\n this._hooks.on_retry?.();\n }, this._cooldown_ms);\n this._wake.unref();\n }\n\n private _clear_wake(): void {\n if (this._wake) {\n clearTimeout(this._wake);\n this._wake = undefined;\n }\n }\n\n // Pure state transition for a failure — no side effects.\n private _advance(now: number): CircuitState {\n // Already tripped: this can only be reached from a half-open trial\n // (open skips attempts), so the trial failed — re-open and restart.\n if (this._opened_at !== undefined) {\n this._opened_at = now;\n return \"open\";\n }\n this._failures += 1;\n if (this._failures >= this._threshold) {\n this._opened_at = now;\n return \"open\";\n }\n return \"closed\";\n }\n}\n","/**\n * Build-time classification of the registry + state map. The Act constructor\n * needs three pre-computed inputs to wire its runtime subsystems:\n *\n * - `static_targets` — known-up-front reaction targets, subscribed once\n * at init (correlate marks them from then on)\n * - `event_to_state` — event-name → owning state, for `close({restart})`\n * seed loading in multi-state apps\n * - `event_to_lanes` — event-name → the lanes its reactions run on, for\n * selective arming; its keys are exactly the events\n * that have a reaction\n *\n * Pure function — single pass over events + states, fully testable without\n * instantiating Act.\n */\n\nimport type {\n Registry,\n Schema,\n SchemaRegister,\n Schemas,\n State,\n} from \"../types/index.js\";\nimport type { StaticTarget } from \"./correlate-cycle.js\";\n\n/**\n * Sentinel for \"any reaction on this event has a dynamic resolver, so\n * the lane is opaque until correlate runs the function — arm every\n * controller.\" A Symbol rather than a string literal so it can't\n * collide with a user-declared lane named `\"all\"`.\n */\nexport const ALL_LANES: unique symbol = Symbol(\"act/all-lanes\");\n\n/**\n * Per-event lane fan-in. For events whose every reaction\n * has a static resolver, the value is the union of those reactions'\n * declared lanes — `do()` arms only those controllers on commit. For\n * events with at least one dynamic resolver, the value is\n * {@link ALL_LANES}; `do()` falls back to arming every controller.\n */\nexport type EventLaneSet = ReadonlySet<string> | typeof ALL_LANES;\n\n/**\n * Classification result. Returned by {@link classify_registry}; consumed\n * piecewise by Act's constructor.\n */\nexport type Classification = {\n readonly static_targets: StaticTarget[];\n readonly event_to_state: ReadonlyMap<string, State<any, any, any>>;\n readonly event_to_lanes: ReadonlyMap<string, EventLaneSet>;\n};\n\nconst describe_source = (source: string | undefined) =>\n source === undefined ? \"no source (every stream)\" : `\"${source}\"`;\n\n/**\n * Walk the registry once to collect static reaction targets, the set of\n * reactive event names, the per-event lane fan-in, and the event-to-state\n * map. Static targets are deduplicated by (target, source) — two reactions\n * routing to the same projection produce one subscription.\n */\nexport function classify_registry<\n TSchemaReg extends SchemaRegister<TActions>,\n TEvents extends Schemas,\n TActions extends Schemas,\n>(\n registry: Registry<TSchemaReg, TEvents, TActions>,\n states: ReadonlyMap<string, State<Schema, any, any>>\n): Classification {\n const statics = new Map<string, StaticTarget>();\n // Per-target lane, checked across EVERY reaction to a target regardless of\n // source. A stream drains on exactly one lane, and `subscribe`\n // keys lane per-target, so lane must agree target-wide — the\n // `(target, source)` scoping of `statics` is too narrow to catch a\n // same-target/different-source lane disagreement.\n const target_lanes = new Map<string, string>();\n const event_to_lanes = new Map<string, EventLaneSet>();\n\n for (const [name, register] of Object.entries(registry.events)) {\n for (const reaction of register.reactions.values()) {\n if (typeof reaction.resolver === \"function\") {\n // Dynamic resolver — lane is opaque until runtime. Mark the\n // event as wildcard so `do()` falls back to arming every\n // controller for any commit of it.\n event_to_lanes.set(name, ALL_LANES);\n } else {\n const { target, source, priority = 0, lane } = reaction.resolver;\n const lane_name = lane ?? \"default\";\n const existing_lanes = event_to_lanes.get(name);\n if (existing_lanes !== ALL_LANES) {\n const set =\n (existing_lanes as Set<string> | undefined) ?? new Set<string>();\n set.add(lane_name);\n event_to_lanes.set(name, set);\n }\n // Lanes don't merge — any two reactions to the\n // same target must declare the same lane, regardless of source.\n // First reaction to a target records its lane; every later one must\n // match or it's a config error caught at build time. Both sides\n // compare the NORMALIZED name, so an omitted lane and an\n // explicit \"default\" — the same lane — agree.\n const recorded_lane = target_lanes.get(target);\n if (recorded_lane === undefined) {\n target_lanes.set(target, lane_name);\n } else if (recorded_lane !== lane_name) {\n throw new Error(\n `Stream \"${target}\" has conflicting lane assignments ` +\n `(\"${recorded_lane}\" vs \"${lane_name}\")`\n );\n }\n // Keyed by target alone, because a subscription row IS keyed by\n // stream: every adapter sets `source` once at creation and ignores\n // it thereafter, so a second source is refused, and a second reaction\n // on the same one contributes only its priority. One entry per\n // stream, max priority, so the highest-priority registrant sets the\n // scheduling priority.\n const existing = statics.get(target);\n if (existing && existing.source !== source)\n throw new Error(\n `Target \"${target}\" has reactions on two sources, ${describe_source(existing.source)} and ${describe_source(source)}. A target reads one source, so the second would miss events or read too many. Give it its own target.`\n );\n if (!existing) {\n statics.set(target, { stream: target, source, priority, lane });\n } else if (priority > (existing.priority as number)) {\n // `existing.priority` is always defined here since we always set\n // it when inserting, but the StaticTarget type marks it optional\n // for external consumers.\n statics.set(target, { ...existing, priority });\n }\n }\n }\n }\n\n // Event-name → owning state. Duplicate event names are rejected at\n // registration time (merge.ts), so each entry is unambiguous.\n const event_to_state = new Map<string, State<any, any, any>>();\n for (const merged of states.values()) {\n for (const event_name of Object.keys(merged.events)) {\n event_to_state.set(event_name, merged);\n }\n }\n\n return {\n static_targets: [...statics.values()],\n event_to_state,\n event_to_lanes,\n };\n}\n","/**\n * Compiles the declarative `.autocloses({...})` policy into a predicate.\n * Top-level `after` / `is` / `reaches` combine with AND; an `or: {...}`\n * block adds an alternative path. Validated with\n * {@link AutoclosePolicySchema} when the app builds, so a bad policy throws\n * then, not on the first cycle. Semantics and examples:\n * docs/docs/guides/close-policies.md.\n */\n\nimport { z } from \"zod\";\nimport type {\n AutoclosePolicy,\n AutoclosePredicate,\n Schemas,\n} from \"../types/action.js\";\n\n/**\n * One day in epoch milliseconds. The close surface is day-denominated\n * throughout — policies declare `{ days }`, the State carries\n * `autoclose_*_days`, and the reaction thinks in day offsets. This\n * constant (with {@link days_after} / {@link days_before_now}) is the\n * single place the closing process touches epoch arithmetic, because\n * `Date` itself has no other currency.\n */\nconst DAY_MS = 86_400_000;\n\n/**\n * Lower bound on a resolved `after` window: one minute, expressed in\n * days. Sub-minute cooldowns are almost always misconfiguration.\n * Rejecting at build keeps the failure mode noisy.\n */\nconst MIN_AFTER_DAYS = 1 / 1440;\n\n/**\n * Lower bound on a resolved `keep` window: one full day. The close\n * cycle is low-cadence, non-priority housekeeping — a rolling window\n * shorter than a day signals misconfiguration. Real retention\n * contracts (180 days, 7 years) are days and up.\n */\nconst MIN_KEEP_DAYS = 1;\n\n/** The `Date` that lies `days` after `date`. */\nexport function days_after(date: Date, days: number): Date {\n return new Date(date.getTime() + days * DAY_MS);\n}\n\n/** The `Date` that lies `days` in the past. */\nexport function days_before_now(days: number): Date {\n return new Date(Date.now() - days * DAY_MS);\n}\n\n/**\n * Day-denominated window shared by `after` (terminate cooldown) and\n * `keep` (rolling retention). Fractional days accepted; windows below\n * the field's floor reject at build.\n */\nconst window_schema = (\n field: \"after\" | \"keep\",\n min_days: number,\n floor: string\n) =>\n z\n .object({\n days: z\n .number({ message: `autocloses: ${field}.days must be a number` })\n .positive(`autocloses: ${field}.days must be > 0`),\n })\n .refine((o) => o.days >= min_days, {\n message: `autocloses: ${field} resolves to < ${floor}, which is too short to be a meaningful retention window`,\n });\n\nconst AfterSchema = window_schema(\"after\", MIN_AFTER_DAYS, \"one minute\");\n\nconst KeepSchema = window_schema(\"keep\", MIN_KEEP_DAYS, \"one day\");\n\nconst IsSchema = z.union([\n z.string().min(1, \"autocloses: is must be a non-empty event name\"),\n z\n .array(\n z.string().min(1, \"autocloses: is entries must be non-empty event names\")\n )\n .min(1, \"autocloses: is must include at least one event name\")\n .readonly(),\n]);\n\nconst ReachesSchema = z\n .number({ message: \"autocloses: reaches must be a number\" })\n .int(\"autocloses: reaches must be an integer\")\n .min(1, \"autocloses: reaches must be >= 1\");\n\n/**\n * Schema for the `or: {...}` block — the OR-shaped alternative path.\n * Same field set as the top-level policy minus `or` itself (so nested\n * `or` inside `or` rejects via `.strict()` instead of recursing). At\n * least one field required; empty `{}` is a misconfiguration.\n */\nconst OrBlockSchema = z\n .object({\n after: AfterSchema.optional(),\n is: IsSchema.optional(),\n reaches: ReachesSchema.optional(),\n })\n .strict()\n .refine(\n (o) =>\n o.after !== undefined || o.is !== undefined || o.reaches !== undefined,\n {\n message:\n \"autocloses: `or` block must include at least one of after / is / reaches\",\n }\n );\n\n/**\n * Zod schema for the declarative {@link AutoclosePolicy} bag.\n * Internal `const` per the config-validation standard\n * (`.claude/rules/config-validation.md`) — the public surface is the inferred\n * {@link AutoclosePolicy} type and the `.autocloses({...})` overload,\n * never this schema. `.strict()` rejects unknown keys so typos surface\n * at build instead of being silently ignored.\n */\nconst AutoclosePolicySchema = z\n .object({\n after: AfterSchema.optional(),\n is: IsSchema.optional(),\n reaches: ReachesSchema.optional(),\n or: OrBlockSchema.optional(),\n keep: KeepSchema.optional(),\n })\n .strict()\n .refine(\n (o) =>\n o.after !== undefined ||\n o.is !== undefined ||\n o.reaches !== undefined ||\n o.or !== undefined ||\n o.keep !== undefined,\n {\n message:\n \"autocloses: at least one of after / is / reaches / or / keep must be specified — empty `{}` is a misconfiguration\",\n }\n ) satisfies z.ZodType<AutoclosePolicy>;\n\n/** Compile a single `after` field into its predicate slice. */\nfunction compile_after(\n after: NonNullable<AutoclosePolicy[\"after\"]>\n): AutoclosePredicate<Schemas> {\n return (_stream, head) => days_after(head.created, after.days) <= new Date();\n}\n\n/** Compile a single `is` field into its predicate slice. */\nfunction compile_is(\n is: NonNullable<AutoclosePolicy[\"is\"]>\n): AutoclosePredicate<Schemas> {\n const set = new Set(typeof is === \"string\" ? [is] : is);\n return (_stream, head) => set.has(head.name as string);\n}\n\n/** Compile a single `reaches` field into its predicate slice. */\nfunction compile_reaches(\n reaches: NonNullable<AutoclosePolicy[\"reaches\"]>\n): AutoclosePredicate<Schemas> {\n return (_stream, _head, count) => count >= reaches;\n}\n\n/**\n * Every `after` window (in days) in a policy. The reaction parks on the\n * earliest one still ahead, so a branch with a later window keeps its turn once\n * an earlier one has passed.\n */\nexport function policy_after_windows(options: AutoclosePolicy): number[] {\n const parsed = AutoclosePolicySchema.parse(options);\n return [parsed.after, parsed.or?.after].flatMap((w) => (w ? [w.days] : []));\n}\n\n/**\n * The rolling-window width (in days) of a policy's `keep` field, or\n * `undefined` when the policy declares no rolling window. The\n * synthesized autoclose reaction prunes the prefix older than the\n * window (via a windowed close) and derives its prune due-time as\n * `tail.created` plus this many days — the earliest the oldest\n * surviving domain event can age out of the window.\n */\nexport function policy_keep_days(options: AutoclosePolicy): number | undefined {\n const parsed = AutoclosePolicySchema.parse(options);\n return parsed.keep?.days;\n}\n\n/**\n * Compile a declarative {@link AutoclosePolicy} into an\n * {@link AutoclosePredicate}. The state-builder's\n * `.autocloses({...})` overload calls this; tests can also build a\n * state and read `state.autoclose` to grab the compiled predicate.\n *\n * Returned predicate fires when either:\n *\n * 1. **All** top-level non-`or` fields match (AND), or\n * 2. **Any** field inside the `or` block matches.\n *\n * Top-level with zero non-`or` fields never satisfies path (1) — the\n * `every` check on an empty list is short-circuited to `false` so the\n * policy doesn't truncate the entire universe on an `or`-only\n * declaration. (Validation rejects all-empty bags up front; this guard\n * is the in-cycle equivalent for the synthesized empty AND-group.)\n *\n * Assignable to any `AutoclosePredicate<TEvents>` slot via\n * function-parameter contravariance — the returned predicate inspects\n * `head.name` as a plain string, so narrower event unions stay\n * assignable.\n *\n * Throws `ZodError` at call time when the options are invalid (empty\n * bag, non-positive `reaches`, sub-minute `after`, empty `is`, empty\n * `or`, nested `or`, unknown keys).\n */\nexport function compile_autoclose_policy(\n options: AutoclosePolicy\n): AutoclosePredicate<Schemas> {\n const parsed = AutoclosePolicySchema.parse(options);\n\n // Top-level AND group — only the non-`or` fields.\n const and_preds: AutoclosePredicate<Schemas>[] = [];\n if (parsed.after) and_preds.push(compile_after(parsed.after));\n if (parsed.is) and_preds.push(compile_is(parsed.is));\n if (parsed.reaches) and_preds.push(compile_reaches(parsed.reaches));\n\n // OR-block — at least one of its fields must match.\n const or_preds: AutoclosePredicate<Schemas>[] = [];\n if (parsed.or) {\n if (parsed.or.after) or_preds.push(compile_after(parsed.or.after));\n if (parsed.or.is) or_preds.push(compile_is(parsed.or.is));\n if (parsed.or.reaches) or_preds.push(compile_reaches(parsed.or.reaches));\n }\n\n return (stream, head, count) => {\n // AND path: every top-level field matches AND the group is non-empty\n // (an `or`-only declaration leaves `and_preds` empty — that\n // shouldn't auto-fire).\n if (\n and_preds.length > 0 &&\n and_preds.every((p) => p(stream, head, count))\n ) {\n return true;\n }\n // OR path: any `or`-block field matches.\n if (or_preds.some((p) => p(stream, head, count))) {\n return true;\n }\n return false;\n };\n}\n","/**\n * Off-hours window math for autoclose — hour-in-zone, DST-gap handling, and\n * \"next time the window opens\".\n */\n\nimport type { AutocloseConfig } from \"../types/index.js\";\n\n/**\n * The current hour `[0, 23]` in the given IANA time zone, DST-correct\n * via `Intl`. Split out so the window check can be unit-tested without\n * spinning a controller.\n */\nexport function hour_in_zone(now: Date, timeZone: string): number {\n const parts = new Intl.DateTimeFormat(\"en-US\", {\n timeZone,\n hour: \"2-digit\",\n hourCycle: \"h23\",\n }).formatToParts(now);\n return Number(parts.find((p) => p.type === \"hour\")?.value);\n}\n\n/**\n * True when a plain `[start, end)` hour comparison places `hour` inside\n * the window. Half-open on hour boundaries and wrapping past midnight\n * when `start > end`.\n */\nfunction hour_in_range(hour: number, start: number, end: number): boolean {\n return start < end\n ? hour >= start && hour < end\n : hour >= start || hour < end;\n}\n\n/**\n * True when `now` is the instant a DST spring-forward gap skipped over\n * the window's `start` hour. On such a day the local `start` hour never\n * occurs — the clock jumps from `start - 1` straight past `start` — so a\n * plain hour comparison would report the window closed all day. The gap\n * surfaces as a one-hour boundary where the local hour jumps from below\n * `start` to above it; that boundary instant is the window's replacement\n * opening. Detected by comparing the hour at `now` with the hour one\n * hour earlier: a jump of more than one hour that steps over `start`.\n */\nfunction is_dst_gap_open(now: Date, timeZone: string, start: number): boolean {\n const hour = hour_in_zone(now, timeZone);\n if (hour <= start) return false;\n const prev = hour_in_zone(new Date(now.getTime() - 3_600_000), timeZone);\n // A normal step advances one local hour; a spring-forward gap advances\n // two, skipping exactly one local hour. This instant is the gap opening\n // only when the skipped hour is the window's `start`: the previous hour\n // sits just below `start` and this hour just above it.\n return prev === start - 1 && hour === start + 1;\n}\n\n/**\n * Whether `now` falls inside the configured off-hours window. The\n * window is half-open on hour boundaries — `[start, end)` — and wraps\n * past midnight when `start > end`. With no window configured every\n * tick runs, so callers treat `undefined` as \"always in window.\"\n *\n * On a DST spring-forward day whose `start` hour is skipped, the window\n * would otherwise be closed for the whole day (the `start` hour never\n * occurs). The gap's replacement instant is admitted so autoclose still\n * runs — see {@link is_dst_gap_open}.\n */\nexport function in_autoclose_window(\n window: AutocloseConfig[\"autocloseWindow\"],\n now: Date\n): boolean {\n if (!window) return true;\n const hour = hour_in_zone(now, window.timeZone);\n return (\n hour_in_range(hour, window.start, window.end) ||\n is_dst_gap_open(now, window.timeZone, window.start)\n );\n}\n\n/**\n * The next instant the off-hours window opens at or after `now`. The\n * synthesized autoclose reaction defers to this when a tick lands\n * outside the window — parking until the window actually opens instead\n * of blind-polling on a configured cadence (the old behavior,\n * where a poll interval longer than the window could oscillate around\n * it and miss it repeatedly).\n *\n * Walks forward hour by hour and asks `Intl` for the local hour at each\n * step, so DST transitions resolve exactly the way the runtime's zone\n * database says they do — a 23- or 25-hour day never desynchronizes the\n * walk. The window validates as non-empty at build, and every zone hits\n * each `[0, 23]` hour label within any 48-hour span, so the walk always\n * terminates; the bound is a defensive backstop, with \"one day out\" as\n * the fallback no real zone can reach.\n *\n * Minute/second offsets within the opening hour are preserved from\n * `now` shifted by whole hours — the contract is hour-granular, matching\n * the window's own `[start, end)` hour semantics.\n *\n * On a DST spring-forward day whose `start` hour is skipped, the `start`\n * hour never occurs, so the minute-preserving walk would never match and\n * the window would defer ~24 h. The walk also checks each hour-aligned\n * boundary for the gap opening (see {@link is_dst_gap_open}) and returns\n * that boundary instant — deferring ~1 h to the replacement instant\n * rather than a full day. The boundary is returned as-is (no minute\n * offset): the gap opening is a single transition instant, not a range.\n */\nexport function next_window_open(\n window: NonNullable<AutocloseConfig[\"autocloseWindow\"]>,\n now: Date\n): Date {\n const start_ms = now.getTime();\n for (let h = 0; h <= 48; h++) {\n const candidate = new Date(start_ms + h * 3_600_000);\n if (hour_in_zone(candidate, window.timeZone) === window.start)\n return candidate;\n // The `start` hour may be unreachable on a spring-forward day; catch\n // the gap boundary at the top of this candidate's hour. The boundary is\n // UTC-hour aligned, so in a fractional-offset zone the first one can sit\n // behind `now` — a past due is never excluded by claim, so skip it.\n const boundary = new Date(\n candidate.getTime() - (candidate.getTime() % 3_600_000)\n );\n if (\n boundary.getTime() >= start_ms &&\n is_dst_gap_open(boundary, window.timeZone, window.start)\n )\n return boundary;\n }\n return new Date(start_ms + 86_400_000);\n}\n","/**\n * The `when` options for the public `defer` surface. A\n * reaction defers itself to a future time either declaratively (the\n * `.defer(when)` builder step) or imperatively (`throw new DeferSignal(when)`\n * inside a handler); both resolve `when` through here.\n *\n * The load-bearing rule is **derivability**. A deferred stream's due-time must\n * be recomputable by whichever worker re-claims it after the wait, so `when`\n * never resolves against `Date.now()`. `after` is measured from the triggering\n * event's `created` timestamp, and `at` is either a fixed `Date` or a pure\n * function of the event. Either way, re-delivering the same event yields the\n * same due-time, which is what makes a defer correct across restarts and\n * competing workers.\n *\n * Validation follows the config-schema standard\n * (`.claude/rules/config-validation.md`): an internal `*OptionsSchema`\n * const, a public inferred type, and a resolver.\n */\n\nimport { z } from \"zod\";\nimport { DeferSignal } from \"../types/errors.js\";\nimport type { Committed, DeferWhen, Schemas } from \"../types/index.js\";\n\n/**\n * A relative span, measured from the triggering event's `created` time. At\n * least one field is required; fields are additive (`{ hours: 1, minutes: 30 }`\n * is 90 minutes).\n */\nconst DeferDurationSchema = z\n .object({\n days: z.number().positive().optional(),\n hours: z.number().positive().optional(),\n minutes: z.number().positive().optional(),\n })\n .strict()\n .refine((d) => d.days != null || d.hours != null || d.minutes != null, {\n message: \"defer: a duration needs at least one of days, hours, or minutes\",\n });\n\n/**\n * Zod schema for the `defer(when)` options bag. Exactly one of `after` / `at`;\n * `at` is an absolute `Date`. Internal per the config standard; the public\n * surface is {@link DeferWhen} and {@link resolve_defer_at}.\n */\nconst DeferWhenSchema = z\n .object({\n after: DeferDurationSchema.optional(),\n at: z.date().optional(),\n })\n .strict()\n .refine((w) => (w.after === undefined) !== (w.at === undefined), {\n message: \"defer: specify exactly one of `after` or `at`\",\n });\n\n/** Sum a duration bag to milliseconds. */\nfunction duration_ms(d: {\n days?: number;\n hours?: number;\n minutes?: number;\n}): number {\n return (\n (d.days ?? 0) * 86_400_000 +\n (d.hours ?? 0) * 3_600_000 +\n (d.minutes ?? 0) * 60_000\n );\n}\n\n/**\n * Resolve `when` to an absolute due-time (ms since epoch) for a given\n * triggering event. Validates via {@link DeferWhenSchema} (throws `ZodError`\n * on a bad shape), then derives the time: `after` from `event.created`, `at`\n * from its absolute `Date`. Never reads `Date.now()`, so the result is stable\n * across re-delivery.\n */\nexport function resolve_defer_at<E extends Schemas>(\n when: DeferWhen,\n event: Committed<E, keyof E>\n): number {\n const parsed = DeferWhenSchema.parse(when);\n if (parsed.after) return event.created.getTime() + duration_ms(parsed.after);\n return parsed.at!.getTime();\n}\n\n/**\n * The schedule handed to the declarative `.defer` builder step: either a\n * literal {@link DeferWhen} (fixed cooldown/deadline) or a function of the\n * triggering event (read the payload to choose the schedule).\n */\nexport type DeferSchedule<TEvent> = DeferWhen | ((event: TEvent) => DeferWhen);\n\n/**\n * Validate a literal `when` at build time (fail fast, per the config-schema\n * standard) — throws `ZodError` on a bad shape (both/neither of `after`/`at`,\n * an empty or non-positive duration). The function form of a `.defer` schedule\n * can only be checked when it runs, so builders pass just the literal here.\n */\nexport function assert_defer_when(when: DeferWhen): void {\n DeferWhenSchema.parse(when);\n}\n\n/**\n * Wrap a reaction handler so it holds until its schedule is due, then runs.\n * On each delivery it resolves the schedule against the triggering event; if\n * the due-time hasn't arrived it throws {@link DeferSignal} (the drain holds\n * the stream, no watermark advance, no retry bump), otherwise it runs the\n * real handler. The wrapper keeps the original handler's `name` so reaction\n * registration and de-dup are unaffected, and preserves the handler's exact\n * type so the builder step is transparent.\n */\nexport function make_deferred<H extends (...args: any[]) => Promise<unknown>>(\n handler: H,\n schedule: DeferSchedule<Parameters<H>[0]>\n): H {\n const call = handler as (...args: unknown[]) => Promise<unknown>;\n const deferred = async (\n event: Parameters<H>[0],\n stream: string,\n app: unknown\n ) => {\n const when = typeof schedule === \"function\" ? schedule(event) : schedule;\n if (Date.now() < resolve_defer_at(when, event)) throw new DeferSignal(when);\n return call(event, stream, app);\n };\n Object.defineProperty(deferred, \"name\", { value: handler.name });\n return deferred as unknown as H;\n}\n","/**\n * The drain pipeline: {@link run_drain_cycle} is one stateless\n * claim → fetch → dispatch → ack/block round-trip; {@link DrainController}\n * owns the armed flag, the lock, the lag/lead ratio and the defer wake.\n */\n\nimport { randomUUID } from \"node:crypto\";\nimport { log } from \"../ports.js\";\nimport { NonRetryableError } from \"../types/errors.js\";\nimport type {\n BatchHandler,\n BlockedLease,\n CloseTarget,\n Drain,\n DrainOptions,\n Fetch,\n Lease,\n Logger,\n ReactionOptions,\n ReactionPayload,\n Registry,\n Resolved,\n SchemaRegister,\n Schemas,\n} from \"../types/index.js\";\nimport { compute_backoff_delay } from \"./backoff.js\";\nimport type { CircuitBreaker } from \"./circuit-breaker.js\";\nimport {\n DEFAULT_BACKOFF,\n DEFAULT_EVENT_LIMIT,\n DEFAULT_LEASE_MILLIS,\n DEFAULT_STREAM_LIMIT,\n} from \"./config.js\";\nimport { DeferTimer } from \"./defer-timer.js\";\nimport type { DrainOps } from \"./drain-ops.js\";\nimport { compute_lag_lead_ratio } from \"./drain-ratio.js\";\nimport { report_once } from \"./report-once.js\";\nimport { trace_cycle } from \"./tracing.js\";\n\n/** Outcome of handling one leased stream; drives its ack/block. */\nexport type HandleResult = Readonly<{\n lease: Lease;\n handled: number;\n /** Last successful event id, or `lease.at` when there was no work. */\n acked_at: number;\n error?: string;\n block?: boolean;\n /** Epoch ms of the next retry, from the backoff. Only set on a retry. */\n next_attempt_at?: number;\n /** Epoch ms to redeliver a deferred stream; no error, no retry bump. */\n defer?: number;\n /** From a `CloseSignal`; acked first so the close guard sees it caught up. */\n close?: CloseTarget;\n /** Event id that threw (sparse ids make it differ from `acked_at + 1`); never in batch mode. */\n failed_at?: number;\n}>;\n\n/** `Act.handle`. */\nexport type Handle<TEvents extends Schemas> = (\n lease: Lease,\n payloads: ReactionPayload<TEvents>[]\n) => Promise<HandleResult>;\n\n/** `Act.handle_batch`. */\nexport type HandleBatch<TEvents extends Schemas> = (\n lease: Lease,\n payloads: ReactionPayload<TEvents>[],\n batchHandler: BatchHandler<TEvents>\n) => Promise<HandleResult>;\n\ntype DrainCycle<TEvents extends Schemas> = {\n readonly leased: Lease[];\n readonly fetched: Fetch<TEvents>;\n readonly handled: HandleResult[];\n readonly acked: Lease[];\n readonly blocked: BlockedLease[];\n readonly closeable: CloseTarget[];\n};\n\n/**\n * Blocks a stream whose retries were all spent losing the lease (no handler\n * error ever reached the block decision). Strictly `> maxRetries`: the final\n * attempt runs at `=== maxRetries`. Stands down while the store is failing,\n * since `claim` counts retries no handler earned.\n */\nfunction budget_exhausted<TEvents extends Schemas>(\n lease: Lease,\n options: ReactionPayload<TEvents>[\"options\"] | undefined,\n store_failing: boolean\n): HandleResult | undefined {\n if (\n store_failing ||\n !options?.blockOnError ||\n lease.retry <= options.maxRetries\n )\n return undefined;\n const error = `Blocking ${lease.stream} after ${lease.retry} claims with no acknowledged progress — the retry budget (${options.maxRetries}) was spent without the handler ever reporting an error. That means every attempt lost its lease before it could ack: move the reaction to a lane whose leaseMillis covers the handler, then unblock the stream.`;\n log().error(error);\n return { lease, handled: 0, acked_at: lease.at, error, block: true };\n}\n\n/**\n * A failed fetch has no payloads to say which reaction it was for, so take\n * the most conservative policy: block only if every reaction does, after\n * the largest budget.\n */\nfunction fetch_failure_policy<\n TSchemaReg extends SchemaRegister<TActions>,\n TEvents extends Schemas,\n TActions extends Schemas,\n>(registry: Registry<TSchemaReg, TEvents, TActions>): ReactionOptions {\n let blockOnError = true;\n let maxRetries = 0;\n for (const register of Object.values(registry.events))\n for (const reaction of register.reactions.values()) {\n blockOnError &&= reaction.options.blockOnError;\n maxRetries = Math.max(maxRetries, reaction.options.maxRetries);\n }\n return { blockOnError, maxRetries };\n}\n\n/** A resolver's error, and the options of the reaction it belongs to. */\ntype ResolverFailure = { error: Error; options: ReactionOptions };\n\n/**\n * The one retry-or-block decision for a stream that failed: a handler,\n * a resolver, or the stream's own fetch. The error string always rides\n * the result; the drain decides whether to ack partial progress from\n * `handled > 0`, not from the error.\n */\nexport function finalize(\n lease: Lease,\n handled: number,\n at: number,\n error: Error | undefined,\n options: ReactionOptions,\n logger: Logger,\n failed_at?: number\n): HandleResult {\n if (!error) return { lease, handled, acked_at: at };\n logger.error(error);\n // A `NonRetryableError` from the handler short-circuits the retry\n // budget — block on first attempt when the operator has opted in via\n // `blockOnError`. When `blockOnError` is false, the operator has\n // explicitly chosen \"retry forever,\" so we don't override that.\n const non_retryable = error instanceof NonRetryableError;\n const block =\n options.blockOnError &&\n (non_retryable || lease.retry >= options.maxRetries);\n if (block)\n logger.error(\n non_retryable\n ? `Blocking ${lease.stream} on non-retryable error.`\n : `Blocking ${lease.stream} after ${lease.retry} retries.`\n );\n // Every retry is paced by the reaction's backoff, or the default one;\n // terminal blocks never defer. `lease.retry` here is the just-failed\n // attempt's counter, so the delay paces the *next* attempt.\n const next_attempt_at = block\n ? undefined\n : Date.now() +\n compute_backoff_delay(lease.retry, options.backoff ?? DEFAULT_BACKOFF);\n return {\n lease,\n handled,\n acked_at: at,\n error: error.message,\n block,\n next_attempt_at,\n failed_at,\n };\n}\n\n/** Reported once per declaration; every key part is declared, so it stays bounded. */\nfunction warn_misrouted(\n seen: Set<string>,\n stream: string,\n handler: string,\n event: string\n): void {\n report_once(\n seen,\n `${stream}|${handler}|${event}`,\n `Reaction \"${handler}\" on \"${event}\" resolved to target \"${stream}\", which a projection already serves. ` +\n \"A target is served by one batch handler or one state projection, so this reaction can never run — and delivering to it would hand the projection an aggregate from another stream. \" +\n \"Skipping it. The equivalent static `.to({ target })` is rejected at build; a dynamic resolver's target is only knowable here.\"\n );\n}\n\ntype CycleInput = {\n readonly lagging: number;\n readonly leading: number;\n readonly eventLimit: number;\n readonly leaseMillis: number;\n readonly misrouted: Set<string>;\n readonly store_failing: boolean;\n};\n\n/** One drain cycle; `undefined` when nothing was claimed. */\nasync function run_drain_cycle<\n TEvents extends Schemas,\n TActions extends Schemas,\n TSchemaReg extends SchemaRegister<TActions>,\n>(\n deps: DrainControllerDeps<TEvents, TActions, TSchemaReg>,\n cycle: CycleInput\n): Promise<DrainCycle<TEvents> | undefined> {\n const { ops, registry, batch_handlers, handle, handle_batch, lane } = deps;\n const {\n lagging,\n leading,\n eventLimit,\n leaseMillis,\n misrouted,\n store_failing,\n } = cycle;\n const leased = await ops.claim(\n lagging,\n leading,\n randomUUID(),\n leaseMillis,\n lane\n );\n if (!leased.length) return undefined;\n\n const fetched = await ops.fetch(leased, eventLimit);\n\n type FetchEntry = (typeof fetched)[number];\n const fetch_map = new Map<\n string,\n {\n fetch: FetchEntry;\n payloads: ReactionPayload<TEvents>[];\n failed?: ResolverFailure;\n }\n >();\n\n const fetch_window_at = fetched.reduce(\n (max, { at, events }) => Math.max(max, events.at(-1)?.id || at),\n 0\n );\n\n for (const f of fetched) {\n const { stream, events } = f;\n let failed: ResolverFailure | undefined;\n const payloads = events.flatMap((event) => {\n const register = registry.events[event.name];\n if (!register) return [];\n return [...register.reactions.values()]\n .filter((reaction) => {\n const resolver = reaction.resolver;\n const dynamic = typeof resolver === \"function\";\n let resolved: Resolved | undefined;\n try {\n resolved = dynamic ? resolver(event) : resolver;\n } catch (error) {\n failed ??= {\n error: new Error(\n `Resolver of reaction \"${reaction.handler.name}\" threw on ${String(event.name)} #${event.id} (stream \"${event.stream}\"): ${String(error)}`\n ),\n options: reaction.options,\n };\n return false;\n }\n if (!resolved || resolved.target !== stream) return false;\n // A dynamic resolution onto a projection's target: skip and report.\n // Not a throw, which would read as a store failure.\n if (!dynamic || !batch_handlers.has(stream)) return true;\n warn_misrouted(\n misrouted,\n stream,\n reaction.handler.name,\n String(event.name)\n );\n return false;\n })\n .map((reaction) => ({ ...reaction, event }));\n });\n fetch_map.set(stream, { fetch: f, payloads, failed });\n }\n\n const handled = await Promise.all(\n leased.map((lease) => {\n const entry = fetch_map.get(lease.stream)!;\n // Retried after the default backoff; blocks once the budget is spent,\n // unless the whole store is failing (the breaker's job).\n if (entry.fetch.error !== undefined) {\n const policy = fetch_failure_policy(registry);\n return Promise.resolve(\n finalize(\n lease,\n 0,\n lease.at,\n new Error(`Fetch failed for ${lease.stream}: ${entry.fetch.error}`),\n store_failing ? { ...policy, blockOnError: false } : policy,\n deps.logger\n )\n );\n }\n // A resolver threw: this stream fails like a handler would.\n if (entry.failed)\n return Promise.resolve(\n finalize(\n lease,\n 0,\n lease.at,\n entry.failed.error,\n entry.failed.options,\n deps.logger\n )\n );\n // fast-forward watermark using fetched events or window max\n const at = entry.fetch.events.at(-1)?.id || fetch_window_at;\n const { payloads } = entry;\n const exhausted = budget_exhausted(\n lease,\n payloads[0]?.options,\n store_failing\n );\n if (exhausted) return Promise.resolve(exhausted);\n const batchHandler = batch_handlers.get(lease.stream);\n if (batchHandler && payloads.length > 0) {\n return handle_batch({ ...lease, at }, payloads, batchHandler);\n }\n return handle({ ...lease, at }, payloads);\n })\n );\n\n // `block` before `ack`: block needs the lease, ack releases it. A\n // partial-progress block goes to both. Deferred and backing-off entries\n // carry `due`, so one `ack` also persists the schedule (defer: retry -1).\n // Most passes block nothing; an empty call would still cost the store a\n // write transaction.\n const to_block = handled\n .filter(({ block }) => block)\n .map(({ lease, error }) => ({ ...lease, error: error! }));\n const blocked = to_block.length ? await ops.block(to_block) : [];\n\n // Before the `ack`, so an ack failure can't lose the terminal event.\n if (blocked.length) deps.on_blocked(blocked);\n\n const submitted = handled.flatMap((h, i) => {\n const advance = h.handled > 0 ? h.acked_at : leased[i].at;\n return h.defer !== undefined\n ? { ...h.lease, at: advance, due: h.defer, retry: -1 }\n : h.next_attempt_at !== undefined\n ? { ...h.lease, at: advance, due: h.next_attempt_at }\n : h.handled > 0 || !h.error\n ? { ...h.lease, at: h.acked_at }\n : [];\n });\n const acked = submitted.length ? await ops.ack(submitted) : [];\n\n // `ack` drops entries whose lease another worker took (deferred entries\n // are never returned).\n const expected = submitted.filter((l) => l.due === undefined).length;\n if (acked.length < expected)\n log().warn(\n `drain: ${expected - acked.length} of ${expected} acks were dropped — the lease was taken by another worker mid-handler. That work will be redelivered (at-least-once), but persistent drops mean leaseMillis is too short for this handler.`\n );\n\n const closeable = handled\n .filter((h) => h.close !== undefined)\n .map((h) => h.close!);\n\n return { leased, fetched, handled, acked, blocked, closeable };\n}\n\nconst EMPTY_DRAIN: Drain<Schemas> = {\n fetched: [],\n leased: [],\n acked: [],\n blocked: [],\n};\n\n/** One drain made of several: every lane of a pass, or every pass of a settle. */\nexport function merge_drains<TEvents extends Schemas>(\n drains: ReadonlyArray<Drain<TEvents>>\n): Drain<TEvents> {\n return {\n fetched: drains.flatMap((d) => d.fetched),\n leased: drains.flatMap((d) => d.leased),\n acked: drains.flatMap((d) => d.acked),\n blocked: drains.flatMap((d) => d.blocked),\n };\n}\n\nexport type DrainControllerDeps<\n TEvents extends Schemas,\n TActions extends Schemas,\n TSchemaReg extends SchemaRegister<TActions>,\n> = {\n readonly logger: Logger;\n readonly ops: DrainOps<TEvents>;\n readonly registry: Registry<TSchemaReg, TEvents, TActions>;\n readonly batch_handlers: Map<string, BatchHandler<TEvents>>;\n readonly handle: Handle<TEvents>;\n readonly handle_batch: HandleBatch<TEvents>;\n readonly on_acked: (acked: Lease[]) => void;\n readonly on_blocked: (blocked: BlockedLease[]) => void;\n /** Awaited, so a slow close doesn't overlap the next claim. */\n readonly on_close: (targets: CloseTarget[]) => Promise<void>;\n readonly breaker: CircuitBreaker;\n /** The worker ticks outside any caller frame, so its drain is re-scoped. */\n readonly run_scoped: <T>(fn: () => Promise<T>) => Promise<T>;\n /** Lane this controller drains. Undefined spans all lanes. */\n readonly lane?: string;\n /** The lane's own config; it wins over the caller's DrainOptions. */\n readonly defaults?: {\n readonly streamLimit?: number;\n readonly leaseMillis?: number;\n };\n};\n\n/** Wake key for the controller's own retry; no stream is named \"\". */\nconst RETRY = \"\";\n\nexport class DrainController<\n TEvents extends Schemas,\n TActions extends Schemas,\n TSchemaReg extends SchemaRegister<TActions>,\n> {\n // Armed while `_raised` is ahead of `_lowered` (the raise count the last\n // empty claim saw), so a claim never lowers over a raise that landed\n // during it.\n private _raised = 0;\n private _lowered = 0;\n private _ratio = 0.5;\n // Local wake at the earliest parked (backoff or defer) visit, or at the\n // lease expiry after a failed pass (the {@link RETRY} key); the schedule\n // itself is persisted. On an idle app nothing else would drain it. It\n // drains until a pass leases nothing or the controller stops, and an entry\n // stays until handled or until a later pass claims nothing.\n private readonly _defer = new DeferTimer(() => {\n this.arm();\n void this._deps.run_scoped(async () => {\n while ((await this.drain()).leased.length > 0);\n });\n });\n private _worker: ReturnType<typeof setTimeout> | undefined;\n private readonly _misrouted = new Set<string>();\n private _stopped = false;\n // The pass in flight. Never rejects; graceful shutdown waits on it.\n private _inflight: Promise<Drain<TEvents>> | undefined;\n\n private readonly _deps: DrainControllerDeps<TEvents, TActions, TSchemaReg>;\n\n constructor(deps: DrainControllerDeps<TEvents, TActions, TSchemaReg>) {\n this._deps = deps;\n }\n\n arm(): void {\n this._raised++;\n }\n\n /** Cold start: re-seed a persisted `deferred_at` into the local wake. */\n seed_defer(stream: string, at: number): void {\n this._defer.set(stream, at);\n this._defer.schedule();\n }\n\n get armed(): boolean {\n return this._raised !== this._lowered;\n }\n\n get inflight(): Promise<Drain<TEvents>> | undefined {\n return this._inflight;\n }\n\n /** This lane's configured lease, or `undefined`; the shutdown grace basis. */\n get lease_millis(): number | undefined {\n return this._deps.defaults?.leaseMillis;\n }\n\n get lane(): string | undefined {\n return this._deps.lane;\n }\n\n /**\n * Drains every `cycleMs` while armed; the unref'd timer never holds the\n * process. Called once, when the controller is built.\n */\n start(cycleMs: number): void {\n // `drain()` never throws.\n const run = this._deps.run_scoped;\n const tick = async () => {\n if (this.armed) await run(() => this.drain());\n if (this._stopped) return;\n this._worker = setTimeout(tick, cycleMs);\n this._worker.unref();\n };\n this._worker = setTimeout(tick, cycleMs);\n this._worker.unref();\n }\n\n stop(): void {\n this._stopped = true;\n if (this._worker) {\n clearTimeout(this._worker);\n this._worker = undefined;\n }\n this._defer.stop();\n }\n\n async drain(options: DrainOptions = {}): Promise<Drain<TEvents>> {\n // A stopped controller claims nothing, so a pass shutdown's grace\n // outlived can't start work after teardown.\n // One pass at a time: a call while one runs claims nothing.\n if (!this.armed || this._stopped || this._inflight)\n return EMPTY_DRAIN as Drain<TEvents>;\n\n const d = this._deps.defaults ?? {};\n // A lane's own budget wins over caller options.\n const streamLimit =\n d.streamLimit ?? options.streamLimit ?? DEFAULT_STREAM_LIMIT;\n const eventLimit = options.eventLimit ?? DEFAULT_EVENT_LIMIT;\n const leaseMillis =\n d.leaseMillis ?? options.leaseMillis ?? DEFAULT_LEASE_MILLIS;\n\n // Circuit open: stay armed and leave the wake alone (re-aiming would fire\n // at once for anything due); the breaker's own wake re-aims it.\n if (this._deps.breaker.state(Date.now()) === \"open\")\n return EMPTY_DRAIN as Drain<TEvents>;\n\n const pass = this._pass(streamLimit, eventLimit, leaseMillis).finally(\n () => {\n this._inflight = undefined;\n }\n );\n this._inflight = pass;\n return pass;\n }\n\n // One claim → fetch → handle → ack pass. Never throws.\n private async _pass(\n streamLimit: number,\n eventLimit: number,\n leaseMillis: number\n ): Promise<Drain<TEvents>> {\n try {\n const lagging = Math.ceil(streamLimit * this._ratio);\n const leading = streamLimit - lagging;\n\n const started = Date.now();\n const raised = this._raised;\n const cycle = await run_drain_cycle(this._deps, {\n lagging,\n leading,\n eventLimit,\n leaseMillis,\n misrouted: this._misrouted,\n store_failing: this._deps.breaker.failing,\n });\n\n if (!cycle) {\n // Caught up: whatever was due when this pass started has no work.\n this._defer.prune(started);\n this._deps.breaker.passed();\n // Lowers only the raises it saw: one that landed during the claim\n // (an unblock, a reset) brought work this claim couldn't see.\n this._lowered = raised;\n return EMPTY_DRAIN as Drain<TEvents>;\n }\n\n const { leased, fetched, handled, acked, blocked, closeable } = cycle;\n\n trace_cycle(this._deps.logger, leased, fetched, handled, acked, blocked);\n\n this._ratio = compute_lag_lead_ratio(handled, lagging, leading);\n\n for (const lease of acked) this._defer.delete(lease.stream);\n for (const lease of blocked) this._defer.delete(lease.stream);\n for (const h of handled) {\n const next = h.defer ?? h.next_attempt_at;\n if (next !== undefined) this._defer.set(h.lease.stream, next);\n }\n\n // Listener throws are contained in `Act.emit`.\n if (acked.length) this._deps.on_acked(acked);\n // The orchestrator contains close failures; anything that still\n // throws here reaches the breaker.\n if (closeable.length) await this._deps.on_close(closeable);\n\n // After `on_close`, so a failed close never counts as a store success.\n this._deps.breaker.passed();\n\n return { fetched, leased, acked, blocked };\n } catch (error) {\n // A store op threw: stay armed and retry after the breaker's cooldown,\n // never before this pass's leases expire, so an idle app retries\n // without waiting for the breaker to open.\n this._defer.set(\n RETRY,\n Date.now() + Math.max(leaseMillis, this._deps.breaker.cooldown_ms)\n );\n this._deps.breaker.failed(Date.now(), error);\n return EMPTY_DRAIN as Drain<TEvents>;\n } finally {\n // Re-aim at the earliest stream still parked.\n if (!this._stopped) this._defer.schedule();\n }\n }\n}\n","/**\n * Per-reaction retry backoff delay computation. Pure function — keeps\n * `DrainController` and `finalize` (in `drain-cycle.ts`) testable in isolation.\n */\n\nimport type { BackoffOptions } from \"../types/action.js\";\n\n/**\n * Compute the wall-clock delay (in ms) to wait before the next attempt on\n * a stream whose handler just failed.\n *\n * @param retry - The lease's `retry` counter at finalize time. `0` is the\n * first attempt that failed; `1` is after one retry; etc.\n * @param opts - Per-reaction backoff config. Returns `0` when undefined.\n * @returns Non-negative integer milliseconds. Always `0` when `opts` is\n * undefined or `baseMs <= 0`.\n */\nexport function compute_backoff_delay(\n retry: number,\n opts: BackoffOptions | undefined\n): number {\n if (!opts || opts.baseMs <= 0) return 0;\n const r = Math.max(0, retry);\n let delay: number;\n switch (opts.strategy) {\n case \"fixed\":\n delay = opts.baseMs;\n break;\n case \"linear\":\n delay = opts.baseMs * (r + 1);\n break;\n case \"exponential\":\n delay = opts.baseMs * 2 ** r;\n if (opts.maxMs !== undefined) delay = Math.min(delay, opts.maxMs);\n break;\n default: {\n // Unreachable once options pass `resolveBackoffConfig` at their\n // declaration site. Defensive so the pure function is total and can\n // never emit `NaN` from an unvalidated strategy — throw instead.\n const _never: never = opts.strategy;\n throw new Error(`unknown backoff strategy: ${String(_never)}`);\n }\n }\n if (opts.jitter) delay = delay * (0.5 + Math.random());\n return Math.max(0, Math.floor(delay));\n}\n","/**\n * The shared \"next visit time\" primitive. A `DeferTimer` holds a\n * `stream → due-time` map and a single collapsed wake timer: it parks\n * streams that should be re-visited later and fires one `on_wake` callback\n * at the earliest pending due-time.\n *\n * The {@link \"drain-cycle\".DrainController} rides it for per-reaction\n * backoff (a retry's `next_attempt_at`) and for the `defer` outcome, which\n * holds a stream pending without advancing the watermark or bumping `retry`.\n * The wake runs a drain, and the drain re-schedules the timer when it ends.\n * An entry stays until its stream is acked or blocked, re-parked, or a\n * drain that started after it came due claims nothing ({@link prune}): a\n * wake that lands during another drain, or a pass that reaches only some of\n * the due streams, leaves the rest due, so the next re-schedule fires again\n * at once.\n *\n * Lives in process memory, per worker — the same per-worker pacing trade-off\n * documented for backoff. Durability comes from the data the due-time is\n * *derived* from (an un-advanced watermark, an event's `created` timestamp),\n * not from the map. A restart empties the map, so the cold-start rebuild is\n * explicit: `CorrelateCycle.init` seeds each still-future `deferred_at` back\n * onto the owning lane's timer via {@link \"drain-cycle\".DrainController.seed_defer},\n * so an idle deferred stream re-arms at its due-time with no\n * intervening commit.\n */\n\n/**\n * Node's `setTimeout` delay is a 32-bit signed int (~24.8 days). A larger\n * delay overflows and fires immediately, so we cap at this and re-arm.\n */\nconst MAX_TIMER_DELAY_MS = 2_147_483_647;\n\n/** A linear scan finds the earliest entry: the map is bounded by claim limits. */\nexport class DeferTimer {\n private readonly _due = new Map<string, number>();\n private _timer: ReturnType<typeof setTimeout> | undefined;\n private readonly _on_wake: () => void;\n\n /**\n * @param on_wake - invoked once each time the earliest due-time elapses.\n * The consumer re-schedules for whatever is still parked.\n */\n constructor(on_wake: () => void) {\n this._on_wake = on_wake;\n }\n\n /** Number of currently parked streams. */\n get size(): number {\n return this._due.size;\n }\n\n /**\n * Park `stream` for a re-visit at `at` (ms since epoch). A plain\n * overwrite: the caller computes the authoritative next-visit for the\n * stream (the drain's `handle` already reconciles a stream's reactions\n * into one result per cycle), so there is no stale value to merge against.\n */\n set(stream: string, at: number): void {\n this._due.set(stream, at);\n }\n\n /** Drop `stream` from the parked set (e.g. on a successful ack or block). */\n delete(stream: string): void {\n this._due.delete(stream);\n }\n\n /**\n * Drop every entry due at or before `before`. The drain calls it when a\n * pass that started at `before` claimed nothing: whatever was due by then\n * was handled elsewhere (another worker) or has no work left, so waking\n * for it again would spin.\n */\n prune(before: number): void {\n for (const [stream, at] of this._due)\n if (at <= before) this._due.delete(stream);\n }\n\n /**\n * (Re)schedule the wake timer at the earliest pending due-time. Idempotent\n * — collapses many parked streams into a single timer. A no-op clears any\n * pending timer when the map is empty.\n *\n * The timer is `unref()`-ed so pending re-visits never keep the process\n * alive on their own.\n */\n schedule(): void {\n if (this._timer) clearTimeout(this._timer);\n if (this._due.size === 0) {\n this._timer = undefined;\n return;\n }\n let earliest = Number.POSITIVE_INFINITY;\n for (const t of this._due.values()) if (t < earliest) earliest = t;\n // A longer due-time (a 90-day autoclose cooldown) wakes at the ceiling;\n // the entry stays and the consumer re-schedules for the rest.\n const delay = Math.min(\n Math.max(0, earliest - Date.now()),\n MAX_TIMER_DELAY_MS\n );\n this._timer = setTimeout(() => {\n this._timer = undefined;\n this._on_wake();\n }, delay);\n this._timer.unref();\n }\n\n /** Cancel any pending wake timer. Idempotent. Leaves the parked set intact. */\n stop(): void {\n if (this._timer) {\n clearTimeout(this._timer);\n this._timer = undefined;\n }\n }\n}\n","/**\n * Adaptive lag-to-lead ratio for the dual-frontier drain strategy.\n *\n * The orchestrator splits its per-cycle stream budget between two frontiers:\n *\n * - **lagging** — newly subscribed or behind streams catching up.\n * - **leading** — actively-processing streams at the head of the log.\n *\n * After each cycle, this helper looks at how many events were actually\n * handled in each frontier and shifts the next cycle's split toward\n * whichever frontier had the higher per-stream throughput. The result is\n * clamped to `[0.2, 0.8]` so neither frontier can be starved.\n */\n\nimport type { HandleResult } from \"./drain-cycle.js\";\n\n/** Floor / ceiling for the lag-to-lead ratio so neither frontier starves. */\nconst RATIO_MIN = 0.2;\nconst RATIO_MAX = 0.8;\n/** Default ratio when no events were handled in either frontier. */\nconst RATIO_DEFAULT = 0.5;\n\n/**\n * Compute the next lag-to-lead ratio from the cycle's handled events and\n * the frontier sizes used to claim them. Returns `RATIO_DEFAULT` when no\n * progress was made (nothing to base a decision on).\n */\nexport function compute_lag_lead_ratio(\n handled: ReadonlyArray<HandleResult>,\n lagging: number,\n leading: number\n): number {\n let lagging_handled = 0;\n let leading_handled = 0;\n for (const { lease, handled: count } of handled) {\n if (lease.lagging) lagging_handled += count;\n else leading_handled += count;\n }\n const lagging_avg = lagging > 0 ? lagging_handled / lagging : 0;\n const leading_avg = leading > 0 ? leading_handled / leading : 0;\n const total = lagging_avg + leading_avg;\n if (total === 0) return RATIO_DEFAULT;\n return Math.max(RATIO_MIN, Math.min(RATIO_MAX, lagging_avg / total));\n}\n","/**\n * One-shot reporting for a misdeclaration a build-time guard can't see: a\n * `.to(fn)` target, lane or priority is only known once an event arrives,\n * so correlate and drain apply those rules and report what breaks them.\n * A resolver fires for every matching event, so reporting once per\n * declaration is what keeps the log readable.\n *\n * The key is the whole design: build it only from what the declaration\n * names (handler, event, lane, a static target), never from a value a\n * resolver computed. A resolved target is the trap: the per-aggregate shape\n * `.to(e => ({ target: e.stream }))` would turn one typo into one line per\n * aggregate. Runtime values still belong in the message, as the example.\n *\n * Never throws: a throw in correlate pins the checkpoint for the whole app,\n * and in drain it reaches the breaker as a store failure.\n */\n\nimport { log } from \"../ports.js\";\n\n/**\n * Report `message` the first time `key` is seen. `seen` belongs to the\n * caller, since `internal/` holds no module state.\n */\nexport function report_once(\n seen: Set<string>,\n key: string,\n message: string\n): void {\n if (seen.has(key)) return;\n seen.add(key);\n log().error(new Error(message));\n}\n","/**\n * The default correlation-id generator. Apps plug in their own scheme\n * through {@link ActOptions.correlator}.\n */\n\nimport { randomInt } from \"node:crypto\";\nimport type { Actor, Correlator } from \"../types/index.js\";\n\nconst BASE = 36;\nconst SEG_WIDTH = 4;\nconst SEG_SPACE = BASE ** SEG_WIDTH;\n\nfunction seg(n: number): string {\n return n.toString(BASE).padStart(SEG_WIDTH, \"0\");\n}\n\n/**\n * Default {@link Correlator}. Produces ids of the form\n * `{state[:4]}-{action[:4]}-{4 ms}{4 random}` — 18 characters, lowercase\n * base36.\n *\n * - Prefix carries human-meaningful context (state + action) so operators\n * can identify a workflow at a glance in logs and query results.\n * - The 4-character `Date.now() % 36^4` segment wraps every ~28 minutes,\n * long enough that adjacent inserts in a typical workflow share B-tree\n * pages — index locality, not global sortability, is the goal.\n * - The 4-character random tail gives 1.68M values per ms; collision risk\n * across K=100 concurrent workers is roughly K² / 3.4M per ms.\n *\n * Names shorter than 4 chars are used as-is (no padding) so a state named\n * `Tx` produces `tx-...` rather than `tx00-...`.\n */\nexport const default_correlator: Correlator = ({ state, action }) => {\n const s = state.slice(0, SEG_WIDTH).toLowerCase();\n const a = action.slice(0, SEG_WIDTH).toLowerCase();\n const ts = seg(Date.now() % SEG_SPACE);\n const rnd = seg(randomInt(SEG_SPACE));\n return `${s}-${a}-${ts}${rnd}`;\n};\n\n/**\n * Resolves the correlation id for the close-the-books transaction.\n * Close runs outside any user action, so we synthesize a context with\n * sentinel state/action names — visible in the id when overrides aren't\n * configured.\n */\nexport function close_correlation(\n correlator: Correlator,\n actor: Actor\n): string {\n return correlator({\n state: \"$close\",\n action: \"close\",\n stream: \"$close\",\n actor,\n });\n}\n","/**\n * Pipeline operations consumed by the drain/correlate loop. Each op is a\n * single async step the orchestrator invokes per drain cycle:\n *\n * - `claim` — atomically discover and lock streams for processing\n * - `fetch` — read events for each leased stream\n * - `ack` — release leases for successfully handled streams\n * - `block` — flag leases that exceeded the retry budget\n * - `subscribe` — register newly correlated streams with the store\n *\n * This module exposes only the bare implementations as plain async functions,\n * mirroring the shape of {@link \"event-sourcing\"}. Trace decoration is\n * layered on top in {@link \"tracing\"} and selected by the orchestrator at\n * construction time. No tracing imports here.\n */\n\nimport { isStreamName } from \"../adapter.js\";\nimport { store } from \"../ports.js\";\nimport type {\n BlockedLease,\n Committed,\n Fetch,\n Lease,\n Schemas,\n SubscribeInput,\n SubscribeResult,\n} from \"../types/index.js\";\n\nexport interface DrainOps<TEvents extends Schemas> {\n claim: typeof claim;\n fetch: typeof fetch<TEvents>;\n ack: typeof ack;\n block: typeof block;\n subscribe: typeof subscribe;\n}\n\nexport const claim = (\n lagging: number,\n leading: number,\n by: string,\n millis: number,\n lane?: string\n): Promise<Lease[]> => store().claim(lagging, leading, by, millis, lane);\n\nexport async function fetch<TEvents extends Schemas>(\n leased: Lease[],\n eventLimit: number\n): Promise<Fetch<TEvents>> {\n return Promise.all(\n leased.map(async ({ stream, source, at, lagging }) => {\n const events: Committed<TEvents, keyof TEvents>[] = [];\n // A literal `source` fetches with `stream_exact` so an exact name\n // like \"s1\" reads only \"s1\" — never a sibling prefix \"s12\". A\n // pattern source (e.g. `^(A|B)$`) stays a regex query, matching the\n // same streams correlate resolved it for.\n const stream_exact =\n source !== undefined && isStreamName(source, stream) ? true : undefined;\n try {\n await store().query<TEvents>((e) => events.push(e), {\n stream: source,\n stream_exact,\n after: at,\n limit: eventLimit,\n });\n } catch (error) {\n // Contain it per stream. These reads are already per-stream, but they\n // shared one `Promise.all`, so one stream's failure rejected the whole\n // cycle and every healthy stream leased beside it got nothing —\n // an unreadable `pii` payload on one aggregate stalled unrelated\n // reactions. The cycle turns this into a no-progress failure\n // for THIS stream only, which the retry budget then escalates.\n //\n // Unlike correlate, this read cannot simply decline the payload:\n // handlers receive it (through their own gate), so a fetch that\n // dropped it would hand them a silently incomplete event.\n return {\n stream,\n source,\n at,\n lagging,\n events: [],\n error: (error as Error)?.message ?? String(error),\n } as const;\n }\n return { stream, source, at, lagging, events } as const;\n })\n );\n}\n\n// Finalize: acks and defers in one atomic store call. Leases\n// carrying `due` are deferred, the rest acked — a failed finalize lands\n// nothing, and redelivery covers every outcome uniformly.\nexport const ack = (leases: Lease[]): Promise<Lease[]> => store().ack(leases);\n\nexport const block = (leases: BlockedLease[]): Promise<BlockedLease[]> =>\n store().block(leases);\n\nexport const subscribe = (\n streams: SubscribeInput[],\n correlated_at?: number,\n correlator?: { key: string; by: string; millis: number }\n): Promise<SubscribeResult> =>\n store().subscribe(streams, correlated_at, correlator);\n","/**\n * Event-sourcing primitives: `snap`, `load`, `action`, `tombstone`, `scan`.\n * Bare implementations; tracing wraps them in `tracing.ts`.\n */\n\nimport { patch } from \"@rotorsoft/act-patch\";\nimport { prettifyError, ZodError, type ZodType } from \"zod\";\nimport { cache, log, store } from \"../ports.js\";\nimport {\n ConcurrencyError,\n PreconditionError,\n StreamClosedError,\n ValidationError,\n} from \"../types/errors.js\";\nimport type {\n CacheEntry,\n Committed,\n DoOptions,\n Emitted,\n EventMeta,\n EventSource,\n Load,\n LoadTarget,\n Message,\n PatchFn,\n ScanOptions,\n ScanResult,\n Schema,\n Schemas,\n Snapshot,\n State,\n Target,\n} from \"../types/index.js\";\nimport {\n REDACTED,\n SHREDDED,\n SNAP_EVENT,\n TOMBSTONE_EVENT,\n} from \"../types/index.js\";\nimport { sleep, validate } from \"../utils.js\";\nimport { compute_backoff_delay } from \"./backoff.js\";\nimport { default_correlator } from \"./correlation-id.js\";\n\n/** The default patch step: a bare merge, so the hot path pays nothing. */\nexport const bare_patch: PatchFn = (_me, state, partial) =>\n patch(state, partial) as typeof state;\n\nconst value_at = (value: unknown, path: readonly PropertyKey[]): unknown =>\n path.reduce<unknown>(\n (at, key) => (at as Record<PropertyKey, unknown> | undefined)?.[key],\n value\n );\n\n/**\n * Checks the state an action leaves against the state's schema (its\n * invariants), without replacing it: a schema with defaults or transforms\n * never rewrites a valid state. A throwing refinement refuses like a failed\n * one, as `validate` does for payloads.\n *\n * A sensitive state is folded through the committing actor's view, so a\n * value it can't read arrives as `[REDACTED]` or `[SHREDDED]`. Those come\n * only from stored history, which passed this check with the real value,\n * so their issues are dropped.\n */\nconst check_invariants = <TState extends Schema>(\n target: string,\n state: TState,\n schema: ZodType<TState>,\n pii_aware: boolean\n): void => {\n let result: ReturnType<typeof schema.safeParse>;\n try {\n result = schema.safeParse(state);\n } catch (error) {\n throw new ValidationError(target, state, error);\n }\n if (result.success) return;\n const issues = pii_aware\n ? result.error.issues.filter((issue) => {\n const value = value_at(state, issue.path);\n return value !== REDACTED && value !== SHREDDED;\n })\n : result.error.issues;\n if (issues.length)\n throw new ValidationError(\n target,\n state,\n prettifyError(new ZodError(issues))\n );\n};\n\nconst DEFAULT_BATCH = 500;\n\n/** `action` with the correlator and patch step bound by `build_es`. */\ntype BoundAction = <\n TState extends Schema,\n TEvents extends Schemas,\n TActions extends Schemas,\n TKey extends keyof TActions,\n>(\n me: State<TState, TEvents, TActions>,\n action: TKey,\n target: Target,\n payload: Readonly<TActions[TKey]>,\n options?: DoOptions<TEvents>\n) => Promise<Snapshot<TState, TEvents>[]>;\n\nexport interface EsOps {\n snap: typeof snap;\n load: typeof load;\n action: BoundAction;\n tombstone: typeof tombstone;\n}\n\n/** Writes a cache checkpoint. A failure only costs the next load a re-fold. */\nconst cache_put = <TState extends Schema>(\n stream: string,\n entry: CacheEntry<TState>\n): Promise<void> =>\n cache()\n .set(stream, entry)\n .catch((err) =>\n log().warn(\n err,\n \"cache set skipped; the next load re-folds from the store\"\n )\n );\n\n/** Drops a cache checkpoint. A failure leaves a stale one, which re-folds. */\nconst cache_drop = (stream: string): Promise<void> =>\n cache()\n .invalidate(stream)\n .catch((err) =>\n log().warn(\n err,\n \"cache invalidate skipped; a stale checkpoint re-folds from its event_id\"\n )\n );\n\n/** Commits a snapshot event. Never throws: a failed snapshot must not fail the action. */\nexport async function snap<TState extends Schema, TEvents extends Schemas>(\n snapshot: Snapshot<TState, TEvents>\n): Promise<Committed<TEvents, keyof TEvents> | undefined> {\n const { id, stream, name, meta, version } = snapshot.event!;\n try {\n const [committed] = await store().commit(\n [\n {\n stream,\n msgs: [{ name: SNAP_EVENT, data: snapshot.state }],\n // IMPORTANT! - state events are committed right after the snapshot event\n expectedVersion: version,\n },\n ],\n {\n correlation: meta.correlation,\n causation: { event: { id, name: name as string, stream } },\n }\n );\n return committed as Committed<TEvents, keyof TEvents>;\n } catch (error) {\n const reason = error instanceof Error ? error.message : String(error);\n log().warn(\n `Snapshot write failed on stream \"${stream}\": ${reason} — cold starts will replay full history until snapshots succeed.`\n );\n }\n}\n\n/**\n * Commits the close guard at `expectedVersion`; `undefined` when the stream\n * moved. Actions then see the tombstone at head and throw {@link StreamClosedError}.\n */\nexport async function tombstone(\n stream: string,\n expectedVersion: number,\n correlation: string\n): Promise<Committed<Schemas, keyof Schemas> | undefined> {\n try {\n const [committed] = await store().commit(\n [\n {\n stream,\n msgs: [{ name: TOMBSTONE_EVENT, data: {} }],\n expectedVersion,\n },\n ],\n { correlation, causation: {} }\n );\n return committed;\n } catch (error) {\n if (error instanceof ConcurrencyError) return undefined;\n throw error;\n }\n}\n\n/**\n * Rejects a negative version or an invalid `created` Date. Duplicate ids and\n * version gaps are left to the sink (partial backups have gaps).\n */\nfunction is_valid(event: Committed<Schemas, keyof Schemas>): boolean {\n if (event.version < 0) return false;\n if (!(event.created instanceof Date) || Number.isNaN(event.created.getTime()))\n return false;\n return true;\n}\n\n/**\n * Pages a restore source: validation, drop filters, migrations, progress and\n * causation remap. Adapters supply only the per-event insert `callback`\n * (see {@link Store.restore}). A source that ignores `limit` (`CsvFile`)\n * returns everything in one page.\n */\nexport async function scan(\n source: EventSource,\n opts: ScanOptions = {},\n callback?: (event: Committed<Schemas, keyof Schemas>) => Promise<number>\n): Promise<Omit<ScanResult, \"duration_ms\">> {\n const {\n drop_snapshots = false,\n drop_closed_streams = false,\n on_progress,\n event_migrations,\n stream_rename,\n } = opts;\n const limit = opts.batch_size ?? DEFAULT_BATCH;\n const id_map = new Map<number, number>();\n let kept = 0;\n let dropped_snaps = 0;\n let dropped_closed = 0;\n let migrated_count = 0;\n let processed = 0;\n let at: number | undefined;\n\n // `drop_closed_streams`: one extra walk to collect tombstoned streams.\n const closed_streams = new Set<string>();\n if (drop_closed_streams) {\n await source.query<Schemas>(\n (e) => {\n if (e.name === TOMBSTONE_EVENT) closed_streams.add(e.stream);\n },\n { names: [TOMBSTONE_EVENT] }\n );\n }\n\n // Probe the highest id (an index seek on SQL stores). A source that\n // ignores the filter returns more than one row; leave max_id unknown.\n let max_id: number | undefined;\n const probed = await source.query<Schemas>(\n (e) => {\n max_id = e.id;\n },\n { backward: true, limit: 1, with_snaps: true }\n );\n if (probed !== 1) max_id = undefined;\n\n while (true) {\n let got = 0;\n let id: number | undefined;\n\n await source.query<Schemas>(\n async (event) => {\n got++;\n id = event.id;\n processed++;\n if (!is_valid(event))\n throw new Error(`Invalid event at index ${processed}`);\n if (on_progress) on_progress({ processed, id: event.id, max_id });\n if (drop_snapshots && event.name === SNAP_EVENT) {\n dropped_snaps++;\n return;\n }\n if (\n closed_streams.has(event.stream) &&\n event.name !== TOMBSTONE_EVENT\n ) {\n // Keep the tombstone: it is what keeps the stream closed.\n dropped_closed++;\n return;\n }\n // Before the causation remap, so `id_map` stays keyed by source id.\n let migrated: typeof event = event;\n const migration = event_migrations?.[event.name as string];\n if (migration) {\n const old_data = migration.from_schema.parse(event.data);\n const new_data = migration.migrate(old_data);\n migration.to_schema.parse(new_data);\n migrated = {\n ...event,\n name: migration.to as typeof event.name,\n data: new_data as any,\n };\n migrated_count++;\n }\n if (stream_rename) {\n const renamed = stream_rename(migrated.stream);\n if (renamed !== migrated.stream)\n migrated = { ...migrated, stream: renamed };\n }\n if (!callback) {\n kept++;\n return;\n }\n // Spread `migrated`, not `event`, or the migration is undone.\n let remapped = migrated;\n const { action, event: cause } = migrated.meta.causation;\n if (cause || (stream_rename && action)) {\n remapped = {\n ...migrated,\n meta: {\n ...migrated.meta,\n causation: {\n ...migrated.meta.causation,\n ...(action &&\n stream_rename && {\n action: { ...action, stream: stream_rename(action.stream) },\n }),\n ...(cause && {\n event: {\n ...cause,\n // A cause missing from the source has no id in the new\n // log; its old id would name another event there.\n id: id_map.get(cause.id) ?? -1,\n stream: stream_rename\n ? stream_rename(cause.stream)\n : cause.stream,\n },\n }),\n },\n },\n };\n }\n const new_id = await callback(remapped);\n id_map.set(event.id, new_id);\n kept++;\n },\n { after: at, limit, with_snaps: true }\n );\n\n // Stop on a short page, or on an oversized one (the source ignored the\n // limit and already returned everything).\n if (got !== limit) break;\n at = id;\n }\n\n return {\n kept,\n migrated: migrated_count,\n dropped: {\n closed_streams: dropped_closed,\n snapshots: dropped_snaps,\n },\n };\n}\n\n/**\n * Folds a stream into state, from the cached checkpoint or the latest\n * snapshot. `asOf` time-travels and bypasses the cache.\n */\nexport async function load<\n TState extends Schema,\n TEvents extends Schemas,\n TActions extends Schemas,\n>(\n me: State<TState, TEvents, TActions>,\n target: LoadTarget,\n callback?: (snapshot: Snapshot<TState, TEvents>) => void,\n patch_fn: PatchFn = bare_patch\n): Promise<Snapshot<TState, TEvents>> {\n const { stream, actor, asOf } = target;\n const time_travel =\n !!asOf && Object.values(asOf).some((v) => v !== undefined);\n // `limit` and `created_after` read a slice of the real events, without a seed.\n const seeded =\n time_travel && asOf!.limit === undefined && !asOf!.created_after;\n const cached = time_travel ? undefined : await cache().get<TState>(stream);\n const cache_hit = !!cached;\n let state = cached?.state ?? (me.init ? me.init() : ({} as TState));\n let patches = cached?.patches ?? 0;\n let snaps = cached?.snaps ?? 0;\n // Events this load processed; `patches` is the snap distance from the cache.\n let replayed = 0;\n let event: Committed<TEvents, keyof TEvents> | undefined;\n\n await store().query<TEvents>(\n (raw) => {\n // Time travel folds the real events. A snapshot only seeds it, holding what\n // a prune or a restart took, so it counts only as the first row.\n if (seeded && raw.name === SNAP_EVENT && replayed > 0) return;\n event = me.view(raw, actor);\n if (event.name === SNAP_EVENT) {\n state = event.data as TState;\n snaps++;\n patches = 0;\n replayed++;\n } else if (me.patch[event.name]) {\n state = patch_fn(me, state, me.patch[event.name](event, state), event);\n patches++;\n replayed++;\n } else if (event.name !== TOMBSTONE_EVENT) {\n // A renamed event, the wrong state, or a contaminated stream.\n log().warn(\n `Skipping unknown event \"${String(event.name)}\" on stream \"${stream}\" (id=${event.id}) — no reducer in state \"${me.name}\"`\n );\n }\n callback?.({\n event,\n state,\n version: event.version,\n id: event.id,\n patches,\n snaps,\n cache_hit,\n replayed,\n });\n },\n {\n stream,\n stream_exact: true,\n // `with_snaps` on every non-time-travel load: cold, it resumes from the\n // latest snapshot; warm, it keeps a snapshot above a stale checkpoint,\n // so a windowed close's prune can't fold the tail onto stale state.\n ...(cached\n ? { after: cached.event_id, with_snaps: true }\n : seeded\n ? // From the start, past the resume floor, which could jump over the\n // time bound. The snapshots are for the seed.\n { with_snaps: true, after: -1, ...asOf }\n : time_travel\n ? asOf\n : { with_snaps: true }),\n }\n );\n\n // A stale write self-corrects: the next load replays past its `event_id`.\n // Not at a tombstone head, or `action()`'s closed check would pass vacuously.\n const head_is_tombstone = event?.name === TOMBSTONE_EVENT;\n if (\n replayed > 0 &&\n !time_travel &&\n event &&\n !me.pii_aware &&\n !head_is_tombstone\n ) {\n await cache_put(stream, {\n stream,\n state,\n version: event.version,\n event_id: event.id,\n patches,\n snaps,\n });\n }\n\n return {\n event,\n state,\n version: event?.version ?? cached?.version ?? -1,\n // Captured with `state`, so consumers never race a separate cache lookup.\n id: event?.id ?? cached?.event_id ?? -1,\n patches,\n snaps,\n cache_hit,\n replayed,\n };\n}\n\n/** A stream an action may append to (its own, or one of its loads'), with the events it emits there. */\ntype Pending = {\n readonly state: State<any, any, any>;\n readonly stream: string;\n readonly snapshot: Snapshot<any, any>;\n readonly expected: number;\n readonly events: { name: string; data: Schema }[];\n};\n\n/**\n * Loads the other streams an action's decision needs, all at once. A target\n * returning `undefined` skips its load. A target can name a stream from the\n * caller's input, so an empty name, the action's own stream or another load's\n * refuses the action, as a rule would. A load of a closed stream throws.\n */\nasync function load_others(\n loads: readonly Load[],\n payload: Schema,\n own: { stream: string; state: Schema },\n actor: Target[\"actor\"],\n patch_fn: PatchFn,\n refuse: (description: string) => Error\n): Promise<(Pending | undefined)[]> {\n const streams = loads.map((l) => l.target(payload, own.state));\n streams.forEach((stream, i) => {\n if (stream === undefined) return;\n if (typeof stream !== \"string\" || !stream)\n throw refuse(`loads \"${loads[i].name}\" from an empty stream name`);\n if (stream === own.stream) throw refuse(`loads its own stream \"${stream}\"`);\n if (streams.indexOf(stream) !== i)\n throw refuse(`loads stream \"${stream}\" twice`);\n });\n return Promise.all(\n loads.map(async (l, i) => {\n const stream = streams[i];\n if (stream === undefined) return undefined;\n const snapshot = await load(\n l.state,\n { stream, actor },\n undefined,\n patch_fn\n );\n if (snapshot.event?.name === TOMBSTONE_EVENT)\n throw new StreamClosedError(stream);\n return {\n state: l.state,\n stream,\n snapshot,\n expected: snapshot.version,\n events: [],\n };\n })\n );\n}\n\n/**\n * Validates, checks preconditions, folds, checks the invariants and commits.\n * An action with loads appends to every stream it emits to in one commit,\n * each guarded by its version at load. On {@link ConcurrencyError} it\n * re-runs from `load` within the action's `maxRetries`; any other error\n * rethrows.\n *\n * Returns the snapshots of every stream appended to, the action's own first.\n */\nexport async function action<\n TState extends Schema,\n TEvents extends Schemas,\n TActions extends Schemas,\n TKey extends keyof TActions,\n>(\n me: State<TState, TEvents, TActions>,\n action: TKey,\n target: Target,\n payload: Readonly<TActions[TKey]>,\n options?: DoOptions<TEvents>,\n patch_fn: PatchFn = bare_patch\n): Promise<Snapshot<TState, TEvents>[]> {\n const { stream, expectedVersion, actor } = target;\n if (!stream) throw new Error(\"Missing target stream\");\n // `Act.do` already filled in the ambient reaction context.\n const reactingTo = options?.reactingTo;\n const correlator = options?.correlator ?? default_correlator;\n\n const validated = validate(action as string, payload, me.actions[action]);\n\n const opts = me.options?.[action];\n const max_retries = opts?.maxRetries ?? 0;\n const loads = me.loads?.[action] ?? [];\n\n for (let attempt = 0; ; attempt++) {\n try {\n const snapshot = await load(\n me,\n { stream, actor: target.actor },\n undefined,\n patch_fn\n );\n if (snapshot.event?.name === TOMBSTONE_EVENT)\n throw new StreamClosedError(stream);\n // `version`, not `event`: on a warm hit `event` is undefined. A new\n // stream expects -1, so two callers creating it can't both commit.\n const own: Pending = {\n state: me,\n stream,\n snapshot,\n expected: expectedVersion ?? snapshot.version,\n events: [],\n };\n const others = loads.length\n ? await load_others(\n loads,\n validated,\n { stream, state: snapshot.state },\n target.actor,\n patch_fn,\n (description) =>\n new PreconditionError(\n action,\n validated,\n target,\n snapshot,\n description\n )\n )\n : [];\n const loaded = Object.fromEntries(\n others.map((p, i) => [loads[i].name, p?.snapshot.state])\n );\n\n // Preconditions in declaration order: the first that fails refuses\n // the action.\n for (const { holds, description } of me.requires?.[action] ?? [])\n if (!holds(validated, snapshot.state, actor, loaded))\n throw new PreconditionError(\n action,\n validated,\n target,\n snapshot,\n description\n );\n\n const result = me.on[action](validated, snapshot, target, loaded);\n if (!result || (Array.isArray(result) && !result.length))\n return [snapshot];\n\n const tuples = Array.isArray(result[0])\n ? (result as Emitted<TEvents>[]) // array of tuples\n : ([result] as Emitted<TEvents>[]); // single tuple\n\n // An event listed on a load goes to that load's stream, and is dropped\n // when the load was skipped; the state's own events go to its own stream.\n for (const [name, data] of tuples) {\n const event = name as string;\n const i = loads.findIndex((l) => l.events.includes(event));\n if (i >= 0 && !others[i]) continue;\n const to = i >= 0 ? others[i] : name in me.events ? own : undefined;\n if (!to)\n throw new Error(\n `Action \"${action as string}\" emitted \"${event}\", which isn't an event of \"${me.name}\" and isn't listed on any of its loads`\n );\n to.events.push({\n name: event,\n data: validate(event, data, to.state.events[event]),\n });\n }\n // The action's own stream records the decision, so an action that\n // appends to other streams appends to its own too.\n if (!own.events.length)\n throw new Error(\n `Action \"${action as string}\" appends only to the streams it loads; it must append an event to its own stream too`\n );\n const appends = [own, ...others].filter(\n (p): p is Pending => !!p?.events.length\n );\n\n const meta: EventMeta = {\n correlation:\n reactingTo?.meta.correlation ||\n correlator({\n action: action as string,\n state: me.name,\n stream,\n actor: target.actor,\n }),\n causation: {\n action: {\n name: action as string,\n ...target,\n // payload intentionally omitted\n },\n event: reactingTo\n ? {\n id: reactingTo.id,\n name: reactingTo.name as string,\n stream: reactingTo.stream,\n }\n : undefined,\n },\n };\n\n // Fold before the commit (the decider rule), so a state that breaks\n // its schema (the invariants) is refused before anything is stored.\n // Each event folds onto its own stream's state. Reducers see the event\n // data and the next version; the store assigns `id` and `created`, so\n // they get placeholders here (`-1`, the commit time).\n const created = new Date();\n const folds = appends.map((p) => {\n let { state, patches } = p.snapshot;\n const folded = p.events.map((e, i) => {\n const event = {\n ...e,\n id: -1,\n stream: p.stream,\n version: p.snapshot.version + i + 1,\n created,\n meta,\n };\n const patch = p.state.patch[event.name](event, state);\n state = patch_fn(p.state, state, patch, event);\n patches++;\n return { state, patch, patches };\n });\n // Once per stream, on the state the action leaves: invariants hold\n // between actions, not between one action's events.\n check_invariants(\n `${p.state.name}.${action as string}`,\n state,\n p.state.state,\n p.state.pii_aware\n );\n return folded;\n });\n\n let committed: Committed<Schemas, keyof Schemas>[];\n try {\n committed = await store().commit<Schemas>(\n appends.map((p) => ({\n stream: p.stream,\n msgs: p.events.map((e) => p.state.message(e)) as Message<\n Schemas,\n string\n >[],\n expectedVersion: p.expected,\n })),\n meta\n );\n } catch (error) {\n // Fire-and-forget, so a cache failure can't replace the ConcurrencyError.\n if (error instanceof ConcurrencyError) void cache_drop(error.stream);\n throw error;\n }\n\n // The stored rows come back in append order, then event order, with\n // the real `id` and `created`; the states are already folded. The\n // caller sent the plaintext, so no view/gate round-trip.\n let row = 0;\n const snapshots: Snapshot<any, any>[] = [];\n for (const [a, append] of appends.entries()) {\n const { snapshot: base, state: owner } = append;\n const appended = append.events.map((e, i) => {\n const stored = committed[row++];\n const fold = folds[a][i];\n return {\n event: { ...stored, data: e.data },\n state: fold.state,\n version: stored.version,\n id: stored.id,\n patches: fold.patches,\n snaps: base.snaps,\n patch: fold.patch,\n cache_hit: base.cache_hit,\n replayed: base.replayed,\n };\n });\n const last = appended.at(-1)!;\n\n // Awaited, so the cache holds the post-snap checkpoint for the next caller.\n const snap_event = owner.snap?.(last) ? await snap(last) : undefined;\n\n // Sensitive states depend on the actor, so they aren't cached.\n if (!owner.pii_aware)\n void cache_put(append.stream, {\n stream: append.stream,\n state: last.state,\n version: snap_event?.version ?? last.event.version,\n event_id: snap_event?.id ?? last.event.id,\n patches: snap_event ? 0 : last.patches,\n snaps: snap_event ? last.snaps + 1 : last.snaps,\n });\n // The snapshot is the stream's head now, so a version pinned from this\n // result doesn't refuse the caller's own next action.\n if (snap_event)\n appended[appended.length - 1] = {\n ...last,\n version: snap_event.version,\n };\n snapshots.push(...appended);\n }\n\n return snapshots;\n } catch (error) {\n if (!(error instanceof ConcurrencyError)) throw error;\n // A caller-pinned version would conflict again on every retry.\n if (expectedVersion !== undefined && error.stream === stream) throw error;\n if (attempt >= max_retries) throw error;\n if (opts?.backoff) {\n const delay_ms = compute_backoff_delay(attempt, opts.backoff);\n if (delay_ms > 0) await sleep(delay_ms);\n }\n }\n }\n}\n","/**\n * Centralized observability for the framework's internal pipelines.\n *\n * Trace decorators wrap a bare implementation with `logger.trace(...)` calls\n * at well-defined moments — entry points for {@link \"event-sourcing\"} (`load`,\n * `snap`, `action`) and exit points for the {@link \"drain\"} pipeline (`claim`,\n * `fetch`, `ack`, `block`, `subscribe`). `action` logs both on entry and\n * after its commit.\n *\n * Output styles:\n * - **Pretty mode** (`config().env !== \"production\"`) — event-sourcing logs\n * show only the colored target body (color carries the operation/phase),\n * drain logs keep a colored caption.\n * - **Plain mode** (production / log aggregators) — every log gets a textual\n * prefix; event-sourcing uses `caption: body`, drain uses `caption body`.\n *\n * The two factories — {@link build_es} and {@link build_drain} — let the\n * orchestrator choose bare or traced variants once at `.build()` time based\n * on the configured log level. Outside this module, no other source file\n * imports tracing primitives.\n */\n\nimport { config } from \"../config.js\";\nimport type {\n AsOf,\n Correlator,\n Logger,\n PatchFn,\n Schemas,\n} from \"../types/index.js\";\nimport { default_correlator } from \"./correlation-id.js\";\nimport type { DrainOps } from \"./drain-ops.js\";\nimport * as drain from \"./drain-ops.js\";\nimport type { EsOps } from \"./event-sourcing.js\";\nimport * as es from \"./event-sourcing.js\";\n\ntype AsyncFn = (...args: any[]) => Promise<any>;\n\nconst PRETTY = config().env !== \"production\";\n\n// 256-color codes for distinctive, theme-friendly hues\nconst C_BLUE = \"\\x1b[38;5;39m\"; // vivid sky blue (action)\nconst C_ORANGE = \"\\x1b[38;5;208m\"; // true orange (committed)\nconst C_GREEN = \"\\x1b[38;5;42m\"; // emerald (load)\nconst C_MAGENTA = \"\\x1b[38;5;165m\"; // bright magenta (snap)\nconst C_DRAIN = \"\\x1b[38;5;244m\"; // muted gray for all drain ops\n// load-trace cache marker shades — distinguishable from C_GREEN body color\nconst C_HIT = \"\\x1b[38;5;82m\"; // lime — fast path, blends visually\nconst C_MISS = \"\\x1b[38;5;220m\"; // amber — non-trivial work happened\nconst C_RESET = \"\\x1b[0m\";\n\n/**\n * Format an event-sourcing trace line. Pretty mode renders just the colored\n * body (the color is the cue for which op/phase fired); plain mode prepends\n * `caption: ` so log aggregators stay readable without ANSI.\n */\nconst es_caption = (caption: string, color: string, body: string): string =>\n PRETTY ? `${color}${body}${C_RESET}` : `${caption}: ${body}`;\n\n/**\n * Format a drain-pipeline caption. Drain logs keep a `>>` marker for easy\n * spotting in mixed log streams, plus a `caption` (past tense — every drain\n * trace fires on exit). All drain ops share one color (gray) so the pipeline\n * reads as a single channel; the caption disambiguates the phase. Lane\n * is appended in lilac, unwrapped, when set and non-default,\n * so the operator's eye lands on the lane name without parsing per-stream\n * detail. Per-stream `@at/retry` and fetched event lists are muted via\n * {@link dim} so the stream name itself reads loudest.\n */\nconst C_LANE = \"\\x1b[38;5;183m\"; // lilac — distinct from gray drain + drain ops\nconst C_DIM = \"\\x1b[38;5;240m\"; // dim gray — dimmer than C_DRAIN\nconst C_ERR = \"\\x1b[38;5;196m\"; // bright red — block marker\nconst C_STREAM = \"\\x1b[38;5;226m\"; // bright yellow — target stream names in drain/correlate traces\n\n/** Wrap with the muted color when pretty mode is on. Plain in production. */\nconst dim = (text: string): string =>\n PRETTY ? `${C_DIM}${text}${C_RESET}` : text;\n\n/** Wrap with a foreground color when pretty mode is on; bare in production. */\nconst hue = (color: string, text: string): string =>\n PRETTY ? `${color}${text}${C_RESET}` : text;\n\nconst drain_caption = (caption: string, lane?: string): string => {\n const show_lane = lane && lane !== \"default\";\n if (PRETTY) {\n const tag = `${C_DRAIN}>> ${caption}${C_RESET}`;\n return show_lane ? `${tag} ${C_LANE}${lane}${C_RESET}` : tag;\n }\n return show_lane ? `>> ${caption} ${lane}` : `>> ${caption}`;\n};\n\n/**\n * Format the cache hit/miss marker for the load trace. In pretty mode the\n * word is colored (lime for hit, amber for miss) and the surrounding\n * `C_GREEN` body color is restored after — embedded ANSI inside `es_caption`'s\n * outer wrap. Plain mode returns the bare word.\n */\nconst cache_marker = (hit: boolean): string => {\n const word = hit ? \"hit\" : \"miss\";\n if (!PRETTY) return word;\n return `${hit ? C_HIT : C_MISS}${word}${C_RESET}${C_GREEN}`;\n};\n\n/**\n * Format the load stats (`v=N replayed=N snaps=N patches=N`) for the load\n * trace. Muted gray in pretty mode so the cache marker reads as the most\n * important cue; plain mode returns the bare text.\n *\n * - `v` — stream head version (the version of the last event applied)\n * - `replayed` — events processed by THIS load past the cache point\n * - `snaps` — cumulative snapshots taken on this stream\n * - `patches` — events since the last snap (snap-policy accumulator)\n */\nconst stats_marker = (\n version: number,\n replayed: number,\n snaps: number,\n patches: number\n): string => {\n const text = `v=${version} replayed=${replayed} snaps=${snaps} patches=${patches}`;\n if (!PRETTY) return text;\n return `${C_DRAIN}${text}${C_RESET}${C_GREEN}`;\n};\n\n/**\n * Format the as-of marker for time-travel loads. Surfaces the active filter\n * fields (before id, created_before/after timestamps, limit) so an operator\n * can tell at a glance which slice was loaded. Empty `asOf` returns \"\" —\n * non-time-travel loads skip the marker entirely.\n */\nconst as_of_marker = (asOf: AsOf | undefined): string => {\n if (!asOf) return \"\";\n const parts: string[] = [];\n if (asOf.before !== undefined) parts.push(`before=${asOf.before}`);\n if (asOf.created_before !== undefined)\n parts.push(`created_before=${asOf.created_before.toISOString()}`);\n if (asOf.created_after !== undefined)\n parts.push(`created_after=${asOf.created_after.toISOString()}`);\n if (asOf.limit !== undefined) parts.push(`limit=${asOf.limit}`);\n return parts.length ? ` (as-of ${parts.join(\" \")})` : \" (as-of)\";\n};\n\n/**\n * Wraps an async function with optional `exit` and `entry` callbacks. Each\n * callback fires at the corresponding phase; both receive the call args, and\n * `exit` additionally receives the resolved result. Used to layer\n * `logger.trace` calls onto bare ops without changing their signatures.\n */\nconst traced = <F extends AsyncFn>(\n inner: F,\n exit?: (result: Awaited<ReturnType<F>>, ...args: Parameters<F>) => void,\n entry?: (...args: Parameters<F>) => void\n): F =>\n (async (...args: Parameters<F>) => {\n entry?.(...args);\n const result = (await inner(...args)) as Awaited<ReturnType<F>>;\n exit?.(result, ...args);\n return result;\n }) as F;\n\n/**\n * Selects bare or traced event-sourcing handlers. Called once by the\n * orchestrator constructor.\n */\nexport function build_es(\n logger: Logger,\n correlator: Correlator = default_correlator,\n patch_fn: PatchFn = es.bare_patch\n): EsOps {\n // The app's correlator and patch step are baked into load and action, so\n // callers don't thread them; a per-call correlator wins when it is set.\n const bound_action: EsOps[\"action\"] = (\n me,\n action_name,\n target,\n payload,\n options\n ) =>\n es.action(\n me,\n action_name,\n target,\n payload,\n { ...options, correlator: options?.correlator ?? correlator },\n patch_fn\n );\n const bound_load: EsOps[\"load\"] = (me, target, callback) =>\n es.load(me, target, callback, patch_fn);\n if (logger.level !== \"trace\") {\n return {\n snap: es.snap,\n load: bound_load,\n action: bound_action,\n tombstone: es.tombstone,\n };\n }\n return {\n snap: traced(es.snap, undefined, (snapshot) => {\n logger.trace(\n es_caption(\n \"snap\",\n C_MAGENTA,\n `${snapshot.event!.stream}@${snapshot.event!.version}`\n )\n );\n }),\n load: traced(bound_load, (result, _me, target) => {\n const stats = stats_marker(\n result.version,\n result.replayed,\n result.snaps,\n result.patches\n );\n logger.trace(\n es_caption(\n \"load\",\n C_GREEN,\n `${target.stream}${as_of_marker(target.asOf)} ${cache_marker(result.cache_hit)} ${stats}`\n )\n );\n }),\n action: traced(\n bound_action,\n (snapshots) => {\n // A loaded snapshot (the action emitted nothing) has no `patch`;\n // each event is named with the stream it was appended to.\n if (snapshots[0].patch)\n logger.trace(\n snapshots.map((s) => s.event!.data),\n es_caption(\n \"committed\",\n C_ORANGE,\n snapshots\n .map((s) => `${s.event!.stream}.${s.event!.name}`)\n .join(\", \")\n )\n );\n },\n (_me, action, target, payload) => {\n logger.trace(\n payload as object,\n es_caption(\"action\", C_BLUE, `${target.stream}.${action}`)\n );\n }\n ),\n tombstone: traced(es.tombstone, (committed, stream) => {\n if (committed)\n logger.trace(\n es_caption(\"tombstoned\", C_ORANGE, `${stream}@${committed.version}`)\n );\n }),\n };\n}\n\n/**\n * Selects bare or traced drain-pipeline ops. Called once by the orchestrator\n * constructor.\n */\nexport function build_drain<TEvents extends Schemas>(\n logger: Logger\n): DrainOps<TEvents> {\n // Cycle-level tracing happens in `DrainController.drain()` via\n // {@link trace_cycle} — claim/fetch/ack/block all flow into one log\n // line per cycle to give the operator a single atomic narrative.\n // `subscribe` stays decorated because it's driven from correlate-\n // cycle (not from run_drain_cycle) and doesn't fit the cycle shape.\n return {\n claim: drain.claim,\n fetch: drain.fetch,\n ack: drain.ack,\n block: drain.block,\n subscribe:\n logger.level !== \"trace\"\n ? drain.subscribe\n : traced(drain.subscribe, (result, streams) => {\n if (!result.subscribed) return;\n // Caption mirrors `drained`: lane in the caption when the\n // whole batch shares a single non-default lane. Mixed-lane\n // batches (rare — different correlated targets resolving\n // to different lanes in one scan) fall back to per-stream\n // `[lane]` tags, default-lane streams stay bare either way.\n const lanes = new Set(streams.map((s) => s.lane ?? \"default\"));\n const uniform_lane =\n lanes.size === 1 ? streams[0]?.lane : undefined;\n const data = streams\n .map(({ stream, lane }) =>\n uniform_lane || !lane || lane === \"default\"\n ? hue(C_STREAM, stream)\n : `${hue(C_STREAM, stream)}${dim(`[${lane}]`)}`\n )\n .join(\" \");\n logger.trace(\n `${drain_caption(\"correlated\", uniform_lane)} ${data}`\n );\n }),\n };\n}\n\n/**\n * Emit one cycle-level drain trace summarizing what happened in a\n * single `run_drain_cycle` pass. Per-stream rendering shape — outcome +\n * post-state anchored on the right:\n *\n * stream<-source [events] ✓ @<acked-at> — full success\n * stream<-source [events] ✗ @<failed-at>/<retry> (error) — total failure → blocked\n * stream<-source [events] ⚠ @<failed-at>/<retry> (error) — total failure → retrying\n * stream<-source [events] ✓ @<acked-at> ✗ @<failed-at>/<retry> (error) — partial then blocked\n * stream<-source [events] ✓ @<acked-at> ⚠ @<failed-at>/<retry> (error) — partial then retrying\n * stream<-source ⊘ @<at>/<retry> — deferred (backoff)\n *\n * Partial-success-then-failure is the dual-outcome case: events\n * 1..K succeeded (watermark advanced to K), event K+1 threw. The\n * trace renders both the lime `✓ @K` and the red/amber `✗`/`⚠ @K+1`\n * on the same line so an operator sees \"we made progress *and* then\n * something broke\" at a glance.\n *\n * Lane prefixes the caption in lilac when non-default. The outcome\n * marker and its adjacent post-state share the marker's color so the\n * eye reads \"outcome + where it landed\" as one unit. Per-stream\n * `[events]` and `(error)` stay dim — secondary context.\n */\nexport function trace_cycle<TEvents extends Schemas>(\n logger: Logger,\n leased: ReadonlyArray<{\n readonly stream: string;\n readonly at: number;\n readonly retry: number;\n readonly lane?: string;\n }>,\n fetched: ReadonlyArray<{\n readonly stream: string;\n readonly source?: string;\n readonly events: ReadonlyArray<{\n readonly id: number;\n readonly name: keyof TEvents;\n }>;\n }>,\n handled: ReadonlyArray<{\n readonly lease: { readonly stream: string };\n readonly error?: string;\n readonly block?: boolean;\n readonly failed_at?: number;\n }>,\n acked: ReadonlyArray<{ readonly stream: string; readonly at: number }>,\n blocked: ReadonlyArray<{ readonly stream: string; readonly error: string }>\n): void {\n if (logger.level !== \"trace\" || !leased.length) return;\n const lane = leased[0]?.lane;\n const fetch_by_stream = new Map(fetched.map((f) => [f.stream, f]));\n const acked_by_stream = new Map(acked.map((a) => [a.stream, a.at]));\n const blocked_by_stream = new Map(blocked.map((b) => [b.stream, b.error]));\n // Handled-with-error stays a single index now: `block` discriminates\n // the marker (✗ vs ⚠); the failure exists independently of whether\n // ack happened.\n const failed_by_stream = new Map(\n handled.filter((h) => h.error).map((h) => [h.lease.stream, h] as const)\n );\n const detail = leased\n .map(({ stream, at, retry }) => {\n const f = fetch_by_stream.get(stream);\n // Target stream in yellow so the operator's eye lands on \"which\n // stream did this happen on?\" first; source (the events' origin)\n // stays dim — secondary info.\n const key = f?.source\n ? `${hue(C_STREAM, stream)}${dim(`<-${f.source}`)}`\n : hue(C_STREAM, stream);\n const events = f?.events.length\n ? ` ${dim(\n `[${f.events.map(({ id, name }) => `#${id} ${String(name)}`).join(\", \")}]`\n )}`\n : \"\";\n // Build ack + fail segments independently — both can fire for\n // the same stream in the partial-success-then-failure case.\n const acked_at = acked_by_stream.get(stream);\n const ack_part =\n acked_at !== undefined\n ? hue(C_HIT, `✓ @${acked_at}`) // ✓ + new at in lime\n : \"\";\n const failure = failed_by_stream.get(stream);\n let fail_part = \"\";\n if (failure) {\n // Failed event id when known (per-event path), else falls back\n // to lease.at — the post-fetch watermark — for batch-mode\n // total failures where no single event is \"the one.\"\n const failed_at = failure.failed_at ?? at;\n const blocked_error = blocked_by_stream.get(stream);\n if (blocked_error !== undefined) {\n fail_part = `${hue(C_ERR, `✗ @${failed_at}/${retry}`)} ${dim(`(${blocked_error})`)}`;\n } else {\n fail_part = `${hue(C_MISS, `⚠ @${failed_at}/${retry}`)} ${dim(`(${failure.error})`)}`;\n }\n }\n let tail: string;\n if (ack_part && fail_part) tail = ` ${ack_part} ${fail_part}`;\n else if (ack_part) tail = ` ${ack_part}`;\n else if (fail_part) tail = ` ${fail_part}`;\n else tail = ` ${dim(`⊘ @${at}/${retry}`)}`; // nothing happened\n return `${key}${events}${tail}`;\n })\n .join(\", \");\n logger.trace(`${drain_caption(\"drained\", lane)} ${detail}`);\n}\n","/**\n * Reaction dispatch — what runs inside the drain pipeline once `run_drain_cycle`\n * has fetched events for a leased stream. Two shapes:\n *\n * - per-event `handle`: walks payloads sequentially, running each handler\n * inside the reaction scope so `action()` threads `reactingTo`\n * - bulk `handle_batch`: hands every event for a static-target projection to\n * a single batch callback, enabling one-transaction replays\n *\n * Both finish through the drain's `finalize`, the one retry-or-block\n * decision for every per-stream failure. A handler steers its outcome by\n * throwing `DeferSignal` (hold until due) or {@link CloseSignal} (retire the\n * stream); dispatch turns either into a `HandleResult`.\n */\n\nimport type { ReactionScope } from \"../scoped.js\";\nimport { DeferSignal } from \"../types/errors.js\";\nimport type {\n Actor,\n BatchHandler,\n Committed,\n Lease,\n Logger,\n ReactionPayload,\n Schemas,\n} from \"../types/index.js\";\nimport { resolve_defer_at } from \"./defer-config.js\";\nimport { finalize, type Handle, type HandleBatch } from \"./drain-cycle.js\";\n\n/**\n * The control-flow signal a reaction handler throws to *close* a stream.\n * Like `DeferSignal` it rides the dispatcher's\n * `try/catch`, but where a defer holds the stream for later, a close asks the\n * orchestrator to retire it: `build_handle` turns the signal into a\n * `HandleResult.close` (a {@link CloseTarget}), `run_drain_cycle` acks the\n * triggering event and collects the target, and the `DrainController` hands it\n * to the orchestrator's `on_close` callback, which runs the same\n * `run_close_cycle` machinery as `app.close`.\n *\n * Internal: the compiled autoclose reaction throws it. Closing stays an\n * orchestrator capability — reactions only *signal* the intent, so the public\n * reaction-scoped `IAct` gains no `close`.\n *\n * The autoclose reaction runs on a **synthetic stream** (`source` = the\n * aggregate, `target` = a per-aggregate `__autoclose__` key) so it never\n * shares a watermark with the aggregate's own reactions. That makes the close\n * *target* distinct from the reaction's lease stream, so the signal carries the\n * stream to close explicitly (`stream`); when omitted (a user reaction closing\n * its own stream) it defaults to the lease stream.\n */\nexport class CloseSignal extends Error {\n /**\n * Stream to close. Omitted → the reaction's own lease stream (a self-close).\n * The synthesized autoclose reaction sets it to the aggregate stream, since\n * its lease runs on a synthetic `__autoclose__` target.\n */\n readonly stream?: string;\n /** Optional archive callback to run while the stream is guarded. */\n readonly archive?: () => Promise<void>;\n /**\n * Watermark to ack the requesting reaction to before the close runs. The\n * close-cycle safety guard skips a stream whose subscriptions (matched by\n * source) lag the head; the autoclose reaction's `source` is the aggregate,\n * so it must advance its own watermark to the live head id it evaluated\n * against — otherwise it blocks its own close. Defaults to the triggering\n * event id when omitted.\n */\n readonly at?: number;\n /**\n * Windowed close: prune events older than this cutoff behind\n * the closest safe snapshot instead of retiring the stream. Thrown by\n * the autoclose reaction of a `.autocloses({ keep })` state; flows\n * into {@link CloseTarget.before}. Omitted → a full close.\n */\n readonly before?: Date;\n /**\n * Revisit the requesting reaction at this time. Only useful with an `at`\n * below the head: a reaction runs only when an event is waiting for it.\n */\n readonly defer?: Date;\n\n constructor(opts?: {\n stream?: string;\n archive?: () => Promise<void>;\n at?: number;\n before?: Date;\n defer?: Date;\n }) {\n super(\"reaction requested close\");\n this.name = \"CloseSignal\";\n this.stream = opts?.stream;\n this.archive = opts?.archive;\n this.at = opts?.at;\n this.before = opts?.before;\n this.defer = opts?.defer;\n }\n}\n\n/**\n * What the dispatcher needs from the orchestrator: a logger for retry and\n * error breadcrumbs, and the scope a handler runs inside.\n */\nexport type ReactionDeps<\n TEvents extends Schemas,\n TActions extends Schemas,\n TActor extends Actor = Actor,\n> = {\n readonly logger: Logger;\n /**\n * What a handler runs inside — its `IAct` facade and its triggering-event\n * context — assembled by the orchestrator. How either half works is not\n * this module's business; it receives the scope whole and calls it.\n */\n readonly reaction_scope: ReactionScope<TEvents, TActions, TActor>;\n};\n\n/**\n * Builds the per-event reaction dispatcher passed to `run_drain_cycle`.\n *\n * The triggering event is installed as ambient context around each handler\n * call, so `action()` resolves it as `reactingTo`. Ambient\n * rather than bound to the `IAct` argument, so a handler that dispatches\n * through a captured `app` inherits the chain too.\n */\nexport function build_handle<\n TEvents extends Schemas,\n TActions extends Schemas,\n TActor extends Actor = Actor,\n>(deps: ReactionDeps<TEvents, TActions, TActor>): Handle<TEvents> {\n const { logger, reaction_scope } = deps;\n return async (lease, payloads) => {\n if (payloads.length === 0) return { lease, handled: 0, acked_at: lease.at };\n\n const stream = lease.stream;\n // One event fans out to one payload per matching reaction, and the\n // watermark may only advance past an event once EVERY reaction on it\n // has handled it — acking mid-group would silently drop the remaining\n // reactions on redelivery. Track the last payload index per\n // event id (payloads arrive in event order) so `at` advances exactly\n // when a group completes; `handled` counts completed events, not\n // payloads, so a mid-group failure with no completed events is a\n // no-progress result (no ack, retry counter advances toward\n // `blockOnError` instead of resetting on every partial pass).\n const last_index_of = new Map<number, number>();\n for (let i = 0; i < payloads.length; i++)\n last_index_of.set(payloads[i].event.id, i);\n let at = lease.at;\n let handled = 0;\n\n if (lease.retry > 0)\n logger.warn(\n `Retrying ${stream}@${payloads.at(0)!.event.id} (${lease.retry}).`\n );\n\n for (let i = 0; i < payloads.length; i++) {\n const payload = payloads[i];\n const { event, handler } = payload;\n try {\n // Scoped per payload, not hoisted to the lease: the context has to\n // unwind with the handler so it never reaches the drain cycle, and\n // work a handler started without awaiting has to resume into its\n // own event's frame.\n await reaction_scope.run(event as Committed<Schemas, string>, () =>\n handler(event, stream, reaction_scope.app)\n );\n if (last_index_of.get(event.id) === i) {\n at = event.id;\n handled++;\n }\n } catch (error) {\n // A defer is not a failure: hold the triggering events pending\n // (exclude from ack via `defer`), don't bump `retry`, and re-visit\n // the stream at the carried due-time. `acked_at` is unused on\n // the defer path — drain never acks a deferred result.\n if (error instanceof DeferSignal) {\n let defer: number;\n try {\n defer = resolve_defer_at<TEvents>(error.when, event);\n } catch (invalid) {\n // A schedule the schema rejects fails this reaction like any\n // handler error, as the declarative `.defer` path does; thrown\n // from here it would void the whole drain pass.\n return finalize(\n lease,\n handled,\n at,\n invalid as Error,\n payload.options,\n logger,\n event.id\n );\n }\n return { lease, handled, acked_at: at, defer };\n }\n // A close request advances past the triggering event (so the\n // requesting reaction isn't counted as in-flight by the close-cycle\n // guard) and hands the target to the orchestrator's on_close.\n if (error instanceof CloseSignal)\n return {\n lease,\n handled: handled + 1,\n // Advance to the live head the handler evaluated against (when\n // provided) so the close-cycle guard sees this reaction caught up.\n acked_at: error.at ?? event.id,\n defer: error.defer?.getTime(),\n // Close the signalled stream (the autoclose reaction's aggregate,\n // which differs from its synthetic lease stream); a self-closing\n // user reaction omits it and closes its own lease stream. A\n // carried `before` makes it a windowed close (prune, not retire).\n close: {\n stream: error.stream ?? stream,\n archive: error.archive,\n before: error.before,\n },\n };\n return finalize(\n lease,\n handled,\n at,\n error as Error,\n payload.options,\n logger,\n event.id\n );\n }\n }\n return finalize(lease, handled, at, undefined, payloads[0].options, logger);\n };\n}\n\n/**\n * Builds the bulk reaction dispatcher passed to `run_drain_cycle`. All events\n * for a static-target projection are handed to a single callback so the\n * projection can do one transaction per drain (catch-up replays especially).\n */\nexport function build_handle_batch<TEvents extends Schemas>(\n logger: Logger\n): HandleBatch<TEvents> {\n return async (\n lease: Lease,\n payloads: ReactionPayload<TEvents>[],\n batchHandler: BatchHandler<TEvents>\n ) => {\n const stream = lease.stream;\n // One payload per (event, reaction) pair: an event with several\n // reactions on this target arrives several times in a row. The batch\n // handler gets each event once, in order — handing it the duplicates\n // made a non-idempotent batch count every event once per reaction.\n // The per-event path groups by id for the same reason.\n const events: Committed<TEvents, keyof TEvents & string>[] = [];\n const seen = new Set<number>();\n for (const p of payloads) {\n if (seen.has(p.event.id)) continue;\n seen.add(p.event.id);\n events.push(p.event as Committed<TEvents, keyof TEvents & string>);\n }\n const options = payloads[0].options;\n\n if (lease.retry > 0)\n logger.warn(`Retrying batch ${stream}@${events[0].id} (${lease.retry}).`);\n\n try {\n await batchHandler(events, stream);\n return finalize(\n lease,\n events.length,\n events.at(-1)!.id,\n undefined,\n options,\n logger\n );\n } catch (error) {\n return finalize(lease, 0, lease.at, error as Error, options, logger);\n }\n };\n}\n","/**\n * Synthesis of the online close-the-books reaction. `.autocloses(policy)`\n * is not a sweep: it is a reaction on every event the declaring state owns\n * that evaluates the policy against the LIVE head (so a reopened stream\n * re-evaluates correctly), defers to the cooldown's earliest opening\n * (`head.created + the policy's min after`), and closes via `CloseSignal`\n * once the policy holds.\n *\n * Runs at build time — after the registry is fully merged and before the\n * orchestrator classifies it — so the synthesized dynamic resolver is\n * discovered by `classify_registry` and its target stream subscribed. The\n * registry is complete once the builder finishes; the orchestrator never\n * mutates it.\n */\n\nimport { isStreamName } from \"../adapter.js\";\nimport { store } from \"../ports.js\";\nimport { DeferSignal } from \"../types/errors.js\";\nimport type {\n AutocloseConfig,\n Reaction,\n Registry,\n SchemaRegister,\n Schemas,\n State,\n} from \"../types/index.js\";\nimport { SNAP_EVENT, TOMBSTONE_EVENT } from \"../types/index.js\";\nimport { days_after, days_before_now } from \"./autoclose-policy.js\";\nimport { in_autoclose_window, next_window_open } from \"./autoclose-window.js\";\nimport { DEFAULT_MAX_RETRIES } from \"./config.js\";\nimport { CloseSignal } from \"./reaction-dispatch.js\";\n\n/**\n * Prefix for the synthetic per-aggregate stream the autoclose reaction\n * runs on. `target = \\`${AUTOCLOSE_TARGET_PREFIX}${aggregate}\\``, `source =\n * aggregate` — a watermark distinct from the aggregate's own reactions, so\n * an autoclose defer never short-circuits them. Internal; not a public\n * surface.\n */\nexport const AUTOCLOSE_TARGET_PREFIX = \"__autoclose__:\";\n\n/**\n * Inject one synthesized autoclose reaction per `.autocloses(...)` state\n * into the registry's event registers. The handler resolves ports at call\n * time (`store()`), so the reaction is orchestrator-agnostic. The reactions\n * are synthesized once into the shared registry, so nothing\n * per-Act is captured here — the off-hours window is read from the running\n * Act at resolution time via the injected `read_window`.\n */\nexport function synthesize_autoclose_reactions<\n TSchemaReg extends SchemaRegister<TActions>,\n TEvents extends Schemas,\n TActions extends Schemas,\n>(\n registry: Registry<TSchemaReg, TEvents, TActions>,\n states: ReadonlyMap<string, State<any, any, any>>,\n /**\n * Reads the *running* Act's off-hours window. Injected rather than\n * imported: these reactions are synthesized once into the shared\n * registry and run by every Act built from that builder, so the window\n * has to be resolved per call, and `internal/` never reaches for\n * ambient state itself.\n */\n read_window: () => AutocloseConfig[\"autocloseWindow\"]\n): void {\n for (const st of states.values()) {\n const predicate = st.autoclose;\n if (!predicate) continue;\n const after_windows = st.autoclose_after_windows!;\n const keep_days = st.autoclose_keep_days;\n const archiver = st.archive;\n const reaction: Reaction<TEvents> = {\n // Run on a SYNTHETIC stream — `source` is the aggregate, `target` is a\n // per-aggregate `__autoclose__` key — so the autoclose reaction never\n // shares a watermark with the aggregate's own reactions. A shared\n // watermark would let autoclose's defer short-circuit the aggregate's\n // other reactions (the \"a defer affects all reactions on a stream\"\n // hazard). The close still targets the aggregate (`source`).\n // An anchored stream name would read as a pattern, and a store may refuse\n // it at subscribe, stopping every reaction. Such a stream has no\n // autoclose: `app.close` still closes it.\n resolver: (e) =>\n isStreamName(e.stream)\n ? {\n target: `${AUTOCLOSE_TARGET_PREFIX}${e.stream}`,\n source: e.stream,\n }\n : undefined,\n // Never block on autoclose: a transient query/store error should retry,\n // not quarantine the synthetic stream.\n options: { blockOnError: false, maxRetries: DEFAULT_MAX_RETRIES },\n handler: async (event) => {\n const aggregate = event.stream;\n // Off-hours gating: outside the window, park until the window\n // opens. Derived from the window itself — no polling cadence.\n //\n // Read from the running Act's frame, not from a closure. These\n // reactions are synthesized once into the shared registry and\n // handed by reference to every Act built from the same builder, so\n // a captured window would be the first-built Act's for all of them\n // — and the documented multi-tenant shape is one builder built per\n // tenant.\n const window = read_window();\n if (!in_autoclose_window(window, new Date()))\n throw new DeferSignal({ at: next_window_open(window!, new Date()) });\n // Every policy keys on the *domain* head/count, so snapshots are\n // excluded unconditionally — matching `scan_stream_heads` in\n // close-cycle.ts. `snap()` commits a `__snapshot__` at a higher id\n // right after the triggering domain event, so a terminal commit that\n // crosses a `.snap()` boundary would otherwise make the snapshot the\n // head: `is` never matches (`head.name === \"__snapshot__\"`) and never\n // recovers, `after` measures the cooldown from the snapshot's\n // timestamp, and `reaches:N` counts snapshot events toward N. Only\n // rolling-window (`keep`) policies additionally fetch the tail: the\n // prune decision keys on the oldest *domain* event — after a prune the\n // oldest surviving event is the boundary snapshot, whose age says\n // nothing about whether another prune would be productive.\n const stats = await store().query_stats([aggregate], {\n count: true,\n tail: keep_days !== undefined ? true : undefined,\n exclude: [TOMBSTONE_EVENT, SNAP_EVENT],\n });\n const entry = stats.get(aggregate);\n // No live (non-tombstone) head → already closed, nothing to do.\n if (!entry) return;\n const head = entry.head;\n // `count` is always present — query_stats is called with\n // `count: true` above, so the option contract guarantees it.\n if (predicate(aggregate, head, entry.count!))\n throw new CloseSignal({\n stream: aggregate,\n archive: archiver ? () => archiver(aggregate, head) : undefined,\n // Ack this reaction's own watermark to the live head so the\n // close-cycle guard (which matches subscriptions by source =\n // aggregate) sees it caught up instead of blocking its own close.\n at: head.id,\n });\n // Rolling window: when the oldest domain event has aged out of the\n // window, stage a windowed close — prune the prefix older than the\n // cutoff behind the closest safe snapshot. `tail` is present\n // whenever the stats entry is (same non-excluded event set).\n if (keep_days !== undefined) {\n const cutoff = days_before_now(keep_days);\n if (entry.tail!.created < cutoff) {\n // A terminate window still ahead needs a wake, and only a pending\n // event can give one: hold the head unconsumed and revisit. The\n // hold also caps the prune below the head, which a later `is` or\n // `after` has to read. The first visit parks on the real tail.\n const waiting = after_windows.some(\n (days) => days_after(head.created, days).getTime() > Date.now()\n );\n throw new CloseSignal({\n stream: aggregate,\n before: cutoff,\n archive: archiver\n ? () => archiver(aggregate, head, cutoff)\n : undefined,\n at: waiting ? head.id - 1 : head.id,\n defer: waiting ? days_after(new Date(), 1) : undefined,\n });\n }\n }\n // Not eligible yet: park on the earliest derivable due-time — the\n // day a terminate cooldown opens and/or the day the oldest\n // domain event ages out of the rolling window. Neither → wait for\n // the next event to re-trigger (e.g. a `reaches` threshold).\n const dues: Date[] = [];\n for (const days of after_windows)\n dues.push(days_after(head.created, days));\n if (keep_days !== undefined)\n dues.push(days_after(entry.tail!.created, keep_days));\n // Only defer to a FUTURE due-time. A due already in the past (the\n // stream idled longer than the cooldown while the AND-combined\n // predicate stayed unmet) can never be excluded by `claim`, which\n // skips only future `deferred_at` — so a past defer would be\n // re-claimed every cycle (perpetual query_stats burn). When\n // nothing is future, fall through and return: advance the watermark\n // and wait for the next event to re-trigger.\n const future = dues\n .map((d) => d.getTime())\n .filter((t) => t > Date.now());\n if (future.length)\n throw new DeferSignal({ at: new Date(Math.min(...future)) });\n },\n };\n const key = `__autoclose_${st.name}`;\n for (const event_name of Object.keys(st.events)) {\n registry.events[event_name as keyof TEvents]?.reactions.set(\n key,\n reaction as Reaction<TEvents, keyof TEvents>\n );\n }\n }\n}\n","/**\n * Pure orchestration of the close-the-books flow: scan stream heads,\n * partition by reaction safety, guard with tombstones, optionally seed\n * restart state, run user archive callbacks, atomically truncate, and\n * update the cache.\n *\n * Also home to the pieces a closer needs around the cycle: the per-stream\n * {@link CloseLock} and the bounded {@link catch_up_correlation}. The Act\n * orchestrator only wires its ports in and emits `\"closed\"`.\n */\n\nimport { isStreamName } from \"../adapter.js\";\nimport { cache, store } from \"../ports.js\";\nimport type {\n CloseResult,\n CloseTarget,\n Logger,\n Schema,\n State,\n} from \"../types/index.js\";\nimport { SNAP_EVENT, TOMBSTONE_EVENT } from \"../types/index.js\";\nimport { AUTOCLOSE_TARGET_PREFIX } from \"./autoclose-reaction.js\";\nimport type { EsOps } from \"./event-sourcing.js\";\nimport { walk_streams } from \"./walk-streams.js\";\n\n/**\n * Dependencies the close cycle needs from the Act orchestrator. Decoupled\n * from `Act` itself so the cycle can be exercised from tests in isolation.\n */\nexport type CloseCycleDeps = {\n /** Whether any event has a reaction; without one nothing can be pending. */\n readonly reactive: boolean;\n readonly event_to_state: ReadonlyMap<string, State<any, any, any>>;\n readonly load: EsOps[\"load\"];\n readonly tombstone: EsOps[\"tombstone\"];\n readonly logger: Logger;\n /**\n * Correlation id for the close transaction. Caller (`Act.close`)\n * computes this via the configured {@link Correlator}, so close\n * commits share the user's chosen id scheme instead of stamping a\n * UUID.\n */\n readonly correlation: string;\n /**\n * Page size for the safety probe's `query_streams` pagination.\n * Defaults to {@link SAFETY_PROBE_PAGE_SIZE}; production callers omit\n * it, tests set a small value to exercise the multi-page path.\n */\n readonly probe_page_size?: number;\n /** See {@link catch_up_correlation}. */\n readonly catch_up_correlation: (until: number) => Promise<number>;\n /** See {@link CloseLock}; identity when run in isolation. */\n readonly with_stream_lock?: <T>(\n stream: string,\n work: () => Promise<T>\n ) => Promise<T>;\n /**\n * Drop retired streams from correlate's in-process \"already subscribed\"\n * set, so a later scan re-issues `subscribe()` for them. An operator may\n * reclaim a retired subscription row while this process runs; forgetting\n * keeps the in-process view from outliving it, which would otherwise stop\n * delivery to a target named after the stream. Skipped in isolation.\n */\n readonly forget_subscribed?: (streams: string[]) => void;\n};\n\n/**\n * Scan window and pass cap for {@link catch_up_correlation}. Bounded, so a\n * close behind a large backlog skips the stream (the documented retryable\n * outcome) rather than scanning the whole log inside an operator call.\n */\nconst CLOSE_CATCH_UP_LIMIT = 1000;\nconst CLOSE_CATCH_UP_PASSES = 20;\n\n/**\n * Advance correlation until the read cursor reaches `until`, and report\n * where it landed. The safety probe cannot judge a subscription's pending\n * work over events correlate has not resolved yet, and an autoclose often\n * fires from an uncorrelated trigger; anything still above the cursor is\n * held back as pending.\n *\n * Stops as soon as a pass makes no progress (the log has no more to give),\n * and after {@link CLOSE_CATCH_UP_PASSES} windows.\n */\nexport async function catch_up_correlation(\n cursor: { readonly checkpoint: number; arm(): void },\n correlate: (limit: number) => Promise<unknown>,\n until: number\n): Promise<number> {\n for (\n let pass = 0;\n pass < CLOSE_CATCH_UP_PASSES && cursor.checkpoint < until;\n pass++\n ) {\n const before = cursor.checkpoint;\n // Force the scan: the armed flag can't say whether a tail exists.\n cursor.arm();\n await correlate(CLOSE_CATCH_UP_LIMIT);\n if (cursor.checkpoint <= before) break;\n }\n return cursor.checkpoint;\n}\n\n/**\n * Per-stream serialization for close critical sections: two closers of the\n * same stream never prune or archive concurrently (a manual close has no\n * drain lease to exclude an autoclose), and a second full closer never\n * mistakes the first one's tombstone for an interrupted close. Different\n * streams proceed in parallel. One instance per Act.\n */\nexport class CloseLock {\n private readonly _tails = new Map<string, Promise<unknown>>();\n\n /** Run `work` after every earlier close of `stream` has settled. */\n run<T>(stream: string, work: () => Promise<T>): Promise<T> {\n const prev = this._tails.get(stream) ?? Promise.resolve();\n // Chain after the previous holder however it settled, so a failed close\n // can't wedge the lock.\n const next = prev.then(work, work);\n this._tails.set(stream, next);\n // Drop the tail once settled, unless a later waiter replaced it.\n const cleanup = () => {\n if (this._tails.get(stream) === next) this._tails.delete(stream);\n };\n next.then(cleanup, cleanup);\n return next;\n }\n}\n\n/**\n * Page size for the safety probe's keyset pagination over the\n * subscriptions table. Above `query_streams`'s default `limit` of 100\n * to keep the round-trip count low while bounding per-page work.\n */\nconst SAFETY_PROBE_PAGE_SIZE = 1000;\n\n/**\n * Per-stream scan result: the latest domain event's metadata. The scan\n * reads `query_stats` heads with snapshots and tombstones excluded, so\n * `last_event_name` is always a domain event's name; `resumed_guard` marks\n * a stream whose real head is a tombstone from an interrupted close.\n */\ntype StreamHead = {\n readonly max_id: number;\n readonly version: number;\n readonly last_event_name: string;\n /**\n * Set when the stream already carries a tombstone but still holds domain\n * events — a close that wrote its guard and was then interrupted before\n * truncating (a throwing archive callback, or a `truncate` that failed).\n * Carries the existing guard's event id so the retry resumes at Phase 4\n * instead of re-tombstoning (which would fail the version guard) or being\n * dropped from the scan entirely.\n */\n readonly resumed_guard?: { readonly id: number };\n};\n\n/**\n * Run the full close cycle for the given targets. Caller owns the\n * lifecycle event emission.\n *\n * Targets carrying a `before` cutoff take the **windowed** branch — a\n * pure prefix delete behind an existing snapshot (see\n * {@link run_windowed_closes}); the rest run the guarded\n * tombstone/restart pipeline below.\n */\nexport async function run_close_cycle(\n targets: CloseTarget[],\n deps: CloseCycleDeps\n): Promise<CloseResult> {\n // Caller (Act.close) filters empty targets; run_close_cycle assumes at\n // least one target.\n const target_map = new Map(targets.map((t) => [t.stream, t]));\n for (const t of target_map.values()) {\n if (t.before !== undefined && t.restart)\n throw new Error(\n `close: \\`before\\` and \\`restart\\` are mutually exclusive (stream \"${t.stream}\") — a windowed close keeps the stream live behind a real snapshot; restart reseeds it`\n );\n }\n const windowed = [...target_map.values()].filter(\n (t) => t.before !== undefined\n );\n const full = [...target_map.values()].filter((t) => t.before === undefined);\n const skipped: string[] = [];\n const windowed_result = windowed.length\n ? await run_windowed_closes(windowed, deps, skipped)\n : new Map();\n if (!full.length) return { truncated: windowed_result, skipped };\n const truncated = await with_stream_locks(\n full.map((t) => t.stream),\n deps,\n () => run_full_closes(full, target_map, deps, skipped)\n );\n // A tombstone seed retired the stream; a snapshot seed restarted it.\n const retired = [...truncated.entries()]\n .filter(([, r]) => r.committed.name === TOMBSTONE_EVENT)\n .map(([stream]) => stream);\n if (retired.length) deps.forget_subscribed?.(retired);\n for (const [stream, entry] of windowed_result) truncated.set(stream, entry);\n return { truncated, skipped };\n}\n\n/**\n * Run `work` holding the per-stream close lock of every stream in\n * `streams`. Locks are taken in sorted order, so two closers whose batches\n * share streams in a different order cannot each hold one and wait on the\n * other.\n */\nfunction with_stream_locks<T>(\n streams: string[],\n deps: CloseCycleDeps,\n work: () => Promise<T>\n): Promise<T> {\n const with_lock = deps.with_stream_lock ?? ((_stream, w) => w());\n return [...streams]\n .sort()\n .reduceRight<() => Promise<T>>(\n (inner, stream) => () => with_lock(stream, inner),\n work\n )();\n}\n\n/**\n * The guarded tombstone/restart pipeline (Phases 1-6), run while holding\n * every target stream's close lock.\n */\nasync function run_full_closes(\n full: CloseTarget[],\n target_map: Map<string, CloseTarget>,\n deps: CloseCycleDeps,\n skipped: string[]\n): Promise<CloseResult[\"truncated\"]> {\n const none: CloseResult[\"truncated\"] = new Map();\n const streams = full.map((t) => t.stream);\n\n // 1. Scan: find the latest non-tombstone event per stream\n const stream_info = await scan_stream_heads(streams);\n\n // 1b. A restart target whose state has sensitive fields can't be seeded\n // (an actorless load would redact them; a privileged one would put\n // plaintext where `forget` can't reach), so it is skipped, untouched,\n // before anything is written.\n for (const target of full) {\n if (!target.restart) continue;\n const info = stream_info.get(target.stream);\n if (!info) continue;\n const owner = deps.event_to_state.get(info.last_event_name);\n if (owner?.pii_aware) {\n deps.logger.error(\n `Refusing to close \"${target.stream}\" with restart: state \"${owner.name}\" carries sensitive fields, so a restart seed would persist redacted values while deleting the originals. Close it without restart to retire the stream, or leave it open.`\n );\n skipped.push(target.stream);\n stream_info.delete(target.stream);\n }\n }\n\n // 2. Partition: skip streams with pending reactions in flight\n const safe = await partition_by_safety(\n stream_info,\n deps.reactive,\n skipped,\n deps.probe_page_size ?? SAFETY_PROBE_PAGE_SIZE,\n deps.catch_up_correlation\n );\n if (!safe.length) return none;\n\n // 3. Guard: commit a tombstone with expectedVersion per safe stream.\n // Correlation comes from the orchestrator's configured correlator so\n // close commits share the app's id scheme.\n const { guarded, guard_events } = await guard_with_tombstones(\n safe,\n stream_info,\n deps.correlation,\n deps.tombstone,\n skipped\n );\n if (!guarded.length) return none;\n\n // 4. Seed: load final state for restart targets through the owning state\n const seed_states = await load_restart_seeds(\n guarded,\n target_map,\n stream_info,\n deps.event_to_state,\n deps.load,\n deps.logger\n );\n\n // 5. Archive: user-provided per-stream callback while guarded\n await run_archive_callbacks(guarded, target_map);\n\n // 5b. Re-check: truncate only streams whose head is still this close's\n // guard. The lock above serializes closers in this process; a closer in\n // another process can still resume our guard, finish first, and reseed\n // the stream, after which a commit can land on it. Truncating then would\n // delete that accepted commit.\n const still_guarded = await heads_still_guarded(\n guarded,\n guard_events,\n skipped\n );\n if (!still_guarded.length) return none;\n\n // 6. Truncate + seed: atomic per-store transaction\n return truncate_and_warm_cache(\n still_guarded,\n seed_states,\n guard_events,\n deps.correlation\n );\n}\n\n// Windowed branch — prune the prefix behind an existing snapshot\n\n/**\n * Run the windowed closes: probe the min consumer watermark per stream\n * (the `max_id` cap that keeps the boundary at/below what the laggiest\n * consumer has read), run archive callbacks against the cutoff, then\n * hand the boundary targets to {@link Store.truncate}.\n *\n * No tombstone guard and no cache touch — the cutoff is always in the\n * past, so a concurrently-written snapshot (`created = now`) can never\n * become the boundary: once the cutoff is fixed the boundary snapshot is\n * fixed, and the prefix below it is immutable. Concurrent appends land\n * at the head, above the boundary. Current state is unchanged, so the\n * cache stays warm. Streams the store skips (no qualifying snapshot)\n * are reported in `skipped`.\n */\nasync function run_windowed_closes(\n windowed: CloseTarget[],\n deps: CloseCycleDeps,\n skipped: string[]\n): Promise<CloseResult[\"truncated\"]> {\n // 1. Safety probe: how far may each stream be pruned (skipped when the\n // app has no reactions). A consumer with pending work caps at its\n // watermark; a caught-up one caps at the correlate checkpoint, since a\n // reaction to only some event types sits below the head with nothing\n // pending. Catching up first makes that cap as high as it can be.\n const checkpoint = deps.reactive\n ? await deps.catch_up_correlation(Number.MAX_SAFE_INTEGER)\n : -1;\n const min_at = deps.reactive\n ? await probe_min_watermarks(\n windowed.map((t) => t.stream),\n deps.probe_page_size ?? SAFETY_PROBE_PAGE_SIZE,\n checkpoint\n )\n : new Map<string, number>();\n\n // 2 + 3. Per stream, under its lock: archive only when the prune would\n // delete a prefix, then truncate. The lock plus that check make the\n // archive fire at most once per pruned range.\n const with_lock = deps.with_stream_lock ?? ((_stream, work) => work());\n const truncated: CloseResult[\"truncated\"] = new Map();\n for (const t of windowed) {\n const entry = await with_lock(t.stream, async () => {\n const max_id = min_at.get(t.stream);\n // Nothing to prune (see windowed_prune_pending): skip the archive\n // and report the stream skipped, as a no-op truncate would.\n if (!(await windowed_prune_pending(t.stream, t.before!, max_id)))\n return undefined;\n // Archive: user callback against the cutoff, run while the prefix\n // is still present. Sequential/fail-fast: a throw propagates to the\n // caller and leaves the stream un-truncated (no data loss).\n if (t.archive) await t.archive();\n // Boundary truncate: atomic per-store transaction; no seed.\n const result = await store().truncate([\n { stream: t.stream, before: t.before!, max_id },\n ]);\n return result.get(t.stream);\n });\n if (entry) truncated.set(t.stream, entry);\n else skipped.push(t.stream);\n }\n return truncated;\n}\n\n/**\n * Read-only probe: would a windowed truncate of `stream` at `before`\n * (optionally capped at `max_id`) delete a prefix? Mirrors the store's\n * boundary rule — the latest `__snapshot__` with `created < before` and,\n * when capped, `id <= max_id` — then reports whether any event sorts\n * strictly below that boundary. False when no snapshot qualifies (a\n * no-op truncate) or when the boundary is already the earliest event\n * (the prefix was pruned by a prior closer). This is the guard that\n * makes the windowed archive fire at most once per pruned range.\n */\nasync function windowed_prune_pending(\n stream: string,\n before: Date,\n max_id: number | undefined\n): Promise<boolean> {\n let boundary_id: number | undefined;\n let min_id: number | undefined;\n await store().query(\n (event) => {\n if (min_id === undefined || event.id < min_id) min_id = event.id;\n if (\n event.name === SNAP_EVENT &&\n event.created < before &&\n (max_id === undefined || event.id <= max_id) &&\n (boundary_id === undefined || event.id > boundary_id)\n )\n boundary_id = event.id;\n },\n { stream, stream_exact: true, with_snaps: true, after: -1 }\n );\n // No qualifying snapshot → nothing to prune behind. Otherwise a prune\n // is pending only when some event sorts below the boundary.\n return boundary_id !== undefined && min_id! < boundary_id;\n}\n\n/**\n * Min subscription watermark per target stream — the read-only probe\n * backing the windowed close's `max_id` cap. Pagination and source\n * matching mirror {@link partition_by_safety}; instead of flagging\n * pending streams it folds `min(at)` per stream. Streams with no\n * matching subscriptions are absent (no cap).\n */\nasync function probe_min_watermarks(\n streams: string[],\n page_size: number,\n checkpoint: number\n): Promise<Map<string, number>> {\n const min_at = new Map<string, number>();\n const matches = source_matcher();\n await walk_streams(\n store(),\n (position) => {\n // Pending work caps at the watermark; caught up caps at the\n // checkpoint; an unmarked row keeps the conservative watermark.\n const pending =\n position.correlated_at === undefined ||\n position.at < position.correlated_at;\n const cap = pending ? position.at : Math.max(position.at, checkpoint);\n for (const stream of streams) {\n if (matches(position.source, position.stream, stream)) {\n const prev = min_at.get(stream);\n if (prev === undefined || cap < prev) min_at.set(stream, cap);\n }\n }\n },\n { limit: page_size }\n );\n return min_at;\n}\n\n/**\n * Does a subscription with this `source` consume from `stream`? No source\n * consumes every stream; a literal source consumes only that name. Compiled\n * patterns are cached per matcher.\n */\nfunction source_matcher(): (\n source: string | undefined,\n target: string,\n stream: string\n) => boolean {\n const compiled = new Map<string, RegExp>();\n return (source, target, stream) => {\n if (!source) return true;\n if (isStreamName(source, target)) return source === stream;\n let re = compiled.get(source);\n if (!re) {\n re = new RegExp(source);\n compiled.set(source, re);\n }\n return re.test(stream);\n };\n}\n\n// Phase 1 — scan stream heads\n\nasync function scan_stream_heads(\n streams: string[]\n): Promise<Map<string, StreamHead>> {\n // The latest non-snapshot event per stream (heads-only, indexed): a\n // tombstone here marks a close that was interrupted after its guard.\n const stats = await store().query_stats(streams, {\n exclude: [SNAP_EVENT],\n });\n // Domain head, markers excluded. A stream absent here has no domain\n // events left, so a previous close ran to completion and there is\n // nothing to do. A stream present here whose `stats` head is a tombstone\n // was guarded and then interrupted — it must be resumed, not skipped.\n // `last_event_name` also has to come from this pass: the\n // restart-seed owner lookup needs the domain event, not the marker.\n const domain_heads = await store().query_stats(streams, {\n exclude: [SNAP_EVENT, TOMBSTONE_EVENT],\n });\n // The tombstone must expect the stream's real head version, which a\n // trailing `__snapshot__` raises by one. Everything else uses the domain\n // head, so the true head gets its own heads-only read.\n const true_heads = await store().query_stats(streams, {});\n const out = new Map<string, StreamHead>();\n for (const [stream, { head }] of domain_heads) {\n const marker_head = stats.get(stream)?.head;\n const interrupted = marker_head?.name === TOMBSTONE_EVENT;\n out.set(stream, {\n max_id: head.id,\n version: true_heads.get(stream)!.head.version,\n last_event_name: head.name as string,\n ...(interrupted ? { resumed_guard: { id: marker_head.id } } : {}),\n });\n }\n return out;\n}\n\n// Phase 2 — partition by safety\n\nasync function partition_by_safety(\n stream_info: Map<string, StreamHead>,\n reactive: boolean,\n skipped: string[],\n page_size: number,\n catch_up_correlation: (until: number) => Promise<number>\n): Promise<string[]> {\n if (!reactive) return [...stream_info.keys()];\n\n // Correlate the tail first (see `catch_up_correlation`); anything still\n // above the cursor afterwards is held back.\n let needed = -1;\n for (const info of stream_info.values())\n needed = Math.max(needed, info.max_id);\n const checkpoint = await catch_up_correlation(needed);\n const uncorrelated = new Set<string>();\n for (const [stream, info] of stream_info) {\n if (checkpoint < info.max_id) uncorrelated.add(stream);\n }\n\n // Over-matching a source only widens the pending set, the safe direction.\n const pending_set = new Set<string>();\n const matches = source_matcher();\n\n // Every page, so a lagging reaction past the first one still counts.\n await walk_streams(\n store(),\n (position) => {\n // Pending means what `claim` means: a mark above the watermark. An\n // unmarked row has nothing to wait for; the catch-up above has landed\n // every mark that was owed.\n const has_work =\n position.correlated_at !== undefined &&\n position.at < position.correlated_at;\n if (!has_work) return;\n // A parked autoclose reads the live head and consumes nothing, so it\n // has no work a full close would lose.\n if (position.stream.startsWith(AUTOCLOSE_TARGET_PREFIX)) return;\n for (const [stream, info] of stream_info) {\n if (\n matches(position.source, position.stream, stream) &&\n position.at < info.max_id\n )\n pending_set.add(stream);\n }\n },\n { limit: page_size }\n );\n\n const safe: string[] = [];\n for (const [stream] of stream_info) {\n if (pending_set.has(stream) || uncorrelated.has(stream))\n skipped.push(stream);\n else safe.push(stream);\n }\n return safe;\n}\n\n// Phase 3 — guard with tombstones\n\nasync function guard_with_tombstones(\n safe: string[],\n stream_info: Map<string, StreamHead>,\n correlation: string,\n tombstone: EsOps[\"tombstone\"],\n skipped: string[]\n): Promise<{\n guarded: string[];\n guard_events: Map<string, { id: number; stream: string }>;\n}> {\n const guarded: string[] = [];\n const guard_events = new Map<string, { id: number; stream: string }>();\n await Promise.all(\n safe.map(async (stream) => {\n const info = stream_info.get(stream)!;\n if (info.resumed_guard) {\n // Guard already written by the interrupted run — reuse it rather\n // than re-tombstoning (the version guard would reject it anyway).\n guarded.push(stream);\n guard_events.set(stream, { id: info.resumed_guard.id, stream });\n return;\n }\n const committed = await tombstone(stream, info.version, correlation);\n if (committed) {\n guarded.push(stream);\n guard_events.set(stream, { id: committed.id, stream });\n } else {\n // ConcurrencyError → another writer beat the guard\n skipped.push(stream);\n }\n })\n );\n return { guarded, guard_events };\n}\n\n// Phase 4 — load restart seeds\n\nasync function load_restart_seeds(\n guarded: string[],\n target_map: Map<string, CloseTarget>,\n stream_info: Map<string, StreamHead>,\n event_to_state: ReadonlyMap<string, State<any, any, any>>,\n load: EsOps[\"load\"],\n logger: Logger\n): Promise<Map<string, Schema>> {\n const seed_states = new Map<string, Schema>();\n await Promise.all(\n guarded\n .filter((s) => target_map.get(s)?.restart)\n .map(async (stream) => {\n // stream_info entry is guaranteed (guarded ⊆ stream_info.keys()).\n const last_event_name = stream_info.get(stream)!.last_event_name;\n const owner_state = event_to_state.get(last_event_name);\n if (!owner_state) {\n // No registered state owns the stream's events (deleted state,\n // schema versioning gone wrong, etc.). Tombstone instead of\n // seeding a corrupted snapshot.\n logger.error(\n `Cannot seed restart for \"${stream}\": no registered state owns event \"${last_event_name}\". Stream will be tombstoned instead.`\n );\n return;\n }\n const snap = await load(owner_state, { stream });\n seed_states.set(stream, snap.state as Schema);\n })\n );\n return seed_states;\n}\n\n// Phase 5 — archive callbacks\n\nasync function run_archive_callbacks(\n guarded: string[],\n target_map: Map<string, CloseTarget>\n): Promise<void> {\n // Sequential — user callbacks may share resources (S3 client, etc.) and\n // a failure should propagate to the caller without leaving partial state.\n for (const stream of guarded) {\n const archive_fn = target_map.get(stream)?.archive;\n if (archive_fn) await archive_fn();\n }\n}\n\n// Phase 5b — confirm the guard is still the head\n\nasync function heads_still_guarded(\n guarded: string[],\n guard_events: Map<string, { id: number; stream: string }>,\n skipped: string[]\n): Promise<string[]> {\n // True heads, markers included: the guard is a tombstone, and a reseed\n // by another closer is a snapshot.\n const heads = await store().query_stats(guarded, {});\n return guarded.filter((stream) => {\n if (heads.get(stream)?.head.id === guard_events.get(stream)!.id)\n return true;\n skipped.push(stream);\n return false;\n });\n}\n\n// Phase 6 — atomic truncate + cache warm\n\nasync function truncate_and_warm_cache(\n guarded: string[],\n seed_states: Map<string, Schema>,\n guard_events: Map<string, { id: number; stream: string }>,\n correlation: string\n): Promise<CloseResult[\"truncated\"]> {\n const trunc_targets = guarded.map((stream) => {\n const snapshot = seed_states.get(stream);\n const guard = guard_events.get(stream)!;\n return {\n stream,\n snapshot,\n meta: {\n correlation,\n causation: {\n event: { id: guard.id, name: TOMBSTONE_EVENT, stream: guard.stream },\n },\n },\n };\n });\n const truncated = await store().truncate(trunc_targets);\n\n // Cache invalidate / warm — use real event IDs from committed events\n await Promise.all(\n guarded.map(async (stream) => {\n const entry = truncated.get(stream);\n const state = seed_states.get(stream);\n if (state && entry) {\n await cache().set(stream, {\n stream,\n state,\n version: entry.committed.version,\n event_id: entry.committed.id,\n patches: 0,\n snaps: 1,\n });\n } else {\n await cache().invalidate(stream);\n }\n })\n );\n\n return truncated;\n}\n","/**\n * Correlation, the discovery half of correlate→drain: resolves each event to\n * its target streams and raises each target's work mark (`correlated_at`),\n * which is what `claim` reads. See docs/architecture/correlation-and-drain.\n */\n\nimport { createHash, randomUUID } from \"node:crypto\";\nimport { isStreamName } from \"../adapter.js\";\nimport { log, store } from \"../ports.js\";\nimport type {\n EventRegister,\n Registry,\n Resolved,\n SchemaRegister,\n Schemas,\n StreamPosition,\n SubscribeInput,\n} from \"../types/index.js\";\nimport { DEFAULT_LANE } from \"../types/index.js\";\nimport { is_valid_target } from \"./config.js\";\nimport type { DrainOps } from \"./drain-ops.js\";\nimport { LruMap } from \"./lru-map.js\";\nimport { report_once } from \"./report-once.js\";\n\n/**\n * First-boot scan starts this far below the watermark, so an event committed\n * but not correlated before a crash is found again. Re-scanning is harmless:\n * `subscribe` is an idempotent upsert and a mark never regresses.\n */\nconst COLD_START_BACK_SCAN = 10_000;\n\n/**\n * Too short and a slow scan outruns its lease (duplicate work, still safe);\n * too long and a crashed holder stalls discovery.\n */\nconst CORRELATION_LEASE_MS = 5_000;\n\n/**\n * The correlation lease key: a hash of every reacted-to event name with its\n * handler names, so only interchangeable workers share a lease. See\n * docs/architecture/correlation-and-drain § The correlation lease.\n */\nconst registry_key = <TEvents extends Schemas>(\n events: EventRegister<TEvents>\n): string => {\n const shape = Object.keys(events)\n .filter((name) => events[name].reactions.size > 0)\n .sort()\n .map((name) => [name, [...events[name].reactions.keys()].sort()]);\n return createHash(\"sha256\")\n .update(JSON.stringify(shape))\n .digest(\"hex\")\n .slice(0, 32);\n};\n\n/**\n * One correlate pass. An `idle` pass read nothing it keeps (it was\n * disarmed, refused the lease, or discarded its read), so it is no\n * evidence the store is up; a `scanned` pass read the log.\n */\nexport type CorrelatePass =\n | { readonly kind: \"idle\"; readonly last_id: number }\n | {\n readonly kind: \"scanned\";\n readonly last_id: number;\n /** Targets newly subscribed. */\n readonly subscribed: number;\n /** Targets whose work mark was raised. */\n readonly marked: number;\n /** It read events: settle's progress signal. */\n readonly read: boolean;\n };\n\n/** Bound on compiled pattern sources; guards a resolver that mints one per event. */\nconst PATTERN_CACHE_SIZE = 32;\n\n/** Static resolver target collected at build time and subscribed at init. */\nexport type StaticTarget = {\n readonly stream: string;\n readonly source?: string;\n readonly priority?: number;\n readonly lane?: string;\n};\n\n/**\n * What a target's subscription row holds. A resolution sends its own\n * priority/lane only when it beats `priority` (never, for a static target);\n * otherwise it re-sends these values with the mark. The store owns the lane;\n * this only caches it, so a missing record is re-read from the row.\n */\ntype Subscription = {\n readonly priority: number;\n readonly lane: string | undefined;\n};\n\n/** One target accumulated during a scan; `correlated_at` is its work mark. */\ntype Correlated = {\n source: string | undefined;\n priority: number;\n lane: string | undefined;\n /** True when priority/lane came from a resolution that beat the record. */\n upgraded: boolean;\n /** True when the target had no record, so its row must be read. */\n missed: boolean;\n /** The reaction whose resolution set priority/lane. */\n handler: string;\n correlated_at: number | undefined;\n};\n\n/** Constructor dependencies for {@link CorrelateCycle}. */\nexport type CorrelateCycleDeps<\n TSchemaReg extends SchemaRegister<TActions>,\n TEvents extends Schemas,\n TActions extends Schemas,\n> = {\n registry: Registry<TSchemaReg, TEvents, TActions>;\n static_targets: ReadonlyArray<StaticTarget>;\n cd: DrainOps<TEvents>;\n max_subscribed_streams: number;\n /** Every lane a controller exists for; others are rerouted to default. */\n declared_lanes: ReadonlySet<string>;\n /** Set when `onlyLanes` leaves a lane out; each shard gets its own lease. */\n shard?: ReadonlyArray<string>;\n /** Runs once at the end of init: arms the lanes and re-seeds defer timers across a restart. */\n on_init?: () => Promise<void>;\n};\n\n/**\n * A dynamic resolution named an undeclared lane. Rerouted to `\"default\"`\n * rather than skipped, so the work still runs. Reported once per reaction\n * and lane, since a resolver mints one target per aggregate.\n */\nfunction report_undeclared_lane(\n seen: Set<string>,\n handler: string,\n target: string,\n lane: string,\n declared: ReadonlySet<string>\n): void {\n report_once(\n seen,\n `lane|${handler}|${lane}`,\n `Reaction \"${handler}\" resolved onto undeclared lane \"${lane}\" — for example target \"${target}\". ` +\n `Declared lanes: ${[...declared].map((l) => `\"${l}\"`).join(\", \")}. ` +\n 'No controller claims it, so the stream would never drain — running it on \"default\" instead. ' +\n \"The equivalent static `.to({ lane })` is rejected at build; a dynamic resolver's lane is only knowable here.\"\n );\n}\n\n/**\n * Two resolutions disagreed on one target's lane. Reported, not corrected:\n * re-laning a live stream would move it out from under a lease holder.\n * Keyed by orientation, since \"first discovered\" can land either way.\n */\nfunction report_bad_priority(\n seen: Set<string>,\n handler: string,\n target: string,\n priority: unknown\n): void {\n report_once(\n seen,\n `priority|${handler}|${String(priority)}`,\n `Reaction \"${handler}\" resolved priority ${String(priority)} for target \"${target}\", which isn't a 32-bit integer. ` +\n \"Skipping that event for this reaction; other reactions keep running. \" +\n \"The equivalent static `.to({ priority })` is rejected at build; a dynamic resolver's priority is only knowable here.\"\n );\n}\n\nfunction report_lane_conflict(\n seen: Set<string>,\n handler: string,\n target: string,\n kept: string,\n dropped: string\n): void {\n report_once(\n seen,\n `conflict|${handler}|${kept}|${dropped}`,\n `Reaction \"${handler}\" resolved lane \"${dropped}\" for a stream already on \"${kept}\" — for example \"${target}\". ` +\n `These are conflicting lane assignments from two dynamic resolutions at equal priority. ` +\n `Keeping \"${kept}\", the lane it was first discovered on — re-laning a live stream would move it out from under a worker holding its lease. ` +\n `The reaction resolving \"${dropped}\" runs inside the \"${kept}\" lane's budget, and a process restricted to \"${dropped}\" via onlyLanes never runs it. ` +\n \"The equivalent static declaration is rejected at build; align the resolvers, or split the target.\"\n );\n}\n\n/** Drives correlation for one Act: the checkpoint, the lease, the subscription records. */\nexport class CorrelateCycle<\n TSchemaReg extends SchemaRegister<TActions>,\n TEvents extends Schemas,\n TActions extends Schemas,\n> {\n private _checkpoint = -1;\n // Lease holder id; per instance, so a restart never inherits a stale claim.\n private readonly _by = randomUUID();\n private readonly _key: string;\n // Local expiry of the held lease (0 = none); stale only costs a duplicate scan.\n private _lease_until = 0;\n // Armed while `_raised` (bumped by a commit or notification) is ahead of\n // `_lowered` (the raise count the last short page saw). Starts armed.\n private _raised = 1;\n private _lowered = 0;\n // Bumped by a release (shutdown), so a scan or lease reply that was out\n // across one writes nothing.\n private _epoch = 0;\n // Passes in flight: a restore waits for them, and refuses new ones.\n private readonly _passes = new Set<Promise<CorrelatePass>>();\n private _restoring = false;\n private _init_promise: Promise<void> | undefined;\n // Bounded by `maxSubscribedStreams`; static records live apart so eviction\n // never lets a resolution re-lane them.\n private readonly _dynamic_subscriptions: LruMap<string, Subscription>;\n private readonly _static_subscriptions = new Map<string, Subscription>();\n private readonly _patterns = new LruMap<string, RegExp>(PATTERN_CACHE_SIZE);\n private readonly _registry: Registry<TSchemaReg, TEvents, TActions>;\n private readonly _static_targets: ReadonlyArray<StaticTarget>;\n private readonly _cd: DrainOps<TEvents>;\n private readonly _on_init: (() => Promise<void>) | undefined;\n private readonly _declared_lanes: ReadonlySet<string>;\n // Report-once keys; per instance because `internal/` holds no module state.\n private readonly _reported = new Set<string>();\n\n constructor({\n registry,\n static_targets,\n cd,\n max_subscribed_streams,\n declared_lanes,\n shard,\n on_init,\n }: CorrelateCycleDeps<TSchemaReg, TEvents, TActions>) {\n this._key = shard\n ? `${registry_key(registry.events)}:${[...shard].sort().join(\",\")}`\n : registry_key(registry.events);\n this._dynamic_subscriptions = new LruMap(max_subscribed_streams);\n this._registry = registry;\n this._declared_lanes = declared_lanes;\n this._static_targets = static_targets;\n this._cd = cd;\n this._on_init = on_init;\n }\n\n get checkpoint(): number {\n return this._checkpoint;\n }\n\n /** A commit (local or remote) may have produced uncorrelated events. */\n arm(): void {\n this._raised++;\n }\n\n private async _init(): Promise<void> {\n // Single-flight, but a failure clears the promise so the next call retries.\n this._init_promise ??= this._run_init().catch((error) => {\n this._init_promise = undefined;\n throw error;\n });\n await this._init_promise;\n }\n\n private async _run_init(): Promise<void> {\n const { watermark, correlated_at } = await this._cd.subscribe([\n ...this._static_targets,\n ]);\n this._checkpoint =\n correlated_at >= 0\n ? correlated_at\n : Math.max(-1, watermark - COLD_START_BACK_SCAN);\n for (const { stream, priority = 0, lane } of this._static_targets) {\n this._static_subscriptions.set(stream, {\n priority,\n lane,\n });\n }\n // After the static subscribe, so the streams walk sees them.\n await this._on_init?.();\n }\n\n /**\n * Replace the log with no pass in flight, then cold-start: a pass that\n * read the old log writes before the restore, never into the new one.\n */\n async restart(restore: () => Promise<void>): Promise<void> {\n this._restoring = true;\n try {\n await Promise.allSettled(this._passes);\n await restore();\n } finally {\n this._restoring = false;\n }\n this._init_promise = undefined;\n this._checkpoint = -1;\n this._dynamic_subscriptions.clear();\n this._static_subscriptions.clear();\n }\n\n /** Forget dynamic targets whose rows a full close deleted, so they re-subscribe. */\n forget_subscribed(streams: Iterable<string>): void {\n for (const stream of streams) this._dynamic_subscriptions.delete(stream);\n }\n\n // Would the target's own `fetch` (filtered by `source`) return this event?\n private _in_fetch_window(\n source: string | undefined,\n stream: string\n ): boolean {\n if (source === undefined || source === stream) return true;\n if (isStreamName(source)) return false;\n let pattern = this._patterns.get(source);\n if (!pattern) {\n pattern = new RegExp(source);\n this._patterns.set(source, pattern);\n }\n return pattern.test(stream);\n }\n\n /** Scan past the checkpoint, subscribe new targets and raise their work marks. */\n async correlate(\n /** The most events the scan reads (`0` reads everything). */\n limit: number,\n /**\n * Honour the correlation lease. Only the settle loop and poller do; an\n * explicit `app.correlate()` scans now, since `close` loops on it.\n */\n lease = false\n ): Promise<CorrelatePass> {\n if (this._restoring) return { kind: \"idle\", last_id: this._checkpoint };\n const pass = this._scan(limit, lease);\n this._passes.add(pass);\n try {\n return await pass;\n } finally {\n this._passes.delete(pass);\n }\n }\n\n private async _scan(limit: number, lease: boolean): Promise<CorrelatePass> {\n await this._init();\n const epoch = this._epoch;\n const idle = (): CorrelatePass => ({\n kind: \"idle\",\n last_id: this._checkpoint,\n });\n\n // A remote writer without notify leaves this disarmed; the poller re-arms.\n if (this._raised === this._lowered) return idle();\n\n const raised = this._raised;\n\n // The lease rides `subscribe` with no streams (\"may I scan?\"). Its shared\n // checkpoint is ignored: adopting it would skip events this worker never\n // read. Renew at the halfway mark.\n const now = Date.now();\n if (lease && now >= this._lease_until - CORRELATION_LEASE_MS / 2) {\n const { correlating } = await this._cd.subscribe([], undefined, {\n key: this._key,\n by: this._by,\n millis: CORRELATION_LEASE_MS,\n });\n // A release that landed while the call was out (shutdown) stays\n // released: the reply must not hand the lease back to this worker.\n if (this._epoch !== epoch) return idle();\n this._lease_until = correlating ? now + CORRELATION_LEASE_MS : 0;\n // `undefined` = store without leasing. Refused: stay armed, look again.\n if (correlating === false) return idle();\n }\n\n const after = this._checkpoint;\n const correlated = new Map<string, Correlated>();\n let last_id = after;\n // A resolver threw: the scan stops before that event, so the next one\n // retries it and nothing past it is lost.\n let stopped = false;\n const found = await store().query<TEvents>(\n (event) => {\n if (stopped) return;\n const register = this._registry.events[event.name];\n if (register) {\n for (const reaction of register.reactions.values()) {\n let resolved: Resolved | undefined;\n try {\n resolved =\n typeof reaction.resolver === \"function\"\n ? reaction.resolver(event)\n : reaction.resolver;\n } catch (error) {\n stopped = true;\n report_once(\n this._reported,\n `resolver|${reaction.handler.name}|${event.id}`,\n `Resolver of reaction \"${reaction.handler.name}\" threw on ${String(event.name)} #${event.id} (stream \"${event.stream}\"): ${String(error)}. ` +\n \"Correlation stops before this event until the resolver stops throwing; work already found keeps draining.\"\n );\n return;\n }\n if (!resolved) continue;\n if (!is_valid_target(resolved)) {\n report_bad_priority(\n this._reported,\n reaction.handler.name,\n resolved.target,\n resolved.priority\n );\n continue;\n }\n let lane = resolved.lane;\n if (lane !== undefined && !this._declared_lanes.has(lane)) {\n report_undeclared_lane(\n this._reported,\n reaction.handler.name,\n resolved.target,\n lane,\n this._declared_lanes\n );\n lane = undefined;\n }\n const fixed = this._static_subscriptions.get(resolved.target);\n const recorded =\n fixed ?? this._dynamic_subscriptions.get(resolved.target);\n const priority = resolved.priority ?? 0;\n const upgraded =\n !recorded || (!fixed && priority > recorded.priority);\n const carried = upgraded\n ? { priority, lane }\n : { priority: recorded.priority, lane: recorded.lane };\n const entry = correlated.get(resolved.target) || {\n source: resolved.source,\n priority: carried.priority,\n lane: carried.lane,\n upgraded,\n missed: !recorded,\n handler: reaction.handler.name,\n correlated_at: undefined,\n };\n // Compare against what the target already carries, from this\n // scan or a past one.\n const seen_in_scan = correlated.has(resolved.target);\n const held_lane =\n (seen_in_scan ? entry.lane : recorded?.lane) ?? DEFAULT_LANE;\n const held_priority = seen_in_scan\n ? entry.priority\n : recorded?.priority;\n const resolved_lane = lane ?? DEFAULT_LANE;\n if (held_priority === priority && held_lane !== resolved_lane)\n report_lane_conflict(\n this._reported,\n reaction.handler.name,\n resolved.target,\n held_lane,\n resolved_lane\n );\n // Within one scan the highest priority sets the lane.\n if (carried.priority > entry.priority) {\n entry.priority = carried.priority;\n entry.lane = carried.lane;\n entry.upgraded = upgraded;\n entry.handler = reaction.handler.name;\n }\n if (this._in_fetch_window(resolved.source, event.stream))\n entry.correlated_at = event.id;\n correlated.set(resolved.target, entry);\n }\n }\n last_id = event.id;\n },\n // Resolvers see `pii: null`: correlate runs actor-less, and one\n // undecryptable row would otherwise stop every stream's reactions.\n { after, limit, with_pii: false }\n );\n\n if (this._declared_lanes.size > 1) await this._recall(correlated);\n const read = last_id > after;\n\n // Released while the scan was out: what it read belongs to a lease this\n // worker gave up, and writing it would take the lease back.\n if (this._epoch !== epoch) return idle();\n\n // Only targets with a mark to raise or priority/lane to register.\n const streams: SubscribeInput[] = [];\n for (const [stream, entry] of correlated) {\n if (entry.upgraded || entry.correlated_at !== undefined)\n streams.push({\n stream,\n source: entry.source,\n priority: entry.priority,\n lane: entry.lane,\n correlated_at: entry.correlated_at,\n });\n }\n\n if (streams.length) {\n // Leasing renews for free on the same call.\n const renewed_at = Date.now();\n const { subscribed, correlating } = await this._cd.subscribe(\n streams,\n last_id,\n lease\n ? { key: this._key, by: this._by, millis: CORRELATION_LEASE_MS }\n : undefined\n );\n if (lease && correlating !== false)\n this._lease_until = renewed_at + CORRELATION_LEASE_MS;\n // The orchestrator arms on re-marks too, not just new subscriptions.\n const marked = streams.filter(\n (entry) => entry.correlated_at !== undefined\n ).length;\n this._checkpoint = last_id;\n // Only dynamic targets can be upgraded: a static target is never re-laned.\n for (const { stream, priority, lane } of streams) {\n if (correlated.get(stream)?.upgraded)\n this._dynamic_subscriptions.set(stream, {\n priority: priority as number,\n lane,\n });\n }\n return { kind: \"scanned\", last_id, subscribed, marked, read };\n }\n // Only a short page proves the log is exhausted; resolving nothing does\n // not. It lowers only the raises it saw, so one that landed mid-scan\n // keeps the cycle armed.\n this._checkpoint = last_id;\n if (!stopped && found !== limit) this._lowered = raised;\n return { kind: \"scanned\", last_id, subscribed: 0, marked: 0, read };\n }\n\n // Read the row of each target this scan had no record of (new or evicted),\n // so a resolution that doesn't beat its priority keeps the row's lane.\n // Only called with more than one lane declared.\n private async _recall(correlated: Map<string, Correlated>): Promise<void> {\n const missed = [...correlated].filter(([, entry]) => entry.missed);\n await Promise.all(\n missed.map(async ([stream, entry]) => {\n let row: StreamPosition | undefined;\n await store().query_streams(\n (position) => {\n row = position;\n },\n { stream, stream_exact: true, limit: 1 }\n );\n if (!row) return;\n this._dynamic_subscriptions.set(stream, {\n priority: row.priority,\n lane: row.lane,\n });\n if (entry.priority > row.priority) return;\n const held_lane = row.lane ?? DEFAULT_LANE;\n const resolved_lane = entry.lane ?? DEFAULT_LANE;\n if (entry.priority === row.priority && held_lane !== resolved_lane)\n report_lane_conflict(\n this._reported,\n entry.handler,\n stream,\n held_lane,\n resolved_lane\n );\n entry.priority = row.priority;\n entry.lane = row.lane;\n entry.upgraded = false;\n })\n );\n }\n\n /** Release the lease early by re-acquiring it for zero ms. Best-effort. */\n async release_correlation(): Promise<void> {\n try {\n this._lease_until = 0;\n this._epoch++;\n await this._cd.subscribe([], undefined, {\n key: this._key,\n by: this._by,\n millis: 0,\n });\n } catch (error) {\n log().warn(\n `Could not hand back the correlation lease during shutdown; it expires on its own within ${CORRELATION_LEASE_MS}ms and correlation resumes normally after that. ` +\n \"On a single-writer store this usually means another connection holds the database. \" +\n `Cause: ${String((error as Error).cause ?? error)}`\n );\n }\n }\n}\n","/**\n * The transforms that apply the sensitive-data marker (`../sensitive.ts`):\n * split sensitive fields out at commit, gate them on read, and strip them\n * before projection and reaction handlers.\n */\n\nimport type { Actor, Committed, Schemas } from \"../types/index.js\";\nimport { REDACTED, SHREDDED } from \"../types/schemas.js\";\n\n/**\n * Split an emitted event's `data` into `data` (non-sensitive) + `pii`\n * (sensitive) using the field list precomputed at build time. Called by the\n * state's `message` hook (`event-builder.ts`) on the way to `Store.commit`,\n * and only for events that declare sensitive fields.\n */\nexport function pii_split<TName, TData extends Record<string, unknown>>(\n emitted: { name: TName; data: TData },\n fields: readonly string[]\n): { name: TName; data: TData; pii: Record<string, unknown> } {\n const data = { ...emitted.data };\n const pii: Record<string, unknown> = {};\n for (const f of fields) {\n if (f in data) {\n pii[f] = data[f];\n delete data[f];\n }\n }\n return { name: emitted.name, data, pii };\n}\n\n/**\n * Build the **external view** of a committed event — the form returned by\n * `load()`, `query()`, `query_array()`, and the snapshot in `do()`'s reply.\n *\n * Reached only through {@link make_gate}, for events that declare sensitive\n * fields, so `fields` is never empty.\n *\n * - Event whose `pii` payload is null/undefined → substitute {@link SHREDDED}\n * for each declared field. Irrecoverable, so no predicate check.\n * - Event with a `pii` payload, predicate returns `true` → merge `pii` into\n * `data` (plaintext).\n * - Event with a `pii` payload, predicate returns `false` OR no predicate\n * declared (framework default-deny) → substitute {@link REDACTED} for each\n * declared field.\n */\nfunction pii_gate<TEvents extends Schemas, TKey extends keyof TEvents>(\n event: Committed<TEvents, TKey>,\n fields: readonly string[],\n predicate: ((event: any, actor: Actor) => boolean) | null,\n actor: Actor | undefined\n): Committed<TEvents, TKey> {\n const data = event.data as Record<string, unknown>;\n // The external view never carries the isolated `pii` sidecar: keeping it\n // would leak plaintext on every gated read (`load`, `query`,\n // `query_array`) even while `data` is redacted. The plaintext lives in\n // `data` only on the authorized path.\n const { pii, ...rest } = event as Committed<TEvents, TKey> & {\n pii?: Record<string, unknown> | null;\n };\n if (pii == null) {\n const shredded: Record<string, unknown> = { ...data };\n for (const f of fields) shredded[f] = SHREDDED;\n return { ...rest, data: shredded as Committed<TEvents, TKey>[\"data\"] };\n }\n // Plaintext path requires both an actor AND a predicate that allows. Missing\n // either → default-deny → REDACTED.\n const allowed = !!actor && !!predicate && predicate(event, actor);\n if (allowed) {\n return {\n ...rest,\n data: { ...data, ...pii } as Committed<TEvents, TKey>[\"data\"],\n };\n }\n const redacted: Record<string, unknown> = { ...data };\n for (const f of fields) redacted[f] = REDACTED;\n return { ...rest, data: redacted as Committed<TEvents, TKey>[\"data\"] };\n}\n\n/**\n * A prebuilt per-event read gate: the event as the reading actor may see\n * it. The builder prebuilds one per event for every read surface; the\n * actor-less `query` / `query_array` pass no actor (default-deny), `load`\n * and `do`'s reply pass the reader.\n */\nexport type EventGate = <TEvents extends Schemas, TKey extends keyof TEvents>(\n event: Committed<TEvents, TKey>,\n actor?: Actor\n) => Committed<TEvents, TKey>;\n\n/** The gate for every event with no sensitive fields: no allocation. */\nexport const IDENTITY_GATE: EventGate = (event) => event;\n\n/**\n * Prebuild a sensitive event's read gate: its field list and disclosure\n * predicate are captured once, and {@link pii_gate} applies them per read\n * (`predicate = null` is the default-deny of the actor-less surfaces).\n */\nexport function make_gate(\n fields: readonly string[],\n predicate: ((event: any, actor: Actor) => boolean) | null\n): EventGate {\n return (event, actor) => pii_gate(event, fields, predicate, actor);\n}\n\n/**\n * Build the **handler view** — sensitive keys removed entirely from `data`\n * and the `pii` field dropped from the event. Used before invoking projection\n * handlers and reaction handlers, which never see PII by framework rule.\n *\n * Different from {@link pii_gate} (which substitutes {@link REDACTED} or\n * {@link SHREDDED}) — projection tables and reaction sinks shouldn't even\n * structurally observe the keys, so a handler that mistakenly writes\n * `event.data.email` into a column would get `undefined`, not a sentinel\n * string that looks like real data. The strictness is deliberate.\n *\n * Reactions that genuinely need PII (e.g. a welcome-email reaction reading\n * `email`) opt back in by explicitly calling `app.load(stream, { actor:\n * system_actor })` inside the handler — pulling PII through the gate at the\n * call site makes the security-relevant path visible in code review.\n */\nexport function pii_strip<\n TEvents extends Schemas,\n TKey extends keyof TEvents & string,\n>(\n event: Committed<TEvents, TKey>,\n fields: readonly string[]\n): Committed<TEvents, TKey> {\n // Contract: `fields` is non-empty. The event gate (`event-builder.ts`) and\n // the projection fold (`projection-fold.ts`) call it only when it is.\n const data = event.data as Record<string, unknown>;\n const stripped: Record<string, unknown> = {};\n for (const k of Object.keys(data)) {\n if (!fields.includes(k)) stripped[k] = data[k];\n }\n const { pii: _drop_pii, ...rest } = event as Committed<TEvents, TKey> & {\n pii?: unknown;\n };\n return {\n ...rest,\n data: stripped as Committed<TEvents, TKey>[\"data\"],\n } as Committed<TEvents, TKey>;\n}\n","/**\n * Fold engine behind `projection(name).of(state)` — maintains per-stream\n * folded states in a bounded in-memory cache and flushes one row per dirty\n * stream per round, so write amplification tracks the distinct-key count\n * instead of the event count.\n *\n * The flush payload deliberately has no type of its own: a state\n * projection flushes the cache layer outward — the rows ARE the\n * streams' {@link CacheEntry} values.\n *\n * Correctness discipline:\n * - The engine runs as the projection's batch handler, so the watermark\n * acks only after a fully-flushed batch — fold work is never\n * acknowledged before it is durable.\n * - On first sight of a stream the engine loads its head state through\n * the same `load()` the command path uses (cache, snapshots and all).\n * The loaded snapshot carries its own head position (`version` and the\n * global event `id`), captured atomically with `state`, so the engine\n * never pairs a stale state with a newer head id read separately from\n * the cache. Fetched events at or below the loaded id are\n * skipped, later ones fold through the state's own patch reducers.\n * - Eviction under `maxCachedStates` pressure flushes the evictee first\n * (flush-before-evict) — eviction never loses folded work.\n */\nimport type {\n BatchHandler,\n CacheEntry,\n Schema,\n Schemas,\n State,\n} from \"../types/index.js\";\nimport type { FoldConfig } from \"./config.js\";\nimport { bare_patch, load } from \"./event-sourcing.js\";\nimport { pii_strip } from \"./pii.js\";\n\n/**\n * A stream's in-flight fold: a mutable {@link CacheEntry} plus the\n * engine's `dirty` flag. Mutable because the hot loop updates one\n * object per stream rather than allocating per event; the required\n * frontier fields are what keep a warm-cache load from ever\n * re-applying history. Stripping `dirty` at the flush boundary yields\n * the entry — the flush payload IS the cache entry.\n */\ntype Fold<TState extends Schema> = {\n -readonly [K in keyof CacheEntry<TState>]: CacheEntry<TState>[K];\n} & { dirty: boolean };\n\n/**\n * Internal handle a fold handler exposes so the orchestrator can drop its\n * process-local state.\n *\n * A rebuild must not trust a per-Act cache: `reset` rewinds the watermark and\n * replays from the beginning, and every replayed event is at or below the\n * cached head, so the fold takes its already-folded branch and re-flushes\n * whatever it happens to hold. If that cache is stale, the rebuild writes the\n * staleness back out — the one outcome a rebuild exists to prevent. Dropping\n * the cache makes the next batch re-load head state from the store, which is\n * authoritative by definition.\n *\n * A symbol on the function keeps `BatchHandler` a plain function type; nothing\n * here is re-exported from `src/index.ts`.\n */\nexport const FOLD_RESET = Symbol(\"act.fold.reset\");\n\n/** A batch handler that owns a fold cache it can be told to drop. */\nexport type ResettableBatchHandler<TEvents extends Schemas> =\n BatchHandler<TEvents> & {\n readonly [FOLD_RESET]?: () => void;\n };\n\n/**\n * Build the batch handler that folds a state's events into per-stream rows.\n * The returned closure is long-lived (one per built projection): its cache\n * survives across drain cycles, so warm streams fold without I/O. It carries\n * a {@link FOLD_RESET} handle so a rebuild can drop that cache.\n */\nexport function make_fold_handler<\n TState extends Schema,\n TEvents extends Schemas,\n TActions extends Schemas,\n>(\n me: State<TState, TEvents, TActions>,\n flush: (rows: ReadonlyArray<CacheEntry<TState>>) => Promise<void>,\n config: FoldConfig,\n sensitive_fields: (event_name: string) => readonly string[]\n): BatchHandler<TEvents> {\n // First-sight head loads must apply the SAME PII treatment as the warm\n // path (which folds `pii_strip`ped events handed in by the batch handler):\n // sensitive keys removed entirely, not gated to `[REDACTED]`. `load()`\n // folds over `me.view`, so compose the view with `pii_strip` for sensitive\n // events — otherwise an actorless head load would gate to `[REDACTED]` and\n // the projected row would differ from the warm path by cache warmth.\n // For a non-PII projection every lookup is empty, so `load_me === me`\n // behaviorally.\n const load_me: State<TState, TEvents, TActions> = {\n ...me,\n view: (raw, actor) => {\n const viewed = me.view(raw, actor);\n const fields = sensitive_fields(viewed.name as string);\n return fields.length\n ? (pii_strip(viewed as never, fields) as typeof viewed)\n : viewed;\n },\n };\n // Insertion-ordered Map as LRU: first key is the oldest. A promote is\n // delete + re-insert. Not the shared LruMap — eviction here must await\n // a flush, and a sync auto-evicting set() would drop folded work.\n const cache = new Map<string, Fold<TState>>();\n\n const row = ({ dirty: _, ...row }: Fold<TState>): CacheEntry<TState> => row;\n\n const flush_dirty = async () => {\n const rows: CacheEntry<TState>[] = [];\n const flushed: Fold<TState>[] = [];\n for (const f of cache.values())\n if (f.dirty) {\n rows.push(row(f));\n flushed.push(f);\n }\n if (rows.length === 0) return;\n await flush(rows);\n for (const f of flushed) f.dirty = false;\n };\n\n /**\n * Load a stream's head state and seat it in the cache.\n *\n * The loaded state and its head position (`version`, global `id`,\n * `patches`, `snaps`) are captured atomically inside `load()` — even on a\n * warm cache hit where `snapshot.event` is undefined. Reading the head id\n * back from the cache separately opened a TOCTOU window: a\n * concurrent `action()` committing between the two awaits pairs this\n * OLDER state with a NEWER event_id, and the frontier guard below then\n * permanently skips the intervening events. Dirty from the start: the row\n * must be written at least once.\n */\n const first_sight = async (stream: string): Promise<Fold<TState>> => {\n if (cache.size >= config.maxCachedStates) {\n // flush-before-evict: the oldest entry leaves only after its folded\n // work is durable.\n const oldest = cache.keys().next().value as string;\n const evictee = cache.get(oldest) as Fold<TState>;\n if (evictee.dirty) await flush([row(evictee)]);\n cache.delete(oldest);\n }\n const snapshot = await load(load_me, { stream });\n const seated: Fold<TState> = {\n stream,\n state: snapshot.state,\n version: snapshot.version,\n event_id: snapshot.id,\n patches: snapshot.patches,\n snaps: snapshot.snaps,\n dirty: true,\n };\n cache.set(stream, seated);\n return seated;\n };\n\n const handler: ResettableBatchHandler<TEvents> = async (events) => {\n let folded_since_flush = 0;\n for (const event of events) {\n const stream = event.stream;\n let fold = cache.get(stream);\n if (fold) {\n // promote to most-recent\n cache.delete(stream);\n cache.set(stream, fold);\n } else {\n fold = await first_sight(stream);\n }\n // Fold forward only across a CONTIGUOUS version step. The\n // cache is per-Act but the subscription watermark is shared, so a\n // worker can be handed an event whose predecessors were drained by a\n // sibling worker — its cached state is then stale, and folding onto\n // it silently corrupts the row for good (the flushed row carries the\n // newest event_id, so the monotonic-upsert guard overwrites the\n // correct row with the wrong one). \"Newer than what I hold\" is not\n // the same question as \"next after what I hold\".\n //\n // A gap re-takes the first-sight path: drop the entry and load head\n // state, which is authoritative and absorbs both the missed window\n // and the version slot a `__snapshot__` consumes. The reloaded entry\n // sits at head, so this event then takes the already-folded branch.\n const contiguous = event.version === fold.version + 1;\n if (event.id > fold.event_id && !contiguous) {\n cache.delete(stream);\n fold = await first_sight(stream);\n }\n if (event.id > fold.event_id) {\n const reducer = me.patch[event.name as keyof TEvents];\n fold.state = bare_patch(\n me,\n fold.state,\n reducer(event as never, fold.state),\n event as never\n );\n fold.version = event.version;\n fold.event_id = event.id;\n fold.patches++;\n fold.dirty = true;\n } else {\n // Already folded (head load or redelivery) — mark dirty anyway\n // so replays repopulate the read table: this is what keeps a\n // rebuild at one upsert per stream instead of zero.\n fold.dirty = true;\n }\n if (++folded_since_flush >= config.flushEvery) {\n await flush_dirty();\n folded_since_flush = 0;\n }\n }\n // Flush before returning: the drain acks this batch's watermark only\n // after the handler resolves, so rows are durable before the ack.\n await flush_dirty();\n };\n\n // Dirty entries are dropped rather than flushed: a rebuild is about to\n // re-derive every row from the store, so a pending write of process-local\n // state has nothing to contribute and everything to get wrong.\n Object.defineProperty(handler, FOLD_RESET, { value: () => cache.clear() });\n return handler;\n}\n","/**\n * Debounced correlate→drain loop. Sits one level above both correlation\n * and drain: schedule() coalesces rapid callers into a single cycle, then\n * runs correlate+drain in a loop until a pass produces no progress.\n *\n * Owns the debounce timer and the cycle in flight. Everything else is\n * supplied via the `SettleDeps` callbacks so this module stays free of\n * orchestrator state.\n */\n\nimport type {\n Drain,\n DrainOptions,\n Query,\n Schemas,\n SettleOptions,\n} from \"../types/index.js\";\nimport type { CircuitBreaker } from \"./circuit-breaker.js\";\nimport type { CorrelatePass } from \"./correlate-cycle.js\";\nimport { merge_drains } from \"./drain-cycle.js\";\n\n/**\n * Callbacks the settle loop needs from the orchestrator. Modeled as an\n * input bag so this file doesn't import `Act` (avoids a cycle) and stays\n * independently testable.\n */\nexport type SettleDeps<TEvents extends Schemas> = {\n /** Scans from correlation's own checkpoint. */\n readonly correlate: (query: Query) => Promise<CorrelatePass>;\n readonly drain: (options: DrainOptions) => Promise<Drain<TEvents>>;\n readonly on_settled: (drain: Drain<TEvents>) => void;\n /** The shared breaker: settle records correlate's store outcome on it. */\n readonly breaker: CircuitBreaker;\n};\n\n/**\n * Drives the debounced correlate→drain catch-up cycle. One instance per\n * Act orchestrator.\n */\nexport class SettleLoop<TEvents extends Schemas> {\n private _timer: ReturnType<typeof setTimeout> | undefined = undefined;\n // The cycle in flight, set while one runs. Shutdown waits for it\n // (`stop()` cancels scheduling only). Never rejects.\n private _inflight: Promise<void> | undefined;\n // A wake-up arrived while a cycle ran: run one more pass after it.\n private _pending = false;\n // The last caller's options, used by the next pass.\n private _next: SettleOptions | undefined = undefined;\n // When the scheduled pass fires (epoch ms).\n private _due = 0;\n // Set at shutdown: nothing schedules again.\n private _stopped = false;\n private readonly _deps: SettleDeps<TEvents>;\n // Debounce window applied when the caller doesn't override via `SettleOptions.debounceMs`.\n private readonly _default_debounce_ms: number;\n\n constructor(deps: SettleDeps<TEvents>, default_debounce_ms: number) {\n this._deps = deps;\n this._default_debounce_ms = default_debounce_ms;\n }\n\n /**\n * Schedule a settle pass. A pass already scheduled is never put off or\n * replaced: calls that arrive before it runs join it (a shorter\n * `debounceMs` brings it forward), and a call during a running cycle\n * queues one more pass after it. Callers pass options, which the next\n * pass uses; internal wake-ups pass none, so they never discard a\n * caller's. The cycle runs correlate→drain passes until one makes no\n * progress (see {@link SettleOptions.maxPasses}), then emits the\n * `\"settled\"` lifecycle event via {@link SettleDeps.on_settled}.\n */\n schedule(options?: SettleOptions): void {\n if (this._stopped) return;\n if (options) this._next = options;\n if (this._inflight) {\n this._pending = true;\n return;\n }\n const delay = options?.debounceMs ?? this._default_debounce_ms;\n const due = Date.now() + delay;\n if (this._timer) {\n if (due >= this._due) return;\n clearTimeout(this._timer);\n }\n this._due = due;\n this._timer = setTimeout(() => {\n this._timer = undefined;\n const {\n debounceMs: _,\n correlate: correlate_query = {},\n maxPasses = Infinity,\n ...drain_options\n } = this._next ?? {};\n this._next = undefined;\n\n this._inflight = (async () => {\n // Every pass, so `settled` reports what the whole settle did; its\n // last pass made no progress and is always empty.\n const passes: Drain<TEvents>[] = [];\n // Loop until a pass produces no work, so one settle catches up a\n // paginated backlog. Shutdown waits for the pass in flight, not the\n // loop.\n for (let i = 0; i < maxPasses && !this._stopped; i++) {\n const pass = await this._deps.correlate(correlate_query);\n // Only a pass that read the log is evidence the store is up.\n // Recording an idle one would re-close an OPEN breaker mid-outage\n // and let the drain below hammer a store nobody has heard from.\n const scanned = pass.kind === \"scanned\";\n if (scanned) this._deps.breaker.passed();\n const drain = await this._deps.drain(drain_options);\n passes.push(drain);\n // Only a pass that read no events and leased nothing is idle: a\n // leased stream that deferred or failed may leave work behind. It\n // ends because ids are finite and a leased stream advances or\n // leaves the claimable set (acked, blocked, scheduled); a zero\n // backoff keeps it claimable until it blocks or succeeds.\n const made_progress =\n drain.leased.length > 0 || (scanned && pass.read);\n if (!made_progress) break;\n }\n // `Act.emit` contains listener throws, so the store-failure catch\n // below never sees one.\n if (passes.length) this._deps.on_settled(merge_drains(passes));\n })()\n .catch((err) => {\n // Correlate failed (a store op, its startup included). Record on\n // the shared breaker, which logs it and surfaces the `error` event;\n // the drain loop reads the same breaker to pace itself.\n this._deps.breaker.failed(Date.now(), err);\n })\n .finally(() => {\n this._inflight = undefined;\n // A wake-up arrived mid-cycle: run one more pass so it isn't lost.\n if (this._pending) {\n this._pending = false;\n this.schedule(this._next);\n }\n });\n }, delay);\n }\n\n /**\n * The cycle currently in flight, or `undefined` when idle. A\n * graceful shutdown awaits this alongside the drain controllers so a\n * settle parked in `correlate` does not resume after teardown.\n */\n get inflight(): Promise<void> | undefined {\n return this._inflight;\n }\n\n /**\n * Cancel any pending settle pass. Idempotent. `final` (shutdown) also\n * stops all later scheduling.\n */\n stop(final = false): void {\n if (final) this._stopped = true;\n // Drop a mid-cycle wake-up too — a stopped loop must not re-arm from\n // the running cycle's `finally`.\n this._pending = false;\n this._next = undefined;\n if (this._timer) {\n clearTimeout(this._timer);\n this._timer = undefined;\n }\n }\n}\n","/**\n * @module merge\n * @category Internal\n *\n * Shared utilities for merging partial states and projections across builders.\n * Lives in `internal/` because the symbols are consumed by the builder layer\n * (`act-builder`, `slice-builder`, `projection-builder`) but aren't part of\n * the public package surface.\n *\n * @internal\n */\nimport { ZodObject, type ZodType } from \"zod\";\nimport { def_of, inner_of } from \"../internal/zod.js\";\nimport type { Projection } from \"../types/builders.js\";\nimport type { Schema, State } from \"../types/index.js\";\n\n/**\n * The kind of value a field holds under its wrappers (optional, nullable,\n * default, ...), e.g. `z.string().optional()` -> `\"string\"`. A list names its\n * element, `\"array of string\"`, so it differs from a value and from a list of\n * something else. Zod's `.unwrap()` returns the element and loses the list.\n */\nfunction base_type_name(schema: ZodType): string {\n let def = def_of(schema)!;\n for (let inner = inner_of(def); inner; inner = inner_of(def))\n def = def_of(inner)!;\n return def.type === \"array\"\n ? `array of ${base_type_name(def.element)}`\n : def.type;\n}\n\n/**\n * Merges two Zod schemas. If both are ZodObject instances, checks for\n * overlapping shape keys with incompatible base types (throws descriptive\n * error), then merges via `.extend()`. The same schema instance (one partial\n * re-registered through another slice) is kept as-is. Any other pair where\n * either side is not a ZodObject throws — there is no shape to extend, and\n * keeping one side would silently drop the other partial's fields.\n */\nfunction merge_schemas(\n existing: ZodType,\n incoming: ZodType,\n state_name: string\n): ZodType {\n if (existing === incoming) return existing;\n const existing_object = as_object(existing, \"existing\", state_name);\n const incoming_object = as_object(incoming, \"incoming\", state_name);\n const existing_shape = existing_object.shape as Record<string, ZodType>;\n const incoming_shape = incoming_object.shape as Record<string, ZodType>;\n for (const key of Object.keys(incoming_shape)) {\n if (key in existing_shape) {\n const existing_base = base_type_name(existing_shape[key]);\n const incoming_base = base_type_name(incoming_shape[key]);\n if (existing_base !== incoming_base) {\n throw new Error(\n `Schema conflict in \"${state_name}\": key \"${key}\" has type \"${existing_base}\" but incoming partial declares \"${incoming_base}\"`\n );\n }\n }\n }\n return existing_object.extend(incoming_shape);\n}\n\n/**\n * Narrows a partial's state schema to the ZodObject that merging needs, or\n * throws naming the state, which side failed, and what it is instead.\n */\nfunction as_object(\n schema: ZodType,\n side: \"existing\" | \"incoming\",\n state_name: string\n): ZodObject {\n if (schema instanceof ZodObject) return schema;\n throw new Error(\n `Cannot merge state schemas for \"${state_name}\": the ${side} partial's schema is a ${schema.constructor.name}, not a z.object. ` +\n `Partials of the same state are merged by extending their shapes, ` +\n `so declare every partial's state as a plain z.object({ ... }).`\n );\n}\n\n/**\n * Merges two init functions by spreading both results together.\n * Each partial only provides its own defaults.\n */\nfunction merge_inits<TState extends Schema>(\n existing: () => Readonly<TState>,\n incoming: () => Readonly<TState>\n): () => Readonly<TState> {\n return () => ({ ...existing(), ...incoming() });\n}\n\n/**\n * Registers a state into a states map and action/event registries,\n * merging with existing same-name states (partial state support).\n */\nexport function register_state(\n state: State<any, any, any>,\n states: Map<string, State<any, any, any>>,\n actions: Record<string, any>,\n events: Record<string, any>\n): void {\n const existing = states.get(state.name);\n if (existing) {\n merge_into_existing(state, existing, states, actions, events);\n } else {\n register_new_state(state, states, actions, events);\n }\n}\n\n/**\n * Registers a state for the first time. All action/event names must be unique\n * across the registry; collisions throw.\n */\nfunction register_new_state(\n state: State<any, any, any>,\n states: Map<string, State<any, any, any>>,\n actions: Record<string, any>,\n events: Record<string, any>\n): void {\n states.set(state.name, state);\n for (const name of Object.keys(state.actions)) {\n if (actions[name]) throw new Error(`Duplicate action \"${name}\"`);\n actions[name] = state;\n }\n for (const name of Object.keys(state.events)) {\n if (events[name]) throw new Error(`Duplicate event \"${name}\"`);\n events[name] = { schema: state.events[name], reactions: new Map() };\n }\n}\n\n/**\n * Picks the value of a field only one partial may declare. Mirrors the\n * `snap` rule: whichever partial declared it wins, and two different\n * declarations are a conflict rather than a silent first-wins.\n *\n * Without this, a spread of `existing` keeps the FIRST partial's value and\n * silently discards the incoming one, so a policy declared on a later slice\n * never runs.\n */\nfunction pick_declared<T>(\n existing: T | undefined,\n incoming: T | undefined,\n what: string,\n state_name: string\n): T | undefined {\n if (existing && incoming && existing !== incoming)\n throw new Error(`Duplicate ${what} for state \"${state_name}\"`);\n return incoming ?? existing;\n}\n\n/**\n * Resolves the `.autocloses(...)` triple. The predicate and its two day\n * fields are set together by the builder, so they move together — taking the\n * predicate from one partial and a day field from another would produce a\n * window the caller never declared.\n */\nfunction autoclose_of(\n existing: State<any, any, any>,\n state: State<any, any, any>\n): Pick<\n State<any, any, any>,\n | \"autoclose\"\n | \"autoclose_after_days\"\n | \"autoclose_after_windows\"\n | \"autoclose_keep_days\"\n> {\n pick_declared(\n existing.autoclose,\n state.autoclose,\n \"autoclose policy\",\n state.name\n );\n const owner = state.autoclose ? state : existing;\n return {\n autoclose: owner.autoclose,\n autoclose_after_days: owner.autoclose_after_days,\n autoclose_after_windows: owner.autoclose_after_windows,\n autoclose_keep_days: owner.autoclose_keep_days,\n };\n}\n\n/**\n * Merges an incoming partial state into an existing same-name state and\n * updates the action/event registries. Splits into four phases:\n * 1. validate no cross-state action/event collisions\n * 2. merge per-event patches (one custom patch per event)\n * 3. build the merged state and replace it in the states map\n * (including the single-declaration policies, which a bare spread\n * would silently take from the first partial only)\n * 4. update action→state pointers and register new events\n */\nfunction merge_into_existing(\n state: State<any, any, any>,\n existing: State<any, any, any>,\n states: Map<string, State<any, any, any>>,\n actions: Record<string, any>,\n events: Record<string, any>\n): void {\n // 1. Validate no cross-state collisions for actions/events\n for (const name of Object.keys(state.actions)) {\n // The same handler means the same partial re-registered via another\n // slice. A shared schema doesn't: two partials can declare one action\n // with one exported schema, and merging them would pair one partial's\n // rules with the other's handler.\n if (existing.on[name] === state.on[name]) continue;\n if (actions[name]) throw new Error(`Duplicate action \"${name}\"`);\n }\n for (const name of Object.keys(state.events)) {\n // Same schema reference means the same partial re-registered via another slice\n if (existing.events[name] === state.events[name]) continue;\n // Same event name registered in a same-name state partial with a\n // different Zod schema reference — silent contract drift that the\n // type system can't catch (structurally compatible shapes flow\n // through TS even when refinements/enums/literals disagree).\n // Reference identity is the rule: cross-slice event schemas must\n // come from a single shared instance.\n if (existing.events[name]) {\n throw new Error(\n `Event \"${name}\" in state \"${state.name}\" is declared with different Zod schemas across slices. ` +\n `Cross-slice event schemas must reference the same instance — ` +\n `extract a shared schema (e.g. \\`export const ${name} = z.object({ ... })\\` in a shared module) ` +\n `and import it in every slice that declares it.`\n );\n }\n if (events[name]) throw new Error(`Duplicate event \"${name}\"`);\n }\n\n // 2. Merge patches with custom-vs-passthrough resolution\n const merged_patch = merge_patches(existing.patch, state.patch, state.name);\n\n // 3. Build merged state\n const merged = {\n ...existing,\n state: merge_schemas(existing.state, state.state, state.name),\n init: merge_inits(existing.init, state.init),\n events: { ...existing.events, ...state.events },\n actions: { ...existing.actions, ...state.actions },\n patch: merged_patch,\n on: { ...existing.on, ...state.on },\n requires: { ...existing.requires, ...state.requires },\n loads:\n existing.loads || state.loads\n ? { ...existing.loads, ...state.loads }\n : undefined,\n snap: pick_declared(existing.snap, state.snap, \"snap strategy\", state.name),\n // Per-action retry policy is keyed by action name, so the two partials'\n // maps combine. Left `undefined` when neither declared one, so the\n // orchestrator's `me.options?.[action]` lookup is unchanged.\n options:\n existing.options || state.options\n ? { ...existing.options, ...state.options }\n : undefined,\n disclose: pick_declared(\n existing.disclose,\n state.disclose,\n \"disclosure predicate\",\n state.name\n ),\n archive: pick_declared(\n existing.archive,\n state.archive,\n \"archiver\",\n state.name\n ),\n // `.autocloses(...)` sets its two day fields alongside the predicate, so\n // the whole triple travels together from whichever partial declared it.\n ...autoclose_of(existing, state),\n };\n states.set(state.name, merged);\n\n // 4. Update action→state pointers; register events not yet seen\n for (const name of Object.keys(merged.actions)) {\n actions[name] = merged;\n }\n for (const name of Object.keys(state.events)) {\n if (events[name]) continue; // already registered, preserve reactions\n events[name] = { schema: state.events[name], reactions: new Map() };\n }\n}\n\n/**\n * Merges two patch maps. Only one custom (non-passthrough) patch per event is\n * allowed; passthroughs always yield to custom reducers, and re-registering\n * the same custom patch (same reference, e.g. across slices) is a no-op.\n */\nfunction merge_patches(\n existing: Record<string, any>,\n incoming: Record<string, any>,\n state_name: string\n): Record<string, any> {\n const merged = { ...existing };\n for (const name of Object.keys(incoming)) {\n const existing_p = existing[name];\n const incoming_p = incoming[name];\n if (!existing_p) {\n merged[name] = incoming_p;\n continue;\n }\n const existing_is_default = existing_p._passthrough;\n const incoming_is_default = incoming_p._passthrough;\n if (\n !existing_is_default &&\n !incoming_is_default &&\n existing_p !== incoming_p\n ) {\n throw new Error(\n `Duplicate custom patch for event \"${name}\" in state \"${state_name}\"`\n );\n }\n // Keep whichever is custom; if both passthrough or existing custom, keep existing\n if (existing_is_default && !incoming_is_default) {\n merged[name] = incoming_p;\n }\n }\n return merged;\n}\n\n/**\n * Merges reactions from one event register into another. The target is\n * assumed to already contain entries for every event name in the source\n * (e.g., act-builder's `.withSlice()` registers the slice's states first,\n * which seeds the target events). Reactions are keyed by `handler.name`;\n * two distinct handlers sharing a name on the same event throw rather than\n * silently overwriting. Re-merging the identical reaction object\n * is idempotent — mirrors {@link register_batch_handler}.\n */\nexport function merge_event_register(\n target: Record<string, { reactions: Map<string, unknown> }>,\n source: Record<string, { reactions: Map<string, unknown> }>\n): void {\n for (const [event_name, source_reg] of Object.entries(source)) {\n const target_reg = target[event_name];\n if (!target_reg) continue;\n for (const [name, reaction] of source_reg.reactions) {\n const existing = target_reg.reactions.get(name);\n if (existing !== undefined && existing !== reaction)\n throw new Error(\n `Duplicate reaction \"${name}\" for event \"${event_name}\". ` +\n `Reaction handlers are keyed by function name; rename one of them.`\n );\n target_reg.reactions.set(name, reaction);\n }\n }\n}\n\n/**\n * Merges a projection's event schemas and reactions into an event registry,\n * deduplicating reaction names by appending \"_p\" on collision.\n */\nexport function merge_projection(\n proj: Projection<any>,\n events: Record<string, any>\n): void {\n for (const event_name of Object.keys(proj.events)) {\n const proj_register = proj.events[event_name];\n const existing = events[event_name];\n if (!existing) {\n events[event_name] = {\n schema: proj_register.schema,\n reactions: new Map(proj_register.reactions),\n };\n } else {\n for (const [name, reaction] of proj_register.reactions) {\n // The `_p` rename resolves a NAME collision between two genuinely\n // different handlers. Registering the SAME reaction object again is\n // not a collision — it is the same projection reached along two\n // paths (exported from a module and embedded by two slices, or a\n // `.withProjection(p)` written twice) — and renaming it registered a\n // second copy under `name_p`, so the handler ran twice per event,\n // forever, frozen into the registry at build.\n //\n // Not the at-least-once redelivery contract: a structural duplicate,\n // deterministic on every event, with no signal anywhere. Both\n // siblings already guard on identity — `merge_event_register` throws\n // on a different handler under the same name, `register_batch_handler`\n // likewise — this one only lacked the check.\n if ([...existing.reactions.values()].includes(reaction)) continue;\n let key = name;\n while (existing.reactions.has(key)) key = `${key}_p`;\n existing.reactions.set(key, reaction);\n }\n }\n }\n}\n\n// Resolves the event stream as source and target (default)\nexport const _this_ = ({ stream }: { stream: string }) => ({\n source: stream,\n target: stream,\n});\n","/**\n * @module builder-utils\n * @category Internal\n *\n * Shared builder machinery reused by both `act-builder.ts` and\n * `slice-builder.ts`. The two builders expose the same reaction-registration\n * and lane-declaration surface and differ only in the concrete builder type\n * they return (`ActBuilder` vs `SliceBuilder`) and the event register they\n * write into (`registry.events` vs the slice's `events`). This module owns the\n * one copy of that logic so the builders stay thin delegations.\n *\n * @internal\n */\n\nimport {\n DEFAULT_BLOCK_ON_ERROR,\n DEFAULT_MAX_RETRIES,\n resolveLaneConfig,\n resolveReactionConfig,\n resolveTargetConfig,\n} from \"../internal/config.js\";\nimport {\n assert_defer_when,\n type DeferSchedule,\n make_deferred,\n} from \"../internal/defer-config.js\";\nimport type {\n Committed,\n EventRegister,\n LaneConfig,\n Reaction,\n ReactionHandler,\n ReactionOptions,\n ReactionResolver,\n Schemas,\n} from \"../types/index.js\";\nimport { DEFAULT_LANE } from \"../types/index.js\";\nimport { _this_ } from \"./merge.js\";\n\n/**\n * Validate and register a drain lane, the one rule for `withLane` on an Act\n * or a slice and for the lanes a slice brings to `withSlice`, in any order.\n * Validating here means a bad lane bag throws at declaration, not by\n * silently draining nothing. `\"default\"` is reserved; a name declares one\n * config, so declaring it again with the same config is a no-op and with a\n * different one throws. Mutates `lanes` in place.\n *\n * @internal\n */\nexport function register_lane(config: LaneConfig, lanes: LaneConfig[]): void {\n resolveLaneConfig(config);\n if (config.name === DEFAULT_LANE)\n throw new Error(`Lane \"${DEFAULT_LANE}\" is reserved`);\n const existing = lanes.find((l) => l.name === config.name);\n if (!existing) return void lanes.push(config);\n if (\n existing.leaseMillis !== config.leaseMillis ||\n existing.streamLimit !== config.streamLimit ||\n existing.cycleMs !== config.cycleMs\n )\n throw new Error(\n `Lane \"${config.name}\" was already declared with a different config`\n );\n}\n\n/**\n * Register a reaction once, keyed by its handler's name, and hand back\n * `builder` patched with `.to(...)`, which reroutes the same reaction in\n * place (no second `Map.set()`). The one registration step for reactions and\n * projection handlers: the named-function and duplicate guards run before\n * `make` builds the reaction, and `kind` picks the wording of their errors.\n *\n * @internal\n */\nexport function add_reaction<\n TEvents extends Schemas,\n TKey extends keyof TEvents,\n TBuilder extends object,\n>(\n events: EventRegister<TEvents>,\n event: TKey,\n name: string,\n kind: \"Reaction\" | \"Projection\",\n make: () => Reaction<TEvents, TKey>,\n builder: TBuilder\n) {\n if (!name)\n throw new Error(\n `${kind} handler for \"${String(event)}\" must be a named function`\n );\n const label = kind === \"Reaction\" ? \"reaction\" : \"projection handler\";\n if (events[event].reactions.has(name))\n throw new Error(\n `Duplicate ${label} \"${name}\" for event \"${String(event)}\". ` +\n `${kind} handlers are keyed by function name; rename one of them.`\n );\n const reaction = make();\n events[event].reactions.set(name, reaction);\n return Object.assign(builder, {\n to(resolver: ReactionResolver<TEvents, TKey> | string) {\n if (typeof resolver === \"object\") resolveTargetConfig(resolver);\n reaction.resolver =\n typeof resolver === \"string\" ? { target: resolver } : resolver;\n return builder;\n },\n });\n}\n\n/**\n * Build the `.on(event)` step shared by both builders. Registers a reaction\n * (named-function + duplicate guards, fail-fast literal-schedule validation,\n * the default `_this_` resolver, and the `.defer` handler wrap) into\n * `events[event].reactions`, and hands back `builder` patched with `.to(...)`\n * for in-place resolver routing.\n *\n * The strict, builder-specific type is supplied by each builder's own `on`\n * signature ({@link ReactionOn}); the runtime here is builder-agnostic.\n *\n * @internal\n */\nexport function reaction_on<\n TEvents extends Schemas,\n TKey extends keyof TEvents,\n TBuilder extends object,\n>(event: TKey, events: EventRegister<TEvents>, builder: TBuilder) {\n const register = (\n handler: ReactionHandler<TEvents, TKey>,\n options?: Partial<ReactionOptions>,\n schedule?: DeferSchedule<Committed<TEvents, TKey>>\n ) =>\n add_reaction(\n events,\n event,\n handler.name,\n \"Reaction\",\n () => {\n // Fail fast on a bad literal schedule; the function form is checked\n // when it runs (no event to resolve against at build time).\n if (schedule && typeof schedule !== \"function\")\n assert_defer_when(schedule);\n return {\n handler: schedule ? make_deferred(handler, schedule) : handler,\n resolver: _this_,\n // Validate the whole bag at the declaration site so a bad\n // `maxRetries`/`backoff`/`blockOnError` throws ZodError at build,\n // not a NaN gate on the first retry.\n options: resolveReactionConfig({\n blockOnError: options?.blockOnError ?? DEFAULT_BLOCK_ON_ERROR,\n maxRetries: options?.maxRetries ?? DEFAULT_MAX_RETRIES,\n backoff: options?.backoff,\n }),\n };\n },\n builder\n );\n return {\n do: (\n handler: ReactionHandler<TEvents, TKey>,\n options?: Partial<ReactionOptions>\n ) => register(handler, options),\n defer: (schedule: DeferSchedule<Committed<TEvents, TKey>>) => ({\n do: (\n handler: ReactionHandler<TEvents, TKey>,\n options?: Partial<ReactionOptions>\n ) => register(handler, options, schedule),\n }),\n };\n}\n","/**\n * @module event-builder\n * @category Internal\n *\n * Everything `act().build()` derives from the registered events.\n *\n * This is the build-time half of the event lifecycle. The other two halves\n * are the `sensitive(...)` marker (`sensitive.ts`) and the runtime\n * transforms (`pii_gate`, `pii_strip`, `pii_split`, in `internal/pii.ts`)\n * that a reader is composed from. Nothing here runs per event at runtime; everything here runs\n * once, at build, and hands the orchestrator a prebuilt function.\n *\n * Three things are derived, all in ONE walk over the registered events:\n *\n * - **validation** — a reaction may not target a lane nobody declared, nor a\n * target a projection already serves. Both checks skip dynamic resolvers,\n * because a `.to(fn)` target is unknowable until an event arrives.\n * - **resolution** — each event's schema is read once into {@link EventTags}:\n * which fields are sensitive, and how to revive the dates in a stored\n * payload. Working out where the dates are is a Zod concern, so it lives in\n * `internal/date-reviver.ts`; this module composes what that returns.\n * - **composition** — the per-surface readers, each a single {@link EventGate}\n * that types the payload and applies disclosure in one call.\n *\n * Deliberately NOT here: deprecation. `Foo` is deprecated only because\n * `Foo_v2` exists beside it, so it is derived from event *names across a whole\n * state* rather than from one event's schema — and it governs *emitting* (a\n * static `.emit()` throws at build), not reading. Replay of a deprecated event\n * stays silent by design.\n *\n * @internal\n */\n\nimport { z } from \"zod\";\nimport { date_reviver_schema } from \"../internal/date-reviver.js\";\nimport {\n type EventGate,\n IDENTITY_GATE,\n make_gate,\n pii_split,\n pii_strip,\n} from \"../internal/pii.js\";\nimport { def_of, output_of } from \"../internal/zod.js\";\nimport { pii_schemas } from \"../sensitive.js\";\nimport type { Actor, LaneConfig, Registry } from \"../types/index.js\";\nimport { DEFAULT_LANE, SNAP_EVENT } from \"../types/index.js\";\n\n/** What one pass over an event's schema resolves. @internal */\nexport type EventTags = {\n /**\n * Keys marked `sensitive(...)`, top level (and across union variants), with\n * the schema each declares.\n */\n readonly sensitive: Readonly<Record<string, z.ZodType>>;\n /**\n * Revives the dates in a stored `data` payload, or `undefined` when the\n * schema declares none.\n */\n readonly date_reviver: ((data: unknown) => unknown) | undefined;\n /**\n * Revives the dates in a stored `pii` sidecar, or `undefined` when no\n * sensitive field is a date.\n */\n readonly pii_date_reviver: ((pii: unknown) => unknown) | undefined;\n};\n\n/**\n * Resolve an event's schema in a single pass.\n *\n * Sensitive markers are read at the top level only — the documented carve-out\n * (`sensitive.ts`), since the write path splits whole top-level keys. A union\n * event has no top-level shape, so its variants are walked and unioned: a key\n * sensitive in any variant must be split, because the stored payload could be\n * that variant.\n *\n * @internal\n */\nexport function event_tags(schema: z.ZodType): EventTags {\n // Which fields are sensitive is `sensitive.ts`'s question and where the\n // dates are is `date-reviver.ts`'s; this composes the two answers. The\n // sidecar holds the split-out fields alone, so a date among them needs its\n // own reviver — without it a disclosed `sensitive(z.date())` arrives as text\n // beside a plain sibling that is a Date.\n const pii = pii_schemas(schema);\n const pii_dates: Record<string, z.ZodType> = {};\n for (const [key, field] of Object.entries(pii)) {\n const dates = date_reviver_schema(field);\n if (dates) pii_dates[key] = dates.optional();\n }\n\n const data_reviver_schema = date_reviver_schema(schema);\n // Reviving must never reject. A stored payload can disagree with the current\n // declaration in ways this schema deliberately does not describe, and handing\n // back what is stored beats refusing to read it.\n const revive = (schema: z.ZodType) => (data: unknown) => {\n const revived = schema.safeParse(data);\n return revived.success ? revived.data : data;\n };\n const dated_pii = Object.keys(pii_dates).length > 0;\n return {\n sensitive: pii,\n date_reviver: data_reviver_schema && revive(data_reviver_schema),\n pii_date_reviver: dated_pii ? revive(z.looseObject(pii_dates)) : undefined,\n };\n}\n\n/**\n * What the reader should do about sensitive fields.\n *\n * - `redact` — substitute `[REDACTED]` unless `disclose` authorizes the actor,\n * and drop the `pii` sidecar. The read surfaces (`query`, `query_array`,\n * `load`).\n * - `strip` — remove the keys entirely. Reaction and projection handlers,\n * which never see PII by framework rule, and shouldn't structurally observe\n * the keys either.\n *\n * @internal\n */\nexport type Disclosure = \"redact\" | \"strip\";\n\n/**\n * Compose one event's typing and disclosure into a single gate.\n *\n * Returns `undefined` when the event needs neither, so the caller can fall\n * back to the shared {@link IDENTITY_GATE} and the common path allocates\n * nothing.\n *\n * @internal\n */\nfunction make_event_reader(\n tags: EventTags,\n disclosure: Disclosure,\n predicate: ((event: never, actor: Actor) => boolean) | null = null\n): EventGate | undefined {\n const { date_reviver, pii_date_reviver } = tags;\n const sensitive = Object.keys(tags.sensitive);\n if (!date_reviver && sensitive.length === 0) return undefined;\n\n const gate: EventGate =\n sensitive.length === 0\n ? IDENTITY_GATE\n : disclosure === \"strip\"\n ? (((event) => pii_strip(event as never, sensitive)) as EventGate)\n : make_gate(sensitive, predicate as never);\n\n if (!date_reviver) return gate;\n\n // The sidecar is only worth reviving for a reader that can be shown it.\n // A `strip` reader drops `pii` outright, and a redacting one discloses only\n // to an actor a predicate approves — so no actor and no predicate means the\n // values are on their way to REDACTED whatever they hold. The predicate\n // itself stays uncalled here: the gate owns that decision and calling it\n // twice would run a caller's code twice.\n const revive_pii =\n disclosure === \"redact\" && predicate ? pii_date_reviver : undefined;\n\n // Revive before disclosing: the gate copies, so reviving afterwards would\n // leave the consumer's value a string — and it substitutes REDACTED and\n // SHREDDED, which are not dates.\n return ((event, actor) => {\n const pii = (event as { pii?: unknown }).pii;\n return gate(\n {\n ...event,\n data: date_reviver(event.data),\n ...(revive_pii && actor && pii != null ? { pii: revive_pii(pii) } : {}),\n } as never,\n actor\n );\n }) as EventGate;\n}\n\n/**\n * Exactly what the registry serves, keyed by event name — no intermediates.\n *\n * The per-state `view` is installed directly on each state rather than\n * returned: it is event-derived wiring like the rest, and handing it back for\n * the caller to install would put the composition back where it came from.\n *\n * @internal\n */\nexport type BuiltEvents = {\n /** Backs `registry.sensitive_fields`. */\n readonly sensitive: Map<string, readonly string[]>;\n /**\n * The sensitive-type advisory, naming each sensitive `Event.field`, and\n * `State.field` of its name, that a redaction marker doesn't fit; or\n * `undefined` when there are none. The builder logs it once.\n */\n readonly advisory: string | undefined;\n /** Backs `registry.query_gate` — the actor-less read surfaces. */\n readonly query_readers: Map<string, EventGate>;\n /** Readers for handlers — sensitive keys removed, payload typed. */\n readonly handler_readers: Map<string, EventGate>;\n};\n\n/** What validation needs to know about the projections already registered. */\nexport type TargetOwners = {\n readonly batch_handlers: ReadonlyMap<string, unknown>;\n readonly fold_targets: ReadonlySet<string>;\n /** A projection's own reactions legitimately target it — excluded by identity. */\n readonly projection_reactions: ReadonlySet<unknown>;\n};\n\ntype EventEntry = {\n schema: import(\"zod\").ZodType;\n reactions: Map<string, { handler: any; resolver: unknown }>;\n};\n\n/**\n * Validate every static reaction and wire every event, in a single walk.\n *\n * Ownership conflicts throw as they are found; lane violations are collected\n * and thrown afterwards. That ordering is deliberate — it preserves the\n * precedence the two separate passes had, where the ownership guard ran to\n * completion before lane references were checked, so a config violating both\n * reports the same error it always did.\n *\n * @internal\n */\nexport function build_events(\n registry: Registry<any, any, any>,\n states: ReadonlyMap<string, any>,\n lanes: ReadonlyArray<LaneConfig>,\n owners: TargetOwners\n): BuiltEvents {\n const declared = new Set<string>([DEFAULT_LANE, ...lanes.map((l) => l.name)]);\n const lane_errors: string[] = [];\n\n const tags = new Map<string, EventTags>();\n const sensitive = new Map<string, readonly string[]>();\n const query_readers = new Map<string, EventGate>();\n const handler_readers = new Map<string, EventGate>();\n\n for (const [event_name, def] of Object.entries(\n registry.events as Record<string, EventEntry>\n )) {\n for (const [handler_name, reaction] of def.reactions) {\n // A build-time guard can only see a static target: a `.to(fn)` target\n // is unknowable until an event arrives.\n if (typeof reaction.resolver === \"function\") continue;\n const resolver = reaction.resolver as { target: string; lane?: string };\n\n const claimed =\n owners.batch_handlers.has(resolver.target) ||\n owners.fold_targets.has(resolver.target);\n if (claimed && !owners.projection_reactions.has(reaction))\n throw new Error(\n `Reaction on target \"${resolver.target}\" conflicts with the projection that already serves it — a target is served by one batch handler or one state projection, and a reaction to it would never run`\n );\n\n if (resolver.lane !== undefined && !declared.has(resolver.lane))\n lane_errors.push(\n `Reaction \"${handler_name}\" on \"${event_name}\" targets undeclared lane \"${resolver.lane}\". ` +\n `Declared lanes: ${[...declared].map((l) => `\"${l}\"`).join(\", \")}. ` +\n `Add \\`.withLane({ name: \"${resolver.lane}\", ... })\\` to act() or correct the .to() declaration.`\n );\n }\n\n // One resolution of the declared schema yields both facts a reader is\n // built from: which fields are sensitive, and how to type the payload.\n const event = event_tags(def.schema);\n tags.set(event_name, event);\n const fields = Object.keys(event.sensitive);\n if (fields.length > 0) sensitive.set(event_name, fields);\n\n // An event needing neither typing nor redaction produces no reader and\n // falls back to the shared IDENTITY_GATE — zero per-event cost.\n const query_reader = make_event_reader(event, \"redact\", null);\n if (query_reader) query_readers.set(event_name, query_reader);\n\n // Handlers never see PII by framework rule, and shouldn't observe the\n // keys structurally either — so `strip`, not `redact`.\n const handler_reader = make_event_reader(event, \"strip\");\n if (handler_reader) {\n handler_readers.set(event_name, handler_reader);\n for (const [name, reaction] of def.reactions) {\n const inner = reaction.handler;\n const wrapped = (evt: any, stream: string, app: any) =>\n inner(handler_reader(evt), stream, app);\n // Preserve handler.name — build_handle asserts on named functions.\n Object.defineProperty(wrapped, \"name\", { value: inner.name });\n reaction.handler = wrapped;\n def.reactions.set(name, reaction as never);\n }\n }\n }\n\n if (lane_errors.length > 0) throw new Error(lane_errors[0]);\n\n // Per-state wiring, all of it derived from the same event resolution: the\n // read view, the write split, and the guard that refuses to combine the two\n // things that cannot coexist.\n //\n // A sensitive field reads as \"[REDACTED]\" or \"[SHREDDED]\" to a caller who\n // may not see it, and so does any state field a reducer copies it into: a\n // string. A field typed as anything else then holds a value its type\n // doesn't allow, so it is named in the advisory. A state field is matched by\n // name; a copy under another name can't be seen from the types.\n const advised = new Set<string>();\n for (const state of states.values()) {\n const shape: Record<string, z.ZodType> = state.state.shape ?? {};\n const state_fields = new Map<string, readonly string[]>();\n for (const event_name of Object.keys(state.events)) {\n const fields = sensitive.get(event_name);\n if (!fields) continue;\n state_fields.set(event_name, fields);\n const event = tags.get(event_name) as EventTags;\n for (const field of fields) {\n if (!reads_as_string(event.sensitive[field]))\n advised.add(`${event_name}.${field}`);\n if (shape[field] && !reads_as_string(shape[field]))\n advised.add(`${state.name}.${field}`);\n }\n }\n\n if (state_fields.size > 0) {\n // Snapshots write derived state into `__snapshot__.data`, which\n // `forget_pii` cannot reach. Reject the combination at build so the\n // misconfiguration surfaces in dev/CI, not as a silent leak past the\n // GDPR boundary months later.\n if (state.snap)\n throw new Error(\n `State \"${state.name}\" cannot snapshot — events {${[...state_fields.keys()].join(\", \")}} carry sensitive fields. ` +\n \"Snapshots write derived state into __snapshot__.data, which forget_pii cannot reach. \" +\n \"Remove .snap() or remove sensitive(...) markers.\"\n );\n state.pii_aware = true;\n // The write half: split declared fields into the `pii` sidecar on the\n // way to `Store.commit`.\n state.message = (validated: { name: string }) => {\n const fields = state_fields.get(validated.name);\n return fields ? pii_split(validated as never, fields) : validated;\n };\n }\n\n // The read half. A state's disclosure predicate is an input to the\n // reader, not a second gate layered over it. A `__snapshot__` carries\n // folded STATE rather than event data, so its typing comes from the state\n // schema — without that a restart from a snapshot loses every `z.date()`\n // the state holds.\n const readers = new Map<string, EventGate>();\n for (const event_name of Object.keys(state.events)) {\n const event = tags.get(event_name);\n const reader =\n event && make_event_reader(event, \"redact\", state.disclose ?? null);\n if (reader) readers.set(event_name, reader);\n }\n const snap = make_event_reader(event_tags(state.state), \"redact\", null);\n if (snap) readers.set(SNAP_EVENT, snap);\n if (readers.size === 0) continue;\n state.view = (event: { name: string }, actor: Actor) =>\n (readers.get(event.name) ?? IDENTITY_GATE)(event as never, actor);\n }\n\n const advisory =\n advised.size > 0\n ? `Act has ${advised.size} sensitive field(s) whose type isn't a string: ${[...advised].join(\", \")}. ` +\n `A caller who may not see one reads \"[REDACTED]\" or \"[SHREDDED]\" there instead, ` +\n `which its type doesn't allow. Declare sensitive fields as strings. ` +\n `See docs/docs/guides/sensitive-data.md.`\n : undefined;\n return { sensitive, advisory, query_readers, handler_readers };\n}\n\n// Whether a schema's value is a string, so a redaction marker fits its type.\n// A transform's output can't be known, so it counts as a string rather than\n// be named falsely.\nfunction reads_as_string(schema: z.ZodType): boolean {\n const type = def_of(output_of(schema))?.type;\n return type === \"string\" || type === \"transform\";\n}\n","/**\n * Turning stored text back into `Date`s, driven by the declared schema.\n *\n * JSON has no date type, so a `Date` is stored as its ISO form. Which fields\n * to revive is a property of the Zod schema, so this module takes a schema\n * and returns one that revives its dates (or `undefined` when there are\n * none); it knows nothing about events. A field declared `z.string()` stays\n * a string even when it looks like an ISO date.\n */\n\nimport { z } from \"zod\";\nimport { def_of, inner_of } from \"./zod.js\";\n\ntype Walk = (schema: unknown) => z.ZodType | undefined;\n\n/**\n * Rebuild one union variant so it still recognises its own payloads.\n *\n * Same date coercion as everywhere else, but the variant keeps its other\n * fields — this is the one place the date paths alone are not enough. A\n * variant can only reject a sibling's payload if enough of its shape is left\n * to check, and which fields do that is not knowable: a literal discriminator\n * usually does it, but a union can just as well be told apart by the *type* of\n * an ordinary field. Narrowing to the dates, or relaxing the rest, makes the\n * first variant match everything, so the one that declared the date is never\n * tried and a sibling's payload is read under the wrong rules.\n *\n * Every key is optional, so the variant still matches when a `sensitive(...)`\n * field sits in the `pii` sidecar or when a stored payload predates a field\n * the declaration has since gained.\n *\n * Reports whether this variant declared a date, so a union with none anywhere\n * builds nothing at all.\n */\nfunction variant_schema(\n schema: unknown,\n walk: Walk\n): {\n schema: z.ZodType;\n dated: boolean;\n} {\n const shape = def_of(schema)?.shape as Record<string, z.ZodType> | undefined;\n if (!shape) {\n const dates = walk(schema);\n return { schema: dates ?? (schema as z.ZodType), dated: !!dates };\n }\n const next: Record<string, z.ZodType> = {};\n let dated = false;\n for (const [key, field] of Object.entries(shape)) {\n const dates = walk(field);\n if (dates) dated = true;\n next[key] = (dates ?? field).optional();\n }\n return { schema: z.looseObject(next), dated };\n}\n\n/**\n * Build the schema that revives an event's dates, or `undefined` when it\n * declares none.\n *\n * JSON has no date type, so a stored `Date` comes back as text and something\n * has to turn it back. That is this function's only job, and the schema it\n * returns says only where the dates are: every other field is left out and\n * rides through the loose object untouched. The payload was validated when it\n * was committed, so re-checking it on the way out would be work already done.\n *\n * Naming only the dates is also what makes a read tolerant, without needing a\n * rule per exception. A `sensitive(...)` field lives in the `pii` sidecar\n * rather than in `data`; an event written against an older declaration\n * predates whatever was added since; a field dropped from the declaration is\n * still in the store. None of those are dates, so none of them are described\n * here, and a payload carrying any of them still reads. The dates themselves\n * are optional for the same reason — absent is not wrong.\n *\n * Zod does the walking, so nesting, arrays, records, unions and the wrappers\n * are handled by the engine rather than by a traversal of our own that would\n * drift as Zod grows constructs. A construct this doesn't recognise\n * contributes no date, which is the documented fallthrough.\n *\n * A recursive schema is walked twice. The first pass stops at any schema it is\n * already inside, which visits everything reachable and answers whether there\n * is a date at all, so a recursive schema with none still builds nothing. The\n * second ties each of those stops back to the schema's own result.\n */\nexport function date_reviver_schema(schema: unknown): z.ZodType | undefined {\n let recursive = false;\n const pass = (tie: boolean): z.ZodType | undefined => {\n const done = new Map<unknown, z.ZodType | undefined>();\n const active = new Set<unknown>();\n const walk: Walk = (node) => {\n if (done.has(node)) return done.get(node);\n if (active.has(node)) {\n recursive = true;\n // Every schema on a cycle has a result by the time this reads it.\n return tie ? z.lazy(() => done.get(node) as z.ZodType) : undefined;\n }\n active.add(node);\n const result = build(node, walk);\n active.delete(node);\n done.set(node, result);\n return result;\n };\n return walk(schema);\n };\n const first = pass(false);\n return first && recursive ? pass(true) : first;\n}\n\nfunction build(schema: unknown, walk: Walk): z.ZodType | undefined {\n const def = def_of(schema);\n if (!def) return undefined;\n const inner = () => walk(def.innerType);\n switch (def.type) {\n case \"date\":\n return z.coerce.date();\n case \"object\": {\n const shape = def.shape as Record<string, z.ZodType> | undefined;\n if (!shape) return undefined;\n const dated: Record<string, z.ZodType> = {};\n for (const [key, field] of Object.entries(shape)) {\n const dates = walk(field);\n if (dates) dated[key] = dates.optional();\n }\n return Object.keys(dated).length ? z.looseObject(dated) : undefined;\n }\n case \"array\": {\n const element = walk(def.element);\n return element && z.array(element);\n }\n case \"tuple\": {\n const items = (def.items as unknown[]).map((i) => walk(i));\n return items.some(Boolean)\n ? z.tuple(items.map((i) => i ?? z.unknown()) as never)\n : undefined;\n }\n case \"record\": {\n const value = walk(def.valueType);\n return value && z.record(z.string(), value);\n }\n case \"union\": {\n // A union is the one place the date paths are not enough. Zod picks a\n // variant by trying each until one matches, so an option reduced to its\n // dates matches almost anything and the first one wins — the variant\n // that actually declared the date never gets tried, and a sibling's\n // payload gets the wrong variant's rules. Every option therefore keeps\n // its fields; see {@link variant_schema}.\n const variants = (def.options as unknown[]).map((o) =>\n variant_schema(o, walk)\n );\n return variants.some((v) => v.dated)\n ? z.union(variants.map((v) => v.schema) as never)\n : undefined;\n }\n case \"nullable\":\n // Keep the null: coercing it would hand back the epoch.\n return inner()?.nullable();\n case \"pipe\":\n // `z.preprocess()` and `.pipe()`: the stored value is the output side.\n // A `.transform()`'s output is unknown, so it revives nothing.\n return walk(def.out);\n case \"lazy\":\n return walk((def.getter as () => unknown)());\n case \"intersection\": {\n // One side after the other, not a Zod intersection: each side keeps the\n // fields it doesn't revive, so the two results wouldn't merge.\n const left = walk(def.left);\n const right = walk(def.right);\n return left && right ? left.pipe(right) : (left ?? right);\n }\n default:\n return inner_of(def) ? inner() : undefined;\n }\n}\n","/**\n * @module act-builder\n * @category Builders\n *\n * Fluent builder for composing event-sourced applications.\n */\nimport { Act } from \"../act.js\";\nimport { synthesize_autoclose_reactions } from \"../internal/autoclose-reaction.js\";\nimport { resolveActConfig } from \"../internal/config.js\";\nimport {\n current_version_of,\n deprecated_event_names,\n} from \"../internal/event-versions.js\";\nimport { type EventGate, IDENTITY_GATE } from \"../internal/pii.js\";\nimport {\n FOLD_RESET,\n make_fold_handler,\n type ResettableBatchHandler,\n} from \"../internal/projection-fold.js\";\nimport { log } from \"../ports.js\";\nimport { current_autoclose_window } from \"../scoped.js\";\nimport type { ActBuilder, Projection } from \"../types/builders.js\";\nimport type {\n ActOptions,\n Actor,\n BatchHandler,\n LaneConfig,\n Load,\n Registry,\n Schema,\n SchemaRegister,\n Schemas,\n State,\n} from \"../types/index.js\";\nimport { reaction_on, register_lane } from \"./builder-utils.js\";\nimport { build_events } from \"./event-builder.js\";\nimport {\n merge_event_register,\n merge_projection,\n register_state,\n} from \"./merge.js\";\n\n/**\n * Registers a projection's batch handler against its target stream, throwing\n * if a different handler already serves it. Folds (`.of(...)`) have no\n * batch handler; their side of the check is in `build()`.\n */\nfunction register_batch_handler(\n proj: Projection<any>,\n batch_handlers: Map<string, BatchHandler<any>>\n): void {\n if (!proj.batchHandler || !proj.target) return;\n const existing = batch_handlers.get(proj.target);\n if (existing && existing !== proj.batchHandler) {\n throw new Error(\n `Duplicate projection target \"${proj.target}\" — a target is served by one batch handler or one state projection, never both`\n );\n }\n batch_handlers.set(proj.target, proj.batchHandler);\n}\n\n/**\n * Creates a new Act orchestrator builder for composing event-sourced applications.\n *\n * @example Basic application with single state\n * ```typescript\n * const app = act()\n * .withState(Counter)\n * .build();\n * ```\n *\n * @see {@link ActBuilder} for available builder methods\n * @see {@link Act} for orchestrator API methods\n * @see {@link state} for defining states\n * @see {@link slice} for defining slices\n */\nexport function act(): ActBuilder<{}, {}, {}, {}, Actor>;\nexport function act<\n TSchemaReg extends SchemaRegister<TActions>,\n TEvents extends Schemas = {},\n TActions extends Schemas = {},\n TStateMap extends Record<string, Schema> = {},\n TActor extends Actor = Actor,\n>(): ActBuilder<TSchemaReg, TEvents, TActions, TStateMap, TActor>;\nexport function act<\n TSchemaReg extends SchemaRegister<TActions>,\n TEvents extends Schemas = {},\n TActions extends Schemas = {},\n TStateMap extends Record<string, Schema> = {},\n TActor extends Actor = Actor,\n>(): ActBuilder<TSchemaReg, TEvents, TActions, TStateMap, TActor> {\n // Mutable runtime state — one set of references shared across the entire\n // fluent chain. Each `with*` / `on` call mutates these and returns the\n // same builder cast to the widened generic; type fanout is preserved\n // through the public type signatures, runtime allocation is not.\n const states = new Map<string, State<any, any, any>>();\n // Caches behind the registry's derived lookups, populated on the first\n // `.build()`. Each event schema is walked once.\n const _sf = new Map<string, readonly string[]>();\n // Prebuilt handler readers — sensitive keys removed, payload typed. Absent\n // when the event needs neither.\n const _hr = new Map<string, EventGate>();\n // Prebuilt default-deny read gates, one per sensitive event. Non-sensitive\n // events are absent → `query_gate` falls back to the shared IDENTITY_GATE.\n const _qg = new Map<string, EventGate>();\n const _dp = new Map<string, (event: any, actor: Actor) => boolean>();\n const _de = new Map<string, ReadonlySet<string>>();\n const _ac = new Map<\n string,\n (stream: string, head: any, count: number) => boolean\n >();\n const _aa = new Map<string, (stream: string, head: any) => Promise<void>>();\n const EMPTY_DEPRECATED: ReadonlySet<string> = new Set();\n const registry: Registry<TSchemaReg, TEvents, TActions> = {\n actions: {} as Registry<TSchemaReg, TEvents, TActions>[\"actions\"],\n events: {} as Registry<TSchemaReg, TEvents, TActions>[\"events\"],\n sensitive_fields: (event_name) => _sf.get(event_name) ?? [],\n query_gate: (event_name) => _qg.get(event_name) ?? IDENTITY_GATE,\n disclosure_predicate: (state_name) => _dp.get(state_name) ?? null,\n deprecated_events: (state_name) => _de.get(state_name) ?? EMPTY_DEPRECATED,\n autoclose_policy: (state_name) => _ac.get(state_name) ?? null,\n autoclose_archiver: (state_name) => _aa.get(state_name) ?? null,\n };\n const pending_projections: Projection<any>[] = [];\n /**\n * Reactions contributed by projections, recorded at registration. Only\n * these may target a projection's stream; anything else is a collision.\n */\n const projection_reactions = new Set<unknown>();\n const record_projection_reactions = (proj: Projection<any>) => {\n // Only a projection that SERVES its target (a batch handler or a fold)\n // owns it. A per-event projection naming the same target is just another\n // claimant: exempting it let it share a fold's or batch's target, where\n // its handler never ran and the fold wrote foreign rows.\n if (!proj.batchHandler && !proj.fold) return;\n for (const register of Object.values(\n proj.events as Record<string, { reactions: Map<string, unknown> }>\n ))\n for (const reaction of register.reactions.values())\n projection_reactions.add(reaction);\n };\n const fold_projections: Projection<any>[] = [];\n const batch_handlers = new Map<string, BatchHandler<any>>();\n const add_projection = (proj: Projection<any>) => {\n record_projection_reactions(proj);\n merge_projection(proj, registry.events as Record<string, any>);\n register_batch_handler(proj, batch_handlers);\n if (proj.fold) fold_projections.push(proj);\n };\n // Validated fold-projection ingredients, resolved once on the first\n // build. The HANDLERS themselves are built per `.build()` — see\n // `make_batch_handlers` — because a fold handler owns a mutable\n // per-stream cache that must never be shared across Acts.\n const fold_specs: {\n target: string;\n /** Identity of the registering projection, so a repeat registration of\n * the same object is recognized as one claim rather than two. */\n projection: Projection<any>;\n merged: any;\n flush: any;\n config: any;\n }[] = [];\n const lanes: LaneConfig[] = [];\n\n // Set on the first `.build()` call. Lets the same builder produce\n // many Acts (multi-tenant / A-B testing patterns) without re-merging\n // projections or re-logging the deprecation advisory.\n let _built = false;\n\n /**\n * Wraps a batch handler so it receives events in handler form — payload\n * typed from the declared schema, sensitive keys removed — the same reader\n * `event-builder` gives per-event handlers. Resolved lazily at dispatch, by\n * when the events pass has populated it.\n */\n const read_wrap = (original: BatchHandler<any>): BatchHandler<any> => {\n const wrapped = async (events: readonly any[], stream: string) => {\n // The same prebuilt reader the per-event handlers get: typed payload,\n // sensitive keys removed. Absent → the event passes through untouched.\n const read = events.map((e) => _hr.get(e.name as string)?.(e) ?? e);\n return original(read as never, stream);\n };\n // Carry the fold's cache-reset handle through the wrapper. The\n // orchestrator only ever sees what this map holds, so a handle left on\n // the inner handler is a handle nobody can reach.\n const reset = (original as ResettableBatchHandler<any>)[FOLD_RESET];\n if (reset) Object.defineProperty(wrapped, FOLD_RESET, { value: reset });\n return wrapped;\n };\n\n /**\n * Per-Act batch-handler map. Stateless handlers are shared; fold\n * handlers own a per-stream cache, so each `.build()` gets fresh ones.\n */\n const make_batch_handlers = () => {\n const handlers = new Map(batch_handlers);\n for (const spec of fold_specs) {\n handlers.set(\n spec.target,\n read_wrap(\n make_fold_handler(\n spec.merged,\n spec.flush,\n spec.config,\n // Head loads strip sensitive keys like the warm path.\n registry.sensitive_fields\n )\n ) as never\n );\n }\n return handlers;\n };\n\n // Versioned events: per state, the highest `_v<n>` is current and lower\n // ones are deprecated (`registry.deprecated_events`). A static\n // `.emit(\"X\")` of a deprecated event throws; a one-line advisory lists\n // the legacy events kept for replay.\n const finalize_deprecations = () => {\n const deprecation_summary: Array<{\n state_name: string;\n deprecated: string;\n current: string;\n }> = [];\n for (const state of states.values()) {\n const event_names = Object.keys(state.events);\n const deprecated = deprecated_event_names(event_names);\n if (deprecated.size === 0) continue;\n _de.set(state.name, deprecated);\n for (const name of deprecated) {\n // `current_version_of` is guaranteed non-undefined here — `name`\n // is in `deprecated`, which by construction means a higher-\n // versioned sibling exists in the same group.\n const current = current_version_of(name, event_names) as string;\n deprecation_summary.push({\n state_name: state.name,\n deprecated: name,\n current,\n });\n }\n for (const [action_name, handler] of Object.entries(state.on)) {\n const static_target = (handler as { _static_emit?: string } | undefined)\n ?._static_emit;\n if (static_target && deprecated.has(static_target)) {\n const current = current_version_of(static_target, event_names);\n throw new Error(\n `Action \"${action_name}\" in state \"${state.name}\" emits deprecated event \"${static_target}\". ` +\n `A newer version exists: \"${current}\". Update the .emit() call ` +\n `to target the current version. The reducer (.patch) for ` +\n `\"${static_target}\" stays as-is — historical events still need it.`\n );\n }\n }\n }\n if (deprecation_summary.length > 0) {\n const list = deprecation_summary\n .map(\n (d) =>\n `\"${d.deprecated}\" (current: \"${d.current}\", state: \"${d.state_name}\")`\n )\n .join(\", \");\n log().info(\n `Act registered ${deprecation_summary.length} deprecated event(s): ${list}. ` +\n `These are legacy versions kept for the read path. Consider truncating ` +\n `closed streams via app.close() when feasible to reduce historical event load. ` +\n `See docs/docs/architecture/event-schema-evolution.md.`\n );\n }\n };\n\n /**\n * Registration is closed once `build()` has classified the registry: every\n * mutating method throws a clear error after it. `build()` itself stays\n * callable repeatedly, since the multi-tenant pattern calls\n * `.build({scoped})` per tenant and registers nothing.\n */\n const closed = (method: string): never => {\n throw new Error(\n `act().${method}() was called after build(); the registry is already classified. Register everything before build() — build() itself may be called repeatedly (e.g. once per tenant with ActOptions.scoped).`\n );\n };\n\n // The `as` chain on `self` is the type fanout: each fluent method\n // mutates state and returns `self` cast to its post-call generic\n // signature. Internal-only — public types stay narrow.\n const builder: ActBuilder<TSchemaReg, TEvents, TActions, TStateMap, TActor> =\n {\n withState: (state) => {\n if (_built) closed(\"withState\");\n register_state(state, states, registry.actions, registry.events);\n return builder as never;\n },\n withSlice: (input) => {\n if (_built) closed(\"withSlice\");\n for (const s of input.states.values()) {\n register_state(s, states, registry.actions, registry.events);\n }\n merge_event_register(registry.events, input.events);\n pending_projections.push(...input.projections);\n for (const lane of input.lanes) register_lane(lane, lanes);\n return builder as never;\n },\n withProjection: (proj) => {\n if (_built) closed(\"withProjection\");\n add_projection(proj as Projection<any>);\n return builder;\n },\n withActor: <TNewActor extends Actor>() =>\n builder as unknown as ActBuilder<\n TSchemaReg,\n TEvents,\n TActions,\n TStateMap,\n TNewActor\n >,\n withLane: (config) => {\n if (_built) closed(\"withLane\");\n register_lane(config, lanes);\n return builder as never;\n },\n on: <TKey extends keyof TEvents>(event: TKey) => {\n if (_built) closed(\"on\");\n return reaction_on(event, registry.events, builder) as never;\n },\n build: (options?: ActOptions) => {\n // Validate the top-level scalar knobs at build (the nested autoclose /\n // circuitBreaker bags are validated by their own resolvers). A bad\n // maxSubscribedStreams / settleDebounceMs throws ZodError here.\n resolveActConfig(options);\n // Finalize once: repeated builds (per tenant) share the registry.\n if (!_built) {\n for (const proj of pending_projections) add_projection(proj);\n // State projections fold the registry-merged FULL state — the\n // builder only recorded intent. Resolve here, where every\n // partial has merged, and refuse silently-partial folds: the\n // projection's register must cover the state's whole register.\n for (const proj of fold_projections) {\n const fold = proj.fold!;\n const merged = states.get(fold.name);\n if (!merged)\n throw new Error(\n `State projection \"${proj.target}\" folds \"${fold.name}\", which is not registered — add it via withState/withSlice before build()`\n );\n const missing = Object.keys(merged.events).filter(\n (event_name) => !(event_name in proj.events)\n );\n if (missing.length > 0)\n throw new Error(\n `State projection \"${proj.target}\" of \"${fold.name}\" is missing events ${missing.join(\", \")} — pass every partial of the state to .of()`\n );\n // A target is claimed once, by a batch handler or a fold; two\n // different projections on one target throw. The same projection\n // registered twice is fine.\n const claimed = fold_specs.find((s) => s.target === proj.target);\n if (claimed?.projection === proj) continue;\n if (batch_handlers.has(proj.target!) || claimed)\n throw new Error(\n `Duplicate projection target \"${proj.target}\" — a target is served by one batch handler or one state projection, never both`\n );\n // Record the validated ingredients only. The handler is\n // constructed per `.build()` (see `make_batch_handlers`) — it\n // owns a mutable per-stream fold cache, so one shared instance\n // would leak folded rows between Acts built from this builder.\n fold_specs.push({\n target: proj.target!,\n projection: proj,\n merged,\n flush: fold.flush,\n config: fold.config,\n });\n }\n // An ordinary reaction on a projection's target would never run and\n // would feed the fold another aggregate, so `build_events` rejects\n // it (the projection's own reactions are exempt).\n //\n // One walk over the registered events: validate every static\n // reaction, resolve each schema once, and compose the per-surface\n // readers from it. See `event-builder.ts`.\n const built = build_events(registry, states, lanes, {\n batch_handlers,\n fold_targets: new Set(fold_specs.map((f) => f.target)),\n projection_reactions,\n });\n for (const [name, fields] of built.sensitive) _sf.set(name, fields);\n for (const [name, gate] of built.query_readers) _qg.set(name, gate);\n for (const [name, gate] of built.handler_readers) _hr.set(name, gate);\n finalize_deprecations();\n if (built.advisory) log().warn(built.advisory);\n\n // A load reads and writes through this Act's store, so it must name\n // a registered state; it resolves to the merged one, partials and all.\n // The resolved loads go on a copy this Act owns: the state object\n // the app passed in may be registered in other Acts, with other\n // partials of the loaded state.\n for (const [name, state] of states) {\n if (!state.loads) continue;\n const resolved: Record<string, Load[]> = {};\n for (const [action, loads] of Object.entries(state.loads)) {\n resolved[action] = loads!.map((l) => {\n const registered = states.get(l.state.name);\n if (!registered)\n throw new Error(\n `Action \"${action}\" loads \"${l.state.name}\", which is not registered — add it via withState/withSlice before build()`\n );\n // An event listed on a load is emitted as statically as\n // `.emit(\"X\")`, so a deprecated one throws the same way.\n const deprecated = l.events.find((e) =>\n _de.get(registered.name)?.has(e)\n );\n if (deprecated)\n throw new Error(\n `Action \"${action}\" lists deprecated event \"${deprecated}\" on its load of \"${registered.name}\". ` +\n `A newer version exists: \"${current_version_of(deprecated, Object.keys(registered.events))}\". ` +\n `List the current version instead.`\n );\n return { ...l, state: registered };\n });\n }\n for (const [action, loads] of Object.entries(resolved)) {\n const static_target = (\n state.on[action] as { _static_emit?: string }\n )._static_emit;\n if (\n static_target &&\n loads.some((l) => l.events.includes(static_target))\n )\n throw new Error(\n `Action \"${action}\" statically emits \"${static_target}\", which its load lists, so nothing goes to its own stream; emit one of its own events too`\n );\n }\n const own = { ...state, loads: resolved };\n states.set(name, own);\n for (const action of Object.keys(own.actions))\n (registry.actions as Record<string, unknown>)[action] = own;\n }\n\n for (const state of states.values()) {\n if (state.disclose) _dp.set(state.name, state.disclose);\n if (state.autoclose) _ac.set(state.name, state.autoclose);\n if (state.archive) _aa.set(state.name, state.archive);\n }\n for (const [target, original] of batch_handlers) {\n batch_handlers.set(target, read_wrap(original) as never);\n }\n // Synthesize the autoclose reactions last, once the registry is\n // fully merged — their dynamic resolvers must be present before\n // the orchestrator classifies the registry.\n //\n // Nothing per-Act is captured: repeat builds share these reactions,\n // and the off-hours window comes from the running Act's frame.\n synthesize_autoclose_reactions(\n registry,\n states,\n current_autoclose_window\n );\n // Freeze the registry shape; the `_built` latch on each method stops\n // later registration (freezing doesn't seal the reaction `Map`s).\n Object.freeze(registry.actions);\n Object.freeze(registry.events);\n Object.freeze(registry);\n _built = true;\n }\n\n return new Act<TSchemaReg, TEvents, TActions, TStateMap, TActor>(\n registry,\n states,\n make_batch_handlers(),\n options,\n lanes\n );\n },\n events: registry.events,\n };\n return builder;\n}\n","import {\n DEFAULT_BLOCK_ON_ERROR,\n DEFAULT_MAX_RETRIES,\n resolveFoldConfig,\n} from \"../internal/config.js\";\nimport type {\n EventEntry,\n Projection,\n ProjectionBuilder,\n} from \"../types/builders.js\";\nimport type {\n BatchHandler,\n CacheEntry,\n Committed,\n EventRegister,\n FoldOptions,\n Schema,\n Schemas,\n State,\n} from \"../types/index.js\";\nimport { add_reaction } from \"./builder-utils.js\";\nimport { _this_ } from \"./merge.js\";\n\n/**\n * @internal Build the core builder object (shared between overloads). One\n * mutable `events` register threaded through every fluent call; .on()\n * mutates and returns the same builder cast to its widened generic.\n */\nfunction _projection<\n TEvents extends Schemas,\n TTarget extends string | undefined,\n>(target: TTarget): ProjectionBuilder<TEvents, TTarget> {\n const events = {} as EventRegister<TEvents>;\n const default_resolver: { target: string } | undefined =\n typeof target === \"string\" ? { target } : undefined;\n\n // Mutable runtime bag — typed loosely; the public projection() return\n // type narrows back to the user-facing `ProjectionBuilder<TEvents, TTarget>`.\n\n const base: any = {\n on: <TKey extends string, TData extends Schema>(\n entry: EventEntry<TKey, TData>\n ) => {\n const keys = Object.keys(entry);\n if (keys.length !== 1) throw new Error(\".on() requires exactly one key\");\n const event = keys[0] as TKey;\n const schema = entry[event];\n\n // Register the event schema if not already present\n if (!(event in events)) {\n (events as Record<string, unknown>)[event] = {\n schema,\n reactions: new Map(),\n };\n }\n\n return {\n do: (\n handler: (\n event: Committed<TEvents & { [P in TKey]: TData }, TKey>,\n stream: string\n ) => Promise<void>\n ) => {\n // Same builder, widened generic — no recursive call.\n const widened = base as unknown as ProjectionBuilder<\n TEvents & { [P in TKey]: TData },\n TTarget\n >;\n return add_reaction(\n events as unknown as EventRegister<\n TEvents & { [P in TKey]: TData }\n >,\n event,\n handler.name,\n \"Projection\",\n () => ({\n handler,\n resolver: default_resolver ?? _this_,\n options: {\n blockOnError: DEFAULT_BLOCK_ON_ERROR,\n maxRetries: DEFAULT_MAX_RETRIES,\n },\n }),\n widened\n );\n },\n };\n },\n build: () => ({\n _tag: \"Projection\" as const,\n events,\n ...(target !== undefined && { target }),\n }),\n events,\n };\n\n // Add .batch() and .of() only for static-target projections\n if (typeof target === \"string\") {\n return Object.assign(base, {\n batch: (handler: BatchHandler<TEvents>) => ({\n build: () => ({\n _tag: \"Projection\" as const,\n events,\n target,\n batchHandler: handler,\n }),\n }),\n of: (...args: unknown[]) => {\n if (Object.keys(events).length > 0)\n throw new Error(\n `Projection \"${target}\" mixes .of() with .on() handlers — a projection either folds a state or declares handlers, never both`\n );\n // Trailing options bag is the only non-State argument.\n const is_state = (a: unknown): a is State<Schema, Schemas, Schemas> =>\n !!a &&\n typeof (a as State<Schema, Schemas, Schemas>).init === \"function\";\n const partials = args.filter(is_state);\n const options = (args.find((a) => !is_state(a)) ?? {}) as FoldOptions;\n if (partials.length === 0)\n throw new Error(`Projection \"${target}\" .of() requires a state`);\n const name = partials[0].name;\n for (const partial of partials)\n if (partial.name !== name)\n throw new Error(\n `Projection \"${target}\" .of() partials must share one state name — got \"${name}\" and \"${partial.name}\"`\n );\n // Misconfiguration surfaces here, at startup — not on first drain.\n const config = resolveFoldConfig(options);\n // The partials' own schema instances register the events, so the\n // same-name declarations in slices pass the identity check in\n // merge_event_register. The named no-op reaction routes fetches\n // to this target; dispatch always goes through the batch handler\n // the orchestrator synthesizes from the registry-merged state.\n const fold_events = {} as EventRegister<Schemas>;\n for (const partial of partials)\n for (const [event_name, schema] of Object.entries(partial.events)) {\n if (event_name in fold_events) continue;\n const noop = {\n [`${target}_fold`]: async () => {},\n }[`${target}_fold`] as (\n event: Committed<Schemas, string>,\n stream: string\n ) => Promise<void>;\n (fold_events as Record<string, unknown>)[event_name] = {\n schema,\n reactions: new Map([\n [\n `${target}_fold`,\n {\n handler: noop,\n resolver: { target },\n options: {\n blockOnError: DEFAULT_BLOCK_ON_ERROR,\n maxRetries: DEFAULT_MAX_RETRIES,\n },\n },\n ],\n ]),\n };\n }\n return {\n flush: (\n handler: (rows: ReadonlyArray<CacheEntry<Schema>>) => Promise<void>\n ) => ({\n build: () => ({\n _tag: \"Projection\" as const,\n events: fold_events,\n target,\n fold: { name, flush: handler, config },\n }),\n }),\n };\n },\n }) as ProjectionBuilder<TEvents, TTarget>;\n }\n\n return base as ProjectionBuilder<TEvents, TTarget>;\n}\n\n/**\n * Creates a new projection builder for composing read-model update handlers,\n * with a static target stream.\n *\n * Projections enable separation of read-model concerns from command handling.\n * Each `.on({ Event }).do(handler)` call registers a handler that updates\n * a projection (database table, cache, etc.) in response to events. All\n * handlers inherit the target resolver automatically, and `.batch()` is\n * enabled for bulk event processing in a single transaction. Omit the target\n * and use per-handler `.to()` when handlers route to different streams.\n *\n * @param target - Static target stream for all handlers\n *\n * @example Default target (all handlers routed to \"tickets\")\n * ```typescript\n * const TicketProjection = projection(\"tickets\")\n * .on({ TicketOpened })\n * .do(async function openTicket({ stream, data }) {\n * await db.insert(tickets).values({ id: stream, ...data });\n * })\n * .on({ TicketClosed })\n * .do(async function closeTicket({ stream, data }) {\n * await db.update(tickets).set(data).where(eq(tickets.id, stream));\n * })\n * .build();\n * ```\n *\n * @see {@link ProjectionBuilder} for builder methods\n * @see {@link Projection} for the output type\n */\nexport function projection<TEvents extends Schemas = {}>(\n target: string\n): ProjectionBuilder<TEvents, string>;\n/**\n * Creates a new projection builder without a default target.\n *\n * Use per-handler `.to()` to route events to different streams.\n */\nexport function projection<TEvents extends Schemas = {}>(\n target?: undefined\n): ProjectionBuilder<TEvents, undefined>;\nexport function projection<TEvents extends Schemas = {}>(\n target?: string\n): ProjectionBuilder<TEvents, string | undefined> {\n return _projection<TEvents, string | undefined>(target);\n}\n","/**\n * @module slice-builder\n * @category Builders\n *\n * Fluent builder for composing partial states with scoped reactions into\n * self-contained functional slices (vertical slice architecture).\n */\n\nimport type { Projection, Slice, SliceBuilder } from \"../types/builders.js\";\nimport type {\n Actor,\n EventRegister,\n LaneConfig,\n Schema,\n SchemaRegister,\n Schemas,\n State,\n} from \"../types/index.js\";\nimport { reaction_on, register_lane } from \"./builder-utils.js\";\nimport { register_state } from \"./merge.js\";\n\n/**\n * Creates a new slice builder for composing partial states with scoped reactions.\n *\n * Slices enable vertical slice architecture by grouping related states and\n * reactions into self-contained feature modules. Reactions defined in a slice\n * are type-scoped to events from that slice's states only.\n *\n * @example Single-state slice with typed dispatch\n * ```typescript\n * const CounterSlice = slice()\n * .withState(Counter)\n * .on(\"Incremented\")\n * .do(async function resetCounter(event, _stream, app) {\n * await app.do(\"reset\", target, {});\n * })\n * .to(\"counter-target\")\n * .build();\n * ```\n *\n * @see {@link SliceBuilder} for builder methods\n * @see {@link Slice} for the output type\n */\nexport function slice(): SliceBuilder<{}, {}, {}, {}, Actor>;\nexport function slice<\n TSchemaReg extends SchemaRegister<TActions>,\n TEvents extends Schemas = {},\n TActions extends Schemas = {},\n TStateMap extends Record<string, Schema> = {},\n TActor extends Actor = Actor,\n>(): SliceBuilder<TSchemaReg, TEvents, TActions, TStateMap, TActor>;\nexport function slice<\n TSchemaReg extends SchemaRegister<TActions>,\n TEvents extends Schemas = {},\n TActions extends Schemas = {},\n TStateMap extends Record<string, Schema> = {},\n TActor extends Actor = Actor,\n>(): SliceBuilder<TSchemaReg, TEvents, TActions, TStateMap, TActor> {\n // One mutable state shared across the entire fluent chain. Each\n // `withState` / `withProjection` / `on` call mutates these and returns\n // the same builder cast to the widened generic; type fanout is preserved\n // through the public type signatures, runtime allocation is not.\n const states = new Map<string, State<any, any, any>>();\n const actions: Record<string, any> = {};\n const events = {} as EventRegister<TEvents>;\n const projections: Projection<any>[] = [];\n const lanes: LaneConfig[] = [];\n\n const builder: SliceBuilder<\n TSchemaReg,\n TEvents,\n TActions,\n TStateMap,\n TActor\n > = {\n withState: (state) => {\n register_state(state, states, actions, events as Record<string, unknown>);\n return builder as never;\n },\n withProjection: (proj) => {\n projections.push(proj as Projection<any>);\n return builder;\n },\n withLane: (config) => {\n register_lane(config, lanes);\n return builder as never;\n },\n on: <TKey extends keyof TEvents>(event: TKey) =>\n reaction_on(event, events, builder) as never,\n build: () => ({\n _tag: \"Slice\" as const,\n states,\n events,\n projections,\n lanes,\n }),\n events,\n };\n return builder;\n}\n","/**\n * @module state-builder\n * @category Builders\n *\n * Fluent interface for defining a strongly-typed state machine using Zod schemas.\n */\nimport type { ZodType } from \"zod\";\nimport {\n compile_autoclose_policy,\n policy_after_windows,\n policy_keep_days,\n} from \"../internal/autoclose-policy.js\";\nimport { resolveActionConfig } from \"../internal/config.js\";\nimport type {\n ActionBuilder,\n ActionEntry,\n StateBuilder,\n StateEntry,\n} from \"../types/builders.js\";\nimport type {\n ActionHandler,\n ActionOptions,\n Actor,\n AutocloseArchiver,\n AutoclosePolicy,\n AutoclosePredicate,\n Committed,\n Load,\n PassthroughPatchHandler,\n PatchHandlers,\n Precondition,\n Schema,\n Schemas,\n Snapshot,\n State,\n ZodTypes,\n} from \"../types/index.js\";\n\n/**\n * Creates a new state definition with event sourcing capabilities.\n *\n * States are the core building blocks of Act. Each state represents a consistency\n * boundary (aggregate) that processes actions, emits events, and maintains its own\n * state through event patches (reducers). States use event sourcing to maintain a\n * complete audit trail and enable time-travel capabilities.\n *\n * The state builder provides a fluent API for defining:\n * 1. Initial state via `.init()`\n * 2. Event types via `.emits()` — all events default to passthrough (`({ data }) => data`)\n * 3. Custom event reducers via `.patch()` (optional — only for events that need custom logic)\n * 4. Actions (commands) via `.on()` → `.emit()` — pass an event name string for passthrough\n * 5. Business rules: preconditions via `.requires()`\n * 6. Snapshotting strategy via `.snap()`\n *\n * @template TState - Zod schema type defining the shape of the state\n * @param entry - Single-key record mapping state name to Zod schema (e.g., `{ Counter: z.object({ count: z.number() }) }`)\n * @returns A StateBuilder instance for fluent API configuration\n *\n * @example Basic counter state (with custom patch)\n * ```typescript\n * import { state } from \"@rotorsoft/act\";\n * import { z } from \"zod\";\n *\n * const Counter = state({ Counter: z.object({ count: z.number() }) })\n * .init(() => ({ count: 0 }))\n * .emits({\n * Incremented: z.object({ amount: z.number() })\n * })\n * .patch({ // optional — only for events needing custom reducers\n * Incremented: ({ data }, state) => ({ count: state.count + data.amount })\n * })\n * .on({ increment: z.object({ by: z.number() }) })\n * .emit((action) => [\"Incremented\", { amount: action.by }])\n * .build();\n * ```\n *\n * @see {@link StateBuilder} for available builder methods\n * @see {@link ActionBuilder} for action configuration methods\n * @see {@link https://rotorsoft.github.io/act-root/docs/intro | Getting Started Guide}\n * @see {@link https://rotorsoft.github.io/act-root/docs/examples/calculator | Calculator Example}\n */\nexport function state<TName extends string, TState extends Schema>(\n entry: StateEntry<TName, TState>\n): StateBuilder<TState, TName> {\n const keys = Object.keys(entry);\n if (keys.length !== 1) throw new Error(\"state() requires exactly one key\");\n const name = keys[0] as TName;\n const state_schema = (entry as Record<string, ZodType<TState>>)[name];\n return {\n init(init) {\n return {\n emits<TEvents extends Schema>(events: ZodTypes<TEvents>) {\n // Default passthrough patches: event data merges into state\n const default_patch = Object.fromEntries(\n Object.keys(events).map((k) => {\n const fn = Object.assign(({ data }: { data: any }) => data, {\n _passthrough: true as const,\n }) satisfies PassthroughPatchHandler;\n return [k, fn];\n })\n ) as unknown as PatchHandlers<TState, TEvents>;\n\n // Build one mutable state object the action_builder threads\n // through every fluent call. patch() (if invoked) just mutates\n // the patch map in place — no re-builder wasted.\n const internal: State<TState, TEvents, Schemas, TName> = {\n events,\n actions: {},\n state: state_schema,\n name,\n init,\n patch: default_patch,\n on: {},\n // Step delegates initialized as identity, `pii_aware` false.\n // `act().build()` flips both on states with `sensitive(...)`\n // events to bake in the gate / split and gate the cache write.\n pii_aware: false,\n view: (event) => event,\n message: (validated) => validated,\n };\n\n // `{}` avoids the string index signature `Record<string, never>` would add\n const builder = action_builder<TState, TEvents, {}, TName>(internal);\n\n return Object.assign(builder, {\n patch(customPatch: Partial<PatchHandlers<TState, TEvents>>) {\n Object.assign(internal.patch, customPatch);\n return builder;\n },\n });\n },\n };\n },\n };\n}\n\n/**\n * Internal action-builder. The runtime object is a single mutable bag —\n * each fluent call (`on`, `snap`) mutates it and returns the same builder\n * cast to the widened generic type. Type-level fanout is preserved; the\n * O(N) `{...state}` spreads per call are not.\n *\n * Generics are erased to `Schemas` at runtime — the cast on return narrows\n * back to the call-site's widened types.\n */\nfunction action_builder<\n TState extends Schema,\n TEvents extends Schemas,\n TActions extends Schemas,\n TName extends string = string,\n>(\n state: State<TState, TEvents, TActions, TName>\n): ActionBuilder<TState, TEvents, TActions, TName> {\n // The mutable bag — typed loosely since callers narrow on return.\n const internal = state as unknown as State<TState, TEvents, Schemas, TName>;\n\n const builder: ActionBuilder<TState, TEvents, TActions, TName> = {\n on<TKey extends string, TNewActions extends Schema>(\n entry: ActionEntry<TKey, TNewActions>,\n options?: ActionOptions\n ) {\n const keys = Object.keys(entry);\n if (keys.length !== 1) throw new Error(\".on() requires exactly one key\");\n const action = keys[0] as TKey;\n const schema = entry[action];\n\n if (action in internal.actions)\n throw new Error(`Duplicate action \"${action}\"`);\n\n type MergedActions = TActions & { [P in TKey]: TNewActions };\n (internal.actions as Record<string, ZodType<Schema>>)[action] = schema;\n if (options) {\n // Validate the whole action bag at declaration so a bad\n // `maxRetries`/`backoff` throws ZodError at build, not a NaN gate.\n resolveActionConfig(options);\n internal.options ??= {};\n (internal.options as Record<string, ActionOptions>)[action] = options;\n }\n\n const loads: Load[] = [];\n\n function load(\n state: State<any, any, any>,\n target: Load[\"target\"],\n events: readonly string[] = [],\n name: string = state.name\n ) {\n if (loads.some((l) => l.name === name))\n throw new Error(\n `Action \"${action}\" loads \"${name}\" twice; name each load of the same state`\n );\n for (const event of events) {\n if (!(event in state.events))\n throw new Error(\n `Action \"${action}\" lists \"${event}\" on its load of \"${state.name}\", which doesn't emit it`\n );\n if (loads.some((l) => l.events.includes(event)))\n throw new Error(\n `Action \"${action}\" lists \"${event}\" on two loads; an event goes to one stream`\n );\n }\n loads.push({ state, target, events, name });\n (internal.loads ??= {})[action] = loads;\n return { loads: load, requires, emit };\n }\n\n function requires(rules: Precondition<TState, TNewActions>[]) {\n ((internal.requires ??= {}) as Record<string, unknown>)[action] = rules;\n return { emit };\n }\n\n function emit(\n handler:\n | ActionHandler<TState, TEvents, MergedActions, TKey>\n | (keyof TEvents & string)\n ) {\n if (typeof handler === \"string\") {\n const event_name = handler;\n // Tag the synthetic function with the static event name so\n // the act-builder can check it at build time (a deprecated\n // event, an event a load lists). Dynamic forms compute the\n // event name inside the user's function, so the build can't\n // see it.\n const emit_fn = Object.assign(\n (payload: any) => [event_name, payload],\n {\n _static_emit: event_name,\n }\n );\n (internal.on as Record<string, unknown>)[action] = emit_fn;\n } else {\n (internal.on as Record<string, unknown>)[action] = handler;\n }\n return builder as unknown as ActionBuilder<\n TState,\n TEvents,\n MergedActions,\n TName\n >;\n }\n\n // Typed by the public signature; the runtime bag is the same at every step.\n return { loads: load, requires, emit } as never;\n },\n\n snap(snap: (snapshot: Snapshot<TState, TEvents>) => boolean) {\n internal.snap = snap;\n // Flip the type-level TSnap flag — same runtime object, the cast\n // unlocks `.autocloses({ keep })` for the rest of the chain.\n return builder as unknown as ActionBuilder<\n TState,\n TEvents,\n TActions,\n TName,\n true\n >;\n },\n\n discloses(\n disclose: (\n event: Committed<TEvents, keyof TEvents & string>,\n actor: Actor\n ) => boolean\n ) {\n // Replace on every call — matches snap's state-level semantics. Operators\n // who need per-event differences branch inside the predicate.\n internal.disclose = disclose;\n return builder;\n },\n\n autocloses(policy: AutoclosePolicy) {\n // Declarative policy only. The online path is a synthesized\n // reaction that defers to a derivable due-time and closes — an opaque\n // function predicate has no terminal event to react to nor a window to\n // derive, so it's no longer accepted online. Operators who need custom\n // logic call `app.close(...)` from their own reaction.\n if (typeof policy === \"function\") {\n throw new Error(\n \".autocloses(fn) is no longer supported — pass a declarative policy \" +\n \"({ after, is, reaches, or }) or call app.close(...) from your own \" +\n \"reaction for custom logic.\"\n );\n }\n if (policy === null || typeof policy !== \"object\") {\n throw new Error(\n \".autocloses(...) requires a policy object; got \" + typeof policy\n );\n }\n // The type gate (`TSnap`) already rejects `keep` before `.snap` at\n // compile time; this is the equivalent guard for untyped callers.\n if ((policy as AutoclosePolicy).keep && !internal.snap) {\n throw new Error(\n \".autocloses({ keep }) requires .snap(...) earlier in the chain — a rolling window prunes behind a real snapshot, so a state that never snapshots has nothing to prune behind.\"\n );\n }\n // Replace on every call — matches snap / discloses state-level\n // semantics. Compile to the predicate the reaction evaluates; `keep`\n // resolves to the rolling-window width the reaction prunes against.\n internal.autoclose = compile_autoclose_policy(\n policy\n ) as AutoclosePredicate<TEvents>;\n const windows = policy_after_windows(policy);\n internal.autoclose_after_windows = windows;\n internal.autoclose_after_days = windows.length\n ? Math.min(...windows)\n : undefined;\n internal.autoclose_keep_days = policy_keep_days(policy);\n return builder;\n },\n\n archives(archive: AutocloseArchiver<TEvents>) {\n if (typeof archive !== \"function\") {\n throw new Error(\n \".archives(archive) requires a function; got \" + typeof archive\n );\n }\n internal.archive = archive;\n return builder;\n },\n\n build(): State<TState, TEvents, TActions, TName> {\n return internal as unknown as State<TState, TEvents, TActions, TName>;\n },\n };\n return builder;\n}\n","/**\n * @module csv\n *\n * `CsvFile` — a single class implementing both {@link EventSource}\n * and {@link EventSink} so a CSV file on disk can be either side of\n * a transfer pipeline.\n *\n * - As a source: streams one row at a time off a line interface;\n * the awaited per-event callback gives 1-event-in-flight\n * backpressure on reads.\n * - As a sink: serialized `WriteStream.write` await per row,\n * propagating I/O errors through the chunk callback.\n *\n * `commit` / `claim` / `subscribe` and the rest of `Store` are NOT\n * implemented — `CsvFile` is a transfer-only primitive, not a\n * store you'd run an Act app against.\n */\n\nimport { createReadStream, createWriteStream, type WriteStream } from \"node:fs\";\nimport { createInterface } from \"node:readline\";\nimport type {\n Committed,\n CsvFileOptions,\n EventSink,\n EventSource,\n Query,\n Schemas,\n} from \"./types/action.js\";\n\n/**\n * Same column order as the inspector's backup endpoint, kept here\n * so `CsvFile` is round-trip-compatible with existing backups.\n */\nconst CSV_COLUMNS = [\n \"id\",\n \"name\",\n \"data\",\n \"stream\",\n \"version\",\n \"created\",\n \"meta\",\n] as const;\n\nexport class CsvFile implements EventSource, EventSink {\n private readonly path: string | null;\n private readonly blob: string | null;\n\n constructor(options: CsvFileOptions) {\n if (\"path\" in options) {\n this.path = options.path;\n this.blob = null;\n } else {\n this.path = null;\n this.blob = options.blob;\n }\n }\n\n async query<E extends Schemas>(\n callback: (event: Committed<E, keyof E>) => void,\n _filter?: Query\n ): Promise<number> {\n const lines =\n this.blob !== null ? linesFromBlob(this.blob) : linesFromFile(this.path!);\n let count = 0;\n let header: readonly string[] | null = null;\n for await (const line of lines) {\n if (!line.trim()) continue;\n const fields = parse_csv_line(line);\n if (!header) {\n header = fields;\n const expected = CSV_COLUMNS.join(\",\");\n if (header.join(\",\") !== expected)\n throw new Error(`Invalid CSV header. Expected: ${expected}`);\n continue;\n }\n if (fields.length !== CSV_COLUMNS.length)\n throw new Error(\n `Row ${count + 1}: expected ${CSV_COLUMNS.length} fields, got ${fields.length}`\n );\n const event: Committed<E, keyof E> = {\n id: Number.parseInt(fields[0]!, 10),\n name: fields[1]! as keyof E,\n // Revive dates like every Store adapter does — a Date in an event\n // payload must not depend on whether it came back through a store or\n // through a CSV restore. The `created` column below has\n // always been parsed explicitly; the JSON columns were missed.\n data: JSON.parse(fields[2]!),\n stream: fields[3]!,\n version: Number.parseInt(fields[4]!, 10),\n created: new Date(fields[5]!),\n meta: JSON.parse(fields[6]!),\n };\n await Promise.resolve(callback(event));\n count++;\n }\n if (header === null)\n throw new Error(\"CSV must have a header and at least one row\");\n return count;\n }\n\n async restore(\n driver: (\n callback: (event: Committed<Schemas, keyof Schemas>) => Promise<number>\n ) => Promise<void>\n ): Promise<void> {\n if (this.path === null)\n throw new Error(\n \"CsvFile in blob mode is read-only — provide `path` to write\"\n );\n const writer = createWriteStream(this.path, {\n flags: \"w\",\n encoding: \"utf8\",\n });\n let next_id = 1;\n try {\n await write_line(writer, CSV_COLUMNS.join(\",\"));\n await driver(async (event) => {\n const id = next_id++;\n const row = [\n String(id),\n csv_escape(event.name as string),\n csv_escape(JSON.stringify(event.data)),\n csv_escape(event.stream),\n String(event.version),\n event.created.toISOString(),\n csv_escape(JSON.stringify(event.meta)),\n ].join(\",\");\n await write_line(writer, row);\n return id;\n });\n } finally {\n await new Promise<void>((resolve) => writer.end(resolve));\n }\n }\n\n async dispose(): Promise<void> {\n // No-op: `restore` always closes its writer in a `finally`, and\n // blob mode never opens one. The Disposable contract is here to\n // make `CsvFile` interchangeable with `Store` in transfer\n // pipelines, not because the file handle outlives the call.\n }\n}\n\nasync function* linesFromFile(path: string): AsyncIterable<string> {\n const stream = createReadStream(path, { encoding: \"utf8\" });\n const rl = createInterface({\n input: stream,\n crlfDelay: Number.POSITIVE_INFINITY,\n });\n try {\n for await (const line of rl) yield line;\n } finally {\n rl.close();\n stream.close();\n }\n}\n\nasync function* linesFromBlob(blob: string): AsyncIterable<string> {\n let start = 0;\n while (start < blob.length) {\n const nl = blob.indexOf(\"\\n\", start);\n const end = nl === -1 ? blob.length : nl;\n yield blob.slice(start, end);\n start = nl === -1 ? blob.length : nl + 1;\n await Promise.resolve();\n }\n}\n\nfunction parse_csv_line(line: string): string[] {\n const fields: string[] = [];\n let i = 0;\n while (i < line.length) {\n if (line[i] === '\"') {\n let value = \"\";\n i++;\n while (i < line.length) {\n if (line[i] === '\"' && line[i + 1] === '\"') {\n value += '\"';\n i += 2;\n } else if (line[i] === '\"') {\n i++;\n break;\n } else {\n value += line[i++];\n }\n }\n fields.push(value);\n if (line[i] === \",\") i++;\n } else {\n const next = line.indexOf(\",\", i);\n if (next === -1) {\n fields.push(line.slice(i));\n i = line.length;\n } else {\n fields.push(line.slice(i, next));\n i = next + 1;\n }\n }\n }\n return fields;\n}\n\nfunction csv_escape(value: string): string {\n if (/[\",\\n\\r]/.test(value)) return `\"${value.replace(/\"/g, '\"\"')}\"`;\n return value;\n}\n\nfunction write_line(writer: WriteStream, line: string): Promise<void> {\n return new Promise<void>((resolve, reject) => {\n writer.write(`${line}\\n`, (err) => {\n if (err) reject(err);\n else resolve();\n });\n });\n}\n","// 2.x names kept as aliases of their replacements (RFC 2411). 3.0 removes\n// this file and its block in index.ts.\nimport type { ZodType } from \"zod\";\nimport {\n checkAppends,\n checkVersion,\n concurrencyError,\n fairSlots,\n isStreamName,\n parseNotification,\n seedEvent,\n} from \"./adapter.js\";\nimport { package_schema } from \"./config.js\";\nimport { resolveAutocloseConfig as resolve_autoclose } from \"./internal/config.js\";\nimport { unscoped_ports } from \"./ports.js\";\nimport {\n ActorSchema as actor_schema,\n CausationEventSchema as causation_event_schema,\n CommittedMetaSchema as committed_meta_schema,\n DEFAULT_LANE as default_lane,\n DEFAULT_MAX_SUBSCRIBED_STREAMS as default_max_subscribed_streams,\n DEFAULT_QUERY_STREAMS_LIMIT as default_query_streams_limit,\n DEFAULT_SETTLE_DEBOUNCE_MS as default_settle_debounce_ms,\n Environments as environments,\n EventMetaSchema as event_meta_schema,\n ExitCodes as exit_codes,\n LogLevels as log_levels,\n QuerySchema as query_schema,\n TargetSchema as target_schema,\n} from \"./types/index.js\";\nimport { validate } from \"./utils.js\";\n\n/** @deprecated Use `checkAppends` from `@rotorsoft/act/adapter`. */\nexport const check_appends: typeof checkAppends = checkAppends;\n/** @deprecated Use `checkVersion` from `@rotorsoft/act/adapter`. */\nexport const throw_if_stale: typeof checkVersion = checkVersion;\n/** @deprecated Use `concurrencyError` from `@rotorsoft/act/adapter`. */\nexport const concurrency_error: typeof concurrencyError = concurrencyError;\n/** @deprecated Use `seedEvent` from `@rotorsoft/act/adapter`. */\nexport const seed_event: typeof seedEvent = seedEvent;\n/** @deprecated Use `fairSlots` from `@rotorsoft/act/adapter`. */\nexport const fair_slots: typeof fairSlots = fairSlots;\n/** @deprecated Use `isStreamName` from `@rotorsoft/act/adapter`. */\nexport const is_literal_source: typeof isStreamName = isStreamName;\n/** @deprecated Use `parseNotification` from `@rotorsoft/act/adapter`. */\nexport const notification_of: typeof parseNotification = parseNotification;\n\n/** @deprecated Import it from `@rotorsoft/act/types`. */\nexport const DEFAULT_QUERY_STREAMS_LIMIT: typeof default_query_streams_limit =\n default_query_streams_limit;\n/** @deprecated Import it from `@rotorsoft/act/types`. */\nexport const ActorSchema: typeof actor_schema = actor_schema;\n/** @deprecated Import it from `@rotorsoft/act/types`. */\nexport const TargetSchema: typeof target_schema = target_schema;\n/** @deprecated Import it from `@rotorsoft/act/types`. */\nexport const EventMetaSchema: typeof event_meta_schema = event_meta_schema;\n/** @deprecated Import it from `@rotorsoft/act/types`. */\nexport const CausationEventSchema: typeof causation_event_schema =\n causation_event_schema;\n/** @deprecated Import it from `@rotorsoft/act/types`. */\nexport const CommittedMetaSchema: typeof committed_meta_schema =\n committed_meta_schema;\n/** @deprecated Import it from `@rotorsoft/act/types`. */\nexport const QuerySchema: typeof query_schema = query_schema;\n/** @deprecated Import it from `@rotorsoft/act/types`. */\nexport const Environments: typeof environments = environments;\n/** @deprecated Import it from `@rotorsoft/act/types`. */\nexport const LogLevels: typeof log_levels = log_levels;\n/** @deprecated Import it from `@rotorsoft/act/types`. */\nexport const ExitCodes: typeof exit_codes = exit_codes;\n/** @deprecated Import it from `@rotorsoft/act/types`. */\nexport const DEFAULT_LANE: typeof default_lane = default_lane;\n/** @deprecated Import it from `@rotorsoft/act/types`. */\nexport const DEFAULT_MAX_SUBSCRIBED_STREAMS: typeof default_max_subscribed_streams =\n default_max_subscribed_streams;\n/** @deprecated Import it from `@rotorsoft/act/types`. */\nexport const DEFAULT_SETTLE_DEBOUNCE_MS: typeof default_settle_debounce_ms =\n default_settle_debounce_ms;\n\n/** @deprecated No replacement: `config()` validates package.json itself. */\nexport const PackageSchema: typeof package_schema = package_schema;\n/** @deprecated No replacement: call `store()`, `cache()` or `log()`. */\nexport const default_scope: typeof unscoped_ports = unscoped_ports;\n/** @deprecated No replacement: `act().build()` validates these options. */\nexport const resolveAutocloseConfig: typeof resolve_autoclose =\n resolve_autoclose;\n/** @deprecated No replacement: parse with the schema, spread the defaults. */\nexport const extend = <\n S extends Record<string, unknown>,\n T extends Record<string, unknown>,\n>(\n source: Readonly<S>,\n schema: ZodType<S>,\n target?: Readonly<T>\n): Readonly<S & T> =>\n ({ ...target, ...validate(\"config\", source, schema) }) as Readonly<S & T>;\n\n// An ISO-8601 timestamp, the shape `JSON.stringify` gives a `Date`.\nconst ISO_8601 =\n /^(\\d{4})-(0[1-9]|1[0-2])-(0[1-9]|[1-2][0-9]|3[0-1])T([01][0-9]|2[0-3]):([0-5][0-9]):([0-5][0-9])(\\.\\d+)?(Z|[+-][0-2][0-9]:[0-5][0-9])?$/;\n\n/** @deprecated No replacement: events revive their own `z.date()` fields. */\nexport const dateReviver = (_key: string, value: unknown): unknown =>\n typeof value === \"string\" && ISO_8601.test(value) ? new Date(value) : value;\n"]}
|
|
1
|
+
{"version":3,"sources":["/home/runner/work/act-root/act-root/libs/act/dist/index.cjs","../src/signals.ts","../src/act.ts","../src/internal/event-versions.ts","../src/internal/walk-streams.ts","../src/internal/audit.ts","../src/internal/circuit-breaker.ts","../src/internal/classify.ts","../src/internal/autoclose-policy.ts","../src/internal/autoclose-window.ts","../src/internal/defer-config.ts","../src/internal/drain-cycle.ts","../src/internal/backoff.ts","../src/internal/defer-timer.ts","../src/internal/drain-ratio.ts","../src/internal/report-once.ts","../src/internal/correlation-id.ts","../src/internal/drain-ops.ts","../src/internal/event-sourcing.ts","../src/internal/tracing.ts","../src/internal/reaction-dispatch.ts","../src/internal/autoclose-reaction.ts","../src/internal/close-cycle.ts","../src/internal/correlate-cycle.ts","../src/internal/pii.ts","../src/internal/projection-fold.ts","../src/internal/settle.ts","../src/builders/merge.ts","../src/builders/builder-utils.ts","../src/builders/event-builder.ts","../src/internal/date-reviver.ts","../src/builders/act-builder.ts","../src/builders/projection-builder.ts","../src/builders/slice-builder.ts","../src/builders/state-builder.ts","../src/csv.ts","../src/deprecated.ts"],"names":["store","state","sensitive","deps"],"mappings":"AAAA;AACE;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACF,wDAA6B;AAC7B;AACE;AACA;AACA;AACA;AACA;AACA;AACA;AACF,wDAA6B;AAC7B;AACE;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACF,wDAA6B;AAC7B;AACA;AClFA,OAAA,CAAQ,IAAA,CAAK,QAAA,EAAU,MAAA,CAAO,GAAA,EAAA,GAAc;AAC1C,EAAA,mCAAA,CAAI,CAAE,IAAA,CAAK,GAAA,EAAK,QAAQ,CAAA;AACxB,EAAA,MAAM,8CAAA,MAAqB,CAAA;AAC7B,CAAC,CAAA;AACD,OAAA,CAAQ,IAAA,CAAK,SAAA,EAAW,MAAA,CAAO,GAAA,EAAA,GAAc;AAC3C,EAAA,mCAAA,CAAI,CAAE,IAAA,CAAK,GAAA,EAAK,SAAS,CAAA;AACzB,EAAA,MAAM,8CAAA,MAAqB,CAAA;AAC7B,CAAC,CAAA;AACD,OAAA,CAAQ,IAAA,CAAK,mBAAA,EAAqB,MAAA,CAAO,GAAA,EAAA,GAAc;AACrD,EAAA,mCAAA,CAAI,CAAE,KAAA,CAAM,GAAA,EAAK,oBAAoB,CAAA;AACrC,EAAA,MAAM,8CAAA,OAA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AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA","file":"/home/runner/work/act-root/act-root/libs/act/dist/index.cjs","sourcesContent":[null,"import { disposeAndExit, log } from \"./ports.js\";\n\n// Resolve the logger lazily inside each handler — calling log() here at\n// module load would register the default ConsoleLogger before user code\n// can inject (port singletons are first-call-wins).\nprocess.once(\"SIGINT\", async (arg?: any) => {\n log().info(arg, \"SIGINT\");\n await disposeAndExit(\"EXIT\");\n});\nprocess.once(\"SIGTERM\", async (arg?: any) => {\n log().info(arg, \"SIGTERM\");\n await disposeAndExit(\"EXIT\");\n});\nprocess.once(\"uncaughtException\", async (arg?: any) => {\n log().error(arg, \"Uncaught Exception\");\n await disposeAndExit(\"ERROR\");\n});\nprocess.once(\"unhandledRejection\", async (arg?: any) => {\n log().error(arg, \"Unhandled Rejection\");\n await disposeAndExit(\"ERROR\");\n});\n","import EventEmitter from \"node:events\";\nimport { register_weak_disposer } from \"./disposers.js\";\nimport { type AuditDeps, audit } from \"./internal/audit.js\";\nimport { CircuitBreaker } from \"./internal/circuit-breaker.js\";\nimport {\n ALL_LANES,\n classify_registry,\n type EventLaneSet,\n} from \"./internal/classify.js\";\nimport {\n CloseLock,\n catch_up_correlation,\n run_close_cycle,\n} from \"./internal/close-cycle.js\";\nimport {\n check_store,\n DEFAULT_LEASE_MILLIS,\n MAX_SHUTDOWN_GRACE_MS,\n resolveAutocloseConfig,\n resolveCircuitBreakerConfig,\n resolveDrainConfig,\n resolveSettleConfig,\n resolveShutdownConfig,\n resolveTargetConfig,\n} from \"./internal/config.js\";\nimport {\n CorrelateCycle,\n type CorrelatePass,\n} from \"./internal/correlate-cycle.js\";\nimport {\n close_correlation,\n default_correlator,\n} from \"./internal/correlation-id.js\";\nimport {\n DrainController,\n type Handle,\n type HandleBatch,\n merge_drains,\n} from \"./internal/drain-cycle.js\";\nimport type { DrainOps } from \"./internal/drain-ops.js\";\nimport { bare_patch, type EsOps, scan } from \"./internal/event-sourcing.js\";\nimport {\n FOLD_RESET,\n type ResettableBatchHandler,\n} from \"./internal/projection-fold.js\";\nimport {\n build_handle,\n build_handle_batch,\n} from \"./internal/reaction-dispatch.js\";\nimport { SettleLoop } from \"./internal/settle.js\";\nimport { build_drain, build_es } from \"./internal/tracing.js\";\nimport { walk_streams } from \"./internal/walk-streams.js\";\nimport { cache, log, store, unscoped_ports } from \"./ports.js\";\nimport {\n current_reacting,\n make_reaction_scope,\n make_run_scoped,\n} from \"./scoped.js\";\nimport {\n type ActLifecycleEvents,\n type ActOptions,\n type CircuitState,\n DEFAULT_MAX_SUBSCRIBED_STREAMS,\n DEFAULT_SETTLE_DEBOUNCE_MS,\n type Scoped,\n} from \"./types/act.js\";\nimport { StoreError } from \"./types/errors.js\";\nimport type {\n Actor,\n AsOf,\n AuditCategory,\n AuditFinding,\n AuditOptions,\n BatchHandler,\n CloseResult,\n CloseTarget,\n Committed,\n Correlator,\n DoOptions,\n Drain,\n DrainOptions,\n EventSink,\n EventSource,\n IAct,\n LaneConfig,\n LoadTarget,\n Logger,\n PatchFn,\n Query,\n Registry,\n ScanOptions,\n ScanResult,\n Schema,\n SchemaRegister,\n Schemas,\n SettleOptions,\n ShutdownOptions,\n Snapshot,\n State,\n Store,\n StreamFilter,\n StreamPosition,\n Target,\n} from \"./types/index.js\";\n\n/** Reject `onlyLanes` entries that reference undeclared lanes. */\nfunction validate_only_lanes(\n only: ReadonlyArray<string> | undefined,\n declared: ReadonlyArray<string>\n): void {\n const unknown = (only ?? []).filter((l) => !declared.includes(l));\n if (unknown.length > 0)\n throw new Error(\n `ActOptions.onlyLanes references undeclared lane(s): ${unknown\n .map((l) => `\"${l}\"`)\n .join(\", \")}`\n );\n}\n\n/**\n * @category Orchestrator\n * @see Store\n *\n * The orchestrator: executes actions, loads state, queries events, and runs\n * the reactions each commit frees (on its own, unless `autoSettle: false`).\n *\n * ```typescript\n * const app = act().withState(Counter).build();\n * await app.do(\"increment\", { stream: \"counter1\", actor }, { by: 1 });\n * const snapshot = await app.load(Counter, \"counter1\");\n * ```\n *\n * @template TSchemaReg SchemaRegister for state\n * @template TEvents Schemas for events\n * @template TActions Schemas for actions\n * @template TStateMap Map of state names to state schemas\n * @template TActor Actor type extending base Actor\n */\nexport class Act<\n TSchemaReg extends SchemaRegister<TActions>,\n TEvents extends Schemas,\n TActions extends Schemas,\n TStateMap extends Record<string, Schema> = Record<string, never>,\n TActor extends Actor = Actor,\n> implements IAct<TEvents, TActions, TActor, TSchemaReg>\n{\n private _emitter = new EventEmitter();\n private readonly _breaker: CircuitBreaker;\n private readonly _drain: boolean;\n private readonly _auto_settle: boolean;\n // Whether any event has a reaction; nothing arms without one.\n private readonly _reactive: boolean;\n private readonly _drain_controllers: Map<\n string,\n DrainController<TEvents, TActions, TSchemaReg>\n >;\n private readonly _correlate: CorrelateCycle<TSchemaReg, TEvents, TActions>;\n private readonly _settle: SettleLoop<TEvents>;\n private _poll: ReturnType<typeof setInterval> | undefined;\n // The poll's correlate `limit`, used by every settle pass while it runs.\n private _poll_limit: number | undefined;\n // Wired at construction against the store current then, so a store\n // injected after `build()` is never notified.\n private readonly _notify_disposer: Promise<\n (() => void | Promise<void>) | undefined\n >;\n /** Public registry — kept as-is per the no-prefix-on-public convention. */\n public readonly registry: Registry<\n TSchemaReg,\n TEvents,\n TActions,\n keyof TStateMap & string\n >;\n private readonly _states: Map<string, State<any, any, any>>;\n /**\n * Emit a lifecycle event. The payload type is inferred from the event name\n * via {@link ActLifecycleEvents}.\n *\n * Each listener is contained on its own: a throwing listener is logged,\n * the remaining listeners still run, and the caller (`do()`, `forget()`,\n * `close()`, the drain) never sees the throw, since its durable work has\n * already landed.\n *\n * Uses `rawListeners` so `once` wrappers still de-register themselves, and\n * returns \"had listeners\" to preserve the `EventEmitter.emit` contract.\n */\n emit<E extends keyof ActLifecycleEvents<TSchemaReg, TEvents, TActions>>(\n event: E,\n args: ActLifecycleEvents<TSchemaReg, TEvents, TActions>[E]\n ): boolean {\n return this._notify(event as string, args);\n }\n\n // Run each listener of `key` on its own, logging any that throws.\n private _notify(key: string, args: unknown): boolean {\n const listeners = this._emitter.rawListeners(key);\n for (const listener of listeners) {\n try {\n listener(args);\n } catch (error) {\n this._logger.error(error, `${key} listener threw`);\n }\n }\n return listeners.length > 0;\n }\n\n // The emitter key of one state's `committed` listeners.\n private _committed_key(state: State<any, any, any> | string): string {\n const name = typeof state === \"string\" ? state : state.name;\n if (!this._states.has(name))\n throw new Error(`committed: \"${name}\" is not a state of this app`);\n return `committed:${name}`;\n }\n\n // The one place a store failure is logged and emitted (the breaker's\n // `on_error`). The emit is guarded: an unhandled `\"error\"` emission\n // would crash the process.\n private _emit_error(error: unknown, circuit: CircuitState): void {\n this._logger.error(error);\n if (this._emitter.listenerCount(\"error\") > 0)\n this.emit(\"error\", { error, circuit });\n }\n\n /**\n * Register a listener for a lifecycle event. The listener receives the\n * event-specific payload.\n *\n * `committed` also takes a state, as a `State` or its name: the listener\n * then hears only commits to that state's streams, whichever action\n * appended them, with its snapshots typed from that state.\n *\n * @example\n * ```typescript\n * app.on(\"committed\", Counter, (snapshots) => {\n * console.log(snapshots.at(-1)?.state.count); // typed: number\n * });\n * ```\n */\n on<E extends keyof ActLifecycleEvents<TSchemaReg, TEvents, TActions>>(\n event: E,\n listener: (\n args: ActLifecycleEvents<TSchemaReg, TEvents, TActions>[E]\n ) => void\n ): this;\n on<\n TNewState extends Schema,\n TNewEvents extends Schemas,\n TNewActions extends Schemas,\n >(\n event: \"committed\",\n state: State<TNewState, TNewEvents, TNewActions>,\n listener: (snapshots: Snapshot<TNewState, TNewEvents>[]) => void\n ): this;\n on<TKey extends keyof TStateMap & string>(\n event: \"committed\",\n state: TKey,\n listener: (snapshots: Snapshot<TStateMap[TKey], TEvents>[]) => void\n ): this;\n on(\n event: string,\n state_or_listener: State<any, any, any> | string | ((args: any) => void),\n listener?: (args: any) => void\n ): this {\n if (listener)\n this._emitter.on(\n this._committed_key(state_or_listener as State<any, any, any>),\n listener\n );\n else this._emitter.on(event, state_or_listener as (args: any) => void);\n return this;\n }\n\n /**\n * Remove a previously registered lifecycle listener, with the state it\n * was registered for when it has one.\n */\n off<E extends keyof ActLifecycleEvents<TSchemaReg, TEvents, TActions>>(\n event: E,\n listener: (\n args: ActLifecycleEvents<TSchemaReg, TEvents, TActions>[E]\n ) => void\n ): this;\n off<\n TNewState extends Schema,\n TNewEvents extends Schemas,\n TNewActions extends Schemas,\n >(\n event: \"committed\",\n state: State<TNewState, TNewEvents, TNewActions>,\n listener: (snapshots: Snapshot<TNewState, TNewEvents>[]) => void\n ): this;\n off<TKey extends keyof TStateMap & string>(\n event: \"committed\",\n state: TKey,\n listener: (snapshots: Snapshot<TStateMap[TKey], TEvents>[]) => void\n ): this;\n off(\n event: string,\n state_or_listener: State<any, any, any> | string | ((args: any) => void),\n listener?: (args: any) => void\n ): this {\n if (listener)\n this._emitter.off(\n this._committed_key(state_or_listener as State<any, any, any>),\n listener\n );\n else this._emitter.off(event, state_or_listener as (args: any) => void);\n return this;\n }\n\n private readonly _batch_handlers: Map<string, BatchHandler<TEvents>>;\n private readonly _es: EsOps;\n private readonly _cd: DrainOps<TEvents>;\n // Unambiguous: merge rejects an event name declared by two states.\n private readonly _event_to_state: ReadonlyMap<string, State<any, any, any>>;\n // Lanes to arm per event; `\"all\"` when a dynamic resolver hides the lane.\n private readonly _event_to_lanes: ReadonlyMap<string, EventLaneSet>;\n private readonly _audit_deps: AuditDeps;\n private readonly _logger: Logger = log();\n // This Act's ports: its own bag, or the singleton adapters.\n private readonly _ports: Scoped;\n // Runs a body so internal `store()`/`cache()` calls resolve to `_ports`.\n private readonly _scoped: <T>(fn: () => Promise<T>) => Promise<T>;\n\n private readonly _correlator: Correlator;\n private readonly _lanes: ReadonlyArray<LaneConfig>;\n\n private readonly _close_lock = new CloseLock();\n // Every lane a controller can exist for: `\"default\"` plus each declared one.\n private readonly _declared_lanes: ReadonlyArray<string>;\n\n /** Drain lanes declared via `.withLane(...)`. Implicit default not included. */\n get lanes(): ReadonlyArray<LaneConfig> {\n return this._lanes;\n }\n\n /** Use the {@link act} builder rather than constructing directly. */\n constructor(\n registry: Registry<TSchemaReg, TEvents, TActions, keyof TStateMap & string>,\n states: Map<string, State<any, any, any>> = new Map(),\n batch_handlers: Map<string, BatchHandler<any>> = new Map(),\n options: ActOptions = {},\n lanes: ReadonlyArray<LaneConfig> = [],\n patch_fn: PatchFn = bare_patch\n ) {\n this.registry = registry;\n this._states = states;\n this._batch_handlers = batch_handlers;\n this._lanes = lanes;\n this._declared_lanes = [\"default\", ...lanes.map((l) => l.name)];\n validate_only_lanes(options.onlyLanes, this._declared_lanes);\n // Every Act runs in its own ports frame (the singletons when unscoped),\n // so a shared Act never inherits its caller's frame.\n if (options.scoped) check_store(options.scoped.store);\n this._ports = options.scoped ?? unscoped_ports();\n const ports = this._ports;\n this._scoped = make_run_scoped({\n // Getters, not a spread: the singletons resolve lazily, so a later\n // `store(...)` / `cache(...)` still takes effect.\n get store() {\n return ports.store;\n },\n get cache() {\n return ports.cache;\n },\n // Parsed per build, so a bad window throws on every build.\n autoclose_window: resolveAutocloseConfig(options).autocloseWindow,\n });\n this._correlator = options.correlator ?? default_correlator;\n this._es = build_es(this._logger, this._correlator, patch_fn);\n this._cd = build_drain<TEvents>(this._logger);\n // PII stripping is wrapped around handlers at build time, so the\n // dispatcher is PII-unaware. Bound once, reused by every reaction payload.\n const handle = build_handle<TEvents, TActions, TActor>({\n logger: this._logger,\n reaction_scope: make_reaction_scope({\n do: this.do.bind(this),\n load: this.load.bind(this),\n query: this.query.bind(this),\n query_array: this.query_array.bind(this),\n forget: this.forget.bind(this),\n }),\n });\n const handle_batch = build_handle_batch<TEvents>(this._logger);\n\n const classification = classify_registry(this.registry, this._states);\n this._reactive = classification.event_to_lanes.size > 0;\n this._event_to_state = classification.event_to_state;\n this._event_to_lanes = classification.event_to_lanes;\n this._drain = options.drain !== false;\n this._auto_settle = options.autoSettle !== false;\n\n // Order matters: controllers read the breaker, the audit bag reads the\n // controller set, settle reads the correlate cycle.\n this._breaker = this._build_breaker(options);\n this._drain_controllers = this._build_drain_controllers(\n options,\n lanes,\n handle,\n handle_batch\n );\n this._advise_orphaned_lanes();\n this._audit_deps = this._build_audit_deps();\n this._correlate = this._build_correlate(options, classification);\n this._settle = this._build_settle(options);\n\n // Wire cross-process notify against the store current at construction.\n this._notify_disposer = this._wire_notify(\n this._ports.store,\n options.listen !== false\n );\n\n // Registered weakly, so `dispose()()` reaches a live Act while an\n // unreachable one (per tenant, per test) can still be collected.\n register_weak_disposer(new WeakRef(this), (self) => self.shutdown());\n }\n\n // Shared by drain, settle and autoclose; bad knobs throw at build.\n private _build_breaker(options: ActOptions): CircuitBreaker {\n return new CircuitBreaker(\n resolveCircuitBreakerConfig(options.circuitBreaker),\n {\n on_error: (error, circuit) => this._emit_error(error, circuit),\n // When the cooldown elapses, settle once: its scan or claim is the\n // half-open probe that closes or re-opens the breaker.\n on_retry: () => this._schedule(),\n }\n );\n }\n\n // Apps that declare no lanes pass no lane filter to `claim`.\n private _build_drain_controllers(\n options: ActOptions,\n lanes: ReadonlyArray<LaneConfig>,\n handle: Handle<TEvents>,\n handle_batch: HandleBatch<TEvents>\n ): Map<string, DrainController<TEvents, TActions, TSchemaReg>> {\n const all_lanes = this._declared_lanes;\n const only_set = options.onlyLanes?.length\n ? new Set<string>(options.onlyLanes as readonly string[])\n : undefined;\n const active_lanes = only_set\n ? all_lanes.filter((n) => only_set.has(n))\n : all_lanes;\n // Decided by the declared lanes, not the active ones: a worker narrowed\n // to \"default\" must still filter, or it would claim every lane.\n const single_default_lane = lanes.length === 0;\n const controllers = new Map<\n string,\n DrainController<TEvents, TActions, TSchemaReg>\n >();\n for (const name of active_lanes) {\n const cfg = lanes.find((l) => l.name === name);\n const controller = new DrainController({\n logger: this._logger,\n ops: this._cd,\n registry: this.registry,\n batch_handlers: this._batch_handlers,\n handle,\n handle_batch,\n on_acked: (acked) => this.emit(\"acked\", acked),\n on_blocked: (blocked) => this.emit(\"blocked\", blocked),\n // Reaction-requested close: the same machinery as `app.close`.\n // A store failure reaches the breaker; anything else (the archive\n // callback is app code) is logged here, never counted.\n on_close: async (targets) => {\n try {\n await this._run_close(targets);\n } catch (error) {\n if (error instanceof StoreError) throw error;\n this._logger.error(\n error,\n `Reaction-requested close of ${targets.map((t) => `\"${t.stream}\"`).join(\", \")} failed and was not retried; close it with app.close(...) once the cause is fixed.`\n );\n }\n },\n breaker: this._breaker,\n run_scoped: this._scoped,\n lane: single_default_lane ? undefined : name,\n defaults: cfg && {\n streamLimit: cfg.streamLimit,\n leaseMillis: cfg.leaseMillis,\n },\n });\n // A lane with `cycleMs` drives itself on that timer (not on\n // writer-only instances).\n if (cfg?.cycleMs !== undefined && this._drain)\n controller.start(cfg.cycleMs);\n controllers.set(name, controller);\n }\n return controllers;\n }\n\n // One process can't see the cluster, so it reports its own lane gaps.\n private _advise_orphaned_lanes(): void {\n const active = new Set(this._drain_controllers.keys());\n const orphaned = this._declared_lanes.filter((name) => !active.has(name));\n if (orphaned.length === 0) return;\n const list = orphaned.map((name) => `\"${name}\"`).join(\", \");\n this._logger.info(\n `Act declared ${orphaned.length} orphaned lane(s) on this instance: ${list}. ` +\n `onlyLanes excludes them, so no DrainController claims their streams here — ` +\n `their reactions accumulate un-drained unless a peer worker deploys with these ` +\n `lanes in its onlyLanes. Ensure the cluster invariant holds: the union of every ` +\n `worker's onlyLanes must cover every declared lane. ` +\n `See docs/docs/guides/production-checklist.md § Sizing lanes.`\n );\n }\n\n // Audit deps, built after the controllers so the lane set is final.\n private _build_audit_deps(): AuditDeps {\n return {\n store,\n event_to_state: this._event_to_state,\n // Declared lanes, not this process's controllers: a lane another\n // worker drains is not `unknown-lane`.\n declared_lanes: new Set(this._declared_lanes),\n routed_events: new Set(this._event_to_lanes.keys()),\n };\n }\n\n private _build_correlate(\n options: ActOptions,\n classification: ReturnType<\n typeof classify_registry<TSchemaReg, TEvents, TActions>\n >\n ): CorrelateCycle<TSchemaReg, TEvents, TActions> {\n return new CorrelateCycle({\n registry: this.registry,\n static_targets: classification.static_targets,\n cd: this._cd,\n max_subscribed_streams:\n options.maxSubscribedStreams ?? DEFAULT_MAX_SUBSCRIBED_STREAMS,\n // Declared lanes (not active ones): a lane another process claims is\n // still a valid destination.\n declared_lanes: new Set(this._declared_lanes),\n // Built after the controllers, so their keys are the active lanes.\n shard:\n this._drain_controllers.size < this._declared_lanes.length\n ? [...this._drain_controllers.keys()]\n : undefined,\n // Only reached on a draining app: writer-only ones never correlate.\n on_init: async () => {\n this._arm_all();\n await this._seed_persisted_defers();\n },\n });\n }\n\n // Cold start: an idle deferred stream still fires on time after a restart.\n private async _seed_persisted_defers(): Promise<void> {\n const now = Date.now();\n await walk_streams(store(), (pos) => {\n // A past-due schedule is already claimable.\n if (pos.deferred_at === undefined || pos.deferred_at <= now) return;\n const controller = this._drain_controllers.get(pos.lane ?? \"default\");\n controller?.seed_defer(pos.stream, pos.deferred_at);\n });\n }\n\n private _build_settle(options: ActOptions): SettleLoop<TEvents> {\n return new SettleLoop<TEvents>(\n {\n correlate: (q) =>\n this._correlate_pass(q.limit ?? this._poll_limit ?? 100, true),\n // `settle()` validated the options, and `_schedule` skips writer-only\n // instances, so the loop drains through the internal path.\n drain: (o) => this._scoped(() => this._drain_all(o)),\n on_settled: (drain) => this.emit(\"settled\", drain),\n breaker: this._breaker,\n },\n options.settleDebounceMs ?? DEFAULT_SETTLE_DEBOUNCE_MS\n );\n }\n\n private _shutdown_promise: Promise<void> | undefined;\n\n /**\n * Per-instance teardown: stops scheduling, removes the notify\n * subscription, gives the cycles in flight up to `graceMs` to reach their\n * `ack` (an abandoned handler holds its lease until it expires), then\n * hands back the correlation lease and removes listeners.\n * The budget is a ceiling, not a delay.\n *\n * Idempotent: repeated calls return the same promise, with the first\n * call's `graceMs`. Registered with the global `dispose()` registry, so\n * `dispose()()` covers it; call it directly for prompt cleanup.\n *\n * @param options - See {@link ShutdownOptions}. Defaults the grace budget\n * to the largest lane `leaseMillis` (capped at 30s).\n */\n shutdown(options?: ShutdownOptions): Promise<void> {\n if (!this._shutdown_promise) {\n resolveShutdownConfig(options);\n this._shutdown_promise = (async () => {\n // Stop every scheduler before awaiting anything slow, so nothing\n // starts while the notify subscription comes down.\n this.stop_correlations();\n this._settle.stop(true);\n this._breaker.stop();\n for (const c of this._drain_controllers.values()) c.stop();\n // Never rejects.\n const disposer = await this._notify_disposer;\n if (disposer) await disposer();\n await this._await_inflight(options?.graceMs);\n // Hand the correlation lease back last, after the wait (a settle\n // cycle still running would re-take it), and await it so a\n // successor isn't refused.\n await this._scoped(() => this._correlate.release_correlation());\n this._emitter.removeAllListeners();\n })();\n }\n return this._shutdown_promise;\n }\n\n // The largest `leaseMillis` among lanes with a cycle in flight (the\n // default for none or 0, and for a running settle), capped.\n private _derive_grace_ms(\n running: { readonly lease_millis: number | undefined }[],\n settling: boolean\n ): number {\n // A lane with no lease waits the drain's default lease: as long as its\n // handlers were already allowed to hold a stream.\n let max = settling ? DEFAULT_LEASE_MILLIS : 0;\n for (const c of running)\n max = Math.max(max, c.lease_millis || DEFAULT_LEASE_MILLIS);\n return Math.min(max, MAX_SHUTDOWN_GRACE_MS);\n }\n\n private async _await_inflight(grace_ms?: number): Promise<void> {\n const running = [...this._drain_controllers.values()].filter(\n (c) => c.inflight !== undefined\n );\n // A settle cycle already running keeps going after `stop()`, so wait\n // for it too.\n const settling = this._settle.inflight;\n if (running.length === 0 && !settling) return;\n const grace = grace_ms ?? this._derive_grace_ms(running, !!settling);\n if (grace <= 0) return;\n let timer!: ReturnType<typeof setTimeout>;\n const budget = new Promise<void>((resolve) => {\n timer = setTimeout(resolve, grace);\n timer.unref();\n });\n try {\n await Promise.race([\n Promise.all([...running.map((c) => c.inflight), settling]),\n budget,\n ]);\n } finally {\n // Don't leave the budget timer pending when the cycles won the race.\n clearTimeout(timer);\n }\n }\n\n // Failures are logged, never thrown: `notify` is a hint.\n private async _wire_notify(\n s: Store,\n listen: boolean\n ): Promise<(() => void | Promise<void>) | undefined> {\n if (!this._reactive) return undefined;\n if (!s.notify) return undefined;\n // Only the subscriber side is gated; commits still notify.\n if (!listen) return undefined;\n try {\n return await s.notify((notification) => {\n // Errors are logged and swallowed so the store's listener survives.\n try {\n this.emit(\"notified\", notification);\n this._wake(notification.events.map((e) => e.name));\n } catch (err) {\n this._logger.error(err, \"notified handler threw\");\n }\n });\n } catch (err) {\n this._logger.error(err, \"Store.notify subscription failed\");\n return undefined;\n }\n }\n\n /**\n * Executes an action: validates the payload, loads the state, checks its\n * preconditions, runs the handler, folds the events it emits, checks the\n * state's invariants (its schema) on the result, and commits them with\n * optimistic concurrency on every stream it appends to. The reactions to those events\n * settle on their own (unless `autoSettle: false`).\n *\n * @template TKey - Action name from registered actions\n * @param action - The name of the action to execute\n * @param target - Target specification with stream ID and actor context\n * @param payload - Action payload matching the action's schema\n * @param options - Per-call dispatch options ({@link DoOptions}) —\n * `reactingTo` to thread correlation, `correlator` to override the\n * framework or orchestrator-level correlator for this call only.\n * @returns The snapshots of the action's own stream, one per event appended\n * to it; the loaded snapshot alone when the action commits nothing\n *\n * @throws {ValidationError} If the payload doesn't match the action schema,\n * or the state the action leaves breaks the state schema\n * @throws {PreconditionError} If business rules are violated\n * @throws {ConcurrencyError} If another process modified the stream\n *\n * @example Basic action execution\n * ```typescript\n * const snapshots = await app.do(\n * \"increment\",\n * {\n * stream: \"counter-1\",\n * actor: { id: \"user1\", name: \"Alice\" }\n * },\n * { by: 5 }\n * );\n *\n * console.log(snapshots[0].state.count); // Current count after increment\n * ```\n *\n * @see {@link Target} for target structure\n * @see {@link Snapshot} for return value structure\n * @see {@link ValidationError}, {@link PreconditionError}, {@link ConcurrencyError}\n */\n async do<TKey extends keyof TActions>(\n action: TKey,\n target: Target<TActor>,\n payload: Readonly<TActions[TKey]>,\n options?: DoOptions<TEvents>\n ) {\n // Resolve the ambient reaction context here so `internal/` never reads\n // ambient state. An explicit `reactingTo` wins.\n const reacting_to = options?.reactingTo ?? current_reacting();\n const do_options =\n reacting_to === options?.reactingTo\n ? options\n : { ...options, reactingTo: reacting_to };\n return this._scoped(async () => {\n const snapshots = await this._es.action(\n this.registry.actions[action],\n action,\n target,\n payload,\n do_options\n );\n // An action that emits nothing returns the loaded snapshot, which has\n // no `patch`: nothing committed, so nothing to wake or announce.\n // Snapshots of the streams its loads appended to follow its own.\n if (!snapshots[0].patch) return snapshots;\n // A local commit runs its reactions the way a remote one does.\n this._wake(snapshots.map((s) => s.event!.name as string));\n // `committed` fires once per stream appended to, its own first, so a\n // listener always gets one stream's snapshots, as without loads.\n const by_stream = new Map<string, typeof snapshots>();\n for (const s of snapshots) {\n const of_stream = by_stream.get(s.event!.stream);\n if (of_stream) of_stream.push(s);\n else by_stream.set(s.event!.stream, [s]);\n }\n for (const of_stream of by_stream.values()) {\n const owner = this._event_to_state.get(\n of_stream[0].event!.name as string\n )!;\n this.emit(\"committed\", of_stream);\n this._notify(`committed:${owner.name}`, of_stream);\n }\n return snapshots.filter((s) => s.event!.stream === target.stream);\n });\n }\n\n /**\n * Loads the current state snapshot for a specific stream.\n *\n * Reconstructs the current state by replaying events from the event store.\n * Uses snapshots when available to optimize loading performance.\n *\n * Accepts either a State definition object or a state name string. When\n * using a string, the merged state (from partial states registered via\n * `.withState()`) is resolved by name.\n *\n * @template TNewState - State schema type\n * @template TNewEvents - Event schemas type\n * @template TNewActions - Action schemas type\n * @param state - The state definition or state name to load\n * @param stream - The stream ID (state instance identifier)\n * @param callback - Optional callback invoked with the loaded snapshot\n * @returns The current state snapshot for the stream\n *\n * @example Load by state definition\n * ```typescript\n * const snapshot = await app.load(Counter, \"counter-1\");\n * console.log(snapshot.state.count); // Current count\n * console.log(snapshot.patches); // Events since last snapshot\n * ```\n *\n * @see {@link Snapshot} for snapshot structure\n */\n // Anonymous load (bare stream) — sensitive fields come back as REDACTED.\n async load<\n TNewState extends Schema,\n TNewEvents extends Schemas,\n TNewActions extends Schemas,\n >(\n state: State<TNewState, TNewEvents, TNewActions>,\n stream: string,\n callback?: (snapshot: Snapshot<TNewState, TNewEvents>) => void,\n asOf?: AsOf\n ): Promise<Snapshot<TNewState, TNewEvents>>;\n async load<TKey extends keyof TStateMap & string>(\n name: TKey,\n stream: string,\n callback?: (snapshot: Snapshot<TStateMap[TKey], TEvents>) => void,\n asOf?: AsOf\n ): Promise<Snapshot<TStateMap[TKey], TEvents>>;\n // Auth-aware load — runs `.discloses(predicate)` against the supplied actor.\n async load<\n TNewState extends Schema,\n TNewEvents extends Schemas,\n TNewActions extends Schemas,\n >(\n state: State<TNewState, TNewEvents, TNewActions>,\n target: LoadTarget<TActor>,\n callback?: (snapshot: Snapshot<TNewState, TNewEvents>) => void\n ): Promise<Snapshot<TNewState, TNewEvents>>;\n async load<TKey extends keyof TStateMap & string>(\n name: TKey,\n target: LoadTarget<TActor>,\n callback?: (snapshot: Snapshot<TStateMap[TKey], TEvents>) => void\n ): Promise<Snapshot<TStateMap[TKey], TEvents>>;\n async load<TNewState extends Schema>(\n stateOrName: State<TNewState, any, any> | string,\n streamOrTarget: string | LoadTarget<TActor>,\n callback?: (snapshot: Snapshot<any, any>) => void,\n asOf?: AsOf\n ): Promise<Snapshot<any, any>> {\n return this._scoped(async () => {\n let merged: State<any, any, any>;\n if (typeof stateOrName === \"string\") {\n const found = this._states.get(stateOrName);\n if (!found) throw new Error(`State \"${stateOrName}\" not found`);\n merged = found;\n } else {\n merged = this._states.get(stateOrName.name) || stateOrName;\n }\n // Normalize the two surfaces: bare-stream (default-deny — actor\n // undefined → REDACTED on the discloses check) vs LoadTarget\n // (auth-aware — actor flows into `.discloses(predicate)`).\n const target: LoadTarget<Actor> =\n typeof streamOrTarget === \"string\"\n ? {\n stream: streamOrTarget,\n actor: undefined as unknown as Actor,\n asOf,\n }\n : streamOrTarget;\n return await this._es.load(merged, target, callback);\n });\n }\n\n /**\n * Queries the event store for events matching a filter.\n *\n * Use this for analyzing event streams, generating reports, or debugging.\n * The callback is invoked for each matching event, and the method returns\n * summary information (first event, last event, total count).\n *\n * For small result sets, consider using {@link query_array} instead.\n *\n * @param query - Filter criteria; see {@link Query} for the fields\n * @param callback - Optional callback invoked for each matching event\n * @returns Object with first event, last event, and total count\n *\n * @example Query all events for a stream\n * ```typescript\n * const { first, last, count } = await app.query(\n * { stream: \"counter-1\" },\n * (event) => console.log(event.name, event.data)\n * );\n * console.log(`Found ${count} events from ${first?.id} to ${last?.id}`);\n * ```\n *\n * @see {@link query_array} for loading events into memory\n */\n async query(\n query: Query,\n callback?: (event: Committed<TEvents, keyof TEvents>) => void\n ): Promise<{\n first?: Committed<TEvents, keyof TEvents>;\n last?: Committed<TEvents, keyof TEvents>;\n count: number;\n }> {\n return this._scoped(async () => {\n let first: Committed<TEvents, keyof TEvents> | undefined;\n let last: Committed<TEvents, keyof TEvents> | undefined;\n const count = await store().query<TEvents>((e) => {\n const gated = this.registry.query_gate(e.name as string)(e);\n if (!first) first = gated;\n last = gated;\n callback?.(gated);\n }, query);\n return { first, last, count };\n });\n }\n\n /**\n * Queries the event store and returns all matching events in memory.\n *\n * **Use with caution** - this loads all results into memory. For large result sets,\n * use {@link query} with a callback instead to process events incrementally.\n *\n * @param query - The query filter (same as {@link query})\n * @returns Array of all matching events\n *\n * @example Load all events for a stream\n * ```typescript\n * const events = await app.query_array({ stream: \"counter-1\" });\n * console.log(`Loaded ${events.length} events`);\n * events.forEach(event => console.log(event.name, event.data));\n * ```\n *\n * @see {@link query} for large result sets\n */\n async query_array(\n query: Query\n ): Promise<Committed<TEvents, keyof TEvents>[]> {\n const events: Committed<TEvents, keyof TEvents>[] = [];\n await this.query(query, (e) => events.push(e));\n return events;\n }\n\n /**\n * Wipe the sensitive-data payload for every event on the stream — see\n * {@link IAct.forget}.\n *\n * Throws on adapters without `Store.forget_pii`, invalidates the cache\n * entry for the stream, emits the `forgotten` lifecycle event with the\n * row count. Idempotent: a second call returns `{eventCount: 0}` and\n * does NOT re-emit.\n *\n * @param stream - Target stream.\n * @returns `{eventCount}` — number of events whose PII column was wiped.\n */\n async forget(stream: string): Promise<{ eventCount: number }> {\n return this._scoped(async () => {\n const s = store();\n if (!s.forget_pii) {\n throw new Error(\n `Store does not implement forget_pii — adapter cannot comply with sensitive-data erasure. ` +\n `Use an adapter that declares pii_isolation: true (e.g. @rotorsoft/act on the in-memory store).`\n );\n }\n const eventCount = await s.forget_pii(stream);\n await cache().invalidate(stream);\n if (eventCount > 0) {\n this.emit(\"forgotten\", { stream, at: new Date(), eventCount });\n }\n return { eventCount };\n });\n }\n\n /**\n * Runs one drain cycle: claims streams with marked work (leasing them),\n * fetches their events, runs the matching reactions, and acks or blocks\n * each stream.\n *\n * A stream is claimable only once `correlate()` has marked it, static\n * targets included, so a commit no correlate has seen is not drainable.\n * Apps rarely call this: each commit settles its reactions on its own.\n * With `autoSettle: false`, tests walk the pipeline with `correlate()`\n * then `drain()` (see the testing guide).\n *\n * @param options - Drain configuration — see {@link DrainOptions} for fields\n * (`streamLimit`, `eventLimit`, `leaseMillis`).\n * @returns Drain statistics with fetched, leased, acked, and blocked counts\n *\n * @example Walking the pipeline in a test\n * ```typescript\n * const app = act().withState(User).withProjection(Users).build({ autoSettle: false });\n * await app.do(\"createUser\", target, payload);\n * await app.correlate();\n * await app.drain();\n * ```\n *\n * @see {@link settle} for debounced correlate→drain with lifecycle events\n * @see {@link correlate} for dynamic stream discovery\n */\n async drain(options: DrainOptions = {}): Promise<Drain<TEvents>> {\n // Validate the runtime knobs before anything runs (a bad leaseMillis /\n // streamLimit / eventLimit throws ZodError here, not on the first cycle).\n resolveDrainConfig(options);\n // Writer-only instances run no reactions.\n if (!this._drain)\n return { fetched: [], leased: [], acked: [], blocked: [] };\n return this._scoped(() => this._drain_all(options));\n }\n\n // Arms correlate and every lane; false on an app with no reactions.\n private _arm_all(): boolean {\n if (!this._reactive) return false;\n // A commit may also give the next correlate scan something to find.\n this._correlate.arm();\n for (const c of this._drain_controllers.values()) c.arm();\n return true;\n }\n\n // Wakes what a change freed (a commit, a reset, an unblock, a restore,\n // a notification from another process): arms the lanes these events\n // react on, or every lane without names, and settles them unless the app\n // walks the pipeline itself (`autoSettle: false`).\n private _wake(names?: Iterable<string>): void {\n const armed = names ? this._arm_for_event_names(names) : this._arm_all();\n if (armed && this._auto_settle) this._schedule();\n }\n\n // Schedules a settle pass; writer-only instances (`drain: false`) skip it.\n private _schedule(options?: SettleOptions): void {\n if (this._drain) this._settle.schedule(options);\n }\n\n // Arms only the lanes these events react on; true when any was armed.\n private _arm_for_event_names(names: Iterable<string>): boolean {\n const to_arm = new Set<string>();\n for (const name of names) {\n const set = this._event_to_lanes.get(name);\n if (set === undefined) continue;\n if (set === ALL_LANES) {\n this._arm_all();\n return true;\n }\n for (const lane of set) to_arm.add(lane);\n }\n if (to_arm.size === 0) return false;\n this._correlate.arm();\n for (const lane of to_arm) this._drain_controllers.get(lane)?.arm();\n return true;\n }\n\n // In parallel, so a slow lane never holds up a fast one.\n private async _drain_all(options: DrainOptions): Promise<Drain<TEvents>> {\n const merged = merge_drains(\n await Promise.all(\n [...this._drain_controllers.values()].map((c) => c.drain(options))\n )\n );\n // Actor-less like `query`/`query_array`, so default-deny.\n // Handlers are unaffected — they read through their own strip.\n return {\n ...merged,\n fetched: merged.fetched.map((f) => ({\n ...f,\n events: f.events.map((e) =>\n this.registry.query_gate(e.name as string)(e)\n ),\n })),\n };\n }\n\n /**\n * Scans committed events from the correlation checkpoint, subscribes the\n * target streams their reactions resolve to (static or computed from\n * the event), and marks their work so the next drain can claim it.\n *\n * @param query - Only `limit` is used: the most events the pass reads\n * (10 when the query has none; `0` reads everything). The scan always\n * starts at the correlation checkpoint, which every reaction shares, so\n * filters and `after` are ignored.\n * @returns The number of newly subscribed streams and the last scanned event id\n *\n * @example Manual correlation\n * ```typescript\n * const { subscribed } = await app.correlate({ limit: 100 });\n * ```\n *\n * @see {@link start_correlations} for automatic periodic correlation\n */\n async correlate(\n query: Query = {}\n ): Promise<{ subscribed: number; last_id: number }> {\n const pass = await this._correlate_pass(query.limit ?? 10);\n return {\n subscribed: pass.kind === \"scanned\" ? pass.subscribed : 0,\n last_id: pass.last_id,\n };\n }\n\n // One correlate pass; arms every lane when it found work.\n private async _correlate_pass(\n limit: number,\n /** Honour the correlation lease — settle and the poller only. */\n lease = false\n ): Promise<CorrelatePass> {\n // Writer-only instances don't correlate.\n if (!this._drain) return { kind: \"idle\", last_id: -1 };\n return this._scoped(async () => {\n const pass = await this._correlate.correlate(limit, lease);\n // Only a mark makes a stream claimable. Also re-arms correlate, so a\n // backlog scan keeps going.\n if (pass.kind === \"scanned\" && pass.marked > 0) this._arm_all();\n return pass;\n });\n }\n\n /**\n * Starts a background poll that settles on a timer: each tick looks for\n * new events, subscribes the streams their reactions target, and drains\n * them, along with any stream whose lease a dead worker let expire.\n *\n * Use it when this process can miss commits — another process writes to a\n * store without `notify`, or a notification is lost. It is the safety net\n * under `notify`: a missed wakeup costs at most one `frequency` of latency.\n *\n * Only one poll runs per Act instance. On a writer-only instance\n * (`drain: false`) each tick is a no-op, like `settle()`.\n *\n * @param query - Only `limit` is used: the most events each correlate pass\n * reads. With no limit, or `0`, the passes use the background default\n * (100): a poll never reads the whole log in one tick. The scan always\n * starts at the correlation checkpoint, so `after` is ignored.\n * @param frequency - Milliseconds between ticks (default: 10000)\n * @returns `true` if the poll started, `false` if one is already running\n *\n * @example\n * ```typescript\n * app.start_correlations({ limit: 100 }, 5000);\n * // later\n * app.stop_correlations();\n * ```\n *\n * @see {@link settle} for what each tick runs\n * @see {@link stop_correlations} to stop the poll\n */\n start_correlations(query: Query = {}, frequency = 10_000): boolean {\n if (this._poll) return false;\n this._poll_limit = query.limit || undefined;\n this._poll = setInterval(() => {\n // No local signal says there is work, so look anyway: correlate for\n // new events, and every lane for leases that came free (a dead\n // worker's expired lease is claimable, but no commit will say so).\n this._arm_all();\n this._schedule();\n }, frequency);\n return true;\n }\n\n /**\n * Stops the poll started by {@link start_correlations}. Idempotent, and\n * called by `shutdown()`.\n *\n * @see {@link start_correlations}\n */\n stop_correlations() {\n if (this._poll) {\n clearInterval(this._poll);\n this._poll = undefined;\n this._poll_limit = undefined;\n }\n // Hand the correlation lease back, best-effort and not awaited (this\n // method is synchronous; the lease would expire anyway).\n void this._scoped(() => this._correlate.release_correlation());\n }\n\n /**\n * Drops the settle pass scheduled but not yet started. A cycle already\n * running finishes; later changes schedule new passes.\n *\n * @see {@link settle}\n */\n stop_settling() {\n this._settle.stop();\n }\n\n /**\n * Reset reaction stream watermarks and settle them, replaying their\n * events through their reactions.\n *\n * Use this to replay events through projections (or other reaction targets)\n * after changing handler logic. It rewinds the same watermarks as\n * `store().reset(streams)`, and also wakes the drain and schedules a\n * settle, which loops correlate→drain until the replay catches up;\n * `store().reset(...)` alone leaves a settled app idle. Call\n * `app.settle(options)` right after to give that pass batch options, or,\n * with `autoSettle: false`, `correlate()` / `drain()` to drive the replay\n * by hand.\n *\n * @param input - Reaction target streams (e.g., projection names) to reset, or a {@link StreamFilter} for bulk operations\n * @returns Count of streams that were actually reset\n *\n * @example Rebuild a projection (production)\n * ```typescript\n * await app.reset([\"my-projection\"]);\n * app.settle({ eventLimit: 1000 }); // optional: bigger batches; emits \"settled\"\n * ```\n *\n * @see {@link Store.reset} for the underlying store primitive\n * @see {@link settle} for the debounced full-catch-up loop\n */\n async reset(input: string[] | StreamFilter): Promise<number> {\n return this._scoped(async () => {\n const count = await store().reset(input);\n // Drop every fold cache before the replay, or a warm cache would\n // re-flush stale rows. Cleared for all targets: resolving `input`\n // costs a query, and an extra clear costs one head load per stream.\n for (const handler of this._batch_handlers.values())\n (handler as ResettableBatchHandler<TEvents>)[FOLD_RESET]?.();\n if (count > 0) {\n this._wake();\n }\n return count;\n });\n }\n\n /**\n * Clear the blocked flag on streams without replaying their history.\n *\n * Use this to recover from a poison message after fixing the\n * underlying issue — the stream resumes from the next event after the\n * last successful ack, not from the beginning. Compare with\n * {@link reset}, which rebuilds from event 0 (suitable for projection\n * rebuilds, wrong for \"I fixed the bug, please retry\").\n *\n * Wraps `store().unblock(streams)` and settles the now-free streams on\n * its own. `store().unblock(...)` alone leaves them waiting for the next\n * commit.\n *\n * @param input - Stream names to unblock, or a {@link StreamFilter} for bulk recovery\n * @returns Count of streams that were actually flipped (were blocked)\n *\n * @example Recover from a 4xx webhook after fixing the bug\n * ```typescript\n * await app.unblock([\"webhooks-out-customer-42\"]);\n * // The stream resumes from the next event, not from zero.\n * ```\n *\n * @see {@link Store.unblock} for the underlying store primitive\n * @see {@link reset} for the rebuild-from-zero alternative\n */\n async unblock(input: string[] | StreamFilter): Promise<number> {\n return this._scoped(async () => {\n const count = await store().unblock(input);\n if (count > 0) {\n this._wake();\n }\n return count;\n });\n }\n\n /**\n * Atomically wipe the store and rebuild it from an event source. The\n * framework owns iteration, validation, `drop_snapshots` filtering,\n * `on_progress`, and the per-call `old → new` causation remap; the\n * adapter's {@link Store.restore} driver supplies the transaction\n * lifecycle and per-event insert.\n *\n * Safe in a live process: restoring into this Act's own store waits\n * for its correlate passes in flight, replaces the log, then restarts\n * correlation and settles. A correlate pass that starts meanwhile\n * reads nothing. Other processes on the same store keep their\n * correlation state and must be restarted.\n *\n * Throws if the adapter has no restore capability. Throws on the\n * first invalid event (negative version, malformed `created`) with\n * the running index in the message; atomic transaction rollback in\n * the adapter means a failing restore leaves the store byte-for-byte\n * unchanged.\n *\n * @param source - Any {@link EventSource}: a `CsvFile` backup or\n * another store. Read in batches rather than buffered, so\n * multi-million-event backups don't OOM. Each event's original `id`\n * is used as a causation lookup key but never written through —\n * adapters renumber densely.\n * @param opts - {@link ScanOptions}. `drop_snapshots` skips\n * `__snapshot__` events (counted in the result); `on_progress`\n * fires once per event.\n * @param sink - Where the events land. Defaults to this Act's store.\n * @returns The {@link ScanResult}: what was kept, migrated and dropped,\n * and how long it took.\n *\n * @example Restore a CSV backup into the connected store\n * ```typescript\n * const result = await app.restore(new CsvFile({ path: \"./backup.csv\" }));\n * console.log(`Restored ${result.kept} events in ${result.duration_ms}ms`);\n * await cache().clear(); // operator's responsibility\n * ```\n *\n * @see {@link Store.restore} for the underlying driver-pattern primitive.\n */\n async restore(\n source: EventSource,\n opts: ScanOptions = {},\n sink?: EventSink\n ): Promise<ScanResult> {\n return this._scoped(async () => {\n const started = Date.now();\n // Dry-run: count what a restore would land, touching no sink.\n if (opts.dry_run) {\n const partial = await scan(source, opts);\n return { ...partial, duration_ms: Date.now() - started };\n }\n // Default sink is this Act's store.\n const target: EventSink =\n sink ??\n (() => {\n const s = store();\n if (!s.restore) throw new Error(\"adapter has no restore capability\");\n return s as EventSink;\n })();\n let kept = 0;\n let migrated = 0;\n let dropped = { closed_streams: 0, snapshots: 0 };\n const run = () =>\n target.restore(async (callback) => {\n const partial = await scan(source, opts, callback);\n kept = partial.kept;\n migrated = partial.migrated;\n dropped = partial.dropped;\n });\n if (sink) await run();\n else {\n // Restoring into this app's own store replaces its log (new ids, no\n // subscription rows): restart correlation from cold and arm the drain.\n await this._correlate.restart(run);\n this._wake();\n }\n return { kept, migrated, dropped, duration_ms: Date.now() - started };\n });\n }\n\n /**\n * Return every currently-blocked stream position. Convenience wrapper\n * around `store().query_streams(cb, { blocked: true })` for the common\n * \"show me what's broken\" operational query.\n *\n * Results are ordered by stream name, paginated by `limit` (default\n * 100). Pass `after` to fetch the next page (keyset cursor on the\n * stream name). For richer queries — including blocked + source\n * filters, or full unblocked introspection — drop to\n * `store().query_streams(...)` directly.\n *\n * @returns Array of {@link StreamPosition} for currently-blocked streams.\n *\n * @example Discover and recover\n * ```typescript\n * const blocked = await app.blocked_streams();\n * console.table(blocked.map(({ stream, retry, error }) => ({ stream, retry, error })));\n *\n * // Operator investigates, then bulk-unblocks the family:\n * await app.unblock({ stream: \"^webhooks-out-\" });\n * ```\n */\n async blocked_streams(options?: {\n after?: string;\n limit?: number;\n }): Promise<StreamPosition[]> {\n return this._scoped(async () => {\n const positions: StreamPosition[] = [];\n await store().query_streams(\n (p) => {\n positions.push(p);\n },\n { blocked: true, after: options?.after, limit: options?.limit }\n );\n return positions;\n });\n }\n\n /**\n * Operator-driven store audit: walks the store and yields findings per\n * category, each with the remediation it suggests. Never run by the\n * framework. Pass a subset of categories to scope the work; the iterable\n * can be broken early, and findings stream without buffering the report.\n *\n * @param categories - Subset of categories to run (default: all).\n * @param options - Query window + per-category thresholds.\n * @returns Async iterable of {@link AuditFinding}.\n *\n * @example Schema drift since the last scan\n * ```typescript\n * for await (const f of app.audit([\"schema\"], { query: { created_after: lastScan } }))\n * await escalate(f);\n * ```\n */\n async *audit(\n categories?: AuditCategory[],\n options?: AuditOptions\n ): AsyncIterable<AuditFinding> {\n // Step the generator inside `_scoped`: its body runs lazily in the\n // consumer's frame, which would otherwise resolve the wrong store.\n const it = audit(this._audit_deps, categories, options)[\n Symbol.asyncIterator\n ]();\n while (true) {\n const { value, done } = await this._scoped(() => it.next());\n if (done) break;\n yield value;\n }\n }\n\n /**\n * Sets the scheduling priority of every stream matching `filter`, as-is:\n * unlike build-time priorities (the highest across reactions wins), this\n * overrides them. Useful to let a long replay jump ahead of other lagging\n * streams, or to yield slots back. **An empty filter (`{}`) updates every\n * registered stream.**\n *\n * @param filter - Selection criteria (regex by default, like {@link query}).\n * @param priority - New priority value, a 32-bit integer. Set as-is — no clamp.\n * @returns Count of streams whose priority changed.\n * @throws ZodError when `priority` isn't a 32-bit integer.\n *\n * @example Boost a specific projection mid-replay\n * ```typescript\n * await app.prioritize({ stream: \"^proj-orders$\", stream_exact: false }, 10);\n * ```\n *\n * @see {@link Store.prioritize} for the underlying primitive\n */\n async prioritize(filter: StreamFilter, priority: number): Promise<number> {\n resolveTargetConfig({ priority });\n return this._scoped(() => store().prioritize(filter, priority));\n }\n\n // Shared by `close()` and reaction-requested closes.\n private async _run_close(targets: CloseTarget[]): Promise<CloseResult> {\n const close_actor = { id: \"$close\", name: \"close\" };\n const result = await run_close_cycle(targets, {\n reactive: this._reactive,\n catch_up_correlation: (until) =>\n catch_up_correlation(\n this._correlate,\n (limit) => this.correlate({ limit }),\n until\n ),\n event_to_state: this._event_to_state,\n load: this._es.load,\n tombstone: this._es.tombstone,\n logger: this._logger,\n correlation: close_correlation(this._correlator, close_actor),\n with_stream_lock: (stream, work) => this._close_lock.run(stream, work),\n forget_subscribed: (streams) =>\n this._correlate.forget_subscribed(streams),\n });\n this.emit(\"closed\", result);\n return result;\n }\n\n /**\n * Close the books: guard, archive, truncate, and optionally restart\n * streams. A stream with pending reactions is skipped; an archive\n * failure aborts the whole close while the streams are still guarded.\n * Targets carrying `before` prune a rolling window instead and leave the\n * stream live (needs `.snap(...)`). The phases and their failure\n * semantics are in the close-cycle architecture page.\n *\n * @param targets - Per-stream close options (stream, restart?, archive?, before?)\n * @returns `{ truncated: TruncateResult, skipped: string[] }`\n *\n * @example Archive and close\n * ```typescript\n * await app.close([\n * { stream: \"order-123\", archive: async () => { await archiveToS3(\"order-123\"); } },\n * { stream: \"order-456\" },\n * ]);\n * ```\n */\n async close(targets: CloseTarget[]): Promise<CloseResult> {\n if (!targets.length) return { truncated: new Map(), skipped: [] };\n\n return this._scoped(() => this._run_close(targets));\n }\n\n /**\n * Debounced, non-blocking correlate→drain cycle.\n *\n * A local change that frees reaction work (a commit, `reset()`,\n * `unblock()`, `restore()`) schedules this on its own unless the app\n * sets `autoSettle: false`. Call it at startup, to run what was pending\n * before a restart, or with options for the next pass; the scheduling\n * rule is in the event-sourcing docs (§ settle). Runs correlate→drain\n * passes until one makes no progress (see {@link SettleOptions.maxPasses}),\n * then emits the `\"settled\"` lifecycle event, so one call fully catches\n * up paginated streams without forcing callers to loop.\n *\n * @param options - Settle configuration — see {@link SettleOptions} for fields:\n * `debounceMs` (default 10), `correlate.limit` (default 100, or the\n * poll's limit while `start_correlations` runs; `after` is always the\n * checkpoint),\n * `maxPasses` (default `Infinity`; caps this settle's passes, not the\n * passes a reaction chain's own commits schedule),\n * `streamLimit` (default 10), `eventLimit` (default 10),\n * `leaseMillis` (default 10000).\n *\n * @example Startup\n * ```typescript\n * app.settle(); // run what was pending before the restart\n *\n * app.on(\"settled\", (drain) => {\n * // notify SSE clients, invalidate caches, etc.\n * });\n * ```\n *\n * @see {@link drain} for single synchronous drain cycles\n * @see {@link correlate} for manual correlation\n */\n settle(options?: SettleOptions): void {\n // Validate the runtime knobs before anything runs (a bad debounceMs /\n // leaseMillis / maxPasses throws ZodError here, not on the first pass).\n resolveSettleConfig(options ?? {});\n this._schedule(options);\n }\n}\n","/**\n * Auto-deprecation of legacy event versions via the `_v<digits>` naming\n * convention.\n *\n * Act's schema-evolution pattern keeps the old and new event names alive\n * forever — the old name on the read path (reducers), the new on the write\n * path (emissions). This module reads the convention to identify legacy\n * versions automatically; the framework then enforces \"emit only the\n * current version\" at build time and warns at runtime for dynamic emits.\n *\n * Convention pin: only `_v<digits>` with digits ≥ 2 counts as a version\n * suffix. `Foo_v1` is just a literal event name (the base `Foo` is\n * implicitly v1). Pinning here keeps the contract surface small.\n */\n\nconst VERSION_SUFFIX = /^(.+?)_v(\\d+)$/;\n\ntype Versioned = { version: number; name: string };\n\n/**\n * Splits an event name into (base, version). Names without a `_v<n≥2>`\n * suffix are returned as (name, 1) — the base is its own implicit v1.\n */\nfunction parse(name: string): { base: string; version: number } {\n const m = name.match(VERSION_SUFFIX);\n if (m) {\n const v = Number.parseInt(m[2], 10);\n if (v >= 2) return { base: m[1], version: v };\n }\n return { base: name, version: 1 };\n}\n\n/**\n * Returns the set of event names that are deprecated by virtue of having\n * a higher-numbered sibling in the registry. The highest version in each\n * group is the current version; every lower version is deprecated.\n *\n * Gaps are allowed: `{Foo, Foo_v3}` → `Foo` is deprecated, `Foo_v3` is\n * current. The framework picks the max regardless of contiguity.\n *\n * Single-version groups (no siblings) yield no deprecations.\n */\nexport function deprecated_event_names(names: Iterable<string>): Set<string> {\n const groups = new Map<string, Versioned[]>();\n for (const name of names) {\n const { base, version } = parse(name);\n const list = groups.get(base);\n if (list) list.push({ version, name });\n else groups.set(base, [{ version, name }]);\n }\n const deprecated = new Set<string>();\n for (const list of groups.values()) {\n if (list.length < 2) continue;\n // Two names mapping to the same numeric version (e.g. a leading-zero\n // `Foo_v02` alongside `Foo_v2`) can't both be a distinct version — one\n // is a typo. Left unguarded, the sort below would flag whichever lands\n // second, so declaration order would decide which one is \"current\",\n // and the real current event could be marked deprecated (a static\n // `.emit(...)` on it would then throw at build). Reject the collision\n // with a clear, order-independent error instead.\n const by_version = new Map<number, string>();\n for (const { version, name } of list) {\n const clash = by_version.get(version);\n if (clash)\n throw new Error(\n `duplicate event version: ${clash} and ${name} both map to version ${version} — ` +\n \"leading zeros in a `_v<n>` suffix are not allowed; use a single canonical spelling\"\n );\n by_version.set(version, name);\n }\n list.sort((a, b) => b.version - a.version); // descending\n // index 0 is current; the rest are deprecated\n for (let i = 1; i < list.length; i++) deprecated.add(list[i].name);\n }\n return deprecated;\n}\n\n/**\n * Given a deprecated event name and the full set of event names in its\n * registry, returns the current (highest-version) sibling. Used to build\n * actionable error messages — \"use `Foo_v3` instead.\"\n *\n * Returns `undefined` if the event has no higher-versioned sibling (which\n * means the caller's classification is stale or wrong).\n */\nexport function current_version_of(\n deprecated_name: string,\n all_names: Iterable<string>\n): string | undefined {\n const target = parse(deprecated_name);\n let highest: Versioned | undefined;\n for (const name of all_names) {\n const { base, version } = parse(name);\n if (base !== target.base) continue;\n if (!highest || version > highest.version) highest = { version, name };\n }\n return highest && highest.version > target.version ? highest.name : undefined;\n}\n","import type { QueryStreams, Store, StreamPosition } from \"../types/index.js\";\n\n/** Streams read per page when walking the whole table. */\nconst DEFAULT_STREAM_PAGE = 500;\n\n/**\n * Walks EVERY stream matching `query`, paging with the keyset cursor.\n *\n * `Store.query_streams` defaults to `limit: 100`, so a caller that wants\n * the whole table must page — passing no query silently truncates at the\n * first page, which is a false all-clear for anything that reports on\n * what it found.\n *\n * The cursor is the last stream name the callback saw; results are\n * ordered by stream name, so a short page means the walk is done.\n *\n * @param store - Store to walk.\n * @param callback - Invoked once per matching position, in name order.\n * @param query - Optional filter. A caller-supplied `limit` sets the page\n * size (the walk still visits every match); `after` seeds the cursor.\n * @returns The total number of positions emitted.\n */\nexport async function walk_streams(\n store: Store,\n callback: (position: StreamPosition) => void,\n query?: Omit<QueryStreams, \"after\" | \"limit\"> & {\n after?: string;\n limit?: number;\n }\n): Promise<number> {\n const page_size = query?.limit ?? DEFAULT_STREAM_PAGE;\n let after = query?.after;\n let total = 0;\n for (;;) {\n let last: string | undefined;\n const { count } = await store.query_streams(\n (position) => {\n last = position.stream;\n callback(position);\n },\n { ...query, after, limit: page_size }\n );\n total += count;\n if (count < page_size) return total;\n after = last;\n }\n}\n","/**\n * Operator-driven store audit. Each category is an {@link AuditPass}; the\n * dispatcher runs each needed scan once and broadcasts rows to every pass,\n * so an audit costs at most three scans. Reads only {@link AuditDeps} and\n * the public `Store`, never orchestration internals.\n */\n\nimport { sensitiveFields } from \"../sensitive.js\";\nimport type {\n AuditCategory,\n AuditFinding,\n AuditOptions,\n Committed,\n Query,\n Schemas,\n State,\n Store,\n StreamPosition,\n StreamStats,\n} from \"../types/index.js\";\nimport { SNAP_EVENT, TOMBSTONE_EVENT } from \"../types/index.js\";\nimport {\n current_version_of,\n deprecated_event_names,\n} from \"./event-versions.js\";\nimport { walk_streams } from \"./walk-streams.js\";\n\n/** The orchestrator state the audit reads, built once at `build()`. */\nexport type AuditDeps = {\n readonly store: () => Store;\n /** event-name → state that registers it (for schema validation). */\n readonly event_to_state: ReadonlyMap<string, State<any, any, any>>;\n /** Declared drain lanes (for routing-health unknown-lane). */\n readonly declared_lanes: ReadonlySet<string>;\n /** Event names with at least one reaction (routing-health `unrouted`). */\n readonly routed_events: ReadonlySet<string>;\n};\n\n/** Defaults for {@link AuditOptions.thresholds}. */\nconst DEFAULTS = {\n idle_days: 90,\n restart_min: 10_000,\n stuck_minutes: 30,\n deprecated_min: 0.1,\n drift_min: 500,\n near_block: 3,\n};\n\nconst ALL_CATEGORIES = [\n \"schema\",\n \"close-candidate\",\n \"restart-candidate\",\n \"deprecated-load\",\n \"reaction-health\",\n \"snapshot-drift\",\n \"routing-health\",\n \"correlation-gaps\",\n \"clock-anomalies\",\n \"unreadable-events\",\n] as const satisfies readonly AuditCategory[];\n\n/**\n * One audit category. Which `on_*` callbacks it has decides which shared\n * scans run; `finalize` does targeted follow-up reads; `drain` returns\n * the findings.\n */\ntype AuditPass = {\n category: AuditCategory;\n on_event?: (e: Committed<Schemas, string>) => void;\n on_unreadable?: (row: UnreadableRow) => void;\n on_stream?: (p: StreamPosition) => void;\n on_stat?: (stream: string, s: StreamStats<Schemas>) => void;\n finalize?: (deps: AuditDeps) => Promise<void>;\n drain: () => AuditFinding[];\n};\n\ntype PassFactory = (deps: AuditDeps, options: AuditOptions) => AuditPass;\n\n/** Scans finish before the first yield; bound the work with `options.query`. */\nexport async function* audit(\n deps: AuditDeps,\n categories?: AuditCategory[],\n options: AuditOptions = {}\n): AsyncIterable<AuditFinding> {\n const requested = new Set<AuditCategory>(categories ?? [...ALL_CATEGORIES]);\n // Declaration order, not the caller's.\n const ordered_categories = ALL_CATEGORIES.filter((c) => requested.has(c));\n const passes: AuditPass[] = ordered_categories.map((c) =>\n PASS_FACTORIES[c](deps, options)\n );\n\n const need_stats = passes.some((p) => p.on_stat !== undefined);\n const need_streams = passes.some((p) => p.on_stream !== undefined);\n const need_events = passes.some(\n (p) => p.on_event !== undefined || p.on_unreadable !== undefined\n );\n\n if (need_stats) {\n // Exclude `__snapshot__` so head and count are domain figures; keep\n // `__tombstone__`, which is how a closed stream is recognized.\n const stats = await deps\n .store()\n .query_stats<Schemas>(\n {},\n { count: true, names: true, exclude: [SNAP_EVENT] }\n );\n for (const [stream, s] of stats) {\n for (const p of passes) p.on_stat?.(stream, s);\n }\n }\n\n if (need_streams) {\n // Paged: `query_streams` defaults to 100 rows.\n await walk_streams(deps.store(), (pos) => {\n for (const p of passes) p.on_stream?.(pos);\n });\n }\n\n if (need_events) {\n await scan_events_resiliently(\n deps,\n options.query,\n (event) => {\n for (const p of passes) p.on_event?.(event);\n },\n (row) => {\n for (const p of passes) p.on_unreadable?.(row);\n }\n );\n }\n\n // Serial to avoid pool contention.\n for (const p of passes) await p.finalize?.(deps);\n\n for (const p of passes) {\n for (const f of p.drain()) yield f;\n }\n}\n\n/**\n * A row the store couldn't hand back, located by re-reading it without its\n * payload (`with_pii: false`), which can't fail.\n */\ntype UnreadableRow = {\n stream: string;\n event_id: number;\n error: unknown;\n};\n\n/**\n * Run the event scan so one unreadable row doesn't end it: locate the row\n * it stopped at, report it, and resume past it with the remaining `limit`.\n * Backward scans can't resume, so they rethrow.\n */\nasync function scan_events_resiliently(\n deps: AuditDeps,\n query: Query | undefined,\n on_event: (e: Committed<Schemas, string>) => void,\n on_unreadable: (row: UnreadableRow) => void\n): Promise<void> {\n let cursor = query?.after;\n let remaining = query?.limit;\n for (;;) {\n let seen = 0;\n try {\n await deps.store().query<Schemas>(\n (event) => {\n seen++;\n cursor = event.id;\n on_event(event);\n },\n {\n ...query,\n after: cursor,\n ...(remaining !== undefined && { limit: remaining }),\n }\n );\n return;\n } catch (error) {\n if (query?.backward) throw error;\n let row: UnreadableRow | undefined;\n await deps.store().query<Schemas>(\n (e) => {\n row = { stream: e.stream, event_id: e.id, error };\n },\n { ...query, after: cursor, limit: 1, with_pii: false }\n );\n // Not one unreadable row (a dropped connection, a timeout): rethrow.\n if (!row) throw error;\n on_unreadable(row);\n // The tripping row is never delivered, so `seen` is at most\n // `remaining - 1` and the resumed budget stays at 1 or more.\n if (remaining !== undefined) remaining -= seen;\n cursor = row.event_id;\n }\n }\n}\n\n// =================== Pass factories ===================\n\nconst make_schema_pass: PassFactory = (deps) => {\n const findings: AuditFinding[] = [];\n return {\n category: \"schema\",\n on_event(event) {\n const name = String(event.name);\n const state = deps.event_to_state.get(name);\n if (!state) {\n if (name.startsWith(\"__\")) return;\n findings.push({\n category: \"schema\",\n stream: event.stream,\n event_id: event.id,\n name,\n reason: \"unknown_event_name\",\n });\n return;\n }\n const schema = state.events[name];\n // `sensitive()` keys live in the pii sidecar, so omit them from the parse.\n const sensitive = sensitiveFields(schema);\n let parse_schema = schema;\n if (sensitive.length > 0) {\n const omitter = (\n schema as unknown as {\n omit?: (mask: Record<string, true>) => typeof schema;\n }\n ).omit;\n if (typeof omitter !== \"function\") {\n // A non-object schema with pii can't be masked; any parse is a false positive.\n return;\n }\n parse_schema = omitter.call(\n schema,\n Object.fromEntries(sensitive.map((f) => [f, true as const]))\n );\n }\n const parsed = parse_schema.safeParse(event.data);\n if (!parsed.success) {\n findings.push({\n category: \"schema\",\n stream: event.stream,\n event_id: event.id,\n name,\n reason: \"schema_validation_failed\",\n zod_error: parsed.error,\n });\n }\n },\n drain: () => findings,\n };\n};\n\n/** Deprecated event name → its current sibling, within one state only. */\nconst classify_deprecated_by_state = (\n deps: AuditDeps\n): ReadonlyMap<string, string> => {\n const names_by_state = new Map<State<any, any, any>, Set<string>>();\n for (const [name, state] of deps.event_to_state) {\n let set = names_by_state.get(state);\n if (!set) {\n set = new Set();\n names_by_state.set(state, set);\n }\n set.add(name);\n }\n const deprecated_to_current = new Map<string, string>();\n for (const names of names_by_state.values()) {\n for (const name of deprecated_event_names(names)) {\n deprecated_to_current.set(name, current_version_of(name, names)!);\n }\n }\n return deprecated_to_current;\n};\n\nconst make_deprecated_load_pass: PassFactory = (deps, options) => {\n const share_min =\n options.thresholds?.deprecated_min ?? DEFAULTS.deprecated_min;\n const totals = new Map<string, number>();\n const per_stream = new Map<string, Map<string, number>>();\n return {\n category: \"deprecated-load\",\n on_stat(stream, { names }) {\n for (const [name, count] of Object.entries(names!)) {\n totals.set(name, (totals.get(name) ?? 0) + count!);\n let m = per_stream.get(name);\n if (!m) {\n m = new Map();\n per_stream.set(name, m);\n }\n m.set(stream, count!);\n }\n },\n drain() {\n const findings: AuditFinding[] = [];\n const grand = [...totals.values()].reduce((s, n) => s + n, 0);\n if (grand === 0) return findings;\n const deprecated = classify_deprecated_by_state(deps);\n const sorted = [...deprecated.keys()]\n .map((name) => ({ name, count: totals.get(name) ?? 0 }))\n .sort((a, b) => b.count - a.count);\n for (const { name, count } of sorted) {\n if (count === 0) continue;\n if (count / grand < share_min) continue;\n const current_version = deprecated.get(name)!;\n const top_streams = [...per_stream.get(name)!.entries()]\n .map(([stream, c]) => ({ stream, count: c }))\n .sort((a, b) => b.count - a.count)\n .slice(0, 10);\n findings.push({\n category: \"deprecated-load\",\n name,\n current_version,\n total: count,\n top_streams,\n });\n }\n return findings;\n },\n };\n};\n\nconst make_close_candidate_pass: PassFactory = (deps, options) => {\n const idle_days = options.thresholds?.idle_days ?? DEFAULTS.idle_days;\n const terminal_events = new Set(options.thresholds?.terminal_events ?? []);\n const idle_cutoff = Date.now() - idle_days * 24 * 60 * 60 * 1000;\n const findings: AuditFinding[] = [];\n return {\n category: \"close-candidate\",\n on_stat(stream, { head }) {\n const head_name = String(head.name);\n if (head_name.startsWith(\"__\")) return; // already-closed or mid-truncate\n const head_time = head.created.getTime();\n const is_idle = head_time < idle_cutoff;\n const is_terminal = terminal_events.has(head_name);\n if (!is_idle && !is_terminal) return;\n findings.push({\n category: \"close-candidate\",\n stream,\n last_event_at: head.created.toISOString(),\n reason: is_terminal ? \"terminal\" : \"idle\",\n idle_days: is_idle\n ? Math.floor((Date.now() - head_time) / (24 * 60 * 60 * 1000))\n : undefined,\n restart_supported: restart_is_supported(deps, head_name),\n });\n },\n drain: () => findings,\n };\n};\n\nconst make_restart_candidate_pass: PassFactory = (deps, options) => {\n const threshold = options.thresholds?.restart_min ?? DEFAULTS.restart_min;\n // Snapshot counts are resolved in finalize: the shared stat scan excludes\n // `__snapshot__`, and only a handful of candidates need them.\n const candidates: Array<{ stream: string; count: number }> = [];\n const findings: AuditFinding[] = [];\n return {\n category: \"restart-candidate\",\n on_stat(stream, { head, count }) {\n if (count! < threshold) return;\n const head_name = String(head.name);\n if (head_name.startsWith(\"__\")) return;\n if (!restart_is_supported(deps, head_name)) return;\n candidates.push({ stream, count: count! });\n },\n async finalize(deps) {\n for (const { stream, count } of candidates) {\n let snaps = 0;\n await deps.store().query(\n () => {\n snaps++;\n },\n {\n stream,\n stream_exact: true,\n names: [SNAP_EVENT],\n with_snaps: true,\n // From the start: on its own, `with_snaps` resumes at the latest.\n after: -1,\n }\n );\n findings.push({\n category: \"restart-candidate\",\n stream,\n count,\n snaps,\n });\n }\n },\n drain: () => findings,\n };\n};\n\nconst make_reaction_health_pass: PassFactory = (_deps, options) => {\n const near_block = options.thresholds?.near_block ?? DEFAULTS.near_block;\n const stuck_minutes =\n options.thresholds?.stuck_minutes ?? DEFAULTS.stuck_minutes;\n const stuck_cutoff = Date.now() - stuck_minutes * 60 * 1000;\n const findings: AuditFinding[] = [];\n return {\n category: \"reaction-health\",\n on_stream(p) {\n if (p.blocked) {\n findings.push({\n category: \"reaction-health\",\n stream: p.stream,\n status: \"blocked\",\n retry: p.retry,\n reason: p.error || \"blocked without recorded error\",\n });\n return;\n }\n if (p.retry >= near_block) {\n findings.push({\n category: \"reaction-health\",\n stream: p.stream,\n status: \"near-block\",\n retry: p.retry,\n reason: `retry ${p.retry} ≥ near-block threshold ${near_block}`,\n });\n return;\n }\n if (\n p.leased_by &&\n p.leased_until &&\n p.leased_until.getTime() < stuck_cutoff\n ) {\n const minutes = Math.floor(\n (Date.now() - p.leased_until.getTime()) / (60 * 1000)\n );\n findings.push({\n category: \"reaction-health\",\n stream: p.stream,\n status: \"stuck-backoff\",\n retry: p.retry,\n reason: `lease expired ${minutes}m ago without release`,\n });\n }\n },\n drain: () => findings,\n };\n};\n\nconst make_snapshot_drift_pass: PassFactory = (deps, options) => {\n const drift_min = options.thresholds?.drift_min ?? DEFAULTS.drift_min;\n const candidates: Array<{\n stream: string;\n total: number;\n }> = [];\n const findings: AuditFinding[] = [];\n return {\n category: \"snapshot-drift\",\n on_stat(stream, { head, count }) {\n // Also rejects framework markers, which no user state declares.\n if (!restart_is_supported(deps, String(head.name))) return;\n if (count! < drift_min) return; // upper-bound short-circuit\n candidates.push({\n stream,\n total: count!,\n });\n },\n async finalize(deps) {\n for (const { stream, total } of candidates) {\n let events_since_snap = total;\n let snap_at: number | undefined;\n // The shared stat scan excludes `__snapshot__`, so look it up here.\n const collected: Array<{ id: number }> = [];\n await deps.store().query(\n (e) => {\n collected.push({ id: e.id });\n },\n {\n stream,\n stream_exact: true,\n names: [\"__snapshot__\"],\n backward: true,\n limit: 1,\n with_snaps: true,\n }\n );\n if (collected.length > 0) {\n snap_at = collected[0]!.id;\n let after = 0;\n await deps.store().query(\n () => {\n after++;\n },\n { stream, stream_exact: true, after: snap_at }\n );\n events_since_snap = after;\n }\n if (events_since_snap < drift_min) continue;\n findings.push({\n category: \"snapshot-drift\",\n stream,\n events_since_snap,\n snap_at,\n });\n }\n },\n drain: () => findings,\n };\n};\n\nconst make_routing_health_pass: PassFactory = (deps) => {\n const findings: AuditFinding[] = [];\n const seen_event_names = new Set<string>();\n return {\n category: \"routing-health\",\n on_stream(p) {\n if (!p.lane) return; // default lane — never an unknown-lane finding\n if (deps.declared_lanes.has(p.lane)) return;\n findings.push({\n category: \"routing-health\",\n stream: p.stream,\n reason: \"unknown-lane\",\n lane: p.lane,\n });\n },\n on_stat(_stream, { names }) {\n for (const name of Object.keys(names!)) {\n seen_event_names.add(name);\n }\n },\n finalize() {\n for (const name of seen_event_names) {\n if (name.startsWith(\"__\")) continue;\n if (deps.routed_events.has(name)) continue;\n findings.push({\n category: \"routing-health\",\n stream: \"*\",\n reason: \"unrouted\",\n });\n }\n return Promise.resolve();\n },\n drain: () => findings,\n };\n};\n\nconst make_correlation_gaps_pass: PassFactory = () => {\n const seen_ids = new Set<number>();\n const checks: Array<{ stream: string; id: number; parent_id: number }> = [];\n return {\n category: \"correlation-gaps\",\n on_event(e) {\n seen_ids.add(e.id);\n const causation = (e.meta as Record<string, unknown> | undefined)\n ?.causation as { event?: { id?: number } } | undefined;\n const parent_id = causation?.event?.id;\n // A close's seed names the guard it just deleted, which isn't a gap.\n if (parent_id !== undefined && e.name !== TOMBSTONE_EVENT) {\n checks.push({ stream: e.stream, id: e.id, parent_id });\n }\n },\n drain() {\n const findings: AuditFinding[] = [];\n for (const { stream, id, parent_id } of checks) {\n if (!seen_ids.has(parent_id)) {\n findings.push({\n category: \"correlation-gaps\",\n stream,\n event_id: id,\n reason: \"orphan-parent\",\n });\n }\n }\n return findings;\n },\n };\n};\n\nconst make_clock_anomalies_pass: PassFactory = () => {\n const findings: AuditFinding[] = [];\n const last_per_stream = new Map<string, number>();\n return {\n category: \"clock-anomalies\",\n on_event(e) {\n const created = e.created.getTime();\n if (created > Date.now()) {\n findings.push({\n category: \"clock-anomalies\",\n stream: e.stream,\n event_id: e.id,\n reason: \"future-created\",\n });\n }\n const prev = last_per_stream.get(e.stream);\n if (prev !== undefined && created < prev) {\n findings.push({\n category: \"clock-anomalies\",\n stream: e.stream,\n event_id: e.id,\n reason: \"out-of-order\",\n });\n }\n last_per_stream.set(e.stream, created);\n },\n drain: () => findings,\n };\n};\n\nfunction restart_is_supported(\n deps: AuditDeps,\n head_event_name: string\n): boolean {\n const state = deps.event_to_state.get(head_event_name);\n return state?.snap !== undefined;\n}\n\n/** Fed by the dispatcher with rows the event scan tripped on; never reaches `on_event`. */\nfunction make_unreadable_events_pass(): AuditPass {\n const findings: AuditFinding[] = [];\n return {\n category: \"unreadable-events\",\n on_unreadable({ stream, event_id, error }) {\n findings.push({\n category: \"unreadable-events\",\n stream,\n event_id,\n reason: \"pii_decrypt_failed\",\n error,\n });\n },\n drain: () => findings,\n };\n}\n\nconst PASS_FACTORIES: Record<AuditCategory, PassFactory> = {\n schema: make_schema_pass,\n \"deprecated-load\": make_deprecated_load_pass,\n \"close-candidate\": make_close_candidate_pass,\n \"restart-candidate\": make_restart_candidate_pass,\n \"reaction-health\": make_reaction_health_pass,\n \"snapshot-drift\": make_snapshot_drift_pass,\n \"routing-health\": make_routing_health_pass,\n \"correlation-gaps\": make_correlation_gaps_pass,\n \"clock-anomalies\": make_clock_anomalies_pass,\n \"unreadable-events\": make_unreadable_events_pass,\n};\n","/**\n * Orchestrator-level circuit breaker for store operations. The drain loop\n * polls `claim()` continuously; when the backing store goes down every poll\n * throws a {@link StoreError}, and without a breaker the orchestrator would\n * spin at the cycle cadence hammering a dead database and flooding the logs.\n *\n * The breaker collapses that into three states:\n *\n * - **closed** — normal operation; failures are counted.\n * - **open** — `failureThreshold` consecutive failures tripped it; attempts\n * are skipped for `cooldownMs` so the store gets room to recover.\n * - **half-open** — the cooldown elapsed; a single trial attempt is allowed.\n * Success closes the breaker; failure re-opens it and restarts the clock.\n *\n * Time is passed in (`now`) rather than read from the clock so the state\n * machine is deterministic under test.\n */\n\nimport type { CircuitState } from \"../types/index.js\";\nimport type { CircuitBreakerConfig } from \"./config.js\";\n\n/**\n * Side-effect hooks the orchestrator wires into the breaker so consumers\n * (drain / settle / autoclose) don't each thread their own callbacks.\n */\nexport type CircuitBreakerHooks = {\n /** Invoked on every {@link CircuitBreaker.failed} with the error and state. */\n readonly on_error?: (error: unknown, circuit: CircuitState) => void;\n /**\n * Invoked once, `cooldownMs` after the latest failure, open or not. The\n * orchestrator wires it to a settle, so recovery is automatic even on the\n * default lane, which has no periodic poller.\n */\n readonly on_retry?: () => void;\n};\n\nexport class CircuitBreaker {\n private _failures = 0;\n private _opened_at: number | undefined;\n private _wake: ReturnType<typeof setTimeout> | undefined;\n private readonly _threshold: number;\n private readonly _cooldown_ms: number;\n private readonly _hooks: CircuitBreakerHooks;\n\n constructor(config: CircuitBreakerConfig, hooks: CircuitBreakerHooks = {}) {\n this._threshold = config.failureThreshold;\n this._cooldown_ms = config.cooldownMs;\n this._hooks = hooks;\n }\n\n /**\n * True when the store has failed at least once since the last pass that\n * went all the way through. The breaker can still read \"closed\" here: it\n * only opens after several failures in a row, so this catches the first\n * one, which `state()` cannot.\n */\n get failing(): boolean {\n return this._failures > 0;\n }\n\n /** How long the store is left alone after a failure before a retry. */\n get cooldown_ms(): number {\n return this._cooldown_ms;\n }\n\n /** Current state given the wall-clock `now`. */\n state(now: number): CircuitState {\n if (this._opened_at === undefined) return \"closed\";\n return now - this._opened_at >= this._cooldown_ms ? \"half-open\" : \"open\";\n }\n\n /** A store op passed — reset to closed and cancel any pending retry. */\n passed(): void {\n this._failures = 0;\n this._opened_at = undefined;\n this._clear_wake();\n }\n\n /**\n * A store op failed. Opens the breaker when the consecutive-failure\n * threshold is reached, or immediately re-opens (restarting the cooldown)\n * if a half-open trial just failed. Returns the resulting state.\n *\n * Callers gate on the state directly — `state(now) === \"open\"` means skip.\n * Every failure (re)schedules the `on_retry` wake, so one failed pass on\n * an idle app retries without waiting for the breaker to open; always\n * surfaces the failure via `on_error`.\n */\n failed(now: number, error?: unknown): CircuitState {\n const circuit = this._advance(now);\n this._schedule_wake();\n this._hooks.on_error?.(error, circuit);\n return circuit;\n }\n\n /** Cancel the pending retry timer. Idempotent; call on shutdown. */\n stop(): void {\n this._clear_wake();\n }\n\n // Schedule the `on_retry` wake `cooldownMs` out so the breaker re-trials\n // the store on its own. No-op when no `on_retry` hook is wired (e.g. unit\n // tests of the pure state machine). The timer is `unref`'d so it never\n // keeps the process alive.\n private _schedule_wake(): void {\n if (!this._hooks.on_retry) return;\n this._clear_wake();\n this._wake = setTimeout(() => {\n this._wake = undefined;\n this._hooks.on_retry?.();\n }, this._cooldown_ms);\n this._wake.unref();\n }\n\n private _clear_wake(): void {\n if (this._wake) {\n clearTimeout(this._wake);\n this._wake = undefined;\n }\n }\n\n // Pure state transition for a failure — no side effects.\n private _advance(now: number): CircuitState {\n // Already tripped: this can only be reached from a half-open trial\n // (open skips attempts), so the trial failed — re-open and restart.\n if (this._opened_at !== undefined) {\n this._opened_at = now;\n return \"open\";\n }\n this._failures += 1;\n if (this._failures >= this._threshold) {\n this._opened_at = now;\n return \"open\";\n }\n return \"closed\";\n }\n}\n","/**\n * Build-time classification of the registry + state map. The Act constructor\n * needs three pre-computed inputs to wire its runtime subsystems:\n *\n * - `static_targets` — known-up-front reaction targets, subscribed once\n * at init (correlate marks them from then on)\n * - `event_to_state` — event-name → owning state, for `close({restart})`\n * seed loading in multi-state apps\n * - `event_to_lanes` — event-name → the lanes its reactions run on, for\n * selective arming; its keys are exactly the events\n * that have a reaction\n *\n * Pure function — single pass over events + states, fully testable without\n * instantiating Act.\n */\n\nimport type {\n Registry,\n Schema,\n SchemaRegister,\n Schemas,\n State,\n} from \"../types/index.js\";\nimport type { StaticTarget } from \"./correlate-cycle.js\";\n\n/**\n * Sentinel for \"any reaction on this event has a dynamic resolver, so\n * the lane is opaque until correlate runs the function — arm every\n * controller.\" A Symbol rather than a string literal so it can't\n * collide with a user-declared lane named `\"all\"`.\n */\nexport const ALL_LANES: unique symbol = Symbol(\"act/all-lanes\");\n\n/**\n * Per-event lane fan-in. For events whose every reaction\n * has a static resolver, the value is the union of those reactions'\n * declared lanes — `do()` arms only those controllers on commit. For\n * events with at least one dynamic resolver, the value is\n * {@link ALL_LANES}; `do()` falls back to arming every controller.\n */\nexport type EventLaneSet = ReadonlySet<string> | typeof ALL_LANES;\n\n/**\n * Classification result. Returned by {@link classify_registry}; consumed\n * piecewise by Act's constructor.\n */\nexport type Classification = {\n readonly static_targets: StaticTarget[];\n readonly event_to_state: ReadonlyMap<string, State<any, any, any>>;\n readonly event_to_lanes: ReadonlyMap<string, EventLaneSet>;\n};\n\nconst describe_source = (source: string | undefined) =>\n source === undefined ? \"no source (every stream)\" : `\"${source}\"`;\n\n/**\n * Walk the registry once to collect static reaction targets, the set of\n * reactive event names, the per-event lane fan-in, and the event-to-state\n * map. Static targets are deduplicated by (target, source) — two reactions\n * routing to the same projection produce one subscription.\n */\nexport function classify_registry<\n TSchemaReg extends SchemaRegister<TActions>,\n TEvents extends Schemas,\n TActions extends Schemas,\n>(\n registry: Registry<TSchemaReg, TEvents, TActions>,\n states: ReadonlyMap<string, State<Schema, any, any>>\n): Classification {\n const statics = new Map<string, StaticTarget>();\n // Per-target lane, checked across EVERY reaction to a target regardless of\n // source. A stream drains on exactly one lane, and `subscribe`\n // keys lane per-target, so lane must agree target-wide — the\n // `(target, source)` scoping of `statics` is too narrow to catch a\n // same-target/different-source lane disagreement.\n const target_lanes = new Map<string, string>();\n const event_to_lanes = new Map<string, EventLaneSet>();\n\n for (const [name, register] of Object.entries(registry.events)) {\n for (const reaction of register.reactions.values()) {\n if (typeof reaction.resolver === \"function\") {\n // Dynamic resolver — lane is opaque until runtime. Mark the\n // event as wildcard so `do()` falls back to arming every\n // controller for any commit of it.\n event_to_lanes.set(name, ALL_LANES);\n } else {\n const { target, source, priority = 0, lane } = reaction.resolver;\n const lane_name = lane ?? \"default\";\n const existing_lanes = event_to_lanes.get(name);\n if (existing_lanes !== ALL_LANES) {\n const set =\n (existing_lanes as Set<string> | undefined) ?? new Set<string>();\n set.add(lane_name);\n event_to_lanes.set(name, set);\n }\n // Lanes don't merge — any two reactions to the\n // same target must declare the same lane, regardless of source.\n // First reaction to a target records its lane; every later one must\n // match or it's a config error caught at build time. Both sides\n // compare the NORMALIZED name, so an omitted lane and an\n // explicit \"default\" — the same lane — agree.\n const recorded_lane = target_lanes.get(target);\n if (recorded_lane === undefined) {\n target_lanes.set(target, lane_name);\n } else if (recorded_lane !== lane_name) {\n throw new Error(\n `Stream \"${target}\" has conflicting lane assignments ` +\n `(\"${recorded_lane}\" vs \"${lane_name}\")`\n );\n }\n // Keyed by target alone, because a subscription row IS keyed by\n // stream: every adapter sets `source` once at creation and ignores\n // it thereafter, so a second source is refused, and a second reaction\n // on the same one contributes only its priority. One entry per\n // stream, max priority, so the highest-priority registrant sets the\n // scheduling priority.\n const existing = statics.get(target);\n if (existing && existing.source !== source)\n throw new Error(\n `Target \"${target}\" has reactions on two sources, ${describe_source(existing.source)} and ${describe_source(source)}. A target reads one source, so the second would miss events or read too many. Give it its own target.`\n );\n if (!existing) {\n statics.set(target, { stream: target, source, priority, lane });\n } else if (priority > (existing.priority as number)) {\n // `existing.priority` is always defined here since we always set\n // it when inserting, but the StaticTarget type marks it optional\n // for external consumers.\n statics.set(target, { ...existing, priority });\n }\n }\n }\n }\n\n // Event-name → owning state. Duplicate event names are rejected at\n // registration time (merge.ts), so each entry is unambiguous.\n const event_to_state = new Map<string, State<any, any, any>>();\n for (const merged of states.values()) {\n for (const event_name of Object.keys(merged.events)) {\n event_to_state.set(event_name, merged);\n }\n }\n\n return {\n static_targets: [...statics.values()],\n event_to_state,\n event_to_lanes,\n };\n}\n","/**\n * Compiles the declarative `.autocloses({...})` policy into a predicate.\n * Top-level `after` / `is` / `reaches` combine with AND; an `or: {...}`\n * block adds an alternative path. Validated with\n * {@link AutoclosePolicySchema} when the app builds, so a bad policy throws\n * then, not on the first cycle. Semantics and examples:\n * docs/docs/guides/close-policies.md.\n */\n\nimport { z } from \"zod\";\nimport type {\n AutoclosePolicy,\n AutoclosePredicate,\n Schemas,\n} from \"../types/action.js\";\n\n/**\n * One day in epoch milliseconds. The close surface is day-denominated\n * throughout — policies declare `{ days }`, the State carries\n * `autoclose_*_days`, and the reaction thinks in day offsets. This\n * constant (with {@link days_after} / {@link days_before_now}) is the\n * single place the closing process touches epoch arithmetic, because\n * `Date` itself has no other currency.\n */\nconst DAY_MS = 86_400_000;\n\n/**\n * Lower bound on a resolved `after` window: one minute, expressed in\n * days. Sub-minute cooldowns are almost always misconfiguration.\n * Rejecting at build keeps the failure mode noisy.\n */\nconst MIN_AFTER_DAYS = 1 / 1440;\n\n/**\n * Lower bound on a resolved `keep` window: one full day. The close\n * cycle is low-cadence, non-priority housekeeping — a rolling window\n * shorter than a day signals misconfiguration. Real retention\n * contracts (180 days, 7 years) are days and up.\n */\nconst MIN_KEEP_DAYS = 1;\n\n/** The `Date` that lies `days` after `date`. */\nexport function days_after(date: Date, days: number): Date {\n return new Date(date.getTime() + days * DAY_MS);\n}\n\n/** The `Date` that lies `days` in the past. */\nexport function days_before_now(days: number): Date {\n return new Date(Date.now() - days * DAY_MS);\n}\n\n/**\n * Day-denominated window shared by `after` (terminate cooldown) and\n * `keep` (rolling retention). Fractional days accepted; windows below\n * the field's floor reject at build.\n */\nconst window_schema = (\n field: \"after\" | \"keep\",\n min_days: number,\n floor: string\n) =>\n z\n .object({\n days: z\n .number({ message: `autocloses: ${field}.days must be a number` })\n .positive(`autocloses: ${field}.days must be > 0`),\n })\n .refine((o) => o.days >= min_days, {\n message: `autocloses: ${field} resolves to < ${floor}, which is too short to be a meaningful retention window`,\n });\n\nconst AfterSchema = window_schema(\"after\", MIN_AFTER_DAYS, \"one minute\");\n\nconst KeepSchema = window_schema(\"keep\", MIN_KEEP_DAYS, \"one day\");\n\nconst IsSchema = z.union([\n z.string().min(1, \"autocloses: is must be a non-empty event name\"),\n z\n .array(\n z.string().min(1, \"autocloses: is entries must be non-empty event names\")\n )\n .min(1, \"autocloses: is must include at least one event name\")\n .readonly(),\n]);\n\nconst ReachesSchema = z\n .number({ message: \"autocloses: reaches must be a number\" })\n .int(\"autocloses: reaches must be an integer\")\n .min(1, \"autocloses: reaches must be >= 1\");\n\n/**\n * Schema for the `or: {...}` block — the OR-shaped alternative path.\n * Same field set as the top-level policy minus `or` itself (so nested\n * `or` inside `or` rejects via `.strict()` instead of recursing). At\n * least one field required; empty `{}` is a misconfiguration.\n */\nconst OrBlockSchema = z\n .object({\n after: AfterSchema.optional(),\n is: IsSchema.optional(),\n reaches: ReachesSchema.optional(),\n })\n .strict()\n .refine(\n (o) =>\n o.after !== undefined || o.is !== undefined || o.reaches !== undefined,\n {\n message:\n \"autocloses: `or` block must include at least one of after / is / reaches\",\n }\n );\n\n/**\n * Zod schema for the declarative {@link AutoclosePolicy} bag.\n * Internal `const` per the config-validation standard\n * (`.claude/rules/config-validation.md`) — the public surface is the inferred\n * {@link AutoclosePolicy} type and the `.autocloses({...})` overload,\n * never this schema. `.strict()` rejects unknown keys so typos surface\n * at build instead of being silently ignored.\n */\nconst AutoclosePolicySchema = z\n .object({\n after: AfterSchema.optional(),\n is: IsSchema.optional(),\n reaches: ReachesSchema.optional(),\n or: OrBlockSchema.optional(),\n keep: KeepSchema.optional(),\n })\n .strict()\n .refine(\n (o) =>\n o.after !== undefined ||\n o.is !== undefined ||\n o.reaches !== undefined ||\n o.or !== undefined ||\n o.keep !== undefined,\n {\n message:\n \"autocloses: at least one of after / is / reaches / or / keep must be specified — empty `{}` is a misconfiguration\",\n }\n ) satisfies z.ZodType<AutoclosePolicy>;\n\n/** Compile a single `after` field into its predicate slice. */\nfunction compile_after(\n after: NonNullable<AutoclosePolicy[\"after\"]>\n): AutoclosePredicate<Schemas> {\n return (_stream, head) => days_after(head.created, after.days) <= new Date();\n}\n\n/** Compile a single `is` field into its predicate slice. */\nfunction compile_is(\n is: NonNullable<AutoclosePolicy[\"is\"]>\n): AutoclosePredicate<Schemas> {\n const set = new Set(typeof is === \"string\" ? [is] : is);\n return (_stream, head) => set.has(head.name as string);\n}\n\n/** Compile a single `reaches` field into its predicate slice. */\nfunction compile_reaches(\n reaches: NonNullable<AutoclosePolicy[\"reaches\"]>\n): AutoclosePredicate<Schemas> {\n return (_stream, _head, count) => count >= reaches;\n}\n\n/**\n * Every `after` window (in days) in a policy. The reaction parks on the\n * earliest one still ahead, so a branch with a later window keeps its turn once\n * an earlier one has passed.\n */\nexport function policy_after_windows(options: AutoclosePolicy): number[] {\n const parsed = AutoclosePolicySchema.parse(options);\n return [parsed.after, parsed.or?.after].flatMap((w) => (w ? [w.days] : []));\n}\n\n/**\n * The rolling-window width (in days) of a policy's `keep` field, or\n * `undefined` when the policy declares no rolling window. The\n * synthesized autoclose reaction prunes the prefix older than the\n * window (via a windowed close) and derives its prune due-time as\n * `tail.created` plus this many days — the earliest the oldest\n * surviving domain event can age out of the window.\n */\nexport function policy_keep_days(options: AutoclosePolicy): number | undefined {\n const parsed = AutoclosePolicySchema.parse(options);\n return parsed.keep?.days;\n}\n\n/**\n * Compile a declarative {@link AutoclosePolicy} into an\n * {@link AutoclosePredicate}. The state-builder's\n * `.autocloses({...})` overload calls this; tests can also build a\n * state and read `state.autoclose` to grab the compiled predicate.\n *\n * Returned predicate fires when either:\n *\n * 1. **All** top-level non-`or` fields match (AND), or\n * 2. **Any** field inside the `or` block matches.\n *\n * Top-level with zero non-`or` fields never satisfies path (1) — the\n * `every` check on an empty list is short-circuited to `false` so the\n * policy doesn't truncate the entire universe on an `or`-only\n * declaration. (Validation rejects all-empty bags up front; this guard\n * is the in-cycle equivalent for the synthesized empty AND-group.)\n *\n * Assignable to any `AutoclosePredicate<TEvents>` slot via\n * function-parameter contravariance — the returned predicate inspects\n * `head.name` as a plain string, so narrower event unions stay\n * assignable.\n *\n * Throws `ZodError` at call time when the options are invalid (empty\n * bag, non-positive `reaches`, sub-minute `after`, empty `is`, empty\n * `or`, nested `or`, unknown keys).\n */\nexport function compile_autoclose_policy(\n options: AutoclosePolicy\n): AutoclosePredicate<Schemas> {\n const parsed = AutoclosePolicySchema.parse(options);\n\n // Top-level AND group — only the non-`or` fields.\n const and_preds: AutoclosePredicate<Schemas>[] = [];\n if (parsed.after) and_preds.push(compile_after(parsed.after));\n if (parsed.is) and_preds.push(compile_is(parsed.is));\n if (parsed.reaches) and_preds.push(compile_reaches(parsed.reaches));\n\n // OR-block — at least one of its fields must match.\n const or_preds: AutoclosePredicate<Schemas>[] = [];\n if (parsed.or) {\n if (parsed.or.after) or_preds.push(compile_after(parsed.or.after));\n if (parsed.or.is) or_preds.push(compile_is(parsed.or.is));\n if (parsed.or.reaches) or_preds.push(compile_reaches(parsed.or.reaches));\n }\n\n return (stream, head, count) => {\n // AND path: every top-level field matches AND the group is non-empty\n // (an `or`-only declaration leaves `and_preds` empty — that\n // shouldn't auto-fire).\n if (\n and_preds.length > 0 &&\n and_preds.every((p) => p(stream, head, count))\n ) {\n return true;\n }\n // OR path: any `or`-block field matches.\n if (or_preds.some((p) => p(stream, head, count))) {\n return true;\n }\n return false;\n };\n}\n","/**\n * Off-hours window math for autoclose — hour-in-zone, DST-gap handling, and\n * \"next time the window opens\".\n */\n\nimport type { AutocloseConfig } from \"../types/index.js\";\n\n/**\n * The current hour `[0, 23]` in the given IANA time zone, DST-correct\n * via `Intl`. Split out so the window check can be unit-tested without\n * spinning a controller.\n */\nexport function hour_in_zone(now: Date, timeZone: string): number {\n const parts = new Intl.DateTimeFormat(\"en-US\", {\n timeZone,\n hour: \"2-digit\",\n hourCycle: \"h23\",\n }).formatToParts(now);\n return Number(parts.find((p) => p.type === \"hour\")?.value);\n}\n\n/**\n * True when a plain `[start, end)` hour comparison places `hour` inside\n * the window. Half-open on hour boundaries and wrapping past midnight\n * when `start > end`.\n */\nfunction hour_in_range(hour: number, start: number, end: number): boolean {\n return start < end\n ? hour >= start && hour < end\n : hour >= start || hour < end;\n}\n\n/**\n * True when `now` is the instant a DST spring-forward gap skipped over\n * the window's `start` hour. On such a day the local `start` hour never\n * occurs — the clock jumps from `start - 1` straight past `start` — so a\n * plain hour comparison would report the window closed all day. The gap\n * surfaces as a one-hour boundary where the local hour jumps from below\n * `start` to above it; that boundary instant is the window's replacement\n * opening. Detected by comparing the hour at `now` with the hour one\n * hour earlier: a jump of more than one hour that steps over `start`.\n */\nfunction is_dst_gap_open(now: Date, timeZone: string, start: number): boolean {\n const hour = hour_in_zone(now, timeZone);\n if (hour <= start) return false;\n const prev = hour_in_zone(new Date(now.getTime() - 3_600_000), timeZone);\n // A normal step advances one local hour; a spring-forward gap advances\n // two, skipping exactly one local hour. This instant is the gap opening\n // only when the skipped hour is the window's `start`: the previous hour\n // sits just below `start` and this hour just above it.\n return prev === start - 1 && hour === start + 1;\n}\n\n/**\n * Whether `now` falls inside the configured off-hours window. The\n * window is half-open on hour boundaries — `[start, end)` — and wraps\n * past midnight when `start > end`. With no window configured every\n * tick runs, so callers treat `undefined` as \"always in window.\"\n *\n * On a DST spring-forward day whose `start` hour is skipped, the window\n * would otherwise be closed for the whole day (the `start` hour never\n * occurs). The gap's replacement instant is admitted so autoclose still\n * runs — see {@link is_dst_gap_open}.\n */\nexport function in_autoclose_window(\n window: AutocloseConfig[\"autocloseWindow\"],\n now: Date\n): boolean {\n if (!window) return true;\n const hour = hour_in_zone(now, window.timeZone);\n return (\n hour_in_range(hour, window.start, window.end) ||\n is_dst_gap_open(now, window.timeZone, window.start)\n );\n}\n\n/**\n * The next instant the off-hours window opens at or after `now`. The\n * synthesized autoclose reaction defers to this when a tick lands\n * outside the window — parking until the window actually opens instead\n * of blind-polling on a configured cadence (the old behavior,\n * where a poll interval longer than the window could oscillate around\n * it and miss it repeatedly).\n *\n * Walks forward hour by hour and asks `Intl` for the local hour at each\n * step, so DST transitions resolve exactly the way the runtime's zone\n * database says they do — a 23- or 25-hour day never desynchronizes the\n * walk. The window validates as non-empty at build, and every zone hits\n * each `[0, 23]` hour label within any 48-hour span, so the walk always\n * terminates; the bound is a defensive backstop, with \"one day out\" as\n * the fallback no real zone can reach.\n *\n * Minute/second offsets within the opening hour are preserved from\n * `now` shifted by whole hours — the contract is hour-granular, matching\n * the window's own `[start, end)` hour semantics.\n *\n * On a DST spring-forward day whose `start` hour is skipped, the `start`\n * hour never occurs, so the minute-preserving walk would never match and\n * the window would defer ~24 h. The walk also checks each hour-aligned\n * boundary for the gap opening (see {@link is_dst_gap_open}) and returns\n * that boundary instant — deferring ~1 h to the replacement instant\n * rather than a full day. The boundary is returned as-is (no minute\n * offset): the gap opening is a single transition instant, not a range.\n */\nexport function next_window_open(\n window: NonNullable<AutocloseConfig[\"autocloseWindow\"]>,\n now: Date\n): Date {\n const start_ms = now.getTime();\n for (let h = 0; h <= 48; h++) {\n const candidate = new Date(start_ms + h * 3_600_000);\n if (hour_in_zone(candidate, window.timeZone) === window.start)\n return candidate;\n // The `start` hour may be unreachable on a spring-forward day; catch\n // the gap boundary at the top of this candidate's hour. The boundary is\n // UTC-hour aligned, so in a fractional-offset zone the first one can sit\n // behind `now` — a past due is never excluded by claim, so skip it.\n const boundary = new Date(\n candidate.getTime() - (candidate.getTime() % 3_600_000)\n );\n if (\n boundary.getTime() >= start_ms &&\n is_dst_gap_open(boundary, window.timeZone, window.start)\n )\n return boundary;\n }\n return new Date(start_ms + 86_400_000);\n}\n","/**\n * The `when` options for the public `defer` surface. A\n * reaction defers itself to a future time either declaratively (the\n * `.defer(when)` builder step) or imperatively (`throw new DeferSignal(when)`\n * inside a handler); both resolve `when` through here.\n *\n * The load-bearing rule is **derivability**. A deferred stream's due-time must\n * be recomputable by whichever worker re-claims it after the wait, so `when`\n * never resolves against `Date.now()`. `after` is measured from the triggering\n * event's `created` timestamp, and `at` is either a fixed `Date` or a pure\n * function of the event. Either way, re-delivering the same event yields the\n * same due-time, which is what makes a defer correct across restarts and\n * competing workers.\n *\n * Validation follows the config-schema standard\n * (`.claude/rules/config-validation.md`): an internal `*OptionsSchema`\n * const, a public inferred type, and a resolver.\n */\n\nimport { z } from \"zod\";\nimport { DeferSignal } from \"../types/errors.js\";\nimport type { Committed, DeferWhen, Schemas } from \"../types/index.js\";\n\n/**\n * A relative span, measured from the triggering event's `created` time. At\n * least one field is required; fields are additive (`{ hours: 1, minutes: 30 }`\n * is 90 minutes).\n */\nconst DeferDurationSchema = z\n .object({\n days: z.number().positive().optional(),\n hours: z.number().positive().optional(),\n minutes: z.number().positive().optional(),\n })\n .strict()\n .refine((d) => d.days != null || d.hours != null || d.minutes != null, {\n message: \"defer: a duration needs at least one of days, hours, or minutes\",\n });\n\n/**\n * Zod schema for the `defer(when)` options bag. Exactly one of `after` / `at`;\n * `at` is an absolute `Date`. Internal per the config standard; the public\n * surface is {@link DeferWhen} and {@link resolve_defer_at}.\n */\nconst DeferWhenSchema = z\n .object({\n after: DeferDurationSchema.optional(),\n at: z.date().optional(),\n })\n .strict()\n .refine((w) => (w.after === undefined) !== (w.at === undefined), {\n message: \"defer: specify exactly one of `after` or `at`\",\n });\n\n/** Sum a duration bag to milliseconds. */\nfunction duration_ms(d: {\n days?: number;\n hours?: number;\n minutes?: number;\n}): number {\n return (\n (d.days ?? 0) * 86_400_000 +\n (d.hours ?? 0) * 3_600_000 +\n (d.minutes ?? 0) * 60_000\n );\n}\n\n/**\n * Resolve `when` to an absolute due-time (ms since epoch) for a given\n * triggering event. Validates via {@link DeferWhenSchema} (throws `ZodError`\n * on a bad shape), then derives the time: `after` from `event.created`, `at`\n * from its absolute `Date`. Never reads `Date.now()`, so the result is stable\n * across re-delivery.\n */\nexport function resolve_defer_at<E extends Schemas>(\n when: DeferWhen,\n event: Committed<E, keyof E>\n): number {\n const parsed = DeferWhenSchema.parse(when);\n if (parsed.after) return event.created.getTime() + duration_ms(parsed.after);\n return parsed.at!.getTime();\n}\n\n/**\n * The schedule handed to the declarative `.defer` builder step: either a\n * literal {@link DeferWhen} (fixed cooldown/deadline) or a function of the\n * triggering event (read the payload to choose the schedule).\n */\nexport type DeferSchedule<TEvent> = DeferWhen | ((event: TEvent) => DeferWhen);\n\n/**\n * Validate a literal `when` at build time (fail fast, per the config-schema\n * standard) — throws `ZodError` on a bad shape (both/neither of `after`/`at`,\n * an empty or non-positive duration). The function form of a `.defer` schedule\n * can only be checked when it runs, so builders pass just the literal here.\n */\nexport function assert_defer_when(when: DeferWhen): void {\n DeferWhenSchema.parse(when);\n}\n\n/**\n * Wrap a reaction handler so it holds until its schedule is due, then runs.\n * On each delivery it resolves the schedule against the triggering event; if\n * the due-time hasn't arrived it throws {@link DeferSignal} (the drain holds\n * the stream, no watermark advance, no retry bump), otherwise it runs the\n * real handler. The wrapper keeps the original handler's `name` so reaction\n * registration and de-dup are unaffected, and preserves the handler's exact\n * type so the builder step is transparent.\n */\nexport function make_deferred<H extends (...args: any[]) => Promise<unknown>>(\n handler: H,\n schedule: DeferSchedule<Parameters<H>[0]>\n): H {\n const call = handler as (...args: unknown[]) => Promise<unknown>;\n const deferred = async (\n event: Parameters<H>[0],\n stream: string,\n app: unknown\n ) => {\n const when = typeof schedule === \"function\" ? schedule(event) : schedule;\n if (Date.now() < resolve_defer_at(when, event)) throw new DeferSignal(when);\n return call(event, stream, app);\n };\n Object.defineProperty(deferred, \"name\", { value: handler.name });\n return deferred as unknown as H;\n}\n","/**\n * The drain pipeline: {@link run_drain_cycle} is one stateless\n * claim → fetch → dispatch → ack/block round-trip; {@link DrainController}\n * owns the armed flag, the lock, the lag/lead ratio and the defer wake.\n */\n\nimport { randomUUID } from \"node:crypto\";\nimport { log } from \"../ports.js\";\nimport { NonRetryableError } from \"../types/errors.js\";\nimport type {\n BatchHandler,\n BlockedLease,\n CloseTarget,\n Drain,\n DrainOptions,\n Fetch,\n Lease,\n Logger,\n ReactionOptions,\n ReactionPayload,\n Registry,\n Resolved,\n SchemaRegister,\n Schemas,\n} from \"../types/index.js\";\nimport { compute_backoff_delay } from \"./backoff.js\";\nimport type { CircuitBreaker } from \"./circuit-breaker.js\";\nimport {\n DEFAULT_BACKOFF,\n DEFAULT_EVENT_LIMIT,\n DEFAULT_LEASE_MILLIS,\n DEFAULT_STREAM_LIMIT,\n} from \"./config.js\";\nimport { DeferTimer } from \"./defer-timer.js\";\nimport type { DrainOps } from \"./drain-ops.js\";\nimport { compute_lag_lead_ratio } from \"./drain-ratio.js\";\nimport { report_once } from \"./report-once.js\";\nimport { trace_cycle } from \"./tracing.js\";\n\n/** Outcome of handling one leased stream; drives its ack/block. */\nexport type HandleResult = Readonly<{\n lease: Lease;\n handled: number;\n /** Last successful event id, or `lease.at` when there was no work. */\n acked_at: number;\n error?: string;\n block?: boolean;\n /** Epoch ms of the next retry, from the backoff. Only set on a retry. */\n next_attempt_at?: number;\n /** Epoch ms to redeliver a deferred stream; no error, no retry bump. */\n defer?: number;\n /** From a `CloseSignal`; acked first so the close guard sees it caught up. */\n close?: CloseTarget;\n /** Event id that threw (sparse ids make it differ from `acked_at + 1`); never in batch mode. */\n failed_at?: number;\n}>;\n\n/** `Act.handle`. */\nexport type Handle<TEvents extends Schemas> = (\n lease: Lease,\n payloads: ReactionPayload<TEvents>[]\n) => Promise<HandleResult>;\n\n/** `Act.handle_batch`. */\nexport type HandleBatch<TEvents extends Schemas> = (\n lease: Lease,\n payloads: ReactionPayload<TEvents>[],\n batchHandler: BatchHandler<TEvents>\n) => Promise<HandleResult>;\n\ntype DrainCycle<TEvents extends Schemas> = {\n readonly leased: Lease[];\n readonly fetched: Fetch<TEvents>;\n readonly handled: HandleResult[];\n readonly acked: Lease[];\n readonly blocked: BlockedLease[];\n readonly closeable: CloseTarget[];\n};\n\n/**\n * Blocks a stream whose retries were all spent losing the lease (no handler\n * error ever reached the block decision). Strictly `> maxRetries`: the final\n * attempt runs at `=== maxRetries`. Stands down while the store is failing,\n * since `claim` counts retries no handler earned.\n */\nfunction budget_exhausted<TEvents extends Schemas>(\n lease: Lease,\n options: ReactionPayload<TEvents>[\"options\"] | undefined,\n store_failing: boolean\n): HandleResult | undefined {\n if (\n store_failing ||\n !options?.blockOnError ||\n lease.retry <= options.maxRetries\n )\n return undefined;\n const error = `Blocking ${lease.stream} after ${lease.retry} claims with no acknowledged progress — the retry budget (${options.maxRetries}) was spent without the handler ever reporting an error. That means every attempt lost its lease before it could ack: move the reaction to a lane whose leaseMillis covers the handler, then unblock the stream.`;\n log().error(error);\n return { lease, handled: 0, acked_at: lease.at, error, block: true };\n}\n\n/**\n * A failed fetch has no payloads to say which reaction it was for, so take\n * the most conservative policy: block only if every reaction does, after\n * the largest budget.\n */\nfunction fetch_failure_policy<\n TSchemaReg extends SchemaRegister<TActions>,\n TEvents extends Schemas,\n TActions extends Schemas,\n>(registry: Registry<TSchemaReg, TEvents, TActions>): ReactionOptions {\n let blockOnError = true;\n let maxRetries = 0;\n for (const register of Object.values(registry.events))\n for (const reaction of register.reactions.values()) {\n blockOnError &&= reaction.options.blockOnError;\n maxRetries = Math.max(maxRetries, reaction.options.maxRetries);\n }\n return { blockOnError, maxRetries };\n}\n\n/** A resolver's error, and the options of the reaction it belongs to. */\ntype ResolverFailure = { error: Error; options: ReactionOptions };\n\n/**\n * The one retry-or-block decision for a stream that failed: a handler,\n * a resolver, or the stream's own fetch. The error string always rides\n * the result; the drain decides whether to ack partial progress from\n * `handled > 0`, not from the error.\n */\nexport function finalize(\n lease: Lease,\n handled: number,\n at: number,\n error: Error | undefined,\n options: ReactionOptions,\n logger: Logger,\n failed_at?: number\n): HandleResult {\n if (!error) return { lease, handled, acked_at: at };\n logger.error(error);\n // A `NonRetryableError` from the handler short-circuits the retry\n // budget — block on first attempt when the operator has opted in via\n // `blockOnError`. When `blockOnError` is false, the operator has\n // explicitly chosen \"retry forever,\" so we don't override that.\n const non_retryable = error instanceof NonRetryableError;\n const block =\n options.blockOnError &&\n (non_retryable || lease.retry >= options.maxRetries);\n if (block)\n logger.error(\n non_retryable\n ? `Blocking ${lease.stream} on non-retryable error.`\n : `Blocking ${lease.stream} after ${lease.retry} retries.`\n );\n // Every retry is paced by the reaction's backoff, or the default one;\n // terminal blocks never defer. `lease.retry` here is the just-failed\n // attempt's counter, so the delay paces the *next* attempt.\n const next_attempt_at = block\n ? undefined\n : Date.now() +\n compute_backoff_delay(lease.retry, options.backoff ?? DEFAULT_BACKOFF);\n return {\n lease,\n handled,\n acked_at: at,\n error: error.message,\n block,\n next_attempt_at,\n failed_at,\n };\n}\n\n/** Reported once per declaration; every key part is declared, so it stays bounded. */\nfunction warn_misrouted(\n seen: Set<string>,\n stream: string,\n handler: string,\n event: string\n): void {\n report_once(\n seen,\n `${stream}|${handler}|${event}`,\n `Reaction \"${handler}\" on \"${event}\" resolved to target \"${stream}\", which a projection already serves. ` +\n \"A target is served by one batch handler or one state projection, so this reaction can never run — and delivering to it would hand the projection an aggregate from another stream. \" +\n \"Skipping it. The equivalent static `.to({ target })` is rejected at build; a dynamic resolver's target is only knowable here.\"\n );\n}\n\ntype CycleInput = {\n readonly lagging: number;\n readonly leading: number;\n readonly eventLimit: number;\n readonly leaseMillis: number;\n readonly misrouted: Set<string>;\n readonly store_failing: boolean;\n};\n\n/** One drain cycle; `undefined` when nothing was claimed. */\nasync function run_drain_cycle<\n TEvents extends Schemas,\n TActions extends Schemas,\n TSchemaReg extends SchemaRegister<TActions>,\n>(\n deps: DrainControllerDeps<TEvents, TActions, TSchemaReg>,\n cycle: CycleInput\n): Promise<DrainCycle<TEvents> | undefined> {\n const { ops, registry, batch_handlers, handle, handle_batch, lane } = deps;\n const {\n lagging,\n leading,\n eventLimit,\n leaseMillis,\n misrouted,\n store_failing,\n } = cycle;\n const leased = await ops.claim(\n lagging,\n leading,\n randomUUID(),\n leaseMillis,\n lane\n );\n if (!leased.length) return undefined;\n\n const fetched = await ops.fetch(leased, eventLimit);\n\n type FetchEntry = (typeof fetched)[number];\n const fetch_map = new Map<\n string,\n {\n fetch: FetchEntry;\n payloads: ReactionPayload<TEvents>[];\n failed?: ResolverFailure;\n }\n >();\n\n const fetch_window_at = fetched.reduce(\n (max, { at, events }) => Math.max(max, events.at(-1)?.id || at),\n 0\n );\n\n for (const f of fetched) {\n const { stream, events } = f;\n let failed: ResolverFailure | undefined;\n const payloads = events.flatMap((event) => {\n const register = registry.events[event.name];\n if (!register) return [];\n return [...register.reactions.values()]\n .filter((reaction) => {\n const resolver = reaction.resolver;\n const dynamic = typeof resolver === \"function\";\n let resolved: Resolved | undefined;\n try {\n resolved = dynamic ? resolver(event) : resolver;\n } catch (error) {\n failed ??= {\n error: new Error(\n `Resolver of reaction \"${reaction.handler.name}\" threw on ${String(event.name)} #${event.id} (stream \"${event.stream}\"): ${String(error)}`\n ),\n options: reaction.options,\n };\n return false;\n }\n if (!resolved || resolved.target !== stream) return false;\n // A dynamic resolution onto a projection's target: skip and report.\n // Not a throw, which would read as a store failure.\n if (!dynamic || !batch_handlers.has(stream)) return true;\n warn_misrouted(\n misrouted,\n stream,\n reaction.handler.name,\n String(event.name)\n );\n return false;\n })\n .map((reaction) => ({ ...reaction, event }));\n });\n fetch_map.set(stream, { fetch: f, payloads, failed });\n }\n\n const handled = await Promise.all(\n leased.map((lease) => {\n const entry = fetch_map.get(lease.stream)!;\n // Retried after the default backoff; blocks once the budget is spent,\n // unless the whole store is failing (the breaker's job).\n if (entry.fetch.error !== undefined) {\n const policy = fetch_failure_policy(registry);\n return Promise.resolve(\n finalize(\n lease,\n 0,\n lease.at,\n new Error(`Fetch failed for ${lease.stream}: ${entry.fetch.error}`),\n store_failing ? { ...policy, blockOnError: false } : policy,\n deps.logger\n )\n );\n }\n // A resolver threw: this stream fails like a handler would.\n if (entry.failed)\n return Promise.resolve(\n finalize(\n lease,\n 0,\n lease.at,\n entry.failed.error,\n entry.failed.options,\n deps.logger\n )\n );\n // fast-forward watermark using fetched events or window max\n const at = entry.fetch.events.at(-1)?.id || fetch_window_at;\n const { payloads } = entry;\n const exhausted = budget_exhausted(\n lease,\n payloads[0]?.options,\n store_failing\n );\n if (exhausted) return Promise.resolve(exhausted);\n const batchHandler = batch_handlers.get(lease.stream);\n if (batchHandler && payloads.length > 0) {\n return handle_batch({ ...lease, at }, payloads, batchHandler);\n }\n return handle({ ...lease, at }, payloads);\n })\n );\n\n // `block` before `ack`: block needs the lease, ack releases it. A\n // partial-progress block goes to both. Deferred and backing-off entries\n // carry `due`, so one `ack` also persists the schedule (defer: retry -1).\n // Most passes block nothing; an empty call would still cost the store a\n // write transaction.\n const to_block = handled\n .filter(({ block }) => block)\n .map(({ lease, error }) => ({ ...lease, error: error! }));\n const blocked = to_block.length ? await ops.block(to_block) : [];\n\n // Before the `ack`, so an ack failure can't lose the terminal event.\n if (blocked.length) deps.on_blocked(blocked);\n\n const submitted = handled.flatMap((h, i) => {\n const advance = h.handled > 0 ? h.acked_at : leased[i].at;\n return h.defer !== undefined\n ? { ...h.lease, at: advance, due: h.defer, retry: -1 }\n : h.next_attempt_at !== undefined\n ? { ...h.lease, at: advance, due: h.next_attempt_at }\n : h.handled > 0 || !h.error\n ? { ...h.lease, at: h.acked_at }\n : [];\n });\n const acked = submitted.length ? await ops.ack(submitted) : [];\n\n // `ack` drops entries whose lease another worker took (deferred entries\n // are never returned).\n const expected = submitted.filter((l) => l.due === undefined).length;\n if (acked.length < expected)\n log().warn(\n `drain: ${expected - acked.length} of ${expected} acks were dropped — the lease was taken by another worker mid-handler. That work will be redelivered (at-least-once), but persistent drops mean leaseMillis is too short for this handler.`\n );\n\n const closeable = handled\n .filter((h) => h.close !== undefined)\n .map((h) => h.close!);\n\n return { leased, fetched, handled, acked, blocked, closeable };\n}\n\nconst EMPTY_DRAIN: Drain<Schemas> = {\n fetched: [],\n leased: [],\n acked: [],\n blocked: [],\n};\n\n/** One drain made of several: every lane of a pass, or every pass of a settle. */\nexport function merge_drains<TEvents extends Schemas>(\n drains: ReadonlyArray<Drain<TEvents>>\n): Drain<TEvents> {\n return {\n fetched: drains.flatMap((d) => d.fetched),\n leased: drains.flatMap((d) => d.leased),\n acked: drains.flatMap((d) => d.acked),\n blocked: drains.flatMap((d) => d.blocked),\n };\n}\n\nexport type DrainControllerDeps<\n TEvents extends Schemas,\n TActions extends Schemas,\n TSchemaReg extends SchemaRegister<TActions>,\n> = {\n readonly logger: Logger;\n readonly ops: DrainOps<TEvents>;\n readonly registry: Registry<TSchemaReg, TEvents, TActions>;\n readonly batch_handlers: Map<string, BatchHandler<TEvents>>;\n readonly handle: Handle<TEvents>;\n readonly handle_batch: HandleBatch<TEvents>;\n readonly on_acked: (acked: Lease[]) => void;\n readonly on_blocked: (blocked: BlockedLease[]) => void;\n /** Awaited, so a slow close doesn't overlap the next claim. */\n readonly on_close: (targets: CloseTarget[]) => Promise<void>;\n readonly breaker: CircuitBreaker;\n /** The worker ticks outside any caller frame, so its drain is re-scoped. */\n readonly run_scoped: <T>(fn: () => Promise<T>) => Promise<T>;\n /** Lane this controller drains. Undefined spans all lanes. */\n readonly lane?: string;\n /** The lane's own config; it wins over the caller's DrainOptions. */\n readonly defaults?: {\n readonly streamLimit?: number;\n readonly leaseMillis?: number;\n };\n};\n\n/** Wake key for the controller's own retry; no stream is named \"\". */\nconst RETRY = \"\";\n\nexport class DrainController<\n TEvents extends Schemas,\n TActions extends Schemas,\n TSchemaReg extends SchemaRegister<TActions>,\n> {\n // Armed while `_raised` is ahead of `_lowered` (the raise count the last\n // empty claim saw), so a claim never lowers over a raise that landed\n // during it.\n private _raised = 0;\n private _lowered = 0;\n private _ratio = 0.5;\n // Local wake at the earliest parked (backoff or defer) visit, or at the\n // lease expiry after a failed pass (the {@link RETRY} key); the schedule\n // itself is persisted. On an idle app nothing else would drain it. It\n // drains until a pass leases nothing or the controller stops, and an entry\n // stays until handled or until a later pass claims nothing.\n private readonly _defer = new DeferTimer(() => {\n this.arm();\n void this._deps.run_scoped(async () => {\n while ((await this.drain()).leased.length > 0);\n });\n });\n private _worker: ReturnType<typeof setTimeout> | undefined;\n private readonly _misrouted = new Set<string>();\n private _stopped = false;\n // The pass in flight. Never rejects; graceful shutdown waits on it.\n private _inflight: Promise<Drain<TEvents>> | undefined;\n\n private readonly _deps: DrainControllerDeps<TEvents, TActions, TSchemaReg>;\n\n constructor(deps: DrainControllerDeps<TEvents, TActions, TSchemaReg>) {\n this._deps = deps;\n }\n\n arm(): void {\n this._raised++;\n }\n\n /** Cold start: re-seed a persisted `deferred_at` into the local wake. */\n seed_defer(stream: string, at: number): void {\n this._defer.set(stream, at);\n this._defer.schedule();\n }\n\n get armed(): boolean {\n return this._raised !== this._lowered;\n }\n\n get inflight(): Promise<Drain<TEvents>> | undefined {\n return this._inflight;\n }\n\n /** This lane's configured lease, or `undefined`; the shutdown grace basis. */\n get lease_millis(): number | undefined {\n return this._deps.defaults?.leaseMillis;\n }\n\n get lane(): string | undefined {\n return this._deps.lane;\n }\n\n /**\n * Drains every `cycleMs` while armed; the unref'd timer never holds the\n * process. Called once, when the controller is built.\n */\n start(cycleMs: number): void {\n // `drain()` never throws.\n const run = this._deps.run_scoped;\n const tick = async () => {\n if (this.armed) await run(() => this.drain());\n if (this._stopped) return;\n this._worker = setTimeout(tick, cycleMs);\n this._worker.unref();\n };\n this._worker = setTimeout(tick, cycleMs);\n this._worker.unref();\n }\n\n stop(): void {\n this._stopped = true;\n if (this._worker) {\n clearTimeout(this._worker);\n this._worker = undefined;\n }\n this._defer.stop();\n }\n\n async drain(options: DrainOptions = {}): Promise<Drain<TEvents>> {\n // A stopped controller claims nothing, so a pass shutdown's grace\n // outlived can't start work after teardown.\n // One pass at a time: a call while one runs claims nothing.\n if (!this.armed || this._stopped || this._inflight)\n return EMPTY_DRAIN as Drain<TEvents>;\n\n const d = this._deps.defaults ?? {};\n // A lane's own budget wins over caller options.\n const streamLimit =\n d.streamLimit ?? options.streamLimit ?? DEFAULT_STREAM_LIMIT;\n const eventLimit = options.eventLimit ?? DEFAULT_EVENT_LIMIT;\n const leaseMillis =\n d.leaseMillis ?? options.leaseMillis ?? DEFAULT_LEASE_MILLIS;\n\n // Circuit open: stay armed and leave the wake alone (re-aiming would fire\n // at once for anything due); the breaker's own wake re-aims it.\n if (this._deps.breaker.state(Date.now()) === \"open\")\n return EMPTY_DRAIN as Drain<TEvents>;\n\n const pass = this._pass(streamLimit, eventLimit, leaseMillis).finally(\n () => {\n this._inflight = undefined;\n }\n );\n this._inflight = pass;\n return pass;\n }\n\n // One claim → fetch → handle → ack pass. Never throws.\n private async _pass(\n streamLimit: number,\n eventLimit: number,\n leaseMillis: number\n ): Promise<Drain<TEvents>> {\n try {\n const lagging = Math.ceil(streamLimit * this._ratio);\n const leading = streamLimit - lagging;\n\n const started = Date.now();\n const raised = this._raised;\n const cycle = await run_drain_cycle(this._deps, {\n lagging,\n leading,\n eventLimit,\n leaseMillis,\n misrouted: this._misrouted,\n store_failing: this._deps.breaker.failing,\n });\n\n if (!cycle) {\n // Caught up: whatever was due when this pass started has no work.\n this._defer.prune(started);\n this._deps.breaker.passed();\n // Lowers only the raises it saw: one that landed during the claim\n // (an unblock, a reset) brought work this claim couldn't see.\n this._lowered = raised;\n return EMPTY_DRAIN as Drain<TEvents>;\n }\n\n const { leased, fetched, handled, acked, blocked, closeable } = cycle;\n\n trace_cycle(this._deps.logger, leased, fetched, handled, acked, blocked);\n\n this._ratio = compute_lag_lead_ratio(handled, lagging, leading);\n\n for (const lease of acked) this._defer.delete(lease.stream);\n for (const lease of blocked) this._defer.delete(lease.stream);\n for (const h of handled) {\n const next = h.defer ?? h.next_attempt_at;\n if (next !== undefined) this._defer.set(h.lease.stream, next);\n }\n\n // Listener throws are contained in `Act.emit`.\n if (acked.length) this._deps.on_acked(acked);\n // The orchestrator contains close failures; anything that still\n // throws here reaches the breaker.\n if (closeable.length) await this._deps.on_close(closeable);\n\n // After `on_close`, so a failed close never counts as a store success.\n this._deps.breaker.passed();\n\n return { fetched, leased, acked, blocked };\n } catch (error) {\n // A store op threw: stay armed and retry after the breaker's cooldown,\n // never before this pass's leases expire, so an idle app retries\n // without waiting for the breaker to open.\n this._defer.set(\n RETRY,\n Date.now() + Math.max(leaseMillis, this._deps.breaker.cooldown_ms)\n );\n this._deps.breaker.failed(Date.now(), error);\n return EMPTY_DRAIN as Drain<TEvents>;\n } finally {\n // Re-aim at the earliest stream still parked.\n if (!this._stopped) this._defer.schedule();\n }\n }\n}\n","/**\n * Per-reaction retry backoff delay computation. Pure function — keeps\n * `DrainController` and `finalize` (in `drain-cycle.ts`) testable in isolation.\n */\n\nimport type { BackoffOptions } from \"../types/action.js\";\n\n/**\n * Compute the wall-clock delay (in ms) to wait before the next attempt on\n * a stream whose handler just failed.\n *\n * @param retry - The lease's `retry` counter at finalize time. `0` is the\n * first attempt that failed; `1` is after one retry; etc.\n * @param opts - Per-reaction backoff config. Returns `0` when undefined.\n * @returns Non-negative integer milliseconds. Always `0` when `opts` is\n * undefined or `baseMs <= 0`.\n */\nexport function compute_backoff_delay(\n retry: number,\n opts: BackoffOptions | undefined\n): number {\n if (!opts || opts.baseMs <= 0) return 0;\n const r = Math.max(0, retry);\n let delay: number;\n switch (opts.strategy) {\n case \"fixed\":\n delay = opts.baseMs;\n break;\n case \"linear\":\n delay = opts.baseMs * (r + 1);\n break;\n case \"exponential\":\n delay = opts.baseMs * 2 ** r;\n if (opts.maxMs !== undefined) delay = Math.min(delay, opts.maxMs);\n break;\n default: {\n // Unreachable once options pass `resolveBackoffConfig` at their\n // declaration site. Defensive so the pure function is total and can\n // never emit `NaN` from an unvalidated strategy — throw instead.\n const _never: never = opts.strategy;\n throw new Error(`unknown backoff strategy: ${String(_never)}`);\n }\n }\n if (opts.jitter) delay = delay * (0.5 + Math.random());\n return Math.max(0, Math.floor(delay));\n}\n","/**\n * The shared \"next visit time\" primitive. A `DeferTimer` holds a\n * `stream → due-time` map and a single collapsed wake timer: it parks\n * streams that should be re-visited later and fires one `on_wake` callback\n * at the earliest pending due-time.\n *\n * The {@link \"drain-cycle\".DrainController} rides it for per-reaction\n * backoff (a retry's `next_attempt_at`) and for the `defer` outcome, which\n * holds a stream pending without advancing the watermark or bumping `retry`.\n * The wake runs a drain, and the drain re-schedules the timer when it ends.\n * An entry stays until its stream is acked or blocked, re-parked, or a\n * drain that started after it came due claims nothing ({@link prune}): a\n * wake that lands during another drain, or a pass that reaches only some of\n * the due streams, leaves the rest due, so the next re-schedule fires again\n * at once.\n *\n * Lives in process memory, per worker — the same per-worker pacing trade-off\n * documented for backoff. Durability comes from the data the due-time is\n * *derived* from (an un-advanced watermark, an event's `created` timestamp),\n * not from the map. A restart empties the map, so the cold-start rebuild is\n * explicit: `CorrelateCycle.init` seeds each still-future `deferred_at` back\n * onto the owning lane's timer via {@link \"drain-cycle\".DrainController.seed_defer},\n * so an idle deferred stream re-arms at its due-time with no\n * intervening commit.\n */\n\n/**\n * Node's `setTimeout` delay is a 32-bit signed int (~24.8 days). A larger\n * delay overflows and fires immediately, so we cap at this and re-arm.\n */\nconst MAX_TIMER_DELAY_MS = 2_147_483_647;\n\n/** A linear scan finds the earliest entry: the map is bounded by claim limits. */\nexport class DeferTimer {\n private readonly _due = new Map<string, number>();\n private _timer: ReturnType<typeof setTimeout> | undefined;\n private readonly _on_wake: () => void;\n\n /**\n * @param on_wake - invoked once each time the earliest due-time elapses.\n * The consumer re-schedules for whatever is still parked.\n */\n constructor(on_wake: () => void) {\n this._on_wake = on_wake;\n }\n\n /** Number of currently parked streams. */\n get size(): number {\n return this._due.size;\n }\n\n /**\n * Park `stream` for a re-visit at `at` (ms since epoch). A plain\n * overwrite: the caller computes the authoritative next-visit for the\n * stream (the drain's `handle` already reconciles a stream's reactions\n * into one result per cycle), so there is no stale value to merge against.\n */\n set(stream: string, at: number): void {\n this._due.set(stream, at);\n }\n\n /** Drop `stream` from the parked set (e.g. on a successful ack or block). */\n delete(stream: string): void {\n this._due.delete(stream);\n }\n\n /**\n * Drop every entry due at or before `before`. The drain calls it when a\n * pass that started at `before` claimed nothing: whatever was due by then\n * was handled elsewhere (another worker) or has no work left, so waking\n * for it again would spin.\n */\n prune(before: number): void {\n for (const [stream, at] of this._due)\n if (at <= before) this._due.delete(stream);\n }\n\n /**\n * (Re)schedule the wake timer at the earliest pending due-time. Idempotent\n * — collapses many parked streams into a single timer. A no-op clears any\n * pending timer when the map is empty.\n *\n * The timer is `unref()`-ed so pending re-visits never keep the process\n * alive on their own.\n */\n schedule(): void {\n if (this._timer) clearTimeout(this._timer);\n if (this._due.size === 0) {\n this._timer = undefined;\n return;\n }\n let earliest = Number.POSITIVE_INFINITY;\n for (const t of this._due.values()) if (t < earliest) earliest = t;\n // A longer due-time (a 90-day autoclose cooldown) wakes at the ceiling;\n // the entry stays and the consumer re-schedules for the rest.\n const delay = Math.min(\n Math.max(0, earliest - Date.now()),\n MAX_TIMER_DELAY_MS\n );\n this._timer = setTimeout(() => {\n this._timer = undefined;\n this._on_wake();\n }, delay);\n this._timer.unref();\n }\n\n /** Cancel any pending wake timer. Idempotent. Leaves the parked set intact. */\n stop(): void {\n if (this._timer) {\n clearTimeout(this._timer);\n this._timer = undefined;\n }\n }\n}\n","/**\n * Adaptive lag-to-lead ratio for the dual-frontier drain strategy.\n *\n * The orchestrator splits its per-cycle stream budget between two frontiers:\n *\n * - **lagging** — newly subscribed or behind streams catching up.\n * - **leading** — actively-processing streams at the head of the log.\n *\n * After each cycle, this helper looks at how many events were actually\n * handled in each frontier and shifts the next cycle's split toward\n * whichever frontier had the higher per-stream throughput. The result is\n * clamped to `[0.2, 0.8]` so neither frontier can be starved.\n */\n\nimport type { HandleResult } from \"./drain-cycle.js\";\n\n/** Floor / ceiling for the lag-to-lead ratio so neither frontier starves. */\nconst RATIO_MIN = 0.2;\nconst RATIO_MAX = 0.8;\n/** Default ratio when no events were handled in either frontier. */\nconst RATIO_DEFAULT = 0.5;\n\n/**\n * Compute the next lag-to-lead ratio from the cycle's handled events and\n * the frontier sizes used to claim them. Returns `RATIO_DEFAULT` when no\n * progress was made (nothing to base a decision on).\n */\nexport function compute_lag_lead_ratio(\n handled: ReadonlyArray<HandleResult>,\n lagging: number,\n leading: number\n): number {\n let lagging_handled = 0;\n let leading_handled = 0;\n for (const { lease, handled: count } of handled) {\n if (lease.lagging) lagging_handled += count;\n else leading_handled += count;\n }\n const lagging_avg = lagging > 0 ? lagging_handled / lagging : 0;\n const leading_avg = leading > 0 ? leading_handled / leading : 0;\n const total = lagging_avg + leading_avg;\n if (total === 0) return RATIO_DEFAULT;\n return Math.max(RATIO_MIN, Math.min(RATIO_MAX, lagging_avg / total));\n}\n","/**\n * One-shot reporting for a misdeclaration a build-time guard can't see: a\n * `.to(fn)` target, lane or priority is only known once an event arrives,\n * so correlate and drain apply those rules and report what breaks them.\n * A resolver fires for every matching event, so reporting once per\n * declaration is what keeps the log readable.\n *\n * The key is the whole design: build it only from what the declaration\n * names (handler, event, lane, a static target), never from a value a\n * resolver computed. A resolved target is the trap: the per-aggregate shape\n * `.to(e => ({ target: e.stream }))` would turn one typo into one line per\n * aggregate. Runtime values still belong in the message, as the example.\n *\n * Never throws: a throw in correlate pins the checkpoint for the whole app,\n * and in drain it reaches the breaker as a store failure.\n */\n\nimport { log } from \"../ports.js\";\n\n/**\n * Report `message` the first time `key` is seen. `seen` belongs to the\n * caller, since `internal/` holds no module state.\n */\nexport function report_once(\n seen: Set<string>,\n key: string,\n message: string\n): void {\n if (seen.has(key)) return;\n seen.add(key);\n log().error(new Error(message));\n}\n","/**\n * The default correlation-id generator. Apps plug in their own scheme\n * through {@link ActOptions.correlator}.\n */\n\nimport { randomInt } from \"node:crypto\";\nimport type { Actor, Correlator } from \"../types/index.js\";\n\nconst BASE = 36;\nconst SEG_WIDTH = 4;\nconst SEG_SPACE = BASE ** SEG_WIDTH;\n\nfunction seg(n: number): string {\n return n.toString(BASE).padStart(SEG_WIDTH, \"0\");\n}\n\n/**\n * Default {@link Correlator}. Produces ids of the form\n * `{state[:4]}-{action[:4]}-{4 ms}{4 random}` — 18 characters, lowercase\n * base36.\n *\n * - Prefix carries human-meaningful context (state + action) so operators\n * can identify a workflow at a glance in logs and query results.\n * - The 4-character `Date.now() % 36^4` segment wraps every ~28 minutes,\n * long enough that adjacent inserts in a typical workflow share B-tree\n * pages — index locality, not global sortability, is the goal.\n * - The 4-character random tail gives 1.68M values per ms; collision risk\n * across K=100 concurrent workers is roughly K² / 3.4M per ms.\n *\n * Names shorter than 4 chars are used as-is (no padding) so a state named\n * `Tx` produces `tx-...` rather than `tx00-...`.\n */\nexport const default_correlator: Correlator = ({ state, action }) => {\n const s = state.slice(0, SEG_WIDTH).toLowerCase();\n const a = action.slice(0, SEG_WIDTH).toLowerCase();\n const ts = seg(Date.now() % SEG_SPACE);\n const rnd = seg(randomInt(SEG_SPACE));\n return `${s}-${a}-${ts}${rnd}`;\n};\n\n/**\n * Resolves the correlation id for the close-the-books transaction.\n * Close runs outside any user action, so we synthesize a context with\n * sentinel state/action names — visible in the id when overrides aren't\n * configured.\n */\nexport function close_correlation(\n correlator: Correlator,\n actor: Actor\n): string {\n return correlator({\n state: \"$close\",\n action: \"close\",\n stream: \"$close\",\n actor,\n });\n}\n","/**\n * Pipeline operations consumed by the drain/correlate loop. Each op is a\n * single async step the orchestrator invokes per drain cycle:\n *\n * - `claim` — atomically discover and lock streams for processing\n * - `fetch` — read events for each leased stream\n * - `ack` — release leases for successfully handled streams\n * - `block` — flag leases that exceeded the retry budget\n * - `subscribe` — register newly correlated streams with the store\n *\n * This module exposes only the bare implementations as plain async functions,\n * mirroring the shape of {@link \"event-sourcing\"}. Trace decoration is\n * layered on top in {@link \"tracing\"} and selected by the orchestrator at\n * construction time. No tracing imports here.\n */\n\nimport { isStreamName } from \"../adapter.js\";\nimport { store } from \"../ports.js\";\nimport type {\n BlockedLease,\n Committed,\n Fetch,\n Lease,\n Schemas,\n SubscribeInput,\n SubscribeResult,\n} from \"../types/index.js\";\n\nexport interface DrainOps<TEvents extends Schemas> {\n claim: typeof claim;\n fetch: typeof fetch<TEvents>;\n ack: typeof ack;\n block: typeof block;\n subscribe: typeof subscribe;\n}\n\nexport const claim = (\n lagging: number,\n leading: number,\n by: string,\n millis: number,\n lane?: string\n): Promise<Lease[]> => store().claim(lagging, leading, by, millis, lane);\n\nexport async function fetch<TEvents extends Schemas>(\n leased: Lease[],\n eventLimit: number\n): Promise<Fetch<TEvents>> {\n return Promise.all(\n leased.map(async ({ stream, source, at, lagging }) => {\n const events: Committed<TEvents, keyof TEvents>[] = [];\n // A literal `source` fetches with `stream_exact` so an exact name\n // like \"s1\" reads only \"s1\" — never a sibling prefix \"s12\". A\n // pattern source (e.g. `^(A|B)$`) stays a regex query, matching the\n // same streams correlate resolved it for.\n const stream_exact =\n source !== undefined && isStreamName(source, stream) ? true : undefined;\n try {\n await store().query<TEvents>((e) => events.push(e), {\n stream: source,\n stream_exact,\n after: at,\n limit: eventLimit,\n });\n } catch (error) {\n // Contain it per stream. These reads are already per-stream, but they\n // shared one `Promise.all`, so one stream's failure rejected the whole\n // cycle and every healthy stream leased beside it got nothing —\n // an unreadable `pii` payload on one aggregate stalled unrelated\n // reactions. The cycle turns this into a no-progress failure\n // for THIS stream only, which the retry budget then escalates.\n //\n // Unlike correlate, this read cannot simply decline the payload:\n // handlers receive it (through their own gate), so a fetch that\n // dropped it would hand them a silently incomplete event.\n return {\n stream,\n source,\n at,\n lagging,\n events: [],\n error: (error as Error)?.message ?? String(error),\n } as const;\n }\n return { stream, source, at, lagging, events } as const;\n })\n );\n}\n\n// Finalize: acks and defers in one atomic store call. Leases\n// carrying `due` are deferred, the rest acked — a failed finalize lands\n// nothing, and redelivery covers every outcome uniformly.\nexport const ack = (leases: Lease[]): Promise<Lease[]> => store().ack(leases);\n\nexport const block = (leases: BlockedLease[]): Promise<BlockedLease[]> =>\n store().block(leases);\n\nexport const subscribe = (\n streams: SubscribeInput[],\n correlated_at?: number,\n correlator?: { key: string; by: string; millis: number }\n): Promise<SubscribeResult> =>\n store().subscribe(streams, correlated_at, correlator);\n","/**\n * Event-sourcing primitives: `snap`, `load`, `action`, `tombstone`, `scan`.\n * Bare implementations; tracing wraps them in `tracing.ts`.\n */\n\nimport { patch } from \"@rotorsoft/act-patch\";\nimport { prettifyError, ZodError, type ZodType } from \"zod\";\nimport { cache, log, store } from \"../ports.js\";\nimport {\n ConcurrencyError,\n PreconditionError,\n StreamClosedError,\n ValidationError,\n} from \"../types/errors.js\";\nimport type {\n CacheEntry,\n Committed,\n DoOptions,\n Emitted,\n EventMeta,\n EventSource,\n Load,\n LoadTarget,\n Message,\n PatchFn,\n ScanOptions,\n ScanResult,\n Schema,\n Schemas,\n Snapshot,\n State,\n Target,\n} from \"../types/index.js\";\nimport {\n REDACTED,\n SHREDDED,\n SNAP_EVENT,\n TOMBSTONE_EVENT,\n} from \"../types/index.js\";\nimport { sleep, validate } from \"../utils.js\";\nimport { compute_backoff_delay } from \"./backoff.js\";\nimport { default_correlator } from \"./correlation-id.js\";\n\n/** The default patch step: a bare merge, so the hot path pays nothing. */\nexport const bare_patch: PatchFn = (_me, state, partial) =>\n patch(state, partial) as typeof state;\n\nconst value_at = (value: unknown, path: readonly PropertyKey[]): unknown =>\n path.reduce<unknown>(\n (at, key) => (at as Record<PropertyKey, unknown> | undefined)?.[key],\n value\n );\n\n/**\n * Checks the state an action leaves against the state's schema (its\n * invariants), without replacing it: a schema with defaults or transforms\n * never rewrites a valid state. A throwing refinement refuses like a failed\n * one, as `validate` does for payloads.\n *\n * A sensitive state is folded through the committing actor's view, so a\n * value it can't read arrives as `[REDACTED]` or `[SHREDDED]`. Those come\n * only from stored history, which passed this check with the real value,\n * so their issues are dropped.\n */\nconst check_invariants = <TState extends Schema>(\n target: string,\n state: TState,\n schema: ZodType<TState>,\n pii_aware: boolean\n): void => {\n let result: ReturnType<typeof schema.safeParse>;\n try {\n result = schema.safeParse(state);\n } catch (error) {\n throw new ValidationError(target, state, error);\n }\n if (result.success) return;\n const issues = pii_aware\n ? result.error.issues.filter((issue) => {\n const value = value_at(state, issue.path);\n return value !== REDACTED && value !== SHREDDED;\n })\n : result.error.issues;\n if (issues.length)\n throw new ValidationError(\n target,\n state,\n prettifyError(new ZodError(issues))\n );\n};\n\nconst DEFAULT_BATCH = 500;\n\n/** `action` with the correlator and patch step bound by `build_es`. */\ntype BoundAction = <\n TState extends Schema,\n TEvents extends Schemas,\n TActions extends Schemas,\n TKey extends keyof TActions,\n>(\n me: State<TState, TEvents, TActions>,\n action: TKey,\n target: Target,\n payload: Readonly<TActions[TKey]>,\n options?: DoOptions<TEvents>\n) => Promise<Snapshot<TState, TEvents>[]>;\n\nexport interface EsOps {\n snap: typeof snap;\n load: typeof load;\n action: BoundAction;\n tombstone: typeof tombstone;\n}\n\n/** Writes a cache checkpoint. A failure only costs the next load a re-fold. */\nconst cache_put = <TState extends Schema>(\n stream: string,\n entry: CacheEntry<TState>\n): Promise<void> =>\n cache()\n .set(stream, entry)\n .catch((err) =>\n log().warn(\n err,\n \"cache set skipped; the next load re-folds from the store\"\n )\n );\n\n/** Drops a cache checkpoint. A failure leaves a stale one, which re-folds. */\nconst cache_drop = (stream: string): Promise<void> =>\n cache()\n .invalidate(stream)\n .catch((err) =>\n log().warn(\n err,\n \"cache invalidate skipped; a stale checkpoint re-folds from its event_id\"\n )\n );\n\n/** Commits a snapshot event. Never throws: a failed snapshot must not fail the action. */\nexport async function snap<TState extends Schema, TEvents extends Schemas>(\n snapshot: Snapshot<TState, TEvents>\n): Promise<Committed<TEvents, keyof TEvents> | undefined> {\n const { id, stream, name, meta, version } = snapshot.event!;\n try {\n const [committed] = await store().commit(\n [\n {\n stream,\n msgs: [{ name: SNAP_EVENT, data: snapshot.state }],\n // IMPORTANT! - state events are committed right after the snapshot event\n expectedVersion: version,\n },\n ],\n {\n correlation: meta.correlation,\n causation: { event: { id, name: name as string, stream } },\n }\n );\n return committed as Committed<TEvents, keyof TEvents>;\n } catch (error) {\n const reason = error instanceof Error ? error.message : String(error);\n log().warn(\n `Snapshot write failed on stream \"${stream}\": ${reason} — cold starts will replay full history until snapshots succeed.`\n );\n }\n}\n\n/**\n * Commits the close guard at `expectedVersion`; `undefined` when the stream\n * moved. Actions then see the tombstone at head and throw {@link StreamClosedError}.\n */\nexport async function tombstone(\n stream: string,\n expectedVersion: number,\n correlation: string\n): Promise<Committed<Schemas, keyof Schemas> | undefined> {\n try {\n const [committed] = await store().commit(\n [\n {\n stream,\n msgs: [{ name: TOMBSTONE_EVENT, data: {} }],\n expectedVersion,\n },\n ],\n { correlation, causation: {} }\n );\n return committed;\n } catch (error) {\n if (error instanceof ConcurrencyError) return undefined;\n throw error;\n }\n}\n\n/**\n * Rejects a negative version or an invalid `created` Date. Duplicate ids and\n * version gaps are left to the sink (partial backups have gaps).\n */\nfunction is_valid(event: Committed<Schemas, keyof Schemas>): boolean {\n if (event.version < 0) return false;\n if (!(event.created instanceof Date) || Number.isNaN(event.created.getTime()))\n return false;\n return true;\n}\n\n/**\n * Pages a restore source: validation, drop filters, migrations, progress and\n * causation remap. Adapters supply only the per-event insert `callback`\n * (see {@link Store.restore}). A source that ignores `limit` (`CsvFile`)\n * returns everything in one page.\n */\nexport async function scan(\n source: EventSource,\n opts: ScanOptions = {},\n callback?: (event: Committed<Schemas, keyof Schemas>) => Promise<number>\n): Promise<Omit<ScanResult, \"duration_ms\">> {\n const {\n drop_snapshots = false,\n drop_closed_streams = false,\n on_progress,\n event_migrations,\n stream_rename,\n } = opts;\n const limit = opts.batch_size ?? DEFAULT_BATCH;\n const id_map = new Map<number, number>();\n let kept = 0;\n let dropped_snaps = 0;\n let dropped_closed = 0;\n let migrated_count = 0;\n let processed = 0;\n let at: number | undefined;\n\n // `drop_closed_streams`: one extra walk to collect tombstoned streams.\n const closed_streams = new Set<string>();\n if (drop_closed_streams) {\n await source.query<Schemas>(\n (e) => {\n if (e.name === TOMBSTONE_EVENT) closed_streams.add(e.stream);\n },\n { names: [TOMBSTONE_EVENT] }\n );\n }\n\n // Probe the highest id (an index seek on SQL stores). A source that\n // ignores the filter returns more than one row; leave max_id unknown.\n let max_id: number | undefined;\n const probed = await source.query<Schemas>(\n (e) => {\n max_id = e.id;\n },\n { backward: true, limit: 1, with_snaps: true }\n );\n if (probed !== 1) max_id = undefined;\n\n while (true) {\n let got = 0;\n let id: number | undefined;\n\n await source.query<Schemas>(\n async (event) => {\n got++;\n id = event.id;\n processed++;\n if (!is_valid(event))\n throw new Error(`Invalid event at index ${processed}`);\n if (on_progress) on_progress({ processed, id: event.id, max_id });\n if (drop_snapshots && event.name === SNAP_EVENT) {\n dropped_snaps++;\n return;\n }\n if (\n closed_streams.has(event.stream) &&\n event.name !== TOMBSTONE_EVENT\n ) {\n // Keep the tombstone: it is what keeps the stream closed.\n dropped_closed++;\n return;\n }\n // Before the causation remap, so `id_map` stays keyed by source id.\n let migrated: typeof event = event;\n const migration = event_migrations?.[event.name as string];\n if (migration) {\n const old_data = migration.from_schema.parse(event.data);\n const new_data = migration.migrate(old_data);\n migration.to_schema.parse(new_data);\n migrated = {\n ...event,\n name: migration.to as typeof event.name,\n data: new_data as any,\n };\n migrated_count++;\n }\n if (stream_rename) {\n const renamed = stream_rename(migrated.stream);\n if (renamed !== migrated.stream)\n migrated = { ...migrated, stream: renamed };\n }\n if (!callback) {\n kept++;\n return;\n }\n // Spread `migrated`, not `event`, or the migration is undone.\n let remapped = migrated;\n const { action, event: cause } = migrated.meta.causation;\n if (cause || (stream_rename && action)) {\n remapped = {\n ...migrated,\n meta: {\n ...migrated.meta,\n causation: {\n ...migrated.meta.causation,\n ...(action &&\n stream_rename && {\n action: { ...action, stream: stream_rename(action.stream) },\n }),\n ...(cause && {\n event: {\n ...cause,\n // A cause missing from the source has no id in the new\n // log; its old id would name another event there.\n id: id_map.get(cause.id) ?? -1,\n stream: stream_rename\n ? stream_rename(cause.stream)\n : cause.stream,\n },\n }),\n },\n },\n };\n }\n const new_id = await callback(remapped);\n id_map.set(event.id, new_id);\n kept++;\n },\n { after: at, limit, with_snaps: true }\n );\n\n // Stop on a short page, or on an oversized one (the source ignored the\n // limit and already returned everything).\n if (got !== limit) break;\n at = id;\n }\n\n return {\n kept,\n migrated: migrated_count,\n dropped: {\n closed_streams: dropped_closed,\n snapshots: dropped_snaps,\n },\n };\n}\n\n/**\n * Folds a stream into state, from the cached checkpoint or the latest\n * snapshot. `asOf` time-travels and bypasses the cache.\n */\nexport async function load<\n TState extends Schema,\n TEvents extends Schemas,\n TActions extends Schemas,\n>(\n me: State<TState, TEvents, TActions>,\n target: LoadTarget,\n callback?: (snapshot: Snapshot<TState, TEvents>) => void,\n patch_fn: PatchFn = bare_patch\n): Promise<Snapshot<TState, TEvents>> {\n const { stream, actor, asOf } = target;\n const time_travel =\n !!asOf && Object.values(asOf).some((v) => v !== undefined);\n // `limit` and `created_after` read a slice of the real events, without a seed.\n const seeded =\n time_travel && asOf!.limit === undefined && !asOf!.created_after;\n const cached = time_travel ? undefined : await cache().get<TState>(stream);\n const cache_hit = !!cached;\n let state = cached?.state ?? (me.init ? me.init() : ({} as TState));\n let patches = cached?.patches ?? 0;\n let snaps = cached?.snaps ?? 0;\n // Events this load processed; `patches` is the snap distance from the cache.\n let replayed = 0;\n let event: Committed<TEvents, keyof TEvents> | undefined;\n\n await store().query<TEvents>(\n (raw) => {\n // Time travel folds the real events. A snapshot only seeds it, holding what\n // a prune or a restart took, so it counts only as the first row.\n if (seeded && raw.name === SNAP_EVENT && replayed > 0) return;\n event = me.view(raw, actor);\n if (event.name === SNAP_EVENT) {\n state = event.data as TState;\n snaps++;\n patches = 0;\n replayed++;\n } else if (me.patch[event.name]) {\n state = patch_fn(me, state, me.patch[event.name](event, state), event);\n patches++;\n replayed++;\n } else if (event.name !== TOMBSTONE_EVENT) {\n // A renamed event, the wrong state, or a contaminated stream.\n log().warn(\n `Skipping unknown event \"${String(event.name)}\" on stream \"${stream}\" (id=${event.id}) — no reducer in state \"${me.name}\"`\n );\n }\n callback?.({\n event,\n state,\n version: event.version,\n id: event.id,\n patches,\n snaps,\n cache_hit,\n replayed,\n });\n },\n {\n stream,\n stream_exact: true,\n // `with_snaps` on every non-time-travel load: cold, it resumes from the\n // latest snapshot; warm, it keeps a snapshot above a stale checkpoint,\n // so a windowed close's prune can't fold the tail onto stale state.\n ...(cached\n ? { after: cached.event_id, with_snaps: true }\n : seeded\n ? // From the start, past the resume floor, which could jump over the\n // time bound. The snapshots are for the seed.\n { with_snaps: true, after: -1, ...asOf }\n : time_travel\n ? asOf\n : { with_snaps: true }),\n }\n );\n\n // A stale write self-corrects: the next load replays past its `event_id`.\n // Not at a tombstone head, or `action()`'s closed check would pass vacuously.\n const head_is_tombstone = event?.name === TOMBSTONE_EVENT;\n if (\n replayed > 0 &&\n !time_travel &&\n event &&\n !me.pii_aware &&\n !head_is_tombstone\n ) {\n await cache_put(stream, {\n stream,\n state,\n version: event.version,\n event_id: event.id,\n patches,\n snaps,\n });\n }\n\n return {\n event,\n state,\n version: event?.version ?? cached?.version ?? -1,\n // Captured with `state`, so consumers never race a separate cache lookup.\n id: event?.id ?? cached?.event_id ?? -1,\n patches,\n snaps,\n cache_hit,\n replayed,\n };\n}\n\n/** A stream an action may append to (its own, or one of its loads'), with the events it emits there. */\ntype Pending = {\n readonly state: State<any, any, any>;\n readonly stream: string;\n readonly snapshot: Snapshot<any, any>;\n readonly expected: number;\n readonly events: { name: string; data: Schema }[];\n};\n\n/**\n * Loads the other streams an action's decision needs, all at once. A target\n * returning `undefined` skips its load. A target can name a stream from the\n * caller's input, so an empty name, the action's own stream or another load's\n * refuses the action, as a rule would. A load of a closed stream throws.\n */\nasync function load_others(\n loads: readonly Load[],\n payload: Schema,\n own: { stream: string; state: Schema },\n actor: Target[\"actor\"],\n patch_fn: PatchFn,\n refuse: (description: string) => Error\n): Promise<(Pending | undefined)[]> {\n const streams = loads.map((l) => l.target(payload, own.state));\n streams.forEach((stream, i) => {\n if (stream === undefined) return;\n if (typeof stream !== \"string\" || !stream)\n throw refuse(`loads \"${loads[i].name}\" from an empty stream name`);\n if (stream === own.stream) throw refuse(`loads its own stream \"${stream}\"`);\n if (streams.indexOf(stream) !== i)\n throw refuse(`loads stream \"${stream}\" twice`);\n });\n return Promise.all(\n loads.map(async (l, i) => {\n const stream = streams[i];\n if (stream === undefined) return undefined;\n const snapshot = await load(\n l.state,\n { stream, actor },\n undefined,\n patch_fn\n );\n if (snapshot.event?.name === TOMBSTONE_EVENT)\n throw new StreamClosedError(stream);\n return {\n state: l.state,\n stream,\n snapshot,\n expected: snapshot.version,\n events: [],\n };\n })\n );\n}\n\n/**\n * Validates, checks preconditions, folds, checks the invariants and commits.\n * An action with loads appends to every stream it emits to in one commit,\n * each guarded by its version at load. On {@link ConcurrencyError} it\n * re-runs from `load` within the action's `maxRetries`; any other error\n * rethrows.\n *\n * Returns the snapshots of every stream appended to, the action's own first.\n */\nexport async function action<\n TState extends Schema,\n TEvents extends Schemas,\n TActions extends Schemas,\n TKey extends keyof TActions,\n>(\n me: State<TState, TEvents, TActions>,\n action: TKey,\n target: Target,\n payload: Readonly<TActions[TKey]>,\n options?: DoOptions<TEvents>,\n patch_fn: PatchFn = bare_patch\n): Promise<Snapshot<TState, TEvents>[]> {\n const { stream, expectedVersion, actor } = target;\n if (!stream) throw new Error(\"Missing target stream\");\n // `Act.do` already filled in the ambient reaction context.\n const reactingTo = options?.reactingTo;\n const correlator = options?.correlator ?? default_correlator;\n\n const validated = validate(action as string, payload, me.actions[action]);\n\n const opts = me.options?.[action];\n const max_retries = opts?.maxRetries ?? 0;\n const loads = me.loads?.[action] ?? [];\n\n for (let attempt = 0; ; attempt++) {\n try {\n const snapshot = await load(\n me,\n { stream, actor: target.actor },\n undefined,\n patch_fn\n );\n if (snapshot.event?.name === TOMBSTONE_EVENT)\n throw new StreamClosedError(stream);\n // `version`, not `event`: on a warm hit `event` is undefined. A new\n // stream expects -1, so two callers creating it can't both commit.\n const own: Pending = {\n state: me,\n stream,\n snapshot,\n expected: expectedVersion ?? snapshot.version,\n events: [],\n };\n const others = loads.length\n ? await load_others(\n loads,\n validated,\n { stream, state: snapshot.state },\n target.actor,\n patch_fn,\n (description) =>\n new PreconditionError(\n action,\n validated,\n target,\n snapshot,\n description\n )\n )\n : [];\n const loaded = Object.fromEntries(\n others.map((p, i) => [loads[i].name, p?.snapshot.state])\n );\n\n // Preconditions in declaration order: the first that fails refuses\n // the action.\n for (const { holds, description } of me.requires?.[action] ?? [])\n if (!holds(validated, snapshot.state, actor, loaded))\n throw new PreconditionError(\n action,\n validated,\n target,\n snapshot,\n description\n );\n\n const result = me.on[action](validated, snapshot, target, loaded);\n if (!result || (Array.isArray(result) && !result.length))\n return [snapshot];\n\n const tuples = Array.isArray(result[0])\n ? (result as Emitted<TEvents>[]) // array of tuples\n : ([result] as Emitted<TEvents>[]); // single tuple\n\n // An event listed on a load goes to that load's stream, and is dropped\n // when the load was skipped; the state's own events go to its own stream.\n for (const [name, data] of tuples) {\n const event = name as string;\n const i = loads.findIndex((l) => l.events.includes(event));\n if (i >= 0 && !others[i]) continue;\n const to = i >= 0 ? others[i] : name in me.events ? own : undefined;\n if (!to)\n throw new Error(\n `Action \"${action as string}\" emitted \"${event}\", which isn't an event of \"${me.name}\" and isn't listed on any of its loads`\n );\n to.events.push({\n name: event,\n data: validate(event, data, to.state.events[event]),\n });\n }\n // The action's own stream records the decision, so an action that\n // appends to other streams appends to its own too.\n if (!own.events.length)\n throw new Error(\n `Action \"${action as string}\" appends only to the streams it loads; it must append an event to its own stream too`\n );\n const appends = [own, ...others].filter(\n (p): p is Pending => !!p?.events.length\n );\n\n const meta: EventMeta = {\n correlation:\n reactingTo?.meta.correlation ||\n correlator({\n action: action as string,\n state: me.name,\n stream,\n actor: target.actor,\n }),\n causation: {\n action: {\n name: action as string,\n ...target,\n // payload intentionally omitted\n },\n event: reactingTo\n ? {\n id: reactingTo.id,\n name: reactingTo.name as string,\n stream: reactingTo.stream,\n }\n : undefined,\n },\n };\n\n // Fold before the commit (the decider rule), so a state that breaks\n // its schema (the invariants) is refused before anything is stored.\n // Each event folds onto its own stream's state. Reducers see the event\n // data and the next version; the store assigns `id` and `created`, so\n // they get placeholders here (`-1`, the commit time).\n const created = new Date();\n const folds = appends.map((p) => {\n let { state, patches } = p.snapshot;\n const folded = p.events.map((e, i) => {\n const event = {\n ...e,\n id: -1,\n stream: p.stream,\n version: p.snapshot.version + i + 1,\n created,\n meta,\n };\n const patch = p.state.patch[event.name](event, state);\n state = patch_fn(p.state, state, patch, event);\n patches++;\n return { state, patch, patches };\n });\n // Once per stream, on the state the action leaves: invariants hold\n // between actions, not between one action's events.\n check_invariants(\n `${p.state.name}.${action as string}`,\n state,\n p.state.state,\n p.state.pii_aware\n );\n return folded;\n });\n\n let committed: Committed<Schemas, keyof Schemas>[];\n try {\n committed = await store().commit<Schemas>(\n appends.map((p) => ({\n stream: p.stream,\n msgs: p.events.map((e) => p.state.message(e)) as Message<\n Schemas,\n string\n >[],\n expectedVersion: p.expected,\n })),\n meta\n );\n } catch (error) {\n // Fire-and-forget, so a cache failure can't replace the ConcurrencyError.\n if (error instanceof ConcurrencyError) void cache_drop(error.stream);\n throw error;\n }\n\n // The stored rows come back in append order, then event order, with\n // the real `id` and `created`; the states are already folded. The\n // caller sent the plaintext, so no view/gate round-trip.\n let row = 0;\n const snapshots: Snapshot<any, any>[] = [];\n for (const [a, append] of appends.entries()) {\n const { snapshot: base, state: owner } = append;\n const appended = append.events.map((e, i) => {\n const stored = committed[row++];\n const fold = folds[a][i];\n return {\n event: { ...stored, data: e.data },\n state: fold.state,\n version: stored.version,\n id: stored.id,\n patches: fold.patches,\n snaps: base.snaps,\n patch: fold.patch,\n cache_hit: base.cache_hit,\n replayed: base.replayed,\n };\n });\n const last = appended.at(-1)!;\n\n // Awaited, so the cache holds the post-snap checkpoint for the next caller.\n const snap_event = owner.snap?.(last) ? await snap(last) : undefined;\n\n // Sensitive states depend on the actor, so they aren't cached.\n if (!owner.pii_aware)\n void cache_put(append.stream, {\n stream: append.stream,\n state: last.state,\n version: snap_event?.version ?? last.event.version,\n event_id: snap_event?.id ?? last.event.id,\n patches: snap_event ? 0 : last.patches,\n snaps: snap_event ? last.snaps + 1 : last.snaps,\n });\n // The snapshot is the stream's head now, so a version pinned from this\n // result doesn't refuse the caller's own next action.\n if (snap_event)\n appended[appended.length - 1] = {\n ...last,\n version: snap_event.version,\n };\n snapshots.push(...appended);\n }\n\n return snapshots;\n } catch (error) {\n if (!(error instanceof ConcurrencyError)) throw error;\n // A caller-pinned version would conflict again on every retry.\n if (expectedVersion !== undefined && error.stream === stream) throw error;\n if (attempt >= max_retries) throw error;\n if (opts?.backoff) {\n const delay_ms = compute_backoff_delay(attempt, opts.backoff);\n if (delay_ms > 0) await sleep(delay_ms);\n }\n }\n }\n}\n","/**\n * Centralized observability for the framework's internal pipelines.\n *\n * Trace decorators wrap a bare implementation with `logger.trace(...)` calls\n * at well-defined moments — entry points for {@link \"event-sourcing\"} (`load`,\n * `snap`, `action`) and exit points for the {@link \"drain\"} pipeline (`claim`,\n * `fetch`, `ack`, `block`, `subscribe`). `action` logs both on entry and\n * after its commit.\n *\n * Output styles:\n * - **Pretty mode** (`config().env !== \"production\"`) — event-sourcing logs\n * show only the colored target body (color carries the operation/phase),\n * drain logs keep a colored caption.\n * - **Plain mode** (production / log aggregators) — every log gets a textual\n * prefix; event-sourcing uses `caption: body`, drain uses `caption body`.\n *\n * The two factories — {@link build_es} and {@link build_drain} — let the\n * orchestrator choose bare or traced variants once at `.build()` time based\n * on the configured log level. Outside this module, no other source file\n * imports tracing primitives.\n */\n\nimport { config } from \"../config.js\";\nimport type {\n AsOf,\n Correlator,\n Logger,\n PatchFn,\n Schemas,\n} from \"../types/index.js\";\nimport { default_correlator } from \"./correlation-id.js\";\nimport type { DrainOps } from \"./drain-ops.js\";\nimport * as drain from \"./drain-ops.js\";\nimport type { EsOps } from \"./event-sourcing.js\";\nimport * as es from \"./event-sourcing.js\";\n\ntype AsyncFn = (...args: any[]) => Promise<any>;\n\nconst PRETTY = config().env !== \"production\";\n\n// 256-color codes for distinctive, theme-friendly hues\nconst C_BLUE = \"\\x1b[38;5;39m\"; // vivid sky blue (action)\nconst C_ORANGE = \"\\x1b[38;5;208m\"; // true orange (committed)\nconst C_GREEN = \"\\x1b[38;5;42m\"; // emerald (load)\nconst C_MAGENTA = \"\\x1b[38;5;165m\"; // bright magenta (snap)\nconst C_DRAIN = \"\\x1b[38;5;244m\"; // muted gray for all drain ops\n// load-trace cache marker shades — distinguishable from C_GREEN body color\nconst C_HIT = \"\\x1b[38;5;82m\"; // lime — fast path, blends visually\nconst C_MISS = \"\\x1b[38;5;220m\"; // amber — non-trivial work happened\nconst C_RESET = \"\\x1b[0m\";\n\n/**\n * Format an event-sourcing trace line. Pretty mode renders just the colored\n * body (the color is the cue for which op/phase fired); plain mode prepends\n * `caption: ` so log aggregators stay readable without ANSI.\n */\nconst es_caption = (caption: string, color: string, body: string): string =>\n PRETTY ? `${color}${body}${C_RESET}` : `${caption}: ${body}`;\n\n/**\n * Format a drain-pipeline caption. Drain logs keep a `>>` marker for easy\n * spotting in mixed log streams, plus a `caption` (past tense — every drain\n * trace fires on exit). All drain ops share one color (gray) so the pipeline\n * reads as a single channel; the caption disambiguates the phase. Lane\n * is appended in lilac, unwrapped, when set and non-default,\n * so the operator's eye lands on the lane name without parsing per-stream\n * detail. Per-stream `@at/retry` and fetched event lists are muted via\n * {@link dim} so the stream name itself reads loudest.\n */\nconst C_LANE = \"\\x1b[38;5;183m\"; // lilac — distinct from gray drain + drain ops\nconst C_DIM = \"\\x1b[38;5;240m\"; // dim gray — dimmer than C_DRAIN\nconst C_ERR = \"\\x1b[38;5;196m\"; // bright red — block marker\nconst C_STREAM = \"\\x1b[38;5;226m\"; // bright yellow — target stream names in drain/correlate traces\n\n/** Wrap with the muted color when pretty mode is on. Plain in production. */\nconst dim = (text: string): string =>\n PRETTY ? `${C_DIM}${text}${C_RESET}` : text;\n\n/** Wrap with a foreground color when pretty mode is on; bare in production. */\nconst hue = (color: string, text: string): string =>\n PRETTY ? `${color}${text}${C_RESET}` : text;\n\nconst drain_caption = (caption: string, lane?: string): string => {\n const show_lane = lane && lane !== \"default\";\n if (PRETTY) {\n const tag = `${C_DRAIN}>> ${caption}${C_RESET}`;\n return show_lane ? `${tag} ${C_LANE}${lane}${C_RESET}` : tag;\n }\n return show_lane ? `>> ${caption} ${lane}` : `>> ${caption}`;\n};\n\n/**\n * Format the cache hit/miss marker for the load trace. In pretty mode the\n * word is colored (lime for hit, amber for miss) and the surrounding\n * `C_GREEN` body color is restored after — embedded ANSI inside `es_caption`'s\n * outer wrap. Plain mode returns the bare word.\n */\nconst cache_marker = (hit: boolean): string => {\n const word = hit ? \"hit\" : \"miss\";\n if (!PRETTY) return word;\n return `${hit ? C_HIT : C_MISS}${word}${C_RESET}${C_GREEN}`;\n};\n\n/**\n * Format the load stats (`v=N replayed=N snaps=N patches=N`) for the load\n * trace. Muted gray in pretty mode so the cache marker reads as the most\n * important cue; plain mode returns the bare text.\n *\n * - `v` — stream head version (the version of the last event applied)\n * - `replayed` — events processed by THIS load past the cache point\n * - `snaps` — cumulative snapshots taken on this stream\n * - `patches` — events since the last snap (snap-policy accumulator)\n */\nconst stats_marker = (\n version: number,\n replayed: number,\n snaps: number,\n patches: number\n): string => {\n const text = `v=${version} replayed=${replayed} snaps=${snaps} patches=${patches}`;\n if (!PRETTY) return text;\n return `${C_DRAIN}${text}${C_RESET}${C_GREEN}`;\n};\n\n/**\n * Format the as-of marker for time-travel loads. Surfaces the active filter\n * fields (before id, created_before/after timestamps, limit) so an operator\n * can tell at a glance which slice was loaded. Empty `asOf` returns \"\" —\n * non-time-travel loads skip the marker entirely.\n */\nconst as_of_marker = (asOf: AsOf | undefined): string => {\n if (!asOf) return \"\";\n const parts: string[] = [];\n if (asOf.before !== undefined) parts.push(`before=${asOf.before}`);\n if (asOf.created_before !== undefined)\n parts.push(`created_before=${asOf.created_before.toISOString()}`);\n if (asOf.created_after !== undefined)\n parts.push(`created_after=${asOf.created_after.toISOString()}`);\n if (asOf.limit !== undefined) parts.push(`limit=${asOf.limit}`);\n return parts.length ? ` (as-of ${parts.join(\" \")})` : \" (as-of)\";\n};\n\n/**\n * Wraps an async function with optional `exit` and `entry` callbacks. Each\n * callback fires at the corresponding phase; both receive the call args, and\n * `exit` additionally receives the resolved result. Used to layer\n * `logger.trace` calls onto bare ops without changing their signatures.\n */\nconst traced = <F extends AsyncFn>(\n inner: F,\n exit?: (result: Awaited<ReturnType<F>>, ...args: Parameters<F>) => void,\n entry?: (...args: Parameters<F>) => void\n): F =>\n (async (...args: Parameters<F>) => {\n entry?.(...args);\n const result = (await inner(...args)) as Awaited<ReturnType<F>>;\n exit?.(result, ...args);\n return result;\n }) as F;\n\n/**\n * Selects bare or traced event-sourcing handlers. Called once by the\n * orchestrator constructor.\n */\nexport function build_es(\n logger: Logger,\n correlator: Correlator = default_correlator,\n patch_fn: PatchFn = es.bare_patch\n): EsOps {\n // The app's correlator and patch step are baked into load and action, so\n // callers don't thread them; a per-call correlator wins when it is set.\n const bound_action: EsOps[\"action\"] = (\n me,\n action_name,\n target,\n payload,\n options\n ) =>\n es.action(\n me,\n action_name,\n target,\n payload,\n { ...options, correlator: options?.correlator ?? correlator },\n patch_fn\n );\n const bound_load: EsOps[\"load\"] = (me, target, callback) =>\n es.load(me, target, callback, patch_fn);\n if (logger.level !== \"trace\") {\n return {\n snap: es.snap,\n load: bound_load,\n action: bound_action,\n tombstone: es.tombstone,\n };\n }\n return {\n snap: traced(es.snap, undefined, (snapshot) => {\n logger.trace(\n es_caption(\n \"snap\",\n C_MAGENTA,\n `${snapshot.event!.stream}@${snapshot.event!.version}`\n )\n );\n }),\n load: traced(bound_load, (result, _me, target) => {\n const stats = stats_marker(\n result.version,\n result.replayed,\n result.snaps,\n result.patches\n );\n logger.trace(\n es_caption(\n \"load\",\n C_GREEN,\n `${target.stream}${as_of_marker(target.asOf)} ${cache_marker(result.cache_hit)} ${stats}`\n )\n );\n }),\n action: traced(\n bound_action,\n (snapshots) => {\n // A loaded snapshot (the action emitted nothing) has no `patch`;\n // each event is named with the stream it was appended to.\n if (snapshots[0].patch)\n logger.trace(\n snapshots.map((s) => s.event!.data),\n es_caption(\n \"committed\",\n C_ORANGE,\n snapshots\n .map((s) => `${s.event!.stream}.${s.event!.name}`)\n .join(\", \")\n )\n );\n },\n (_me, action, target, payload) => {\n logger.trace(\n payload as object,\n es_caption(\"action\", C_BLUE, `${target.stream}.${action}`)\n );\n }\n ),\n tombstone: traced(es.tombstone, (committed, stream) => {\n if (committed)\n logger.trace(\n es_caption(\"tombstoned\", C_ORANGE, `${stream}@${committed.version}`)\n );\n }),\n };\n}\n\n/**\n * Selects bare or traced drain-pipeline ops. Called once by the orchestrator\n * constructor.\n */\nexport function build_drain<TEvents extends Schemas>(\n logger: Logger\n): DrainOps<TEvents> {\n // Cycle-level tracing happens in `DrainController.drain()` via\n // {@link trace_cycle} — claim/fetch/ack/block all flow into one log\n // line per cycle to give the operator a single atomic narrative.\n // `subscribe` stays decorated because it's driven from correlate-\n // cycle (not from run_drain_cycle) and doesn't fit the cycle shape.\n return {\n claim: drain.claim,\n fetch: drain.fetch,\n ack: drain.ack,\n block: drain.block,\n subscribe:\n logger.level !== \"trace\"\n ? drain.subscribe\n : traced(drain.subscribe, (result, streams) => {\n if (!result.subscribed) return;\n // Caption mirrors `drained`: lane in the caption when the\n // whole batch shares a single non-default lane. Mixed-lane\n // batches (rare — different correlated targets resolving\n // to different lanes in one scan) fall back to per-stream\n // `[lane]` tags, default-lane streams stay bare either way.\n const lanes = new Set(streams.map((s) => s.lane ?? \"default\"));\n const uniform_lane =\n lanes.size === 1 ? streams[0]?.lane : undefined;\n const data = streams\n .map(({ stream, lane }) =>\n uniform_lane || !lane || lane === \"default\"\n ? hue(C_STREAM, stream)\n : `${hue(C_STREAM, stream)}${dim(`[${lane}]`)}`\n )\n .join(\" \");\n logger.trace(\n `${drain_caption(\"correlated\", uniform_lane)} ${data}`\n );\n }),\n };\n}\n\n/**\n * Emit one cycle-level drain trace summarizing what happened in a\n * single `run_drain_cycle` pass. Per-stream rendering shape — outcome +\n * post-state anchored on the right:\n *\n * stream<-source [events] ✓ @<acked-at> — full success\n * stream<-source [events] ✗ @<failed-at>/<retry> (error) — total failure → blocked\n * stream<-source [events] ⚠ @<failed-at>/<retry> (error) — total failure → retrying\n * stream<-source [events] ✓ @<acked-at> ✗ @<failed-at>/<retry> (error) — partial then blocked\n * stream<-source [events] ✓ @<acked-at> ⚠ @<failed-at>/<retry> (error) — partial then retrying\n * stream<-source ⊘ @<at>/<retry> — deferred (backoff)\n *\n * Partial-success-then-failure is the dual-outcome case: events\n * 1..K succeeded (watermark advanced to K), event K+1 threw. The\n * trace renders both the lime `✓ @K` and the red/amber `✗`/`⚠ @K+1`\n * on the same line so an operator sees \"we made progress *and* then\n * something broke\" at a glance.\n *\n * Lane prefixes the caption in lilac when non-default. The outcome\n * marker and its adjacent post-state share the marker's color so the\n * eye reads \"outcome + where it landed\" as one unit. Per-stream\n * `[events]` and `(error)` stay dim — secondary context.\n */\nexport function trace_cycle<TEvents extends Schemas>(\n logger: Logger,\n leased: ReadonlyArray<{\n readonly stream: string;\n readonly at: number;\n readonly retry: number;\n readonly lane?: string;\n }>,\n fetched: ReadonlyArray<{\n readonly stream: string;\n readonly source?: string;\n readonly events: ReadonlyArray<{\n readonly id: number;\n readonly name: keyof TEvents;\n }>;\n }>,\n handled: ReadonlyArray<{\n readonly lease: { readonly stream: string };\n readonly error?: string;\n readonly block?: boolean;\n readonly failed_at?: number;\n }>,\n acked: ReadonlyArray<{ readonly stream: string; readonly at: number }>,\n blocked: ReadonlyArray<{ readonly stream: string; readonly error: string }>\n): void {\n if (logger.level !== \"trace\" || !leased.length) return;\n const lane = leased[0]?.lane;\n const fetch_by_stream = new Map(fetched.map((f) => [f.stream, f]));\n const acked_by_stream = new Map(acked.map((a) => [a.stream, a.at]));\n const blocked_by_stream = new Map(blocked.map((b) => [b.stream, b.error]));\n // Handled-with-error stays a single index now: `block` discriminates\n // the marker (✗ vs ⚠); the failure exists independently of whether\n // ack happened.\n const failed_by_stream = new Map(\n handled.filter((h) => h.error).map((h) => [h.lease.stream, h] as const)\n );\n const detail = leased\n .map(({ stream, at, retry }) => {\n const f = fetch_by_stream.get(stream);\n // Target stream in yellow so the operator's eye lands on \"which\n // stream did this happen on?\" first; source (the events' origin)\n // stays dim — secondary info.\n const key = f?.source\n ? `${hue(C_STREAM, stream)}${dim(`<-${f.source}`)}`\n : hue(C_STREAM, stream);\n const events = f?.events.length\n ? ` ${dim(\n `[${f.events.map(({ id, name }) => `#${id} ${String(name)}`).join(\", \")}]`\n )}`\n : \"\";\n // Build ack + fail segments independently — both can fire for\n // the same stream in the partial-success-then-failure case.\n const acked_at = acked_by_stream.get(stream);\n const ack_part =\n acked_at !== undefined\n ? hue(C_HIT, `✓ @${acked_at}`) // ✓ + new at in lime\n : \"\";\n const failure = failed_by_stream.get(stream);\n let fail_part = \"\";\n if (failure) {\n // Failed event id when known (per-event path), else falls back\n // to lease.at — the post-fetch watermark — for batch-mode\n // total failures where no single event is \"the one.\"\n const failed_at = failure.failed_at ?? at;\n const blocked_error = blocked_by_stream.get(stream);\n if (blocked_error !== undefined) {\n fail_part = `${hue(C_ERR, `✗ @${failed_at}/${retry}`)} ${dim(`(${blocked_error})`)}`;\n } else {\n fail_part = `${hue(C_MISS, `⚠ @${failed_at}/${retry}`)} ${dim(`(${failure.error})`)}`;\n }\n }\n let tail: string;\n if (ack_part && fail_part) tail = ` ${ack_part} ${fail_part}`;\n else if (ack_part) tail = ` ${ack_part}`;\n else if (fail_part) tail = ` ${fail_part}`;\n else tail = ` ${dim(`⊘ @${at}/${retry}`)}`; // nothing happened\n return `${key}${events}${tail}`;\n })\n .join(\", \");\n logger.trace(`${drain_caption(\"drained\", lane)} ${detail}`);\n}\n","/**\n * Reaction dispatch — what runs inside the drain pipeline once `run_drain_cycle`\n * has fetched events for a leased stream. Two shapes:\n *\n * - per-event `handle`: walks payloads sequentially, running each handler\n * inside the reaction scope so `action()` threads `reactingTo`\n * - bulk `handle_batch`: hands every event for a static-target projection to\n * a single batch callback, enabling one-transaction replays\n *\n * Both finish through the drain's `finalize`, the one retry-or-block\n * decision for every per-stream failure. A handler steers its outcome by\n * throwing `DeferSignal` (hold until due) or {@link CloseSignal} (retire the\n * stream); dispatch turns either into a `HandleResult`.\n */\n\nimport type { ReactionScope } from \"../scoped.js\";\nimport { DeferSignal } from \"../types/errors.js\";\nimport type {\n Actor,\n BatchHandler,\n Committed,\n Lease,\n Logger,\n ReactionPayload,\n Schemas,\n} from \"../types/index.js\";\nimport { resolve_defer_at } from \"./defer-config.js\";\nimport { finalize, type Handle, type HandleBatch } from \"./drain-cycle.js\";\n\n/**\n * The control-flow signal a reaction handler throws to *close* a stream.\n * Like `DeferSignal` it rides the dispatcher's\n * `try/catch`, but where a defer holds the stream for later, a close asks the\n * orchestrator to retire it: `build_handle` turns the signal into a\n * `HandleResult.close` (a {@link CloseTarget}), `run_drain_cycle` acks the\n * triggering event and collects the target, and the `DrainController` hands it\n * to the orchestrator's `on_close` callback, which runs the same\n * `run_close_cycle` machinery as `app.close`.\n *\n * Internal: the compiled autoclose reaction throws it. Closing stays an\n * orchestrator capability — reactions only *signal* the intent, so the public\n * reaction-scoped `IAct` gains no `close`.\n *\n * The autoclose reaction runs on a **synthetic stream** (`source` = the\n * aggregate, `target` = a per-aggregate `__autoclose__` key) so it never\n * shares a watermark with the aggregate's own reactions. That makes the close\n * *target* distinct from the reaction's lease stream, so the signal carries the\n * stream to close explicitly (`stream`); when omitted (a user reaction closing\n * its own stream) it defaults to the lease stream.\n */\nexport class CloseSignal extends Error {\n /**\n * Stream to close. Omitted → the reaction's own lease stream (a self-close).\n * The synthesized autoclose reaction sets it to the aggregate stream, since\n * its lease runs on a synthetic `__autoclose__` target.\n */\n readonly stream?: string;\n /** Optional archive callback to run while the stream is guarded. */\n readonly archive?: () => Promise<void>;\n /**\n * Watermark to ack the requesting reaction to before the close runs. The\n * close-cycle safety guard skips a stream whose subscriptions (matched by\n * source) lag the head; the autoclose reaction's `source` is the aggregate,\n * so it must advance its own watermark to the live head id it evaluated\n * against — otherwise it blocks its own close. Defaults to the triggering\n * event id when omitted.\n */\n readonly at?: number;\n /**\n * Windowed close: prune events older than this cutoff behind\n * the closest safe snapshot instead of retiring the stream. Thrown by\n * the autoclose reaction of a `.autocloses({ keep })` state; flows\n * into {@link CloseTarget.before}. Omitted → a full close.\n */\n readonly before?: Date;\n /**\n * Revisit the requesting reaction at this time. Only useful with an `at`\n * below the head: a reaction runs only when an event is waiting for it.\n */\n readonly defer?: Date;\n\n constructor(opts?: {\n stream?: string;\n archive?: () => Promise<void>;\n at?: number;\n before?: Date;\n defer?: Date;\n }) {\n super(\"reaction requested close\");\n this.name = \"CloseSignal\";\n this.stream = opts?.stream;\n this.archive = opts?.archive;\n this.at = opts?.at;\n this.before = opts?.before;\n this.defer = opts?.defer;\n }\n}\n\n/**\n * What the dispatcher needs from the orchestrator: a logger for retry and\n * error breadcrumbs, and the scope a handler runs inside.\n */\nexport type ReactionDeps<\n TEvents extends Schemas,\n TActions extends Schemas,\n TActor extends Actor = Actor,\n> = {\n readonly logger: Logger;\n /**\n * What a handler runs inside — its `IAct` facade and its triggering-event\n * context — assembled by the orchestrator. How either half works is not\n * this module's business; it receives the scope whole and calls it.\n */\n readonly reaction_scope: ReactionScope<TEvents, TActions, TActor>;\n};\n\n/**\n * Builds the per-event reaction dispatcher passed to `run_drain_cycle`.\n *\n * The triggering event is installed as ambient context around each handler\n * call, so `action()` resolves it as `reactingTo`. Ambient\n * rather than bound to the `IAct` argument, so a handler that dispatches\n * through a captured `app` inherits the chain too.\n */\nexport function build_handle<\n TEvents extends Schemas,\n TActions extends Schemas,\n TActor extends Actor = Actor,\n>(deps: ReactionDeps<TEvents, TActions, TActor>): Handle<TEvents> {\n const { logger, reaction_scope } = deps;\n return async (lease, payloads) => {\n if (payloads.length === 0) return { lease, handled: 0, acked_at: lease.at };\n\n const stream = lease.stream;\n // One event fans out to one payload per matching reaction, and the\n // watermark may only advance past an event once EVERY reaction on it\n // has handled it — acking mid-group would silently drop the remaining\n // reactions on redelivery. Track the last payload index per\n // event id (payloads arrive in event order) so `at` advances exactly\n // when a group completes; `handled` counts completed events, not\n // payloads, so a mid-group failure with no completed events is a\n // no-progress result (no ack, retry counter advances toward\n // `blockOnError` instead of resetting on every partial pass).\n const last_index_of = new Map<number, number>();\n for (let i = 0; i < payloads.length; i++)\n last_index_of.set(payloads[i].event.id, i);\n let at = lease.at;\n let handled = 0;\n\n if (lease.retry > 0)\n logger.warn(\n `Retrying ${stream}@${payloads.at(0)!.event.id} (${lease.retry}).`\n );\n\n for (let i = 0; i < payloads.length; i++) {\n const payload = payloads[i];\n const { event, handler } = payload;\n try {\n // Scoped per payload, not hoisted to the lease: the context has to\n // unwind with the handler so it never reaches the drain cycle, and\n // work a handler started without awaiting has to resume into its\n // own event's frame.\n await reaction_scope.run(event as Committed<Schemas, string>, () =>\n handler(event, stream, reaction_scope.app)\n );\n if (last_index_of.get(event.id) === i) {\n at = event.id;\n handled++;\n }\n } catch (error) {\n // A defer is not a failure: hold the triggering events pending\n // (exclude from ack via `defer`), don't bump `retry`, and re-visit\n // the stream at the carried due-time. `acked_at` is unused on\n // the defer path — drain never acks a deferred result.\n if (error instanceof DeferSignal) {\n let defer: number;\n try {\n defer = resolve_defer_at<TEvents>(error.when, event);\n } catch (invalid) {\n // A schedule the schema rejects fails this reaction like any\n // handler error, as the declarative `.defer` path does; thrown\n // from here it would void the whole drain pass.\n return finalize(\n lease,\n handled,\n at,\n invalid as Error,\n payload.options,\n logger,\n event.id\n );\n }\n return { lease, handled, acked_at: at, defer };\n }\n // A close request advances past the triggering event (so the\n // requesting reaction isn't counted as in-flight by the close-cycle\n // guard) and hands the target to the orchestrator's on_close.\n if (error instanceof CloseSignal)\n return {\n lease,\n handled: handled + 1,\n // Advance to the live head the handler evaluated against (when\n // provided) so the close-cycle guard sees this reaction caught up.\n acked_at: error.at ?? event.id,\n defer: error.defer?.getTime(),\n // Close the signalled stream (the autoclose reaction's aggregate,\n // which differs from its synthetic lease stream); a self-closing\n // user reaction omits it and closes its own lease stream. A\n // carried `before` makes it a windowed close (prune, not retire).\n close: {\n stream: error.stream ?? stream,\n archive: error.archive,\n before: error.before,\n },\n };\n return finalize(\n lease,\n handled,\n at,\n error as Error,\n payload.options,\n logger,\n event.id\n );\n }\n }\n return finalize(lease, handled, at, undefined, payloads[0].options, logger);\n };\n}\n\n/**\n * Builds the bulk reaction dispatcher passed to `run_drain_cycle`. All events\n * for a static-target projection are handed to a single callback so the\n * projection can do one transaction per drain (catch-up replays especially).\n */\nexport function build_handle_batch<TEvents extends Schemas>(\n logger: Logger\n): HandleBatch<TEvents> {\n return async (\n lease: Lease,\n payloads: ReactionPayload<TEvents>[],\n batchHandler: BatchHandler<TEvents>\n ) => {\n const stream = lease.stream;\n // One payload per (event, reaction) pair: an event with several\n // reactions on this target arrives several times in a row. The batch\n // handler gets each event once, in order — handing it the duplicates\n // made a non-idempotent batch count every event once per reaction.\n // The per-event path groups by id for the same reason.\n const events: Committed<TEvents, keyof TEvents & string>[] = [];\n const seen = new Set<number>();\n for (const p of payloads) {\n if (seen.has(p.event.id)) continue;\n seen.add(p.event.id);\n events.push(p.event as Committed<TEvents, keyof TEvents & string>);\n }\n const options = payloads[0].options;\n\n if (lease.retry > 0)\n logger.warn(`Retrying batch ${stream}@${events[0].id} (${lease.retry}).`);\n\n try {\n await batchHandler(events, stream);\n return finalize(\n lease,\n events.length,\n events.at(-1)!.id,\n undefined,\n options,\n logger\n );\n } catch (error) {\n return finalize(lease, 0, lease.at, error as Error, options, logger);\n }\n };\n}\n","/**\n * Synthesis of the online close-the-books reaction. `.autocloses(policy)`\n * is not a sweep: it is a reaction on every event the declaring state owns\n * that evaluates the policy against the LIVE head (so a reopened stream\n * re-evaluates correctly), defers to the cooldown's earliest opening\n * (`head.created + the policy's min after`), and closes via `CloseSignal`\n * once the policy holds.\n *\n * Runs at build time — after the registry is fully merged and before the\n * orchestrator classifies it — so the synthesized dynamic resolver is\n * discovered by `classify_registry` and its target stream subscribed. The\n * registry is complete once the builder finishes; the orchestrator never\n * mutates it.\n */\n\nimport { isStreamName } from \"../adapter.js\";\nimport { store } from \"../ports.js\";\nimport { DeferSignal } from \"../types/errors.js\";\nimport type {\n AutocloseConfig,\n Reaction,\n Registry,\n SchemaRegister,\n Schemas,\n State,\n} from \"../types/index.js\";\nimport { SNAP_EVENT, TOMBSTONE_EVENT } from \"../types/index.js\";\nimport { days_after, days_before_now } from \"./autoclose-policy.js\";\nimport { in_autoclose_window, next_window_open } from \"./autoclose-window.js\";\nimport { DEFAULT_MAX_RETRIES } from \"./config.js\";\nimport { CloseSignal } from \"./reaction-dispatch.js\";\n\n/**\n * Prefix for the synthetic per-aggregate stream the autoclose reaction\n * runs on. `target = \\`${AUTOCLOSE_TARGET_PREFIX}${aggregate}\\``, `source =\n * aggregate` — a watermark distinct from the aggregate's own reactions, so\n * an autoclose defer never short-circuits them. Internal; not a public\n * surface.\n */\nexport const AUTOCLOSE_TARGET_PREFIX = \"__autoclose__:\";\n\n/**\n * Inject one synthesized autoclose reaction per `.autocloses(...)` state\n * into the registry's event registers. The handler resolves ports at call\n * time (`store()`), so the reaction is orchestrator-agnostic. The reactions\n * are synthesized once into the shared registry, so nothing\n * per-Act is captured here — the off-hours window is read from the running\n * Act at resolution time via the injected `read_window`.\n */\nexport function synthesize_autoclose_reactions<\n TSchemaReg extends SchemaRegister<TActions>,\n TEvents extends Schemas,\n TActions extends Schemas,\n>(\n registry: Registry<TSchemaReg, TEvents, TActions>,\n states: ReadonlyMap<string, State<any, any, any>>,\n /**\n * Reads the *running* Act's off-hours window. Injected rather than\n * imported: these reactions are synthesized once into the shared\n * registry and run by every Act built from that builder, so the window\n * has to be resolved per call, and `internal/` never reaches for\n * ambient state itself.\n */\n read_window: () => AutocloseConfig[\"autocloseWindow\"]\n): void {\n for (const st of states.values()) {\n const predicate = st.autoclose;\n if (!predicate) continue;\n const after_windows = st.autoclose_after_windows!;\n const keep_days = st.autoclose_keep_days;\n const archiver = st.archive;\n const reaction: Reaction<TEvents> = {\n // Run on a SYNTHETIC stream — `source` is the aggregate, `target` is a\n // per-aggregate `__autoclose__` key — so the autoclose reaction never\n // shares a watermark with the aggregate's own reactions. A shared\n // watermark would let autoclose's defer short-circuit the aggregate's\n // other reactions (the \"a defer affects all reactions on a stream\"\n // hazard). The close still targets the aggregate (`source`).\n // An anchored stream name would read as a pattern, and a store may refuse\n // it at subscribe, stopping every reaction. Such a stream has no\n // autoclose: `app.close` still closes it.\n resolver: (e) =>\n isStreamName(e.stream)\n ? {\n target: `${AUTOCLOSE_TARGET_PREFIX}${e.stream}`,\n source: e.stream,\n }\n : undefined,\n // Never block on autoclose: a transient query/store error should retry,\n // not quarantine the synthetic stream.\n options: { blockOnError: false, maxRetries: DEFAULT_MAX_RETRIES },\n handler: async (event) => {\n const aggregate = event.stream;\n // Off-hours gating: outside the window, park until the window\n // opens. Derived from the window itself — no polling cadence.\n //\n // Read from the running Act's frame, not from a closure. These\n // reactions are synthesized once into the shared registry and\n // handed by reference to every Act built from the same builder, so\n // a captured window would be the first-built Act's for all of them\n // — and the documented multi-tenant shape is one builder built per\n // tenant.\n const window = read_window();\n if (!in_autoclose_window(window, new Date()))\n throw new DeferSignal({ at: next_window_open(window!, new Date()) });\n // Every policy keys on the *domain* head/count, so snapshots are\n // excluded unconditionally — matching `scan_stream_heads` in\n // close-cycle.ts. `snap()` commits a `__snapshot__` at a higher id\n // right after the triggering domain event, so a terminal commit that\n // crosses a `.snap()` boundary would otherwise make the snapshot the\n // head: `is` never matches (`head.name === \"__snapshot__\"`) and never\n // recovers, `after` measures the cooldown from the snapshot's\n // timestamp, and `reaches:N` counts snapshot events toward N. Only\n // rolling-window (`keep`) policies additionally fetch the tail: the\n // prune decision keys on the oldest *domain* event — after a prune the\n // oldest surviving event is the boundary snapshot, whose age says\n // nothing about whether another prune would be productive.\n const stats = await store().query_stats([aggregate], {\n count: true,\n tail: keep_days !== undefined ? true : undefined,\n exclude: [TOMBSTONE_EVENT, SNAP_EVENT],\n });\n const entry = stats.get(aggregate);\n // No live (non-tombstone) head → already closed, nothing to do.\n if (!entry) return;\n const head = entry.head;\n // `count` is always present — query_stats is called with\n // `count: true` above, so the option contract guarantees it.\n if (predicate(aggregate, head, entry.count!))\n throw new CloseSignal({\n stream: aggregate,\n archive: archiver ? () => archiver(aggregate, head) : undefined,\n // Ack this reaction's own watermark to the live head so the\n // close-cycle guard (which matches subscriptions by source =\n // aggregate) sees it caught up instead of blocking its own close.\n at: head.id,\n });\n // Rolling window: when the oldest domain event has aged out of the\n // window, stage a windowed close — prune the prefix older than the\n // cutoff behind the closest safe snapshot. `tail` is present\n // whenever the stats entry is (same non-excluded event set).\n if (keep_days !== undefined) {\n const cutoff = days_before_now(keep_days);\n if (entry.tail!.created < cutoff) {\n // A terminate window still ahead needs a wake, and only a pending\n // event can give one: hold the head unconsumed and revisit. The\n // hold also caps the prune below the head, which a later `is` or\n // `after` has to read. The first visit parks on the real tail.\n const waiting = after_windows.some(\n (days) => days_after(head.created, days).getTime() > Date.now()\n );\n throw new CloseSignal({\n stream: aggregate,\n before: cutoff,\n archive: archiver\n ? () => archiver(aggregate, head, cutoff)\n : undefined,\n at: waiting ? head.id - 1 : head.id,\n defer: waiting ? days_after(new Date(), 1) : undefined,\n });\n }\n }\n // Not eligible yet: park on the earliest derivable due-time — the\n // day a terminate cooldown opens and/or the day the oldest\n // domain event ages out of the rolling window. Neither → wait for\n // the next event to re-trigger (e.g. a `reaches` threshold).\n const dues: Date[] = [];\n for (const days of after_windows)\n dues.push(days_after(head.created, days));\n if (keep_days !== undefined)\n dues.push(days_after(entry.tail!.created, keep_days));\n // Only defer to a FUTURE due-time. A due already in the past (the\n // stream idled longer than the cooldown while the AND-combined\n // predicate stayed unmet) can never be excluded by `claim`, which\n // skips only future `deferred_at` — so a past defer would be\n // re-claimed every cycle (perpetual query_stats burn). When\n // nothing is future, fall through and return: advance the watermark\n // and wait for the next event to re-trigger.\n const future = dues\n .map((d) => d.getTime())\n .filter((t) => t > Date.now());\n if (future.length)\n throw new DeferSignal({ at: new Date(Math.min(...future)) });\n },\n };\n const key = `__autoclose_${st.name}`;\n for (const event_name of Object.keys(st.events)) {\n registry.events[event_name as keyof TEvents]?.reactions.set(\n key,\n reaction as Reaction<TEvents, keyof TEvents>\n );\n }\n }\n}\n","/**\n * Pure orchestration of the close-the-books flow: scan stream heads,\n * partition by reaction safety, guard with tombstones, optionally seed\n * restart state, run user archive callbacks, atomically truncate, and\n * update the cache.\n *\n * Also home to the pieces a closer needs around the cycle: the per-stream\n * {@link CloseLock} and the bounded {@link catch_up_correlation}. The Act\n * orchestrator only wires its ports in and emits `\"closed\"`.\n */\n\nimport { isStreamName } from \"../adapter.js\";\nimport { cache, store } from \"../ports.js\";\nimport type {\n CloseResult,\n CloseTarget,\n Logger,\n Schema,\n State,\n} from \"../types/index.js\";\nimport { SNAP_EVENT, TOMBSTONE_EVENT } from \"../types/index.js\";\nimport { AUTOCLOSE_TARGET_PREFIX } from \"./autoclose-reaction.js\";\nimport type { EsOps } from \"./event-sourcing.js\";\nimport { walk_streams } from \"./walk-streams.js\";\n\n/**\n * Dependencies the close cycle needs from the Act orchestrator. Decoupled\n * from `Act` itself so the cycle can be exercised from tests in isolation.\n */\nexport type CloseCycleDeps = {\n /** Whether any event has a reaction; without one nothing can be pending. */\n readonly reactive: boolean;\n readonly event_to_state: ReadonlyMap<string, State<any, any, any>>;\n readonly load: EsOps[\"load\"];\n readonly tombstone: EsOps[\"tombstone\"];\n readonly logger: Logger;\n /**\n * Correlation id for the close transaction. Caller (`Act.close`)\n * computes this via the configured {@link Correlator}, so close\n * commits share the user's chosen id scheme instead of stamping a\n * UUID.\n */\n readonly correlation: string;\n /**\n * Page size for the safety probe's `query_streams` pagination.\n * Defaults to {@link SAFETY_PROBE_PAGE_SIZE}; production callers omit\n * it, tests set a small value to exercise the multi-page path.\n */\n readonly probe_page_size?: number;\n /** See {@link catch_up_correlation}. */\n readonly catch_up_correlation: (until: number) => Promise<number>;\n /** See {@link CloseLock}; identity when run in isolation. */\n readonly with_stream_lock?: <T>(\n stream: string,\n work: () => Promise<T>\n ) => Promise<T>;\n /**\n * Drop retired streams from correlate's in-process \"already subscribed\"\n * set, so a later scan re-issues `subscribe()` for them. An operator may\n * reclaim a retired subscription row while this process runs; forgetting\n * keeps the in-process view from outliving it, which would otherwise stop\n * delivery to a target named after the stream. Skipped in isolation.\n */\n readonly forget_subscribed?: (streams: string[]) => void;\n};\n\n/**\n * Scan window and pass cap for {@link catch_up_correlation}. Bounded, so a\n * close behind a large backlog skips the stream (the documented retryable\n * outcome) rather than scanning the whole log inside an operator call.\n */\nconst CLOSE_CATCH_UP_LIMIT = 1000;\nconst CLOSE_CATCH_UP_PASSES = 20;\n\n/**\n * Advance correlation until the read cursor reaches `until`, and report\n * where it landed. The safety probe cannot judge a subscription's pending\n * work over events correlate has not resolved yet, and an autoclose often\n * fires from an uncorrelated trigger; anything still above the cursor is\n * held back as pending.\n *\n * Stops as soon as a pass makes no progress (the log has no more to give),\n * and after {@link CLOSE_CATCH_UP_PASSES} windows.\n */\nexport async function catch_up_correlation(\n cursor: { readonly checkpoint: number; arm(): void },\n correlate: (limit: number) => Promise<unknown>,\n until: number\n): Promise<number> {\n for (\n let pass = 0;\n pass < CLOSE_CATCH_UP_PASSES && cursor.checkpoint < until;\n pass++\n ) {\n const before = cursor.checkpoint;\n // Force the scan: the armed flag can't say whether a tail exists.\n cursor.arm();\n await correlate(CLOSE_CATCH_UP_LIMIT);\n if (cursor.checkpoint <= before) break;\n }\n return cursor.checkpoint;\n}\n\n/**\n * Per-stream serialization for close critical sections: two closers of the\n * same stream never prune or archive concurrently (a manual close has no\n * drain lease to exclude an autoclose), and a second full closer never\n * mistakes the first one's tombstone for an interrupted close. Different\n * streams proceed in parallel. One instance per Act.\n */\nexport class CloseLock {\n private readonly _tails = new Map<string, Promise<unknown>>();\n\n /** Run `work` after every earlier close of `stream` has settled. */\n run<T>(stream: string, work: () => Promise<T>): Promise<T> {\n const prev = this._tails.get(stream) ?? Promise.resolve();\n // Chain after the previous holder however it settled, so a failed close\n // can't wedge the lock.\n const next = prev.then(work, work);\n this._tails.set(stream, next);\n // Drop the tail once settled, unless a later waiter replaced it.\n const cleanup = () => {\n if (this._tails.get(stream) === next) this._tails.delete(stream);\n };\n next.then(cleanup, cleanup);\n return next;\n }\n}\n\n/**\n * Page size for the safety probe's keyset pagination over the\n * subscriptions table. Above `query_streams`'s default `limit` of 100\n * to keep the round-trip count low while bounding per-page work.\n */\nconst SAFETY_PROBE_PAGE_SIZE = 1000;\n\n/**\n * Per-stream scan result: the latest domain event's metadata. The scan\n * reads `query_stats` heads with snapshots and tombstones excluded, so\n * `last_event_name` is always a domain event's name; `resumed_guard` marks\n * a stream whose real head is a tombstone from an interrupted close.\n */\ntype StreamHead = {\n readonly max_id: number;\n readonly version: number;\n readonly last_event_name: string;\n /**\n * Set when the stream already carries a tombstone but still holds domain\n * events — a close that wrote its guard and was then interrupted before\n * truncating (a throwing archive callback, or a `truncate` that failed).\n * Carries the existing guard's event id so the retry resumes at Phase 4\n * instead of re-tombstoning (which would fail the version guard) or being\n * dropped from the scan entirely.\n */\n readonly resumed_guard?: { readonly id: number };\n};\n\n/**\n * Run the full close cycle for the given targets. Caller owns the\n * lifecycle event emission.\n *\n * Targets carrying a `before` cutoff take the **windowed** branch — a\n * pure prefix delete behind an existing snapshot (see\n * {@link run_windowed_closes}); the rest run the guarded\n * tombstone/restart pipeline below.\n */\nexport async function run_close_cycle(\n targets: CloseTarget[],\n deps: CloseCycleDeps\n): Promise<CloseResult> {\n // Caller (Act.close) filters empty targets; run_close_cycle assumes at\n // least one target.\n const target_map = new Map(targets.map((t) => [t.stream, t]));\n for (const t of target_map.values()) {\n if (t.before !== undefined && t.restart)\n throw new Error(\n `close: \\`before\\` and \\`restart\\` are mutually exclusive (stream \"${t.stream}\") — a windowed close keeps the stream live behind a real snapshot; restart reseeds it`\n );\n }\n const windowed = [...target_map.values()].filter(\n (t) => t.before !== undefined\n );\n const full = [...target_map.values()].filter((t) => t.before === undefined);\n const skipped: string[] = [];\n const windowed_result = windowed.length\n ? await run_windowed_closes(windowed, deps, skipped)\n : new Map();\n if (!full.length) return { truncated: windowed_result, skipped };\n const truncated = await with_stream_locks(\n full.map((t) => t.stream),\n deps,\n () => run_full_closes(full, target_map, deps, skipped)\n );\n // A tombstone seed retired the stream; a snapshot seed restarted it.\n const retired = [...truncated.entries()]\n .filter(([, r]) => r.committed.name === TOMBSTONE_EVENT)\n .map(([stream]) => stream);\n if (retired.length) deps.forget_subscribed?.(retired);\n for (const [stream, entry] of windowed_result) truncated.set(stream, entry);\n return { truncated, skipped };\n}\n\n/**\n * Run `work` holding the per-stream close lock of every stream in\n * `streams`. Locks are taken in sorted order, so two closers whose batches\n * share streams in a different order cannot each hold one and wait on the\n * other.\n */\nfunction with_stream_locks<T>(\n streams: string[],\n deps: CloseCycleDeps,\n work: () => Promise<T>\n): Promise<T> {\n const with_lock = deps.with_stream_lock ?? ((_stream, w) => w());\n return [...streams]\n .sort()\n .reduceRight<() => Promise<T>>(\n (inner, stream) => () => with_lock(stream, inner),\n work\n )();\n}\n\n/**\n * The guarded tombstone/restart pipeline (Phases 1-6), run while holding\n * every target stream's close lock.\n */\nasync function run_full_closes(\n full: CloseTarget[],\n target_map: Map<string, CloseTarget>,\n deps: CloseCycleDeps,\n skipped: string[]\n): Promise<CloseResult[\"truncated\"]> {\n const none: CloseResult[\"truncated\"] = new Map();\n const streams = full.map((t) => t.stream);\n\n // 1. Scan: find the latest non-tombstone event per stream\n const stream_info = await scan_stream_heads(streams);\n\n // 1b. A restart target whose state has sensitive fields can't be seeded\n // (an actorless load would redact them; a privileged one would put\n // plaintext where `forget` can't reach), so it is skipped, untouched,\n // before anything is written.\n for (const target of full) {\n if (!target.restart) continue;\n const info = stream_info.get(target.stream);\n if (!info) continue;\n const owner = deps.event_to_state.get(info.last_event_name);\n if (owner?.pii_aware) {\n deps.logger.error(\n `Refusing to close \"${target.stream}\" with restart: state \"${owner.name}\" carries sensitive fields, so a restart seed would persist redacted values while deleting the originals. Close it without restart to retire the stream, or leave it open.`\n );\n skipped.push(target.stream);\n stream_info.delete(target.stream);\n }\n }\n\n // 2. Partition: skip streams with pending reactions in flight\n const safe = await partition_by_safety(\n stream_info,\n deps.reactive,\n skipped,\n deps.probe_page_size ?? SAFETY_PROBE_PAGE_SIZE,\n deps.catch_up_correlation\n );\n if (!safe.length) return none;\n\n // 3. Guard: commit a tombstone with expectedVersion per safe stream.\n // Correlation comes from the orchestrator's configured correlator so\n // close commits share the app's id scheme.\n const { guarded, guard_events } = await guard_with_tombstones(\n safe,\n stream_info,\n deps.correlation,\n deps.tombstone,\n skipped\n );\n if (!guarded.length) return none;\n\n // 4. Seed: load final state for restart targets through the owning state\n const seed_states = await load_restart_seeds(\n guarded,\n target_map,\n stream_info,\n deps.event_to_state,\n deps.load,\n deps.logger\n );\n\n // 5. Archive: user-provided per-stream callback while guarded\n await run_archive_callbacks(guarded, target_map);\n\n // 5b. Re-check: truncate only streams whose head is still this close's\n // guard. The lock above serializes closers in this process; a closer in\n // another process can still resume our guard, finish first, and reseed\n // the stream, after which a commit can land on it. Truncating then would\n // delete that accepted commit.\n const still_guarded = await heads_still_guarded(\n guarded,\n guard_events,\n skipped\n );\n if (!still_guarded.length) return none;\n\n // 6. Truncate + seed: atomic per-store transaction\n return truncate_and_warm_cache(\n still_guarded,\n seed_states,\n guard_events,\n deps.correlation\n );\n}\n\n// Windowed branch — prune the prefix behind an existing snapshot\n\n/**\n * Run the windowed closes: probe the min consumer watermark per stream\n * (the `max_id` cap that keeps the boundary at/below what the laggiest\n * consumer has read), run archive callbacks against the cutoff, then\n * hand the boundary targets to {@link Store.truncate}.\n *\n * No tombstone guard and no cache touch — the cutoff is always in the\n * past, so a concurrently-written snapshot (`created = now`) can never\n * become the boundary: once the cutoff is fixed the boundary snapshot is\n * fixed, and the prefix below it is immutable. Concurrent appends land\n * at the head, above the boundary. Current state is unchanged, so the\n * cache stays warm. Streams the store skips (no qualifying snapshot)\n * are reported in `skipped`.\n */\nasync function run_windowed_closes(\n windowed: CloseTarget[],\n deps: CloseCycleDeps,\n skipped: string[]\n): Promise<CloseResult[\"truncated\"]> {\n // 1. Safety probe: how far may each stream be pruned (skipped when the\n // app has no reactions). A consumer with pending work caps at its\n // watermark; a caught-up one caps at the correlate checkpoint, since a\n // reaction to only some event types sits below the head with nothing\n // pending. Catching up first makes that cap as high as it can be.\n const checkpoint = deps.reactive\n ? await deps.catch_up_correlation(Number.MAX_SAFE_INTEGER)\n : -1;\n const min_at = deps.reactive\n ? await probe_min_watermarks(\n windowed.map((t) => t.stream),\n deps.probe_page_size ?? SAFETY_PROBE_PAGE_SIZE,\n checkpoint\n )\n : new Map<string, number>();\n\n // 2 + 3. Per stream, under its lock: archive only when the prune would\n // delete a prefix, then truncate. The lock plus that check make the\n // archive fire at most once per pruned range.\n const with_lock = deps.with_stream_lock ?? ((_stream, work) => work());\n const truncated: CloseResult[\"truncated\"] = new Map();\n for (const t of windowed) {\n const entry = await with_lock(t.stream, async () => {\n const max_id = min_at.get(t.stream);\n // Nothing to prune (see windowed_prune_pending): skip the archive\n // and report the stream skipped, as a no-op truncate would.\n if (!(await windowed_prune_pending(t.stream, t.before!, max_id)))\n return undefined;\n // Archive: user callback against the cutoff, run while the prefix\n // is still present. Sequential/fail-fast: a throw propagates to the\n // caller and leaves the stream un-truncated (no data loss).\n if (t.archive) await t.archive();\n // Boundary truncate: atomic per-store transaction; no seed.\n const result = await store().truncate([\n { stream: t.stream, before: t.before!, max_id },\n ]);\n return result.get(t.stream);\n });\n if (entry) truncated.set(t.stream, entry);\n else skipped.push(t.stream);\n }\n return truncated;\n}\n\n/**\n * Read-only probe: would a windowed truncate of `stream` at `before`\n * (optionally capped at `max_id`) delete a prefix? Mirrors the store's\n * boundary rule — the latest `__snapshot__` with `created < before` and,\n * when capped, `id <= max_id` — then reports whether any event sorts\n * strictly below that boundary. False when no snapshot qualifies (a\n * no-op truncate) or when the boundary is already the earliest event\n * (the prefix was pruned by a prior closer). This is the guard that\n * makes the windowed archive fire at most once per pruned range.\n */\nasync function windowed_prune_pending(\n stream: string,\n before: Date,\n max_id: number | undefined\n): Promise<boolean> {\n let boundary_id: number | undefined;\n let min_id: number | undefined;\n await store().query(\n (event) => {\n if (min_id === undefined || event.id < min_id) min_id = event.id;\n if (\n event.name === SNAP_EVENT &&\n event.created < before &&\n (max_id === undefined || event.id <= max_id) &&\n (boundary_id === undefined || event.id > boundary_id)\n )\n boundary_id = event.id;\n },\n { stream, stream_exact: true, with_snaps: true, after: -1 }\n );\n // No qualifying snapshot → nothing to prune behind. Otherwise a prune\n // is pending only when some event sorts below the boundary.\n return boundary_id !== undefined && min_id! < boundary_id;\n}\n\n/**\n * Min subscription watermark per target stream — the read-only probe\n * backing the windowed close's `max_id` cap. Pagination and source\n * matching mirror {@link partition_by_safety}; instead of flagging\n * pending streams it folds `min(at)` per stream. Streams with no\n * matching subscriptions are absent (no cap).\n */\nasync function probe_min_watermarks(\n streams: string[],\n page_size: number,\n checkpoint: number\n): Promise<Map<string, number>> {\n const min_at = new Map<string, number>();\n const matches = source_matcher();\n await walk_streams(\n store(),\n (position) => {\n // Pending work caps at the watermark; caught up caps at the\n // checkpoint; an unmarked row keeps the conservative watermark.\n const pending =\n position.correlated_at === undefined ||\n position.at < position.correlated_at;\n const cap = pending ? position.at : Math.max(position.at, checkpoint);\n for (const stream of streams) {\n if (matches(position.source, position.stream, stream)) {\n const prev = min_at.get(stream);\n if (prev === undefined || cap < prev) min_at.set(stream, cap);\n }\n }\n },\n { limit: page_size }\n );\n return min_at;\n}\n\n/**\n * Does a subscription with this `source` consume from `stream`? No source\n * consumes every stream; a literal source consumes only that name. Compiled\n * patterns are cached per matcher.\n */\nfunction source_matcher(): (\n source: string | undefined,\n target: string,\n stream: string\n) => boolean {\n const compiled = new Map<string, RegExp>();\n return (source, target, stream) => {\n if (!source) return true;\n if (isStreamName(source, target)) return source === stream;\n let re = compiled.get(source);\n if (!re) {\n re = new RegExp(source);\n compiled.set(source, re);\n }\n return re.test(stream);\n };\n}\n\n// Phase 1 — scan stream heads\n\nasync function scan_stream_heads(\n streams: string[]\n): Promise<Map<string, StreamHead>> {\n // The latest non-snapshot event per stream (heads-only, indexed): a\n // tombstone here marks a close that was interrupted after its guard.\n const stats = await store().query_stats(streams, {\n exclude: [SNAP_EVENT],\n });\n // Domain head, markers excluded. A stream absent here has no domain\n // events left, so a previous close ran to completion and there is\n // nothing to do. A stream present here whose `stats` head is a tombstone\n // was guarded and then interrupted — it must be resumed, not skipped.\n // `last_event_name` also has to come from this pass: the\n // restart-seed owner lookup needs the domain event, not the marker.\n const domain_heads = await store().query_stats(streams, {\n exclude: [SNAP_EVENT, TOMBSTONE_EVENT],\n });\n // The tombstone must expect the stream's real head version, which a\n // trailing `__snapshot__` raises by one. Everything else uses the domain\n // head, so the true head gets its own heads-only read.\n const true_heads = await store().query_stats(streams, {});\n const out = new Map<string, StreamHead>();\n for (const [stream, { head }] of domain_heads) {\n const marker_head = stats.get(stream)?.head;\n const interrupted = marker_head?.name === TOMBSTONE_EVENT;\n out.set(stream, {\n max_id: head.id,\n version: true_heads.get(stream)!.head.version,\n last_event_name: head.name as string,\n ...(interrupted ? { resumed_guard: { id: marker_head.id } } : {}),\n });\n }\n return out;\n}\n\n// Phase 2 — partition by safety\n\nasync function partition_by_safety(\n stream_info: Map<string, StreamHead>,\n reactive: boolean,\n skipped: string[],\n page_size: number,\n catch_up_correlation: (until: number) => Promise<number>\n): Promise<string[]> {\n if (!reactive) return [...stream_info.keys()];\n\n // Correlate the tail first (see `catch_up_correlation`); anything still\n // above the cursor afterwards is held back.\n let needed = -1;\n for (const info of stream_info.values())\n needed = Math.max(needed, info.max_id);\n const checkpoint = await catch_up_correlation(needed);\n const uncorrelated = new Set<string>();\n for (const [stream, info] of stream_info) {\n if (checkpoint < info.max_id) uncorrelated.add(stream);\n }\n\n // Over-matching a source only widens the pending set, the safe direction.\n const pending_set = new Set<string>();\n const matches = source_matcher();\n\n // Every page, so a lagging reaction past the first one still counts.\n await walk_streams(\n store(),\n (position) => {\n // Pending means what `claim` means: a mark above the watermark. An\n // unmarked row has nothing to wait for; the catch-up above has landed\n // every mark that was owed.\n const has_work =\n position.correlated_at !== undefined &&\n position.at < position.correlated_at;\n if (!has_work) return;\n // A parked autoclose reads the live head and consumes nothing, so it\n // has no work a full close would lose.\n if (position.stream.startsWith(AUTOCLOSE_TARGET_PREFIX)) return;\n for (const [stream, info] of stream_info) {\n if (\n matches(position.source, position.stream, stream) &&\n position.at < info.max_id\n )\n pending_set.add(stream);\n }\n },\n { limit: page_size }\n );\n\n const safe: string[] = [];\n for (const [stream] of stream_info) {\n if (pending_set.has(stream) || uncorrelated.has(stream))\n skipped.push(stream);\n else safe.push(stream);\n }\n return safe;\n}\n\n// Phase 3 — guard with tombstones\n\nasync function guard_with_tombstones(\n safe: string[],\n stream_info: Map<string, StreamHead>,\n correlation: string,\n tombstone: EsOps[\"tombstone\"],\n skipped: string[]\n): Promise<{\n guarded: string[];\n guard_events: Map<string, { id: number; stream: string }>;\n}> {\n const guarded: string[] = [];\n const guard_events = new Map<string, { id: number; stream: string }>();\n await Promise.all(\n safe.map(async (stream) => {\n const info = stream_info.get(stream)!;\n if (info.resumed_guard) {\n // Guard already written by the interrupted run — reuse it rather\n // than re-tombstoning (the version guard would reject it anyway).\n guarded.push(stream);\n guard_events.set(stream, { id: info.resumed_guard.id, stream });\n return;\n }\n const committed = await tombstone(stream, info.version, correlation);\n if (committed) {\n guarded.push(stream);\n guard_events.set(stream, { id: committed.id, stream });\n } else {\n // ConcurrencyError → another writer beat the guard\n skipped.push(stream);\n }\n })\n );\n return { guarded, guard_events };\n}\n\n// Phase 4 — load restart seeds\n\nasync function load_restart_seeds(\n guarded: string[],\n target_map: Map<string, CloseTarget>,\n stream_info: Map<string, StreamHead>,\n event_to_state: ReadonlyMap<string, State<any, any, any>>,\n load: EsOps[\"load\"],\n logger: Logger\n): Promise<Map<string, Schema>> {\n const seed_states = new Map<string, Schema>();\n await Promise.all(\n guarded\n .filter((s) => target_map.get(s)?.restart)\n .map(async (stream) => {\n // stream_info entry is guaranteed (guarded ⊆ stream_info.keys()).\n const last_event_name = stream_info.get(stream)!.last_event_name;\n const owner_state = event_to_state.get(last_event_name);\n if (!owner_state) {\n // No registered state owns the stream's events (deleted state,\n // schema versioning gone wrong, etc.). Tombstone instead of\n // seeding a corrupted snapshot.\n logger.error(\n `Cannot seed restart for \"${stream}\": no registered state owns event \"${last_event_name}\". Stream will be tombstoned instead.`\n );\n return;\n }\n const snap = await load(owner_state, { stream });\n seed_states.set(stream, snap.state as Schema);\n })\n );\n return seed_states;\n}\n\n// Phase 5 — archive callbacks\n\nasync function run_archive_callbacks(\n guarded: string[],\n target_map: Map<string, CloseTarget>\n): Promise<void> {\n // Sequential — user callbacks may share resources (S3 client, etc.) and\n // a failure should propagate to the caller without leaving partial state.\n for (const stream of guarded) {\n const archive_fn = target_map.get(stream)?.archive;\n if (archive_fn) await archive_fn();\n }\n}\n\n// Phase 5b — confirm the guard is still the head\n\nasync function heads_still_guarded(\n guarded: string[],\n guard_events: Map<string, { id: number; stream: string }>,\n skipped: string[]\n): Promise<string[]> {\n // True heads, markers included: the guard is a tombstone, and a reseed\n // by another closer is a snapshot.\n const heads = await store().query_stats(guarded, {});\n return guarded.filter((stream) => {\n if (heads.get(stream)?.head.id === guard_events.get(stream)!.id)\n return true;\n skipped.push(stream);\n return false;\n });\n}\n\n// Phase 6 — atomic truncate + cache warm\n\nasync function truncate_and_warm_cache(\n guarded: string[],\n seed_states: Map<string, Schema>,\n guard_events: Map<string, { id: number; stream: string }>,\n correlation: string\n): Promise<CloseResult[\"truncated\"]> {\n const trunc_targets = guarded.map((stream) => {\n const snapshot = seed_states.get(stream);\n const guard = guard_events.get(stream)!;\n return {\n stream,\n snapshot,\n meta: {\n correlation,\n causation: {\n event: { id: guard.id, name: TOMBSTONE_EVENT, stream: guard.stream },\n },\n },\n };\n });\n const truncated = await store().truncate(trunc_targets);\n\n // Cache invalidate / warm — use real event IDs from committed events\n await Promise.all(\n guarded.map(async (stream) => {\n const entry = truncated.get(stream);\n const state = seed_states.get(stream);\n if (state && entry) {\n await cache().set(stream, {\n stream,\n state,\n version: entry.committed.version,\n event_id: entry.committed.id,\n patches: 0,\n snaps: 1,\n });\n } else {\n await cache().invalidate(stream);\n }\n })\n );\n\n return truncated;\n}\n","/**\n * Correlation, the discovery half of correlate→drain: resolves each event to\n * its target streams and raises each target's work mark (`correlated_at`),\n * which is what `claim` reads. See docs/architecture/correlation-and-drain.\n */\n\nimport { createHash, randomUUID } from \"node:crypto\";\nimport { isStreamName } from \"../adapter.js\";\nimport { log, store } from \"../ports.js\";\nimport type {\n EventRegister,\n Registry,\n Resolved,\n SchemaRegister,\n Schemas,\n StreamPosition,\n SubscribeInput,\n} from \"../types/index.js\";\nimport { DEFAULT_LANE } from \"../types/index.js\";\nimport { is_valid_target } from \"./config.js\";\nimport type { DrainOps } from \"./drain-ops.js\";\nimport { LruMap } from \"./lru-map.js\";\nimport { report_once } from \"./report-once.js\";\n\n/**\n * First-boot scan starts this far below the watermark, so an event committed\n * but not correlated before a crash is found again. Re-scanning is harmless:\n * `subscribe` is an idempotent upsert and a mark never regresses.\n */\nconst COLD_START_BACK_SCAN = 10_000;\n\n/**\n * Too short and a slow scan outruns its lease (duplicate work, still safe);\n * too long and a crashed holder stalls discovery.\n */\nconst CORRELATION_LEASE_MS = 5_000;\n\n/**\n * The correlation lease key: a hash of every reacted-to event name with its\n * handler names, so only interchangeable workers share a lease. See\n * docs/architecture/correlation-and-drain § The correlation lease.\n */\nconst registry_key = <TEvents extends Schemas>(\n events: EventRegister<TEvents>\n): string => {\n const shape = Object.keys(events)\n .filter((name) => events[name].reactions.size > 0)\n .sort()\n .map((name) => [name, [...events[name].reactions.keys()].sort()]);\n return createHash(\"sha256\")\n .update(JSON.stringify(shape))\n .digest(\"hex\")\n .slice(0, 32);\n};\n\n/**\n * One correlate pass. An `idle` pass read nothing it keeps (it was\n * disarmed, refused the lease, or discarded its read), so it is no\n * evidence the store is up; a `scanned` pass read the log.\n */\nexport type CorrelatePass =\n | { readonly kind: \"idle\"; readonly last_id: number }\n | {\n readonly kind: \"scanned\";\n readonly last_id: number;\n /** Targets newly subscribed. */\n readonly subscribed: number;\n /** Targets whose work mark was raised. */\n readonly marked: number;\n /** It read events: settle's progress signal. */\n readonly read: boolean;\n };\n\n/** Bound on compiled pattern sources; guards a resolver that mints one per event. */\nconst PATTERN_CACHE_SIZE = 32;\n\n/** Static resolver target collected at build time and subscribed at init. */\nexport type StaticTarget = {\n readonly stream: string;\n readonly source?: string;\n readonly priority?: number;\n readonly lane?: string;\n};\n\n/**\n * What a target's subscription row holds. A resolution sends its own\n * priority/lane only when it beats `priority` (never, for a static target);\n * otherwise it re-sends these values with the mark. The store owns the lane;\n * this only caches it, so a missing record is re-read from the row.\n */\ntype Subscription = {\n readonly priority: number;\n readonly lane: string | undefined;\n};\n\n/** One target accumulated during a scan; `correlated_at` is its work mark. */\ntype Correlated = {\n source: string | undefined;\n priority: number;\n lane: string | undefined;\n /** True when priority/lane came from a resolution that beat the record. */\n upgraded: boolean;\n /** True when the target had no record, so its row must be read. */\n missed: boolean;\n /** The reaction whose resolution set priority/lane. */\n handler: string;\n correlated_at: number | undefined;\n};\n\n/** Constructor dependencies for {@link CorrelateCycle}. */\nexport type CorrelateCycleDeps<\n TSchemaReg extends SchemaRegister<TActions>,\n TEvents extends Schemas,\n TActions extends Schemas,\n> = {\n registry: Registry<TSchemaReg, TEvents, TActions>;\n static_targets: ReadonlyArray<StaticTarget>;\n cd: DrainOps<TEvents>;\n max_subscribed_streams: number;\n /** Every lane a controller exists for; others are rerouted to default. */\n declared_lanes: ReadonlySet<string>;\n /** Set when `onlyLanes` leaves a lane out; each shard gets its own lease. */\n shard?: ReadonlyArray<string>;\n /** Runs once at the end of init: arms the lanes and re-seeds defer timers across a restart. */\n on_init?: () => Promise<void>;\n};\n\n/**\n * A dynamic resolution named an undeclared lane. Rerouted to `\"default\"`\n * rather than skipped, so the work still runs. Reported once per reaction\n * and lane, since a resolver mints one target per aggregate.\n */\nfunction report_undeclared_lane(\n seen: Set<string>,\n handler: string,\n target: string,\n lane: string,\n declared: ReadonlySet<string>\n): void {\n report_once(\n seen,\n `lane|${handler}|${lane}`,\n `Reaction \"${handler}\" resolved onto undeclared lane \"${lane}\" — for example target \"${target}\". ` +\n `Declared lanes: ${[...declared].map((l) => `\"${l}\"`).join(\", \")}. ` +\n 'No controller claims it, so the stream would never drain — running it on \"default\" instead. ' +\n \"The equivalent static `.to({ lane })` is rejected at build; a dynamic resolver's lane is only knowable here.\"\n );\n}\n\n/**\n * A dynamic resolver's priority isn't a 32-bit integer (Postgres stores\n * `int`). Run at the default priority instead, like an undeclared lane.\n */\nfunction report_bad_priority(\n seen: Set<string>,\n handler: string,\n target: string,\n priority: unknown\n): void {\n report_once(\n seen,\n `priority|${handler}`,\n `Reaction \"${handler}\" resolved priority ${String(priority)} for target \"${target}\", which isn't a 32-bit integer. ` +\n \"Running it at priority 0 instead. \" +\n \"The equivalent static `.to({ priority })` is rejected at build; a dynamic resolver's priority is only knowable here.\"\n );\n}\n\n/**\n * Two resolutions disagreed on one target's lane. Reported, not corrected:\n * re-laning a live stream would move it out from under a lease holder.\n * Keyed by orientation, since \"first discovered\" can land either way.\n */\nfunction report_lane_conflict(\n seen: Set<string>,\n handler: string,\n target: string,\n kept: string,\n dropped: string\n): void {\n report_once(\n seen,\n `conflict|${handler}|${kept}|${dropped}`,\n `Reaction \"${handler}\" resolved lane \"${dropped}\" for a stream already on \"${kept}\" — for example \"${target}\". ` +\n `These are conflicting lane assignments from two dynamic resolutions at equal priority. ` +\n `Keeping \"${kept}\", the lane it was first discovered on — re-laning a live stream would move it out from under a worker holding its lease. ` +\n `The reaction resolving \"${dropped}\" runs inside the \"${kept}\" lane's budget, and a process restricted to \"${dropped}\" via onlyLanes never runs it. ` +\n \"The equivalent static declaration is rejected at build; align the resolvers, or split the target.\"\n );\n}\n\n/** Drives correlation for one Act: the checkpoint, the lease, the subscription records. */\nexport class CorrelateCycle<\n TSchemaReg extends SchemaRegister<TActions>,\n TEvents extends Schemas,\n TActions extends Schemas,\n> {\n private _checkpoint = -1;\n // Lease holder id; per instance, so a restart never inherits a stale claim.\n private readonly _by = randomUUID();\n private readonly _key: string;\n // Local expiry of the held lease (0 = none); stale only costs a duplicate scan.\n private _lease_until = 0;\n // Armed while `_raised` (bumped by a commit or notification) is ahead of\n // `_lowered` (the raise count the last short page saw). Starts armed.\n private _raised = 1;\n private _lowered = 0;\n // Bumped by a release (shutdown), so a scan or lease reply that was out\n // across one writes nothing.\n private _epoch = 0;\n // Passes in flight: a restore waits for them, and refuses new ones.\n private readonly _passes = new Set<Promise<CorrelatePass>>();\n private _restoring = false;\n private _init_promise: Promise<void> | undefined;\n // Bounded by `maxSubscribedStreams`; static records live apart so eviction\n // never lets a resolution re-lane them.\n private readonly _dynamic_subscriptions: LruMap<string, Subscription>;\n private readonly _static_subscriptions = new Map<string, Subscription>();\n private readonly _patterns = new LruMap<string, RegExp>(PATTERN_CACHE_SIZE);\n private readonly _registry: Registry<TSchemaReg, TEvents, TActions>;\n private readonly _static_targets: ReadonlyArray<StaticTarget>;\n private readonly _cd: DrainOps<TEvents>;\n private readonly _on_init: (() => Promise<void>) | undefined;\n private readonly _declared_lanes: ReadonlySet<string>;\n // Report-once keys; per instance because `internal/` holds no module state.\n private readonly _reported = new Set<string>();\n\n constructor({\n registry,\n static_targets,\n cd,\n max_subscribed_streams,\n declared_lanes,\n shard,\n on_init,\n }: CorrelateCycleDeps<TSchemaReg, TEvents, TActions>) {\n this._key = shard\n ? `${registry_key(registry.events)}:${[...shard].sort().join(\",\")}`\n : registry_key(registry.events);\n this._dynamic_subscriptions = new LruMap(max_subscribed_streams);\n this._registry = registry;\n this._declared_lanes = declared_lanes;\n this._static_targets = static_targets;\n this._cd = cd;\n this._on_init = on_init;\n }\n\n get checkpoint(): number {\n return this._checkpoint;\n }\n\n /** A commit (local or remote) may have produced uncorrelated events. */\n arm(): void {\n this._raised++;\n }\n\n private async _init(): Promise<void> {\n // Single-flight, but a failure clears the promise so the next call retries.\n this._init_promise ??= this._run_init().catch((error) => {\n this._init_promise = undefined;\n throw error;\n });\n await this._init_promise;\n }\n\n private async _run_init(): Promise<void> {\n const { watermark, correlated_at } = await this._cd.subscribe([\n ...this._static_targets,\n ]);\n this._checkpoint =\n correlated_at >= 0\n ? correlated_at\n : Math.max(-1, watermark - COLD_START_BACK_SCAN);\n for (const { stream, priority = 0, lane } of this._static_targets) {\n this._static_subscriptions.set(stream, {\n priority,\n lane,\n });\n }\n // After the static subscribe, so the streams walk sees them.\n await this._on_init?.();\n }\n\n /**\n * Replace the log with no pass in flight, then cold-start: a pass that\n * read the old log writes before the restore, never into the new one.\n */\n async restart(restore: () => Promise<void>): Promise<void> {\n this._restoring = true;\n try {\n await Promise.allSettled(this._passes);\n await restore();\n } finally {\n this._restoring = false;\n }\n this._init_promise = undefined;\n this._checkpoint = -1;\n this._dynamic_subscriptions.clear();\n this._static_subscriptions.clear();\n }\n\n /** Forget dynamic targets whose rows a full close deleted, so they re-subscribe. */\n forget_subscribed(streams: Iterable<string>): void {\n for (const stream of streams) this._dynamic_subscriptions.delete(stream);\n }\n\n // Would the target's own `fetch` (filtered by `source`) return this event?\n private _in_fetch_window(\n source: string | undefined,\n stream: string\n ): boolean {\n if (source === undefined || source === stream) return true;\n if (isStreamName(source)) return false;\n let pattern = this._patterns.get(source);\n if (!pattern) {\n pattern = new RegExp(source);\n this._patterns.set(source, pattern);\n }\n return pattern.test(stream);\n }\n\n /** Scan past the checkpoint, subscribe new targets and raise their work marks. */\n async correlate(\n /** The most events the scan reads (`0` reads everything). */\n limit: number,\n /**\n * Honour the correlation lease. Only the settle loop and poller do; an\n * explicit `app.correlate()` scans now, since `close` loops on it.\n */\n lease = false\n ): Promise<CorrelatePass> {\n if (this._restoring) return { kind: \"idle\", last_id: this._checkpoint };\n const pass = this._scan(limit, lease);\n this._passes.add(pass);\n try {\n return await pass;\n } finally {\n this._passes.delete(pass);\n }\n }\n\n private async _scan(limit: number, lease: boolean): Promise<CorrelatePass> {\n await this._init();\n const epoch = this._epoch;\n const idle = (): CorrelatePass => ({\n kind: \"idle\",\n last_id: this._checkpoint,\n });\n\n // A remote writer without notify leaves this disarmed; the poller re-arms.\n if (this._raised === this._lowered) return idle();\n\n const raised = this._raised;\n\n // The lease rides `subscribe` with no streams (\"may I scan?\"). Its shared\n // checkpoint is ignored: adopting it would skip events this worker never\n // read. Renew at the halfway mark.\n const now = Date.now();\n if (lease && now >= this._lease_until - CORRELATION_LEASE_MS / 2) {\n const { correlating } = await this._cd.subscribe([], undefined, {\n key: this._key,\n by: this._by,\n millis: CORRELATION_LEASE_MS,\n });\n // A release that landed while the call was out (shutdown) stays\n // released: the reply must not hand the lease back to this worker.\n if (this._epoch !== epoch) return idle();\n this._lease_until = correlating ? now + CORRELATION_LEASE_MS : 0;\n // `undefined` = store without leasing. Refused: stay armed, look again.\n if (correlating === false) return idle();\n }\n\n const after = this._checkpoint;\n const correlated = new Map<string, Correlated>();\n let last_id = after;\n // A resolver threw: the scan stops before that event, so the next one\n // retries it and nothing past it is lost.\n let stopped = false;\n const found = await store().query<TEvents>(\n (event) => {\n if (stopped) return;\n const register = this._registry.events[event.name];\n if (register) {\n for (const reaction of register.reactions.values()) {\n let resolved: Resolved | undefined;\n try {\n resolved =\n typeof reaction.resolver === \"function\"\n ? reaction.resolver(event)\n : reaction.resolver;\n } catch (error) {\n stopped = true;\n report_once(\n this._reported,\n `resolver|${reaction.handler.name}|${event.id}`,\n `Resolver of reaction \"${reaction.handler.name}\" threw on ${String(event.name)} #${event.id} (stream \"${event.stream}\"): ${String(error)}. ` +\n \"Correlation stops before this event until the resolver stops throwing; work already found keeps draining.\"\n );\n return;\n }\n if (!resolved) continue;\n if (!is_valid_target(resolved)) {\n report_bad_priority(\n this._reported,\n reaction.handler.name,\n resolved.target,\n resolved.priority\n );\n resolved = { ...resolved, priority: 0 };\n }\n let lane = resolved.lane;\n if (lane !== undefined && !this._declared_lanes.has(lane)) {\n report_undeclared_lane(\n this._reported,\n reaction.handler.name,\n resolved.target,\n lane,\n this._declared_lanes\n );\n lane = undefined;\n }\n const fixed = this._static_subscriptions.get(resolved.target);\n const recorded =\n fixed ?? this._dynamic_subscriptions.get(resolved.target);\n const priority = resolved.priority ?? 0;\n const upgraded =\n !recorded || (!fixed && priority > recorded.priority);\n const carried = upgraded\n ? { priority, lane }\n : { priority: recorded.priority, lane: recorded.lane };\n const entry = correlated.get(resolved.target) || {\n source: resolved.source,\n priority: carried.priority,\n lane: carried.lane,\n upgraded,\n missed: !recorded,\n handler: reaction.handler.name,\n correlated_at: undefined,\n };\n // Compare against what the target already carries, from this\n // scan or a past one.\n const seen_in_scan = correlated.has(resolved.target);\n const held_lane =\n (seen_in_scan ? entry.lane : recorded?.lane) ?? DEFAULT_LANE;\n const held_priority = seen_in_scan\n ? entry.priority\n : recorded?.priority;\n const resolved_lane = lane ?? DEFAULT_LANE;\n if (held_priority === priority && held_lane !== resolved_lane)\n report_lane_conflict(\n this._reported,\n reaction.handler.name,\n resolved.target,\n held_lane,\n resolved_lane\n );\n // Within one scan the highest priority sets the lane.\n if (carried.priority > entry.priority) {\n entry.priority = carried.priority;\n entry.lane = carried.lane;\n entry.upgraded = upgraded;\n entry.handler = reaction.handler.name;\n }\n if (this._in_fetch_window(resolved.source, event.stream))\n entry.correlated_at = event.id;\n correlated.set(resolved.target, entry);\n }\n }\n last_id = event.id;\n },\n // Resolvers see `pii: null`: correlate runs actor-less, and one\n // undecryptable row would otherwise stop every stream's reactions.\n { after, limit, with_pii: false }\n );\n\n if (this._declared_lanes.size > 1) await this._recall(correlated);\n const read = last_id > after;\n\n // Released while the scan was out: what it read belongs to a lease this\n // worker gave up, and writing it would take the lease back.\n if (this._epoch !== epoch) return idle();\n\n // Only targets with a mark to raise or priority/lane to register.\n const streams: SubscribeInput[] = [];\n for (const [stream, entry] of correlated) {\n if (entry.upgraded || entry.correlated_at !== undefined)\n streams.push({\n stream,\n source: entry.source,\n priority: entry.priority,\n lane: entry.lane,\n correlated_at: entry.correlated_at,\n });\n }\n\n if (streams.length) {\n // Leasing renews for free on the same call.\n const renewed_at = Date.now();\n const { subscribed, correlating } = await this._cd.subscribe(\n streams,\n last_id,\n lease\n ? { key: this._key, by: this._by, millis: CORRELATION_LEASE_MS }\n : undefined\n );\n if (lease && correlating !== false)\n this._lease_until = renewed_at + CORRELATION_LEASE_MS;\n // The orchestrator arms on re-marks too, not just new subscriptions.\n const marked = streams.filter(\n (entry) => entry.correlated_at !== undefined\n ).length;\n this._checkpoint = last_id;\n // Only dynamic targets can be upgraded: a static target is never re-laned.\n for (const { stream, priority, lane } of streams) {\n if (correlated.get(stream)?.upgraded)\n this._dynamic_subscriptions.set(stream, {\n priority: priority as number,\n lane,\n });\n }\n return { kind: \"scanned\", last_id, subscribed, marked, read };\n }\n // Only a short page proves the log is exhausted; resolving nothing does\n // not. It lowers only the raises it saw, so one that landed mid-scan\n // keeps the cycle armed.\n this._checkpoint = last_id;\n if (!stopped && found !== limit) this._lowered = raised;\n return { kind: \"scanned\", last_id, subscribed: 0, marked: 0, read };\n }\n\n // Read the row of each target this scan had no record of (new or evicted),\n // so a resolution that doesn't beat its priority keeps the row's lane.\n // Only called with more than one lane declared.\n private async _recall(correlated: Map<string, Correlated>): Promise<void> {\n const missed = [...correlated].filter(([, entry]) => entry.missed);\n await Promise.all(\n missed.map(async ([stream, entry]) => {\n let row: StreamPosition | undefined;\n await store().query_streams(\n (position) => {\n row = position;\n },\n { stream, stream_exact: true, limit: 1 }\n );\n if (!row) return;\n this._dynamic_subscriptions.set(stream, {\n priority: row.priority,\n lane: row.lane,\n });\n if (entry.priority > row.priority) return;\n const held_lane = row.lane ?? DEFAULT_LANE;\n const resolved_lane = entry.lane ?? DEFAULT_LANE;\n if (entry.priority === row.priority && held_lane !== resolved_lane)\n report_lane_conflict(\n this._reported,\n entry.handler,\n stream,\n held_lane,\n resolved_lane\n );\n entry.priority = row.priority;\n entry.lane = row.lane;\n entry.upgraded = false;\n })\n );\n }\n\n /** Release the lease early by re-acquiring it for zero ms. Best-effort. */\n async release_correlation(): Promise<void> {\n try {\n this._lease_until = 0;\n this._epoch++;\n await this._cd.subscribe([], undefined, {\n key: this._key,\n by: this._by,\n millis: 0,\n });\n } catch (error) {\n log().warn(\n `Could not hand back the correlation lease during shutdown; it expires on its own within ${CORRELATION_LEASE_MS}ms and correlation resumes normally after that. ` +\n \"On a single-writer store this usually means another connection holds the database. \" +\n `Cause: ${String((error as Error).cause ?? error)}`\n );\n }\n }\n}\n","/**\n * The transforms that apply the sensitive-data marker (`../sensitive.ts`):\n * split sensitive fields out at commit, gate them on read, and strip them\n * before projection and reaction handlers.\n */\n\nimport type { Actor, Committed, Schemas } from \"../types/index.js\";\nimport { REDACTED, SHREDDED } from \"../types/schemas.js\";\n\n/**\n * Split an emitted event's `data` into `data` (non-sensitive) + `pii`\n * (sensitive) using the field list precomputed at build time. Called by the\n * state's `message` hook (`event-builder.ts`) on the way to `Store.commit`,\n * and only for events that declare sensitive fields.\n */\nexport function pii_split<TName, TData extends Record<string, unknown>>(\n emitted: { name: TName; data: TData },\n fields: readonly string[]\n): { name: TName; data: TData; pii: Record<string, unknown> } {\n const data = { ...emitted.data };\n const pii: Record<string, unknown> = {};\n for (const f of fields) {\n if (f in data) {\n pii[f] = data[f];\n delete data[f];\n }\n }\n return { name: emitted.name, data, pii };\n}\n\n/**\n * Build the **external view** of a committed event — the form returned by\n * `load()`, `query()`, `query_array()`, and the snapshot in `do()`'s reply.\n *\n * Reached only through {@link make_gate}, for events that declare sensitive\n * fields, so `fields` is never empty.\n *\n * - Event whose `pii` payload is null/undefined → substitute {@link SHREDDED}\n * for each declared field. Irrecoverable, so no predicate check.\n * - Event with a `pii` payload, predicate returns `true` → merge `pii` into\n * `data` (plaintext).\n * - Event with a `pii` payload, predicate returns `false` OR no predicate\n * declared (framework default-deny) → substitute {@link REDACTED} for each\n * declared field.\n */\nfunction pii_gate<TEvents extends Schemas, TKey extends keyof TEvents>(\n event: Committed<TEvents, TKey>,\n fields: readonly string[],\n predicate: ((event: any, actor: Actor) => boolean) | null,\n actor: Actor | undefined\n): Committed<TEvents, TKey> {\n const data = event.data as Record<string, unknown>;\n // The external view never carries the isolated `pii` sidecar: keeping it\n // would leak plaintext on every gated read (`load`, `query`,\n // `query_array`) even while `data` is redacted. The plaintext lives in\n // `data` only on the authorized path.\n const { pii, ...rest } = event as Committed<TEvents, TKey> & {\n pii?: Record<string, unknown> | null;\n };\n if (pii == null) {\n const shredded: Record<string, unknown> = { ...data };\n for (const f of fields) shredded[f] = SHREDDED;\n return { ...rest, data: shredded as Committed<TEvents, TKey>[\"data\"] };\n }\n // Plaintext path requires both an actor AND a predicate that allows. Missing\n // either → default-deny → REDACTED.\n const allowed = !!actor && !!predicate && predicate(event, actor);\n if (allowed) {\n return {\n ...rest,\n data: { ...data, ...pii } as Committed<TEvents, TKey>[\"data\"],\n };\n }\n const redacted: Record<string, unknown> = { ...data };\n for (const f of fields) redacted[f] = REDACTED;\n return { ...rest, data: redacted as Committed<TEvents, TKey>[\"data\"] };\n}\n\n/**\n * A prebuilt per-event read gate: the event as the reading actor may see\n * it. The builder prebuilds one per event for every read surface; the\n * actor-less `query` / `query_array` pass no actor (default-deny), `load`\n * and `do`'s reply pass the reader.\n */\nexport type EventGate = <TEvents extends Schemas, TKey extends keyof TEvents>(\n event: Committed<TEvents, TKey>,\n actor?: Actor\n) => Committed<TEvents, TKey>;\n\n/** The gate for every event with no sensitive fields: no allocation. */\nexport const IDENTITY_GATE: EventGate = (event) => event;\n\n/**\n * Prebuild a sensitive event's read gate: its field list and disclosure\n * predicate are captured once, and {@link pii_gate} applies them per read\n * (`predicate = null` is the default-deny of the actor-less surfaces).\n */\nexport function make_gate(\n fields: readonly string[],\n predicate: ((event: any, actor: Actor) => boolean) | null\n): EventGate {\n return (event, actor) => pii_gate(event, fields, predicate, actor);\n}\n\n/**\n * Build the **handler view** — sensitive keys removed entirely from `data`\n * and the `pii` field dropped from the event. Used before invoking projection\n * handlers and reaction handlers, which never see PII by framework rule.\n *\n * Different from {@link pii_gate} (which substitutes {@link REDACTED} or\n * {@link SHREDDED}) — projection tables and reaction sinks shouldn't even\n * structurally observe the keys, so a handler that mistakenly writes\n * `event.data.email` into a column would get `undefined`, not a sentinel\n * string that looks like real data. The strictness is deliberate.\n *\n * Reactions that genuinely need PII (e.g. a welcome-email reaction reading\n * `email`) opt back in by explicitly calling `app.load(stream, { actor:\n * system_actor })` inside the handler — pulling PII through the gate at the\n * call site makes the security-relevant path visible in code review.\n */\nexport function pii_strip<\n TEvents extends Schemas,\n TKey extends keyof TEvents & string,\n>(\n event: Committed<TEvents, TKey>,\n fields: readonly string[]\n): Committed<TEvents, TKey> {\n // Contract: `fields` is non-empty. The event gate (`event-builder.ts`) and\n // the projection fold (`projection-fold.ts`) call it only when it is.\n const data = event.data as Record<string, unknown>;\n const stripped: Record<string, unknown> = {};\n for (const k of Object.keys(data)) {\n if (!fields.includes(k)) stripped[k] = data[k];\n }\n const { pii: _drop_pii, ...rest } = event as Committed<TEvents, TKey> & {\n pii?: unknown;\n };\n return {\n ...rest,\n data: stripped as Committed<TEvents, TKey>[\"data\"],\n } as Committed<TEvents, TKey>;\n}\n","/**\n * Fold engine behind `projection(name).of(state)` — maintains per-stream\n * folded states in a bounded in-memory cache and flushes one row per dirty\n * stream per round, so write amplification tracks the distinct-key count\n * instead of the event count.\n *\n * The flush payload deliberately has no type of its own: a state\n * projection flushes the cache layer outward — the rows ARE the\n * streams' {@link CacheEntry} values.\n *\n * Correctness discipline:\n * - The engine runs as the projection's batch handler, so the watermark\n * acks only after a fully-flushed batch — fold work is never\n * acknowledged before it is durable.\n * - On first sight of a stream the engine loads its head state through\n * the same `load()` the command path uses (cache, snapshots and all).\n * The loaded snapshot carries its own head position (`version` and the\n * global event `id`), captured atomically with `state`, so the engine\n * never pairs a stale state with a newer head id read separately from\n * the cache. Fetched events at or below the loaded id are\n * skipped, later ones fold through the state's own patch reducers.\n * - Eviction under `maxCachedStates` pressure flushes the evictee first\n * (flush-before-evict) — eviction never loses folded work.\n */\nimport type {\n BatchHandler,\n CacheEntry,\n Schema,\n Schemas,\n State,\n} from \"../types/index.js\";\nimport type { FoldConfig } from \"./config.js\";\nimport { bare_patch, load } from \"./event-sourcing.js\";\nimport { pii_strip } from \"./pii.js\";\n\n/**\n * A stream's in-flight fold: a mutable {@link CacheEntry} plus the\n * engine's `dirty` flag. Mutable because the hot loop updates one\n * object per stream rather than allocating per event; the required\n * frontier fields are what keep a warm-cache load from ever\n * re-applying history. Stripping `dirty` at the flush boundary yields\n * the entry — the flush payload IS the cache entry.\n */\ntype Fold<TState extends Schema> = {\n -readonly [K in keyof CacheEntry<TState>]: CacheEntry<TState>[K];\n} & { dirty: boolean };\n\n/**\n * Internal handle a fold handler exposes so the orchestrator can drop its\n * process-local state.\n *\n * A rebuild must not trust a per-Act cache: `reset` rewinds the watermark and\n * replays from the beginning, and every replayed event is at or below the\n * cached head, so the fold takes its already-folded branch and re-flushes\n * whatever it happens to hold. If that cache is stale, the rebuild writes the\n * staleness back out — the one outcome a rebuild exists to prevent. Dropping\n * the cache makes the next batch re-load head state from the store, which is\n * authoritative by definition.\n *\n * A symbol on the function keeps `BatchHandler` a plain function type; nothing\n * here is re-exported from `src/index.ts`.\n */\nexport const FOLD_RESET = Symbol(\"act.fold.reset\");\n\n/** A batch handler that owns a fold cache it can be told to drop. */\nexport type ResettableBatchHandler<TEvents extends Schemas> =\n BatchHandler<TEvents> & {\n readonly [FOLD_RESET]?: () => void;\n };\n\n/**\n * Build the batch handler that folds a state's events into per-stream rows.\n * The returned closure is long-lived (one per built projection): its cache\n * survives across drain cycles, so warm streams fold without I/O. It carries\n * a {@link FOLD_RESET} handle so a rebuild can drop that cache.\n */\nexport function make_fold_handler<\n TState extends Schema,\n TEvents extends Schemas,\n TActions extends Schemas,\n>(\n me: State<TState, TEvents, TActions>,\n flush: (rows: ReadonlyArray<CacheEntry<TState>>) => Promise<void>,\n config: FoldConfig,\n sensitive_fields: (event_name: string) => readonly string[]\n): BatchHandler<TEvents> {\n // First-sight head loads must apply the SAME PII treatment as the warm\n // path (which folds `pii_strip`ped events handed in by the batch handler):\n // sensitive keys removed entirely, not gated to `[REDACTED]`. `load()`\n // folds over `me.view`, so compose the view with `pii_strip` for sensitive\n // events — otherwise an actorless head load would gate to `[REDACTED]` and\n // the projected row would differ from the warm path by cache warmth.\n // For a non-PII projection every lookup is empty, so `load_me === me`\n // behaviorally.\n const load_me: State<TState, TEvents, TActions> = {\n ...me,\n view: (raw, actor) => {\n const viewed = me.view(raw, actor);\n const fields = sensitive_fields(viewed.name as string);\n return fields.length\n ? (pii_strip(viewed as never, fields) as typeof viewed)\n : viewed;\n },\n };\n // Insertion-ordered Map as LRU: first key is the oldest. A promote is\n // delete + re-insert. Not the shared LruMap — eviction here must await\n // a flush, and a sync auto-evicting set() would drop folded work.\n const cache = new Map<string, Fold<TState>>();\n\n const row = ({ dirty: _, ...row }: Fold<TState>): CacheEntry<TState> => row;\n\n const flush_dirty = async () => {\n const rows: CacheEntry<TState>[] = [];\n const flushed: Fold<TState>[] = [];\n for (const f of cache.values())\n if (f.dirty) {\n rows.push(row(f));\n flushed.push(f);\n }\n if (rows.length === 0) return;\n await flush(rows);\n for (const f of flushed) f.dirty = false;\n };\n\n /**\n * Load a stream's head state and seat it in the cache.\n *\n * The loaded state and its head position (`version`, global `id`,\n * `patches`, `snaps`) are captured atomically inside `load()` — even on a\n * warm cache hit where `snapshot.event` is undefined. Reading the head id\n * back from the cache separately opened a TOCTOU window: a\n * concurrent `action()` committing between the two awaits pairs this\n * OLDER state with a NEWER event_id, and the frontier guard below then\n * permanently skips the intervening events. Dirty from the start: the row\n * must be written at least once.\n */\n const first_sight = async (stream: string): Promise<Fold<TState>> => {\n if (cache.size >= config.maxCachedStates) {\n // flush-before-evict: the oldest entry leaves only after its folded\n // work is durable.\n const oldest = cache.keys().next().value as string;\n const evictee = cache.get(oldest) as Fold<TState>;\n if (evictee.dirty) await flush([row(evictee)]);\n cache.delete(oldest);\n }\n const snapshot = await load(load_me, { stream });\n const seated: Fold<TState> = {\n stream,\n state: snapshot.state,\n version: snapshot.version,\n event_id: snapshot.id,\n patches: snapshot.patches,\n snaps: snapshot.snaps,\n dirty: true,\n };\n cache.set(stream, seated);\n return seated;\n };\n\n const handler: ResettableBatchHandler<TEvents> = async (events) => {\n let folded_since_flush = 0;\n for (const event of events) {\n const stream = event.stream;\n let fold = cache.get(stream);\n if (fold) {\n // promote to most-recent\n cache.delete(stream);\n cache.set(stream, fold);\n } else {\n fold = await first_sight(stream);\n }\n // Fold forward only across a CONTIGUOUS version step. The\n // cache is per-Act but the subscription watermark is shared, so a\n // worker can be handed an event whose predecessors were drained by a\n // sibling worker — its cached state is then stale, and folding onto\n // it silently corrupts the row for good (the flushed row carries the\n // newest event_id, so the monotonic-upsert guard overwrites the\n // correct row with the wrong one). \"Newer than what I hold\" is not\n // the same question as \"next after what I hold\".\n //\n // A gap re-takes the first-sight path: drop the entry and load head\n // state, which is authoritative and absorbs both the missed window\n // and the version slot a `__snapshot__` consumes. The reloaded entry\n // sits at head, so this event then takes the already-folded branch.\n const contiguous = event.version === fold.version + 1;\n if (event.id > fold.event_id && !contiguous) {\n cache.delete(stream);\n fold = await first_sight(stream);\n }\n if (event.id > fold.event_id) {\n const reducer = me.patch[event.name as keyof TEvents];\n fold.state = bare_patch(\n me,\n fold.state,\n reducer(event as never, fold.state),\n event as never\n );\n fold.version = event.version;\n fold.event_id = event.id;\n fold.patches++;\n fold.dirty = true;\n } else {\n // Already folded (head load or redelivery) — mark dirty anyway\n // so replays repopulate the read table: this is what keeps a\n // rebuild at one upsert per stream instead of zero.\n fold.dirty = true;\n }\n if (++folded_since_flush >= config.flushEvery) {\n await flush_dirty();\n folded_since_flush = 0;\n }\n }\n // Flush before returning: the drain acks this batch's watermark only\n // after the handler resolves, so rows are durable before the ack.\n await flush_dirty();\n };\n\n // Dirty entries are dropped rather than flushed: a rebuild is about to\n // re-derive every row from the store, so a pending write of process-local\n // state has nothing to contribute and everything to get wrong.\n Object.defineProperty(handler, FOLD_RESET, { value: () => cache.clear() });\n return handler;\n}\n","/**\n * Debounced correlate→drain loop. Sits one level above both correlation\n * and drain: schedule() coalesces rapid callers into a single cycle, then\n * runs correlate+drain in a loop until a pass produces no progress.\n *\n * Owns the debounce timer and the cycle in flight. Everything else is\n * supplied via the `SettleDeps` callbacks so this module stays free of\n * orchestrator state.\n */\n\nimport type {\n Drain,\n DrainOptions,\n Query,\n Schemas,\n SettleOptions,\n} from \"../types/index.js\";\nimport type { CircuitBreaker } from \"./circuit-breaker.js\";\nimport type { CorrelatePass } from \"./correlate-cycle.js\";\nimport { merge_drains } from \"./drain-cycle.js\";\n\n/**\n * Callbacks the settle loop needs from the orchestrator. Modeled as an\n * input bag so this file doesn't import `Act` (avoids a cycle) and stays\n * independently testable.\n */\nexport type SettleDeps<TEvents extends Schemas> = {\n /** Scans from correlation's own checkpoint. */\n readonly correlate: (query: Query) => Promise<CorrelatePass>;\n readonly drain: (options: DrainOptions) => Promise<Drain<TEvents>>;\n readonly on_settled: (drain: Drain<TEvents>) => void;\n /** The shared breaker: settle records correlate's store outcome on it. */\n readonly breaker: CircuitBreaker;\n};\n\n/**\n * Drives the debounced correlate→drain catch-up cycle. One instance per\n * Act orchestrator.\n */\nexport class SettleLoop<TEvents extends Schemas> {\n private _timer: ReturnType<typeof setTimeout> | undefined = undefined;\n // The cycle in flight, set while one runs. Shutdown waits for it\n // (`stop()` cancels scheduling only). Never rejects.\n private _inflight: Promise<void> | undefined;\n // A wake-up arrived while a cycle ran: run one more pass after it.\n private _pending = false;\n // The last caller's options, used by the next pass.\n private _next: SettleOptions | undefined = undefined;\n // When the scheduled pass fires (epoch ms).\n private _due = 0;\n // Set at shutdown: nothing schedules again.\n private _stopped = false;\n private readonly _deps: SettleDeps<TEvents>;\n // Debounce window applied when the caller doesn't override via `SettleOptions.debounceMs`.\n private readonly _default_debounce_ms: number;\n\n constructor(deps: SettleDeps<TEvents>, default_debounce_ms: number) {\n this._deps = deps;\n this._default_debounce_ms = default_debounce_ms;\n }\n\n /**\n * Schedule a settle pass. A pass already scheduled is never put off or\n * replaced: calls that arrive before it runs join it (a shorter\n * `debounceMs` brings it forward), and a call during a running cycle\n * queues one more pass after it. Callers pass options, which the next\n * pass uses; internal wake-ups pass none, so they never discard a\n * caller's. The cycle runs correlate→drain passes until one makes no\n * progress (see {@link SettleOptions.maxPasses}), then emits the\n * `\"settled\"` lifecycle event via {@link SettleDeps.on_settled}.\n */\n schedule(options?: SettleOptions): void {\n if (this._stopped) return;\n if (options) this._next = options;\n if (this._inflight) {\n this._pending = true;\n return;\n }\n const delay = options?.debounceMs ?? this._default_debounce_ms;\n const due = Date.now() + delay;\n if (this._timer) {\n if (due >= this._due) return;\n clearTimeout(this._timer);\n }\n this._due = due;\n this._timer = setTimeout(() => {\n this._timer = undefined;\n const {\n debounceMs: _,\n correlate: correlate_query = {},\n maxPasses = Infinity,\n ...drain_options\n } = this._next ?? {};\n this._next = undefined;\n\n this._inflight = (async () => {\n // Every pass, so `settled` reports what the whole settle did; its\n // last pass made no progress and is always empty.\n const passes: Drain<TEvents>[] = [];\n // Loop until a pass produces no work, so one settle catches up a\n // paginated backlog. Shutdown waits for the pass in flight, not the\n // loop.\n for (let i = 0; i < maxPasses && !this._stopped; i++) {\n const pass = await this._deps.correlate(correlate_query);\n // Only a pass that read the log is evidence the store is up.\n // Recording an idle one would re-close an OPEN breaker mid-outage\n // and let the drain below hammer a store nobody has heard from.\n const scanned = pass.kind === \"scanned\";\n if (scanned) this._deps.breaker.passed();\n const drain = await this._deps.drain(drain_options);\n passes.push(drain);\n // Only a pass that read no events and leased nothing is idle: a\n // leased stream that deferred or failed may leave work behind. It\n // ends because ids are finite and a leased stream advances or\n // leaves the claimable set (acked, blocked, scheduled); a zero\n // backoff keeps it claimable until it blocks or succeeds.\n const made_progress =\n drain.leased.length > 0 || (scanned && pass.read);\n if (!made_progress) break;\n }\n // `Act.emit` contains listener throws, so the store-failure catch\n // below never sees one.\n if (passes.length) this._deps.on_settled(merge_drains(passes));\n })()\n .catch((err) => {\n // Correlate failed (a store op, its startup included). Record on\n // the shared breaker, which logs it and surfaces the `error` event;\n // the drain loop reads the same breaker to pace itself.\n this._deps.breaker.failed(Date.now(), err);\n })\n .finally(() => {\n this._inflight = undefined;\n // A wake-up arrived mid-cycle: run one more pass so it isn't lost.\n if (this._pending) {\n this._pending = false;\n this.schedule(this._next);\n }\n });\n }, delay);\n }\n\n /**\n * The cycle currently in flight, or `undefined` when idle. A\n * graceful shutdown awaits this alongside the drain controllers so a\n * settle parked in `correlate` does not resume after teardown.\n */\n get inflight(): Promise<void> | undefined {\n return this._inflight;\n }\n\n /**\n * Cancel any pending settle pass. Idempotent. `final` (shutdown) also\n * stops all later scheduling.\n */\n stop(final = false): void {\n if (final) this._stopped = true;\n // Drop a mid-cycle wake-up too — a stopped loop must not re-arm from\n // the running cycle's `finally`.\n this._pending = false;\n this._next = undefined;\n if (this._timer) {\n clearTimeout(this._timer);\n this._timer = undefined;\n }\n }\n}\n","/**\n * @module merge\n * @category Internal\n *\n * Shared utilities for merging partial states and projections across builders.\n * Lives in `internal/` because the symbols are consumed by the builder layer\n * (`act-builder`, `slice-builder`, `projection-builder`) but aren't part of\n * the public package surface.\n *\n * @internal\n */\nimport { ZodObject, type ZodType } from \"zod\";\nimport { def_of, inner_of } from \"../internal/zod.js\";\nimport type { Projection } from \"../types/builders.js\";\nimport type { Schema, State } from \"../types/index.js\";\n\n/**\n * The kind of value a field holds under its wrappers (optional, nullable,\n * default, ...), e.g. `z.string().optional()` -> `\"string\"`. A list names its\n * element, `\"array of string\"`, so it differs from a value and from a list of\n * something else. Zod's `.unwrap()` returns the element and loses the list.\n */\nfunction base_type_name(schema: ZodType): string {\n let def = def_of(schema)!;\n for (let inner = inner_of(def); inner; inner = inner_of(def))\n def = def_of(inner)!;\n return def.type === \"array\"\n ? `array of ${base_type_name(def.element)}`\n : def.type;\n}\n\n/**\n * Merges two Zod schemas. If both are ZodObject instances, checks for\n * overlapping shape keys with incompatible base types (throws descriptive\n * error), then merges via `.extend()`. The same schema instance (one partial\n * re-registered through another slice) is kept as-is. Any other pair where\n * either side is not a ZodObject throws — there is no shape to extend, and\n * keeping one side would silently drop the other partial's fields.\n */\nfunction merge_schemas(\n existing: ZodType,\n incoming: ZodType,\n state_name: string\n): ZodType {\n if (existing === incoming) return existing;\n const existing_object = as_object(existing, \"existing\", state_name);\n const incoming_object = as_object(incoming, \"incoming\", state_name);\n const existing_shape = existing_object.shape as Record<string, ZodType>;\n const incoming_shape = incoming_object.shape as Record<string, ZodType>;\n for (const key of Object.keys(incoming_shape)) {\n if (key in existing_shape) {\n const existing_base = base_type_name(existing_shape[key]);\n const incoming_base = base_type_name(incoming_shape[key]);\n if (existing_base !== incoming_base) {\n throw new Error(\n `Schema conflict in \"${state_name}\": key \"${key}\" has type \"${existing_base}\" but incoming partial declares \"${incoming_base}\"`\n );\n }\n }\n }\n return existing_object.extend(incoming_shape);\n}\n\n/**\n * Narrows a partial's state schema to the ZodObject that merging needs, or\n * throws naming the state, which side failed, and what it is instead.\n */\nfunction as_object(\n schema: ZodType,\n side: \"existing\" | \"incoming\",\n state_name: string\n): ZodObject {\n if (schema instanceof ZodObject) return schema;\n throw new Error(\n `Cannot merge state schemas for \"${state_name}\": the ${side} partial's schema is a ${schema.constructor.name}, not a z.object. ` +\n `Partials of the same state are merged by extending their shapes, ` +\n `so declare every partial's state as a plain z.object({ ... }).`\n );\n}\n\n/**\n * Merges two init functions by spreading both results together.\n * Each partial only provides its own defaults.\n */\nfunction merge_inits<TState extends Schema>(\n existing: () => Readonly<TState>,\n incoming: () => Readonly<TState>\n): () => Readonly<TState> {\n return () => ({ ...existing(), ...incoming() });\n}\n\n/**\n * Registers a state into a states map and action/event registries,\n * merging with existing same-name states (partial state support).\n */\nexport function register_state(\n state: State<any, any, any>,\n states: Map<string, State<any, any, any>>,\n actions: Record<string, any>,\n events: Record<string, any>\n): void {\n const existing = states.get(state.name);\n if (existing) {\n merge_into_existing(state, existing, states, actions, events);\n } else {\n register_new_state(state, states, actions, events);\n }\n}\n\n/**\n * Registers a state for the first time. All action/event names must be unique\n * across the registry; collisions throw.\n */\nfunction register_new_state(\n state: State<any, any, any>,\n states: Map<string, State<any, any, any>>,\n actions: Record<string, any>,\n events: Record<string, any>\n): void {\n states.set(state.name, state);\n for (const name of Object.keys(state.actions)) {\n if (actions[name]) throw new Error(`Duplicate action \"${name}\"`);\n actions[name] = state;\n }\n for (const name of Object.keys(state.events)) {\n if (events[name]) throw new Error(`Duplicate event \"${name}\"`);\n events[name] = { schema: state.events[name], reactions: new Map() };\n }\n}\n\n/**\n * Picks the value of a field only one partial may declare. Mirrors the\n * `snap` rule: whichever partial declared it wins, and two different\n * declarations are a conflict rather than a silent first-wins.\n *\n * Without this, a spread of `existing` keeps the FIRST partial's value and\n * silently discards the incoming one, so a policy declared on a later slice\n * never runs.\n */\nfunction pick_declared<T>(\n existing: T | undefined,\n incoming: T | undefined,\n what: string,\n state_name: string\n): T | undefined {\n if (existing && incoming && existing !== incoming)\n throw new Error(`Duplicate ${what} for state \"${state_name}\"`);\n return incoming ?? existing;\n}\n\n/**\n * Resolves the `.autocloses(...)` triple. The predicate and its two day\n * fields are set together by the builder, so they move together — taking the\n * predicate from one partial and a day field from another would produce a\n * window the caller never declared.\n */\nfunction autoclose_of(\n existing: State<any, any, any>,\n state: State<any, any, any>\n): Pick<\n State<any, any, any>,\n | \"autoclose\"\n | \"autoclose_after_days\"\n | \"autoclose_after_windows\"\n | \"autoclose_keep_days\"\n> {\n pick_declared(\n existing.autoclose,\n state.autoclose,\n \"autoclose policy\",\n state.name\n );\n const owner = state.autoclose ? state : existing;\n return {\n autoclose: owner.autoclose,\n autoclose_after_days: owner.autoclose_after_days,\n autoclose_after_windows: owner.autoclose_after_windows,\n autoclose_keep_days: owner.autoclose_keep_days,\n };\n}\n\n/**\n * Merges an incoming partial state into an existing same-name state and\n * updates the action/event registries. Splits into four phases:\n * 1. validate no cross-state action/event collisions\n * 2. merge per-event patches (one custom patch per event)\n * 3. build the merged state and replace it in the states map\n * (including the single-declaration policies, which a bare spread\n * would silently take from the first partial only)\n * 4. update action→state pointers and register new events\n */\nfunction merge_into_existing(\n state: State<any, any, any>,\n existing: State<any, any, any>,\n states: Map<string, State<any, any, any>>,\n actions: Record<string, any>,\n events: Record<string, any>\n): void {\n // 1. Validate no cross-state collisions for actions/events\n for (const name of Object.keys(state.actions)) {\n // The same handler means the same partial re-registered via another\n // slice. A shared schema doesn't: two partials can declare one action\n // with one exported schema, and merging them would pair one partial's\n // rules with the other's handler.\n if (existing.on[name] === state.on[name]) continue;\n if (actions[name]) throw new Error(`Duplicate action \"${name}\"`);\n }\n for (const name of Object.keys(state.events)) {\n // Same schema reference means the same partial re-registered via another slice\n if (existing.events[name] === state.events[name]) continue;\n // Same event name registered in a same-name state partial with a\n // different Zod schema reference — silent contract drift that the\n // type system can't catch (structurally compatible shapes flow\n // through TS even when refinements/enums/literals disagree).\n // Reference identity is the rule: cross-slice event schemas must\n // come from a single shared instance.\n if (existing.events[name]) {\n throw new Error(\n `Event \"${name}\" in state \"${state.name}\" is declared with different Zod schemas across slices. ` +\n `Cross-slice event schemas must reference the same instance — ` +\n `extract a shared schema (e.g. \\`export const ${name} = z.object({ ... })\\` in a shared module) ` +\n `and import it in every slice that declares it.`\n );\n }\n if (events[name]) throw new Error(`Duplicate event \"${name}\"`);\n }\n\n // 2. Merge patches with custom-vs-passthrough resolution\n const merged_patch = merge_patches(existing.patch, state.patch, state.name);\n\n // 3. Build merged state\n const merged = {\n ...existing,\n state: merge_schemas(existing.state, state.state, state.name),\n init: merge_inits(existing.init, state.init),\n events: { ...existing.events, ...state.events },\n actions: { ...existing.actions, ...state.actions },\n patch: merged_patch,\n on: { ...existing.on, ...state.on },\n requires: { ...existing.requires, ...state.requires },\n loads:\n existing.loads || state.loads\n ? { ...existing.loads, ...state.loads }\n : undefined,\n snap: pick_declared(existing.snap, state.snap, \"snap strategy\", state.name),\n // Per-action retry policy is keyed by action name, so the two partials'\n // maps combine. Left `undefined` when neither declared one, so the\n // orchestrator's `me.options?.[action]` lookup is unchanged.\n options:\n existing.options || state.options\n ? { ...existing.options, ...state.options }\n : undefined,\n disclose: pick_declared(\n existing.disclose,\n state.disclose,\n \"disclosure predicate\",\n state.name\n ),\n archive: pick_declared(\n existing.archive,\n state.archive,\n \"archiver\",\n state.name\n ),\n // `.autocloses(...)` sets its two day fields alongside the predicate, so\n // the whole triple travels together from whichever partial declared it.\n ...autoclose_of(existing, state),\n };\n states.set(state.name, merged);\n\n // 4. Update action→state pointers; register events not yet seen\n for (const name of Object.keys(merged.actions)) {\n actions[name] = merged;\n }\n for (const name of Object.keys(state.events)) {\n if (events[name]) continue; // already registered, preserve reactions\n events[name] = { schema: state.events[name], reactions: new Map() };\n }\n}\n\n/**\n * Merges two patch maps. Only one custom (non-passthrough) patch per event is\n * allowed; passthroughs always yield to custom reducers, and re-registering\n * the same custom patch (same reference, e.g. across slices) is a no-op.\n */\nfunction merge_patches(\n existing: Record<string, any>,\n incoming: Record<string, any>,\n state_name: string\n): Record<string, any> {\n const merged = { ...existing };\n for (const name of Object.keys(incoming)) {\n const existing_p = existing[name];\n const incoming_p = incoming[name];\n if (!existing_p) {\n merged[name] = incoming_p;\n continue;\n }\n const existing_is_default = existing_p._passthrough;\n const incoming_is_default = incoming_p._passthrough;\n if (\n !existing_is_default &&\n !incoming_is_default &&\n existing_p !== incoming_p\n ) {\n throw new Error(\n `Duplicate custom patch for event \"${name}\" in state \"${state_name}\"`\n );\n }\n // Keep whichever is custom; if both passthrough or existing custom, keep existing\n if (existing_is_default && !incoming_is_default) {\n merged[name] = incoming_p;\n }\n }\n return merged;\n}\n\n/**\n * Merges reactions from one event register into another. The target is\n * assumed to already contain entries for every event name in the source\n * (e.g., act-builder's `.withSlice()` registers the slice's states first,\n * which seeds the target events). Reactions are keyed by `handler.name`;\n * two distinct handlers sharing a name on the same event throw rather than\n * silently overwriting. Re-merging the identical reaction object\n * is idempotent — mirrors {@link register_batch_handler}.\n */\nexport function merge_event_register(\n target: Record<string, { reactions: Map<string, unknown> }>,\n source: Record<string, { reactions: Map<string, unknown> }>\n): void {\n for (const [event_name, source_reg] of Object.entries(source)) {\n const target_reg = target[event_name];\n if (!target_reg) continue;\n for (const [name, reaction] of source_reg.reactions) {\n const existing = target_reg.reactions.get(name);\n if (existing !== undefined && existing !== reaction)\n throw new Error(\n `Duplicate reaction \"${name}\" for event \"${event_name}\". ` +\n `Reaction handlers are keyed by function name; rename one of them.`\n );\n target_reg.reactions.set(name, reaction);\n }\n }\n}\n\n/**\n * Merges a projection's event schemas and reactions into an event registry,\n * deduplicating reaction names by appending \"_p\" on collision.\n */\nexport function merge_projection(\n proj: Projection<any>,\n events: Record<string, any>\n): void {\n for (const event_name of Object.keys(proj.events)) {\n const proj_register = proj.events[event_name];\n const existing = events[event_name];\n if (!existing) {\n events[event_name] = {\n schema: proj_register.schema,\n reactions: new Map(proj_register.reactions),\n };\n } else {\n for (const [name, reaction] of proj_register.reactions) {\n // The `_p` rename resolves a NAME collision between two genuinely\n // different handlers. Registering the SAME reaction object again is\n // not a collision — it is the same projection reached along two\n // paths (exported from a module and embedded by two slices, or a\n // `.withProjection(p)` written twice) — and renaming it registered a\n // second copy under `name_p`, so the handler ran twice per event,\n // forever, frozen into the registry at build.\n //\n // Not the at-least-once redelivery contract: a structural duplicate,\n // deterministic on every event, with no signal anywhere. Both\n // siblings already guard on identity — `merge_event_register` throws\n // on a different handler under the same name, `register_batch_handler`\n // likewise — this one only lacked the check.\n if ([...existing.reactions.values()].includes(reaction)) continue;\n let key = name;\n while (existing.reactions.has(key)) key = `${key}_p`;\n existing.reactions.set(key, reaction);\n }\n }\n }\n}\n\n// Resolves the event stream as source and target (default)\nexport const _this_ = ({ stream }: { stream: string }) => ({\n source: stream,\n target: stream,\n});\n","/**\n * @module builder-utils\n * @category Internal\n *\n * Shared builder machinery reused by both `act-builder.ts` and\n * `slice-builder.ts`. The two builders expose the same reaction-registration\n * and lane-declaration surface and differ only in the concrete builder type\n * they return (`ActBuilder` vs `SliceBuilder`) and the event register they\n * write into (`registry.events` vs the slice's `events`). This module owns the\n * one copy of that logic so the builders stay thin delegations.\n *\n * @internal\n */\n\nimport {\n DEFAULT_BLOCK_ON_ERROR,\n DEFAULT_MAX_RETRIES,\n resolveLaneConfig,\n resolveReactionConfig,\n resolveTargetConfig,\n} from \"../internal/config.js\";\nimport {\n assert_defer_when,\n type DeferSchedule,\n make_deferred,\n} from \"../internal/defer-config.js\";\nimport type {\n Committed,\n EventRegister,\n LaneConfig,\n Reaction,\n ReactionHandler,\n ReactionOptions,\n ReactionResolver,\n Schemas,\n} from \"../types/index.js\";\nimport { DEFAULT_LANE } from \"../types/index.js\";\nimport { _this_ } from \"./merge.js\";\n\n/**\n * Validate and register a drain lane, the one rule for `withLane` on an Act\n * or a slice and for the lanes a slice brings to `withSlice`, in any order.\n * Validating here means a bad lane bag throws at declaration, not by\n * silently draining nothing. `\"default\"` is reserved; a name declares one\n * config, so declaring it again with the same config is a no-op and with a\n * different one throws. Mutates `lanes` in place.\n *\n * @internal\n */\nexport function register_lane(config: LaneConfig, lanes: LaneConfig[]): void {\n resolveLaneConfig(config);\n if (config.name === DEFAULT_LANE)\n throw new Error(`Lane \"${DEFAULT_LANE}\" is reserved`);\n const existing = lanes.find((l) => l.name === config.name);\n if (!existing) return void lanes.push(config);\n if (\n existing.leaseMillis !== config.leaseMillis ||\n existing.streamLimit !== config.streamLimit ||\n existing.cycleMs !== config.cycleMs\n )\n throw new Error(\n `Lane \"${config.name}\" was already declared with a different config`\n );\n}\n\n/**\n * Register a reaction once, keyed by its handler's name, and hand back\n * `builder` patched with `.to(...)`, which reroutes the same reaction in\n * place (no second `Map.set()`). The one registration step for reactions and\n * projection handlers: the named-function and duplicate guards run before\n * `make` builds the reaction, and `kind` picks the wording of their errors.\n *\n * @internal\n */\nexport function add_reaction<\n TEvents extends Schemas,\n TKey extends keyof TEvents,\n TBuilder extends object,\n>(\n events: EventRegister<TEvents>,\n event: TKey,\n name: string,\n kind: \"Reaction\" | \"Projection\",\n make: () => Reaction<TEvents, TKey>,\n builder: TBuilder\n) {\n if (!name)\n throw new Error(\n `${kind} handler for \"${String(event)}\" must be a named function`\n );\n const label = kind === \"Reaction\" ? \"reaction\" : \"projection handler\";\n if (events[event].reactions.has(name))\n throw new Error(\n `Duplicate ${label} \"${name}\" for event \"${String(event)}\". ` +\n `${kind} handlers are keyed by function name; rename one of them.`\n );\n const reaction = make();\n events[event].reactions.set(name, reaction);\n return Object.assign(builder, {\n to(resolver: ReactionResolver<TEvents, TKey> | string) {\n if (typeof resolver === \"object\") resolveTargetConfig(resolver);\n reaction.resolver =\n typeof resolver === \"string\" ? { target: resolver } : resolver;\n return builder;\n },\n });\n}\n\n/**\n * Build the `.on(event)` step shared by both builders. Registers a reaction\n * (named-function + duplicate guards, fail-fast literal-schedule validation,\n * the default `_this_` resolver, and the `.defer` handler wrap) into\n * `events[event].reactions`, and hands back `builder` patched with `.to(...)`\n * for in-place resolver routing.\n *\n * The strict, builder-specific type is supplied by each builder's own `on`\n * signature ({@link ReactionOn}); the runtime here is builder-agnostic.\n *\n * @internal\n */\nexport function reaction_on<\n TEvents extends Schemas,\n TKey extends keyof TEvents,\n TBuilder extends object,\n>(event: TKey, events: EventRegister<TEvents>, builder: TBuilder) {\n const register = (\n handler: ReactionHandler<TEvents, TKey>,\n options?: Partial<ReactionOptions>,\n schedule?: DeferSchedule<Committed<TEvents, TKey>>\n ) =>\n add_reaction(\n events,\n event,\n handler.name,\n \"Reaction\",\n () => {\n // Fail fast on a bad literal schedule; the function form is checked\n // when it runs (no event to resolve against at build time).\n if (schedule && typeof schedule !== \"function\")\n assert_defer_when(schedule);\n return {\n handler: schedule ? make_deferred(handler, schedule) : handler,\n resolver: _this_,\n // Validate the whole bag at the declaration site so a bad\n // `maxRetries`/`backoff`/`blockOnError` throws ZodError at build,\n // not a NaN gate on the first retry.\n options: resolveReactionConfig({\n blockOnError: options?.blockOnError ?? DEFAULT_BLOCK_ON_ERROR,\n maxRetries: options?.maxRetries ?? DEFAULT_MAX_RETRIES,\n backoff: options?.backoff,\n }),\n };\n },\n builder\n );\n return {\n do: (\n handler: ReactionHandler<TEvents, TKey>,\n options?: Partial<ReactionOptions>\n ) => register(handler, options),\n defer: (schedule: DeferSchedule<Committed<TEvents, TKey>>) => ({\n do: (\n handler: ReactionHandler<TEvents, TKey>,\n options?: Partial<ReactionOptions>\n ) => register(handler, options, schedule),\n }),\n };\n}\n","/**\n * @module event-builder\n * @category Internal\n *\n * Everything `act().build()` derives from the registered events.\n *\n * This is the build-time half of the event lifecycle. The other two halves\n * are the `sensitive(...)` marker (`sensitive.ts`) and the runtime\n * transforms (`pii_gate`, `pii_strip`, `pii_split`, in `internal/pii.ts`)\n * that a reader is composed from. Nothing here runs per event at runtime; everything here runs\n * once, at build, and hands the orchestrator a prebuilt function.\n *\n * Three things are derived, all in ONE walk over the registered events:\n *\n * - **validation** — a reaction may not target a lane nobody declared, nor a\n * target a projection already serves. Both checks skip dynamic resolvers,\n * because a `.to(fn)` target is unknowable until an event arrives.\n * - **resolution** — each event's schema is read once into {@link EventTags}:\n * which fields are sensitive, and how to revive the dates in a stored\n * payload. Working out where the dates are is a Zod concern, so it lives in\n * `internal/date-reviver.ts`; this module composes what that returns.\n * - **composition** — the per-surface readers, each a single {@link EventGate}\n * that types the payload and applies disclosure in one call.\n *\n * Deliberately NOT here: deprecation. `Foo` is deprecated only because\n * `Foo_v2` exists beside it, so it is derived from event *names across a whole\n * state* rather than from one event's schema — and it governs *emitting* (a\n * static `.emit()` throws at build), not reading. Replay of a deprecated event\n * stays silent by design.\n *\n * @internal\n */\n\nimport { z } from \"zod\";\nimport { date_reviver_schema } from \"../internal/date-reviver.js\";\nimport {\n type EventGate,\n IDENTITY_GATE,\n make_gate,\n pii_split,\n pii_strip,\n} from \"../internal/pii.js\";\nimport { def_of, output_of } from \"../internal/zod.js\";\nimport { pii_schemas } from \"../sensitive.js\";\nimport type { Actor, LaneConfig, Registry } from \"../types/index.js\";\nimport { DEFAULT_LANE, SNAP_EVENT } from \"../types/index.js\";\n\n/** What one pass over an event's schema resolves. @internal */\nexport type EventTags = {\n /**\n * Keys marked `sensitive(...)`, top level (and across union variants), with\n * the schema each declares.\n */\n readonly sensitive: Readonly<Record<string, z.ZodType>>;\n /**\n * Revives the dates in a stored `data` payload, or `undefined` when the\n * schema declares none.\n */\n readonly date_reviver: ((data: unknown) => unknown) | undefined;\n /**\n * Revives the dates in a stored `pii` sidecar, or `undefined` when no\n * sensitive field is a date.\n */\n readonly pii_date_reviver: ((pii: unknown) => unknown) | undefined;\n};\n\n/**\n * Resolve an event's schema in a single pass.\n *\n * Sensitive markers are read at the top level only — the documented carve-out\n * (`sensitive.ts`), since the write path splits whole top-level keys. A union\n * event has no top-level shape, so its variants are walked and unioned: a key\n * sensitive in any variant must be split, because the stored payload could be\n * that variant.\n *\n * @internal\n */\nexport function event_tags(schema: z.ZodType): EventTags {\n // Which fields are sensitive is `sensitive.ts`'s question and where the\n // dates are is `date-reviver.ts`'s; this composes the two answers. The\n // sidecar holds the split-out fields alone, so a date among them needs its\n // own reviver — without it a disclosed `sensitive(z.date())` arrives as text\n // beside a plain sibling that is a Date.\n const pii = pii_schemas(schema);\n const pii_dates: Record<string, z.ZodType> = {};\n for (const [key, field] of Object.entries(pii)) {\n const dates = date_reviver_schema(field);\n if (dates) pii_dates[key] = dates.optional();\n }\n\n const data_reviver_schema = date_reviver_schema(schema);\n // Reviving must never reject. A stored payload can disagree with the current\n // declaration in ways this schema deliberately does not describe, and handing\n // back what is stored beats refusing to read it.\n const revive = (schema: z.ZodType) => (data: unknown) => {\n const revived = schema.safeParse(data);\n return revived.success ? revived.data : data;\n };\n const dated_pii = Object.keys(pii_dates).length > 0;\n return {\n sensitive: pii,\n date_reviver: data_reviver_schema && revive(data_reviver_schema),\n pii_date_reviver: dated_pii ? revive(z.looseObject(pii_dates)) : undefined,\n };\n}\n\n/**\n * What the reader should do about sensitive fields.\n *\n * - `redact` — substitute `[REDACTED]` unless `disclose` authorizes the actor,\n * and drop the `pii` sidecar. The read surfaces (`query`, `query_array`,\n * `load`).\n * - `strip` — remove the keys entirely. Reaction and projection handlers,\n * which never see PII by framework rule, and shouldn't structurally observe\n * the keys either.\n *\n * @internal\n */\nexport type Disclosure = \"redact\" | \"strip\";\n\n/**\n * Compose one event's typing and disclosure into a single gate.\n *\n * Returns `undefined` when the event needs neither, so the caller can fall\n * back to the shared {@link IDENTITY_GATE} and the common path allocates\n * nothing.\n *\n * @internal\n */\nfunction make_event_reader(\n tags: EventTags,\n disclosure: Disclosure,\n predicate: ((event: never, actor: Actor) => boolean) | null = null\n): EventGate | undefined {\n const { date_reviver, pii_date_reviver } = tags;\n const sensitive = Object.keys(tags.sensitive);\n if (!date_reviver && sensitive.length === 0) return undefined;\n\n const gate: EventGate =\n sensitive.length === 0\n ? IDENTITY_GATE\n : disclosure === \"strip\"\n ? (((event) => pii_strip(event as never, sensitive)) as EventGate)\n : make_gate(sensitive, predicate as never);\n\n if (!date_reviver) return gate;\n\n // The sidecar is only worth reviving for a reader that can be shown it.\n // A `strip` reader drops `pii` outright, and a redacting one discloses only\n // to an actor a predicate approves — so no actor and no predicate means the\n // values are on their way to REDACTED whatever they hold. The predicate\n // itself stays uncalled here: the gate owns that decision and calling it\n // twice would run a caller's code twice.\n const revive_pii =\n disclosure === \"redact\" && predicate ? pii_date_reviver : undefined;\n\n // Revive before disclosing: the gate copies, so reviving afterwards would\n // leave the consumer's value a string — and it substitutes REDACTED and\n // SHREDDED, which are not dates.\n return ((event, actor) => {\n const pii = (event as { pii?: unknown }).pii;\n return gate(\n {\n ...event,\n data: date_reviver(event.data),\n ...(revive_pii && actor && pii != null ? { pii: revive_pii(pii) } : {}),\n } as never,\n actor\n );\n }) as EventGate;\n}\n\n/**\n * Exactly what the registry serves, keyed by event name — no intermediates.\n *\n * The per-state `view` is installed directly on each state rather than\n * returned: it is event-derived wiring like the rest, and handing it back for\n * the caller to install would put the composition back where it came from.\n *\n * @internal\n */\nexport type BuiltEvents = {\n /** Backs `registry.sensitive_fields`. */\n readonly sensitive: Map<string, readonly string[]>;\n /**\n * The sensitive-type advisory, naming each sensitive `Event.field`, and\n * `State.field` of its name, that a redaction marker doesn't fit; or\n * `undefined` when there are none. The builder logs it once.\n */\n readonly advisory: string | undefined;\n /** Backs `registry.query_gate` — the actor-less read surfaces. */\n readonly query_readers: Map<string, EventGate>;\n /** Readers for handlers — sensitive keys removed, payload typed. */\n readonly handler_readers: Map<string, EventGate>;\n};\n\n/** What validation needs to know about the projections already registered. */\nexport type TargetOwners = {\n readonly batch_handlers: ReadonlyMap<string, unknown>;\n readonly fold_targets: ReadonlySet<string>;\n /** A projection's own reactions legitimately target it — excluded by identity. */\n readonly projection_reactions: ReadonlySet<unknown>;\n};\n\ntype EventEntry = {\n schema: import(\"zod\").ZodType;\n reactions: Map<string, { handler: any; resolver: unknown }>;\n};\n\n/**\n * Validate every static reaction and wire every event, in a single walk.\n *\n * Ownership conflicts throw as they are found; lane violations are collected\n * and thrown afterwards. That ordering is deliberate — it preserves the\n * precedence the two separate passes had, where the ownership guard ran to\n * completion before lane references were checked, so a config violating both\n * reports the same error it always did.\n *\n * @internal\n */\nexport function build_events(\n registry: Registry<any, any, any>,\n states: ReadonlyMap<string, any>,\n lanes: ReadonlyArray<LaneConfig>,\n owners: TargetOwners\n): BuiltEvents {\n const declared = new Set<string>([DEFAULT_LANE, ...lanes.map((l) => l.name)]);\n const lane_errors: string[] = [];\n\n const tags = new Map<string, EventTags>();\n const sensitive = new Map<string, readonly string[]>();\n const query_readers = new Map<string, EventGate>();\n const handler_readers = new Map<string, EventGate>();\n\n for (const [event_name, def] of Object.entries(\n registry.events as Record<string, EventEntry>\n )) {\n for (const [handler_name, reaction] of def.reactions) {\n // A build-time guard can only see a static target: a `.to(fn)` target\n // is unknowable until an event arrives.\n if (typeof reaction.resolver === \"function\") continue;\n const resolver = reaction.resolver as { target: string; lane?: string };\n\n const claimed =\n owners.batch_handlers.has(resolver.target) ||\n owners.fold_targets.has(resolver.target);\n if (claimed && !owners.projection_reactions.has(reaction))\n throw new Error(\n `Reaction on target \"${resolver.target}\" conflicts with the projection that already serves it — a target is served by one batch handler or one state projection, and a reaction to it would never run`\n );\n\n if (resolver.lane !== undefined && !declared.has(resolver.lane))\n lane_errors.push(\n `Reaction \"${handler_name}\" on \"${event_name}\" targets undeclared lane \"${resolver.lane}\". ` +\n `Declared lanes: ${[...declared].map((l) => `\"${l}\"`).join(\", \")}. ` +\n `Add \\`.withLane({ name: \"${resolver.lane}\", ... })\\` to act() or correct the .to() declaration.`\n );\n }\n\n // One resolution of the declared schema yields both facts a reader is\n // built from: which fields are sensitive, and how to type the payload.\n const event = event_tags(def.schema);\n tags.set(event_name, event);\n const fields = Object.keys(event.sensitive);\n if (fields.length > 0) sensitive.set(event_name, fields);\n\n // An event needing neither typing nor redaction produces no reader and\n // falls back to the shared IDENTITY_GATE — zero per-event cost.\n const query_reader = make_event_reader(event, \"redact\", null);\n if (query_reader) query_readers.set(event_name, query_reader);\n\n // Handlers never see PII by framework rule, and shouldn't observe the\n // keys structurally either — so `strip`, not `redact`.\n const handler_reader = make_event_reader(event, \"strip\");\n if (handler_reader) {\n handler_readers.set(event_name, handler_reader);\n for (const [name, reaction] of def.reactions) {\n const inner = reaction.handler;\n const wrapped = (evt: any, stream: string, app: any) =>\n inner(handler_reader(evt), stream, app);\n // Preserve handler.name — build_handle asserts on named functions.\n Object.defineProperty(wrapped, \"name\", { value: inner.name });\n reaction.handler = wrapped;\n def.reactions.set(name, reaction as never);\n }\n }\n }\n\n if (lane_errors.length > 0) throw new Error(lane_errors[0]);\n\n // Per-state wiring, all of it derived from the same event resolution: the\n // read view, the write split, and the guard that refuses to combine the two\n // things that cannot coexist.\n //\n // A sensitive field reads as \"[REDACTED]\" or \"[SHREDDED]\" to a caller who\n // may not see it, and so does any state field a reducer copies it into: a\n // string. A field typed as anything else then holds a value its type\n // doesn't allow, so it is named in the advisory. A state field is matched by\n // name; a copy under another name can't be seen from the types.\n const advised = new Set<string>();\n for (const state of states.values()) {\n const shape: Record<string, z.ZodType> = state.state.shape ?? {};\n const state_fields = new Map<string, readonly string[]>();\n for (const event_name of Object.keys(state.events)) {\n const fields = sensitive.get(event_name);\n if (!fields) continue;\n state_fields.set(event_name, fields);\n const event = tags.get(event_name) as EventTags;\n for (const field of fields) {\n if (!reads_as_string(event.sensitive[field]))\n advised.add(`${event_name}.${field}`);\n if (shape[field] && !reads_as_string(shape[field]))\n advised.add(`${state.name}.${field}`);\n }\n }\n\n if (state_fields.size > 0) {\n // Snapshots write derived state into `__snapshot__.data`, which\n // `forget_pii` cannot reach. Reject the combination at build so the\n // misconfiguration surfaces in dev/CI, not as a silent leak past the\n // GDPR boundary months later.\n if (state.snap)\n throw new Error(\n `State \"${state.name}\" cannot snapshot — events {${[...state_fields.keys()].join(\", \")}} carry sensitive fields. ` +\n \"Snapshots write derived state into __snapshot__.data, which forget_pii cannot reach. \" +\n \"Remove .snap() or remove sensitive(...) markers.\"\n );\n state.pii_aware = true;\n // The write half: split declared fields into the `pii` sidecar on the\n // way to `Store.commit`.\n state.message = (validated: { name: string }) => {\n const fields = state_fields.get(validated.name);\n return fields ? pii_split(validated as never, fields) : validated;\n };\n }\n\n // The read half. A state's disclosure predicate is an input to the\n // reader, not a second gate layered over it. A `__snapshot__` carries\n // folded STATE rather than event data, so its typing comes from the state\n // schema — without that a restart from a snapshot loses every `z.date()`\n // the state holds.\n const readers = new Map<string, EventGate>();\n for (const event_name of Object.keys(state.events)) {\n const event = tags.get(event_name);\n const reader =\n event && make_event_reader(event, \"redact\", state.disclose ?? null);\n if (reader) readers.set(event_name, reader);\n }\n const snap = make_event_reader(event_tags(state.state), \"redact\", null);\n if (snap) readers.set(SNAP_EVENT, snap);\n if (readers.size === 0) continue;\n state.view = (event: { name: string }, actor: Actor) =>\n (readers.get(event.name) ?? IDENTITY_GATE)(event as never, actor);\n }\n\n const advisory =\n advised.size > 0\n ? `Act has ${advised.size} sensitive field(s) whose type isn't a string: ${[...advised].join(\", \")}. ` +\n `A caller who may not see one reads \"[REDACTED]\" or \"[SHREDDED]\" there instead, ` +\n `which its type doesn't allow. Declare sensitive fields as strings. ` +\n `See docs/docs/guides/sensitive-data.md.`\n : undefined;\n return { sensitive, advisory, query_readers, handler_readers };\n}\n\n// Whether a schema's value is a string, so a redaction marker fits its type.\n// A transform's output can't be known, so it counts as a string rather than\n// be named falsely.\nfunction reads_as_string(schema: z.ZodType): boolean {\n const type = def_of(output_of(schema))?.type;\n return type === \"string\" || type === \"transform\";\n}\n","/**\n * Turning stored text back into `Date`s, driven by the declared schema.\n *\n * JSON has no date type, so a `Date` is stored as its ISO form. Which fields\n * to revive is a property of the Zod schema, so this module takes a schema\n * and returns one that revives its dates (or `undefined` when there are\n * none); it knows nothing about events. A field declared `z.string()` stays\n * a string even when it looks like an ISO date.\n */\n\nimport { z } from \"zod\";\nimport { def_of, inner_of } from \"./zod.js\";\n\ntype Walk = (schema: unknown) => z.ZodType | undefined;\n\n/**\n * Rebuild one union variant so it still recognises its own payloads.\n *\n * Same date coercion as everywhere else, but the variant keeps its other\n * fields — this is the one place the date paths alone are not enough. A\n * variant can only reject a sibling's payload if enough of its shape is left\n * to check, and which fields do that is not knowable: a literal discriminator\n * usually does it, but a union can just as well be told apart by the *type* of\n * an ordinary field. Narrowing to the dates, or relaxing the rest, makes the\n * first variant match everything, so the one that declared the date is never\n * tried and a sibling's payload is read under the wrong rules.\n *\n * Every key is optional, so the variant still matches when a `sensitive(...)`\n * field sits in the `pii` sidecar or when a stored payload predates a field\n * the declaration has since gained.\n *\n * Reports whether this variant declared a date, so a union with none anywhere\n * builds nothing at all.\n */\nfunction variant_schema(\n schema: unknown,\n walk: Walk\n): {\n schema: z.ZodType;\n dated: boolean;\n} {\n const shape = def_of(schema)?.shape as Record<string, z.ZodType> | undefined;\n if (!shape) {\n const dates = walk(schema);\n return { schema: dates ?? (schema as z.ZodType), dated: !!dates };\n }\n const next: Record<string, z.ZodType> = {};\n let dated = false;\n for (const [key, field] of Object.entries(shape)) {\n const dates = walk(field);\n if (dates) dated = true;\n next[key] = (dates ?? field).optional();\n }\n return { schema: z.looseObject(next), dated };\n}\n\n/**\n * Build the schema that revives an event's dates, or `undefined` when it\n * declares none.\n *\n * JSON has no date type, so a stored `Date` comes back as text and something\n * has to turn it back. That is this function's only job, and the schema it\n * returns says only where the dates are: every other field is left out and\n * rides through the loose object untouched. The payload was validated when it\n * was committed, so re-checking it on the way out would be work already done.\n *\n * Naming only the dates is also what makes a read tolerant, without needing a\n * rule per exception. A `sensitive(...)` field lives in the `pii` sidecar\n * rather than in `data`; an event written against an older declaration\n * predates whatever was added since; a field dropped from the declaration is\n * still in the store. None of those are dates, so none of them are described\n * here, and a payload carrying any of them still reads. The dates themselves\n * are optional for the same reason — absent is not wrong.\n *\n * Zod does the walking, so nesting, arrays, records, unions and the wrappers\n * are handled by the engine rather than by a traversal of our own that would\n * drift as Zod grows constructs. A construct this doesn't recognise\n * contributes no date, which is the documented fallthrough.\n *\n * A recursive schema is walked twice. The first pass stops at any schema it is\n * already inside, which visits everything reachable and answers whether there\n * is a date at all, so a recursive schema with none still builds nothing. The\n * second ties each of those stops back to the schema's own result.\n */\nexport function date_reviver_schema(schema: unknown): z.ZodType | undefined {\n let recursive = false;\n const pass = (tie: boolean): z.ZodType | undefined => {\n const done = new Map<unknown, z.ZodType | undefined>();\n const active = new Set<unknown>();\n const walk: Walk = (node) => {\n if (done.has(node)) return done.get(node);\n if (active.has(node)) {\n recursive = true;\n // Every schema on a cycle has a result by the time this reads it.\n return tie ? z.lazy(() => done.get(node) as z.ZodType) : undefined;\n }\n active.add(node);\n const result = build(node, walk);\n active.delete(node);\n done.set(node, result);\n return result;\n };\n return walk(schema);\n };\n const first = pass(false);\n return first && recursive ? pass(true) : first;\n}\n\nfunction build(schema: unknown, walk: Walk): z.ZodType | undefined {\n const def = def_of(schema);\n if (!def) return undefined;\n const inner = () => walk(def.innerType);\n switch (def.type) {\n case \"date\":\n return z.coerce.date();\n case \"object\": {\n const shape = def.shape as Record<string, z.ZodType> | undefined;\n if (!shape) return undefined;\n const dated: Record<string, z.ZodType> = {};\n for (const [key, field] of Object.entries(shape)) {\n const dates = walk(field);\n if (dates) dated[key] = dates.optional();\n }\n return Object.keys(dated).length ? z.looseObject(dated) : undefined;\n }\n case \"array\": {\n const element = walk(def.element);\n return element && z.array(element);\n }\n case \"tuple\": {\n const items = (def.items as unknown[]).map((i) => walk(i));\n return items.some(Boolean)\n ? z.tuple(items.map((i) => i ?? z.unknown()) as never)\n : undefined;\n }\n case \"record\": {\n const value = walk(def.valueType);\n return value && z.record(z.string(), value);\n }\n case \"union\": {\n // A union is the one place the date paths are not enough. Zod picks a\n // variant by trying each until one matches, so an option reduced to its\n // dates matches almost anything and the first one wins — the variant\n // that actually declared the date never gets tried, and a sibling's\n // payload gets the wrong variant's rules. Every option therefore keeps\n // its fields; see {@link variant_schema}.\n const variants = (def.options as unknown[]).map((o) =>\n variant_schema(o, walk)\n );\n return variants.some((v) => v.dated)\n ? z.union(variants.map((v) => v.schema) as never)\n : undefined;\n }\n case \"nullable\":\n // Keep the null: coercing it would hand back the epoch.\n return inner()?.nullable();\n case \"pipe\":\n // `z.preprocess()` and `.pipe()`: the stored value is the output side.\n // A `.transform()`'s output is unknown, so it revives nothing.\n return walk(def.out);\n case \"lazy\":\n return walk((def.getter as () => unknown)());\n case \"intersection\": {\n // One side after the other, not a Zod intersection: each side keeps the\n // fields it doesn't revive, so the two results wouldn't merge.\n const left = walk(def.left);\n const right = walk(def.right);\n return left && right ? left.pipe(right) : (left ?? right);\n }\n default:\n return inner_of(def) ? inner() : undefined;\n }\n}\n","/**\n * @module act-builder\n * @category Builders\n *\n * Fluent builder for composing event-sourced applications.\n */\nimport { Act } from \"../act.js\";\nimport { synthesize_autoclose_reactions } from \"../internal/autoclose-reaction.js\";\nimport { resolveActConfig } from \"../internal/config.js\";\nimport {\n current_version_of,\n deprecated_event_names,\n} from \"../internal/event-versions.js\";\nimport { type EventGate, IDENTITY_GATE } from \"../internal/pii.js\";\nimport {\n FOLD_RESET,\n make_fold_handler,\n type ResettableBatchHandler,\n} from \"../internal/projection-fold.js\";\nimport { log } from \"../ports.js\";\nimport { current_autoclose_window } from \"../scoped.js\";\nimport type { ActBuilder, Projection } from \"../types/builders.js\";\nimport type {\n ActOptions,\n Actor,\n BatchHandler,\n LaneConfig,\n Load,\n Registry,\n Schema,\n SchemaRegister,\n Schemas,\n State,\n} from \"../types/index.js\";\nimport { reaction_on, register_lane } from \"./builder-utils.js\";\nimport { build_events } from \"./event-builder.js\";\nimport {\n merge_event_register,\n merge_projection,\n register_state,\n} from \"./merge.js\";\n\n/**\n * Registers a projection's batch handler against its target stream, throwing\n * if a different handler already serves it. Folds (`.of(...)`) have no\n * batch handler; their side of the check is in `build()`.\n */\nfunction register_batch_handler(\n proj: Projection<any>,\n batch_handlers: Map<string, BatchHandler<any>>\n): void {\n if (!proj.batchHandler || !proj.target) return;\n const existing = batch_handlers.get(proj.target);\n if (existing && existing !== proj.batchHandler) {\n throw new Error(\n `Duplicate projection target \"${proj.target}\" — a target is served by one batch handler or one state projection, never both`\n );\n }\n batch_handlers.set(proj.target, proj.batchHandler);\n}\n\n/**\n * Creates a new Act orchestrator builder for composing event-sourced applications.\n *\n * @example Basic application with single state\n * ```typescript\n * const app = act()\n * .withState(Counter)\n * .build();\n * ```\n *\n * @see {@link ActBuilder} for available builder methods\n * @see {@link Act} for orchestrator API methods\n * @see {@link state} for defining states\n * @see {@link slice} for defining slices\n */\nexport function act(): ActBuilder<{}, {}, {}, {}, Actor>;\nexport function act<\n TSchemaReg extends SchemaRegister<TActions>,\n TEvents extends Schemas = {},\n TActions extends Schemas = {},\n TStateMap extends Record<string, Schema> = {},\n TActor extends Actor = Actor,\n>(): ActBuilder<TSchemaReg, TEvents, TActions, TStateMap, TActor>;\nexport function act<\n TSchemaReg extends SchemaRegister<TActions>,\n TEvents extends Schemas = {},\n TActions extends Schemas = {},\n TStateMap extends Record<string, Schema> = {},\n TActor extends Actor = Actor,\n>(): ActBuilder<TSchemaReg, TEvents, TActions, TStateMap, TActor> {\n // Mutable runtime state — one set of references shared across the entire\n // fluent chain. Each `with*` / `on` call mutates these and returns the\n // same builder cast to the widened generic; type fanout is preserved\n // through the public type signatures, runtime allocation is not.\n const states = new Map<string, State<any, any, any>>();\n // Caches behind the registry's derived lookups, populated on the first\n // `.build()`. Each event schema is walked once.\n const _sf = new Map<string, readonly string[]>();\n // Prebuilt handler readers — sensitive keys removed, payload typed. Absent\n // when the event needs neither.\n const _hr = new Map<string, EventGate>();\n // Prebuilt default-deny read gates, one per sensitive event. Non-sensitive\n // events are absent → `query_gate` falls back to the shared IDENTITY_GATE.\n const _qg = new Map<string, EventGate>();\n const _dp = new Map<string, (event: any, actor: Actor) => boolean>();\n const _de = new Map<string, ReadonlySet<string>>();\n const _ac = new Map<\n string,\n (stream: string, head: any, count: number) => boolean\n >();\n const _aa = new Map<string, (stream: string, head: any) => Promise<void>>();\n const EMPTY_DEPRECATED: ReadonlySet<string> = new Set();\n const registry: Registry<TSchemaReg, TEvents, TActions> = {\n actions: {} as Registry<TSchemaReg, TEvents, TActions>[\"actions\"],\n events: {} as Registry<TSchemaReg, TEvents, TActions>[\"events\"],\n sensitive_fields: (event_name) => _sf.get(event_name) ?? [],\n query_gate: (event_name) => _qg.get(event_name) ?? IDENTITY_GATE,\n disclosure_predicate: (state_name) => _dp.get(state_name) ?? null,\n deprecated_events: (state_name) => _de.get(state_name) ?? EMPTY_DEPRECATED,\n autoclose_policy: (state_name) => _ac.get(state_name) ?? null,\n autoclose_archiver: (state_name) => _aa.get(state_name) ?? null,\n };\n const pending_projections: Projection<any>[] = [];\n /**\n * Reactions contributed by projections, recorded at registration. Only\n * these may target a projection's stream; anything else is a collision.\n */\n const projection_reactions = new Set<unknown>();\n const record_projection_reactions = (proj: Projection<any>) => {\n // Only a projection that SERVES its target (a batch handler or a fold)\n // owns it. A per-event projection naming the same target is just another\n // claimant: exempting it let it share a fold's or batch's target, where\n // its handler never ran and the fold wrote foreign rows.\n if (!proj.batchHandler && !proj.fold) return;\n for (const register of Object.values(\n proj.events as Record<string, { reactions: Map<string, unknown> }>\n ))\n for (const reaction of register.reactions.values())\n projection_reactions.add(reaction);\n };\n const fold_projections: Projection<any>[] = [];\n const batch_handlers = new Map<string, BatchHandler<any>>();\n const add_projection = (proj: Projection<any>) => {\n record_projection_reactions(proj);\n merge_projection(proj, registry.events as Record<string, any>);\n register_batch_handler(proj, batch_handlers);\n if (proj.fold) fold_projections.push(proj);\n };\n // Validated fold-projection ingredients, resolved once on the first\n // build. The HANDLERS themselves are built per `.build()` — see\n // `make_batch_handlers` — because a fold handler owns a mutable\n // per-stream cache that must never be shared across Acts.\n const fold_specs: {\n target: string;\n /** Identity of the registering projection, so a repeat registration of\n * the same object is recognized as one claim rather than two. */\n projection: Projection<any>;\n merged: any;\n flush: any;\n config: any;\n }[] = [];\n const lanes: LaneConfig[] = [];\n\n // Set on the first `.build()` call. Lets the same builder produce\n // many Acts (multi-tenant / A-B testing patterns) without re-merging\n // projections or re-logging the deprecation advisory.\n let _built = false;\n\n /**\n * Wraps a batch handler so it receives events in handler form — payload\n * typed from the declared schema, sensitive keys removed — the same reader\n * `event-builder` gives per-event handlers. Resolved lazily at dispatch, by\n * when the events pass has populated it.\n */\n const read_wrap = (original: BatchHandler<any>): BatchHandler<any> => {\n const wrapped = async (events: readonly any[], stream: string) => {\n // The same prebuilt reader the per-event handlers get: typed payload,\n // sensitive keys removed. Absent → the event passes through untouched.\n const read = events.map((e) => _hr.get(e.name as string)?.(e) ?? e);\n return original(read as never, stream);\n };\n // Carry the fold's cache-reset handle through the wrapper. The\n // orchestrator only ever sees what this map holds, so a handle left on\n // the inner handler is a handle nobody can reach.\n const reset = (original as ResettableBatchHandler<any>)[FOLD_RESET];\n if (reset) Object.defineProperty(wrapped, FOLD_RESET, { value: reset });\n return wrapped;\n };\n\n /**\n * Per-Act batch-handler map. Stateless handlers are shared; fold\n * handlers own a per-stream cache, so each `.build()` gets fresh ones.\n */\n const make_batch_handlers = () => {\n const handlers = new Map(batch_handlers);\n for (const spec of fold_specs) {\n handlers.set(\n spec.target,\n read_wrap(\n make_fold_handler(\n spec.merged,\n spec.flush,\n spec.config,\n // Head loads strip sensitive keys like the warm path.\n registry.sensitive_fields\n )\n ) as never\n );\n }\n return handlers;\n };\n\n // Versioned events: per state, the highest `_v<n>` is current and lower\n // ones are deprecated (`registry.deprecated_events`). A static\n // `.emit(\"X\")` of a deprecated event throws; a one-line advisory lists\n // the legacy events kept for replay.\n const finalize_deprecations = () => {\n const deprecation_summary: Array<{\n state_name: string;\n deprecated: string;\n current: string;\n }> = [];\n for (const state of states.values()) {\n const event_names = Object.keys(state.events);\n const deprecated = deprecated_event_names(event_names);\n if (deprecated.size === 0) continue;\n _de.set(state.name, deprecated);\n for (const name of deprecated) {\n // `current_version_of` is guaranteed non-undefined here — `name`\n // is in `deprecated`, which by construction means a higher-\n // versioned sibling exists in the same group.\n const current = current_version_of(name, event_names) as string;\n deprecation_summary.push({\n state_name: state.name,\n deprecated: name,\n current,\n });\n }\n for (const [action_name, handler] of Object.entries(state.on)) {\n const static_target = (handler as { _static_emit?: string } | undefined)\n ?._static_emit;\n if (static_target && deprecated.has(static_target)) {\n const current = current_version_of(static_target, event_names);\n throw new Error(\n `Action \"${action_name}\" in state \"${state.name}\" emits deprecated event \"${static_target}\". ` +\n `A newer version exists: \"${current}\". Update the .emit() call ` +\n `to target the current version. The reducer (.patch) for ` +\n `\"${static_target}\" stays as-is — historical events still need it.`\n );\n }\n }\n }\n if (deprecation_summary.length > 0) {\n const list = deprecation_summary\n .map(\n (d) =>\n `\"${d.deprecated}\" (current: \"${d.current}\", state: \"${d.state_name}\")`\n )\n .join(\", \");\n log().info(\n `Act registered ${deprecation_summary.length} deprecated event(s): ${list}. ` +\n `These are legacy versions kept for the read path. Consider truncating ` +\n `closed streams via app.close() when feasible to reduce historical event load. ` +\n `See docs/docs/architecture/event-schema-evolution.md.`\n );\n }\n };\n\n /**\n * Registration is closed once `build()` has classified the registry: every\n * mutating method throws a clear error after it. `build()` itself stays\n * callable repeatedly, since the multi-tenant pattern calls\n * `.build({scoped})` per tenant and registers nothing.\n */\n const closed = (method: string): never => {\n throw new Error(\n `act().${method}() was called after build(); the registry is already classified. Register everything before build() — build() itself may be called repeatedly (e.g. once per tenant with ActOptions.scoped).`\n );\n };\n\n // The `as` chain on `self` is the type fanout: each fluent method\n // mutates state and returns `self` cast to its post-call generic\n // signature. Internal-only — public types stay narrow.\n const builder: ActBuilder<TSchemaReg, TEvents, TActions, TStateMap, TActor> =\n {\n withState: (state) => {\n if (_built) closed(\"withState\");\n register_state(state, states, registry.actions, registry.events);\n return builder as never;\n },\n withSlice: (input) => {\n if (_built) closed(\"withSlice\");\n for (const s of input.states.values()) {\n register_state(s, states, registry.actions, registry.events);\n }\n merge_event_register(registry.events, input.events);\n pending_projections.push(...input.projections);\n for (const lane of input.lanes) register_lane(lane, lanes);\n return builder as never;\n },\n withProjection: (proj) => {\n if (_built) closed(\"withProjection\");\n add_projection(proj as Projection<any>);\n return builder;\n },\n withActor: <TNewActor extends Actor>() =>\n builder as unknown as ActBuilder<\n TSchemaReg,\n TEvents,\n TActions,\n TStateMap,\n TNewActor\n >,\n withLane: (config) => {\n if (_built) closed(\"withLane\");\n register_lane(config, lanes);\n return builder as never;\n },\n on: <TKey extends keyof TEvents>(event: TKey) => {\n if (_built) closed(\"on\");\n return reaction_on(event, registry.events, builder) as never;\n },\n build: (options?: ActOptions) => {\n // Validate the top-level scalar knobs at build (the nested autoclose /\n // circuitBreaker bags are validated by their own resolvers). A bad\n // maxSubscribedStreams / settleDebounceMs throws ZodError here.\n resolveActConfig(options);\n // Finalize once: repeated builds (per tenant) share the registry.\n if (!_built) {\n for (const proj of pending_projections) add_projection(proj);\n // State projections fold the registry-merged FULL state — the\n // builder only recorded intent. Resolve here, where every\n // partial has merged, and refuse silently-partial folds: the\n // projection's register must cover the state's whole register.\n for (const proj of fold_projections) {\n const fold = proj.fold!;\n const merged = states.get(fold.name);\n if (!merged)\n throw new Error(\n `State projection \"${proj.target}\" folds \"${fold.name}\", which is not registered — add it via withState/withSlice before build()`\n );\n const missing = Object.keys(merged.events).filter(\n (event_name) => !(event_name in proj.events)\n );\n if (missing.length > 0)\n throw new Error(\n `State projection \"${proj.target}\" of \"${fold.name}\" is missing events ${missing.join(\", \")} — pass every partial of the state to .of()`\n );\n // A target is claimed once, by a batch handler or a fold; two\n // different projections on one target throw. The same projection\n // registered twice is fine.\n const claimed = fold_specs.find((s) => s.target === proj.target);\n if (claimed?.projection === proj) continue;\n if (batch_handlers.has(proj.target!) || claimed)\n throw new Error(\n `Duplicate projection target \"${proj.target}\" — a target is served by one batch handler or one state projection, never both`\n );\n // Record the validated ingredients only. The handler is\n // constructed per `.build()` (see `make_batch_handlers`) — it\n // owns a mutable per-stream fold cache, so one shared instance\n // would leak folded rows between Acts built from this builder.\n fold_specs.push({\n target: proj.target!,\n projection: proj,\n merged,\n flush: fold.flush,\n config: fold.config,\n });\n }\n // An ordinary reaction on a projection's target would never run and\n // would feed the fold another aggregate, so `build_events` rejects\n // it (the projection's own reactions are exempt).\n //\n // One walk over the registered events: validate every static\n // reaction, resolve each schema once, and compose the per-surface\n // readers from it. See `event-builder.ts`.\n const built = build_events(registry, states, lanes, {\n batch_handlers,\n fold_targets: new Set(fold_specs.map((f) => f.target)),\n projection_reactions,\n });\n for (const [name, fields] of built.sensitive) _sf.set(name, fields);\n for (const [name, gate] of built.query_readers) _qg.set(name, gate);\n for (const [name, gate] of built.handler_readers) _hr.set(name, gate);\n finalize_deprecations();\n if (built.advisory) log().warn(built.advisory);\n\n // A load reads and writes through this Act's store, so it must name\n // a registered state; it resolves to the merged one, partials and all.\n // The resolved loads go on a copy this Act owns: the state object\n // the app passed in may be registered in other Acts, with other\n // partials of the loaded state.\n for (const [name, state] of states) {\n if (!state.loads) continue;\n const resolved: Record<string, Load[]> = {};\n for (const [action, loads] of Object.entries(state.loads)) {\n resolved[action] = loads!.map((l) => {\n const registered = states.get(l.state.name);\n if (!registered)\n throw new Error(\n `Action \"${action}\" loads \"${l.state.name}\", which is not registered — add it via withState/withSlice before build()`\n );\n // An event listed on a load is emitted as statically as\n // `.emit(\"X\")`, so a deprecated one throws the same way.\n const deprecated = l.events.find((e) =>\n _de.get(registered.name)?.has(e)\n );\n if (deprecated)\n throw new Error(\n `Action \"${action}\" lists deprecated event \"${deprecated}\" on its load of \"${registered.name}\". ` +\n `A newer version exists: \"${current_version_of(deprecated, Object.keys(registered.events))}\". ` +\n `List the current version instead.`\n );\n return { ...l, state: registered };\n });\n }\n for (const [action, loads] of Object.entries(resolved)) {\n const static_target = (\n state.on[action] as { _static_emit?: string }\n )._static_emit;\n if (\n static_target &&\n loads.some((l) => l.events.includes(static_target))\n )\n throw new Error(\n `Action \"${action}\" statically emits \"${static_target}\", which its load lists, so nothing goes to its own stream; emit one of its own events too`\n );\n }\n const own = { ...state, loads: resolved };\n states.set(name, own);\n for (const action of Object.keys(own.actions))\n (registry.actions as Record<string, unknown>)[action] = own;\n }\n\n for (const state of states.values()) {\n if (state.disclose) _dp.set(state.name, state.disclose);\n if (state.autoclose) _ac.set(state.name, state.autoclose);\n if (state.archive) _aa.set(state.name, state.archive);\n }\n for (const [target, original] of batch_handlers) {\n batch_handlers.set(target, read_wrap(original) as never);\n }\n // Synthesize the autoclose reactions last, once the registry is\n // fully merged — their dynamic resolvers must be present before\n // the orchestrator classifies the registry.\n //\n // Nothing per-Act is captured: repeat builds share these reactions,\n // and the off-hours window comes from the running Act's frame.\n synthesize_autoclose_reactions(\n registry,\n states,\n current_autoclose_window\n );\n // Freeze the registry shape; the `_built` latch on each method stops\n // later registration (freezing doesn't seal the reaction `Map`s).\n Object.freeze(registry.actions);\n Object.freeze(registry.events);\n Object.freeze(registry);\n _built = true;\n }\n\n return new Act<TSchemaReg, TEvents, TActions, TStateMap, TActor>(\n registry,\n states,\n make_batch_handlers(),\n options,\n lanes\n );\n },\n events: registry.events,\n };\n return builder;\n}\n","import {\n DEFAULT_BLOCK_ON_ERROR,\n DEFAULT_MAX_RETRIES,\n resolveFoldConfig,\n} from \"../internal/config.js\";\nimport type {\n EventEntry,\n Projection,\n ProjectionBuilder,\n} from \"../types/builders.js\";\nimport type {\n BatchHandler,\n CacheEntry,\n Committed,\n EventRegister,\n FoldOptions,\n Schema,\n Schemas,\n State,\n} from \"../types/index.js\";\nimport { add_reaction } from \"./builder-utils.js\";\nimport { _this_ } from \"./merge.js\";\n\n/**\n * @internal Build the core builder object (shared between overloads). One\n * mutable `events` register threaded through every fluent call; .on()\n * mutates and returns the same builder cast to its widened generic.\n */\nfunction _projection<\n TEvents extends Schemas,\n TTarget extends string | undefined,\n>(target: TTarget): ProjectionBuilder<TEvents, TTarget> {\n const events = {} as EventRegister<TEvents>;\n const default_resolver: { target: string } | undefined =\n typeof target === \"string\" ? { target } : undefined;\n\n // Mutable runtime bag — typed loosely; the public projection() return\n // type narrows back to the user-facing `ProjectionBuilder<TEvents, TTarget>`.\n\n const base: any = {\n on: <TKey extends string, TData extends Schema>(\n entry: EventEntry<TKey, TData>\n ) => {\n const keys = Object.keys(entry);\n if (keys.length !== 1) throw new Error(\".on() requires exactly one key\");\n const event = keys[0] as TKey;\n const schema = entry[event];\n\n // Register the event schema if not already present\n if (!(event in events)) {\n (events as Record<string, unknown>)[event] = {\n schema,\n reactions: new Map(),\n };\n }\n\n return {\n do: (\n handler: (\n event: Committed<TEvents & { [P in TKey]: TData }, TKey>,\n stream: string\n ) => Promise<void>\n ) => {\n // Same builder, widened generic — no recursive call.\n const widened = base as unknown as ProjectionBuilder<\n TEvents & { [P in TKey]: TData },\n TTarget\n >;\n return add_reaction(\n events as unknown as EventRegister<\n TEvents & { [P in TKey]: TData }\n >,\n event,\n handler.name,\n \"Projection\",\n () => ({\n handler,\n resolver: default_resolver ?? _this_,\n options: {\n blockOnError: DEFAULT_BLOCK_ON_ERROR,\n maxRetries: DEFAULT_MAX_RETRIES,\n },\n }),\n widened\n );\n },\n };\n },\n build: () => ({\n _tag: \"Projection\" as const,\n events,\n ...(target !== undefined && { target }),\n }),\n events,\n };\n\n // Add .batch() and .of() only for static-target projections\n if (typeof target === \"string\") {\n return Object.assign(base, {\n batch: (handler: BatchHandler<TEvents>) => ({\n build: () => ({\n _tag: \"Projection\" as const,\n events,\n target,\n batchHandler: handler,\n }),\n }),\n of: (...args: unknown[]) => {\n if (Object.keys(events).length > 0)\n throw new Error(\n `Projection \"${target}\" mixes .of() with .on() handlers — a projection either folds a state or declares handlers, never both`\n );\n // Trailing options bag is the only non-State argument.\n const is_state = (a: unknown): a is State<Schema, Schemas, Schemas> =>\n !!a &&\n typeof (a as State<Schema, Schemas, Schemas>).init === \"function\";\n const partials = args.filter(is_state);\n const options = (args.find((a) => !is_state(a)) ?? {}) as FoldOptions;\n if (partials.length === 0)\n throw new Error(`Projection \"${target}\" .of() requires a state`);\n const name = partials[0].name;\n for (const partial of partials)\n if (partial.name !== name)\n throw new Error(\n `Projection \"${target}\" .of() partials must share one state name — got \"${name}\" and \"${partial.name}\"`\n );\n // Misconfiguration surfaces here, at startup — not on first drain.\n const config = resolveFoldConfig(options);\n // The partials' own schema instances register the events, so the\n // same-name declarations in slices pass the identity check in\n // merge_event_register. The named no-op reaction routes fetches\n // to this target; dispatch always goes through the batch handler\n // the orchestrator synthesizes from the registry-merged state.\n const fold_events = {} as EventRegister<Schemas>;\n for (const partial of partials)\n for (const [event_name, schema] of Object.entries(partial.events)) {\n if (event_name in fold_events) continue;\n const noop = {\n [`${target}_fold`]: async () => {},\n }[`${target}_fold`] as (\n event: Committed<Schemas, string>,\n stream: string\n ) => Promise<void>;\n (fold_events as Record<string, unknown>)[event_name] = {\n schema,\n reactions: new Map([\n [\n `${target}_fold`,\n {\n handler: noop,\n resolver: { target },\n options: {\n blockOnError: DEFAULT_BLOCK_ON_ERROR,\n maxRetries: DEFAULT_MAX_RETRIES,\n },\n },\n ],\n ]),\n };\n }\n return {\n flush: (\n handler: (rows: ReadonlyArray<CacheEntry<Schema>>) => Promise<void>\n ) => ({\n build: () => ({\n _tag: \"Projection\" as const,\n events: fold_events,\n target,\n fold: { name, flush: handler, config },\n }),\n }),\n };\n },\n }) as ProjectionBuilder<TEvents, TTarget>;\n }\n\n return base as ProjectionBuilder<TEvents, TTarget>;\n}\n\n/**\n * Creates a new projection builder for composing read-model update handlers,\n * with a static target stream.\n *\n * Projections enable separation of read-model concerns from command handling.\n * Each `.on({ Event }).do(handler)` call registers a handler that updates\n * a projection (database table, cache, etc.) in response to events. All\n * handlers inherit the target resolver automatically, and `.batch()` is\n * enabled for bulk event processing in a single transaction. Omit the target\n * and use per-handler `.to()` when handlers route to different streams.\n *\n * @param target - Static target stream for all handlers\n *\n * @example Default target (all handlers routed to \"tickets\")\n * ```typescript\n * const TicketProjection = projection(\"tickets\")\n * .on({ TicketOpened })\n * .do(async function openTicket({ stream, data }) {\n * await db.insert(tickets).values({ id: stream, ...data });\n * })\n * .on({ TicketClosed })\n * .do(async function closeTicket({ stream, data }) {\n * await db.update(tickets).set(data).where(eq(tickets.id, stream));\n * })\n * .build();\n * ```\n *\n * @see {@link ProjectionBuilder} for builder methods\n * @see {@link Projection} for the output type\n */\nexport function projection<TEvents extends Schemas = {}>(\n target: string\n): ProjectionBuilder<TEvents, string>;\n/**\n * Creates a new projection builder without a default target.\n *\n * Use per-handler `.to()` to route events to different streams.\n */\nexport function projection<TEvents extends Schemas = {}>(\n target?: undefined\n): ProjectionBuilder<TEvents, undefined>;\nexport function projection<TEvents extends Schemas = {}>(\n target?: string\n): ProjectionBuilder<TEvents, string | undefined> {\n return _projection<TEvents, string | undefined>(target);\n}\n","/**\n * @module slice-builder\n * @category Builders\n *\n * Fluent builder for composing partial states with scoped reactions into\n * self-contained functional slices (vertical slice architecture).\n */\n\nimport type { Projection, Slice, SliceBuilder } from \"../types/builders.js\";\nimport type {\n Actor,\n EventRegister,\n LaneConfig,\n Schema,\n SchemaRegister,\n Schemas,\n State,\n} from \"../types/index.js\";\nimport { reaction_on, register_lane } from \"./builder-utils.js\";\nimport { register_state } from \"./merge.js\";\n\n/**\n * Creates a new slice builder for composing partial states with scoped reactions.\n *\n * Slices enable vertical slice architecture by grouping related states and\n * reactions into self-contained feature modules. Reactions defined in a slice\n * are type-scoped to events from that slice's states only.\n *\n * @example Single-state slice with typed dispatch\n * ```typescript\n * const CounterSlice = slice()\n * .withState(Counter)\n * .on(\"Incremented\")\n * .do(async function resetCounter(event, _stream, app) {\n * await app.do(\"reset\", target, {});\n * })\n * .to(\"counter-target\")\n * .build();\n * ```\n *\n * @see {@link SliceBuilder} for builder methods\n * @see {@link Slice} for the output type\n */\nexport function slice(): SliceBuilder<{}, {}, {}, {}, Actor>;\nexport function slice<\n TSchemaReg extends SchemaRegister<TActions>,\n TEvents extends Schemas = {},\n TActions extends Schemas = {},\n TStateMap extends Record<string, Schema> = {},\n TActor extends Actor = Actor,\n>(): SliceBuilder<TSchemaReg, TEvents, TActions, TStateMap, TActor>;\nexport function slice<\n TSchemaReg extends SchemaRegister<TActions>,\n TEvents extends Schemas = {},\n TActions extends Schemas = {},\n TStateMap extends Record<string, Schema> = {},\n TActor extends Actor = Actor,\n>(): SliceBuilder<TSchemaReg, TEvents, TActions, TStateMap, TActor> {\n // One mutable state shared across the entire fluent chain. Each\n // `withState` / `withProjection` / `on` call mutates these and returns\n // the same builder cast to the widened generic; type fanout is preserved\n // through the public type signatures, runtime allocation is not.\n const states = new Map<string, State<any, any, any>>();\n const actions: Record<string, any> = {};\n const events = {} as EventRegister<TEvents>;\n const projections: Projection<any>[] = [];\n const lanes: LaneConfig[] = [];\n\n const builder: SliceBuilder<\n TSchemaReg,\n TEvents,\n TActions,\n TStateMap,\n TActor\n > = {\n withState: (state) => {\n register_state(state, states, actions, events as Record<string, unknown>);\n return builder as never;\n },\n withProjection: (proj) => {\n projections.push(proj as Projection<any>);\n return builder;\n },\n withLane: (config) => {\n register_lane(config, lanes);\n return builder as never;\n },\n on: <TKey extends keyof TEvents>(event: TKey) =>\n reaction_on(event, events, builder) as never,\n build: () => ({\n _tag: \"Slice\" as const,\n states,\n events,\n projections,\n lanes,\n }),\n events,\n };\n return builder;\n}\n","/**\n * @module state-builder\n * @category Builders\n *\n * Fluent interface for defining a strongly-typed state machine using Zod schemas.\n */\nimport type { ZodType } from \"zod\";\nimport {\n compile_autoclose_policy,\n policy_after_windows,\n policy_keep_days,\n} from \"../internal/autoclose-policy.js\";\nimport { resolveActionConfig } from \"../internal/config.js\";\nimport type {\n ActionBuilder,\n ActionEntry,\n StateBuilder,\n StateEntry,\n} from \"../types/builders.js\";\nimport type {\n ActionHandler,\n ActionOptions,\n Actor,\n AutocloseArchiver,\n AutoclosePolicy,\n AutoclosePredicate,\n Committed,\n Load,\n PassthroughPatchHandler,\n PatchHandlers,\n Precondition,\n Schema,\n Schemas,\n Snapshot,\n State,\n ZodTypes,\n} from \"../types/index.js\";\n\n/**\n * Creates a new state definition with event sourcing capabilities.\n *\n * States are the core building blocks of Act. Each state represents a consistency\n * boundary (aggregate) that processes actions, emits events, and maintains its own\n * state through event patches (reducers). States use event sourcing to maintain a\n * complete audit trail and enable time-travel capabilities.\n *\n * The state builder provides a fluent API for defining:\n * 1. Initial state via `.init()`\n * 2. Event types via `.emits()` — all events default to passthrough (`({ data }) => data`)\n * 3. Custom event reducers via `.patch()` (optional — only for events that need custom logic)\n * 4. Actions (commands) via `.on()` → `.emit()` — pass an event name string for passthrough\n * 5. Business rules: preconditions via `.requires()`\n * 6. Snapshotting strategy via `.snap()`\n *\n * @template TState - Zod schema type defining the shape of the state\n * @param entry - Single-key record mapping state name to Zod schema (e.g., `{ Counter: z.object({ count: z.number() }) }`)\n * @returns A StateBuilder instance for fluent API configuration\n *\n * @example Basic counter state (with custom patch)\n * ```typescript\n * import { state } from \"@rotorsoft/act\";\n * import { z } from \"zod\";\n *\n * const Counter = state({ Counter: z.object({ count: z.number() }) })\n * .init(() => ({ count: 0 }))\n * .emits({\n * Incremented: z.object({ amount: z.number() })\n * })\n * .patch({ // optional — only for events needing custom reducers\n * Incremented: ({ data }, state) => ({ count: state.count + data.amount })\n * })\n * .on({ increment: z.object({ by: z.number() }) })\n * .emit((action) => [\"Incremented\", { amount: action.by }])\n * .build();\n * ```\n *\n * @see {@link StateBuilder} for available builder methods\n * @see {@link ActionBuilder} for action configuration methods\n * @see {@link https://rotorsoft.github.io/act-root/docs/intro | Getting Started Guide}\n * @see {@link https://rotorsoft.github.io/act-root/docs/examples/calculator | Calculator Example}\n */\nexport function state<TName extends string, TState extends Schema>(\n entry: StateEntry<TName, TState>\n): StateBuilder<TState, TName> {\n const keys = Object.keys(entry);\n if (keys.length !== 1) throw new Error(\"state() requires exactly one key\");\n const name = keys[0] as TName;\n const state_schema = (entry as Record<string, ZodType<TState>>)[name];\n return {\n init(init) {\n return {\n emits<TEvents extends Schema>(events: ZodTypes<TEvents>) {\n // Default passthrough patches: event data merges into state\n const default_patch = Object.fromEntries(\n Object.keys(events).map((k) => {\n const fn = Object.assign(({ data }: { data: any }) => data, {\n _passthrough: true as const,\n }) satisfies PassthroughPatchHandler;\n return [k, fn];\n })\n ) as unknown as PatchHandlers<TState, TEvents>;\n\n // Build one mutable state object the action_builder threads\n // through every fluent call. patch() (if invoked) just mutates\n // the patch map in place — no re-builder wasted.\n const internal: State<TState, TEvents, Schemas, TName> = {\n events,\n actions: {},\n state: state_schema,\n name,\n init,\n patch: default_patch,\n on: {},\n // Step delegates initialized as identity, `pii_aware` false.\n // `act().build()` flips both on states with `sensitive(...)`\n // events to bake in the gate / split and gate the cache write.\n pii_aware: false,\n view: (event) => event,\n message: (validated) => validated,\n };\n\n // `{}` avoids the string index signature `Record<string, never>` would add\n const builder = action_builder<TState, TEvents, {}, TName>(internal);\n\n return Object.assign(builder, {\n patch(customPatch: Partial<PatchHandlers<TState, TEvents>>) {\n Object.assign(internal.patch, customPatch);\n return builder;\n },\n });\n },\n };\n },\n };\n}\n\n/**\n * Internal action-builder. The runtime object is a single mutable bag —\n * each fluent call (`on`, `snap`) mutates it and returns the same builder\n * cast to the widened generic type. Type-level fanout is preserved; the\n * O(N) `{...state}` spreads per call are not.\n *\n * Generics are erased to `Schemas` at runtime — the cast on return narrows\n * back to the call-site's widened types.\n */\nfunction action_builder<\n TState extends Schema,\n TEvents extends Schemas,\n TActions extends Schemas,\n TName extends string = string,\n>(\n state: State<TState, TEvents, TActions, TName>\n): ActionBuilder<TState, TEvents, TActions, TName> {\n // The mutable bag — typed loosely since callers narrow on return.\n const internal = state as unknown as State<TState, TEvents, Schemas, TName>;\n\n const builder: ActionBuilder<TState, TEvents, TActions, TName> = {\n on<TKey extends string, TNewActions extends Schema>(\n entry: ActionEntry<TKey, TNewActions>,\n options?: ActionOptions\n ) {\n const keys = Object.keys(entry);\n if (keys.length !== 1) throw new Error(\".on() requires exactly one key\");\n const action = keys[0] as TKey;\n const schema = entry[action];\n\n if (action in internal.actions)\n throw new Error(`Duplicate action \"${action}\"`);\n\n type MergedActions = TActions & { [P in TKey]: TNewActions };\n (internal.actions as Record<string, ZodType<Schema>>)[action] = schema;\n if (options) {\n // Validate the whole action bag at declaration so a bad\n // `maxRetries`/`backoff` throws ZodError at build, not a NaN gate.\n resolveActionConfig(options);\n internal.options ??= {};\n (internal.options as Record<string, ActionOptions>)[action] = options;\n }\n\n const loads: Load[] = [];\n\n function load(\n state: State<any, any, any>,\n target: Load[\"target\"],\n events: readonly string[] = [],\n name: string = state.name\n ) {\n if (loads.some((l) => l.name === name))\n throw new Error(\n `Action \"${action}\" loads \"${name}\" twice; name each load of the same state`\n );\n for (const event of events) {\n if (!(event in state.events))\n throw new Error(\n `Action \"${action}\" lists \"${event}\" on its load of \"${state.name}\", which doesn't emit it`\n );\n if (loads.some((l) => l.events.includes(event)))\n throw new Error(\n `Action \"${action}\" lists \"${event}\" on two loads; an event goes to one stream`\n );\n }\n loads.push({ state, target, events, name });\n (internal.loads ??= {})[action] = loads;\n return { loads: load, requires, emit };\n }\n\n function requires(rules: Precondition<TState, TNewActions>[]) {\n ((internal.requires ??= {}) as Record<string, unknown>)[action] = rules;\n return { emit };\n }\n\n function emit(\n handler:\n | ActionHandler<TState, TEvents, MergedActions, TKey>\n | (keyof TEvents & string)\n ) {\n if (typeof handler === \"string\") {\n const event_name = handler;\n // Tag the synthetic function with the static event name so\n // the act-builder can check it at build time (a deprecated\n // event, an event a load lists). Dynamic forms compute the\n // event name inside the user's function, so the build can't\n // see it.\n const emit_fn = Object.assign(\n (payload: any) => [event_name, payload],\n {\n _static_emit: event_name,\n }\n );\n (internal.on as Record<string, unknown>)[action] = emit_fn;\n } else {\n (internal.on as Record<string, unknown>)[action] = handler;\n }\n return builder as unknown as ActionBuilder<\n TState,\n TEvents,\n MergedActions,\n TName\n >;\n }\n\n // Typed by the public signature; the runtime bag is the same at every step.\n return { loads: load, requires, emit } as never;\n },\n\n snap(snap: (snapshot: Snapshot<TState, TEvents>) => boolean) {\n internal.snap = snap;\n // Flip the type-level TSnap flag — same runtime object, the cast\n // unlocks `.autocloses({ keep })` for the rest of the chain.\n return builder as unknown as ActionBuilder<\n TState,\n TEvents,\n TActions,\n TName,\n true\n >;\n },\n\n discloses(\n disclose: (\n event: Committed<TEvents, keyof TEvents & string>,\n actor: Actor\n ) => boolean\n ) {\n // Replace on every call — matches snap's state-level semantics. Operators\n // who need per-event differences branch inside the predicate.\n internal.disclose = disclose;\n return builder;\n },\n\n autocloses(policy: AutoclosePolicy) {\n // Declarative policy only. The online path is a synthesized\n // reaction that defers to a derivable due-time and closes — an opaque\n // function predicate has no terminal event to react to nor a window to\n // derive, so it's no longer accepted online. Operators who need custom\n // logic call `app.close(...)` from their own reaction.\n if (typeof policy === \"function\") {\n throw new Error(\n \".autocloses(fn) is no longer supported — pass a declarative policy \" +\n \"({ after, is, reaches, or }) or call app.close(...) from your own \" +\n \"reaction for custom logic.\"\n );\n }\n if (policy === null || typeof policy !== \"object\") {\n throw new Error(\n \".autocloses(...) requires a policy object; got \" + typeof policy\n );\n }\n // The type gate (`TSnap`) already rejects `keep` before `.snap` at\n // compile time; this is the equivalent guard for untyped callers.\n if ((policy as AutoclosePolicy).keep && !internal.snap) {\n throw new Error(\n \".autocloses({ keep }) requires .snap(...) earlier in the chain — a rolling window prunes behind a real snapshot, so a state that never snapshots has nothing to prune behind.\"\n );\n }\n // Replace on every call — matches snap / discloses state-level\n // semantics. Compile to the predicate the reaction evaluates; `keep`\n // resolves to the rolling-window width the reaction prunes against.\n internal.autoclose = compile_autoclose_policy(\n policy\n ) as AutoclosePredicate<TEvents>;\n const windows = policy_after_windows(policy);\n internal.autoclose_after_windows = windows;\n internal.autoclose_after_days = windows.length\n ? Math.min(...windows)\n : undefined;\n internal.autoclose_keep_days = policy_keep_days(policy);\n return builder;\n },\n\n archives(archive: AutocloseArchiver<TEvents>) {\n if (typeof archive !== \"function\") {\n throw new Error(\n \".archives(archive) requires a function; got \" + typeof archive\n );\n }\n internal.archive = archive;\n return builder;\n },\n\n build(): State<TState, TEvents, TActions, TName> {\n return internal as unknown as State<TState, TEvents, TActions, TName>;\n },\n };\n return builder;\n}\n","/**\n * @module csv\n *\n * `CsvFile` — a single class implementing both {@link EventSource}\n * and {@link EventSink} so a CSV file on disk can be either side of\n * a transfer pipeline.\n *\n * - As a source: streams one row at a time off a line interface;\n * the awaited per-event callback gives 1-event-in-flight\n * backpressure on reads.\n * - As a sink: serialized `WriteStream.write` await per row,\n * propagating I/O errors through the chunk callback.\n *\n * `commit` / `claim` / `subscribe` and the rest of `Store` are NOT\n * implemented — `CsvFile` is a transfer-only primitive, not a\n * store you'd run an Act app against.\n */\n\nimport { createReadStream, createWriteStream, type WriteStream } from \"node:fs\";\nimport { createInterface } from \"node:readline\";\nimport type { Committed, Query, Schemas } from \"./types/action.js\";\nimport type {\n CsvFileOptions,\n EventSink,\n EventSource,\n} from \"./types/restore.js\";\n\n/**\n * Same column order as the inspector's backup endpoint, kept here\n * so `CsvFile` is round-trip-compatible with existing backups.\n */\nconst CSV_COLUMNS = [\n \"id\",\n \"name\",\n \"data\",\n \"stream\",\n \"version\",\n \"created\",\n \"meta\",\n] as const;\n\nexport class CsvFile implements EventSource, EventSink {\n private readonly path: string | null;\n private readonly blob: string | null;\n\n constructor(options: CsvFileOptions) {\n if (\"path\" in options) {\n this.path = options.path;\n this.blob = null;\n } else {\n this.path = null;\n this.blob = options.blob;\n }\n }\n\n async query<E extends Schemas>(\n callback: (event: Committed<E, keyof E>) => void,\n _filter?: Query\n ): Promise<number> {\n const lines =\n this.blob !== null ? linesFromBlob(this.blob) : linesFromFile(this.path!);\n let count = 0;\n let header: readonly string[] | null = null;\n for await (const line of lines) {\n if (!line.trim()) continue;\n const fields = parse_csv_line(line);\n if (!header) {\n header = fields;\n const expected = CSV_COLUMNS.join(\",\");\n if (header.join(\",\") !== expected)\n throw new Error(`Invalid CSV header. Expected: ${expected}`);\n continue;\n }\n if (fields.length !== CSV_COLUMNS.length)\n throw new Error(\n `Row ${count + 1}: expected ${CSV_COLUMNS.length} fields, got ${fields.length}`\n );\n const event: Committed<E, keyof E> = {\n id: Number.parseInt(fields[0]!, 10),\n name: fields[1]! as keyof E,\n // Revive dates like every Store adapter does — a Date in an event\n // payload must not depend on whether it came back through a store or\n // through a CSV restore. The `created` column below has\n // always been parsed explicitly; the JSON columns were missed.\n data: JSON.parse(fields[2]!),\n stream: fields[3]!,\n version: Number.parseInt(fields[4]!, 10),\n created: new Date(fields[5]!),\n meta: JSON.parse(fields[6]!),\n };\n await Promise.resolve(callback(event));\n count++;\n }\n if (header === null)\n throw new Error(\"CSV must have a header and at least one row\");\n return count;\n }\n\n async restore(\n driver: (\n callback: (event: Committed<Schemas, keyof Schemas>) => Promise<number>\n ) => Promise<void>\n ): Promise<void> {\n if (this.path === null)\n throw new Error(\n \"CsvFile in blob mode is read-only — provide `path` to write\"\n );\n const writer = createWriteStream(this.path, {\n flags: \"w\",\n encoding: \"utf8\",\n });\n let next_id = 1;\n try {\n await write_line(writer, CSV_COLUMNS.join(\",\"));\n await driver(async (event) => {\n const id = next_id++;\n const row = [\n String(id),\n csv_escape(event.name as string),\n csv_escape(JSON.stringify(event.data)),\n csv_escape(event.stream),\n String(event.version),\n event.created.toISOString(),\n csv_escape(JSON.stringify(event.meta)),\n ].join(\",\");\n await write_line(writer, row);\n return id;\n });\n } finally {\n await new Promise<void>((resolve) => writer.end(resolve));\n }\n }\n\n async dispose(): Promise<void> {\n // No-op: `restore` always closes its writer in a `finally`, and\n // blob mode never opens one. The Disposable contract is here to\n // make `CsvFile` interchangeable with `Store` in transfer\n // pipelines, not because the file handle outlives the call.\n }\n}\n\nasync function* linesFromFile(path: string): AsyncIterable<string> {\n const stream = createReadStream(path, { encoding: \"utf8\" });\n const rl = createInterface({\n input: stream,\n crlfDelay: Number.POSITIVE_INFINITY,\n });\n try {\n for await (const line of rl) yield line;\n } finally {\n rl.close();\n stream.close();\n }\n}\n\nasync function* linesFromBlob(blob: string): AsyncIterable<string> {\n let start = 0;\n while (start < blob.length) {\n const nl = blob.indexOf(\"\\n\", start);\n const end = nl === -1 ? blob.length : nl;\n yield blob.slice(start, end);\n start = nl === -1 ? blob.length : nl + 1;\n await Promise.resolve();\n }\n}\n\nfunction parse_csv_line(line: string): string[] {\n const fields: string[] = [];\n let i = 0;\n while (i < line.length) {\n if (line[i] === '\"') {\n let value = \"\";\n i++;\n while (i < line.length) {\n if (line[i] === '\"' && line[i + 1] === '\"') {\n value += '\"';\n i += 2;\n } else if (line[i] === '\"') {\n i++;\n break;\n } else {\n value += line[i++];\n }\n }\n fields.push(value);\n if (line[i] === \",\") i++;\n } else {\n const next = line.indexOf(\",\", i);\n if (next === -1) {\n fields.push(line.slice(i));\n i = line.length;\n } else {\n fields.push(line.slice(i, next));\n i = next + 1;\n }\n }\n }\n return fields;\n}\n\nfunction csv_escape(value: string): string {\n if (/[\",\\n\\r]/.test(value)) return `\"${value.replace(/\"/g, '\"\"')}\"`;\n return value;\n}\n\nfunction write_line(writer: WriteStream, line: string): Promise<void> {\n return new Promise<void>((resolve, reject) => {\n writer.write(`${line}\\n`, (err) => {\n if (err) reject(err);\n else resolve();\n });\n });\n}\n","// 2.x names kept as aliases of their replacements. 3.0 removes this file,\n// its block in index.ts, and `pii_fields` in sensitive.ts.\nimport type { ZodType } from \"zod\";\nimport {\n checkAppends,\n checkVersion,\n concurrencyError,\n fairSlots,\n isStreamName,\n parseNotification,\n seedEvent,\n} from \"./adapter.js\";\nimport { package_schema } from \"./config.js\";\nimport { resolveAutocloseConfig as resolve_autoclose } from \"./internal/config.js\";\nimport { unscoped_ports } from \"./ports.js\";\nimport {\n ActorSchema as actor_schema,\n CausationEventSchema as causation_event_schema,\n CommittedMetaSchema as committed_meta_schema,\n DEFAULT_LANE as default_lane,\n DEFAULT_MAX_SUBSCRIBED_STREAMS as default_max_subscribed_streams,\n DEFAULT_QUERY_STREAMS_LIMIT as default_query_streams_limit,\n DEFAULT_SETTLE_DEBOUNCE_MS as default_settle_debounce_ms,\n Environments as environments,\n EventMetaSchema as event_meta_schema,\n ExitCodes as exit_codes,\n LogLevels as log_levels,\n QuerySchema as query_schema,\n TargetSchema as target_schema,\n} from \"./types/index.js\";\nimport { validate } from \"./utils.js\";\n\n/** @deprecated Use `checkAppends` from `@rotorsoft/act/adapter`. */\nexport const check_appends: typeof checkAppends = checkAppends;\n/** @deprecated Use `checkVersion` from `@rotorsoft/act/adapter`. */\nexport const throw_if_stale: typeof checkVersion = checkVersion;\n/** @deprecated Use `concurrencyError` from `@rotorsoft/act/adapter`. */\nexport const concurrency_error: typeof concurrencyError = concurrencyError;\n/** @deprecated Use `seedEvent` from `@rotorsoft/act/adapter`. */\nexport const seed_event: typeof seedEvent = seedEvent;\n/** @deprecated Use `fairSlots` from `@rotorsoft/act/adapter`. */\nexport const fair_slots: typeof fairSlots = fairSlots;\n/** @deprecated Use `isStreamName` from `@rotorsoft/act/adapter`. */\nexport const is_literal_source: typeof isStreamName = isStreamName;\n/** @deprecated Use `parseNotification` from `@rotorsoft/act/adapter`. */\nexport const notification_of: typeof parseNotification = parseNotification;\n\n/** @deprecated Import it from `@rotorsoft/act/types`. */\nexport const DEFAULT_QUERY_STREAMS_LIMIT: typeof default_query_streams_limit =\n default_query_streams_limit;\n/** @deprecated Import it from `@rotorsoft/act/types`. */\nexport const ActorSchema: typeof actor_schema = actor_schema;\n/** @deprecated Import it from `@rotorsoft/act/types`. */\nexport const TargetSchema: typeof target_schema = target_schema;\n/** @deprecated Import it from `@rotorsoft/act/types`. */\nexport const EventMetaSchema: typeof event_meta_schema = event_meta_schema;\n/** @deprecated Import it from `@rotorsoft/act/types`. */\nexport const CausationEventSchema: typeof causation_event_schema =\n causation_event_schema;\n/** @deprecated Import it from `@rotorsoft/act/types`. */\nexport const CommittedMetaSchema: typeof committed_meta_schema =\n committed_meta_schema;\n/** @deprecated Import it from `@rotorsoft/act/types`. */\nexport const QuerySchema: typeof query_schema = query_schema;\n/** @deprecated Import it from `@rotorsoft/act/types`. */\nexport const Environments: typeof environments = environments;\n/** @deprecated Import it from `@rotorsoft/act/types`. */\nexport const LogLevels: typeof log_levels = log_levels;\n/** @deprecated Import it from `@rotorsoft/act/types`. */\nexport const ExitCodes: typeof exit_codes = exit_codes;\n/** @deprecated Import it from `@rotorsoft/act/types`. */\nexport const DEFAULT_LANE: typeof default_lane = default_lane;\n/** @deprecated Import it from `@rotorsoft/act/types`. */\nexport const DEFAULT_MAX_SUBSCRIBED_STREAMS: typeof default_max_subscribed_streams =\n default_max_subscribed_streams;\n/** @deprecated Import it from `@rotorsoft/act/types`. */\nexport const DEFAULT_SETTLE_DEBOUNCE_MS: typeof default_settle_debounce_ms =\n default_settle_debounce_ms;\n\n/** @deprecated No replacement: `config()` validates package.json itself. */\nexport const PackageSchema: typeof package_schema = package_schema;\n/** @deprecated No replacement: call `store()`, `cache()` or `log()`. */\nexport const default_scope: typeof unscoped_ports = unscoped_ports;\n/** @deprecated No replacement: `act().build()` validates these options. */\nexport const resolveAutocloseConfig: typeof resolve_autoclose =\n resolve_autoclose;\n/** @deprecated No replacement: parse with the schema, spread the defaults. */\nexport const extend = <\n S extends Record<string, unknown>,\n T extends Record<string, unknown>,\n>(\n source: Readonly<S>,\n schema: ZodType<S>,\n target?: Readonly<T>\n): Readonly<S & T> =>\n ({ ...target, ...validate(\"config\", source, schema) }) as Readonly<S & T>;\n\n// An ISO-8601 timestamp, the shape `JSON.stringify` gives a `Date`.\nconst ISO_8601 =\n /^(\\d{4})-(0[1-9]|1[0-2])-(0[1-9]|[1-2][0-9]|3[0-1])T([01][0-9]|2[0-3]):([0-5][0-9]):([0-5][0-9])(\\.\\d+)?(Z|[+-][0-2][0-9]:[0-5][0-9])?$/;\n\n/** @deprecated No replacement: events revive their own `z.date()` fields. */\nexport const dateReviver = (_key: string, value: unknown): unknown =>\n typeof value === \"string\" && ISO_8601.test(value) ? new Date(value) : value;\n"]}
|