{"version":3,"sources":["../src/index.ts","../src/adapters/console-logger.ts","../src/internal/lru-map.ts","../src/adapters/in-memory-cache.ts","../src/types/errors.ts","../src/utils.ts","../src/config.ts","../src/types/schemas.ts","../src/internal/sensitive.ts","../src/types/index.ts","../src/adapters/in-memory-store.ts","../src/disposers.ts","../src/scoped.ts","../src/ports.ts","../src/signals.ts","../src/act.ts","../src/builders/build-classify.ts","../src/internal/event-versions.ts","../src/internal/walk-streams.ts","../src/internal/audit.ts","../src/internal/autoclose-policy.ts","../src/internal/autoclose-window.ts","../src/internal/close-signal.ts","../src/internal/defer-signal.ts","../src/internal/autoclose-reaction.ts","../src/internal/backoff.ts","../src/internal/circuit-breaker.ts","../src/internal/close-cycle.ts","../src/internal/config.ts","../src/internal/correlate-cycle.ts","../src/internal/report-once.ts","../src/internal/correlator.ts","../src/internal/date-reviver.ts","../src/internal/defer-config.ts","../src/internal/drain-cycle.ts","../src/internal/defer-timer.ts","../src/internal/drain-ratio.ts","../src/internal/drain.ts","../src/internal/event-sourcing.ts","../src/internal/tracing.ts","../src/internal/projection-fold.ts","../src/internal/settle.ts","../src/builders/reaction-builder.ts","../src/builders/merge.ts","../src/builders/builder-utils.ts","../src/builders/event-builder.ts","../src/builders/act-builder.ts","../src/builders/projection-builder.ts","../src/builders/slice-builder.ts","../src/builders/state-builder.ts","../src/csv.ts"],"sourcesContent":["import \"./signals.js\";\n\n/**\n * @packageDocumentation\n * @module act\n * Main entry point for the Act framework. Re-exports all core APIs.\n */\nexport * from \"./act.js\";\nexport * from \"./adapters/index.js\";\nexport * from \"./builders/index.js\";\nexport * from \"./config.js\";\nexport * from \"./csv.js\";\n// The imperative defer escape hatch (#1091): a reaction throws this with a\n// `DeferWhen` (see ./types/action.ts) to hold itself until the resolved\n// due-time. The declarative `.defer(when)` builder step is the common path.\nexport { DeferSignal } from \"./internal/index.js\";\nexport * from \"./ports.js\";\nexport * from \"./types/index.js\";\nexport * from \"./utils.js\";\n","/**\n * @module adapters/console-logger\n *\n * High-performance console logger inspired by pino's design:\n * - Numeric level comparison for O(1) gating\n * - stdout.write() in production for raw JSON lines (no console overhead)\n * - Colorized single-line output in development\n * - No-op method replacement when level is above threshold\n * - Child logger support with merged bindings\n */\nimport type { Logger } from \"../types/index.js\";\n\nconst LEVEL_VALUES: Record<string, number> = {\n  fatal: 60,\n  error: 50,\n  warn: 40,\n  info: 30,\n  debug: 20,\n  trace: 10,\n};\n\nconst LEVEL_COLORS: Record<string, string> = {\n  fatal: \"\\x1b[41m\\x1b[37m\", // white on red bg\n  error: \"\\x1b[31m\", // red\n  warn: \"\\x1b[33m\", // yellow\n  info: \"\\x1b[32m\", // green\n  debug: \"\\x1b[36m\", // cyan\n  trace: \"\\x1b[90m\", // gray\n};\n\nconst RESET = \"\\x1b[0m\";\n\nconst noop = () => {};\n\n/**\n * Default console logger for the Act framework.\n *\n * Production mode emits newline-delimited JSON (compatible with GCP, AWS\n * CloudWatch, Datadog, and other structured log ingestion systems).\n *\n * Development mode emits colorized, human-readable output.\n */\nexport class ConsoleLogger implements Logger {\n  level: string;\n  private readonly _pretty: boolean;\n\n  readonly fatal: Logger[\"fatal\"];\n  readonly error: Logger[\"error\"];\n  readonly warn: Logger[\"warn\"];\n  readonly info: Logger[\"info\"];\n  readonly debug: Logger[\"debug\"];\n  readonly trace: Logger[\"trace\"];\n\n  constructor(\n    options: {\n      level?: string;\n      pretty?: boolean;\n      bindings?: Record<string, unknown>;\n    } = {}\n  ) {\n    const {\n      level = \"info\",\n      pretty = process.env.NODE_ENV !== \"production\",\n      bindings,\n    } = options;\n    this._pretty = pretty;\n    this.level = level;\n\n    const threshold = LEVEL_VALUES[level] ?? 30;\n    const write = pretty\n      ? this._pretty_write.bind(this, bindings)\n      : this._json_write.bind(this, bindings);\n\n    // Assign methods — noop when level is gated (like pino's level-based replacement)\n    this.fatal = write.bind(this, \"fatal\", 60); // fatal is always enabled\n    this.error = threshold <= 50 ? write.bind(this, \"error\", 50) : noop;\n    this.warn = threshold <= 40 ? write.bind(this, \"warn\", 40) : noop;\n    this.info = threshold <= 30 ? write.bind(this, \"info\", 30) : noop;\n    this.debug = threshold <= 20 ? write.bind(this, \"debug\", 20) : noop;\n    this.trace = threshold <= 10 ? write.bind(this, \"trace\", 10) : noop;\n  }\n\n  /** No-op — `console.log` has no resources to release. */\n  async dispose(): Promise<void> {}\n\n  /** @inheritDoc */\n  child(bindings: Record<string, unknown>): Logger {\n    return new ConsoleLogger({\n      level: this.level,\n      pretty: this._pretty,\n      bindings,\n    });\n  }\n\n  private _json_write(\n    bindings: Record<string, unknown> | undefined,\n    level: string,\n    _num: number,\n    obj_or_msg: unknown,\n    msg?: string\n  ): void {\n    let obj: Record<string, unknown>;\n    let message: string | undefined;\n\n    if (typeof obj_or_msg === \"string\") {\n      message = obj_or_msg;\n      obj = {};\n    } else if (obj_or_msg instanceof Error) {\n      // Error instances spread to `{}` — capture the salient fields\n      // explicitly so structured log aggregators see them.\n      message = msg ?? obj_or_msg.message;\n      obj = {\n        error: { message: obj_or_msg.message, name: obj_or_msg.name },\n        stack: obj_or_msg.stack,\n      };\n    } else if (obj_or_msg !== null && typeof obj_or_msg === \"object\") {\n      message = msg;\n      obj = { ...(obj_or_msg as Record<string, unknown>) };\n    } else {\n      message = msg;\n      obj = { value: obj_or_msg };\n    }\n\n    const entry = Object.assign({ level, time: Date.now() }, bindings, obj);\n    if (message) entry.msg = message;\n\n    let line: string;\n    try {\n      line = JSON.stringify(entry);\n    } catch {\n      // Cyclic or unserializable payload — emit a minimal line rather\n      // than crash the log call site.\n      line = JSON.stringify({\n        level,\n        time: entry.time,\n        msg: message ?? \"[unserializable]\",\n        unserializable: true,\n      });\n    }\n    process.stdout.write(line + \"\\n\");\n  }\n\n  private _pretty_write(\n    bindings: Record<string, unknown> | undefined,\n    level: string,\n    _num: number,\n    obj_or_msg: unknown,\n    msg?: string\n  ): void {\n    const color = LEVEL_COLORS[level];\n    const tag = `${color}${level.toUpperCase().padEnd(5)}${RESET}`;\n    const ts = new Date().toISOString().slice(11, 23); // HH:mm:ss.SSS\n\n    let message: string;\n    let data: string | undefined;\n\n    if (typeof obj_or_msg === \"string\") {\n      message = obj_or_msg;\n    } else if (obj_or_msg instanceof Error) {\n      // Error instances don't serialize their `message`/`stack` via\n      // JSON.stringify — `JSON.stringify(err) === \"{}\"`. Render the\n      // message inline and the stack as the data payload so operators\n      // see something useful instead of an empty object.\n      message = msg ?? obj_or_msg.message;\n      data = obj_or_msg.stack;\n    } else {\n      message = msg ?? \"\";\n      if (obj_or_msg !== undefined && obj_or_msg !== null) {\n        try {\n          data = JSON.stringify(obj_or_msg);\n        } catch {\n          data = \"[unserializable]\";\n        }\n      }\n    }\n\n    const bind_str =\n      bindings && Object.keys(bindings).length\n        ? ` ${JSON.stringify(bindings)}`\n        : \"\";\n\n    const parts = [ts, tag, message, data, bind_str].filter(Boolean);\n    process.stdout.write(parts.join(\" \") + \"\\n\");\n  }\n}\n","/**\n * @module lru-map\n * @category Internal\n *\n * Tiny bounded LRU map / set built on insertion-ordered `Map`. Used to cap\n * memory in long-running orchestrators that mint large numbers of keys —\n * notably:\n *\n * - {@link InMemoryCache}: stream → state checkpoint\n * - `Act._subscribed_streams`: stream → presence (LruSet)\n *\n * Apps with millions of dynamic streams (one target per aggregate) can't\n * afford an unbounded `Set<string>` — eviction is required.\n *\n * @internal\n */\n\n/**\n * Bounded LRU map. `get()` promotes; `has()` does not. `set()` always\n * promotes and evicts the oldest entry when at capacity.\n *\n * @internal\n */\nexport class LruMap<K, V> {\n  private readonly _entries = new Map<K, V>();\n  private readonly _max_size: number;\n\n  constructor(maxSize: number) {\n    this._max_size = maxSize;\n  }\n\n  get(key: K): V | undefined {\n    const v = this._entries.get(key);\n    if (v === undefined) return undefined;\n    // promote: delete + re-insert moves to most-recent position\n    this._entries.delete(key);\n    this._entries.set(key, v);\n    return v;\n  }\n\n  has(key: K): boolean {\n    return this._entries.has(key);\n  }\n\n  set(key: K, value: V): void {\n    this._entries.delete(key);\n    if (this._entries.size >= this._max_size) {\n      // size >= maxSize ≥ 1 → at least one entry exists → next().value\n      // is the oldest key (asserted with `!`).\n      const oldest = this._entries.keys().next().value!;\n      this._entries.delete(oldest);\n    }\n    this._entries.set(key, value);\n  }\n\n  delete(key: K): boolean {\n    return this._entries.delete(key);\n  }\n\n  clear(): void {\n    this._entries.clear();\n  }\n\n  get size(): number {\n    return this._entries.size;\n  }\n}\n\n/**\n * Bounded LRU set built on top of {@link LruMap}. `has()` does not promote;\n * `add()` does (re-inserting if already present, evicting the oldest at\n * capacity).\n *\n * @internal\n */\nexport class LruSet<T> {\n  private readonly _map: LruMap<T, true>;\n\n  constructor(maxSize: number) {\n    this._map = new LruMap(maxSize);\n  }\n\n  has(value: T): boolean {\n    return this._map.has(value);\n  }\n\n  add(value: T): void {\n    this._map.set(value, true);\n  }\n\n  delete(value: T): boolean {\n    return this._map.delete(value);\n  }\n\n  clear(): void {\n    this._map.clear();\n  }\n\n  get size(): number {\n    return this._map.size;\n  }\n}\n","import { LruMap } from \"../internal/lru-map.js\";\nimport type { Cache, CacheEntry, Schema } from \"../types/index.js\";\n\n/**\n * In-memory LRU cache for stream snapshots.\n *\n * Backed by an internal `LruMap` for O(1) get/set with LRU eviction.\n * Configurable `maxSize` bounds memory usage.\n *\n * @example\n * ```typescript\n * import { cache } from \"@rotorsoft/act\";\n * import { InMemoryCache } from \"@rotorsoft/act\";\n *\n * cache(new InMemoryCache({ maxSize: 500 }));\n * ```\n */\n/* eslint-disable @typescript-eslint/require-await -- async interface for Redis-compatibility */\nexport class InMemoryCache implements Cache {\n  // CacheEntry<any> lets `get<TState>` and `set<TState>` flow without casts:\n  // any is bidirectionally compatible with the per-call TState binding, while\n  // the public Cache interface still presents a typed surface to callers.\n  private readonly _entries: LruMap<string, CacheEntry<any>>;\n\n  constructor(options?: { maxSize?: number }) {\n    this._entries = new LruMap(options?.maxSize ?? 1000);\n  }\n\n  /** @inheritDoc */\n  async get<TState extends Schema>(\n    stream: string\n  ): Promise<CacheEntry<TState> | undefined> {\n    return this._entries.get(stream);\n  }\n\n  /** @inheritDoc */\n  async set<TState extends Schema>(\n    stream: string,\n    entry: CacheEntry<TState>\n  ): Promise<void> {\n    this._entries.set(stream, entry);\n  }\n\n  /** @inheritDoc */\n  async invalidate(stream: string): Promise<void> {\n    this._entries.delete(stream);\n  }\n\n  /** @inheritDoc */\n  async clear(): Promise<void> {\n    this._entries.clear();\n  }\n\n  /** @inheritDoc */\n  async dispose(): Promise<void> {\n    this._entries.clear();\n  }\n\n  /** Current number of entries held by the LRU. */\n  get size(): number {\n    return this._entries.size;\n  }\n}\n","import type {\n  Actor,\n  Message,\n  Schema,\n  Schemas,\n  Snapshot,\n  Target,\n} from \"./action.js\";\n\n/**\n * @packageDocumentation\n * @module act/types\n * @category Types\n * Application error type constants and error classes for the Act Framework.\n *\n * - `ERR_VALIDATION`: Schema validation error\n * - `ERR_INVARIANT`: Invariant validation error\n * - `ERR_CONCURRENCY`: Optimistic concurrency validation error on commits\n */\nexport const Errors = {\n  ValidationError: \"ERR_VALIDATION\",\n  InvariantError: \"ERR_INVARIANT\",\n  ConcurrencyError: \"ERR_CONCURRENCY\",\n  StreamClosedError: \"ERR_STREAM_CLOSED\",\n  NonRetryableError: \"ERR_NON_RETRYABLE\",\n  StoreError: \"ERR_STORE\",\n} as const;\n\n/**\n * Thrown when an action or event payload fails Zod schema validation.\n *\n * This error indicates that data doesn't match the expected schema defined\n * for an action or event. The `details` property contains the Zod validation\n * error with specific information about what failed.\n *\n * @example Catching validation errors\n * ```typescript\n * import { ValidationError } from \"@rotorsoft/act\";\n *\n * try {\n *   await app.do(\"createUser\", target, {\n *     email: \"invalid-email\",  // Missing @ symbol\n *     age: -5                  // Negative age\n *   });\n * } catch (error) {\n *   if (error instanceof ValidationError) {\n *     console.error(\"Validation failed for:\", error.target);\n *     console.error(\"Invalid payload:\", error.payload);\n *     console.error(\"Validation details:\", error.details);\n *     // details contains Zod error with field-level info\n *   }\n * }\n * ```\n *\n * @example Logging validation details\n * ```typescript\n * try {\n *   await app.do(\"updateProfile\", target, payload);\n * } catch (error) {\n *   if (error instanceof ValidationError) {\n *     error.details.errors.forEach((err) => {\n *       console.error(`Field ${err.path.join(\".\")}: ${err.message}`);\n *     });\n *   }\n * }\n * ```\n *\n * @see {@link https://zod.dev | Zod documentation} for validation details\n */\nexport class ValidationError extends Error {\n  /** The type of target being validated (e.g., \"action\", \"event\") */\n  public readonly target: string;\n  /** The invalid payload that failed validation */\n  public readonly payload: any;\n  /** Zod validation error details */\n  public readonly details: any;\n\n  constructor(target: string, payload: any, details: any) {\n    super(`Invalid ${target} payload`);\n    this.name = Errors.ValidationError;\n    this.target = target;\n    this.payload = payload;\n    this.details = details;\n  }\n}\n\n/**\n * Thrown when a business rule (invariant) is violated during action execution.\n *\n * Invariants are conditions that must hold true for an action to succeed.\n * They're checked after loading the current state but before emitting events.\n * This error provides complete context about what action was attempted and\n * why it was rejected.\n *\n * @template TState - State schema type\n * @template TEvents - Event schemas type\n * @template TActions - Action schemas type\n * @template TKey - Action name\n * @template TActor - Actor type extending base Actor\n *\n * @example Catching invariant violations\n * ```typescript\n * import { InvariantError } from \"@rotorsoft/act\";\n *\n * try {\n *   await app.do(\"withdraw\",\n *     { stream: \"account-123\", actor: { id: \"user1\", name: \"Alice\" } },\n *     { amount: 1000 }\n *   );\n * } catch (error) {\n *   if (error instanceof InvariantError) {\n *     console.error(\"Action:\", error.action);\n *     console.error(\"Reason:\", error.description);\n *     console.error(\"Current state:\", error.snapshot.state);\n *     console.error(\"Attempted payload:\", error.payload);\n *   }\n * }\n * ```\n *\n * @example User-friendly error messages\n * ```typescript\n * try {\n *   await app.do(\"closeTicket\", target, payload);\n * } catch (error) {\n *   if (error instanceof InvariantError) {\n *     // Present friendly message to user\n *     if (error.description === \"Ticket must be open\") {\n *       return { error: \"This ticket is already closed\" };\n *     } else if (error.description === \"Not authorized\") {\n *       return { error: \"You don't have permission to close this ticket\" };\n *     }\n *   }\n * }\n * ```\n *\n * @example Logging with context\n * ```typescript\n * try {\n *   await app.do(\"transfer\", target, { to: \"account2\", amount: 500 });\n * } catch (error) {\n *   if (error instanceof InvariantError) {\n *     logger.error({\n *       action: error.action,\n *       stream: error.target.stream,\n *       actor: error.target.actor,\n *       reason: error.description,\n *       balance: error.snapshot.state.balance,\n *       attempted: error.payload.amount\n *     }, \"Invariant violation\");\n *   }\n * }\n * ```\n *\n * @see {@link Invariant} for defining business rules\n */\nexport class InvariantError<\n  TState extends Schema,\n  TEvents extends Schemas,\n  TActions extends Schemas,\n  TKey extends keyof TActions,\n  TActor extends Actor = Actor,\n> extends Error {\n  /** The action that was attempted */\n  readonly action: TKey;\n  /** The action payload that was provided */\n  readonly payload: Readonly<TActions[TKey]>;\n  /** The target stream and actor context */\n  readonly target: Target<TActor>;\n  /** The current state snapshot when invariant was checked */\n  readonly snapshot: Snapshot<TState, TEvents>;\n  /** Human-readable description of why the invariant failed */\n  readonly description: string;\n\n  constructor(\n    action: TKey,\n    payload: Readonly<TActions[TKey]>,\n    target: Target<TActor>,\n    snapshot: Snapshot<TState, TEvents>,\n    description: string\n  ) {\n    super(`${action as string} failed invariant: ${description}`);\n    this.name = Errors.InvariantError;\n    this.action = action;\n    this.payload = payload;\n    this.target = target;\n    this.snapshot = snapshot;\n    this.description = description;\n  }\n}\n\n/**\n * Thrown when optimistic concurrency control detects a conflict.\n *\n * This error occurs when trying to commit events to a stream that has been\n * modified by another process since it was last loaded. The version number\n * doesn't match expectations, indicating a concurrent modification.\n *\n * This is a normal occurrence in distributed systems and should be handled\n * by reloading the current state and retrying the action.\n *\n * @example Handling concurrency conflicts with retry\n * ```typescript\n * import { ConcurrencyError } from \"@rotorsoft/act\";\n *\n * async function transferWithRetry(from, to, amount, maxRetries = 3) {\n *   for (let attempt = 0; attempt < maxRetries; attempt++) {\n *     try {\n *       await app.do(\"transfer\",\n *         { stream: from, actor: currentUser },\n *         { to, amount }\n *       );\n *       return { success: true };\n *     } catch (error) {\n *       if (error instanceof ConcurrencyError) {\n *         if (attempt < maxRetries - 1) {\n *           console.log(`Concurrent modification detected, retrying... (${attempt + 1}/${maxRetries})`);\n *           await sleep(100 * Math.pow(2, attempt)); // Exponential backoff\n *           continue;\n *         }\n *       }\n *       throw error;\n *     }\n *   }\n *   return { success: false, reason: \"Too many concurrent modifications\" };\n * }\n * ```\n *\n * @example Logging concurrency conflicts\n * ```typescript\n * try {\n *   await app.do(\"updateInventory\", target, payload);\n * } catch (error) {\n *   if (error instanceof ConcurrencyError) {\n *     logger.warn({\n *       stream: error.stream,\n *       expectedVersion: error.expectedVersion,\n *       actualVersion: error.lastVersion,\n *       events: error.events.map(e => e.name)\n *     }, \"Concurrent modification detected\");\n *   }\n * }\n * ```\n *\n * @example User feedback for conflicts\n * ```typescript\n * try {\n *   await app.do(\"editDocument\", target, { content: newContent });\n * } catch (error) {\n *   if (error instanceof ConcurrencyError) {\n *     return {\n *       error: \"This document was modified by another user. Please refresh and try again.\",\n *       code: \"CONCURRENT_MODIFICATION\"\n *     };\n *   }\n * }\n * ```\n *\n * @see {@link Store.commit} for version checking details\n */\nexport class ConcurrencyError extends Error {\n  /** The stream that had the concurrent modification */\n  public readonly stream: string;\n  /** The actual current version in the store */\n  public readonly lastVersion: number;\n  /** The events that were being committed */\n  public readonly events: Message<Schemas, keyof Schemas>[];\n  /** The version number that was expected */\n  public readonly expectedVersion: number;\n\n  constructor(\n    stream: string,\n    lastVersion: number,\n    events: Message<Schemas, keyof Schemas>[],\n    expectedVersion: number\n  ) {\n    // Message lists stream + event names only. Payloads remain accessible\n    // via `error.events` for callers who need them — keeping them out of\n    // the message avoids MB-scale strings on contended writes and keeps\n    // potentially-sensitive data out of log streams.\n    super(\n      `Concurrency error committing \"${events\n        .map((e) => `${stream}.${e.name}`)\n        .join(\n          \", \"\n        )}\". Expected version ${expectedVersion} but found version ${lastVersion}.`\n    );\n    this.name = Errors.ConcurrencyError;\n    this.stream = stream;\n    this.lastVersion = lastVersion;\n    this.events = events;\n    this.expectedVersion = expectedVersion;\n  }\n}\n\n/**\n * Thrown when attempting to write to a stream that has been closed\n * with a tombstone event.\n *\n * A tombstoned stream is permanently closed — no further actions can\n * be executed against it. The only way to reopen a tombstoned stream\n * is through `Act.close()` with a `restart` callback.\n *\n * @example\n * ```typescript\n * import { StreamClosedError } from \"@rotorsoft/act\";\n *\n * try {\n *   await app.do(\"updateTicket\", target, payload);\n * } catch (error) {\n *   if (error instanceof StreamClosedError) {\n *     console.error(`Stream ${error.stream} is closed`);\n *   }\n * }\n * ```\n *\n * @see {@link Act.close} for closing streams\n */\nexport class StreamClosedError extends Error {\n  /** The stream that is closed */\n  public readonly stream: string;\n\n  constructor(stream: string) {\n    super(`Stream \"${stream}\" is closed (tombstoned)`);\n    this.name = Errors.StreamClosedError;\n    this.stream = stream;\n  }\n}\n\n/**\n * Thrown by a {@link Store} adapter when an infrastructure operation fails\n * for a reason that is *not* a domain condition — a dropped connection, a\n * transaction rollback, a query timeout. It is the typed boundary between\n * \"the store is unavailable/degraded\" and the domain errors above\n * ({@link ConcurrencyError}, {@link StreamClosedError}), which describe\n * legitimate outcomes the caller should branch on.\n *\n * Adapters wrap their driver errors in `StoreError` (preserving the\n * original via `cause`) so the orchestrator can distinguish a degraded\n * backend from \"no work\" and react accordingly — see the drain circuit\n * breaker, which trips on repeated `StoreError`s and surfaces an\n * `error` lifecycle event instead of silently spinning on a down\n * database.\n *\n * @example\n * ```typescript\n * app.on(\"error\", ({ error, circuit }) => {\n *   if (error instanceof StoreError)\n *     alert(`store ${error.operation} failing; circuit=${circuit}`);\n * });\n * ```\n */\nexport class StoreError extends Error {\n  /** The store operation that failed (e.g. `\"claim\"`, `\"ack\"`, `\"commit\"`). */\n  public readonly operation: string;\n\n  constructor(operation: string, options?: { cause?: unknown }) {\n    super(`Store operation \"${operation}\" failed`, options);\n    this.name = Errors.StoreError;\n    this.operation = operation;\n  }\n}\n\n/**\n * Thrown by a reaction handler to signal that the failure is permanent\n * and the drain pipeline should block the stream immediately, without\n * consuming the rest of the `maxRetries` budget.\n *\n * The drain finalizer detects `instanceof NonRetryableError` and forces\n * `block = options.blockOnError` regardless of `lease.retry`. When\n * `blockOnError` is `false`, behavior is unchanged (drain keeps retrying\n * forever) — the class never overrides the operator's explicit \"never\n * block\" choice.\n *\n * Use this for failures the handler *knows* won't get better on retry:\n * a 4xx from a webhook, a `ZodError` on malformed input, a \"user\n * deleted\" 404 from a downstream API. Use regular `Error` (or a\n * subclass) for transient failures so the existing retry-with-backoff\n * loop applies.\n *\n * @example Wrapping a permanent downstream error\n * ```typescript\n * import { NonRetryableError } from \"@rotorsoft/act\";\n *\n * .on(\"OrderConfirmed\")\n *   .do(async (event) => {\n *     const res = await fetch(url, ...);\n *     if (res.status >= 400 && res.status < 500) {\n *       throw new NonRetryableError(\n *         `webhook ${url} responded ${res.status}`,\n *         { cause: await res.text() }\n *       );\n *     }\n *     if (!res.ok) throw new Error(`webhook ${url} responded ${res.status}`);\n *   })\n * ```\n *\n * @example Marking validation failures as non-retryable\n * ```typescript\n * .on(\"PaymentReceived\")\n *   .do(async (event) => {\n *     const parsed = Schema.safeParse(event.data);\n *     if (!parsed.success) {\n *       throw new NonRetryableError(\"payment payload failed validation\", {\n *         cause: parsed.error,\n *       });\n *     }\n *     // ... handle parsed payload\n *   })\n * ```\n */\nexport class NonRetryableError extends Error {\n  /** The original failure, if any. Mirrors the standard `Error.cause` shape. */\n  public override readonly cause?: unknown;\n\n  constructor(message: string, options?: { cause?: unknown }) {\n    super(message);\n    this.name = Errors.NonRetryableError;\n    this.cause = options?.cause;\n  }\n}\n","import { prettifyError, ZodError, type ZodType } from \"zod\";\nimport { config } from \"./config.js\";\nimport { ValidationError } from \"./types/index.js\";\n\n/**\n * @module utils\n * @category Utilities\n *\n * Small utilities used across the framework:\n * - {@link validate} — parse a payload against a Zod schema, throwing\n *   {@link ValidationError} on failure.\n * - {@link extend} — validate a source object and merge into defaults.\n * - {@link sleep} — async delay (default duration from `config().sleepMs`).\n */\n\n/**\n * Parse `payload` against `schema`, returning the validated value or throwing\n * a {@link ValidationError} with prettified Zod details. When `schema` is\n * omitted, returns `payload` unchanged. The framework calls this for every\n * `app.do()` action, every emitted event, and every state init.\n *\n * @example\n * ```typescript\n * const UserSchema = z.object({ email: z.string().email() });\n * const user = validate(\"User\", { email: \"alice@example.com\" }, UserSchema);\n * ```\n *\n * @see {@link ValidationError}\n */\nexport const validate = <S>(\n  target: string,\n  payload: Readonly<S>,\n  schema?: ZodType<S>\n): Readonly<S> => {\n  try {\n    return schema ? schema.parse(payload) : payload;\n  } catch (error) {\n    if (error instanceof ZodError) {\n      throw new ValidationError(target, payload, prettifyError(error));\n    }\n    throw new ValidationError(target, payload, error);\n  }\n};\n\n/**\n * Validate `source` against `schema` and return a new object that merges\n * `source` over the optional `target` defaults. Used by {@link config} for\n * env-var-overrides-defaults patterns; safe to call elsewhere — it never\n * mutates `target`.\n *\n * @example\n * ```typescript\n * const schema = z.object({ host: z.string(), port: z.number() });\n * const cfg = extend({ port: 8080 }, schema, { host: \"localhost\", port: 80 });\n * // → { host: \"localhost\", port: 8080 }\n * ```\n *\n * @throws {@link ValidationError} if `source` fails the schema.\n */\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  const value = validate(\"config\", source, schema);\n  return { ...target, ...value } as Readonly<S & T>;\n};\n\n/**\n * Pause for `ms` milliseconds (or `config().sleepMs` when omitted — `100ms`\n * in dev, `0ms` in tests). Used by adapters to simulate async I/O.\n *\n * @example\n * ```typescript\n * await sleep();      // default delay from config\n * await sleep(500);   // explicit 500ms\n * ```\n */\nexport async function sleep(ms?: number) {\n  return new Promise((resolve) => setTimeout(resolve, ms ?? config().sleepMs));\n}\n\n/**\n * Regex metacharacters that, when present in a reaction `source`, make it a\n * pattern rather than a literal stream name. A source containing none of\n * these is a bare stream name — the common case — and every claim/fetch\n * site matches it by string equality on the store's stream index. A source\n * containing any of them is compiled as a RegExp and matched against\n * candidate streams with the caller's own anchoring (e.g. `^(A|B)$`).\n */\nconst SOURCE_METACHARACTERS = /[\\^$.*+?()[\\]{}|\\\\]/;\n\n/**\n * True when `source` is a **literal** stream name — it carries no regex\n * metacharacter, so every adapter treats it as an exact match. This is the\n * fast, index-friendly path and covers every autoclose/dynamic-resolver\n * source (bare stream names). A `false` return means the source is a\n * **pattern** (contains `^ $ . * + ? ( ) [ ] { } | \\`) and must be compiled\n * as a RegExp before matching — the shape the calculator's static\n * `source: \"^(A|B)$\"` reaction relies on.\n *\n * The single source of truth for literal-vs-pattern classification across\n * the InMemory has-work probe, the drain fetch path, and the SQL adapters,\n * so all three agree on which sources take the exact path.\n *\n * @example\n * ```typescript\n * is_literal_source(\"Board\");    // → true  (exact lookup)\n * is_literal_source(\"^(A|B)$\");  // → false (compile as RegExp)\n * ```\n */\nexport function is_literal_source(source: string): boolean {\n  return !SOURCE_METACHARACTERS.test(source);\n}\n\n/**\n * Matches an ISO-8601 timestamp, the shape `JSON.stringify` produces for a\n * `Date`.\n *\n * @internal\n */\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/**\n * Revive ISO-8601-shaped strings into `Date`s during `JSON.parse`.\n *\n * **The framework no longer uses this.** Dates are resolved from the declared\n * `z.date()` paths at build time and converted on read, so a field declared\n * `z.string()` keeps its string even when the value looks like a timestamp\n * ([#1556](https://github.com/Rotorsoft/act-root/issues/1556)). Adapters\n * return what they stored; typing is the orchestrator's job.\n *\n * Kept exported for host applications that parse Act JSON themselves and want\n * the old shape-based behaviour. New code should let the schema decide.\n *\n */\nexport const dateReviver = (_key: string, value: unknown): unknown =>\n  typeof value === \"string\" && ISO_8601.test(value) ? new Date(value) : value;\n","/**\n * @packageDocumentation\n * Configuration utilities for Act Framework environment, logging, and package metadata.\n *\n * Provides type-safe configuration loading and validation using Zod schemas.\n *\n * @module config\n */\nimport * as fs from \"node:fs\";\nimport { z } from \"zod\";\nimport { log } from \"./ports.js\";\nimport {\n  type Environment,\n  Environments,\n  type LogLevel,\n  LogLevels,\n} from \"./types/index.js\";\nimport { extend } from \"./utils.js\";\n\n/**\n * Zod schema for validating package.json metadata.\n * @internal\n */\nexport const PackageSchema = z.object({\n  name: z.string().min(1),\n  version: z.string().min(1),\n  description: z.string().min(1).optional(),\n  author: z\n    .object({ name: z.string().min(1), email: z.string().optional() })\n    .optional()\n    .or(z.string().min(1))\n    .optional(),\n  license: z.string().min(1).optional(),\n  dependencies: z.record(z.string(), z.string()).optional(),\n});\n\n/**\n * Type representing the validated package.json metadata.\n *\n * @internal\n */\nexport type Package = z.infer<typeof PackageSchema>;\n\n/**\n * Fallback package metadata when `package.json` can't be read at module\n * load — happens when the framework is consumed from a CWD that doesn't\n * have one (bundled CLIs, Lambda layers, embedded scripts) or when the\n * file exists but is malformed.\n *\n * The values are deliberately synthetic so callers spot them immediately:\n * `config().name === \"act-fallback\"` is a runtime signal that the framework\n * couldn't load the host project's package.json.\n *\n * @internal\n */\nconst FALLBACK_PACKAGE: Package = {\n  name: \"act-fallback\",\n  version: \"0.0.0-fallback\",\n  description: \"Synthetic fallback — package.json could not be loaded\",\n};\n\n/**\n * Loads and parses the local package.json file as a Package object. On\n * any read or parse failure, falls back to {@link FALLBACK_PACKAGE} and\n * stashes the error so {@link config} can surface it on first access —\n * we can't call `log()` here because the logger port memoizes on first\n * call and locking it at module load defeats user injection.\n *\n * @internal\n */\nconst get_package = (): Package => {\n  try {\n    const raw = fs.readFileSync(\"package.json\");\n    return JSON.parse(raw.toString()) as Package;\n  } catch (err) {\n    pkg_load_error = err;\n    return FALLBACK_PACKAGE;\n  }\n};\n\n/** Stashed read/parse error from {@link get_package}, surfaced by config(). */\nlet pkg_load_error: unknown;\n\n/**\n * Zod schema for the full Act Framework configuration object.\n * Includes package metadata, environment, logging, and timing options.\n * @internal\n */\nconst BaseSchema = PackageSchema.extend({\n  env: z.enum(Environments),\n  logLevel: z.enum(LogLevels),\n  logSingleLine: z.boolean(),\n  sleepMs: z.number().int().min(0).max(5000),\n});\n\n/**\n * Type representing the validated Act Framework configuration object.\n */\nexport type Config = z.infer<typeof BaseSchema>;\n\nconst { NODE_ENV, LOG_LEVEL, LOG_SINGLE_LINE, SLEEP_MS } = process.env;\n\nconst env = (NODE_ENV || \"development\") as Environment;\nconst logLevel = (LOG_LEVEL ||\n  (NODE_ENV === \"test\"\n    ? \"fatal\"\n    : NODE_ENV === \"production\"\n      ? \"info\"\n      : \"trace\")) as LogLevel;\nconst logSingleLine = (LOG_SINGLE_LINE || \"true\") === \"true\";\nconst sleepMs = parseInt(NODE_ENV === \"test\" ? \"0\" : (SLEEP_MS ?? \"100\"), 10);\n\nconst pkg = get_package();\n\n// Lazily validated on first call. Cannot run extend() at module load\n// because of a utils.ts <-> config.ts cycle (utils imports config for\n// sleep()'s default). Inputs are frozen after import, so the cached\n// result is stable for the life of the process.\nlet _validated: Config | undefined;\n\n/**\n * Gets the current Act Framework configuration.\n *\n * Configuration is loaded from package.json and environment variables, providing\n * type-safe access to application metadata and runtime settings.\n *\n * **Environment Variables:**\n * - `NODE_ENV`: \"development\" | \"test\" | \"staging\" | \"production\" (default: \"development\")\n * - `LOG_LEVEL`: \"fatal\" | \"error\" | \"warn\" | \"info\" | \"debug\" | \"trace\"\n * - `LOG_SINGLE_LINE`: \"true\" | \"false\" (default: \"true\")\n * - `SLEEP_MS`: Milliseconds for sleep utility (default: 100, 0 for tests)\n *\n * **Defaults by environment:**\n * - test: logLevel=\"error\", sleepMs=0\n * - production: logLevel=\"info\"\n * - development: logLevel=\"trace\"\n *\n * @returns The validated configuration object\n *\n * @example Basic usage\n * ```typescript\n * import { config } from \"@rotorsoft/act\";\n *\n * const cfg = config();\n * console.log(`App: ${cfg.name} v${cfg.version}`);\n * console.log(`Environment: ${cfg.env}`);\n * console.log(`Log level: ${cfg.logLevel}`);\n * ```\n *\n * @example Environment-specific behavior\n * ```typescript\n * import { config } from \"@rotorsoft/act\";\n *\n * const cfg = config();\n *\n * if (cfg.env === \"production\") {\n *   // Use PostgreSQL in production\n *   store(new PostgresStore(prodConfig));\n * } else {\n *   // Use in-memory store for dev/test\n *   store(new InMemoryStore());\n * }\n * ```\n *\n * @example Adjusting log levels\n * ```typescript\n * // Set via environment variable:\n * // LOG_LEVEL=debug npm start\n *\n * // Or check in code:\n * const cfg = config();\n * if (cfg.logLevel === \"trace\") {\n *   logger.trace(\"Detailed debugging enabled\");\n * }\n * ```\n *\n * @see {@link Config} for configuration type\n */\nexport const config = (): Config => {\n  if (!_validated) {\n    _validated = extend(\n      { ...pkg, env, logLevel, logSingleLine, sleepMs },\n      BaseSchema\n    );\n    if (pkg_load_error) {\n      // Surface the fallback once, after _validated is set so the\n      // recursive log() → config() call short-circuits. log() resolves\n      // through the port singleton — respects user injection and level.\n      const msg =\n        pkg_load_error instanceof Error\n          ? pkg_load_error.message\n          : typeof pkg_load_error === \"string\"\n            ? pkg_load_error\n            : \"unknown error\";\n      log().warn(\n        `[act] Could not read package.json (${msg}); using synthetic ` +\n          `name=\"${FALLBACK_PACKAGE.name}\" version=\"${FALLBACK_PACKAGE.version}\".`\n      );\n      pkg_load_error = undefined;\n    }\n  }\n  return _validated;\n};\n","import { type ZodObject, type ZodRawShape, z } from \"zod\";\n// Deep-path import (vs `../internal/index.js`) is deliberate — `_registry` is\n// a side-effect-free leaf, and going through the internal barrel would pull\n// tracing.ts → config.ts in at type-schema load time and crash on TDZ when a\n// test imports a public schema before config is initialized.\nimport { _mark_sensitive, _registry } from \"../internal/sensitive.js\";\n\n/**\n * @packageDocumentation\n * @module act/types\n * @category Types\n * Zod schemas and helpers for the Act Framework.\n */\n\n/**\n * An empty Zod schema (no properties).\n */\nexport const ZodEmpty = z.record(z.string(), z.never());\n\n/**\n * Sensitive-data foundation re-exports (#855 / epic #566).\n *\n * - `REDACTED` / `SHREDDED` — sentinels placed in `event.data[field]`\n *   when the caller isn't authorized to see a sensitive field\n *   (`.discloses(predicate)` returned `false` or none was declared —\n *   recoverable) or the underlying PII was wiped (`Store.forget_pii` —\n *   irrecoverable).\n *   top-level field names marked via {@link sensitive}. A pure,\n *   read-only helper that inspects the out-of-band sensitive registry (a\n *   process-global `WeakMap`) `sensitive()` populates, otherwise\n *   unreachable from outside the package. Surfaced for adapters and\n *   tooling that must reflect input sensitivity on their own wire\n *   surface — e.g. the `@rotorsoft/act-http/openapi` emitter marks these\n *   fields `writeOnly` + `format: password` so generated clients and\n *   Swagger UI don't echo PII freely. Returns `[]` for non-object\n *   schemas or objects with no sensitive fields; top-level shape only.\n */\nexport { pii_fields, REDACTED, SHREDDED } from \"../internal/sensitive.js\";\n\n/**\n * Mark a Zod schema as sensitive. Returns the same schema instance — the\n * marker is registered out-of-band so the static type is preserved and the\n * call site reads as a pure annotation.\n *\n * Idempotent: re-wrapping an already-sensitive schema is a no-op.\n *\n * The marker is what the orchestrator inspects to split event payloads into\n * `data` + `pii` on commit, gate reads via `.discloses`, and strip handler\n * payloads. Part of the sensitive-data foundation (#855 / epic #566).\n *\n * @example\n * ```ts\n * import { z } from \"zod\";\n * import { state, sensitive } from \"@rotorsoft/act\";\n *\n * const UserRegistered = z.object({\n *   email: sensitive(z.string()),\n *   name: sensitive(z.string()),\n *   plan: z.enum([\"free\", \"pro\"]),  // not sensitive — stays in events.data\n * });\n * ```\n *\n * @param schema - The Zod schema to mark sensitive.\n * @returns The same schema instance, unmodified at the type level.\n */\nexport function sensitive<T extends z.ZodType>(schema: T): T {\n  _registry.add(schema, { sensitive: true });\n  // Also stamp the def, so the marker survives the clone Zod produces for\n  // any refinement chained AFTER this call — `sensitive(z.string()).min(1)`\n  // used to lose it silently and write plaintext into `events.data` (#1417).\n  _mark_sensitive(schema);\n  return schema;\n}\n\n/**\n * Zod schema for an actor (user, system, etc.).\n */\nexport const ActorSchema = z\n  .object({\n    id: z.string(),\n    name: z.string(),\n  })\n  .loose()\n  .readonly();\n\n/**\n * Zod schema for a target (stream and actor info).\n */\nexport const TargetSchema = z\n  .object({\n    stream: z.string(),\n    actor: ActorSchema,\n    expectedVersion: z.number().optional(),\n  })\n  .loose()\n  .readonly();\n\n/**\n * Zod schema for causation event metadata.\n */\nexport const CausationEventSchema = z.object({\n  id: z.number(),\n  name: z.string(),\n  stream: z.string(),\n});\n\n/**\n * Zod schema for event metadata (correlation and causation).\n */\nexport const EventMetaSchema = z\n  .object({\n    correlation: z.string(),\n    causation: z.object({\n      action: TargetSchema.and(z.object({ name: z.string() })).optional(),\n      event: CausationEventSchema.optional(),\n    }),\n  })\n  .readonly();\n\n/**\n * Zod schema for committed event metadata (id, stream, version, created, meta).\n */\nexport const CommittedMetaSchema = z\n  .object({\n    id: z.number(),\n    stream: z.string(),\n    version: z.number(),\n    created: z.date(),\n    meta: EventMetaSchema,\n  })\n  .readonly();\n\n/**\n * Type representing the full state schema for a domain.\n * @property events - Map of event names to Zod schemas.\n * @property actions - Map of action names to Zod schemas.\n * @property state - Zod schema for the state object.\n */\nexport type StateSchema = Readonly<{\n  events: Record<string, ZodObject<ZodRawShape> | typeof ZodEmpty>;\n  actions: Record<string, ZodObject<ZodRawShape> | typeof ZodEmpty>;\n  state: ZodObject<ZodRawShape>;\n}>;\n\n/**\n * Query options for event store queries.\n */\nexport const QuerySchema = z\n  .object({\n    stream: z.string().optional(),\n    names: z.string().array().optional(),\n    before: z.number().optional(),\n    after: z.number().optional(),\n    limit: z.number().optional(),\n    created_before: z.date().optional(),\n    created_after: z.date().optional(),\n    backward: z.boolean().optional(),\n    correlation: z.string().optional(),\n    with_snaps: z.boolean().optional(),\n    stream_exact: z.boolean().optional(),\n  })\n  .readonly();\n","/**\n * @module sensitive\n * @category Internal\n *\n * Internal mechanics for the sensitive-data foundation (#855 / epic #566).\n * The public surface (`sensitive(zodType)`) lives at `libs/act/src/sensitive.ts`\n * and re-exports `REDACTED` / `SHREDDED` from here; this module holds the\n * registry plus the helpers the orchestrator calls during commit, load, and\n * handler dispatch.\n *\n * - `_registry` — process-global `z.registry<{ sensitive: true }>()`. Public\n *   `sensitive()` adds to it; the helpers in this module read it.\n * - `pii_fields(schema)` — walk a Zod schema's top-level shape, return the\n *   keys marked via `sensitive(...)`.\n * - `pii_gate(event, fields, predicate, actor)` — produce the external\n *   view: plaintext when authorized, `[REDACTED]` when not, `[SHREDDED]`\n *   when the underlying pii column is null.\n * - `pii_strip(event, fields)` — remove sensitive keys entirely\n *   before invoking projection / reaction handlers.\n *\n * @internal\n */\n\nimport { z } from \"zod\";\nimport type { Actor, Committed, Schemas } from \"../types/index.js\";\n\n/**\n * Sentinel placed in `event.data[field]` when the caller isn't authorized to\n * see the sensitive field — either `.discloses(predicate)` returned `false`,\n * or no predicate was declared (framework default-deny). Recoverable: a\n * properly-authorized read returns the plaintext.\n *\n * Re-exported from `libs/act/src/sensitive.ts` as part of the public surface.\n */\nexport const REDACTED = \"[REDACTED]\" as const;\n\n/**\n * Sentinel placed in `event.data[field]` when the underlying PII payload has\n * been wiped via `Store.forget_pii(stream)` — the row's pii column is `NULL`\n * and the original plaintext is gone forever. Irrecoverable.\n *\n * Re-exported from `libs/act/src/sensitive.ts` as part of the public surface.\n */\nexport const SHREDDED = \"[SHREDDED]\" as const;\n\n/**\n * Process-global registry holding every Zod schema marked sensitive. Backed\n * by a `WeakMap`, so wrapper-created instances (`.optional()`, `.nullable()`,\n * `.default()`) that chain off a marked schema produce *new* schema instances\n * the registry doesn't track; the field walker handles those via unwrap.\n *\n * Exported so the public `sensitive(zodType)` wrapper can call `_registry.add`.\n * Underscore prefix marks \"framework-private, don't touch from user code.\"\n *\n * @internal\n */\nexport const _registry = z.registry<{ sensitive: true }>();\n\n/**\n * Marker key stamped onto a schema's own `def`. Zod clones a schema on every\n * refinement (`.min()`, `.email()`, `.trim()`, `.describe()`, `.refine()`,\n * `.transform()`, …) via `{...def}`, which copies own symbol keys — so a\n * marker on the def survives the whole chain, while the `_registry` WeakMap\n * (keyed on the *instance*) does not (#1417).\n *\n * The registry is still populated and still consulted: it covers schemas\n * marked before this key existed, and it is the mechanism the public\n * `sensitive()` doc-comment describes.\n *\n * @internal\n */\nexport const _SENSITIVE = Symbol.for(\"act.sensitive\");\n\n/**\n * Stamp the def-level marker. Called by the public `sensitive()` alongside\n * `_registry.add`.\n *\n * @internal\n */\nexport function _mark_sensitive(schema: z.ZodType): void {\n  const def = (\n    schema as unknown as {\n      _zod?: { def?: Record<PropertyKey, unknown> };\n    }\n  )._zod?.def;\n  if (def) def[_SENSITIVE] = true;\n}\n\n/**\n * True when the given schema was marked via `sensitive(...)`.\n *\n * Walks through Zod wrapper layers (`.optional()`, `.nullable()`,\n * `.default()`, `.readonly()`) by following `_def.innerType` until it reaches\n * a non-wrapper schema, then checks the registry. Wrappers create new schema\n * instances; the marker lives on the *inner* schema the user wrapped, so we\n * test that one.\n *\n * @internal\n */\nexport function is_pii(schema: z.ZodType): boolean {\n  let cur: z.ZodType = schema;\n  while (true) {\n    if (_registry.has(cur)) return true;\n    // Def-level marker: survives the clone a refinement produces, which the\n    // instance-keyed registry above cannot (#1417).\n    const def = (\n      cur as unknown as {\n        _zod?: { def?: Record<PropertyKey, unknown> };\n      }\n    )._zod?.def;\n    if (def?.[_SENSITIVE] === true) return true;\n    const inner = (cur as { _def?: { innerType?: z.ZodType } })._def?.innerType;\n    if (!inner || inner === cur) return false;\n    cur = inner;\n  }\n}\n\n/**\n * Derive an event's sensitive fields, as the declared schema of each.\n *\n * Walks the top-level shape of a `z.object({...})` and keeps the keys whose\n * schema (after unwrapping optional/nullable/default wrappers) was marked via\n * `sensitive(...)`. Returns an empty object for non-object schemas or events\n * with no sensitive fields — the common-case zero-cost path.\n *\n * Only the top-level shape is walked. Sensitive fields nested inside a\n * `z.object` declared inside the event payload would require recursive\n * descent; that's deferred until a real callsite needs it.\n *\n * A union event has no top-level shape, so the options are walked and merged:\n * a key sensitive in any variant must be split, because the stored payload\n * could be that variant ([#1417](https://github.com/Rotorsoft/act-root/issues/1417)).\n * The first variant to declare a key wins, which only matters to a caller that\n * wants the schema rather than the name.\n *\n * Returning the schemas rather than just the names is what lets a caller do\n * something per field — the event builder asks each one whether it holds a\n * date, so the `pii` sidecar's dates can be revived like any other.\n *\n * @internal\n */\nexport function pii_schemas(schema: z.ZodType): Record<string, z.ZodType> {\n  const shape = (schema as { shape?: Record<string, z.ZodType> }).shape;\n  if (shape && typeof shape === \"object\") {\n    const fields: Record<string, z.ZodType> = {};\n    for (const key of Object.keys(shape))\n      if (is_pii(shape[key])) fields[key] = shape[key];\n    return fields;\n  }\n  const options = (schema as { options?: unknown }).options;\n  if (Array.isArray(options)) {\n    const fields: Record<string, z.ZodType> = {};\n    for (const option of options)\n      for (const [key, field] of Object.entries(\n        pii_schemas(option as z.ZodType)\n      ))\n        fields[key] ??= field;\n    return fields;\n  }\n  return {};\n}\n\n/**\n * The names of an event's sensitive fields — {@link pii_schemas} keyed.\n *\n * @internal — consumed by the registry's `sensitive_fields(event_name)` lookup,\n * and public through `types/schemas.ts`, where act-http's OpenAPI emitter uses\n * it to mark request-body properties `writeOnly`.\n */\nexport function pii_fields(schema: z.ZodType): readonly string[] {\n  return Object.keys(pii_schemas(schema));\n}\n\n/**\n * Split an emitted event's `data` into `data` (non-sensitive) + `pii`\n * (sensitive) using the field list precomputed at build time. Used by the\n * State's `_pii_split` decorator just before `Store.commit`.\n *\n * Single forward pass over `Object.keys(validated)` — same shape as the\n * spread-and-delete-free implementation in slice 3, just hoisted out of the\n * orchestrator hot path so it's only invoked when the State actually has a\n * sensitive event.\n *\n * @internal\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 * Only ever reached for events that declare sensitive fields — the sole caller\n * is {@link make_gate}, which the builder invokes exclusively for sensitive\n * events; non-sensitive events short-circuit to {@link IDENTITY_GATE} before\n * they get here. `fields` is therefore guaranteed non-empty (same contract as\n * {@link pii_strip}).\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 *\n * @internal\n */\nexport function 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 — dropping it\n  // is the whole point of the gate. Keeping it (an earlier `...event` spread)\n  // leaked plaintext PII on every gated read surface (`load`, `query`,\n  // `query_array`) even while `data` was correctly redacted (#1277). Strip it\n  // once here; the plaintext lives in `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: given a committed event and the reading\n * actor, return the caller-visible form. This is the single gating primitive\n * the builder prebuilds for **every** read surface — both the actor-less\n * `query` / `query_array` (which pass no actor → default-deny) and the\n * actor-aware `load` / `do`-return view (which pass the reader). Non-sensitive\n * events use the shared {@link IDENTITY_GATE}; sensitive events use a redactor\n * built by {@link make_gate} that closes over the field list and the state's\n * disclosure predicate, so the read path never recomputes the sensitive-field\n * lookup nor allocates per event.\n *\n * The `actor` is optional so the actor-less surfaces can call `gate(event)`.\n *\n * @internal\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/**\n * Shared zero-cost gate for every event with no `sensitive(...)` fields — a\n * single frozen reference the builder hands back for non-sensitive events, so\n * the common path is one `Map` miss and an identity call, no allocation. This\n * is the \"by default, return the event\" half of the prebuilt per-event gate.\n *\n * @internal\n */\nexport const IDENTITY_GATE: EventGate = (event) => event;\n\n/**\n * Prebuild a read gate for a sensitive event, capturing its field list and the\n * disclosure predicate once at build time. The returned closure defers to\n * {@link pii_gate} with the reading actor supplied per call:\n *\n * - `predicate = null` (the actor-less `query` surfaces, or a state that never\n *   declared `.discloses`) → default-deny: declared fields come back\n *   {@link REDACTED} (or {@link SHREDDED} once the pii column is forgotten).\n * - `predicate` set + an authorized actor → plaintext merged into `data`.\n *\n * Either way the isolated `pii` sidecar is dropped. The builder stores one gate\n * per sensitive event (per state for the load path; predicate-less for the\n * query path); non-sensitive events fall back to {@link IDENTITY_GATE}.\n *\n * @internal\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 *\n * @internal\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. `build_handle` / `build_handle_batch`\n  // filter on `fields.length > 0` before invocation.\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 * @packageDocumentation\n * @module act/types\n * Barrel file for Act Framework core types.\n *\n * Re-exports all major type definitions for actions, errors, ports, reactions, registries, and schemas.\n * Also defines common environment and log level types/constants for configuration and logging.\n *\n * @remarks\n * Import from this module to access all core framework types in one place.\n */\nexport type * from \"./action.js\";\nexport type * from \"./audit.js\";\nexport * from \"./errors.js\";\nexport type * from \"./ports.js\";\nexport type * from \"./reaction.js\";\nexport type * from \"./registry.js\";\nexport * from \"./schemas.js\";\n\n/**\n * Supported runtime environments for the framework.\n * - `development`: Local development\n * - `test`: Automated testing\n * - `staging`: Pre-production\n * - `production`: Live/production\n */\nexport const Environments = [\n  \"development\",\n  \"test\",\n  \"staging\",\n  \"production\",\n] as const;\n\n/**\n * Type representing a valid environment string.\n */\nexport type Environment = (typeof Environments)[number];\n\n/**\n * Supported log levels for framework logging.\n * - `fatal`, `error`, `warn`, `info`, `debug`, `trace`\n */\nexport const LogLevels = [\n  \"fatal\",\n  \"error\",\n  \"warn\",\n  \"info\",\n  \"debug\",\n  \"trace\",\n] as const;\n\n/**\n * Type representing a valid log level string.\n */\nexport type LogLevel = (typeof LogLevels)[number];\n","/**\n * @packageDocumentation\n * @module act/adapters\n * In-memory event store adapter for the Act Framework.\n *\n * This adapter implements the Store interface and is suitable for development, testing, and demonstration purposes.\n * All data is stored in memory and lost on process exit.\n *\n * @category Adapters\n */\n\nimport { DEFAULT_LANE, SNAP_EVENT, TOMBSTONE_EVENT } from \"../ports.js\";\nimport { ConcurrencyError } from \"../types/errors.js\";\nimport type {\n  BlockedLease,\n  Committed,\n  EventMeta,\n  Lease,\n  Message,\n  Query,\n  QueryStatsOptions,\n  QueryStreams,\n  QueryStreamsResult,\n  Schema,\n  Schemas,\n  Store,\n  StreamFilter,\n  StreamPosition,\n  StreamStats,\n  SubscribeInput,\n} from \"../types/index.js\";\nimport { sleep } from \"../utils.js\";\n\n/**\n * @internal\n * Represents an in-memory stream for event processing and leasing.\n */\nclass InMemoryStream {\n  readonly stream: string;\n  readonly source: string | undefined;\n  private _at = -1;\n  private _retry = -1;\n  private _blocked = false;\n  private _error = \"\";\n  private _leased_by: string | undefined = undefined;\n  private _leased_until: Date | undefined = undefined;\n  private _priority = 0;\n  private _lane: string = DEFAULT_LANE;\n  // Persisted next-visit time (#1090). When set and still in the future, the\n  // stream is held out of `claim` entirely — so a deferred reaction is not\n  // re-claimed (and `retry` is never bumped) until its due-time passes. Unlike\n  // in-process backoff, this is durable store state shared across workers.\n  private _deferred_at: number | undefined = undefined;\n  // Work mark (#1485): highest event id observed to resolve to this target.\n  // `undefined` means UNKNOWN — the row predates the mark, so `claim` falls\n  // back to the legacy has-work probe rather than treating it as \"no work\".\n  private _correlated_at: number | undefined = undefined;\n\n  constructor(\n    stream: string,\n    source: string | undefined,\n    priority = 0,\n    lane: string = DEFAULT_LANE\n  ) {\n    this.stream = stream;\n    this.source = source;\n    this._priority = priority;\n    this._lane = lane;\n  }\n\n  get priority() {\n    return this._priority;\n  }\n\n  get lane() {\n    return this._lane;\n  }\n\n  /** Replace on every subscribe — current builder config wins on restart. */\n  set lane(value: string) {\n    this._lane = value;\n  }\n\n  /**\n   * Bump the priority via {@link subscribe}: keeps the maximum across\n   * reactions so the highest-priority registrant wins.\n   */\n  bump_priority(priority: number) {\n    if (priority > this._priority) this._priority = priority;\n  }\n\n  get correlated_at() {\n    return this._correlated_at;\n  }\n\n  /**\n   * Raise the work mark via {@link subscribe}: keeps the maximum, for every\n   * value including zero and negatives, so a mark never regresses.\n   */\n  mark(correlated_at: number) {\n    if (\n      this._correlated_at === undefined ||\n      correlated_at > this._correlated_at\n    )\n      this._correlated_at = correlated_at;\n  }\n\n  /**\n   * Set the priority outright via {@link prioritize}: operator\n   * runtime override that ignores the build-time `max()` invariant.\n   */\n  set_priority(priority: number) {\n    this._priority = priority;\n  }\n\n  get is_available() {\n    return (\n      !this._blocked &&\n      (!this._leased_until || this._leased_until <= new Date()) &&\n      // A stream deferred to a future time is not claimable until due (#1090).\n      (!this._deferred_at || this._deferred_at <= Date.now())\n    );\n  }\n\n  /**\n   * Hold this stream out of `claim` until `deferred_at` (ms since epoch).\n   * Set by a deliberate `defer` outcome — not a failure, so retry/blocked\n   * state is untouched. Cleared by ack/block/reset/unblock.\n   */\n  defer(deferred_at: number) {\n    this._deferred_at = deferred_at;\n    // A defer is not a failure: reset retry so the redelivery after the\n    // due-time is a fresh attempt, never accumulating toward maxRetries.\n    this._retry = -1;\n  }\n\n  get at() {\n    return this._at;\n  }\n\n  get retry() {\n    return this._retry;\n  }\n\n  get blocked() {\n    return this._blocked;\n  }\n\n  get error() {\n    return this._error;\n  }\n\n  get leased_by() {\n    return this._leased_by;\n  }\n\n  get leased_until() {\n    return this._leased_until;\n  }\n\n  /** Persisted next-visit time (#1090/#1221), or undefined when no active defer. */\n  get deferred_at() {\n    return this._deferred_at;\n  }\n\n  /**\n   * Attempt to lease this stream for processing.\n   * @param lease - The lease request.\n   * @param millis - Lease duration in milliseconds.\n   * @returns The granted lease or undefined if blocked.\n   */\n  lease(lease: Lease, millis: number): Lease {\n    // The holder is recorded whatever the duration, matching both SQL\n    // adapters. `millis` governs only how long the lease stands: a\n    // zero-length one expires the instant it is granted, so the stream is\n    // immediately re-claimable — but `ack` is gated on the holder, and a\n    // lease granted with no holder recorded is one whose every ack is\n    // dropped, leaving the watermark parked and every event redelivered.\n    this._leased_by = lease.by;\n    this._leased_until = new Date(Date.now() + millis);\n    this._retry = this._retry + 1;\n    return {\n      stream: this.stream,\n      source: this.source,\n      at: lease.at,\n      by: lease.by,\n      retry: this._retry,\n      lagging: lease.lagging,\n      lane: this._lane,\n    };\n  }\n\n  /**\n   * Finalize this stream's lease: ack (advance the watermark) or, when the\n   * lease carries a `due` marker, defer (persist the schedule, hold the\n   * watermark) — see {@link Store.ack}.\n   * @param lease - The lease request.\n   */\n  ack(lease: Lease) {\n    if (this._leased_by === lease.by) {\n      this._leased_by = undefined;\n      this._leased_until = undefined;\n      if (lease.due !== undefined) {\n        // Due marker: advance the watermark past the events handled this cycle\n        // (`lease.at`) AND schedule the re-visit, persisting the caller's\n        // retry — advance and defer are independent legs (#1278). Advancing\n        // means the succeeded prefix never re-runs on redelivery. An explicit\n        // defer passes `retry: -1` (a defer is not a failure); a backoff retry\n        // passes the climbing counter so it keeps accruing toward the block\n        // threshold across windows (#1262). Deferred entries are not part of\n        // ack's return value.\n        this._at = lease.at;\n        this._retry = lease.retry;\n        this._deferred_at = lease.due;\n        return undefined;\n      }\n      // A successful ack clears the retry budget and any pending defer.\n      this._retry = -1;\n      this._at = lease.at;\n      this._deferred_at = undefined;\n      return {\n        stream: this.stream,\n        source: this.source,\n        at: this._at,\n        by: lease.by,\n        retry: this._retry,\n        lagging: lease.lagging,\n        lane: this._lane,\n      };\n    }\n  }\n\n  /**\n   * Block a stream for processing after failing to process and reaching max retries with blocking enabled.\n   * @param lease - The lease request.\n   * @param error Blocked error message.\n   */\n  block(lease: Lease, error: string) {\n    // Skip already-blocked streams so a redundant block is a no-op, mirroring\n    // the SQL adapters' `WHERE ... AND blocked = false` guard (#1263). Without\n    // this, re-blocking returns the lease again and emits a spurious duplicate\n    // `blocked` lifecycle event that the durable stores suppress.\n    if (this._leased_by === lease.by && !this._blocked) {\n      this._blocked = true;\n      this._error = error;\n      // A blocked stream is poison; clear any pending defer (#1090).\n      this._deferred_at = undefined;\n      return {\n        stream: this.stream,\n        source: this.source,\n        at: this._at,\n        by: this._leased_by,\n        retry: this._retry,\n        error: this._error,\n        lagging: lease.lagging,\n        lane: this._lane,\n      };\n    }\n  }\n\n  /**\n   * Reset this stream's watermark and state for replay. The retry counter\n   * resets to -1 to match the constructor + ack() invariant (\"released\n   * stream\"); the next claim() bumps it to 0 (first attempt).\n   */\n  reset() {\n    this._at = -1;\n    this._retry = -1;\n    this._blocked = false;\n    this._error = \"\";\n    this._leased_by = undefined;\n    this._leased_until = undefined;\n    this._deferred_at = undefined;\n  }\n\n  /**\n   * Clear the blocked flag and lease bookkeeping without touching the\n   * watermark. Returns true if the stream was actually blocked (and is\n   * now flipped); false otherwise.\n   */\n  unblock(): boolean {\n    if (!this._blocked) return false;\n    this._blocked = false;\n    this._retry = -1;\n    this._error = \"\";\n    this._leased_by = undefined;\n    this._leased_until = undefined;\n    this._deferred_at = undefined;\n    return true;\n  }\n}\n\n/**\n * In-memory event store implementation.\n *\n * This is the default store used by Act when no other store is injected.\n * It stores all events in memory and is suitable for:\n * - Development and prototyping\n * - Unit and integration testing\n * - Demonstrations and examples\n *\n * **Not suitable for production** - all data is lost when the process exits.\n * Use {@link PostgresStore} for production deployments.\n *\n * The in-memory store provides:\n * - Full {@link Store} interface implementation\n * - Optimistic concurrency control\n * - Stream leasing for distributed processing simulation\n * - Snapshot support\n * - Fast performance (no I/O overhead)\n *\n * **`Store.notify` is intentionally not implemented.** The notify hook is a\n * cross-process wake-up signal — local commits already arm the drain via\n * `do()`. An in-memory store is single-process by definition, so there is\n * no remote writer to be notified of. The {@link Act} orchestrator\n * detects the absence and falls back to the existing debounce/poll path.\n *\n * @example Using in tests\n * ```typescript\n * import { store } from \"@rotorsoft/act\";\n *\n * describe(\"Counter\", () => {\n *   beforeEach(async () => {\n *     // Reset store between tests\n *     await store().seed();\n *   });\n *\n *   it(\"increments\", async () => {\n *     await app.do(\"increment\", target, { by: 5 });\n *     const snapshot = await app.load(Counter, \"counter-1\");\n *     expect(snapshot.state.count).toBe(5);\n *   });\n * });\n * ```\n *\n * @example Explicit instantiation\n * ```typescript\n * import { InMemoryStore } from \"@rotorsoft/act\";\n *\n * const testStore = new InMemoryStore();\n * await testStore.seed();\n *\n * // Use for specific test scenarios\n * await testStore.commit(\"test-stream\", events, meta);\n * ```\n *\n * @example Querying events\n * ```typescript\n * const events: any[] = [];\n * await store().query(\n *   (event) => events.push(event),\n *   { stream: \"test-stream\" }\n * );\n * console.log(`Found ${events.length} events`);\n * ```\n *\n * @see {@link Store} for the interface definition\n * @see {@link PostgresStore} for production use\n * @see {@link store} for injecting stores\n *\n * @category Adapters\n */\nexport class InMemoryStore implements Store {\n  // stored events\n  private _events: Committed<Schemas, keyof Schemas>[] = [];\n  // next event id — monotonic, never reused. Deletions (truncate, windowed\n  // prune) punch holes in the id sequence, so ids are NOT array indexes and\n  // NOT `_events.length`; they only stay sorted ascending in `_events`.\n  private _next_id = 0;\n  // stored stream positions and other metadata\n  private _streams: Map<string, InMemoryStream> = new Map();\n  /** Correlate checkpoint (#1484): how far the log has been READ. */\n  private _correlated_at = -1;\n  /**\n   * Per-correlator checkpoint and lease (#1532), keyed by correlator.\n   *\n   * Keyed rather than singular because correlators that look for different\n   * things read the log for different reasons: sharing one position lets a\n   * partial-behaviour worker inherit another's, and sharing one lease lets\n   * one starve the other. Callers that supply no correlator use\n   * `_correlated_at` instead, which is the pre-#1532 behaviour.\n   */\n  private _correlators = new Map<\n    string,\n    { at: number; by: string; until: number }\n  >();\n  // last committed version per stream — O(1) replacement for filter-on-commit\n  private _stream_versions: Map<string, number> = new Map();\n  // max non-snapshot event id per stream — drives the has-work probe in\n  // claim(): an O(1) lookup for a literal source, and the per-stream max\n  // that a pattern source scans, without touching the full event log.\n  private _max_event_id_by_stream: Map<string, number> = new Map();\n  // global max non-snapshot event id — fast pre-check for source-less streams in claim()\n  private _max_non_snap_event_id = -1;\n  // stream → (event_id → cloned sensitive payload). Two-level so `forget_pii`\n  // is O(1) — drop the inner Map for the stream and the wipe is done — mirroring\n  // the `DELETE WHERE stream = ?` scope that durable adapters get from their\n  // stream index. Entries exist only for events committed with a non-null\n  // `pii` field; absence means \"no PII\" (returned as `null` on load).\n  private _pii: Map<string, Map<number, Record<string, unknown>>> = new Map();\n\n  private _reset_indexes() {\n    this._events.length = 0;\n    this._next_id = 0;\n    this._correlated_at = -1;\n    this._stream_versions.clear();\n    this._max_event_id_by_stream.clear();\n    this._max_non_snap_event_id = -1;\n    this._pii.clear();\n  }\n\n  // First index whose event id is greater than `after`. `_events` stays\n  // sorted ascending by id (append-only commits; deletions preserve\n  // order), so id-bounded scans binary-search their start instead of\n  // assuming id === index — an invariant that truncation breaks.\n  private _first_index_after(after: number): number {\n    let lo = 0;\n    let hi = this._events.length;\n    while (lo < hi) {\n      const mid = (lo + hi) >>> 1;\n      if (this._events[mid].id > after) hi = mid;\n      else lo = mid + 1;\n    }\n    return lo;\n  }\n\n  // Attach the isolated PII payload (or null) to an event before handing it to\n  // a caller. Allocation-free for events without PII — by far the common case.\n  private _with_pii<E extends Schemas>(\n    e: Committed<E, keyof E>\n  ): Committed<E, keyof E> {\n    const pii = this._pii.get(e.stream)?.get(e.id);\n    return pii ? ({ ...e, pii } as Committed<E, keyof E>) : e;\n  }\n\n  /**\n   * Dispose of the store and clear all events.\n   * @returns Promise that resolves when disposal is complete.\n   */\n  async dispose() {\n    await sleep();\n    this._reset_indexes();\n  }\n\n  /**\n   * Seed the store with initial data (no-op for in-memory).\n   * @returns Promise that resolves when seeding is complete.\n   */\n  async seed() {\n    await sleep();\n  }\n\n  /**\n   * Drop all data from the store.\n   * @returns Promise that resolves when the store is cleared.\n   */\n  async drop() {\n    await sleep();\n    this._reset_indexes();\n    this._streams = new Map();\n  }\n\n  private in_query<E extends Schemas>(query: Query, e: Committed<E, keyof E>) {\n    if (query.stream) {\n      if (query.stream_exact) {\n        if (e.stream !== query.stream) return false;\n      } else if (!RegExp(query.stream).test(e.stream)) return false;\n    }\n    if (query.names && !query.names.includes(e.name as string)) return false;\n    if (query.correlation && e.meta?.correlation !== query.correlation)\n      return false;\n    if (e.name === SNAP_EVENT && !query.with_snaps) return false;\n    return true;\n  }\n\n  /**\n   * Query events in the store, optionally filtered by query options.\n   * @param callback - Function to call for each event.\n   * @param query - Optional query options.\n   * @returns The number of events processed.\n   */\n  async query<E extends Schemas>(\n    callback: (event: Committed<E, keyof E>) => void,\n    query?: Query\n  ) {\n    await sleep();\n    let count = 0;\n    // Snapshot resume floor: `with_snaps` requests a resume at the latest\n    // snapshot for an exact single stream, so pre-snapshot events aren't read.\n    // The orchestrator sets `with_snaps` only for an unbounded current-state\n    // load — it suppresses the flag under any `asOf` bound (RFC 1274) — so the\n    // store applies the floor whenever asked and never re-checks bounds. An\n    // explicit `after` is a separate resume point that wins. No snapshot → -1,\n    // i.e. a full scan. Forward starts at the snapshot; backward stops at it.\n    let floor_index = -1;\n    if (\n      query?.with_snaps &&\n      query.stream_exact &&\n      query.stream !== undefined &&\n      query.after === undefined\n    ) {\n      for (let j = this._events.length - 1; j >= 0; j--) {\n        const e = this._events[j];\n        if (e.stream === query.stream && e.name === SNAP_EVENT) {\n          floor_index = j;\n          break;\n        }\n      }\n    }\n    if (query?.backward) {\n      const floor_id = floor_index >= 0 ? this._events[floor_index].id : -1;\n      let i =\n        (query?.before !== undefined\n          ? this._first_index_after(query.before - 1)\n          : this._events.length) - 1;\n      while (i >= 0) {\n        const e = this._events[i--];\n        if (query && !this.in_query(query, e)) continue;\n        if (query?.created_before && e.created >= query.created_before)\n          continue;\n        if (query.after !== undefined && e.id <= query.after) break;\n        // Below the resume floor → every remaining (lower-id) event is too,\n        // so stop the DESC scan.\n        if (floor_id >= 0 && e.id < floor_id) break;\n        // `created` is not monotonic with `id` (restore preserves the\n        // source timestamps verbatim), so a failing time bound skips the\n        // event rather than terminating the scan — matching PG/SQLite,\n        // which treat `created` bounds as pure WHERE filters. Only the\n        // id-ordered `after` bound above may short-circuit.\n        if (query.created_after && e.created <= query.created_after) continue;\n        await Promise.resolve(\n          callback(this._with_pii(e as Committed<E, keyof E>))\n        );\n        count++;\n        if (query?.limit && count >= query.limit) break;\n      }\n    } else {\n      let i =\n        floor_index >= 0\n          ? floor_index\n          : this._first_index_after(query?.after ?? -1);\n      while (i < this._events.length) {\n        const e = this._events[i++];\n        if (query && !this.in_query(query, e)) continue;\n        if (query?.created_after && e.created <= query.created_after) continue;\n        if (query?.before !== undefined && e.id >= query.before) break;\n        // `created` is not monotonic with `id`, so a failing time bound\n        // skips the event rather than terminating the scan — matching\n        // PG/SQLite. Only the id-ordered `before` bound above may\n        // short-circuit.\n        if (query?.created_before && e.created >= query.created_before)\n          continue;\n        await Promise.resolve(\n          callback(this._with_pii(e as Committed<E, keyof E>))\n        );\n        count++;\n        if (query?.limit && count >= query.limit) break;\n      }\n    }\n    return count;\n  }\n\n  /**\n   * Commit one or more events to a stream.\n   * @param stream - The stream name.\n   * @param msgs - The events/messages to commit.\n   * @param meta - Event metadata.\n   * @param expectedVersion - Optional optimistic concurrency check.\n   * @returns The committed events with metadata.\n   * @throws ConcurrencyError if expectedVersion does not match.\n   */\n  async commit<E extends Schemas>(\n    stream: string,\n    msgs: Message<E, keyof E>[],\n    meta: EventMeta,\n    expectedVersion?: number\n  ) {\n    await sleep();\n    const current_version = this._stream_versions.get(stream) ?? -1;\n    if (\n      typeof expectedVersion === \"number\" &&\n      current_version !== expectedVersion\n    ) {\n      throw new ConcurrencyError(\n        stream,\n        current_version,\n        msgs as Message<Schemas, keyof Schemas>[],\n        expectedVersion\n      );\n    }\n\n    let version = current_version + 1;\n    let last_non_snap_id = -1;\n    const committed = msgs.map(({ name, data, pii }) => {\n      const c: Committed<E, keyof E> = {\n        id: this._next_id++,\n        stream,\n        version,\n        created: new Date(),\n        name,\n        data,\n        meta,\n      };\n      // The stored event is the pii-less view — `forget_pii` only has to\n      // drop the inner Map for the stream, never the event row. Mandatory\n      // clone on the pii payload defends against caller-side mutation.\n      this._events.push(c as Committed<Schemas, keyof Schemas>);\n      if (pii != null) {\n        let per_stream = this._pii.get(stream);\n        if (!per_stream) {\n          per_stream = new Map();\n          this._pii.set(stream, per_stream);\n        }\n        per_stream.set(c.id, structuredClone(pii) as Record<string, unknown>);\n      }\n      if (name !== SNAP_EVENT) last_non_snap_id = c.id;\n      version++;\n      return this._with_pii(c);\n    });\n    this._stream_versions.set(stream, version - 1);\n    if (last_non_snap_id >= 0) {\n      this._max_event_id_by_stream.set(stream, last_non_snap_id);\n      // commit always assigns a fresh id from the monotonic _next_id, so\n      // any non-snap commit strictly raises the global max.\n      this._max_non_snap_event_id = last_non_snap_id;\n    }\n    return committed;\n  }\n\n  /**\n   * Atomically discovers and leases streams for processing.\n   * Fuses poll + lease into a single operation.\n   * @param lagging - Max streams from lagging frontier.\n   * @param leading - Max streams from leading frontier.\n   * @param by - Lease holder identifier.\n   * @param millis - Lease duration in milliseconds.\n   * @returns Granted leases.\n   */\n  async claim(\n    lagging: number,\n    leading: number,\n    by: string,\n    millis: number,\n    lane?: string\n  ) {\n    await sleep();\n    // Eligibility is a pure subscription-row predicate (#1488). `claim`\n    // never looks at the event log: `correlate` records the highest event id\n    // that resolves to a target, and `at < correlated_at` is the whole\n    // question. The probe this replaced walked the event index once per\n    // eligible subscription, matching `source` literally or as a pattern —\n    // matching that now happens in correlate, when it decides what to mark.\n    //\n    // An unmarked row is not claimable, by definition (#1446): `undefined`\n    // means the row has never been correlated, not that it has no work.\n    const has_work = (s: InMemoryStream): boolean =>\n      s.correlated_at !== undefined && s.at < s.correlated_at;\n    const available = [...this._streams.values()].filter(\n      (s) =>\n        s.is_available && has_work(s) && (lane === undefined || s.lane === lane)\n    );\n    // Lagging frontier orders by priority DESC (higher first), then by\n    // watermark ASC (most-behind first). Mirrors the PG `claim()` SQL\n    // — see `libs/act-pg/PERFORMANCE.md` for the benchmark that\n    // motivated the priority dimension. A fairness reserve (ACT-1223)\n    // carves `fair` slots off the budget and fills them by pure watermark\n    // order (priority ignored) so a default-priority lagging stream can\n    // never be starved out of the frontier by sustained higher-priority\n    // load. With everyone at the same priority both slices order by `at`,\n    // so this is a behavioral no-op for existing workloads.\n    const fair = lagging >= 2 ? Math.max(1, Math.floor(lagging / 4)) : 0;\n    const by_priority = [...available].sort(\n      (a, b) => b.priority - a.priority || a.at - b.at\n    );\n    const priority_slice = by_priority.slice(0, lagging - fair);\n    const picked = new Set(priority_slice.map((s) => s.stream));\n    const fair_slice = [...available]\n      .sort((a, b) => a.at - b.at)\n      .filter((s) => !picked.has(s.stream))\n      .slice(0, fair);\n    const lag = [...priority_slice, ...fair_slice].map((s) => ({\n      stream: s.stream,\n      source: s.source,\n      at: s.at,\n      lagging: true,\n    }));\n    const lead = available\n      .sort((a, b) => b.at - a.at)\n      .slice(0, leading)\n      .map((s) => ({\n        stream: s.stream,\n        source: s.source,\n        at: s.at,\n        lagging: false,\n      }));\n    // deduplicate (a stream can appear in both frontiers)\n    const seen = new Set<string>();\n    const combined = [...lag, ...lead].filter((p) => {\n      if (seen.has(p.stream)) return false;\n      seen.add(p.stream);\n      return true;\n    });\n    // lease each atomically\n    return combined\n      .map((p) =>\n        this._streams.get(p.stream)?.lease({ ...p, by, retry: 0 }, millis)\n      )\n      .filter((l) => !!l);\n  }\n\n  /**\n   * Registers streams for event processing. When the same stream is\n   * resubscribed with a different priority, the **maximum** wins — so\n   * the highest-priority registered reaction sets the scheduling lane.\n   * Use {@link prioritize} for operator runtime overrides.\n   *\n   * @param streams - Streams to register with optional source + priority.\n   * @returns subscribed count and current max watermark.\n   */\n  async subscribe(\n    streams: SubscribeInput[],\n    correlated_at?: number,\n    correlator?: { key: string; by: string; millis: number }\n  ) {\n    await sleep();\n\n    // The correlate checkpoint is written by its own producer, in the call\n    // correlate already makes (#1484). Monotonic: a lower value is ignored.\n    //\n    // With a correlator the position and the lease are per-key (#1532); a key\n    // with no row yet inherits the shared value, so an upgrade does not\n    // re-read history.\n    let correlating: boolean | undefined;\n    /** This correlator's position, once known — always set when keyed. */\n    let keyed_at: number | undefined;\n    if (correlator) {\n      const now = Date.now();\n      const held = this._correlators.get(correlator.key);\n      // A key with no row yet inherits the shared position, so a new\n      // correlator does not re-read history.\n      const at = Math.max(held?.at ?? this._correlated_at, correlated_at ?? -1);\n      keyed_at = at;\n      if (!held || held.until < now || held.by === correlator.by) {\n        correlating = true;\n        this._correlators.set(correlator.key, {\n          at,\n          by: correlator.by,\n          // A non-positive `millis` releases outright rather than setting an\n          // expiry a hair in the future: a successor asking inside the same\n          // millisecond would otherwise still be refused.\n          until: correlator.millis > 0 ? now + correlator.millis : 0,\n        });\n      } else {\n        // Refused, which is only possible when a live holder exists — so the\n        // row is here to keep. The position still advances: this caller may\n        // already have scanned, and dropping how far it read would leave its\n        // marks ahead of its recorded position.\n        correlating = false;\n        held.at = at;\n      }\n      // The shared position tracks how far *any* correlator has read: the\n      // floor a brand-new key inherits, and what a caller reading without a\n      // correlator still sees.\n      if (correlated_at !== undefined && correlated_at > this._correlated_at)\n        this._correlated_at = correlated_at;\n    } else if (\n      correlated_at !== undefined &&\n      correlated_at > this._correlated_at\n    )\n      this._correlated_at = correlated_at;\n\n    let subscribed = 0;\n    for (const {\n      stream,\n      source,\n      priority = 0,\n      lane = DEFAULT_LANE,\n      correlated_at,\n    } of streams) {\n      const existing = this._streams.get(stream);\n      if (existing) {\n        // The lane rides the priority max (#1599): compared before the\n        // bump, so a subscribe at or above the stored priority sets the\n        // lane and one below leaves it alone. A caller that has forgotten\n        // what a stream carries — an evicted LRU record, a fresh process —\n        // then cannot re-lane it by resolving to it at a lower priority.\n        if (priority >= existing.priority) existing.lane = lane;\n        existing.bump_priority(priority);\n        if (correlated_at !== undefined) existing.mark(correlated_at);\n      } else {\n        const created = new InMemoryStream(stream, source, priority, lane);\n        if (correlated_at !== undefined) created.mark(correlated_at);\n        this._streams.set(stream, created);\n        subscribed++;\n      }\n    }\n    let watermark = -1;\n    for (const s of this._streams.values()) {\n      if (s.at > watermark) watermark = s.at;\n    }\n    return {\n      subscribed,\n      watermark,\n      correlated_at: keyed_at ?? this._correlated_at,\n      ...(correlating === undefined ? {} : { correlating }),\n    };\n  }\n\n  /**\n   * Acknowledge completion of processing for leased streams.\n   * @param leases - Leases to acknowledge, including last processed watermark and lease holder.\n   */\n  async ack(leases: Lease[]) {\n    await sleep();\n    // Acks and defer schedules land in one synchronous pass — the\n    // in-memory equivalent of the single-transaction contract on\n    // {@link Store.ack}: no await between entries, so a caller\n    // never observes a cycle's acks without its schedules. `due`-carrying\n    // entries defer (and return undefined), the rest ack.\n    return leases\n      .map((l) => this._streams.get(l.stream)?.ack(l))\n      .filter((l) => !!l);\n  }\n\n  /**\n   * Block a stream for processing after failing to process and reaching max retries with blocking enabled.\n   * @param leases - Leases to block, including lease holder and last error message.\n   * @returns Blocked leases.\n   */\n  async block(leases: BlockedLease[]) {\n    await sleep();\n    return leases\n      .map((l) => this._streams.get(l.stream)?.block(l, l.error))\n      .filter((l) => !!l);\n  }\n\n  /**\n   * Hold the matched streams out of {@link claim} until `deferred_at`\n   * (ms since epoch) — see {@link Store.defer}. Accepts an explicit list\n   * of names or a {@link StreamFilter}, mirroring {@link reset}/{@link unblock}.\n   * Persisted store state (unlike in-process backoff), so the skip is honored\n   * by every competing worker. Unknown names are silently skipped.\n   *\n   * @returns Count of streams whose `deferred_at` was set.\n   */\n  async defer(input: string[] | StreamFilter, deferred_at: number) {\n    await sleep();\n    let count = 0;\n    if (Array.isArray(input)) {\n      // De-dup the array so a repeated name counts once, matching PG's\n      // set-based `WHERE stream = ANY(...)` (#1360).\n      for (const name of new Set(input)) {\n        const s = this._streams.get(name);\n        if (s) {\n          s.defer(deferred_at);\n          count++;\n        }\n      }\n    } else {\n      const matches = this._filter_predicate(input);\n      for (const s of this._streams.values()) {\n        if (matches(s)) {\n          s.defer(deferred_at);\n          count++;\n        }\n      }\n    }\n    return count;\n  }\n\n  /**\n   * Build a predicate from a {@link StreamFilter}. Compiled regexes are\n   * cached in the closure so callers can apply it across the streams\n   * map without re-compiling per iteration.\n   */\n  private _filter_predicate(\n    filter: StreamFilter\n  ): (s: InMemoryStream) => boolean {\n    const stream_re =\n      filter.stream && !filter.stream_exact\n        ? new RegExp(filter.stream)\n        : undefined;\n    const source_re =\n      filter.source && !filter.source_exact\n        ? new RegExp(filter.source)\n        : undefined;\n    return (s) => {\n      if (filter.stream !== undefined) {\n        if (\n          filter.stream_exact\n            ? s.stream !== filter.stream\n            : !stream_re!.test(s.stream)\n        )\n          return false;\n      }\n      if (filter.source !== undefined) {\n        if (s.source === undefined) return false;\n        if (\n          filter.source_exact\n            ? s.source !== filter.source\n            : !source_re!.test(s.source)\n        )\n          return false;\n      }\n      if (filter.blocked !== undefined && s.blocked !== filter.blocked)\n        return false;\n      if (filter.lane !== undefined && s.lane !== filter.lane) return false;\n      return true;\n    };\n  }\n\n  /**\n   * Reset watermarks to -1, clearing retry, blocked, error, and lease\n   * state so the matched streams can be replayed from the beginning.\n   * Accepts either an explicit list of names or a {@link StreamFilter}.\n   *\n   * @param input - Stream names or a filter selecting the streams to reset.\n   * @returns Count of streams that were actually reset.\n   */\n  async reset(input: string[] | StreamFilter) {\n    await sleep();\n    let count = 0;\n    if (Array.isArray(input)) {\n      // De-dup the array so a repeated name counts once, matching PG's\n      // set-based `WHERE stream = ANY(...)` (#1360).\n      for (const name of new Set(input)) {\n        const s = this._streams.get(name);\n        if (s) {\n          s.reset();\n          count++;\n        }\n      }\n    } else {\n      const matches = this._filter_predicate(input);\n      for (const s of this._streams.values()) {\n        if (matches(s)) {\n          s.reset();\n          count++;\n        }\n      }\n    }\n    return count;\n  }\n\n  /**\n   * Clear the blocked flag (and retry / error / lease) on the matched\n   * streams without touching the watermark. Streams that aren't blocked\n   * at call time are silently skipped. Accepts either an explicit list\n   * of names or a {@link StreamFilter}. The filter form always restricts\n   * to blocked streams — passing `blocked: false` matches nothing.\n   * See {@link Store.unblock}.\n   *\n   * @param input - Stream names or a filter selecting the streams to unblock.\n   * @returns Count of streams that were actually flipped (were blocked).\n   */\n  /**\n   * Wipe the sensitive-data payload for every event on the stream — see\n   * {@link Store.forget_pii}. O(1) drop of the stream's inner Map; the size of\n   * that Map is the count of events that had PII. Idempotent: a second call\n   * finds no inner Map and returns `0`.\n   *\n   * @param stream - Target stream.\n   * @returns Count of events whose isolated PII payload was deleted.\n   */\n  async forget_pii(stream: string): Promise<number> {\n    await sleep();\n    const count = this._pii.get(stream)?.size ?? 0;\n    this._pii.delete(stream);\n    return count;\n  }\n\n  async unblock(input: string[] | StreamFilter) {\n    await sleep();\n    let count = 0;\n    if (Array.isArray(input)) {\n      for (const name of input) {\n        const s = this._streams.get(name);\n        if (s?.unblock()) count++;\n      }\n    } else {\n      // Filter form: always restrict to blocked streams. An explicit\n      // `blocked: false` in the filter is silently overridden — there\n      // is no use case for \"unblock unblocked streams.\"\n      const matches = this._filter_predicate({ ...input, blocked: true });\n      for (const s of this._streams.values()) {\n        if (matches(s) && s.unblock()) count++;\n      }\n    }\n    return count;\n  }\n\n  /**\n   * Bulk-update priority of streams matching `filter`. Mirrors\n   * {@link query_streams}'s filter semantics — see {@link Store.prioritize}.\n   * Unlike {@link subscribe} (which keeps `max()` of registered\n   * priorities), this sets the priority outright — operator override\n   * for the build-time scheduling policy.\n   *\n   * @returns Count of streams whose priority changed.\n   */\n  async prioritize(filter: StreamFilter, priority: number) {\n    await sleep();\n    const matches = this._filter_predicate(filter);\n    let count = 0;\n    for (const s of this._streams.values()) {\n      if (!matches(s)) continue;\n      if (s.priority !== priority) {\n        s.set_priority(priority);\n        count++;\n      }\n    }\n    return count;\n  }\n\n  /**\n   * Streams registered subscription positions to the callback, ordered by\n   * stream name. Returns the highest event id in the store and the count\n   * of positions emitted.\n   */\n  async query_streams(\n    callback: (position: StreamPosition) => void,\n    query?: QueryStreams\n  ): Promise<QueryStreamsResult> {\n    await sleep();\n    const limit = query?.limit ?? 100;\n    const after = query?.after;\n    const blocked = query?.blocked;\n    const source_matches = query?.source_matches;\n    const stream_re =\n      query?.stream && !query.stream_exact\n        ? new RegExp(query.stream)\n        : undefined;\n    const source_re =\n      query?.source && !query.source_exact\n        ? new RegExp(query.source)\n        : undefined;\n    // Reverse-match: a stream qualifies when its stored `source` pattern\n    // matches at least one of the requested names. Patterns are compiled\n    // once and cached — many subscriptions share one source pattern.\n    const reverse_cache = new Map<string, RegExp>();\n    const reverse_match = (source: string): boolean => {\n      let re = reverse_cache.get(source);\n      if (!re) {\n        re = new RegExp(source);\n        reverse_cache.set(source, re);\n      }\n      return source_matches!.some((name) => re!.test(name));\n    };\n\n    // Order by stream name so `after`/`limit` keyset-paginate\n    // deterministically. The sort MUST agree with the `after` cursor below\n    // (JS `<=`, i.e. UTF-16 code-unit order) — `localeCompare` disagrees\n    // with `<=` on mixed-case/accented names (`B`=66 < `a`=97 by code unit,\n    // but `a` < `B` by locale), which let the cursor skip streams the sort\n    // placed after it (#1375, the `query_streams` twin of #1357).\n    // The default `Array.sort()` comparator IS code-unit order, so it\n    // matches `<=` exactly — and PG/SQLite, which paginate under their\n    // binary collation. Sorting the keys (rather than comparing values)\n    // keeps that default in play.\n    const sorted = [...this._streams.keys()]\n      .sort()\n      .map((stream) => this._streams.get(stream) as InMemoryStream);\n\n    let count = 0;\n    for (const s of sorted) {\n      if (after !== undefined && s.stream <= after) continue;\n      if (query?.stream !== undefined) {\n        if (\n          query.stream_exact\n            ? s.stream !== query.stream\n            : !stream_re!.test(s.stream)\n        )\n          continue;\n      }\n      if (query?.source !== undefined) {\n        if (s.source === undefined) continue;\n        if (\n          query.source_exact\n            ? s.source !== query.source\n            : !source_re!.test(s.source)\n        )\n          continue;\n      }\n      if (source_matches !== undefined) {\n        // Absent/empty source = no source constraint = consumes from\n        // every stream, so it matches any requested name. Only a\n        // present source that matches none of them is excluded.\n        if (s.source && !reverse_match(s.source)) continue;\n      }\n      if (blocked !== undefined && s.blocked !== blocked) continue;\n      if (query?.lane !== undefined && s.lane !== query.lane) continue;\n      // Checked before emitting, not after: a bound applied afterwards\n      // lets `limit: 0` through as exactly one row, where both SQL\n      // adapters return none.\n      if (count >= limit) break;\n      callback({\n        stream: s.stream,\n        source: s.source,\n        at: s.at,\n        retry: s.retry,\n        blocked: s.blocked,\n        error: s.error,\n        priority: s.priority,\n        leased_by: s.leased_by,\n        leased_until: s.leased_until,\n        lane: s.lane,\n        deferred_at: s.deferred_at,\n        correlated_at: s.correlated_at,\n      });\n      count++;\n    }\n    return { maxEventId: this._events.at(-1)?.id ?? -1, count };\n  }\n\n  /**\n   * Per-stream aggregated stats — see {@link Store.query_stats}.\n   *\n   * Single forward scan over the in-memory event list, accumulating per\n   * stream. The \"cheap heads\" cost tier from durable adapters doesn't\n   * apply here (InMemory has no indexes); correctness is the goal, perf\n   * is a non-issue.\n   *\n   * Scope rules:\n   * - Array `input` — explicit stream names, regardless of subscription.\n   * - Filter `input` — `stream`/`stream_exact` match against event-bearing\n   *   stream names; `source`/`source_exact`/`blocked` require a\n   *   corresponding subscription in `_streams` (those are subscription\n   *   concepts, not event concepts). Empty filter `{}` matches every\n   *   event-bearing stream.\n   */\n  async query_stats<E extends Schemas>(\n    input: string[] | Pick<StreamFilter, \"stream\" | \"stream_exact\">,\n    options?: QueryStatsOptions<E>\n  ): Promise<Map<string, StreamStats<E>>> {\n    await sleep();\n    const exclude = new Set<string>(options?.exclude ?? []);\n    const want_tail = options?.tail ?? false;\n    const want_count = options?.count ?? false;\n    const want_names = options?.names ?? false;\n    const before = options?.before;\n    const after = options?.after;\n    const limit = options?.limit;\n\n    // Pre-compile per-stream scope predicate, cached as we go so each\n    // distinct stream evaluates the regex once.\n    const array_targets = Array.isArray(input) ? new Set(input) : null;\n    const filter = Array.isArray(input) ? null : input;\n    const stream_re =\n      filter?.stream && !filter.stream_exact\n        ? new RegExp(filter.stream)\n        : undefined;\n\n    const scope_cache = new Map<string, boolean>();\n    const in_scope = (stream: string): boolean => {\n      const cached = scope_cache.get(stream);\n      if (cached !== undefined) return cached;\n      let ok = true;\n      if (array_targets) {\n        ok = array_targets.has(stream);\n      } else if (filter?.stream !== undefined) {\n        ok = filter.stream_exact\n          ? stream === filter.stream\n          : // stream_re set when stream is regex\n            stream_re!.test(stream);\n      }\n      scope_cache.set(stream, ok);\n      return ok;\n    };\n\n    type Acc = {\n      head: Committed<Schemas, keyof Schemas>;\n      tail?: Committed<Schemas, keyof Schemas>;\n      count: number;\n      names?: Record<string, number>;\n    };\n    const acc = new Map<string, Acc>();\n    for (const e of this._events) {\n      if (before !== undefined && e.id >= before) continue;\n      if (!in_scope(e.stream)) continue;\n      if (exclude.has(e.name as string)) continue;\n      let a = acc.get(e.stream);\n      if (!a) {\n        a = { head: e, count: 0 };\n        if (want_tail) a.tail = e;\n        if (want_names) a.names = {};\n        acc.set(e.stream, a);\n      }\n      a.head = e;\n      a.count++;\n      if (want_names) {\n        const n = String(e.name);\n        // a.names initialized above when want_names\n        a.names![n] = (a.names![n] ?? 0) + 1;\n      }\n    }\n\n    // Order by stream name so `after`/`limit` keyset-paginate\n    // deterministically. The sort MUST agree with the `after` cursor below\n    // (JS `<=`, i.e. UTF-16 code-unit order) — `localeCompare` disagrees with\n    // `<=` on mixed-case/accented names (`B`=66 < `a`=97 by code unit, but\n    // `a` < `B` by locale), which would let the cursor skip streams the sort\n    // placed after it (#1357). The default `Array.sort()` comparator IS\n    // code-unit order, so it matches `<=` exactly — and PG/SQLite, which\n    // paginate `query_stats` under their binary collation.\n    const ordered = [...acc.keys()].sort();\n    const out = new Map<string, StreamStats<E>>();\n    for (const stream of ordered) {\n      // Before the row, not after it — `limit: 0` means none.\n      if (limit !== undefined && out.size >= limit) break;\n      if (after !== undefined && stream <= after) continue;\n      const a = acc.get(stream)!;\n      const stats: {\n        head: Committed<Schemas, keyof Schemas>;\n        tail?: Committed<Schemas, keyof Schemas>;\n        count?: number;\n        names?: Record<string, number>;\n      } = { head: a.head };\n      if (want_tail) stats.tail = a.tail;\n      if (want_count) stats.count = a.count;\n      if (want_names) stats.names = a.names;\n      out.set(stream, stats as StreamStats<E>);\n    }\n    return out;\n  }\n\n  /**\n   * Atomically truncates streams and seeds each with a snapshot or tombstone.\n   * Windowed targets (`before` set) prune the prefix below the closest safe\n   * `__snapshot__` instead — no seed, subscriptions untouched, no-op when no\n   * snapshot qualifies.\n   * @param targets - Streams to truncate with optional snapshot state and meta,\n   *   or a `before`/`max_id` boundary for a windowed prefix delete.\n   * @returns Map keyed by stream name, each entry with `deleted` count and `committed` event.\n   */\n  async truncate(\n    targets: Array<{\n      stream: string;\n      snapshot?: Schema;\n      meta?: EventMeta;\n      before?: Date;\n      max_id?: number;\n    }>\n  ) {\n    await sleep();\n    const result = new Map<\n      string,\n      {\n        deleted: number;\n        committed: Committed<Schemas, keyof Schemas>;\n        before?: Date;\n      }\n    >();\n\n    // Windowed targets: pure prefix delete behind the closest safe snapshot.\n    const windowed = targets.filter((t) => t.before !== undefined);\n    if (windowed.length) {\n      const drop = new Set<number>();\n      for (const { stream, before, max_id } of windowed) {\n        let boundary: Committed<Schemas, keyof Schemas> | undefined;\n        for (const e of this._events) {\n          if (\n            e.stream === stream &&\n            e.name === SNAP_EVENT &&\n            e.created < before! &&\n            (max_id === undefined || e.id <= max_id) &&\n            (!boundary || e.id > boundary.id)\n          )\n            boundary = e;\n        }\n        if (!boundary) continue; // no qualifying snapshot → no-op\n        let deleted = 0;\n        for (const e of this._events) {\n          if (e.stream === stream && e.id < boundary.id) {\n            drop.add(e.id);\n            this._pii.get(stream)?.delete(e.id);\n            deleted++;\n          }\n        }\n        result.set(stream, { deleted, committed: boundary, before });\n      }\n      if (drop.size) this._events = this._events.filter((e) => !drop.has(e.id));\n    }\n\n    const full = targets.filter((t) => t.before === undefined);\n    // Count per-stream deletions\n    const deleted_counts = new Map<string, number>();\n    const stream_set = new Set(full.map((t) => t.stream));\n    for (const e of this._events) {\n      if (stream_set.has(e.stream)) {\n        deleted_counts.set(e.stream, (deleted_counts.get(e.stream) ?? 0) + 1);\n      }\n    }\n    this._events = this._events.filter((e) => !stream_set.has(e.stream));\n    // Subscriptions are deliberately untouched, for restart *and* retire\n    // targets alike — see the note in truncate's contract. A tombstoned\n    // stream's subscription is inert, and reaping it is maintenance that\n    // `seed()` performs (#1527).\n    for (const stream of stream_set) {\n      this._stream_versions.delete(stream);\n      this._max_event_id_by_stream.delete(stream);\n      // The pii payloads die with the event rows, matching the durable\n      // adapters' `DELETE WHERE stream = ?` scope.\n      this._pii.delete(stream);\n    }\n    for (const { stream, snapshot, meta } of full) {\n      const event: Committed<Schemas, keyof Schemas> = {\n        id: this._next_id++,\n        stream,\n        version: 0,\n        created: new Date(),\n        name: snapshot !== undefined ? SNAP_EVENT : TOMBSTONE_EVENT,\n        data: snapshot ?? {},\n        meta: meta ?? { correlation: \"\", causation: {} },\n      };\n      this._events.push(event);\n      this._stream_versions.set(stream, 0);\n      if (event.name !== SNAP_EVENT) {\n        this._max_event_id_by_stream.set(stream, event.id);\n      }\n      result.set(stream, {\n        deleted: deleted_counts.get(stream) ?? 0,\n        committed: event,\n      });\n    }\n    // Recompute global max from the per-stream index — deletions may have\n    // dropped the previous max, while new tombstones may have raised it.\n    let max = -1;\n    for (const id of this._max_event_id_by_stream.values())\n      if (id > max) max = id;\n    this._max_non_snap_event_id = max;\n    return result;\n  }\n\n  /**\n   * Atomically wipe-and-rebuild the store under an in-process snapshot.\n   *\n   * Captures every index state up front, clears it, then hands the\n   * orchestrator a per-event insert `callback` via the driver. Any\n   * throw inside the driver restores the snapshot, leaving the store\n   * byte-for-byte unchanged from the operator's perspective.\n   *\n   * `id`s are reassigned `0..N-1` as events arrive (dense — the\n   * monotonic id counter restarts at 0 for the rebuild). `created` is\n   * preserved verbatim from the source.\n   */\n  async restore(\n    driver: (\n      callback: (event: Committed<Schemas, keyof Schemas>) => Promise<number>\n    ) => Promise<void>\n  ): Promise<void> {\n    await sleep();\n    // Snapshot every index so we can roll back on throw.\n    const prev_events = this._events;\n    const prev_next_id = this._next_id;\n    const prev_streams = this._streams;\n    const prev_stream_versions = this._stream_versions;\n    const prev_max_event_id_by_stream = this._max_event_id_by_stream;\n    const prev_max_non_snap_event_id = this._max_non_snap_event_id;\n    const prev_pii = this._pii;\n    // Swap in fresh state for the duration of the rebuild.\n    this._events = [];\n    this._next_id = 0;\n    this._streams = new Map();\n    this._stream_versions = new Map();\n    this._max_event_id_by_stream = new Map();\n    this._max_non_snap_event_id = -1;\n    this._pii = new Map();\n    try {\n      await driver(async (event) => {\n        const id = this._next_id++;\n        // Split `pii` out of the stored row into the isolated `_pii` map,\n        // mirroring `commit`. The stored event is the pii-less view so\n        // `forget_pii` — which only drops the `_pii` entry — actually\n        // erases restored PII (durable adapters restore into their\n        // isolated column for the same reason).\n        const { pii, ...rest } = event;\n        const committed: Committed<Schemas, keyof Schemas> = { ...rest, id };\n        this._events.push(committed);\n        if (pii != null) {\n          let per_stream = this._pii.get(event.stream);\n          if (!per_stream) {\n            per_stream = new Map();\n            this._pii.set(event.stream, per_stream);\n          }\n          per_stream.set(id, structuredClone(pii) as Record<string, unknown>);\n        }\n        // Last event per stream wins for the version watermark — the\n        // source is expected to be in commit order, so this is also\n        // the highest version. Out-of-order sources get last-wins,\n        // matching the legacy raw-SQL restore.\n        this._stream_versions.set(event.stream, event.version);\n        if (event.name !== SNAP_EVENT) {\n          this._max_event_id_by_stream.set(event.stream, id);\n          this._max_non_snap_event_id = id;\n        }\n        return id;\n      });\n    } catch (err) {\n      // Roll back to the captured snapshot — every index restored\n      // exactly as it was before the call started.\n      this._events = prev_events;\n      this._next_id = prev_next_id;\n      this._streams = prev_streams;\n      this._stream_versions = prev_stream_versions;\n      this._max_event_id_by_stream = prev_max_event_id_by_stream;\n      this._max_non_snap_event_id = prev_max_non_snap_event_id;\n      this._pii = prev_pii;\n      throw err;\n    }\n  }\n}\n","import type { Disposer } from \"./types/index.js\";\n\n/**\n * The shape {@link register_weak_disposer} needs from a `WeakRef`. Declared\n * structurally so tests can hand in a stub that reports its target as\n * collected — real garbage collection is not schedulable, and a guarantee\n * about releasing memory deserves a deterministic test.\n */\nexport type RefLike<T extends object> = { deref: () => T | undefined };\n\n/**\n * A registered cleanup function, optionally tied to the lifetime of the\n * object it cleans up. `ref` present means \"run this only while its target\n * is still reachable\" — the entry holds no strong reference to that target,\n * so registering never keeps it alive. The target is handed back to `run`,\n * so a weak disposer never has to re-check what the registry just proved.\n */\ntype Entry = {\n  readonly run: (target: never) => Promise<void>;\n  readonly ref?: RefLike<object>;\n};\n\n/** Registered cleanup functions, executed in reverse order during shutdown. */\nconst entries: Entry[] = [];\n\n/**\n * Drop entries whose target has been collected.\n *\n * Called on every registration so the registry stays proportional to the\n * live objects rather than to every object ever built. That matters for apps\n * that mint short-lived Acts — one per tenant, per request, per test — where\n * the registry would otherwise grow without bound for the process lifetime\n * (#1441).\n */\nconst prune = (): void => {\n  for (let i = entries.length - 1; i >= 0; i--) {\n    const { ref } = entries[i];\n    if (ref && !ref.deref()) entries.splice(i, 1);\n  }\n};\n\n/** Register a cleanup function that runs unconditionally at teardown. */\nexport const register_disposer = (run: Disposer): void => {\n  prune();\n  entries.push({ run });\n};\n\n/**\n * Register a cleanup function bound to `ref`'s target, held weakly.\n *\n * The registry never retains the target, so an object that becomes\n * unreachable is collectable whether or not it was cleaned up first, and its\n * entry is skipped at teardown — there is nothing left to clean up.\n */\nexport const register_weak_disposer = <T extends object>(\n  ref: RefLike<T>,\n  run: (target: T) => Promise<void>\n): void => {\n  prune();\n  entries.push({\n    run: run as (target: never) => Promise<void>,\n    ref: ref as RefLike<object>,\n  });\n};\n\n/**\n * Run every live disposer in reverse registration order, sequentially, so a\n * disposer can rely on later-registered ones having already finished.\n *\n * Registrations are left in place, so a second teardown call re-runs them,\n * exactly as before this registry learned about weak entries.\n */\nexport const run_disposers = async (): Promise<void> => {\n  for (const { run, ref } of [...entries].reverse()) {\n    if (!ref) {\n      await (run as Disposer)();\n      continue;\n    }\n    const target = ref.deref();\n    if (target) await (run as (t: object) => Promise<void>)(target);\n  }\n};\n","/**\n * @module scoped\n * @category Internal\n *\n * Ambient execution context — every `AsyncLocalStorage` the framework owns\n * lives here, and so does every operation on one. No other module calls\n * `.run()` or `.getStore()`; they ask for a runner or a reader instead, so\n * this file is the single place to look at the abstraction.\n *\n * Two contexts:\n *\n * - **ports** — the active Act's store/cache bag, so `store()` / `cache()`\n *   resolve per-Act rather than per-process (ACT-501). Installed by the\n *   orchestrator via {@link make_run_scoped}, read by the port singletons\n *   via {@link current_ports}.\n * - **reaction** — the event a handler is processing, so a dispatch made\n *   anywhere inside that handler can thread `reactingTo` whichever `IAct`\n *   reference made the call (#1541). Installed via {@link run_reacting},\n *   read at the orchestrator boundary via {@link current_reacting}.\n *\n * Keeping the mechanics here keeps ambient state out of `internal/`, whose\n * modules are stateless implementations that receive what they need.\n *\n * @internal\n */\n\nimport { AsyncLocalStorage } from \"node:async_hooks\";\nimport type {\n  Actor,\n  Cache,\n  Committed,\n  IAct,\n  Schemas,\n  Store,\n} from \"./types/index.js\";\n\n/** Per-Act ports bag (ACT-501). Both required together — a shared cache across stores would collide on stream keys. */\nexport type Scoped = {\n  readonly store: Store;\n  readonly cache: Cache;\n};\n\n/**\n * What an Act actually installs in its frame: the ports a caller passed,\n * plus per-Act settings that runtime code has to read from the *running*\n * Act rather than from whatever closure it was built in.\n *\n * `autoclose_window` is here because the autoclose reactions are\n * synthesized once into the shared registry and handed by reference to\n * every Act built from that builder, so a window captured at synthesis is\n * the first tenant's window for everyone (#1615). The frame is per-Act, so\n * reading it here is what makes the setting per-Act too.\n *\n * Wider than {@link Scoped} on purpose: `Scoped` types what a caller\n * *passes* through `ActOptions.scoped` and is public; this is what the\n * orchestrator *installs* and is not.\n *\n * @internal\n */\nexport type ActFrame = Scoped & {\n  readonly autoclose_window?: {\n    readonly start: number;\n    readonly end: number;\n    readonly timeZone: string;\n  };\n};\n\n/**\n * AsyncLocalStorage carrying the active Act's ports.\n *\n * Exported for in-repo tooling that measures the context itself (the\n * scope-overhead bench). NOT public: `ports.ts` no longer re-exports it and\n * `index.ts` reaches this module only for the `Scoped` type, so it is not\n * importable from the package. Everything else uses the helpers below.\n */\nexport const scoped = new AsyncLocalStorage<ActFrame>();\n\n/**\n * The reaction currently running, as a box the handler can empty.\n *\n * A frame captured by work the handler started and did not await outlives the\n * handler and can never be unbound. The *frame* is unreclaimable, but the\n * *box inside it* is not: clearing `event` as the handler settles turns every\n * later read through that frame into \"no reaction\", without anyone having to\n * ask a second question (#1562).\n *\n * Not reachable from `index.ts`.\n */\ntype Reacting = { event: Committed<Schemas, string> | undefined };\n\nconst reacting = new AsyncLocalStorage<Reacting>();\n\n/**\n * Builds the runner an Act uses to enter its own port scope.\n *\n * Every Act gets a frame, including one built without `ActOptions.scoped` —\n * that one carries the singleton adapters (see `default_scope` in `ports.ts`).\n * Entering unconditionally is what makes an Act's ports its own: a runner that\n * collapsed to `fn()` for a singleton Act did not leave whatever frame it was\n * called from, so dispatching into a shared Act from inside a tenant's handler\n * resolved `store()` to that tenant and wrote the shared Act's events into the\n * tenant's log ([#1597](https://github.com/Rotorsoft/act-root/issues/1597)).\n *\n * @internal\n */\nexport function make_run_scoped(\n  bag: ActFrame\n): <T>(fn: () => Promise<T>) => Promise<T> {\n  return (fn) => scoped.run(bag, fn);\n}\n\n/**\n * The running Act's off-hours autoclose window, or `undefined` when it\n * declared none (or when read outside any Act).\n *\n * Read at resolution time rather than captured at synthesis: the autoclose\n * reactions belong to the shared registry, and only the frame knows which\n * Act is running them (#1615).\n *\n * @internal\n */\nexport function current_autoclose_window(): ActFrame[\"autoclose_window\"] {\n  return scoped.getStore()?.autoclose_window;\n}\n\n/**\n * The active Act's ports, or `undefined` outside any Act.\n *\n * Every Act runs in a frame, so this is `undefined` only for a call made\n * outside one — `store()` and `cache()` fall back to the singleton adapters\n * there, which is what a bare `store()` in application setup expects.\n *\n * @internal\n */\nexport function current_ports(): Scoped | undefined {\n  return scoped.getStore();\n}\n\n/**\n * Runs `fn` with `event` installed as the triggering-event context.\n *\n * Entered per payload rather than per lease: the context has to unwind with\n * the handler so it never reaches the drain cycle, and work a handler started\n * without awaiting has to resume into its own event's frame.\n *\n * @internal\n */\nexport function run_reacting<T>(\n  event: Committed<Schemas, string>,\n  fn: () => Promise<T>\n): Promise<T> {\n  const box: Reacting = { event };\n  return reacting.run(box, async () => {\n    try {\n      return await fn();\n    } finally {\n      // Anything still running keeps this frame; from here it reads empty.\n      box.event = undefined;\n    }\n  });\n}\n\n/**\n * The event being reacted to, or `undefined` outside a running handler —\n * including inside work that outlived one.\n *\n * @internal\n */\nexport function current_reacting(): Committed<Schemas, string> | undefined {\n  return reacting.getStore()?.event;\n}\n\n/**\n * Everything a reaction handler runs inside: the `IAct` facade it is handed\n * as its third argument, and the triggering-event context that every dispatch\n * made within it resolves — including one through a captured `app`.\n *\n * Built here rather than in the dispatcher so the dispatcher never has to\n * know how either half works; it receives this whole and calls it.\n *\n * @internal\n */\nexport type ReactionScope<\n  TEvents extends Schemas,\n  TActions extends Schemas,\n  TActor extends Actor = Actor,\n> = {\n  readonly app: IAct<TEvents, TActions, TActor>;\n  readonly run: <T>(\n    event: Committed<Schemas, string>,\n    fn: () => Promise<T>\n  ) => Promise<T>;\n};\n\n/**\n * Assembles the reaction scope from the orchestrator's bound `IAct` methods.\n *\n * @internal\n */\nexport function make_reaction_scope<\n  TEvents extends Schemas,\n  TActions extends Schemas,\n  TActor extends Actor = Actor,\n>(\n  app: IAct<TEvents, TActions, TActor>\n): ReactionScope<TEvents, TActions, TActor> {\n  return { app, run: run_reacting };\n}\n","import { ConsoleLogger } from \"./adapters/console-logger.js\";\nimport { InMemoryCache } from \"./adapters/in-memory-cache.js\";\nimport { InMemoryStore } from \"./adapters/in-memory-store.js\";\nimport { config } from \"./config.js\";\nimport { register_disposer, run_disposers } from \"./disposers.js\";\nimport { current_ports, type Scoped } from \"./scoped.js\";\nimport type {\n  Cache,\n  Disposable,\n  Disposer,\n  Logger,\n  Store,\n} from \"./types/index.js\";\n\n// `Scoped` is the type of the public `ActOptions.scoped` bag, so it stays\n// exported. The AsyncLocalStorage carrying it does not: it is a mechanism,\n// it was only ever reachable because `index.ts` star-exports this module,\n// and its own doc-comment already declared it internal.\nexport type { Scoped } from \"./scoped.js\";\n\n/**\n * Port/adapter infrastructure for the Act framework.\n *\n * All infrastructure concerns (logging, storage, caching) are managed as\n * singleton adapters injected via port functions. Each port follows the same\n * pattern: first call wins with a sensible default, optional adapter injection.\n *\n * - `log()` — structured logging (default: ConsoleLogger)\n * - `store()` — event persistence (default: InMemoryStore)\n * - `cache()` — state checkpoints (default: InMemoryCache)\n * - `dispose()` — register cleanup functions for graceful shutdown\n *\n * @module ports\n */\n\n/**\n * List of exit codes for process termination. Consumed by signal handlers\n * and {@link disposeAndExit}; not part of the user-facing surface.\n *\n * @internal\n */\nexport const ExitCodes = [\"ERROR\", \"EXIT\"] as const;\n\n/**\n * Type for allowed exit codes.\n *\n * - `\"ERROR\"` — abnormal termination (uncaught exception, unhandled rejection)\n * - `\"EXIT\"` — clean shutdown (SIGINT, SIGTERM, or manual trigger)\n *\n * @internal\n */\nexport type ExitCode = (typeof ExitCodes)[number];\n\n// ---------------------------------------------------------------------------\n// Port factory\n// ---------------------------------------------------------------------------\n\n/**\n * Factory function that creates or returns the injected adapter.\n * @internal\n */\ntype Injector<Port extends Disposable> = (adapter?: Port) => Port;\n\n/** Singleton adapter registry, keyed by injector function name. */\nconst adapters = new Map<string, Disposable>();\n\n/**\n * Creates a singleton port with optional adapter injection.\n *\n * The first call initializes the adapter (using the provided adapter or the\n * injector's default). Subsequent calls return the cached singleton. Adapters\n * are disposed in reverse registration order during {@link disposeAndExit}.\n *\n * @param injector - Named function that creates the default adapter\n * @returns Port function: call with no args to get the singleton, or pass an\n *          adapter on the first call to override the default\n *\n * @example\n * ```typescript\n * const store = port(function store(adapter?: Store) {\n *   return adapter || new InMemoryStore();\n * });\n * const s = store(); // InMemoryStore\n * ```\n */\nexport function port<Port extends Disposable>(injector: Injector<Port>) {\n  return (adapter?: Port): Port => {\n    if (!adapters.has(injector.name)) {\n      const injected = injector(adapter);\n      adapters.set(injector.name, injected);\n      // log() is now in adapters (or this IS the log port we just registered),\n      // so the recursive call resolves immediately. Routing through the logger\n      // means level gating (e.g. silenced in tests at fatal) takes effect.\n      log().info(`[act] + ${injector.name}:${injected.constructor.name}`);\n    }\n    return adapters.get(injector.name) as Port;\n  };\n}\n\n// ---------------------------------------------------------------------------\n// Ports: log, store, cache\n// ---------------------------------------------------------------------------\n\n/**\n * Gets or injects the singleton logger.\n *\n * By default, Act uses a built-in {@link ConsoleLogger} that emits JSON lines\n * in production (compatible with GCP, AWS CloudWatch, Datadog) and colorized\n * output in development — zero external dependencies.\n *\n * For pino, inject a `PinoLogger` from `@rotorsoft/act-pino` before building\n * your application.\n *\n * @param adapter - Optional logger implementation to inject\n * @returns The singleton logger instance\n *\n * @example Default console logger\n * ```typescript\n * import { log } from \"@rotorsoft/act\";\n * const logger = log();\n * logger.info(\"Application started\");\n * ```\n *\n * @example Injecting pino\n * ```typescript\n * import { log } from \"@rotorsoft/act\";\n * import { PinoLogger } from \"@rotorsoft/act-pino\";\n * log(new PinoLogger({ level: \"debug\", pretty: true }));\n * ```\n *\n * @see {@link Logger} for the interface contract\n * @see {@link ConsoleLogger} for the default implementation\n */\nexport const log = port(function log(adapter?: Logger) {\n  const cfg = config();\n  return (\n    adapter ||\n    new ConsoleLogger({\n      level: cfg.logLevel,\n      pretty: cfg.env !== \"production\",\n    })\n  );\n});\n\n/**\n * Gets or injects the singleton event store.\n *\n * By default, Act uses an {@link InMemoryStore} suitable for development and\n * testing. For production, inject a persistent store like `PostgresStore` from\n * `@rotorsoft/act-pg` before building your application.\n *\n * **Important:** Store injection must happen before creating any Act instances.\n * Once set, the store cannot be changed without restarting the application.\n *\n * @param adapter - Optional store implementation to inject\n * @returns The singleton store instance\n *\n * @example Default in-memory store\n * ```typescript\n * import { store } from \"@rotorsoft/act\";\n * const s = store();\n * ```\n *\n * @example Injecting PostgreSQL\n * ```typescript\n * import { store } from \"@rotorsoft/act\";\n * import { PostgresStore } from \"@rotorsoft/act-pg\";\n *\n * store(new PostgresStore({\n *   host: \"localhost\",\n *   port: 5432,\n *   database: \"myapp\",\n *   user: \"postgres\",\n *   password: \"secret\",\n * }));\n * ```\n *\n * @see {@link Store} for the interface contract\n * @see {@link InMemoryStore} for the default implementation\n */\n// ALS check lives outside `port()` — its cache fires only once, so the\n// per-call branch on a scoped Act has to be in the public wrapper.\nconst _store = port(function store(adapter?: Store): Store {\n  return adapter ?? new InMemoryStore();\n});\n\nexport const store = ((adapter?: Store): Store => {\n  return current_ports()?.store ?? _store(adapter);\n}) as (adapter?: Store) => Store;\n\n/**\n * Gets or injects the singleton cache.\n *\n * By default, Act uses an {@link InMemoryCache} (LRU, maxSize 1000). For\n * distributed deployments, inject a Redis-backed cache before building your\n * application.\n *\n * @param adapter - Optional cache implementation to inject\n * @returns The singleton cache instance\n *\n * @see {@link Cache} for the interface contract\n * @see {@link InMemoryCache} for the default implementation\n */\nconst _cache = port(function cache(adapter?: Cache) {\n  return adapter ?? new InMemoryCache();\n});\n\nexport const cache = ((adapter?: Cache): Cache => {\n  return current_ports()?.cache ?? _cache(adapter);\n}) as (adapter?: Cache) => Cache;\n\n/**\n * The ports bag an Act without `ActOptions.scoped` runs in: the singleton\n * adapters, read through the same frame a scoped Act uses.\n *\n * Every Act entering a frame is what keeps its ports its own. Without one, a\n * shared Act called from inside a tenant's handler inherited that tenant's\n * frame and committed to the tenant's store (#1597).\n *\n * The properties are getters on purpose. The adapters are resolved lazily and\n * injected after `act().build()` in the normal case — `store(new PgStore())`\n * in application setup, or a test's `beforeEach` — so capturing them when the\n * bag is made would pin whatever existed at build time. They read the raw\n * resolvers rather than the public `store()`/`cache()`, which consult the\n * frame this bag *is* and would recurse.\n *\n * @internal\n */\nexport const default_scope = (): Scoped => DEFAULT_SCOPE;\n\nconst DEFAULT_SCOPE: Scoped = {\n  get store() {\n    return _store();\n  },\n  get cache() {\n    return _cache();\n  },\n};\n\n// ---------------------------------------------------------------------------\n// Disposal\n// ---------------------------------------------------------------------------\n\n/**\n * Registered cleanup functions live in `disposers.ts`, which holds\n * lifetime-bound entries weakly so registering never pins its target for the\n * process lifetime (#1441). The public surface here is unchanged.\n */\n\n/**\n * Disposes all registered adapters and disposers, then exits the process.\n *\n * Execution order:\n * 1. Custom disposers (registered via {@link dispose}) — in reverse order\n * 2. Port adapters (log, store, cache) — in reverse registration order\n * 3. Adapter registry is cleared\n * 4. Process exits (skipped in test environment)\n *\n * In production, `\"ERROR\"` exits are silently ignored to avoid crashing on\n * transient failures (e.g. an uncaught promise in a non-critical path).\n *\n * @param code - Exit code: `\"EXIT\"` for clean shutdown (exit 0),\n *               `\"ERROR\"` for abnormal termination (exit 1)\n */\nexport async function disposeAndExit(code: ExitCode = \"EXIT\"): Promise<void> {\n  if (code === \"ERROR\" && config().env === \"production\") {\n    // Surface the swallow so incident triage can see it. Without this\n    // log the framework looks unresponsive after an uncaught exception\n    // in prod — exactly when operators most need a breadcrumb.\n    log().warn(\n      \"disposeAndExit('ERROR') ignored in production — process kept alive\"\n    );\n    return;\n  }\n\n  // Run sequentially in reverse registration order so a disposer can rely on\n  // later-registered disposers (and adapters on later-registered adapters)\n  // having already finished — Promise.all would race them.\n  await run_disposers();\n  for (const adapter of [...adapters.values()].reverse()) {\n    await adapter.dispose();\n    log().info(`[act] - ${adapter.constructor.name}`);\n  }\n  adapters.clear();\n  config().env !== \"test\" && process.exit(code === \"ERROR\" ? 1 : 0);\n}\n\n/**\n * Registers a cleanup function for graceful shutdown.\n *\n * Disposers are called automatically on SIGINT, SIGTERM, uncaught exceptions,\n * and unhandled rejections. They execute in reverse registration order before\n * port adapters are disposed.\n *\n * @param disposer - Async function to call during cleanup. Omit to get a\n *                   reference to {@link disposeAndExit} without registering.\n * @returns Function to manually trigger disposal and exit\n *\n * @example\n * ```typescript\n * import { dispose } from \"@rotorsoft/act\";\n *\n * const db = connectDatabase();\n * dispose(async () => await db.close());\n *\n * // In tests\n * afterAll(async () => await dispose()());\n * ```\n *\n * @see {@link disposeAndExit} for the full shutdown sequence\n */\nexport function dispose(\n  disposer?: Disposer\n): (code?: ExitCode) => Promise<void> {\n  disposer && register_disposer(disposer);\n  return disposeAndExit;\n}\n\n// ---------------------------------------------------------------------------\n// Constants\n// ---------------------------------------------------------------------------\n\n/**\n * Event name used internally for snapshot events in the event store.\n * Snapshot events store a full state checkpoint, enabling efficient cold-start\n * recovery without replaying the entire event stream.\n */\nexport const SNAP_EVENT = \"__snapshot__\";\n\n/**\n * Event name used internally for tombstone events in the event store.\n * A tombstone marks a stream as permanently closed — no further writes\n * are permitted until the stream is explicitly restarted via `close()`.\n *\n * @see {@link Act.close} for the close-the-books API\n */\nexport const TOMBSTONE_EVENT = \"__tombstone__\";\n\n/**\n * Name of the implicit lane every reaction lands in unless its `.to({lane})`\n * declaration says otherwise (ACT-1103). Acts that don't call\n * `.withLane(...)` see only this lane, and behavior is identical to\n * pre-1103 single-controller drain.\n *\n * Persisted on `streams.lane` and threaded as the strict-typed default in\n * builder generics — `lane?: TLanes` always includes `\"default\"`.\n */\nexport const DEFAULT_LANE = \"default\";\n","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 {\n  ALL_LANES,\n  classify_registry,\n  type EventLaneSet,\n} from \"./builders/build-classify.js\";\nimport {\n  build_handle,\n  build_handle_batch,\n} from \"./builders/reaction-builder.js\";\nimport { register_weak_disposer } from \"./disposers.js\";\nimport {\n  type AuditDeps,\n  audit,\n  bare_patch,\n  build_drain,\n  build_es,\n  CircuitBreaker,\n  type CircuitBreakerOptions,\n  type CircuitState,\n  CorrelateCycle,\n  close_correlation,\n  DEFAULT_SHUTDOWN_GRACE_MS,\n  DrainController,\n  type DrainOps,\n  default_correlator,\n  type EsOps,\n  FOLD_RESET,\n  type Handle,\n  type HandleBatch,\n  MAX_SHUTDOWN_GRACE_MS,\n  type PatchFn,\n  type ResettableBatchHandler,\n  resolveAutocloseConfig,\n  resolveCircuitBreakerConfig,\n  resolveDrainConfig,\n  resolveSettleConfig,\n  resolveShutdownConfig,\n  run_close_cycle,\n  SettleLoop,\n  scan,\n  walk_streams,\n} from \"./internal/index.js\";\nimport {\n  current_reacting,\n  make_reaction_scope,\n  make_run_scoped,\n} from \"./scoped.js\";\n\n// Public re-exports: these appear in ActOptions / ActLifecycleEvents above.\nexport type { CircuitBreakerOptions, CircuitState } from \"./internal/index.js\";\n\nimport {\n  cache,\n  default_scope,\n  log,\n  type Scoped,\n  store,\n  TOMBSTONE_EVENT,\n} from \"./ports.js\";\nimport type {\n  Actor,\n  AsOf,\n  AuditCategory,\n  AuditFinding,\n  AuditOptions,\n  BatchHandler,\n  BlockedLease,\n  CloseResult,\n  CloseTarget,\n  Committed,\n  Correlator,\n  DoOptions,\n  Drain,\n  DrainOptions,\n  EventSink,\n  EventSource,\n  IAct,\n  LaneConfig,\n  Lease,\n  LoadTarget,\n  Logger,\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  StoreNotification,\n  StreamFilter,\n  StreamPosition,\n  Target,\n} from \"./types/index.js\";\n\n/**\n * @category Orchestrator\n * @see Store\n *\n * Main orchestrator for event-sourced state machines and workflows.\n *\n * It manages the lifecycle of actions, reactions, and event streams, providing APIs for loading state, executing actions, querying events, and draining reactions.\n *\n * ## Usage\n *\n * ```typescript\n * const app = new Act(registry, 100);\n * await app.do(\"increment\", { stream: \"counter1\", actor }, { by: 1 });\n * const snapshot = await app.load(Counter, \"counter1\");\n * await app.drain();\n * ```\n *\n * - Register event listeners with `.on(\"committed\", ...)` and `.on(\"acked\", ...)` to react to lifecycle events.\n * - Use `.query()` to analyze event streams for analytics or debugging.\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 */\n/**\n * Default LRU cap for the subscribed-streams cache. Apps that mint many\n * dynamic targets (one per aggregate) should override via\n * {@link ActOptions.maxSubscribedStreams} based on expected concurrency.\n */\nexport const DEFAULT_MAX_SUBSCRIBED_STREAMS = 1000;\n\n/**\n * Scan window and pass cap for the correlation catch-up the close-cycle\n * safety probe runs (#1487). The probe cannot judge pending work over\n * events correlate has not resolved, so it advances the cursor to the head\n * of the streams being closed first — bounded, so a close behind a large\n * backlog skips the stream (the documented retryable outcome) rather than\n * scanning the whole log inside an operator call.\n *\n * @internal\n */\nconst CLOSE_CATCH_UP_LIMIT = 1000;\nconst CLOSE_CATCH_UP_PASSES = 20;\n\n/**\n * Default debounce window (ms) for `settle()` when neither the per-call\n * `SettleOptions.debounceMs` nor `ActOptions.settleDebounceMs` is set.\n * Coalesces commits in the same tick and small bursts; sub-perceptible\n * latency on the `\"settled\"` signal.\n */\nexport const DEFAULT_SETTLE_DEBOUNCE_MS = 10;\n\n// Re-export the autoclose config surface so operators can\n// `import { DEFAULT_AUTOCLOSE_CYCLE_MINUTES, resolveAutocloseConfig }\n// from \"@rotorsoft/act\"`. The implementation lives in\n// `internal/config.ts` (the single home for builder-facing config bags)\n// to keep this orchestrator file focused on the `Act` class.\nexport {\n  type AutocloseConfig,\n  type AutoclosePolicy,\n  DEFAULT_AUTOCLOSE_CYCLE_MINUTES,\n  DEFAULT_CLOSE_BATCH_SIZE,\n  DEFAULT_CLOSE_YIELD_MS,\n  resolveAutocloseConfig,\n} from \"./internal/index.js\";\n\n/**\n * Lifecycle events emitted by {@link Act}, mapped to their payload type.\n * Drives the typing of `emit` / `on` / `off` — the event-name argument\n * narrows its payload at the call site.\n *\n * The first parameter is kept (unused) for arity compatibility: `committed`\n * carries snapshots of whichever state each action targeted, so its honest\n * element type is `Snapshot<Schema, TEvents>` — the register map itself was\n * never the shape of any snapshot's state.\n */\nexport type ActLifecycleEvents<\n  _TSchemaReg extends SchemaRegister<TActions>,\n  TEvents extends Schemas,\n  TActions extends Schemas,\n> = {\n  committed: Snapshot<Schema, TEvents>[];\n  acked: Lease[];\n  blocked: BlockedLease[];\n  settled: Drain<TEvents>;\n  closed: CloseResult;\n  /**\n   * A **different process** committed an event to the same backing store.\n   *\n   * Fires only when the configured store implements\n   * {@link Store.notify} and there is at least one registered reaction.\n   * The orchestrator uses the same signal internally to wake `settle()`\n   * — listeners get the raw payload for SSE fan-out, dashboards, and\n   * audit logs.\n   *\n   * Local commits do *not* fire `notified` (use `committed` for those):\n   * stores self-filter their own writes so this channel has a clean\n   * cross-process semantic.\n   */\n  notified: StoreNotification;\n  /**\n   * A stream's sensitive-data payload was wiped via {@link Act.forget}.\n   * Fires exactly once per successful `forget(stream)` call — idempotent\n   * second calls (no PII left on the stream) return `eventCount: 0` and\n   * do NOT re-emit. Apps that never call `forget()` never see this event.\n   *\n   * Listeners use it for the compliance side of GDPR / CCPA: audit log,\n   * downstream cache busts, projection-side wipes that the framework\n   * doesn't reach (e.g., search indexes, ETL caches). The framework's own\n   * cache is invalidated by `forget()` itself before the event fires.\n   */\n  forgotten: { stream: string; at: Date; eventCount: number };\n  /**\n   * A store operation failed during the drain loop (ACT-984). Fires on\n   * every failed drain cycle — typically a {@link StoreError} from a\n   * degraded backend — carrying the orchestrator circuit breaker's state\n   * after the failure (`open` means the drain loop has backed off and will\n   * retry after the cooldown). Listen to alert on a degraded store; the\n   * framework logs the same error regardless. Emitted only when a listener\n   * is registered (Node's `EventEmitter` throws on an unhandled `\"error\"`).\n   */\n  error: { error: unknown; circuit: CircuitState };\n};\n\n/**\n * Options for {@link Act} construction (passed via {@link ActBuilder.build}).\n *\n * @property maxSubscribedStreams - Cap for the LRU tracking what each\n *   dynamically resolved reaction target was last subscribed at. Statically\n *   declared targets are held outside it and never evicted, so their lane\n *   and priority stay owned by the build-time subscribe (#1582).\n *   Default: {@link DEFAULT_MAX_SUBSCRIBED_STREAMS}.\n * @property settleDebounceMs - Debounce window (ms) used by `settle()` when\n *   the caller doesn't pass `SettleOptions.debounceMs`. Tune this once per\n *   Act instance instead of threading the value through every call site.\n *   Default: {@link DEFAULT_SETTLE_DEBOUNCE_MS}.\n */\nexport type ActOptions<TLanes extends string = string> = {\n  readonly maxSubscribedStreams?: number;\n  readonly settleDebounceMs?: number;\n  /**\n   * Per-Act ports (ACT-501). When set, this Act runs against the\n   * provided store + cache instead of the singletons — threaded via\n   * AsyncLocalStorage so internals are unchanged. Both are required\n   * together (a shared cache across distinct stores would collide on\n   * stream keys). Omit for the singleton path.\n   */\n  readonly scoped?: Scoped;\n  /**\n   * Correlation-id generator for originating actions (ACT-404). When\n   * omitted, Act uses {@link default_correlator}, which produces a\n   * readable, time-monotonic-within-window, lowercase id of the form\n   * `{state[:4]}-{action[:4]}-{ts}{rnd}` (18 chars).\n   *\n   * Reactions inherit `reactingTo.meta.correlation` so the chain stays\n   * intact — the delegate is only consulted on originating commits and\n   * for the close-the-books transaction.\n   */\n  readonly correlator?: Correlator;\n  /** Restrict this process to a subset of declared lanes (ACT-1103). */\n  readonly onlyLanes?: ReadonlyArray<TLanes>;\n  /**\n   * Subscribe to {@link Store.notify} on this instance (#803). Defaults\n   * to `true`. Set `false` on instances that only commit and never\n   * react — the subscriber-connection budget is the practical scaling\n   * ceiling for the notify/listen pattern, and writer-only fleets\n   * spend it for nothing when they subscribe to a channel they never\n   * read. Commits still emit notifications (that's part of the\n   * store's commit protocol); only the subscriber side is gated.\n   */\n  readonly listen?: boolean;\n  /**\n   * Run the local reaction pipeline on this instance (#803). Defaults\n   * to `true`. Set `false` on writer-only or sidecar instances: drain\n   * controllers' auto-cycle workers don't start, `correlate()` /\n   * `drain()` / `settle()` become no-ops, and the notify handler\n   * skips its drain-wakeup arm (but still emits the `notified`\n   * lifecycle event so observability sidecars work).\n   */\n  readonly drain?: boolean;\n  /**\n   * Orchestrator circuit breaker for the drain loop (ACT-984). After\n   * `failureThreshold` consecutive store failures the breaker opens and\n   * the drain loop skips `claim()` for `cooldownMs` instead of hammering a\n   * down backend, then allows a half-open trial. Out-of-range values throw\n   * a `ZodError` at `act().build()`. Defaults: threshold 5, cooldown 30s.\n   */\n  readonly circuitBreaker?: CircuitBreakerOptions;\n  /**\n   * @deprecated Since #1175 this knob is accepted, validated, and\n   * ignored. It paced the off-hours re-check of the pre-#1090 autoclose\n   * sweep; the synthesized autoclose reaction now derives its re-check\n   * directly from `autocloseWindow` — a tick landing outside the window\n   * parks until the exact instant the window opens, so there is no\n   * polling cadence to configure (and nothing minute-denominated on the\n   * close surface). Still validated as an integer `[1, 1440]` so typos\n   * keep failing loudly at `act().build()`. Will be removed in the next\n   * major.\n   */\n  readonly autocloseCycleMinutes?: number;\n  /**\n   * @deprecated Dead since #1090 replaced the autoclose sweep with a\n   * synthesized per-aggregate reaction — nothing pages the store in\n   * batches anymore, so nothing reads this. Accepted and validated\n   * (`[1, 1024]`) for compatibility; will be removed in the next major.\n   */\n  readonly closeBatchSize?: number;\n  /**\n   * @deprecated Dead since #1090 — the sweep that yielded between\n   * successive `Store.truncate` calls no longer exists; closes are\n   * staged per stream by the autoclose reaction. Accepted and validated\n   * (`[0, 1000]`) for compatibility; will be removed in the next major.\n   */\n  readonly closeYieldMs?: number;\n  /**\n   * @deprecated Dead since #1090 — the sweep-side predicate try/catch\n   * this flag steered no longer exists; a throwing policy predicate now\n   * follows the reaction retry path (`blockOnError: false`, three\n   * retries). Accepted for compatibility; will be removed in the next\n   * major.\n   */\n  readonly closeOnError?: boolean;\n  /**\n   * Optional off-hours window restricting when autoclose evaluates. A\n   * synthesized autoclose reaction that triggers outside the window\n   * defers to the next instant the window opens — derived from the\n   * window itself, no polling cadence. Hours are `[0, 23]` integers in\n   * `timeZone` (IANA, default `\"UTC\"`, DST-correct); `start > end` is\n   * an overnight window (e.g. `{ start: 22, end: 6 }`). Omit to\n   * evaluate regardless of clock time.\n   */\n  readonly autocloseWindow?: {\n    readonly start: number;\n    readonly end: number;\n    readonly timeZone?: string;\n  };\n  /**\n   * Validate folded state against its declared Zod schema after every\n   * reduction (ACT-1238). Off by default.\n   *\n   * When `true`, each time an event is folded into state — on the\n   * command path (`do`), on `load`/replay, and inside projection-fold\n   * projections — the merged full state is parsed against the owning\n   * state's `state({ Name: schema })` schema. A reducer that produces\n   * schema-violating state (the calculator divide-by-zero NaN class,\n   * #1230) throws a {@link ValidationError} at the triggering event,\n   * whose `target` names the state and the event (`<state>.<event>#<id>`)\n   * — instead of the bad value propagating and surfacing hops later as a\n   * confusing downstream error.\n   *\n   * This is a **debugging / CI aid, not a production guard**. Turn it on\n   * in development and CI to catch total-reducer bugs at the source; the\n   * framework already validates action inputs and emitted events, so the\n   * reduced state is the one shape it otherwise trusts. The per-event\n   * patch step is selected **once at `build()`** (the same way the\n   * orchestrator picks bare vs trace-decorated store ops from the log\n   * level): when `false` (the default) the fold loop is byte-identical to\n   * a bare reduction — the validating patch step is never selected, so\n   * there is no per-event cost, not even a branch.\n   */\n  readonly validateFoldedState?: boolean;\n};\n\n/** Reject `onlyLanes` entries that reference undeclared lanes. */\nfunction validate_only_lanes(\n  options: ActOptions,\n  lanes: ReadonlyArray<LaneConfig>\n): void {\n  if (!options.onlyLanes || options.onlyLanes.length === 0) return;\n  const declared = new Set<string>([\"default\", ...lanes.map((l) => l.name)]);\n  const unknown = options.onlyLanes.filter((l) => !declared.has(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\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  /** ACT-984: orchestrator-owned circuit breaker shared by all drain lanes. */\n  private readonly _breaker: CircuitBreaker;\n  /** #803: gate the `Store.notify` subscription side. */\n  private readonly _listen: boolean;\n  /** #803: gate the local reaction pipeline (drain controllers, settle, correlate). */\n  private readonly _drain: boolean;\n  /** Event names with at least one registered reaction (computed at build time) */\n  private readonly _reactive_events: ReadonlySet<string>;\n  /** One DrainController per active lane, keyed by lane name. */\n  private readonly _drain_controllers: Map<\n    string,\n    DrainController<TEvents, TActions, TSchemaReg>\n  >;\n  /** Correlation state machine: lazy init, dynamic-resolver scan, periodic worker. */\n  private readonly _correlate: CorrelateCycle<TSchemaReg, TEvents, TActions>;\n  /** Debounced correlate→drain catch-up loop. */\n  private readonly _settle: SettleLoop<TEvents>;\n  /**\n   * Disposer for the cross-process notify subscription, set up eagerly\n   * during construction. Held as a promise because the subscription\n   * itself may be async (the PG adapter checks out a dedicated client\n   * and runs `LISTEN` before resolving). Resolves to `undefined` when\n   * the store doesn't implement `notify` or there are no registered\n   * reactions.\n   *\n   * **Contract:** the configured store must be injected via\n   * {@link store}`(adapter)` *before* calling `act()...build()`. The\n   * orchestrator wires notify against whatever store is current at\n   * construction time — late injection after build is unsupported.\n   */\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  /** Map of state name → state definition; populated by the builder. */\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   * **Every listener is contained individually.** Lifecycle listeners are\n   * observers — `observability.md` promises that a throwing one is \"contained,\n   * not fatal\" — and containment belongs here rather than at each call site,\n   * for two reasons the previous arrangement got wrong (#1437):\n   *\n   * - Wrapping the *emit* rather than each *listener* still let the first\n   *   thrower abort the rest: `EventEmitter.emit` stops dispatching on the\n   *   first exception, so a second `app.on(\"acked\", …)` never ran. The\n   *   documented \"the remaining sinks still fire\" was false whenever an event\n   *   had more than one listener. Same lesson as #1423, where guarding the\n   *   loop instead of each callback left every later SSE subscriber unserved.\n   * - Only *some* call sites wrapped at all. The drain contained `acked` and\n   *   `blocked`; `committed`, `forgotten` and `close()`'s `closed` did not, so\n   *   a throwing listener rejected `do()`, `forget()` and `close()` **after**\n   *   their durable work had already landed. A caller retrying a \"failed\"\n   *   `do()` writes the event twice, since the framework has no dedup by\n   *   design.\n   *\n   * Containing here makes it a property of emitting, so a new lifecycle event\n   * cannot reintroduce the gap by omission.\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    const listeners = this._emitter.rawListeners(event as string);\n    for (const listener of listeners) {\n      try {\n        listener(args);\n      } catch (error) {\n        this._logger.error(error, `${String(event)} listener threw`);\n      }\n    }\n    return listeners.length > 0;\n  }\n\n  /**\n   * The single store-failure handler: log it, then emit the `error`\n   * lifecycle event. Wired into the circuit breaker's `on_error`, so it\n   * runs on every `failed()` — drain / settle / autoclose just call\n   * `breaker.failed(now, error)` and never log or emit themselves.\n   *\n   * The emit is guarded against Node's `EventEmitter` contract that an\n   * unhandled `\"error\"` emission is rethrown (which would crash the process\n   * from inside the drain catch); logging is unconditional so failures are\n   * never silent.\n   */\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  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    this._emitter.on(event, listener);\n    return this;\n  }\n\n  /**\n   * Remove a previously registered lifecycle listener.\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    this._emitter.off(event, listener);\n    return this;\n  }\n\n  /** Batch handlers for static-target projections (target → handler) */\n  private readonly _batch_handlers: Map<string, BatchHandler<TEvents>>;\n  /** Event-sourcing handlers, optionally wrapped with trace decorators */\n  private readonly _es: EsOps;\n  /** Correlate/drain pipeline ops, optionally wrapped with trace decorators */\n  private readonly _cd: DrainOps<TEvents>;\n  /**\n   * Event-name → owning state, computed at build time. The duplicate-event\n   * guard in merge.ts ensures one event name maps to at most one state, so\n   * this lookup is unambiguous. Used by `close()` to pick the right reducer\n   * set when seeding a `restart` snapshot in multi-state apps.\n   */\n  private readonly _event_to_state: ReadonlyMap<string, State<any, any, any>>;\n  /**\n   * Event-name → lane fan-in for selective arming (ACT-1103). Built by\n   * `classify_registry` once per build. `\"all\"` means at least one of\n   * the event's reactions is a dynamic resolver (lane opaque until\n   * runtime); a `Set<string>` lists the static lanes only that event's\n   * reactions target.\n   */\n  private readonly _event_to_lanes: ReadonlyMap<string, EventLaneSet>;\n  /**\n   * Audit dependency bag (#723). Built once at construction; held as\n   * an immutable snapshot of the registry state the audit module\n   * needs. Lives in `internal/audit.ts` — this orchestrator never\n   * carries audit logic, only the deps + a one-liner that hands them\n   * over.\n   */\n  private readonly _audit_deps: AuditDeps;\n  /** Logger resolved at construction time (after user port configuration) */\n  private readonly _logger: Logger = log();\n  /** Wraps a public-method body so internal `store()`/`cache()` resolve to the\n   * per-Act ports (ACT-501). No-op when the Act is unscoped — so the singleton\n   * path keeps reading fresh `store()`/`cache()` per call, which matters for\n   * tests that dispose and re-seed mid-suite. */\n  /** This Act's ports: its own bag, or the singleton adapters. */\n  private readonly _ports: Scoped;\n  private readonly _scoped: <T>(fn: () => Promise<T>) => Promise<T>;\n\n  /**\n   * Correlation-id generator for originating actions. Bound at\n   * construction from `options.correlator ?? default_correlator`. The\n   * `do()` path passes this into the `_es.action` closure; close-cycle\n   * uses it via {@link close_correlation}.\n   */\n  private readonly _correlator: Correlator;\n  /** Pre-bound IAct methods reused across drain cycles. Only `do` varies per\n   * payload (it captures the triggering event for reactingTo auto-inject). */\n  private readonly _bound_do = this.do.bind(this);\n  private readonly _bound_load = this.load.bind(this);\n  private readonly _bound_query = this.query.bind(this);\n  private readonly _bound_query_array = this.query_array.bind(this);\n  private readonly _bound_forget = this.forget.bind(this);\n  /** Reaction dispatchers built once and handed to run_drain_cycle each cycle. */\n  private readonly _handle: Handle<TEvents>;\n  private readonly _handle_batch: HandleBatch<TEvents>;\n  /** Declared drain lanes (ACT-1103). */\n  private readonly _lanes: ReadonlyArray<LaneConfig>;\n\n  /**\n   * Per-stream close serialization tails (#1222). Chains each stream's\n   * windowed-close work behind the previous one so a manual\n   * `app.close([{stream, before}])` and an autoclose windowed close for\n   * the same stream never run their guard-free prune concurrently — the\n   * manual path bypasses the `__autoclose__:X` drain lease that would\n   * otherwise exclude them, so without this both closers archive the\n   * same prefix. Process-local: both racers run on the same Act\n   * instance. Entries are dropped once their tail resolves so the map\n   * doesn't grow with distinct stream names.\n   */\n  private readonly _close_locks = new Map<string, Promise<unknown>>();\n\n  /**\n   * Run `work` under the per-stream close lock (#1222). Serializes\n   * windowed-close critical sections for the same stream while letting\n   * different streams proceed in parallel.\n   */\n  private _with_close_lock<T>(\n    stream: string,\n    work: () => Promise<T>\n  ): Promise<T> {\n    const prev = this._close_locks.get(stream) ?? Promise.resolve();\n    // Chain after the previous holder regardless of how it settled — a\n    // failed close must not wedge the stream's lock forever. The next\n    // waiter chains off `next` (the work), so its start is gated on this\n    // work completing.\n    const next = prev.then(work, work);\n    this._close_locks.set(stream, next);\n    // Drop the tail once it settles, but only if it's still the current\n    // one — a later waiter that already replaced it owns the entry now.\n    const cleanup = () => {\n      if (this._close_locks.get(stream) === next)\n        this._close_locks.delete(stream);\n    };\n    next.then(cleanup, cleanup);\n    return next;\n  }\n\n  /** Drain lanes declared via `.withLane(...)`. Implicit default not included. */\n  get lanes(): ReadonlyArray<LaneConfig> {\n    return this._lanes;\n  }\n\n  /**\n   * Create a new Act orchestrator. Prefer the {@link act} builder over\n   * direct construction — `act()...build()` wires the registry, merges\n   * partial states, and collects batch handlers from registered slices\n   * and projections in one pass.\n   *\n   * @param registry  Schemas for every event and action across registered states\n   * @param states    Merged map of state name → state definition\n   * @param batch_handlers Static-target projection batch handlers (target → handler)\n   * @param options   Tuning knobs — see {@link ActOptions}\n   * @param lanes     Declared drain lanes (ACT-1103). The builder collects\n   *   these from `.withLane(...)` calls. Slice 1 records them on the\n   *   instance; later slices fan out one `DrainController` per lane.\n   * @param patch_fn  The per-event patch step selected once by the builder\n   *   from `ActOptions.validateFoldedState` (ACT-1238) — `bare_patch` by\n   *   default, `validating_patch` when the flag is on. The builder uses\n   *   the same value for its projection-fold handlers, so there is a\n   *   single selection site. Defaults to `bare_patch` for direct\n   *   construction.\n   */\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    validate_only_lanes(options, lanes);\n    // Every Act runs in its own ports frame. Without `scoped` that frame\n    // carries the singleton adapters, which is what stops a shared Act\n    // inheriting the frame of whoever called it (#1597).\n    this._ports = options.scoped ?? default_scope();\n    // Resolved here rather than at reaction synthesis, so it is this Act's\n    // window and not the first-built Act's (#1615). Parsing on every\n    // construction is also what restores the startup-validation contract:\n    // an out-of-range window throws where it was declared, on every build,\n    // not only the first.\n    const ports = this._ports;\n    this._scoped = make_run_scoped({\n      // Delegating getters, NOT a spread: `default_scope()` resolves the\n      // process singletons lazily, so copying its properties would freeze\n      // whichever adapters happened to be installed at construction and\n      // ignore a later `store(...)` / `cache(...)`.\n      get store() {\n        return ports.store;\n      },\n      get cache() {\n        return ports.cache;\n      },\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    // Reaction-level PII wrapping happens at build time inside `act-builder`:\n    // reactions registered against an event with `sensitive(...)` fields get\n    // a stripping handler closure; reactions against non-PII events keep\n    // their original handler reference. So the dispatcher is PII-unaware.\n    this._handle = build_handle<TEvents, TActions, TActor>({\n      logger: this._logger,\n      // The orchestrator owns ambient context; `build_handle` only asks for\n      // the triggering event to be in scope while the handler runs.\n      reaction_scope: make_reaction_scope({\n        do: this._bound_do,\n        load: this._bound_load,\n        query: this._bound_query,\n        query_array: this._bound_query_array,\n        forget: this._bound_forget,\n      }),\n    });\n    this._handle_batch = build_handle_batch<TEvents>(this._logger);\n\n    // The registry arrives complete and frozen from the builder — the\n    // autoclose reactions were synthesized there, so classification sees\n    // the finished shape and nothing here mutates it.\n    const classification = classify_registry(this.registry, this._states);\n    this._reactive_events = classification.reactive_events;\n    this._event_to_state = classification.event_to_state;\n    this._event_to_lanes = classification.event_to_lanes;\n    this._listen = options.listen !== false;\n    this._drain = options.drain !== false;\n\n    // Composition sequence — each step builds one runtime subsystem from\n    // the pieces above. Order matters: controllers read the breaker, the\n    // audit bag reads the finalized controller set, settle reads the\n    // correlate cycle.\n    this._breaker = this._build_breaker(options);\n    this._drain_controllers = this._build_drain_controllers(options, lanes);\n    this._advise_orphaned_lanes(options, 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    // Auto-wire cross-process notify when the store supports it. Bound at\n    // construction time — late `store(adapter)` injection after build won't\n    // take effect. Scoped Acts bind against their own store.\n    this._notify_disposer = this._wire_notify(this._ports.store);\n\n    // Registered weakly (#1441). A plain `dispose(() => this.shutdown())`\n    // closure captures `this` in a module-level array that is never emptied,\n    // so every Act ever built — with its registry, drain controllers, and for\n    // a scoped Act its own store and cache, connection pools included —\n    // survives for the process lifetime. Apps that mint short-lived Acts (one\n    // per tenant, per request, per test) leak one apiece. Holding the\n    // reference weakly keeps process-wide `dispose()()` working for a live\n    // Act while letting an unreachable one be collected, shut down or not.\n    register_weak_disposer(new WeakRef(this), (self) => self.shutdown());\n  }\n\n  /**\n   * Circuit breaker shared by every store-polling loop (drain, the settle\n   * correlate, autoclose). Validates the knobs eagerly so out-of-range\n   * values throw at build time, not on the first cycle tick.\n   */\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        // Re-probe the store when the cooldown elapses, so recovery is\n        // automatic even on the default lane (which has no periodic poller).\n        // The wake fires `settle()`, which (in half-open) runs a real store\n        // probe: for a dynamic-resolver app the probe is settle's correlate\n        // (a store scan); for a static-reaction app correlate is a no-op that\n        // records no health, so the probe is settle's DRAIN claim — either\n        // way one success closes the breaker and every loop resumes, a\n        // failure re-opens it and reschedules the wake. Settle does NOT close\n        // the breaker off a no-op correlate (#1329) — only a real store op\n        // (correlate scan or drain claim) records `passed()`.\n        on_retry: () => {\n          this.settle({ debounceMs: 0 });\n        },\n      }\n    );\n  }\n\n  /**\n   * One DrainController per active lane. The implicit \"default\" lane is\n   * always present unless onlyLanes excludes it. Each controller filters\n   * its claim() by its lane name; the legacy single-controller path is the\n   * no-lane-declared case with `lane: undefined` deps so claim() doesn't\n   * filter (preserves the single-lane SQL planner shape for apps that never\n   * call withLane).\n   */\n  private _build_drain_controllers(\n    options: ActOptions,\n    lanes: ReadonlyArray<LaneConfig>\n  ): Map<string, DrainController<TEvents, TActions, TSchemaReg>> {\n    const all_lanes = [\"default\", ...lanes.map((l) => l.name)];\n    const only_set =\n      options.onlyLanes && options.onlyLanes.length > 0\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    // Keyed on the DECLARED universe, not the active slice: a worker\n    // narrowed to `onlyLanes: [\"default\"]` still shares the store with\n    // peers draining other lanes, and `claim`'s lane argument is an\n    // optional filter — dropping it there would claim every lane's\n    // streams (#1545).\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: this._handle,\n        handle_batch: this._handle_batch,\n        on_acked: (acked) => this.emit(\"acked\", acked),\n        on_blocked: (blocked) => this.emit(\"blocked\", blocked),\n        // Reaction-requested close. Runs the same close machinery as\n        // `app.close` (tombstone guard + archive + atomic truncate) for the\n        // targets a handler signalled via `CloseSignal`. No `correlate()`\n        // here — the drain that produced these targets has already\n        // correlated.\n        on_close: async (targets) => {\n          const close_actor = { id: \"$close\", name: \"close\" };\n          const result = await run_close_cycle(targets, {\n            reactive_events_size: this._reactive_events.size,\n            catch_up_correlation: (until) => this._catch_up_correlation(until),\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) =>\n              this._with_close_lock(stream, work),\n          });\n          this._forget_closed_subscriptions(result);\n          // The close machinery above is deliberately NOT wrapped, so a\n          // real StoreError reaches the breaker (#1388). The emit needs no\n          // guard here: `Act.emit` contains each listener (#1437).\n          this.emit(\"closed\", result);\n        },\n        breaker: this._breaker,\n        // Re-scope the per-lane worker's auto-start ticks so their drain\n        // resolves the scoped ports, not the singleton (#1191).\n        run_scoped: this._scoped,\n        // Pass lane only when a true per-lane controller is active.\n        // The all-lanes (single default) case keeps lane=undefined so\n        // adapter SQL collapses to the single-lane shape.\n        lane: single_default_lane ? undefined : name,\n        defaults: cfg && {\n          streamLimit: cfg.streamLimit,\n          leaseMillis: cfg.leaseMillis,\n        },\n      });\n      // Auto-start a per-lane worker when the operator declared a\n      // cycleMs — the intent of `withLane({cycleMs: 100})` is \"drive\n      // this lane every 100 ms,\" independent of the Act-level settle\n      // loop. unref()'d so the timer doesn't keep the process alive.\n      // Writer-only instances (`drain: false`) construct the controller\n      // but never run reactions locally, so the auto-start is skipped.\n      if (cfg?.cycleMs !== undefined && options.drain !== false)\n        controller.start(cfg.cycleMs);\n      controllers.set(name, controller);\n    }\n    return controllers;\n  }\n\n  /**\n   * Orphaned-lane startup advisory (#1220). When `onlyLanes` is set, this\n   * instance builds a controller only for its slice of the declared lane\n   * universe — every OTHER declared lane's stream is persisted (correlate\n   * subscribes all static targets regardless of `onlyLanes`) but never\n   * claimed here. If no peer worker deploys with those lanes in ITS\n   * `onlyLanes`, their reactions accumulate forever, silently. A single\n   * process can't verify the cluster invariant `∪ onlyLanes ⊇ declared\n   * lanes`, so we surface the per-instance signal — \"these declared lanes\n   * have no controller here\" — the same way the deprecated-event advisory\n   * surfaces legacy events. No advisory when `onlyLanes` is unset (every\n   * lane gets a controller) or covers every declared lane.\n   */\n  private _advise_orphaned_lanes(\n    options: ActOptions,\n    lanes: ReadonlyArray<LaneConfig>\n  ): void {\n    if (!options.onlyLanes || options.onlyLanes.length === 0) return;\n    const active = new Set(this._drain_controllers.keys());\n    const orphaned = [\"default\", ...lanes.map((l) => l.name)].filter(\n      (name) => !active.has(name)\n    );\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  /**\n   * Audit deps bag. Snapshotted after registry classification and\n   * drain-controller build so the audit module sees the finalized lane\n   * set. Held as an immutable bag — the orchestrator never carries audit\n   * logic itself, only this typed contract.\n   */\n  private _build_audit_deps(): AuditDeps {\n    return {\n      store,\n      logger: this._logger,\n      event_to_state: this._event_to_state,\n      states: this._states,\n      // The DECLARED lane universe — the implicit \"default\" plus every\n      // `.withLane(...)` name — NOT `_drain_controllers.keys()` (#1224).\n      // An `onlyLanes`-filtered instance builds a controller only for its\n      // slice of lanes, so keying off the active controller set would flag\n      // a stream correctly assigned to an excluded-but-declared lane (one\n      // another worker drains) as `unknown-lane`. The audit reports what's\n      // structurally routable across the cluster, not what this process runs.\n      declared_lanes: new Set([\"default\", ...this._lanes.map((l) => l.name)]),\n      routed_events: new Set(this._event_to_lanes.keys()),\n    };\n  }\n\n  /**\n   * Correlate cycle over the classified registry. The cold-start callback\n   * arms every controller — historical events may need processing —\n   * except on writer-only instances (`drain: false`).\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      // Every lane a controller can exist for, so correlate can reroute a\n      // dynamic resolution that names one that doesn't (#1564). Declared,\n      // not active: `onlyLanes` shrinks this process's controllers, but a\n      // lane another process claims is still a valid destination.\n      declared_lanes: new Set<string>([\n        \"default\",\n        ...this._lanes.map((l) => l.name),\n      ]),\n      on_init: () => {\n        if (this._drain && this._reactive_events.size > 0) this._arm_all();\n      },\n      // Re-scope the background `start_correlations` timer so its\n      // correlate resolves the scoped ports, not the singleton (#1191).\n      run_scoped: this._scoped,\n      // Cold-start defer re-seed (#1221). Skipped on writer-only instances\n      // (`drain: false`) — they run no local controllers to re-arm.\n      on_init_async: this._drain\n        ? () => this._seed_persisted_defers()\n        : undefined,\n    });\n  }\n\n  /**\n   * Re-seed every active lane controller's process-local defer timer from\n   * the store's persisted `deferred_at` (#1221). Runs once at cold start,\n   * inside `CorrelateCycle.init`, after static targets are subscribed.\n   *\n   * The defer timer is worker memory: empty after a restart. A stream\n   * deferred to a future due-time (the classic case: an idle autoclose\n   * aggregate that deferred its terminal close) is durable in the store but\n   * has nothing in memory to re-arm the drain — the controller disarms on\n   * the first empty claim and, since the aggregate is idle, no commit ever\n   * re-arms it. Reading the persisted schedule and seeding the owning lane's\n   * timer restores the wake, so the close fires at the due-time.\n   *\n   * Streams whose lane has no controller on this instance (excluded by\n   * `onlyLanes`) are skipped — a peer worker owns that lane's timer.\n   */\n  private async _seed_persisted_defers(): Promise<void> {\n    const now = Date.now();\n    // Paged — `query_streams` defaults to 100, and a stream sorting past\n    // the first page would never get its timer re-armed. The failing case\n    // is exactly the one described above: an idle aggregate no commit\n    // ever re-arms.\n    await walk_streams(store(), (pos) => {\n      // Only future defers matter — a past-due schedule is claimable\n      // already, so the ordinary armed drain picks it up.\n      if (pos.deferred_at === undefined || pos.deferred_at <= now) return;\n      // Route to the controller that owns the stream's lane. A missing\n      // controller means the lane is excluded on this instance (onlyLanes) —\n      // skip it, a peer worker owns that timer. The default lane's\n      // controller is keyed \"default\" and matches an undefined stored lane.\n      const controller = this._drain_controllers.get(pos.lane ?? \"default\");\n      controller?.seed_defer(pos.stream, pos.deferred_at);\n    });\n  }\n\n  /** Settle loop driving correlate + drain to quiescence. */\n  private _build_settle(options: ActOptions): SettleLoop<TEvents> {\n    return new SettleLoop<TEvents>(\n      {\n        // Scope the init like every other store-touching path — a bare\n        // `this._correlate.init()` runs `store().subscribe(...)` against\n        // the singleton for a scoped Act, so static targets never land on\n        // the scoped store and `_initialized` then blocks a retry (#1191).\n        init: () => this._scoped(() => this._correlate.init()),\n        checkpoint: () => this._correlate.checkpoint,\n        correlate: (q) => this._correlate_scanned(q, true),\n        drain: (o) => this.drain(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  /** True after the first `shutdown()` call. Guards idempotency. */\n  private _shutdown_promise: Promise<void> | undefined;\n\n  /**\n   * Per-instance teardown: stop scheduling new work, give drain cycles\n   * already in flight a bounded chance to finish, then remove lifecycle\n   * listeners and tear down the cross-process notify subscription.\n   *\n   * The order is deliberate (#1442). Scheduling stops first, so nothing new\n   * is claimed while teardown runs. Then in-flight cycles are awaited up to\n   * `graceMs`: a reaction handler parked on an `await` holds its stream's\n   * lease until it acks, so abandoning it costs the replacement worker up to\n   * `leaseMillis` of dead time on that stream and discards the round of work\n   * (which #1418 then redelivers). Listeners come off *after* that wait, not\n   * before, so an `acked` / `blocked` subscriber still observes the work\n   * that completed during the grace window.\n   *\n   * The budget is a ceiling, not a delay — teardown continues the moment the\n   * last in-flight cycle finishes. When it is exhausted, teardown proceeds\n   * anyway: one stuck handler must not hang a deploy, which is the failure\n   * mode an unbounded wait would trade for.\n   *\n   * Idempotent — repeated calls return the same promise, and the first\n   * call's `graceMs` is the one that applies. Registered automatically with\n   * the global `dispose()` registry at construction, so process-wide\n   * `dispose()()` covers it; test helpers (or operators that mint\n   * short-lived Acts) call it explicitly 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        this.stop_correlations();\n        // Unsubscribe BEFORE stopping the settle loop. A notification\n        // arriving after `stop_settling()` reaches the handler below and\n        // schedules a fresh cycle that nothing is left to cancel, so a\n        // worker that has already shut down takes a new lease — and with a\n        // grace budget in play that window is seconds wide (#1596). Stopping\n        // the source first leaves nothing able to arm.\n        //\n        // `_wire_notify` swallows subscription errors and resolves to\n        // `undefined`, so this promise never rejects.\n        const disposer = await this._notify_disposer;\n        if (disposer) await disposer();\n        this.stop_settling();\n        this._breaker.stop();\n        for (const c of this._drain_controllers.values()) c.stop();\n        await this._await_inflight(options?.graceMs);\n        // Hand the correlation lease back rather than making the next worker\n        // wait out its expiry (#1532), and *await* it: a fire-and-forget\n        // release can land after the process that replaces this one has\n        // already asked, which reads as the successor being denied.\n        //\n        // After the wait, not before it (#1618). `stop_correlations()`\n        // cancels the polling timer, not a correlate already running inside\n        // a settle cycle — and that cycle re-takes the lease on its ordinary\n        // path. Released first, it was re-acquired seconds later and then\n        // held to expiry by a worker that had already shut down, which is\n        // the delay the release exists to remove.\n        //\n        // Wrapped in `_scoped` because it resolves the store through the\n        // port — a scoped Act would otherwise release against the singleton\n        // and leave its real lease held.\n        await this._scoped(() => this._correlate.release_correlation());\n        this._emitter.removeAllListeners();\n      })();\n    }\n    return this._shutdown_promise;\n  }\n\n  /**\n   * Wait for every in-flight drain cycle, or for the grace budget to elapse,\n   * whichever comes first. Cycle promises never reject (`drain()` contains\n   * its own errors), so this never throws.\n   *\n   * An omitted budget is derived from the lanes that actually have a cycle\n   * in flight: their `leaseMillis` is the operator's own statement of how\n   * long one of their handlers may hold a stream, which makes it the honest\n   * ceiling for how long teardown should wait for that handler. A parked\n   * lane that pinned no lease contributes `drain()`'s own fallback, and the\n   * whole thing is capped so a long-leased lane cannot hold a deploy open.\n   * Idle lanes do not count — nothing is running on them to wait for.\n   *\n   * An in-flight settle counts the same way, on the same fallback (#1617).\n   * It is waited on like any cycle, and deriving from the lanes alone gave\n   * it a budget of `0` whenever it was the only thing running — which\n   * returned before the wait it was about to be added to.\n   *\n   * A lane configured `leaseMillis: 0` takes the fallback rather than its\n   * own value, which is why this coalesces on falsy and not just on absent\n   * (#1647). A zero-length lease expires the instant it is granted, so it\n   * has no answer to offer for \"how long may a handler hold this stream\" —\n   * it is the pinned-no-lease case spelled with a number, and #1617 already\n   * settled what that case is worth. Taking it literally derived a budget\n   * of `0` and abandoned the very cycle this had just found running.\n   */\n  private _derive_grace_ms(\n    running: { readonly lease_millis: number | undefined }[],\n    settling: boolean\n  ): number {\n    let max = settling ? DEFAULT_SHUTDOWN_GRACE_MS : 0;\n    for (const c of running)\n      max = Math.max(max, c.lease_millis || DEFAULT_SHUTDOWN_GRACE_MS);\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    // The settle loop drives the drain, so it has to be waited on too\n    // (#1468). `SettleLoop.stop()` cancels scheduling only: a cycle already\n    // inside its correlate → drain loop keeps running, and would otherwise\n    // claim a stream after teardown returned — and, under `disposeAndExit`,\n    // after the store adapter was disposed.\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    const inflight = running.map((c) => c.inflight);\n    if (settling) inflight.push(settling);\n    // Assigned synchronously by the executor below, before the race is\n    // awaited — so the `finally` never has to test for it.\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([Promise.all(inflight), budget]);\n    } finally {\n      // Don't leave the budget timer pending when the cycles won the race.\n      clearTimeout(timer);\n    }\n  }\n\n  /**\n   * Subscribe to {@link Store.notify} when both the store and the\n   * registry support it. Returns the disposer (or `undefined` when no\n   * subscription was made). Errors during subscription are logged but\n   * never thrown — `notify` is a hint, not a contract.\n   */\n  private async _wire_notify(\n    s: Store\n  ): Promise<(() => void | Promise<void>) | undefined> {\n    if (this._reactive_events.size === 0) return undefined;\n    if (!s.notify) return undefined;\n    // #803: writer-only / single-instance deployments opt out of the\n    // subscriber-connection cost. Commits still notify (that's the\n    // store's commit protocol); only the subscriber side is gated.\n    if (!this._listen) return undefined;\n    try {\n      return await s.notify((notification) => {\n        // Generic concerns (lifecycle emit, drain wakeup, listener\n        // error containment) live here so adapters only have to\n        // handle their own wire format. Errors in user-registered\n        // `notified` listeners or in our own bookkeeping are logged\n        // and swallowed — the store's listener stays alive.\n        try {\n          this.emit(\"notified\", notification);\n          // Wake once per commit when at least one event has a local\n          // reaction. Avoids spurious wake-ups for remote commits\n          // belonging to bounded contexts this process doesn't react to.\n          // ACT-1103: selective arming via the shared helper — only the\n          // lanes whose reactions match the notified events.\n          // #803: the sidecar pattern (listen: true, drain: false)\n          // wants the `notified` lifecycle event for observability\n          // without engaging the local reaction pipeline.\n          if (this._drain) {\n            const armed = this._arm_for_event_names(\n              notification.events.map((e) => e.name)\n            );\n            if (armed) this._settle.schedule({ debounceMs: 0 });\n          }\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 on a state instance, committing resulting events.\n   *\n   * This is the primary method for modifying state. It:\n   * 1. Validates the action payload against the schema\n   * 2. Loads the current state snapshot\n   * 3. Checks invariants (business rules)\n   * 4. Executes the action handler to generate events\n   * 5. Applies events to create new state\n   * 6. Commits events to the store with optimistic concurrency control\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 Array of snapshots for all affected states (usually one)\n   *\n   * @throws {ValidationError} If payload doesn't match action schema\n   * @throws {InvariantError} 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   * @example With error handling\n   * ```typescript\n   * try {\n   *   await app.do(\n   *     \"withdraw\",\n   *     { stream: \"account-123\", actor: { id: \"user1\", name: \"Alice\" } },\n   *     { amount: 1000 }\n   *   );\n   * } catch (error) {\n   *   if (error instanceof InvariantError) {\n   *     console.error(\"Business rule violated:\", error.description);\n   *   } else if (error instanceof ConcurrencyError) {\n   *     console.error(\"Concurrent modification detected, retry...\");\n   *   } else if (error instanceof ValidationError) {\n   *     console.error(\"Invalid payload:\", error.details);\n   *   }\n   * }\n   * ```\n   *\n   * @example Reaction triggering another action (reactingTo auto-injected)\n   * ```typescript\n   * const app = act()\n   *   .withState(Order)\n   *   .withState(Inventory)\n   *   .on(\"OrderPlaced\")\n   *     .do(async function reduceInventory(event, _stream, app) {\n   *       // Inside reaction handlers, reactingTo is auto-injected when omitted.\n   *       // The triggering event is used by default, maintaining the correlation chain.\n   *       await app.do(\n   *         \"reduceStock\",\n   *         { stream: \"inventory-1\", actor: { id: \"sys\", name: \"system\" } },\n   *         { amount: event.data.items.length }\n   *       );\n   *       // To use a different correlation, pass reactingTo explicitly:\n   *       // await app.do(\"reduceStock\", target, payload, { reactingTo: customEvent });\n   *     })\n   *     .to(\"inventory-1\")\n   *   .build();\n   * ```\n   *\n   * @see {@link Target} for target structure\n   * @see {@link Snapshot} for return value structure\n   * @see {@link ValidationError}, {@link InvariantError}, {@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, at the orchestrator\n    // boundary, and hand `action()` an explicit value — a dispatch made\n    // anywhere inside a reaction handler threads the chain whichever `IAct`\n    // reference made the call (#1541), while `internal/` stays free of\n    // ambient reads. An explicitly-passed `reactingTo` still 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      // Arm the drain when any committed event has reactions (ACT-1103:\n      // arm only the lanes whose reactions match — events whose reactions\n      // are all statically lane-resolved arm a subset; events with at\n      // least one dynamic resolver fall back to _arm_all via the \"all\"\n      // sentinel).\n      if (this._reactive_events.size > 0)\n        // Snapshots produced by `action()` always carry their committed\n        // event — the optional `event?` on the type is for load()\n        // snapshots, which don't reach this path.\n        this._arm_for_event_names(\n          snapshots.map((s) => (s.event as { name: string }).name)\n        );\n      this.emit(\"committed\", snapshots);\n      return snapshots;\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   * @example Load by state name (useful with partial states)\n   * ```typescript\n   * const snapshot = await app.load(\"Ticket\", \"ticket-123\");\n   * console.log(snapshot.state.title);    // Merged state from all partials\n   * ```\n   *\n   * @example Load multiple states\n   * ```typescript\n   * const [user, account] = await Promise.all([\n   *   app.load(User, \"user-123\"),\n   *   app.load(BankAccount, \"account-456\")\n   * ]);\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 available fields\n   *   (`stream`, `name`, `after`, `before`, `created_after`, `created_before`,\n   *   `limit`, `with_snaps`, `stream_exact`)\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   * @example Query specific event types\n   * ```typescript\n   * const { count } = await app.query(\n   *   { name: \"UserCreated\", limit: 100 },\n   *   (event) => {\n   *     console.log(\"User created:\", event.data.email);\n   *   }\n   * );\n   * ```\n   *\n   * @example Query events in time range\n   * ```typescript\n   * const yesterday = new Date(Date.now() - 24 * 60 * 60 * 1000);\n   * const { count } = await app.query({\n   *   created_after: yesterday,\n   *   stream: \"user-123\"\n   * });\n   * console.log(`User had ${count} events in last 24 hours`);\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   * @example Get recent events\n   * ```typescript\n   * const recent = await app.query_array({\n   *   stream: \"user-123\",\n   *   limit: 10\n   * });\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}. Application-level half of #566.\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   * Processes pending reactions by draining uncommitted events from the event store.\n   *\n   * Runs a single drain cycle:\n   * 1. Polls the store for streams with uncommitted events\n   * 2. Leases streams to prevent concurrent processing\n   * 3. Fetches events for each leased stream\n   * 4. Executes matching reaction handlers\n   * 5. Acknowledges successful reactions or blocks failing ones\n   *\n   * Drain uses a dual-frontier strategy to balance processing of new streams (lagging)\n   * vs active streams (leading). The ratio adapts based on event pressure.\n   *\n   * Call `correlate()` before `drain()`. It is not only how dynamic targets\n   * are discovered: a stream is claimable while `at < correlated_at`, and\n   * `correlate` is the only component that raises that mark (#1487), so a\n   * commit no correlate has seen is not drainable — including for static\n   * targets, which were served by a probe of the event log before. For a\n   * higher-level API that handles debouncing, correlation, and signaling\n   * automatically, use {@link settle}.\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 In tests and scripts\n   * ```typescript\n   * await app.do(\"createUser\", target, payload);\n   * await app.correlate();\n   * await app.drain();\n   * ```\n   *\n   * @example In production, prefer settle()\n   * ```typescript\n   * await app.do(\"CreateItem\", target, input);\n   * app.settle(); // debounced correlate→drain, emits \"settled\"\n   * ```\n   *\n   * @see {@link settle} for debounced correlate→drain with lifecycle events\n   * @see {@link correlate} for dynamic stream discovery\n   * @see {@link start_correlations} for automatic correlation\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    // #803: writer-only instances skip the local reaction pipeline.\n    // Return an empty Drain result so call sites that aggregate (e.g.,\n    // `settle` listeners) keep working without special-casing.\n    if (!this._drain)\n      return { fetched: [], leased: [], acked: [], blocked: [] };\n    return this._scoped(() => this._drain_all(options));\n  }\n\n  /** Arm every active lane controller (ACT-1103). */\n  private _arm_all(): void {\n    // Correlate is armed alongside the drain (#1510): a commit is exactly the\n    // event that might give a scan something to find, and without this the\n    // scan runs on every settle pass whether or not anything happened.\n    this._correlate.arm();\n    for (const c of this._drain_controllers.values()) c.arm();\n  }\n\n  /**\n   * Arm only the lane controllers whose reactions match the supplied\n   * event names (ACT-1103 selective arming). Events with any dynamic\n   * resolver fall back to `_arm_all()` via the `\"all\"` sentinel — the\n   * resolver's lane isn't known until correlate runs the function.\n   * Events with no reactions are skipped; `_event_to_lanes` doesn't\n   * carry them. Returns true when any controller was armed (used by\n   * the notify handler to decide whether to schedule a settle).\n   */\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  /** Drain every active lane controller in parallel and aggregate.\n   *\n   * Parallel — not sequential — so a slow lane's in-flight handler does\n   * not block a fast lane's claim/dispatch/ack cycle. Each controller's\n   * `claim()` is independent (filtered by lane); the store's\n   * `SKIP LOCKED` keeps cross-controller races safe. Lifecycle events\n   * (`acked`, `blocked`) may interleave by lane — listeners filter via\n   * `lease.lane`. */\n  private async _drain_all(options: DrainOptions): Promise<Drain<TEvents>> {\n    const results = await Promise.all(\n      [...this._drain_controllers.values()].map((c) => c.drain(options))\n    );\n    const fetched: Drain<TEvents>[\"fetched\"] = [];\n    const leased: Lease[] = [];\n    const acked: Lease[] = [];\n    const blocked: BlockedLease[] = [];\n    for (const r of results) {\n      fetched.push(...r.fetched);\n      leased.push(...r.leased);\n      acked.push(...r.acked);\n      blocked.push(...r.blocked);\n    }\n    return { fetched, leased, acked, blocked };\n  }\n\n  /**\n   * Discovers and registers new streams dynamically based on reaction resolvers.\n   *\n   * Correlation enables \"dynamic reactions\" where target streams are determined at runtime\n   * based on event content. For example, you might create a stats stream for each user\n   * when they perform certain actions.\n   *\n   * This method scans events matching the query and identifies new target streams based\n   * on reaction resolvers. It then registers these streams so they'll be picked up by\n   * the next drain cycle.\n   *\n   * @param query - Query filter to scan for new correlations\n   * @param query - Scan filter — see {@link Query} for fields (typically\n   *   `{ after: <event-id>, limit: <count> }`)\n   * @returns Object with newly leased streams and last scanned event ID\n   *\n   * @example Manual correlation\n   * ```typescript\n   * // Scan for new streams\n   * const { leased, last_id } = await app.correlate({ after: 0, limit: 100 });\n   * console.log(`Found ${leased.length} new streams`);\n   *\n   * // Save last_id for next scan\n   * await saveCheckpoint(last_id);\n   * ```\n   *\n   * @example Dynamic stream creation\n   * ```typescript\n   * const app = act()\n   *   .withState(User)\n   *   .withState(UserStats)\n   *   .on(\"UserLoggedIn\")\n   *     .do(async (event) => [\"incrementLoginCount\", {}])\n   *     .to((event) => ({\n   *       target: `stats-${event.stream}` // Dynamic target per user\n   *     }))\n   *   .build();\n   *\n   * // Discover stats streams as users log in\n   * await app.correlate();\n   * ```\n   *\n   * @see {@link start_correlations} for automatic periodic correlation\n   * @see {@link stop_correlations} to stop automatic correlation\n   */\n  async correlate(\n    query: Query = { after: -1, limit: 10 }\n  ): Promise<{ subscribed: number; last_id: number }> {\n    const { subscribed, last_id } = await this._correlate_scanned(query);\n    return { subscribed, last_id };\n  }\n\n  /**\n   * `correlate` plus whether the pass actually read the store (#1510).\n   *\n   * The settle loop needs that extra bit to decide whether the pass carries a\n   * circuit-breaker health signal, and a disarmed pass carries none. It stays\n   * internal rather than widening the public `correlate` return, which is\n   * charter-covered and has no use for it.\n   */\n  private async _correlate_scanned(\n    query: Query,\n    /** Honour the correlation lease — settle and the poller only (#1532). */\n    lease = false\n  ): Promise<{ subscribed: number; last_id: number; scanned: boolean }> {\n    // Writer-only instances skip dynamic stream discovery. The\n    // {subscribed, last_id} pair returns the no-op result; the\n    // checkpoint stays where it was.\n    if (!this._drain) return { subscribed: 0, last_id: -1, scanned: false };\n    return this._scoped(async () => {\n      const { subscribed, last_id, marked, scanned } =\n        await this._correlate.correlate(query, lease);\n      // Newly-subscribed streams must arm their lane controllers, same\n      // as reset/unblock: a lane worker's tick can disarm on an empty\n      // claim in the window before the subscription lands, and nothing\n      // re-arms until an unrelated commit — starving the fresh stream\n      // on an otherwise idle system.\n      //\n      // A raised mark arms for the same reason (#1488). Eligibility comes\n      // from the mark now, so a target that was already subscribed goes from\n      // \"nothing to do\" to \"claimable\" without its row being new — and a\n      // worker that disarmed on an empty claim moments earlier would sleep\n      // through it.\n      //\n      // Arming here also re-arms CORRELATE itself, which is what keeps a\n      // backlog moving: a scan that found something leaves the flag up so the\n      // next pass continues, while the scan that finds nothing takes the\n      // disarm branch and stops the loop (#1510).\n      if ((subscribed > 0 || marked > 0) && this._reactive_events.size > 0)\n        this._arm_all();\n      return { subscribed, last_id, scanned };\n    });\n  }\n\n  /**\n   * Starts automatic periodic correlation worker for discovering new streams.\n   *\n   * The correlation worker runs in the background, scanning for new events and identifying\n   * new target streams based on reaction resolvers. It maintains a sliding window that\n   * advances with each scan, ensuring all events are eventually correlated.\n   *\n   * This is useful for dynamic stream creation patterns where you don't know all streams\n   * upfront - they're discovered as events arrive.\n   *\n   * **Note:** Only one correlation worker can run at a time per Act instance.\n   *\n   * @param query - Query filter for correlation scans — see {@link Query}\n   *   (typically `{ after: -1, limit: 100 }`)\n   * @param frequency - Correlation frequency in milliseconds (default: 10000)\n   * @param callback - Optional callback invoked with newly discovered streams\n   * @returns `true` if worker started, `false` if already running\n   *\n   * @example Start automatic correlation\n   * ```typescript\n   * // Start correlation worker scanning every 5 seconds\n   * app.start_correlations(\n   *   { after: 0, limit: 100 },\n   *   5000,\n   *   (leased) => {\n   *     console.log(`Discovered ${leased.length} new streams`);\n   *   }\n   * );\n   *\n   * // Later, stop it\n   * app.stop_correlations();\n   * ```\n   *\n   * @example With checkpoint persistence\n   * ```typescript\n   * // Load last checkpoint\n   * const lastId = await loadCheckpoint();\n   *\n   * app.start_correlations(\n   *   { after: lastId, limit: 100 },\n   *   10000,\n   *   async (leased) => {\n   *     // Save checkpoint for next restart\n   *     if (leased.length) {\n   *       const maxId = Math.max(...leased.map(l => l.at));\n   *       await saveCheckpoint(maxId);\n   *     }\n   *   }\n   * );\n   * ```\n   *\n   * @see {@link correlate} for manual one-time correlation\n   * @see {@link stop_correlations} to stop the worker\n   */\n  start_correlations(\n    query: Query = {},\n    frequency = 10_000,\n    callback?: (subscribed: number) => void\n  ): boolean {\n    const started = this._correlate.start_polling(query, frequency, callback);\n    return started;\n  }\n\n  /**\n   * Stops the automatic correlation worker.\n   *\n   * Call this to stop the background correlation worker started by {@link start_correlations}.\n   * This is automatically called when the Act instance is disposed.\n   *\n   * @example\n   * ```typescript\n   * // Start correlation\n   * app.start_correlations();\n   *\n   * // Later, stop it\n   * app.stop_correlations();\n   * ```\n   *\n   * @see {@link start_correlations}\n   */\n  stop_correlations() {\n    this._correlate.stop_polling();\n    // Hand the correlation lease back rather than making the next worker\n    // wait out its expiry (#1532). Best-effort and deliberately not awaited:\n    // stopping correlations is synchronous by contract, and the fallback is\n    // the expiry that would have applied anyway.\n    // Wrapped in `_scoped` because it resolves the store through the port: a\n    // scoped Act would otherwise release against the singleton and leave its\n    // real lease held until expiry.\n    void this._scoped(() => this._correlate.release_correlation());\n  }\n\n  /**\n   * Cancels any pending or active settle cycle.\n   *\n   * @see {@link settle}\n   */\n  stop_settling() {\n    this._settle.stop();\n  }\n\n  /**\n   * Reset reaction stream watermarks and request a drain on the next\n   * `drain()` / `settle()` cycle.\n   *\n   * Use this to replay events through projections (or other reaction targets)\n   * after changing handler logic. Equivalent to calling `store().reset(streams)`\n   * directly, but also raises the orchestrator's internal \"needs drain\" flag —\n   * `store().reset(...)` alone leaves the flag untouched, so a settled app\n   * would short-circuit and skip the replay.\n   *\n   * Pair with `app.settle()` (or a single `app.drain()` for small streams).\n   * `settle()` loops correlate→drain until no progress is made, so one call\n   * fully catches up paginated streams without forcing callers to roll\n   * their own loop.\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 });   // emits \"settled\" when fully replayed\n   * ```\n   *\n   * @example Rebuild a projection (tests / scripts)\n   * ```typescript\n   * await app.reset([\"my-projection\"]);\n   * await app.drain({ eventLimit: 1000 });   // small streams: one pass is enough\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 reaches a handler (#1466).\n      // A rebuild replays from the beginning, so every event lands at or\n      // below a warm fold's head and takes its already-folded branch, which\n      // re-flushes whatever that cache holds — writing a stale row straight\n      // back out. Cleared unconditionally rather than per target: `input`\n      // may be a filter, resolving it costs a query, and the only cost of\n      // clearing a cache that did not need it is one head load per stream\n      // on the next batch.\n      for (const handler of this._batch_handlers.values())\n        (handler as ResettableBatchHandler<TEvents>)[FOLD_RESET]?.();\n      if (count > 0 && this._reactive_events.size > 0) this._arm_all();\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 raises the orchestrator's\n   * internal \"needs drain\" flag so a settled app picks up the now-free\n   * streams on the next cycle. Equivalent to calling `store().unblock(...)`\n   * directly, but `store().unblock(...)` alone leaves the flag\n   * untouched.\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 && this._reactive_events.size > 0) this._arm_all();\n      return count;\n    });\n  }\n\n  /**\n   * Atomically wipe the store and rebuild it from an async stream of\n   * committed events. The framework owns iteration, validation,\n   * `drop_snapshots` filtering, `on_progress`, and the per-call\n   * `old → new` causation remap; the adapter's {@link Store.restore}\n   * driver supplies the transaction lifecycle and per-event insert.\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 - Async stream of events in target order. Streamed\n   *   rather than buffered so multi-million-event backups don't OOM.\n   *   Each event's original `id` is used as a causation lookup key but\n   *   never written through — 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   * @returns {@link ScanResult} with `kept`, `duration_ms`, and\n   *   `dropped` per-category counters.\n   *\n   * @example Round-trip a CSV backup\n   * ```typescript\n   * async function* parseCsv(blob: string) {\n   *   for (const line of blob.split(\"\\n\").slice(1)) {\n   *     const [id, name, data, stream, version, created, meta] = parse(line);\n   *     yield {\n   *       id: +id, name, data: JSON.parse(data), stream,\n   *       version: +version, created: new Date(created),\n   *       meta: JSON.parse(meta),\n   *     };\n   *   }\n   * }\n   * const result = await app.restore(parseCsv(csvBlob), {});\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: walk the source via scan without touching any sink\n      // — same scan loop, no callback, no transaction, no capability\n      // check. Returns the counts a destructive restore would land.\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 the singleton store. Explicit `sink` lets\n      // callers route to a different EventSink (another adapter, a\n      // CsvFile, etc.) without binding the singleton.\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      await 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      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 (#723).\n   *\n   * Walks the connected store and yields per-category findings —\n   * each tagged with the remediation it suggests. Same operator-\n   * driven category as `app.close()` / `app.reset()` /\n   * `app.unblock()` / `app.blocked_streams()`: never auto-invoked by\n   * the framework; the operator decides when to run it (CI gate,\n   * scheduled job, ad-hoc forensics) and what to do with the\n   * findings.\n   *\n   * Categories are independent — pass a subset to scope the work,\n   * or omit to run everything:\n   *\n   * ```typescript\n   * // Targeted: schema drift + deprecated-event load only\n   * for await (const f of app.audit([\"schema\", \"deprecated-load\"], {\n   *   query: { created_after: lastScan },\n   *   thresholds: { deprecatedLoadShareMin: 0.10 },\n   * })) {\n   *   await escalate(f);\n   * }\n   *\n   * // Full audit, default thresholds\n   * for await (const f of app.audit()) console.log(f);\n   * ```\n   *\n   * Returns an `AsyncIterable` so callers can `break` early — the\n   * underlying store paginations respect the iterator protocol and\n   * stop cleanly. Each finding is emitted independently, so\n   * pipelining into Slack / persistence / further analysis works\n   * without buffering the full report in memory.\n   *\n   * Findings shape — see {@link AuditFinding}. The discriminated\n   * union carries enough context for the operator to act on each\n   * finding directly: stream id, event id, recommendation hints.\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  async *audit(\n    categories?: AuditCategory[],\n    options?: AuditOptions\n  ): AsyncIterable<AuditFinding> {\n    // Drive the audit generator one step at a time INSIDE `_scoped`, so the\n    // `store()` calls in its body resolve the scoped bag during lazy\n    // iteration. A plain `return audit(...)` would run the generator body in\n    // the consumer's `for await` frame, outside any scope — resolving the\n    // singleton store and auditing the wrong tenant (#1317). For a\n    // non-scoped Act `_scoped(fn)` is just `fn()`, so this is a no-op.\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   * Bulk-update scheduling priority for streams matching `filter`.\n   *\n   * Operator-grade override of the `claim()` lagging-frontier\n   * ordering (ACT-102). Useful when a long-running replay needs to\n   * jump ahead of other lagging streams, or when a no-longer-urgent\n   * job should yield slots back to the rest. Build-time priorities\n   * (set via the resolver's `priority` field) are subject to a\n   * `max()` invariant across reactions; this API ignores that and\n   * sets the priority outright on every matching row.\n   *\n   * Filter shape mirrors {@link query} / {@link Store.query_streams}:\n   * `stream` / `source` are regex by default, exact with the\n   * `*_exact` flags; `blocked` restricts to blocked or unblocked\n   * rows. **An empty filter (`{}`) updates every registered stream.**\n   *\n   * @param filter - Selection criteria (regex by default).\n   * @param priority - New priority value. Set as-is — no clamp.\n   * @returns Count of streams whose priority changed.\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   * @example Drop all audit projections to background\n   * ```typescript\n   * await app.prioritize({ source: \"^audit-\" }, -5);\n   * ```\n   *\n   * @example Reset everyone to default\n   * ```typescript\n   * await app.prioritize({}, 0);\n   * ```\n   *\n   * @see {@link Store.prioritize} for the underlying primitive\n   * @see {@link claim} for how priority biases scheduling\n   */\n  async prioritize(filter: StreamFilter, priority: number): Promise<number> {\n    return this._scoped(() => store().prioritize(filter, priority));\n  }\n\n  /**\n   * Close the books — guard, archive, truncate, and optionally restart streams.\n   *\n   * Safely removes historical events from the operational store:\n   *\n   * 1. **Correlate** — discover pending reaction targets\n   * 2. **Safety check** — skip streams with pending reactions (skipped when no reactive events)\n   * 3. **Guard** — commit `__tombstone__` with `expectedVersion` to block concurrent writes\n   * 4. **Load state** — for streams in `snapshots`, load final state while guarded (no races)\n   * 5. **Archive** — user callback per stream (abort-all on failure, streams are guarded)\n   * 6. **Truncate + seed** — atomic: delete all events, insert `__snapshot__` or `__tombstone__`\n   * 7. **Cache** — invalidate (tombstoned) or warm (restarted)\n   * 8. **Emit \"closed\"** — lifecycle event with results\n   *\n   * Targets carrying `before` take the **windowed** branch instead —\n   * close the books on a rolling window: probe the min consumer\n   * watermark (so the boundary never rises past a lagging reaction),\n   * run the archive callback against the cutoff, then prune the prefix\n   * below the closest safe `__snapshot__`. No tombstone guard (the\n   * pre-cutoff prefix is immutable), no seed, cache untouched — the\n   * stream stays live and keeps accepting actions. Requires the state\n   * to snapshot via `.snap(...)`; no qualifying snapshot ⇒ the stream\n   * lands in `skipped` (retry after the next snapshot). Windowed\n   * entries in the result echo `before` and carry the surviving\n   * boundary snapshot as `committed`.\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   * @example Close with restart (state loaded automatically after guard)\n   * ```typescript\n   * await app.close([\n   *   { stream: \"counter-1\", restart: true },\n   *   { stream: \"counter-2\" },  // tombstoned\n   * ]);\n   * ```\n   *\n   * @example Windowed close — keep the last 180 days of real events\n   * ```typescript\n   * const cutoff = new Date();\n   * cutoff.setDate(cutoff.getDate() - 180);\n   * await app.close([\n   *   {\n   *     stream: \"ledger-acme\",\n   *     before: cutoff,\n   *     archive: async () => { await archiveToS3(\"ledger-acme\", cutoff); },\n   *   },\n   * ]);\n   * ```\n   */\n  /**\n   * After a close, forget any target whose subscription row the truncate\n   * removed, so a later correlate can re-subscribe it (#1398). Restart\n   * targets keep their row, so only fully-retired streams are forgotten.\n   */\n  /**\n   * Advance correlation until the read cursor reaches `until`, and report\n   * where it landed (#1487). Used by the close cycle's safety probe, which\n   * cannot judge a subscription's pending work over events correlate has\n   * not resolved yet.\n   *\n   * Bounded on both ends: it stops as soon as a pass makes no progress (the\n   * log has no more to give), and after {@link CLOSE_CATCH_UP_PASSES}\n   * windows, so a close behind an enormous backlog degrades to skipping the\n   * stream — the documented retryable outcome — instead of scanning the\n   * whole log inside an operator call.\n   */\n  private async _catch_up_correlation(until: number): Promise<number> {\n    for (\n      let pass = 0;\n      pass < CLOSE_CATCH_UP_PASSES && this._correlate.checkpoint < until;\n      pass++\n    ) {\n      const before = this._correlate.checkpoint;\n      // Force the look: close is asking whether a tail exists, which is\n      // exactly the question the armed flag cannot answer (#1510).\n      this._correlate.arm();\n      await this.correlate({ limit: CLOSE_CATCH_UP_LIMIT });\n      if (this._correlate.checkpoint <= before) break;\n    }\n    return this._correlate.checkpoint;\n  }\n\n  /**\n   * Drop retired streams from correlate's in-process \"already subscribed\"\n   * set, so a later scan re-issues `subscribe()` for them.\n   *\n   * A tombstone seed means the stream was retired; a snapshot seed means it\n   * was restarted and is still consuming.\n   *\n   * `truncate` no longer removes the subscription row (#1527), so this is no\n   * longer repairing damage the close itself did. It still matters, because\n   * the row can disappear later: reclaiming retired subscriptions is an\n   * operator job now, and that `DELETE` can land while this process is\n   * running. Forgetting here keeps the in-process view from outliving a row\n   * an operator removed, which is the same silent-no-delivery failure #1398\n   * described — a reaction whose target is named after the stream would never\n   * be re-registered.\n   */\n  private _forget_closed_subscriptions(result: CloseResult): void {\n    const retired = [...result.truncated.entries()]\n      .filter(([, r]) => r.committed.name === TOMBSTONE_EVENT)\n      .map(([stream]) => stream);\n    if (retired.length) this._correlate.forget_subscribed(retired);\n  }\n\n  async close(targets: CloseTarget[]): Promise<CloseResult> {\n    if (!targets.length) return { truncated: new Map(), skipped: [] };\n\n    return this._scoped(async () => {\n      // Correlate first so dynamic reaction targets are discovered before\n      // the safety check examines subscription positions.\n      await this.correlate({ limit: 1000 });\n\n      // Synthesize an actor for the close transaction so user-supplied\n      // correlators can still tag tenant context / trace ids.\n      const close_actor = { id: \"$close\", name: \"close\" };\n      const result = await run_close_cycle(targets, {\n        reactive_events_size: this._reactive_events.size,\n        catch_up_correlation: (until) => this._catch_up_correlation(until),\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._with_close_lock(stream, work),\n      });\n\n      this._forget_closed_subscriptions(result);\n      this.emit(\"closed\", result);\n      return result;\n    });\n  }\n\n  /**\n   * Debounced, non-blocking correlate→drain cycle.\n   *\n   * Call this after `app.do()` (or `app.reset()`) to schedule a background\n   * drain. Multiple rapid calls within the debounce window are coalesced\n   * into a single cycle. Runs correlate→drain in a loop until a pass makes\n   * no progress — no new subscriptions, no acks, no blocks — then emits\n   * the `\"settled\"` lifecycle event. This means a single `settle()` call\n   * fully catches up paginated streams (e.g. after `reset()` on a long\n   * projection) without forcing callers to loop.\n   *\n   * @param options - Settle configuration — see {@link SettleOptions} for fields:\n   *   `debounceMs` (default 10), `correlate` (default `{ after: -1, limit: 100 }`),\n   *   `maxPasses` (default `Infinity` — kill-switch for runaway loops),\n   *   `streamLimit` (default 10), `eventLimit` (default 10),\n   *   `leaseMillis` (default 10000).\n   *\n   * @example API mutations\n   * ```typescript\n   * await app.do(\"CreateItem\", target, input);\n   * app.settle(); // non-blocking, returns immediately\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    // #803: writer-only instances skip settle entirely. The bootstrap\n    // pattern `app.on(\"committed\", () => app.settle())` keeps working —\n    // it just runs zero work on writers.\n    if (!this._drain) return;\n    this._settle.schedule(options);\n  }\n}\n","/**\n * @module build-classify\n * @category Internal\n *\n * Build-time classification of the registry + state map. The Act constructor\n * needs four 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 * - `reactive_events`    — event names with at least one reaction (drives\n *                         the drain skip-flag in `do()` and `reset()`)\n * - `event_to_state`      — event-name → owning state, for `close({restart})`\n *                         seed loading in multi-state apps\n *\n * Pure function — single pass over events + states, fully testable without\n * instantiating Act.\n *\n * @internal\n */\n\nimport type { StaticTarget } from \"../internal/index.js\";\nimport type {\n  Registry,\n  Schema,\n  SchemaRegister,\n  Schemas,\n  State,\n} from \"../types/index.js\";\n\n/**\n * Classification result. Returned by {@link classify_registry}; consumed\n * piecewise by Act's constructor.\n *\n * @internal\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 *\n * @internal\n */\nexport const ALL_LANES: unique symbol = Symbol(\"act-1103/all-lanes\");\n\n/**\n * Per-event lane fan-in (ACT-1103). 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 *\n * @internal\n */\nexport type EventLaneSet = ReadonlySet<string> | typeof ALL_LANES;\n\nexport type Classification = {\n  readonly static_targets: StaticTarget[];\n  readonly reactive_events: ReadonlySet<string>;\n  readonly event_to_state: ReadonlyMap<string, State<any, any, any>>;\n  readonly event_to_lanes: ReadonlyMap<string, EventLaneSet>;\n};\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 *\n * @internal\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 (#1325). 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 reactive_events = new Set<string>();\n  const event_to_lanes = new Map<string, EventLaneSet>();\n\n  for (const [name, register] of Object.entries(registry.events)) {\n    if (register.reactions.size > 0) reactive_events.add(name);\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        // ACT-1103 / #1325: 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 (#1583), 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        const key = `${target}|${source ?? \"\"}`;\n        const existing = statics.get(key);\n        if (!existing) {\n          statics.set(key, { stream: target, source, priority, lane });\n        } else if (priority > (existing.priority as number)) {\n          // Multiple reactions with the same (target, source) — keep the max\n          // priority so the highest-priority registrant sets the scheduling\n          // priority (mirrors subscribe-side semantics). `existing.priority`\n          // is always defined here since we always set it when inserting, but\n          // the StaticTarget type marks it optional for external consumers.\n          statics.set(key, { ...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    reactive_events,\n    event_to_state,\n    event_to_lanes,\n  };\n}\n","/**\n * @module event-versions\n * @category Internal\n *\n * Auto-deprecation of legacy event versions via the `_v<digits>` naming\n * convention (ACT-403).\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 * @internal\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 *\n * @internal\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 *\n * @internal\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. */\nexport const 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 *\n * @internal\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 * @module audit\n * @category Internal\n *\n * Operator-driven store audit (#723).\n *\n * Walks the connected store and yields per-category {@link AuditFinding}s.\n * Each category answers a different \"what should I do with this store?\"\n * question and pairs with a remediation:\n *\n *   - `schema` → fix the data model (poison events, unknown names)\n *   - `close-candidate` → `app.close([...])`\n *   - `restart-candidate` → `app.close([{stream, restart:true}, …])`\n *   - `deprecated-load` → `app.close([...])` on the heaviest carriers\n *   - `reaction-health` → `app.unblock(...)` / `app.reset(...)`\n *   - `snapshot-drift` → manual `load({snap:true})` or wait for policy\n *   - `routing-health` → restart-with-new-config to re-lane\n *   - `correlation-gaps` → fix upstream correlator misconfig\n *   - `clock-anomalies` → infra remediation (clock skew)\n *\n * ## Single-scan multiplex (efficiency contract)\n *\n * Earlier draft had each category run its own `store.query(...)`,\n * which meant N requested categories → N table walks. Bad for large\n * stores. Refactored to a pass-based design: each category is a\n * factory that returns an {@link AuditPass} with optional per-row\n * callbacks (`on_event` / `on_stream` / `on_stat`) and a `finalize` hook\n * for any second-pass work. The dispatcher determines the UNION of\n * required data sources, runs each *once*, and broadcasts each row\n * to all interested passes. Worst case: three scans total (events,\n * streams, stats) regardless of how many categories the operator\n * requested. Most categories also share state — close-candidate and\n * restart-candidate both consume the same `on_stat` stream; schema,\n * correlation-gaps, and clock-anomalies all hang off the same\n * `on_event` broadcast.\n *\n * Categories that need follow-up work (snapshot-drift's per-stream\n * snapshot lookup, correlation-gaps' orphan-id check after collecting\n * ids) do that in their `finalize` hook with their own targeted store\n * calls — keeps the shared scan path minimal.\n *\n * Isolated from orchestration internals — `act.ts` builds the\n * {@link AuditDeps} bag at `.build()` time and hands it here via\n * a one-liner. The audit module never reaches into\n * `internal/{event-sourcing,drain-cycle,settle,close-cycle}.ts`; it\n * only reads through the deps interface and the public `Store`\n * surface. Same shape as `act-tck` within the workspace — a peer of\n * orchestration, not entangled with its private mechanics.\n *\n * @internal\n */\n\nimport { SNAP_EVENT } from \"../ports.js\";\nimport type {\n  AuditCategory,\n  AuditFinding,\n  AuditOptions,\n  Committed,\n  Logger,\n  Schemas,\n  State,\n  Store,\n  StreamPosition,\n  StreamStats,\n} from \"../types/index.js\";\nimport {\n  current_version_of,\n  deprecated_event_names,\n} from \"./event-versions.js\";\nimport { pii_fields } from \"./sensitive.js\";\nimport { walk_streams } from \"./walk-streams.js\";\n\n/**\n * Snapshot of orchestrator state the audit reads. Built once at\n * `app.build()`; the audit treats it as immutable for the duration\n * of a call. The orchestrator never passes its own private maps in\n * directly — this bag is the abstraction boundary so a future\n * orchestration refactor can't accidentally entangle with audit\n * logic.\n */\nexport type AuditDeps = {\n  readonly store: () => Store;\n  readonly logger: Logger;\n  /** event-name → state that registers it (for schema validation). */\n  readonly event_to_state: ReadonlyMap<string, State<any, any, any>>;\n  /** state-name → state (for snapshot-supported check on restart-candidate). */\n  readonly states: ReadonlyMap<string, State<any, any, any>>;\n  /** Declared drain lanes (for routing-health unknown-lane). */\n  readonly declared_lanes: ReadonlySet<string>;\n  /**\n   * Event names that the registry has at least one reaction for —\n   * used by routing-health to detect \"registered but unrouted\"\n   * events. Normalized down from the internal `event_to_lanes` map\n   * (which carries lane-set details audit doesn't need).\n   */\n  readonly routed_events: ReadonlySet<string>;\n};\n\n/**\n * Defaults applied when the operator doesn't override via\n * {@link AuditOptions.thresholds}. Values land where most workloads\n * find them operationally useful — operators can tune per call.\n */\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] as const satisfies readonly AuditCategory[];\n\n/**\n * A single audit category, expressed as a stream-consumer:\n *\n * - `on_event` / `on_stream` / `on_stat` are called by the dispatcher\n *   during the shared scans. Each is optional; the dispatcher uses\n *   the presence/absence to decide which scans to run.\n * - `finalize` runs after all shared scans complete. Categories that\n *   need targeted follow-up store calls (snapshot-drift fetches the\n *   last `__snapshot__` per drifted stream; correlation-gaps cross-\n *   checks causations against the collected id set) do that here.\n * - `drain` is called last and returns the accumulated findings.\n */\ntype AuditPass = {\n  category: AuditCategory;\n  on_event?: (e: Committed<Schemas, string>) => 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/**\n * Top-level audit dispatcher. Single-scan multiplex: each requested\n * category contributes a `AuditPass`, the dispatcher determines the\n * union of required data sources (events / streams / stats), runs\n * each once, broadcasts rows, and yields per-category findings in\n * the order the categories were requested.\n *\n * Callers can `break` the iteration early — the underlying scan\n * loops have already completed by the time yield starts, so early\n * break only saves the iteration over already-collected findings.\n * (Per-row early termination during a scan isn't feasible without\n * coordination across passes; the audit is bounded by `options.query`\n * scoping rather than mid-scan cancellation.)\n */\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  // Preserve a deterministic category order (matches ALL_CATEGORIES\n  // declaration) so output ordering doesn't depend on the order\n  // operators list categories in their call.\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  // Determine scan needs. `some(...)` short-circuits — three trivial\n  // walks at worst.\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((p) => p.on_event !== undefined);\n\n  if (need_stats) {\n    // Exclude `__snapshot__` so `head` and `count` are DOMAIN figures.\n    // A snapshot is committed right after the domain event that triggered\n    // it, so without this the head of any snapshotting stream is\n    // `__snapshot__` — and every pass that gates on the head name\n    // (`startsWith(\"__\")` → \"already closed\") silently skips the stream.\n    // Same reasoning as `scan_stream_heads` in the close cycle.\n    //\n    // `__tombstone__` is deliberately NOT excluded: a tombstoned stream\n    // really is closed, and the head-name gates are what recognize it.\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, and an audit that inspects\n    // only the first page reports a false all-clear for every stream that\n    // sorts past it.\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 deps.store().query<Schemas>((event) => {\n      for (const p of passes) p.on_event?.(event);\n    }, options.query);\n  }\n\n  // Async post-processing (per-stream queries, second-pass orphan\n  // detection). Serial to avoid pool contention; categories are\n  // independent so order doesn't matter semantically.\n  for (const p of passes) await p.finalize?.(deps);\n\n  // Yield findings in requested-category order.\n  for (const p of passes) {\n    for (const f of p.drain()) yield f;\n  }\n}\n\n// =================== Pass factories ===================\n//\n// Each category is implemented as a closure-bound `AuditPass`. The\n// factory captures `deps` + relevant options + a `findings` array;\n// the returned pass exposes the per-row hooks the dispatcher calls.\n//\n// All findings are accumulated in a per-pass `findings` buffer and\n// returned from `drain()`. No yield-during-scan — that would couple\n// the pass to async iteration semantics and prevent the shared-scan\n// multiplexing.\n\n/**\n * `schema` — every event in the audit window is parsed against the\n * Zod schema the registry currently declares for its name. Two\n * failure modes: `unknown_event_name` (event sits on disk, registry\n * has no entry) and `schema_validation_failed` (event matches a\n * known name but fails the current Zod schema).\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        // Skip framework markers — they're not user-declared.\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 are split out of `data` into the pii sidecar at\n      // commit — their absence from `data` is correct, not corruption. The\n      // pass reads raw stored rows, so parsing against the full schema\n      // reported every healthy sensitive event as invalid, one finding per\n      // event, burying the real ones (#1424). Omit those keys instead; the\n      // rest of the payload is still validated.\n      const sensitive = pii_fields(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 (e.g. a union) whose variants carry pii —\n          // the split keys can't be masked off, so any parse here is a\n          // guaranteed false positive. Skip rather than cry wolf.\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/**\n * `deprecated-load` — workspace-wide event-name histogram classified\n * by the framework's `_v<digits>` rule. Built from the shared `on_stat`\n * stream — accumulates per-name + per-stream totals in memory, then\n * emits one finding per deprecated event above the threshold during\n * `drain`.\n */\n/**\n * Per-state deprecation classification — mirrors the builder/registry\n * (`registry.deprecated_events(state_name)`), which group `_v<n>` families\n * strictly within one state's own event set. Classifying over the global\n * event-name union instead would conflate same-stem events across\n * unrelated states (a false-positive migration finding) and even throw on\n * a cross-state leading-zero version collision the builder accepted (#1310).\n * Returns a map of deprecated event name → its current (highest) sibling.\n */\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      // `current_version_of` is guaranteed defined for a deprecated name\n      // within its own state's family.\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      // Contract: query_stats was called with `{names: true}`,\n      // so adapter populates `names` with positive integer counts.\n      // No runtime fallback needed.\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      // Per-state deprecation classification (not on-disk-driven, and not\n      // over the global event-name union — see #1310).\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        // `classify_deprecated_by_state` maps every deprecated name to its\n        // current (highest-version) sibling within the same state.\n        const current_version = deprecated.get(name)!;\n        // per_stream is populated in lockstep with totals — name is guaranteed present.\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\n/**\n * `close-candidate` — flags streams ripe for `app.close(...)`. Two\n * flavours: `idle` (head older than `idle_days`) and `terminal` (head\n * event name in operator-supplied `terminal_events` list). Each\n * finding carries `restart_supported` (state has `.snap()`).\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      // All in-tree adapters return `created` as Date; the Date\n      // constructor passes Date instances through unchanged, so a\n      // single call shape works regardless.\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\n/**\n * `restart-candidate` — streams above `event_count_for_restart` whose\n * state declares `.snap()`. Reads from the shared `on_stat` stream.\n */\nconst make_restart_candidate_pass: PassFactory = (deps, options) => {\n  const threshold = options.thresholds?.restart_min ?? DEFAULTS.restart_min;\n  // Resolved in finalize — the shared stat scan excludes `__snapshot__`\n  // (so heads and counts are domain figures), which means the snapshot\n  // tally isn't in `names`. Candidates are streams above `restart_min`,\n  // so this is a handful of targeted counts, not a second table walk.\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      // `count` always populated — query_stats is called with the flag set.\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          }\n        );\n        findings.push({\n          category: \"restart-candidate\",\n          stream,\n          count,\n          snaps,\n        });\n      }\n    },\n    drain: () => findings,\n  };\n};\n\n/**\n * `reaction-health` — surfaces blocked / near-block / stuck-backoff\n * streams. Reads from the shared `on_stream` stream-positions\n * broadcast.\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\n/**\n * `snapshot-drift` — buffers candidate streams from the shared\n * `on_stat` pass (skipping non-snap states + tombstoned heads), then\n * does targeted per-stream lookups in `finalize` to find the last\n * `__snapshot__` event id and count events past it.\n */\nconst make_snapshot_drift_pass: PassFactory = (deps, options) => {\n  const drift_min = options.thresholds?.drift_min ?? DEFAULTS.drift_min;\n  // Streams the workspace pass identifies as drift candidates —\n  // resolved in finalize with per-stream queries.\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      // restart_is_supported() already filters out framework markers\n      // (__snapshot__, __tombstone__) — neither name appears in any\n      // user state's events map, so the snap check rejects them.\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 every other\n        // pass sees domain heads, which means the snapshot count isn't\n        // in `names` — resolve it from this targeted lookup instead. A\n        // stream with no snapshot yields nothing here and keeps\n        // `events_since_snap = total`, the same answer as before.\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\n/**\n * `routing-health` — `unknown-lane` from the streams-table pass +\n * `unrouted` from the stats pass. Reads from BOTH shared streams.\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\n/**\n * `correlation-gaps` — collects ids + parent_ids during the shared\n * event pass; flags orphans in `drain`. No second store walk — the\n * id-set + the (id, parent) buffer are both populated in one pass.\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      if (parent_id !== undefined) {\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\n/**\n * `clock-anomalies` — flags future timestamps + per-stream out-of-\n * order `created`. Single pass, per-stream \"last seen\" state in a\n * Map. Cheap.\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      // `created` is a Date instance per the Store contract.\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\n/** Does the stream's owning state declare a `.snap()` reducer? */\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/** Factory registry — pass-creation indexed by category name. */\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};\n","/**\n * @module autoclose-policy\n * @category Internal\n *\n * Declarative close-policy options consumed by `.autocloses({...})`\n * (#838 / epic #802). Three optional fields cover the three\n * operational pressure points every real close policy traces back to:\n *\n *   - `after`   — time / compliance (\"autocloses **after** N days\")\n *   - `is`      — domain lifecycle (\"autocloses ... **is** Resolved\")\n *   - `reaches` — resource (\"autocloses ... **reaches** 10k events\")\n *\n * Top-level fields combine with **AND** semantics. This captures the\n * common cooldown-after-terminal pattern that runs through almost\n * every business app — *\"close 90 days after `Resolved`\"*, *\"close 14\n * days after `Delivered`\"*, *\"close 30 days after a GDPR deletion\n * request\"*. All conditions must hold for the cycle to truncate.\n *\n * A separate `or: {...}` block opens an alternative path: when\n * present, the policy fires if **either** the top-level AND group\n * matches **or** any field inside `or` matches. Use it for safety\n * nets — *\"close (Resolved AND aged 90 days) OR if event count\n * reaches 10k\"*. The two-axis split mirrors the two ways close\n * policies appear in practice: primary close logic (AND-shaped) and\n * defensive backstops (OR-shaped).\n *\n * The state builder's `.autocloses(...)` overload distinguishes\n * function (predicate) from object (policy) and routes the latter\n * through {@link compile_autoclose_policy}, which validates via\n * {@link AutoclosePolicySchema} and returns the compiled predicate.\n * Operators with custom needs (per-stream metadata, multi-branch\n * AND/OR like \"(`Resolved` + 90d) OR (`Cancelled` + 30d)\") keep the\n * function form; the declarative form covers the 90% case.\n *\n * Validation runs at the builder call (`act().build()` time), so\n * misconfiguration — empty bag, sub-1 `reaches`, sub-minute `after`,\n * empty `is`, empty `or`, nested `or` inside `or`, unknown keys —\n * throws at build, not on the first cycle tick.\n *\n * @internal\n */\n\nimport { z } from \"zod\";\nimport type { AutoclosePredicate, Schemas } 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`. @internal */\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. @internal */\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 *\n * @internal\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 *\n * @internal\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-schema standard (CLAUDE.md\n * \"Config-validation schemas\") — 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 *\n * @internal\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  );\n\n/**\n * Declarative close-policy options consumed by `.autocloses({...})`.\n * Top-level fields are AND-combined; the optional `or` block opens an\n * alternative OR-path. Omitted fields contribute nothing — they do\n * not mean \"match everything.\"\n *\n * @property after - Close when `head.created` is at least the resolved\n *   window in the past. Days are the close surface's only unit;\n *   fractional `days` cover sub-day cooldowns (`{ days: 1/24 }` is one\n *   hour) without introducing another denomination.\n * @property is - Close when `head.name` matches. String for the\n *   single-terminal-event case (the most common); `readonly string[]`\n *   for multi-terminal states (`Order: Shipped | Delivered |\n *   Cancelled`).\n * @property reaches - Close when the stream's event count is `>= N`\n *   (inclusive — fires the moment the threshold is reached).\n * @property or - Alternative OR-path. When present, the policy fires\n *   if EITHER the top-level AND group matches OR any field inside\n *   `or` matches. Used for safety-net backstops layered onto a\n *   primary cooldown policy (e.g. *\"(Resolved AND 90 days) OR reaches\n *   10k\"*). Nested `or` inside `or` rejects at build time.\n * @property keep - Rolling-window retention (#1011), **independent** of\n *   the terminate fields: while the stream stays open, prune events\n *   older than `now − keep` behind the closest safe snapshot via a\n *   windowed close. Does not participate in the AND group or the `or`\n *   block — a policy may terminate, prune, or both. Requires\n *   `.snap(...)` earlier in the builder chain (type-gated) and a\n *   window of at least one day — the close cycle is low-cadence\n *   housekeeping, never sub-day realtime.\n */\nexport type AutoclosePolicy = z.infer<typeof AutoclosePolicySchema>;\n\n/** Compile a single `after` field into its predicate slice. @internal */\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. @internal */\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. @internal */\nfunction compile_reaches(\n  reaches: NonNullable<AutoclosePolicy[\"reaches\"]>\n): AutoclosePredicate<Schemas> {\n  return (_stream, _head, count) => count >= reaches;\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 *\n * @internal\n */\n/**\n * The smallest `after` window (in days) anywhere in a policy — across\n * the top-level `after` and the `or.after` block — or `undefined` when\n * the policy has no time component.\n *\n * The synthesized autoclose reaction (#1090) uses this to decide how to\n * wait: a policy with an `after` defers its re-check to `head.created`\n * plus this many days (the earliest its time gate could open); a policy\n * without one (`is` / `reaches` only) has no time gate, so the reaction\n * just waits for the next event to re-trigger rather than parking on a\n * due-time. Conservative — the min across branches never defers past\n * the soonest a branch could fire.\n *\n * @internal\n */\nexport function policy_min_after_days(\n  options: AutoclosePolicy\n): number | undefined {\n  const parsed = AutoclosePolicySchema.parse(options);\n  const windows: number[] = [];\n  if (parsed.after) windows.push(parsed.after.days);\n  if (parsed.or?.after) windows.push(parsed.or.after.days);\n  return windows.length ? Math.min(...windows) : undefined;\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 *\n * @internal\n */\nexport function policy_keep_days(options: AutoclosePolicy): number | undefined {\n  const parsed = AutoclosePolicySchema.parse(options);\n  return parsed.keep?.days;\n}\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 * @module autoclose-window\n * @category Internal\n *\n * Off-hours window math for autoclose — hour-in-zone, DST-gap handling, and\n * \"next time the window opens\". The autoclose **config** (defaults, schema,\n * resolver) lives in `./config.js`, the single home for builder-facing config\n * bags; this module is the runtime window logic those knobs drive.\n *\n * @internal\n */\n\nimport type { AutocloseConfig } from \"./config.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 *\n * @internal\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 *\n * @internal\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 *\n * @internal\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 *\n * @internal\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 pre-#1175 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 *\n * @internal\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.\n    const boundary = new Date(\n      candidate.getTime() - (candidate.getTime() % 3_600_000)\n    );\n    if (is_dst_gap_open(boundary, window.timeZone, window.start))\n      return boundary;\n  }\n  return new Date(start_ms + 86_400_000);\n}\n","/**\n * @module close-signal\n * @category Internal\n *\n * The control-flow signal a reaction handler throws to *close* a stream\n * (#1090). Like {@link \"defer-signal\".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 *\n * @internal\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 (#1011): 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  constructor(opts?: {\n    stream?: string;\n    archive?: () => Promise<void>;\n    at?: number;\n    before?: 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  }\n}\n","/**\n * @module defer-signal\n * @category Internal\n *\n * The control-flow signal a reaction handler throws to *defer* itself\n * (#1090, #1091). Unlike an error, a defer is not a failure: the dispatcher\n * ({@link \"reaction-builder\".build_handle}) catches it and produces a\n * `HandleResult.defer` — the triggering events stay pending (watermark not\n * advanced), `retry` is not bumped, and the drain re-visits the stream at the\n * resolved due-time.\n *\n * `DeferSignal` is the **imperative escape hatch** and is re-exported from the\n * package root, so reaction code can throw it directly when a static\n * `.defer(when)` step isn't expressive enough (a deadline computed from loaded\n * state, say). It carries the *unresolved* {@link DeferWhen}; the dispatcher\n * resolves it against the triggering event it is already dispatching (via\n * `resolve_defer_at`), which is what anchors `{ after }` and the `at` function\n * form to that event and keeps the due-time derivable. Fully dynamic times go\n * through `{ at: someDate }`.\n *\n * Modeled as an `Error` subclass — like `NonRetryableError` — so it rides the\n * existing `try/catch` in the handler loop instead of needing a separate\n * return channel through every dispatcher signature. The compiled autoclose\n * reaction throws the same signal.\n */\nimport type { DeferWhen } from \"../types/index.js\";\n\nexport class DeferSignal extends Error {\n  /**\n   * The unresolved schedule. The dispatcher turns this into an absolute\n   * due-time by resolving it against the triggering event.\n   */\n  readonly when: DeferWhen;\n\n  constructor(when: DeferWhen) {\n    super(\"reaction deferred\");\n    this.name = \"DeferSignal\";\n    this.when = when;\n  }\n}\n","/**\n * @module autoclose-reaction\n * @category Internal\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 * @internal\n */\n\nimport { SNAP_EVENT, store, TOMBSTONE_EVENT } from \"../ports.js\";\nimport type {\n  Reaction,\n  Registry,\n  SchemaRegister,\n  Schemas,\n  State,\n} 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 { CloseSignal } from \"./close-signal.js\";\nimport type { AutocloseConfig } from \"./config.js\";\nimport { DeferSignal } from \"./defer-signal.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 resolved\n * The reactions 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` (#1615).\n *\n * @internal\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 (#1615).\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_days = st.autoclose_after_days;\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      resolver: (e) => ({\n        target: `${AUTOCLOSE_TARGET_PREFIX}${e.stream}`,\n        source: e.stream,\n      }),\n      // Never block on autoclose: a transient query/store error should retry,\n      // not quarantine the synthetic stream.\n      options: { blockOnError: false, maxRetries: 3 },\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 (#1615).\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 (#1356) — 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            throw new CloseSignal({\n              stream: aggregate,\n              before: cutoff,\n              archive: archiver\n                ? () => archiver(aggregate, head, cutoff)\n                : undefined,\n              at: head.id,\n            });\n        }\n        // Not eligible yet: park on the earliest derivable due-time — the\n        // day the 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        if (after_days !== undefined)\n          dues.push(days_after(head.created, after_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, #1330). 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 * @module backoff\n * @category Internal\n *\n * Per-reaction retry backoff delay computation. Pure function — keeps\n * `DrainController` and `reactions._finalize` testable in isolation.\n *\n * @internal\n */\n\nimport type { BackoffOptions } from \"../types/action.js\";\n\n// The `BackoffOptions` config schema + resolver live in `./config.ts` (the\n// single home for every builder-facing config bag). This module keeps only\n// the runtime delay math, which stays hot-path and dependency-free.\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 * @module internal/circuit-breaker\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 { CircuitBreakerConfig } from \"./config.js\";\n\n/** Circuit breaker state. */\nexport type CircuitState = \"closed\" | \"open\" | \"half-open\";\n\n// The circuit-breaker config schema, defaults, and resolver live in\n// `./config.js` (the single home for builder-facing config bags). This\n// module keeps only the state machine that consumes the resolved config.\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 breaker opens (and again on each\n   * re-open). The orchestrator wires it to re-attempt a drain — so recovery\n   * is automatic even on the 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  /** 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   * On opening, schedules the `on_retry` wake so recovery is automatic;\n   * always surfaces the failure via `on_error`.\n   */\n  failed(now: number, error?: unknown): CircuitState {\n    const circuit = this._advance(now);\n    if (circuit === \"open\") 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  /**\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   */\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 * @module close-cycle\n * @category Internal\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 * The Act orchestrator owns lifecycle (correlate gate, emit(\"closed\")) and\n * the registry-derived inputs (reactive-event count, event→state map). All\n * sequential phase work between those state touches lives here.\n *\n * @internal\n */\n\nimport { cache, SNAP_EVENT, store, TOMBSTONE_EVENT } from \"../ports.js\";\nimport type {\n  CloseResult,\n  CloseTarget,\n  Logger,\n  Schema,\n  State,\n} from \"../types/index.js\";\nimport type { EsOps } from \"./event-sourcing.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 *\n * @internal\n */\nexport type CloseCycleDeps = {\n  readonly reactive_events_size: number;\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  /**\n   * Advance correlation to at least `until` (an event id) and return how\n   * far it actually got (#1487).\n   *\n   * The safety probe asks each subscription whether it has unconsumed\n   * work, which is only a fair question about events correlate has already\n   * resolved. An event past the read cursor has raised no mark yet, so\n   * every reader answers \"caught up\" about it — including a reader that\n   * does not exist yet, because the subscription a dynamic resolver would\n   * create is itself a product of correlating that event.\n   *\n   * Refusing to close is the wrong answer: the autoclose path fires *from*\n   * the event that reaches the terminal state, so its own trigger is\n   * routinely uncorrelated, and a retired stream gets no further commits to\n   * retry with. So the cycle makes the precondition true instead — it\n   * correlates the tail, then decides. Whatever remains above the cursor\n   * afterwards is held back as pending.\n   */\n  readonly catch_up_correlation: (until: number) => Promise<number>;\n  /**\n   * Per-stream critical section (#1222). The windowed branch is\n   * deliberately guard-free at the store level — a past cutoff makes the\n   * boundary immutable, so a concurrent append can never race the prune.\n   * But that assumes a *single* closer per stream. A manual\n   * `app.close([{stream, before}])` runs `run_close_cycle` directly,\n   * bypassing the `__autoclose__:X` lease that would otherwise exclude a\n   * concurrent autoclose windowed close, so both closers can archive the\n   * same prefix — a double S3 upload / double JSONL append. This runs the\n   * given work under a process-local per-stream lock so the two closers\n   * serialize; the second sees the already-pruned prefix and skips its\n   * archive. Provided by the Act orchestrator (shared across `app.close`\n   * and the drain's `on_close`); defaults to identity (no serialization)\n   * when the cycle is exercised in isolation.\n   */\n  readonly with_stream_lock?: <T>(\n    stream: string,\n    work: () => Promise<T>\n  ) => Promise<T>;\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 *\n * @internal\n */\nexport const SAFETY_PROBE_PAGE_SIZE = 1000;\n\n/**\n * Per-stream scan result: latest non-tombstone domain event metadata.\n * `last_event_name` is always defined — the scan filters tombstones in the\n * callback and queries without `with_snaps`, so any event reaching the\n * callback is a domain event whose name we capture alongside id/version.\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 (#1389).\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 *\n * @internal\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 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. Reject restart targets whose owning state carries sensitive\n  // fields, BEFORE anything is written. The seed load in phase 4 is\n  // actorless, so every `sensitive()` field would fold to the redaction\n  // sentinel and the truncate would then delete the originals — and\n  // loading privileged instead would persist plaintext into\n  // `__snapshot__.data`, which `forget_pii` cannot reach (the reason\n  // `.snap()` is rejected at build time for these states). Such a stream\n  // cannot be restarted at all, so it must not be closed either: the\n  // caller asked to keep the aggregate alive, and tombstoning it instead\n  // would be a strictly more destructive outcome than the one requested.\n  // It lands in `skipped`, the established channel for \"couldn't do this\n  // one\", with nothing mutated.\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_events_size,\n    skipped,\n    deps.probe_page_size ?? SAFETY_PROBE_PAGE_SIZE,\n    deps.catch_up_correlation\n  );\n  if (!safe.length) return { truncated: windowed_result, skipped };\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 — see ACT-404.\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 { truncated: windowed_result, skipped };\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  // 6. Truncate + seed: atomic per-store transaction\n  const truncated = await truncate_and_warm_cache(\n    guarded,\n    seed_states,\n    guard_events,\n    deps.correlation\n  );\n\n  for (const [stream, entry] of windowed_result) truncated.set(stream, entry);\n  return { truncated, skipped };\n}\n\n// ---------------------------------------------------------------------------\n// Windowed branch — prune the prefix behind an existing snapshot\n// ---------------------------------------------------------------------------\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 *\n * @internal\n */\nasync function run_windowed_closes(\n  windowed: CloseTarget[],\n  deps: CloseCycleDeps,\n  skipped: string[]\n): Promise<CloseResult[\"truncated\"]> {\n  // 1. Safety probe: min consumer watermark per stream. Skipped entirely\n  // when the app has no reactions — nothing can lag.\n  //\n  // The cap asks each consumer \"how far is it safe to prune?\", and a\n  // watermark alone stopped answering that when correlate became the producer\n  // of the work mark (#1520). A subscription advances only over events that\n  // resolve to it, so a reaction covering a subset of a state's events sits\n  // permanently below the head with nothing pending — and capped the prune at\n  // its frozen watermark, which for a retention window means pruning almost\n  // nothing, every time, with no error and no `skipped` entry to explain it.\n  //\n  // A caught-up consumer is instead capped at the correlate checkpoint. Not\n  // at infinity: events above the checkpoint have not been resolved yet, so a\n  // mark for them may still be coming, and pruning past it could delete work\n  // a consumer is about to be told about. Catching up first makes that bound\n  // as generous as it can honestly be.\n  const checkpoint =\n    deps.reactive_events_size > 0\n      ? await deps.catch_up_correlation(Number.MAX_SAFE_INTEGER)\n      : -1;\n  const min_at =\n    deps.reactive_events_size > 0\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 a process-local lock (#1222): probe the\n  // boundary, archive against intact history only when the prune would\n  // actually delete a prefix, then truncate. Serialization + the\n  // \"prune is non-empty\" gate together make the archive fire at most\n  // once per pruned range when a manual `app.close` races an autoclose\n  // windowed close for the same stream — the second closer, run behind\n  // the lock, sees the already-pruned prefix (boundary is now the\n  // earliest event) and skips its archive. Each stream is independent,\n  // so `truncate` is called per stream inside its own lock rather than\n  // once for the batch; a windowed truncate touches only its own stream.\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      // Boundary probe: will a windowed truncate prune anything? The\n      // store deletes events with `id < boundary.id`, where `boundary`\n      // is the latest `__snapshot__` with `created < before` (and, when\n      // capped, `id <= max_id`). No such prefix ⇒ archive is skipped and\n      // the stream is reported skipped, exactly 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 (#1222).\n *\n * @internal\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 *\n * @internal\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 source_regex = new Map<string, RegExp>();\n  const get_regex = (source: string): RegExp => {\n    let re = source_regex.get(source);\n    if (!re) {\n      re = new RegExp(source);\n      source_regex.set(source, re);\n    }\n    return re;\n  };\n\n  let after: string | undefined;\n  for (;;) {\n    let last: string | undefined;\n    const { count } = await store().query_streams(\n      (position) => {\n        last = position.stream;\n        const source_re = position.source\n          ? get_regex(position.source)\n          : undefined;\n        // How far this consumer permits a prune. A row with unconsumed work\n        // caps at its watermark, as it always did. A row that has consumed\n        // everything marked for it caps at the correlate checkpoint instead —\n        // its watermark says nothing about safety, only about which event\n        // types it happens to handle. An unmarked row keeps the conservative\n        // watermark cap, matching how it is read everywhere else until every\n        // install has converted.\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 (!source_re || source_re.test(stream)) {\n            const prev = min_at.get(stream);\n            if (prev === undefined || cap < prev) min_at.set(stream, cap);\n          }\n        }\n      },\n      { after, limit: page_size, source_matches: streams }\n    );\n    if (count < page_size) break;\n    after = last;\n  }\n  return min_at;\n}\n\n// ---------------------------------------------------------------------------\n// Phase 1 — scan stream heads\n// ---------------------------------------------------------------------------\n\nasync function scan_stream_heads(\n  streams: string[]\n): Promise<Map<string, StreamHead>> {\n  // query_stats returns the latest non-snap event per stream (heads-only\n  // cheap path, indexed). Streams whose latest non-snap event is a tombstone\n  // are filtered out in the loop — we don't want to re-tombstone an\n  // already-closed stream. Streams with no events (or only snap/tombstone\n  // events filtered out) are absent from the result map entirely.\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  // (#1389). `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's optimistic lock must expect the stream's ACTUAL current\n  // version, which is one higher when a `__snapshot__` trails the domain head\n  // — `snap()` commits it into the next version slot (event-sourcing.ts). The\n  // domain head above still drives `max_id` (the safety probe: a subscription\n  // advances its watermark on domain events, never snapshots) and\n  // `last_event_name` (the restart-seed owner lookup). Only the guard version\n  // needs the true head, so a second heads-only pass reads it with snapshots\n  // included. Without this, a terminal commit that crossed a `.snap()`\n  // boundary makes the guard expect a stale version and skip the close (#1356).\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// ---------------------------------------------------------------------------\n// Phase 2 — partition by safety\n// ---------------------------------------------------------------------------\n\nasync function partition_by_safety(\n  stream_info: Map<string, StreamHead>,\n  reactive_events_size: number,\n  skipped: string[],\n  page_size: number,\n  catch_up_correlation: (until: number) => Promise<number>\n): Promise<string[]> {\n  if (reactive_events_size === 0) return [...stream_info.keys()];\n\n  // Correlate the tail first (#1487). A head past the read cursor has\n  // raised no mark, so the probe below would read every reader as caught\n  // up on it — and the reader that needs it may not even be subscribed\n  // yet. Catching up both raises the marks and creates those subscriptions,\n  // so the probe answers about the real state of the log. Anything still\n  // above the cursor afterwards (the log outran us) 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  // Read-only probe: query_streams returns subscription positions without\n  // leasing or mutating retry state.\n  //\n  // The stored `source` on a subscription may be a literal stream name or\n  // a pattern (e.g. `^(A|B)$`); this probe matches it as a regex against\n  // close-target names either way — a literal regex-matches itself, and a\n  // pattern matches the streams it claims for. Any metacharacter\n  // over-match only widens the pending set — the conservative direction\n  // for a safety probe. Compiled patterns are cached because dynamic\n  // reactions commonly produce many subscriptions sharing one source, so\n  // the callback fires repeatedly with the same `source`.\n  const pending_set = new Set<string>();\n  const source_regex = new Map<string, RegExp>();\n  const get_regex = (source: string): RegExp => {\n    let re = source_regex.get(source);\n    if (!re) {\n      re = new RegExp(source);\n      source_regex.set(source, re);\n    }\n    return re;\n  };\n\n  // `source_matches` narrows the probe server-side to subscriptions that\n  // could consume from a stream we're closing — a best-effort hint, so\n  // the per-position source/target re-check below still runs and keeps\n  // the result correct even when a store returns a superset.\n  const targets = [...stream_info.keys()];\n\n  // Keyset-paginate the (narrowed) subscriptions on the `after` cursor —\n  // `query_streams` caps each call at `limit` rows, so every page is\n  // inspected until a short page signals the last one. A lagging reaction\n  // marks its close target pending regardless of how far its subscription\n  // sorts past the first page.\n  let after: string | undefined;\n  for (;;) {\n    let last: string | undefined;\n    const { count } = await store().query_streams(\n      (position) => {\n        last = position.stream;\n        const source_re = position.source\n          ? get_regex(position.source)\n          : undefined;\n        // \"Behind the head\" stopped meaning \"has work to do\" when correlate\n        // became the producer of the work mark (#1487): a subscription's\n        // watermark advances only over events that resolve to it, so a\n        // consumer of two of a state's ten event types sits permanently below\n        // a head it has no reaction for. Asking the row the same question\n        // `claim` asks keeps the guard honest — and keeps close from skipping\n        // every such stream forever.\n        //\n        // An unmarked row is not pending, and that is now definitional rather\n        // than conservative (#1488): `claim` will never serve it either, so\n        // there is no consumer to wait for. The catch-up above is what makes\n        // the reading safe — any mark that was owed has landed by here.\n        const has_work =\n          position.correlated_at !== undefined &&\n          position.at < position.correlated_at;\n        if (!has_work) return;\n        for (const [stream, info] of stream_info) {\n          if (\n            (!source_re || source_re.test(stream)) &&\n            position.at < info.max_id\n          ) {\n            pending_set.add(stream);\n          }\n        }\n      },\n      { after, limit: page_size, source_matches: targets }\n    );\n    if (count < page_size) break;\n    after = last;\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// ---------------------------------------------------------------------------\n// Phase 3 — guard with tombstones\n// ---------------------------------------------------------------------------\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// ---------------------------------------------------------------------------\n// Phase 4 — load restart seeds\n// ---------------------------------------------------------------------------\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// ---------------------------------------------------------------------------\n// Phase 5 — archive callbacks\n// ---------------------------------------------------------------------------\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// ---------------------------------------------------------------------------\n// Phase 6 — atomic truncate + cache warm\n// ---------------------------------------------------------------------------\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 * @module internal/config\n * @category Internal\n *\n * **The single home for every builder-facing config bag in act-core.** Any\n * options object an operator hands to `act().build()`, a builder method\n * (`.on(...)`, `.do(...)`, `.withLane(...)`), or a runtime cycle\n * (`drain(...)` / `settle(...)`) is validated here with Zod — never with a\n * hand-written `if (x < min) throw` ladder — so misconfiguration surfaces as\n * a `ZodError` at the entry point, not as `NaN` arithmetic on the first cycle\n * tick.\n *\n * Layout: one section per bag, each with its `DEFAULT_*` constants, an\n * internal `<Type>OptionsSchema`, an inferred `<Type>Config`, and a\n * `resolve<Type>Config(options): <Type>Config`. The schema is never\n * re-exported — the public surface is the inferred type + resolver.\n *\n * Index of bags owned here:\n * - **Backoff** — retry pacing (`BackoffOptions`), nested in reaction/action.\n * - **Reaction** — `.do(handler, options)` (`blockOnError` / `maxRetries` / `backoff`).\n * - **Action** — `.on(entry, options)` (`maxRetries` / `backoff`).\n * - **Lane** — `.withLane({...})` (`leaseMillis` / `streamLimit` / `cycleMs`).\n * - **Drain / Settle** — `drain(...)` / `settle(...)` runtime knobs.\n * - **Autoclose** — the `.autocloses` / `ActOptions` autoclose knobs (+ window).\n * - **CircuitBreaker** — the store-op breaker on `ActOptions`.\n * - **Fold** — `projection(...).of(...)` batch-fold knobs.\n *\n * Sibling env/package config (`config()`, `NODE_ENV`, log level) lives in the\n * public `../config.ts` — a different concern (process environment, not\n * builder input). The `@rotorsoft/act-http` transport bags (`SseOptions`,\n * `OpenAPIOptions`) live in that package; core cannot own another package's\n * surface.\n *\n * Validation philosophy: reject only what is genuinely broken — `NaN`,\n * `±Infinity` (Zod 4's `z.number()` rejects both by default), and negatives\n * where nonsensical. A value that works today is never newly rejected. The\n * real strictness lands on `maxRetries` and `backoff`, the knobs whose bad\n * values silently corrupt the poison-quarantine and retry-loop-exit gates.\n *\n * @internal\n */\n\nimport { z } from \"zod\";\nimport type { ActOptions } from \"../act.js\";\nimport type {\n  ActionOptions,\n  BackoffOptions,\n  DrainOptions,\n  FoldOptions,\n  LaneConfig,\n  ReactionOptions,\n  SettleOptions,\n  ShutdownOptions,\n} from \"../types/index.js\";\n\n// ---------------------------------------------------------------------------\n// Backoff — retry pacing. Nested inside the reaction/action bags below; also\n// resolvable on its own (`resolveBackoffConfig`) for direct callers.\n// ---------------------------------------------------------------------------\n\n/**\n * Rejects an off-union `strategy`, a non-finite/negative `baseMs`, or a\n * non-finite/non-positive `maxMs` (ACT-1269). Zod 4's `z.number()` rejects\n * `NaN`/`±Infinity` by default, so `.min(0)` / `.gt(0)` also close the\n * non-finite gap. No `maxMs >= baseMs` constraint — a sub-`baseMs` cap on\n * `exponential` is documented behavior, not an error.\n * @internal\n */\nconst BackoffOptionsSchema = z.object({\n  strategy: z.enum([\"fixed\", \"linear\", \"exponential\"]),\n  baseMs: z.number().min(0),\n  maxMs: z.number().gt(0).optional(),\n  jitter: z.boolean().optional(),\n});\n\n/** Validate a backoff bag, or pass `undefined` through. Throws `ZodError`. */\nexport function resolveBackoffConfig(\n  options: BackoffOptions | undefined\n): BackoffOptions | undefined {\n  return options === undefined\n    ? undefined\n    : BackoffOptionsSchema.parse(options);\n}\n\n// ---------------------------------------------------------------------------\n// Reaction — `.do(handler, options)`. `maxRetries` gates the poison-quarantine\n// decision (`retry >= maxRetries`), so a `NaN` here silently disables\n// `blockOnError` (a poison message retries forever). Validate the whole bag.\n// ---------------------------------------------------------------------------\n\nconst ReactionOptionsSchema = z.object({\n  blockOnError: z.boolean(),\n  maxRetries: z.number().int().min(0),\n  backoff: BackoffOptionsSchema.optional(),\n});\n\n/** Resolved reaction options. */\nexport type ReactionConfig = z.infer<typeof ReactionOptionsSchema>;\n\n/** Validate a fully-defaulted reaction options bag. Throws `ZodError`. */\nexport function resolveReactionConfig(\n  options: ReactionOptions\n): ReactionConfig {\n  return ReactionOptionsSchema.parse(options);\n}\n\n// ---------------------------------------------------------------------------\n// Action — `.on(entry, options)`. `maxRetries` gates the command retry loop's\n// exit (`attempt >= maxRetries`), so a `NaN` here can spin the loop forever on\n// a contended stream. All fields optional (the argument itself is optional).\n// ---------------------------------------------------------------------------\n\nconst ActionOptionsSchema = z.object({\n  maxRetries: z.number().int().min(0).optional(),\n  backoff: BackoffOptionsSchema.optional(),\n});\n\n/** Resolved action options. */\nexport type ActionConfig = z.infer<typeof ActionOptionsSchema>;\n\n/** Validate an action options bag. Throws `ZodError`. */\nexport function resolveActionConfig(options: ActionOptions): ActionConfig {\n  return ActionOptionsSchema.parse(options);\n}\n\n// ---------------------------------------------------------------------------\n// Lane — `.withLane({...})`. Per-lane overrides of the drain budget. Time\n// knobs (`leaseMillis` / `cycleMs`) accept any non-negative ms; `streamLimit`\n// is an integer count. Reject NaN/Infinity/negative; allow 0 (as today).\n// ---------------------------------------------------------------------------\n\nconst LaneConfigSchema = z.object({\n  name: z.string().min(1),\n  leaseMillis: z.number().min(0).optional(),\n  streamLimit: z.number().int().min(0).optional(),\n  cycleMs: z.number().min(0).optional(),\n});\n\n/** Validate a lane config. Throws `ZodError`. Returns the input shape. */\nexport function resolveLaneConfig<TName extends string>(\n  options: LaneConfig<TName>\n): LaneConfig<TName> {\n  LaneConfigSchema.parse(options);\n  return options;\n}\n\n// ---------------------------------------------------------------------------\n// Drain / Settle — runtime knobs for `drain(...)` / `settle(...)`. Parsed once\n// per call (cheap). Reject NaN/Infinity/negative; allow 0. `correlate` is a\n// pass-through query filter (validated by the store), so it is not reshaped.\n// ---------------------------------------------------------------------------\n\nconst DrainOptionsSchema = z.object({\n  streamLimit: z.number().int().min(0).optional(),\n  eventLimit: z.number().int().min(0).optional(),\n  leaseMillis: z.number().min(0).optional(),\n});\n\n/** Validate drain options, or pass `undefined` through. Throws `ZodError`. */\nexport function resolveDrainConfig(\n  options: DrainOptions | undefined\n): DrainOptions | undefined {\n  if (options === undefined) return undefined;\n  DrainOptionsSchema.parse(options);\n  return options;\n}\n\nconst SettleOptionsSchema = DrainOptionsSchema.extend({\n  debounceMs: z.number().min(0).optional(),\n  // `maxPasses` defaults to Infinity (no cap) when omitted; a present value is\n  // a non-negative integer — `0` is legal and means \"run no passes\".\n  maxPasses: z.number().int().min(0).optional(),\n}).loose();\n\n/** Validate settle options, or pass `undefined` through. Throws `ZodError`. */\nexport function resolveSettleConfig(\n  options: SettleOptions | undefined\n): SettleOptions | undefined {\n  if (options === undefined) return undefined;\n  SettleOptionsSchema.parse(options);\n  return options;\n}\n\n// ---------------------------------------------------------------------------\n// Shutdown — the grace budget `shutdown(...)` gives in-flight drain cycles\n// (#1442).\n// ---------------------------------------------------------------------------\n\n/**\n * Ceiling on the derived shutdown grace budget. Without a cap, a lane\n * configured with a long lease (minutes, for a genuinely slow integration)\n * would let one parked handler hold a rolling deploy open for that whole\n * lease. 30s is the longest `leaseMillis` the production checklist\n * recommends, so it is the point past which \"graceful\" stops being the\n * operator's intent.\n */\nexport const MAX_SHUTDOWN_GRACE_MS = 30_000;\n\n/**\n * Grace budget used when no lane pinned a `leaseMillis` — matches `drain()`'s\n * own `leaseMillis` fallback, so the default deployment gets a budget\n * consistent with how long its handlers were already allowed to hold a\n * stream.\n */\nexport const DEFAULT_SHUTDOWN_GRACE_MS = 10_000;\n\nconst ShutdownOptionsSchema = z\n  .object({\n    // `0` is legal and is exactly today's behavior: stop scheduling and\n    // return without waiting.\n    graceMs: z.number().min(0).optional(),\n  })\n  .loose();\n\n/** Validate shutdown options, or pass `undefined` through. Throws `ZodError`. */\nexport function resolveShutdownConfig(\n  options: ShutdownOptions | undefined\n): ShutdownOptions | undefined {\n  if (options === undefined) return undefined;\n  ShutdownOptionsSchema.parse(options);\n  return options;\n}\n\n// ---------------------------------------------------------------------------\n// Act — the top-level `act().build(options)` scalar knobs. The nested bags\n// (`autocloseWindow`, `circuitBreaker`) are resolved by their own resolvers\n// below; the `scoped`/`correlator` fields are objects/functions passed\n// through untouched (`.loose()`), so only the scalar knobs are checked here.\n// ---------------------------------------------------------------------------\n\nconst ActOptionsSchema = z\n  .object({\n    maxSubscribedStreams: z.number().int().min(1).optional(),\n    settleDebounceMs: z.number().int().min(0).optional(),\n  })\n  .loose();\n\n/** Validate the scalar `ActOptions` knobs at build. Throws `ZodError`. */\nexport function resolveActConfig(\n  options: ActOptions | undefined\n): ActOptions | undefined {\n  if (options === undefined) return undefined;\n  ActOptionsSchema.parse(options);\n  return options;\n}\n\n// ---------------------------------------------------------------------------\n// Autoclose — the autoclose knobs on `ActOptions` (+ the off-hours window).\n// The window *logic* (DST, hour math) stays in `autoclose-window.ts`; only\n// the schema, defaults, and resolver live here.\n// ---------------------------------------------------------------------------\n\n/**\n * @deprecated The cadence knob is derived from `autocloseWindow` now (#1175);\n * nothing consumes it. Kept for compat; removed in the next major.\n */\nexport const DEFAULT_AUTOCLOSE_CYCLE_MINUTES = 720;\n/** @deprecated Dead since #1090 removed the autoclose sweep. */\nexport const DEFAULT_CLOSE_BATCH_SIZE = 64;\n/** @deprecated Dead since #1090 removed the autoclose sweep. */\nexport const DEFAULT_CLOSE_YIELD_MS = 0;\n/** Default IANA zone for `autocloseWindow` when the operator omits one. */\nexport const DEFAULT_AUTOCLOSE_WINDOW_TZ = \"UTC\";\n\n/** True when `tz` is a zone the runtime's `Intl` accepts. @internal */\nfunction is_valid_time_zone(tz: string): boolean {\n  try {\n    new Intl.DateTimeFormat(\"en-US\", { timeZone: tz });\n    return true;\n  } catch {\n    return false;\n  }\n}\n\nconst AutocloseWindowSchema = z\n  .object({\n    start: z\n      .number()\n      .int()\n      .min(0)\n      .max(23, { message: \"autocloseWindow.start must be an hour in [0, 23]\" }),\n    end: z\n      .number()\n      .int()\n      .min(0)\n      .max(23, { message: \"autocloseWindow.end must be an hour in [0, 23]\" }),\n    timeZone: z\n      .string()\n      .refine(is_valid_time_zone, {\n        message: \"autocloseWindow.timeZone must be a valid IANA time zone\",\n      })\n      .default(DEFAULT_AUTOCLOSE_WINDOW_TZ),\n  })\n  .refine((w) => w.start !== w.end, {\n    message:\n      \"autocloseWindow.start and end must differ — an empty window disables autoclose\",\n  });\n\nconst AutocloseOptionsSchema = z.object({\n  autocloseCycleMinutes: z\n    .number()\n    .int()\n    .min(1)\n    .max(1440)\n    .default(DEFAULT_AUTOCLOSE_CYCLE_MINUTES),\n  closeBatchSize: z\n    .number()\n    .int()\n    .min(1)\n    .max(1024)\n    .default(DEFAULT_CLOSE_BATCH_SIZE),\n  closeYieldMs: z.number().min(0).max(1000).default(DEFAULT_CLOSE_YIELD_MS),\n  closeOnError: z.boolean().default(false),\n  autocloseWindow: AutocloseWindowSchema.optional(),\n});\n\n/** Resolved autoclose configuration after validation + default expansion. */\nexport type AutocloseConfig = z.infer<typeof AutocloseOptionsSchema>;\n\n/** Validate + default the autoclose knobs on `ActOptions`. Throws `ZodError`. */\nexport function resolveAutocloseConfig(\n  options: ActOptions | undefined\n): AutocloseConfig {\n  return AutocloseOptionsSchema.parse({\n    autocloseCycleMinutes: options?.autocloseCycleMinutes,\n    closeBatchSize: options?.closeBatchSize,\n    closeYieldMs: options?.closeYieldMs,\n    closeOnError: options?.closeOnError,\n    autocloseWindow: options?.autocloseWindow,\n  });\n}\n\n// ---------------------------------------------------------------------------\n// CircuitBreaker — the store-op breaker on `ActOptions`. The `CircuitBreaker`\n// state machine stays in `circuit-breaker.ts` and imports the resolved type.\n// ---------------------------------------------------------------------------\n\nexport const DEFAULT_CIRCUIT_FAILURE_THRESHOLD = 5;\nexport const DEFAULT_CIRCUIT_COOLDOWN_MS = 30_000;\n\nconst CircuitBreakerOptionsSchema = z.object({\n  failureThreshold: z\n    .number()\n    .int()\n    .min(1)\n    .default(DEFAULT_CIRCUIT_FAILURE_THRESHOLD),\n  cooldownMs: z\n    .number()\n    .int()\n    .min(100)\n    .max(3_600_000)\n    .default(DEFAULT_CIRCUIT_COOLDOWN_MS),\n});\n\n/** Public, all-optional circuit-breaker options bag for `act().build()`. */\nexport type CircuitBreakerOptions = z.input<typeof CircuitBreakerOptionsSchema>;\n\n/** Resolved circuit-breaker configuration. */\nexport type CircuitBreakerConfig = z.infer<typeof CircuitBreakerOptionsSchema>;\n\n/** Parse + apply defaults. Throws `ZodError` on out-of-range values. */\nexport const resolveCircuitBreakerConfig = (\n  options?: CircuitBreakerOptions\n): CircuitBreakerConfig => CircuitBreakerOptionsSchema.parse(options ?? {});\n\n// ---------------------------------------------------------------------------\n// Fold — `projection(name).of(state)` batch-fold knobs.\n// ---------------------------------------------------------------------------\n\nexport const DEFAULT_FOLD_FLUSH_EVERY = 1_000;\nexport const DEFAULT_MAX_CACHED_STATES = 10_000;\n\nconst FoldOptionsSchema = z.object({\n  flushEvery: z.number().int().min(1).default(DEFAULT_FOLD_FLUSH_EVERY),\n  maxCachedStates: z.number().int().min(1).default(DEFAULT_MAX_CACHED_STATES),\n});\n\n/** Resolved fold configuration. */\nexport type FoldConfig = z.infer<typeof FoldOptionsSchema>;\n\n/** Validate + default the fold knobs. Throws `ZodError`. */\nexport function resolveFoldConfig(options: FoldOptions): FoldConfig {\n  return FoldOptionsSchema.parse(options);\n}\n","/**\n * @module correlate-cycle\n * @category Internal\n *\n * Correlation — the discovery half of the correlate→drain pair. Owns the\n * lazy init (subscribe static targets, read cold-start watermark), the\n * scan that resolves each event to its target streams, and the periodic\n * timer that drives background discovery.\n *\n * The scan is also the **producer of the work mark** (#1487): every target\n * an event resolves to is subscribed with `correlated_at` = that event's\n * id, which is how `claim` answers \"does this stream have work?\" off the\n * subscription row instead of probing the event log.\n *\n * The Act orchestrator passes registry + classification (which static\n * targets to subscribe) at build time; everything past that lives here.\n *\n * @internal\n */\n\nimport { createHash, randomUUID } from \"node:crypto\";\nimport { DEFAULT_LANE, log, store } from \"../ports.js\";\nimport type {\n  EventRegister,\n  Query,\n  Registry,\n  SchemaRegister,\n  Schemas,\n  SubscribeInput,\n} from \"../types/index.js\";\nimport { is_literal_source } from \"../utils.js\";\nimport type { DrainOps } from \"./drain.js\";\nimport { LruMap } from \"./lru-map.js\";\nimport { report_once } from \"./report-once.js\";\n\n/**\n * Cold-start back-scan window (ACT-1207). On init the correlate cursor\n * would otherwise jump straight to the store watermark (`max(at)` across\n * every subscribed stream). A dynamic-resolver event committed but not\n * yet correlated before a crash sits *below* that watermark whenever a\n * busier stream has since advanced — so a plain `max(at)` cold start\n * skips it forever, and a one-shot dynamic target is never subscribed.\n *\n * Flooring the cold-start checkpoint at `watermark - BACK_SCAN` re-scans\n * the tail on restart so those in-flight events are re-discovered.\n * Re-scanning already-correlated events is harmless: a re-issued\n * `subscribe` is an idempotent UPSERT and a re-issued mark never\n * regresses. The window bounds the one-time restart cost; steady-state\n * correlation still advances the checkpoint forward normally.\n *\n * @internal\n */\nconst DEFAULT_COLD_START_BACK_SCAN = 10_000;\n\n/**\n * Default correlation lease duration (#1532).\n *\n * Bounds two opposing risks. Too short and a slow scan outruns its own lease,\n * letting a second worker scan the same range — which is merely the\n * duplication that exists without a lease at all, so it fails safe. Too long\n * and a crashed holder stalls discovery for that whole window, because\n * nothing raises marks while nobody holds the lease and nothing becomes\n * claimable. Seconds rather than minutes, for that reason.\n */\nconst DEFAULT_CORRELATION_LEASE_MS = 5_000;\n\n/**\n * A stable identity for \"which correlator is this?\" (#1532).\n *\n * The correlation lease lets one worker scan on behalf of others, which is\n * only sound when they are interchangeable. Two processes running the same\n * application are; two different applications sharing one database are not —\n * leasing across those would let one starve the other, and its reactions\n * would silently stop.\n *\n * The key is every event name this correlator reacts to, each with the names\n * of the handlers registered for it. Event names alone would do if reacting\n * to an event implied doing the same thing with it, and it does not: two\n * applications can both react to `Placed` and resolve it to entirely\n * different targets, so a shared lease would mark one's targets and never the\n * other's. Handler names cost nothing — the registry already keys reactions\n * by them — and separate exactly that case.\n *\n * Sorted before hashing so identical workers agree regardless of declaration\n * order. Truncated to 32 hex characters: a collision means two applications\n * with identical event *and* handler names share a lease, and those are\n * interchangeable by construction.\n *\n * **This separates leases; it does not make the topology supported.** Two\n * applications over one store still share a single read cursor, and a key\n * with no row of its own is seeded from it — so the second application\n * resumes where the first had read to and never correlates what lies below\n * (#1581). One store belongs to one application; the split-stores recipe is\n * the migration. The key exists so that many processes of the *same*\n * application can hand the scan between them, which is the supported case.\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 * How many distinct pattern sources keep a compiled `RegExp` around. A\n * pattern source is declared on a resolver, so the live set is tiny; the\n * bound only guards a dynamic resolver that mints one per event.\n *\n * @internal\n */\nconst PATTERN_CACHE_SIZE = 32;\n\n/**\n * Static resolver target collected at build time. Subscribed once during\n * init, then marked by every scan whose events resolve to it.\n *\n * @property priority - Scheduling priority for the resolved target stream.\n *   Combined with peers via `max()` at build time when multiple reactions\n *   target the same stream — see `build-classify.ts`.\n *\n * @internal\n */\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 was last subscribed at, remembered per target so a scan\n * knows what its subscription row already holds.\n *\n * `floor` guards priority upgrades (#1363): a resolution re-subscribes its\n * own priority/lane only when it beats the floor, and a static target sits\n * at `+Infinity` so a dynamic resolution never re-opens what the build-time\n * subscribe owns. `priority`/`lane` are what the row holds, re-sent\n * verbatim by a resolution that does *not* beat the floor, so the work mark\n * riding the same `subscribe` carries the row's own values rather than a\n * losing resolution's.\n *\n * This is an optimization, not the guarantee. A record can go missing —\n * eviction here, an empty map after a restart — and a missing record reads\n * as never-seen. What keeps a forgotten target on its lane is the store:\n * `subscribe` writes the lane only when the incoming priority is at or\n * above the stored one, the same max it merges priority with (#1599).\n *\n * Where the record lives decides whether the floor survives: dynamic\n * targets are unbounded and go in the evictable LRU, static targets are a\n * bounded build-time list and go in a plain map that never evicts (#1582).\n *\n * @internal\n */\ntype Subscription = {\n  readonly floor: number;\n  readonly priority: number;\n  readonly lane: string | undefined;\n};\n\n/**\n * One target accumulated during a scan: the values to subscribe it with,\n * and the highest event id observed to resolve to it — its work mark,\n * `undefined` when no scanned event fell inside the target's fetch window.\n *\n * @internal\n */\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 floor. */\n  upgraded: boolean;\n  correlated_at: number | undefined;\n};\n\n/**\n * Drives correlation for one Act instance. Owns the checkpoint, the\n * subscribed-streams LRU, and the periodic timer.\n *\n * @internal\n */\n/**\n * Constructor dependencies for {@link CorrelateCycle}. A named bag rather\n * than a positional list: the trailing hooks (`on_init`, `on_init_async`)\n * plus `cold_start_back_scan` are all optional and easy to transpose\n * positionally, so callers pass them by name.\n */\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  /**\n   * Every lane a controller exists for — `\"default\"` plus each\n   * `.withLane({name})`. Injected rather than derived: `internal/` receives\n   * what it needs. A resolution naming anything outside this set has no\n   * claimant, so correlate reroutes it here (#1564).\n   */\n  declared_lanes: ReadonlySet<string>;\n  run_scoped: <T>(fn: () => Promise<T>) => Promise<T>;\n  on_init?: () => void;\n  on_init_async?: () => Promise<void>;\n  cold_start_back_scan?: number;\n  lease_millis?: number;\n};\n\n/**\n * A dynamic resolution named a lane no controller claims (#1564).\n *\n * Reroutes to `\"default\"` rather than skipping: the target is legitimate and\n * only its lane is wrong, so stranding the stream at watermark `-1` — where\n * no health surface can see it — loses work that the operator never asked to\n * lose. `\"default\"` is where the reaction would have run had the lane been\n * omitted, which makes this the smallest correction that keeps it running.\n *\n * Keyed on the reaction and the lane it named, not on the target it minted\n * (#1584). One typo in one `.to(fn)` reroutes every target that resolver\n * produces, and the documented per-aggregate shape produces one per\n * aggregate — the target belongs in the message as an example, never in the\n * key. A resolver computing its lane from the event still reports each\n * distinct bad name, because each is a separate thing to fix.\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 (#1567).\n *\n * Reported, not corrected. The lane a target already carries is the one its\n * in-flight leases were taken under, so re-laning it mid-run would move a\n * stream out from under a worker holding it; re-laning is restart-driven by\n * design. What the operator loses meanwhile is lane discipline — the losing\n * reaction runs inside the winner's `leaseMillis` and `streamLimit` — and\n * under `onlyLanes` sharding, a process provisioned for the losing lane never\n * runs it at all.\n *\n * Keyed on the losing declaration — the reaction whose lane was dropped, and\n * the two lanes — with the target out of the key (#1584), because a resolver\n * mints one target per aggregate and a target-keyed report scales with the\n * aggregate count rather than with the number of things to fix.\n *\n * The winner is named by lane rather than by handler on purpose. Which side\n * wins is \"first discovered\", so the same pair can land either way on\n * different targets, and those are two different facts about the same\n * misdeclaration: an operator seeing only one of them would read the outcome\n * as deterministic. Keeping the orientation in the key reports both, and the\n * count stays bounded by the declarations, which is what #1584 asked for.\n * (The winning handler is not available here anyway — a lane carried over\n * from an earlier scan, or seeded by a static subscribe, has no handler\n * recorded against it.)\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\nexport class CorrelateCycle<\n  TSchemaReg extends SchemaRegister<TActions>,\n  TEvents extends Schemas,\n  TActions extends Schemas,\n> {\n  private _checkpoint = -1;\n  private _initialized = false;\n  /**\n   * This worker's identity for the correlation lease (#1532). A per-instance\n   * UUID, matching the drain's convention, so a renewal is recognised as the\n   * same holder and a restarted process never inherits a stale claim.\n   */\n  private readonly _by = randomUUID();\n  /** How long the correlation lease is taken for. */\n  private readonly _lease_millis: number;\n  /**\n   * Which correlator this is. Computed once from the registry so identical\n   * workers share a lease and unrelated applications never do.\n   */\n  private readonly _key: string;\n  /**\n   * When this worker's correlation lease runs out, as a local clock reading,\n   * or 0 when it holds none.\n   *\n   * Asking the store on every pass costs a round trip that the holder — which\n   * is the *only* worker in a single-node deployment, and the steady-state\n   * one everywhere else — gains nothing from: it already knows the answer.\n   * The act-sqlite perf gate caught that as a 1.5x regression on\n   * correlate+drain, which is the shape an embedded app runs constantly.\n   *\n   * Believing this while the store disagrees is safe in the one direction it\n   * can fail. A worker that scans without really holding the lease produces\n   * the duplicate scan that existed before the lease, and the marks are\n   * idempotent — so a stale belief costs work, never correctness.\n   */\n  private _lease_until = 0;\n  /**\n   * Whether a scan might find anything. The drain has carried the same flag\n   * since it was written — a commit raises it, an empty claim lowers it, and\n   * a disarmed drain returns without touching the store. Correlate had no\n   * equivalent, so a settle pass always scanned, including the final pass\n   * whose only job is to confirm nothing changed (#1510).\n   *\n   * Starts armed: the log may already hold events this process has never\n   * correlated, and only a scan can find out.\n   */\n  private _armed = true;\n  /** In-flight init, memoized for single-flight and cleared on failure. */\n  private _init_promise: Promise<void> | undefined;\n  private _timer: ReturnType<typeof setInterval> | undefined = undefined;\n  // Dynamically discovered targets → what each was last subscribed at,\n  // bounded by `maxSubscribedStreams`. The static half lives in\n  // `_static_subscriptions` below, which is deliberately not evictable.\n  //\n  // Every scan re-subscribes the\n  // targets it resolved (that is how the work mark lands), so this no longer\n  // decides *whether* a target is sent — it decides *what* is sent with it:\n  // a resolution raises priority/lane only when it beats the recorded floor,\n  // and otherwise re-sends the row's own values so the mark changes nothing\n  // else. See {@link Subscription}.\n  private readonly _dynamic_subscriptions: LruMap<string, Subscription>;\n  /**\n   * What each static target was subscribed at by `init`. A plain map, never\n   * evicted: the collection is the build-time `_static_targets` list, so it\n   * is already bounded by the registry and costs nothing the registry does\n   * not already hold.\n   *\n   * Keeping these out of the LRU is what makes the `+Infinity` floor an\n   * invariant rather than a race (#1582). Sharing the bounded map meant a\n   * churn of dynamic targets could evict a static record, and the next\n   * dynamic resolution to that target found no record, took the\n   * first-discovery branch, and re-subscribed the target with its own\n   * priority and lane — silently re-laning a stream whose lane the\n   * build-time subscribe owns, and starving it wherever `onlyLanes` had\n   * provisioned a worker for the declared lane.\n   */\n  private readonly _static_subscriptions = new Map<string, Subscription>();\n  /** Compiled pattern sources, bounded by {@link PATTERN_CACHE_SIZE}. */\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: (() => void) | undefined;\n  /**\n   * Async cold-start hook (#1221). Runs once, after the sync `on_init`,\n   * inside the same `init()` await. The orchestrator uses it to re-seed the\n   * process-local defer timers from the store's persisted `deferred_at` so\n   * an idle deferred stream re-arms its drain across a restart. Kept\n   * separate from `on_init` because seeding is an async store read; `init`\n   * already awaits, so folding it in here preserves the \"runs exactly once\"\n   * guarantee without a second gate on the Act side.\n   */\n  private readonly _on_init_async: (() => Promise<void>) | undefined;\n  /**\n   * Scope runner (#1191). The periodic `start_polling` timer fires\n   * outside any caller frame, so its `correlate()` must be re-wrapped in\n   * the Act's `_scoped` bag or `store()`/`cache()` resolve to the\n   * singleton for a scoped Act. The orchestrator always threads its\n   * `_scoped` (identity for a non-scoped Act), so it's required.\n   */\n  private readonly _run_scoped: <T>(fn: () => Promise<T>) => Promise<T>;\n  /**\n   * Tail re-scan window applied to the cold-start checkpoint (ACT-1207).\n   * See {@link DEFAULT_COLD_START_BACK_SCAN}. Constructor arg (not a\n   * public option) so tests can shrink it; defaults otherwise.\n   */\n  private readonly _cold_start_back_scan: number;\n  /** Lanes a controller exists for. See {@link CorrelateCycleDeps}. */\n  private readonly _declared_lanes: ReadonlySet<string>;\n  /**\n   * Offending declarations already reported, so a resolver firing for every\n   * matching event reports once. Owned by the instance rather than the\n   * module: `internal/` holds no module-level state.\n   */\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    run_scoped,\n    on_init,\n    on_init_async,\n    cold_start_back_scan = DEFAULT_COLD_START_BACK_SCAN,\n    lease_millis = DEFAULT_CORRELATION_LEASE_MS,\n  }: CorrelateCycleDeps<TSchemaReg, TEvents, TActions>) {\n    this._lease_millis = lease_millis;\n    this._key = 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    this._run_scoped = run_scoped;\n    this._on_init_async = on_init_async;\n    this._cold_start_back_scan = cold_start_back_scan;\n  }\n\n  /** Last correlated event id. */\n  get checkpoint(): number {\n    return this._checkpoint;\n  }\n\n  /**\n   * Signal that a commit (local or remote) may have produced events this\n   * process has not correlated. Cheap and idempotent — the orchestrator calls\n   * it on every commit and every notification.\n   */\n  arm(): void {\n    this._armed = true;\n  }\n\n  /**\n   * Initialize correlation state on first call.\n   * - Reads the durable correlate checkpoint (and max(at)) from the store,\n   *   flooring a first boot at `watermark - back_scan` so an event\n   *   committed-but-not-correlated before a crash is re-scanned on\n   *   restart instead of skipped (ACT-1207)\n   * - Subscribes static resolver targets (idempotent upsert)\n   * - Populates the subscribed-streams LRU\n   * - Fires `on_init` once (Act uses this to flag a cold-start drain)\n   */\n  async init(): Promise<void> {\n    if (this._initialized) return;\n    // Single-flight, but retryable: the promise is memoized so concurrent\n    // callers (correlate, the settle loop, every lane worker) share one\n    // run, and cleared on rejection so a transient store failure doesn't\n    // latch. Setting a boolean before the await instead left every static\n    // target unsubscribed for the process lifetime after one blip — the\n    // reaction pipeline silently dead, with nothing in blocked_streams or\n    // the audit to reveal it, because the subscription row never existed.\n    if (!this._init_promise) {\n      this._init_promise = this._run_init().catch((error) => {\n        this._init_promise = undefined;\n        throw error;\n      });\n    }\n    await this._init_promise;\n    this._initialized = true;\n  }\n\n  private async _run_init(): Promise<void> {\n    const { watermark, correlated_at } = await store().subscribe([\n      ...this._static_targets,\n    ]);\n    // Resume from the durable checkpoint when one exists (#1484). On a first\n    // boot it sits at -1 and a full scan of an existing log would be\n    // unbounded, so seed from the old heuristic: the watermark backed off by\n    // a bounded window, which re-discovers the crash-window tail (an\n    // uncorrelated event now below a busier stream's watermark). Never floor\n    // below -1. After the first scan the checkpoint is exact and the\n    // heuristic never runs again.\n    //\n    // Static-only apps take the same path since #1487: correlate scans for\n    // every app now, because a target that is never scanned is a target that\n    // is never marked.\n    this._checkpoint =\n      correlated_at >= 0\n        ? correlated_at\n        : Math.max(-1, watermark - this._cold_start_back_scan);\n    this._on_init?.();\n    for (const { stream, priority = 0, lane } of this._static_targets) {\n      // floor +Infinity: a dynamic resolution's priority can never exceed it,\n      // so a static target is never re-opened through the dynamic path\n      // (#1363) — its priority/lane are owned by the build-time subscribe\n      // above, and a scan that marks it re-sends exactly those values.\n      // Recorded outside the LRU so eviction can't take the floor with it\n      // (#1582).\n      this._static_subscriptions.set(stream, {\n        floor: Number.POSITIVE_INFINITY,\n        priority,\n        lane,\n      });\n    }\n    // Cold-start defer re-seed (#1221) — after the static targets are\n    // subscribed, so a walk of the streams table sees them.\n    await this._on_init_async?.();\n  }\n\n  /**\n   * Forget targets whose subscription rows no longer exist, so a later\n   * scan can re-subscribe them.\n   *\n   * A full close deletes the closed stream's subscription row. The\n   * in-process dedup would otherwise still believe the target is\n   * subscribed and never re-issue `subscribe()`, silently stopping\n   * delivery for any reaction whose target is named after the stream —\n   * the documented per-aggregate shape `.to(e => ({target: e.stream}))`\n   * makes those two namespaces collide by construction (#1398).\n   *\n   * Static targets are left alone: their record lives in\n   * `_static_subscriptions`, which this never touches, so they stay pinned\n   * at +Infinity and the dynamic path never re-opens them.\n   */\n  forget_subscribed(streams: Iterable<string>): void {\n    for (const stream of streams) this._dynamic_subscriptions.delete(stream);\n  }\n\n  /**\n   * Would an event from `stream` be fetched for a target subscribed with\n   * `source`? The subscription's source is the filter `fetch` queries with\n   * — literal names by equality, patterns compiled as a `RegExp` — so an\n   * event outside it is not work for that target and must not mark it.\n   * No source means the target consumes every stream.\n   */\n  private _in_fetch_window(\n    source: string | undefined,\n    stream: string\n  ): boolean {\n    if (source === undefined || source === stream) return true;\n    if (is_literal_source(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  /**\n   * Scan the events past the checkpoint, resolve each to its target\n   * streams, and record what it found through `cd.subscribe` — new dynamic\n   * targets get registered, and every target an event resolved to gets its\n   * **work mark** raised to that event's id (#1487).\n   *\n   * Both resolver kinds are walked. A static target is already subscribed\n   * at init, but marking it is what makes it claimable without probing the\n   * event log, so the scan runs for every app.\n   */\n  async correlate(\n    query: Query = { after: -1, limit: 10 },\n    /**\n     * Whether to honour the correlation lease (#1532).\n     *\n     * True only on the automatic paths — the settle loop and the poller —\n     * where the question is \"should *someone* scan?\" and one worker doing it\n     * serves all of them.\n     *\n     * An explicit `app.correlate()` means \"scan now\", and silently no-oping\n     * it because a peer holds the lease would be wrong rather than merely\n     * surprising: `close` catches up by looping until the checkpoint moves,\n     * so a blocked scan would make it give up and cap its prune at a stale\n     * position — pruning far less than the retention window asked for, with\n     * nothing to explain why.\n     */\n    lease = false\n  ): Promise<{\n    subscribed: number;\n    last_id: number;\n    marked: number;\n    /** False when the pass was disarmed and returned without a store read. */\n    scanned: boolean;\n  }> {\n    await this.init();\n\n    // Nothing has happened since the last scan reached the end of the log, so\n    // there is nothing to find (#1510).\n    //\n    // The flag only ever means \"a local signal says there may be work\" — a\n    // commit through `do()`, or a `notify` from another process. It is\n    // deliberately NOT a claim that the log is unchanged: a remote writer on a\n    // store with no notify support leaves this process disarmed and stale.\n    // `start_polling` exists for exactly that case and arms on every tick, so\n    // the poller keeps its meaning (\"I have no signal, go and look anyway\").\n    if (!this._armed)\n      return {\n        subscribed: 0,\n        last_id: this._checkpoint,\n        marked: 0,\n        scanned: false,\n      };\n\n    // Only one worker per registry scans at a time (#1532). Each worker holds\n    // its own in-memory checkpoint, so without this they all wake on the same\n    // commit and each reads the whole range and writes the same marks —\n    // measured at exactly W reads and W mark-writes per committed event for W\n    // workers.\n    //\n    // The lease rides `subscribe`, the call correlate already makes to\n    // persist its checkpoint, rather than a verb of its own. Asking with no\n    // streams and no advance is a pure \"may I scan?\".\n    //\n    // The answer's checkpoint is deliberately ignored. Adopting it looks like\n    // free catch-up and is not: the durable position is a floor shared with\n    // every other correlator, so a worker that adopted it would start its\n    // scan past events it had never read and never mark their targets. A\n    // worker that takes over instead re-scans from its own position —\n    // redundant, bounded by paging, idempotent, and correct. `init` remains\n    // the only place the durable checkpoint seeds a local one, where the\n    // cold-start back-scan window guards exactly this hazard.\n    // Re-ask only when the lease is running out. Renewing at the halfway mark\n    // leaves a full half-lease of slack for the call itself, so a holder never\n    // lapses by asking too late.\n    const now = Date.now();\n    if (lease && now >= this._lease_until - this._lease_millis / 2) {\n      const { correlating } = await this._cd.subscribe([], undefined, {\n        key: this._key,\n        by: this._by,\n        millis: this._lease_millis,\n      });\n      this._lease_until = correlating ? now + this._lease_millis : 0;\n      // `undefined` means the store does not implement leasing, so every\n      // worker scans exactly as before.\n      if (correlating === false)\n        // Another worker with the same registry is scanning, so this one need\n        // not. Stay armed: the work still needs doing, and this worker should\n        // look again next pass rather than disarm and wait for an unrelated\n        // commit to wake it.\n        return {\n          subscribed: 0,\n          last_id: this._checkpoint,\n          marked: 0,\n          scanned: false,\n        };\n    }\n\n    // Use checkpoint as floor, allow explicit query.after to override upward\n    const after = Math.max(this._checkpoint, query.after || -1);\n    const correlated = new Map<string, Correlated>();\n    let last_id = after;\n    await store().query<TEvents>(\n      (event) => {\n        last_id = event.id;\n        const register = this._registry.events[event.name];\n        // skip events with no registered reactions\n        if (register) {\n          for (const reaction of register.reactions.values()) {\n            const resolved =\n              typeof reaction.resolver === \"function\"\n                ? reaction.resolver(event)\n                : reaction.resolver;\n            if (!resolved) continue;\n            // A lane no controller claims has no claimant, so the stream\n            // would sit at watermark -1 forever. Reroute to \"default\" and\n            // say so (#1564) — the build-time guard sees only static lanes.\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            // Raise priority/lane only when this resolution beats what the\n            // target was last subscribed at, so the store's `GREATEST` upsert\n            // runs — the documented runtime `max()` invariant, which the\n            // plain \"already subscribed?\" dedup silently froze at first\n            // discovery (#1363). A never-seen target has no record, so its\n            // first resolution always wins; a static target sits at +Infinity\n            // and never does. Otherwise the row's own values ride along\n            // unchanged, because the mark travels on the same upsert.\n            //\n            // Statics are consulted first and from their own map: the LRU\n            // can evict, and a missing record reads as never-seen (#1582).\n            const recorded =\n              this._static_subscriptions.get(resolved.target) ??\n              this._dynamic_subscriptions.get(resolved.target);\n            const priority = resolved.priority ?? 0;\n            const upgraded = !recorded || priority > recorded.floor;\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              correlated_at: undefined,\n            };\n            // Two resolutions wanting different lanes for one target, with\n            // neither outranking the other, is what the build-time guard\n            // rejects for static declarations (#1567). Priority still decides\n            // below; this only reports the tie the operator can't otherwise\n            // see. Compare against what this target already carries, whether\n            // that came from an earlier reaction in this scan or a past one,\n            // and against that same source's priority — a resolution that\n            // beat the floor outranks what it found rather than tying with\n            // itself.\n            //\n            // Both lanes are compared by their resolved name, exactly as the\n            // static guard does (#1583): an omitted lane *is* the default\n            // lane, and the default lane is what the subscription row ends up\n            // holding, so an omitted lane against a declared one is a real\n            // disagreement. A never-seen target holds no lane at all, which is\n            // not the same as holding \"default\" — the record's existence is\n            // what gates the report.\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            // Multiple reactions targeting the same stream within a\n            // single correlate scan — keep the max priority, and carry the\n            // winning reaction's lane so the highest-priority reaction sets\n            // the lane (matches the subscribe-side `max()` invariant).\n            if (carried.priority > entry.priority) {\n              entry.priority = carried.priority;\n              entry.lane = carried.lane;\n              entry.upgraded = upgraded;\n            }\n            // The mark is an assertion about the log: only an event the\n            // target's own fetch would return may raise it. Ids ascend\n            // through the scan, so the last one wins.\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      },\n      { ...query, after }\n    );\n\n    // A target rides the batch when it has something to say: a mark to\n    // raise, or priority/lane to register. A re-seen target that this scan\n    // found no work for (its source filtered every event out) says neither,\n    // and is left alone.\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      // Persist the read cursor with the targets this scan discovered\n      // (#1484). Correlate is the only component that knows how far it has\n      // read, and it is already making this call.\n      // Carry the correlator only when this pass is actually leasing, so it\n      // renews as a side effect of persisting what the scan found.\n      //\n      // An explicit `app.correlate()` does not lease, and must not pay for\n      // one either: sending a correlator turns a single checkpoint UPDATE\n      // into a keyed upsert plus a second write and a read. The act-sqlite\n      // perf gate caught exactly that as a regression on correlate+drain,\n      // which is the shape an embedded app runs constantly and which never\n      // wanted a lease in the first place.\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: this._lease_millis }\n          : undefined\n      );\n      if (lease && correlating !== false)\n        this._lease_until = renewed_at + this._lease_millis;\n      // Raising a mark is work becoming claimable, exactly like registering\n      // a new target — the orchestrator arms on both (#1488). A target that\n      // was already subscribed reports `subscribed: 0`, so arming on that\n      // alone leaves freshly marked work sitting until an unrelated commit\n      // wakes the lane.\n      const marked = streams.filter(\n        (entry) => entry.correlated_at !== undefined\n      ).length;\n      // Advance checkpoint only after subscribe succeeds\n      this._checkpoint = last_id;\n      // Record what each upgraded target was just subscribed at (the\n      // within-scan max), so a later lower-or-equal resolution carries these\n      // values forward and a strictly-higher one re-opens the guard (#1363).\n      // Only dynamic targets reach here — a static sits at +Infinity, so no\n      // resolution to one is ever `upgraded`.\n      for (const { stream, priority, lane } of streams) {\n        if (correlated.get(stream)?.upgraded)\n          this._dynamic_subscriptions.set(stream, {\n            floor: priority as number,\n            priority: priority as number,\n            lane,\n          });\n      }\n      return { subscribed, last_id, marked, scanned: true };\n    }\n    // Nothing to subscribe — safe to advance. Disarm only here: this is the\n    // branch where the scan resolved no target at all, which is what \"the log\n    // has nothing more for us\" looks like. A scan that found something leaves\n    // the flag up, so the next pass continues from the new checkpoint rather\n    // than stopping mid-backlog.\n    this._checkpoint = last_id;\n    this._armed = false;\n    return { subscribed: 0, last_id, marked: 0, scanned: true };\n  }\n\n  /**\n   * Start a periodic correlation worker. Returns false if one is already\n   * running. Errors from `correlate()` are routed through `log()` so they\n   * land in the configured logger (the timer keeps running on failure).\n   */\n  start_polling(\n    query: Query = {},\n    frequency = 10_000,\n    callback?: (subscribed: number) => void\n  ): boolean {\n    if (this._timer) return false;\n\n    const limit = query.limit || 100;\n    this._timer = setInterval(\n      () =>\n        this._run_scoped(() => {\n          // Polling is the discovery path for commits this process never saw —\n          // a remote writer on a store without `notify`. Arming each tick is\n          // what keeps that true now that a scan can park itself (#1510).\n          this.arm();\n          // The poller is an automatic path, so it honours the lease: one\n          // worker scanning on each tick serves every worker.\n          return this.correlate(\n            {\n              ...query,\n              after: this._checkpoint,\n              limit,\n            },\n            true\n          );\n        })\n          .then((result) => {\n            if (callback && result.subscribed) callback(result.subscribed);\n          })\n          .catch((err) => log().error(err)),\n      frequency\n    );\n    return true;\n  }\n\n  /** Stop the periodic correlation worker. Idempotent. */\n  /**\n   * Hand the correlation lease back early.\n   *\n   * There is no release verb on the port, deliberately — expiry is the only\n   * path, which keeps a crash and a clean stop on the same code path. A\n   * holder can still shorten its own lease, because re-acquiring as the same\n   * holder renews, and renewing to a millisecond is a release in all but\n   * name.\n   *\n   * Without this a worker that stops cleanly still blocks discovery for the\n   * rest of its lease — invisible in a long-lived deployment, very visible\n   * anywhere Acts are created and dropped inside one process.\n   *\n   * Best-effort: failing here costs the lease's remaining lifetime, which is\n   * what would have happened had the process died instead.\n   */\n  async release_correlation(): Promise<void> {\n    try {\n      // Zero releases outright. A near-zero expiry would still refuse a\n      // successor asking in the same instant, which reads as the handback\n      // not having happened.\n      this._lease_until = 0;\n      await this._cd.subscribe([], undefined, {\n        key: this._key,\n        by: this._by,\n        millis: 0,\n      });\n    } catch (error) {\n      // The handback is best-effort by construction: the lease carries its\n      // own expiry, so failing here costs at most `_lease_millis` before a\n      // successor can take over, and nothing is lost.\n      //\n      // `warn`, not `error`, and deliberately: this runs during shutdown,\n      // where the store is at its most contended — a pool closing under it,\n      // or, on a single-writer store like SQLite, another connection holding\n      // the file. Nothing is lost and it self-heals, so it does not deserve\n      // a severity operators routinely page on; a clean Ctrl-C would page\n      // every time. It stays visible because a contended file is still worth\n      // investigating (#1577).\n      //\n      // A plain message rather than an `Error`: the stack would point at\n      // this catch, not at whatever holds the lock, so it is noise.\n      log().warn(\n        `Could not hand back the correlation lease during shutdown; it expires on its own within ${this._lease_millis}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)}`\n      );\n    }\n  }\n\n  stop_polling(): void {\n    if (this._timer) {\n      clearInterval(this._timer);\n      this._timer = undefined;\n    }\n  }\n}\n","/**\n * @module report-once\n * @category Internal\n *\n * One-shot reporting for a misdeclaration that a build-time guard could not\n * catch.\n *\n * The guards in `build_events` and `build-classify` can only inspect a static\n * `.to({...})` — a `.to(fn)` target, lane and priority are a function until an\n * event arrives. The pipelines that resolve them (correlate for lane and\n * target, drain for the payload) are therefore where the same rules have to be\n * applied, and where the operator has to be told.\n *\n * Reporting there has one hazard the build-time guards don't: a resolver fires\n * for *every* matching event, so a naive log turns one bad declaration into a\n * line per event on a busy stream. Reporting once per offending declaration is\n * what makes the message readable.\n *\n * Which makes the key the whole design. It may only be built from things the\n * *declaration* names — handler names, event names, lane names, a statically\n * declared target — and never from a value a resolver computed at runtime.\n * A resolved target is the trap: the documented per-aggregate shape is\n * `.to(e => ({target: e.stream}))`, so a target-keyed report dedups nothing\n * across aggregates and one typo scales into one line per aggregate — the\n * unbounded volume this module exists to prevent (#1584). Runtime values\n * still belong in the *message*, as the concrete example that turns \"a\n * reaction misdeclared its lane\" into something an operator can go look at.\n *\n * Never throws. A throw inside correlate pins the checkpoint for the whole app\n * (#1420); inside drain it reaches the circuit breaker as a store failure and\n * stalls every stream.\n *\n * @internal\n */\n\nimport { log } from \"../ports.js\";\n\n/**\n * Report `message` the first time `key` is seen, and never again.\n *\n * `seen` belongs to the calling pipeline and is passed in, so a resolver\n * firing for every matching event still reports once without this module\n * remembering anything between calls — `internal/` holds no module state.\n *\n * @param seen - The caller's set of already-reported keys. Mutated.\n * @param key - Identifies the offending declaration, not the occurrence —\n *   declared identifiers only, never a runtime-resolved target.\n * @param message - Wrapped in an `Error` so the logger renders a stack.\n *\n * @internal\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 * @module correlator\n * @category Internal\n *\n * Correlation-id generator and the default implementation (ACT-404).\n *\n * The default produces a readable, time-monotonic-within-window, lowercase\n * id like `coun-incr-lwxk9p3a` — short enough to scan in logs, structured\n * enough to identify the originating state/action, and well-distributed\n * enough that competing-consumer workers don't collide.\n *\n * Apps override via {@link ActOptions.correlator} to plug in any scheme\n * (tenant-prefixed, trace-id-propagated, DB-sequence-backed, etc.).\n *\n * @internal\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 *\n * @internal\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 * @module date-reviver\n * @category Internal\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 and something\n * has to revive it on the way out. Which fields those are is a property of the\n * Zod schema, so working it out is a Zod concern rather than an event one —\n * this module knows nothing about events, states or PII. It takes a declared\n * schema and returns the schema that revives its dates, or `undefined` when\n * there are none to revive.\n *\n * Sits beside the other schema utilities rather than inside the event builder,\n * which composes it: `event_tags` asks for one reviver for an event's `data`\n * and another for the sensitive fields held in its `pii` sidecar. One function\n * is the whole interface — how a Zod schema is taken apart stays in here.\n *\n * The shape-based {@link dateReviver} in `utils.ts` is the predecessor this\n * replaced — it revived anything ISO-8601-looking, including fields declared\n * `z.string()` ([#1556](https://github.com/Rotorsoft/act-root/issues/1556)).\n *\n * @internal\n */\n\nimport { z } from \"zod\";\n\n/** Zod exposes its shape under `_zod.def` in v4 and `def` in older builds. */\nconst def_of = (schema: unknown): Record<string, unknown> | undefined =>\n  (schema as { _zod?: { def?: Record<string, unknown> } })._zod?.def ??\n  (schema as { def?: Record<string, unknown> }).def;\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(schema: unknown): {\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 = date_reviver_schema(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 = date_reviver_schema(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 */\nexport function date_reviver_schema(schema: unknown): z.ZodType | undefined {\n  const def = def_of(schema);\n  if (!def) return undefined;\n  const inner = () => date_reviver_schema(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 = date_reviver_schema(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 = date_reviver_schema(def.element);\n      return element && z.array(element);\n    }\n    case \"tuple\": {\n      const items = (def.items as unknown[]).map((i) => date_reviver_schema(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 = date_reviver_schema(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(variant_schema);\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 \"optional\":\n    case \"nonoptional\":\n    case \"readonly\":\n    case \"default\":\n    case \"prefault\":\n    case \"catch\":\n      return inner();\n    default:\n      return undefined;\n  }\n}\n","/**\n * @module defer-config\n * @category Internal\n *\n * The `when` options for the public `defer` surface (#1091, RFC 0001). 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 (CLAUDE.md): an internal\n * `*OptionsSchema` const, a public inferred type, and a resolver. Slice 2\n * ships `after` / `at`; recurrence (`every`) extends this in Slice 3 (#1092).\n *\n * @internal\n */\n\nimport { z } from \"zod\";\nimport type { Committed, DeferWhen, Schemas } from \"../types/index.js\";\nimport { DeferSignal } from \"./defer-signal.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 *\n * @internal\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. @internal */\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 *\n * @internal\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 *\n * @internal\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 *\n * @internal\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 *\n * @internal\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 * @module drain-cycle\n * @category Internal\n *\n * Two layers of the drain pipeline:\n *\n * - {@link run_drain_cycle} — pure function for one round-trip of\n *   claim → fetch → group → dispatch → ack/block. No orchestrator state.\n *   Reusable for property tests and standalone benchmarks.\n *\n * - {@link DrainController} — stateful driver that owns the armed flag,\n *   the concurrency lock, and the adaptive lag/lead ratio. Wraps\n *   `run_drain_cycle` with the lifecycle decisions Act used to make inline.\n *\n * @internal\n */\n\nimport { randomUUID } from \"node:crypto\";\nimport { log } from \"../ports.js\";\nimport type {\n  BatchHandler,\n  BlockedLease,\n  CloseTarget,\n  Drain,\n  DrainOptions,\n  Fetch,\n  Lease,\n  Logger,\n  ReactionPayload,\n  Registry,\n  SchemaRegister,\n  Schemas,\n} from \"../types/index.js\";\nimport type { CircuitBreaker } from \"./circuit-breaker.js\";\nimport { DeferTimer } from \"./defer-timer.js\";\nimport type { DrainOps } from \"./drain.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/**\n * Outcome of processing a single leased stream — produced by Act's `handle`\n * / `handle_batch` dispatchers, consumed by `run_drain_cycle` to drive ack/block.\n *\n * @internal\n */\nexport type HandleResult = Readonly<{\n  lease: Lease;\n  handled: number;\n  /**\n   * Event id at which the ack would land — the last *successful* event\n   * id, or `lease.at` when the batch had no work (empty payloads). Named\n   * `acked_at` to pair symmetrically with {@link failed_at} and to keep\n   * it visually distinct from `Lease.at` (the pre-cycle watermark — same\n   * field name across types but a different semantic).\n   */\n  acked_at: number;\n  error?: string;\n  block?: boolean;\n  /**\n   * Wall-clock timestamp (ms since epoch) at which the next attempt on\n   * this stream may run. Populated by `_finalize` only on retry paths\n   * where the reaction defined `options.backoff`. Undefined means \"no\n   * backoff configured\" — drain re-attempts as soon as the lease expires.\n   */\n  next_attempt_at?: number;\n  /**\n   * Wall-clock timestamp (ms since epoch) at which this stream should be\n   * re-visited. Set by a handler that *defers* instead of acking or\n   * failing: the triggering events stay pending (watermark not advanced),\n   * `retry` is not bumped (a defer is not a failure), and the drain holds\n   * the stream until `defer` elapses, then redelivers so the handler can\n   * re-evaluate. This is the timing primitive autoclose rides (#1090);\n   * unlike {@link next_attempt_at} (a retry-only backoff), a defer carries\n   * no error and never blocks. When present, the result is excluded from\n   * ack and block — it neither advances nor terminates the watermark.\n   */\n  defer?: number;\n  /**\n   * Close request (#1090). Set when a handler throws `CloseSignal` to retire\n   * its stream: the triggering event is acked (so the closing reaction isn't\n   * seen as an in-flight consumer by the close-cycle safety guard) and the\n   * drain hands this {@link CloseTarget} to the orchestrator's `on_close`,\n   * which runs `run_close_cycle`. Carries the optional archiver from the\n   * signal. Distinct from {@link defer} (hold for later) — a close advances\n   * and retires.\n   */\n  close?: CloseTarget;\n  /**\n   * Event id that threw, when a handler error occurred. Distinct from\n   * {@link acked_at}: `failed_at = acked_at + 1` in dense streams, but\n   * adapters with sparse ids give the trace the exact position. Always\n   * set on the per-event error path; absent in batch mode (where no\n   * single event id can be attributed to the failure).\n   */\n  failed_at?: number;\n}>;\n\n/**\n * Per-event reaction dispatcher signature (matches `Act.handle`).\n * @internal\n */\nexport type Handle<TEvents extends Schemas> = (\n  lease: Lease,\n  payloads: ReactionPayload<TEvents>[]\n) => Promise<HandleResult>;\n\n/**\n * Bulk reaction dispatcher signature (matches `Act.handle_batch`).\n * @internal\n */\nexport type HandleBatch<TEvents extends Schemas> = (\n  lease: Lease,\n  payloads: ReactionPayload<TEvents>[],\n  batchHandler: BatchHandler<TEvents>\n) => Promise<HandleResult>;\n\n/**\n * One drain cycle's results. Returned by {@link run_drain_cycle}; consumed by\n * `Act.drain()` to update lifecycle state, the lag/lead ratio, and emit the\n * `acked` / `blocked` lifecycle events.\n *\n * @internal\n */\nexport type 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  /** Streams a handler asked to close this cycle (#1090) — handed to `on_close`. */\n  readonly closeable: CloseTarget[];\n};\n\n/**\n * Terminal result for a stream whose retry budget was spent without a single\n * attempt ever reaching the block decision — or `undefined` when the stream\n * still has budget.\n *\n * The budget is consulted on the *error* path (`finalize` returns early when\n * a handler didn't throw), so it only terminates handlers that fail loudly. A\n * handler that fails by overrunning its lease never throws: it completes,\n * submits an ack the store drops (`WHERE leased_by = by`), and the next claim\n * bumps `retry` again. `retry` climbs without bound, the watermark never\n * advances, and the side effect re-runs forever — the one outcome\n * `blockOnError` exists to prevent (#1418).\n *\n * The threshold is strictly greater than `maxRetries`, not `>=`, and that is\n * load-bearing. A stream legitimately reaches `retry === maxRetries` on its\n * final attempt, which `finalize` is entitled to run and block only if it\n * fails again. Blocking here at `>=` would take that attempt away and change\n * every error-driven path. At `>` the only way to arrive is with the budget\n * already spent and no attempt having produced an error — a lease lost every\n * single round, which is the stuck stream and nothing else.\n *\n * Gated on `blockOnError` for the same reason `finalize` is: an operator who\n * opted out of blocking chose \"retry forever,\" and that choice holds here too.\n *\n * Skipped entirely while the store is failing. `claim` writes the counter up\n * before a handler runs, and only a completed pass resets it, so a pass that\n * dies on a store call leaves a count behind that no handler earned. A few of\n * those in a row look exactly like a lost lease from here, and quarantining a\n * healthy stream over a database hiccup is the worse mistake — the store\n * recovering resets the counter on its own.\n *\n * @internal\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: raise leaseMillis for this 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 * Report a misrouted resolution once per offending declaration.\n *\n * All three key parts are declared, not resolved — which is the rule\n * `report-once` states and the one #1584 caught the lane reporters breaking.\n * `stream` looks like the runtime target that trap is about, but it is only\n * ever a key of `batch_handlers`, and those are the projections' *static*\n * targets: one per projection declaration, bounded by the build, never one\n * per aggregate. A handler registered on several events misroutes once per\n * event, and each of those is its own `.on(E).do(h).to(fn)` to fix.\n */\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\n/**\n * Run one drain cycle: claim streams, fetch their events, dispatch\n * matching reactions, ack the successes, block the retries-exhausted.\n *\n * Returns `undefined` when nothing was claimed — caller can short-circuit\n * the rest of the drain pass.\n *\n * **Deferred streams** (backoff windows and explicit defers) are excluded\n * upstream by `claim`: their persisted `deferred_at` gates re-dispatch, so\n * they never reach this cycle until the schedule elapses.\n *\n * @internal\n */\nexport async function run_drain_cycle<\n  TEvents extends Schemas,\n  TActions extends Schemas,\n  TSchemaReg extends SchemaRegister<TActions>,\n>(\n  ops: DrainOps<TEvents>,\n  registry: Registry<TSchemaReg, TEvents, TActions>,\n  batch_handlers: Map<string, BatchHandler<TEvents>>,\n  misrouted: Set<string>,\n  /** The store failed on the previous pass — see {@link budget_exhausted}. */\n  store_failing: boolean,\n  handle: Handle<TEvents>,\n  handle_batch: HandleBatch<TEvents>,\n  lagging: number,\n  leading: number,\n  eventLimit: number,\n  leaseMillis: number,\n  /**\n   * Emitted as soon as `block` confirms, BEFORE the `ack` that follows.\n   * A block is terminal: every adapter gates `block` on `blocked = false`\n   * and excludes a blocked stream from `claim`, so it never runs again for\n   * that stream. If the emit waited until the end of the cycle, an `ack`\n   * failure in between would lose the `blocked` event permanently (#1390).\n   */\n  on_blocked: (blocked: BlockedLease[]) => void,\n  lane?: string\n): Promise<DrainCycle<TEvents> | undefined> {\n  // Atomically discover and lease streams (competing consumer pattern)\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  // Fetch events for each leased stream. Streams in a backoff window are\n  // already excluded here: the store persists `deferred_at` on a due-marked\n  // ack and `claim` skips streams whose schedule hasn't elapsed (#1262), so\n  // a paced retry never reaches dispatch and no local skip-gate is needed.\n  const fetched = await ops.fetch(leased, eventLimit);\n\n  // Build a single index keyed by stream — collapses two passes\n  // (payloads_map build + per-lease fetched.find) into one Map lookup.\n  type FetchEntry = (typeof fetched)[number];\n  const fetch_map = new Map<\n    string,\n    { fetch: FetchEntry; payloads: ReactionPayload<TEvents>[] }\n  >();\n\n  // compute fetch window max event id\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    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          const resolved = dynamic ? resolver(event) : resolver;\n          if (!resolved || resolved.target !== stream) return false;\n          // A stream a projection serves is served by that projection alone:\n          // every payload here goes to its batch handler, so a reaction\n          // resolving onto it would never run AND would hand the projection\n          // an aggregate it knows nothing about (#1563).\n          //\n          // `dynamic` is an exact discriminator, not a heuristic: a STATIC\n          // reaction onto a projection's target is rejected at build, and a\n          // projection's own consumption is synthesized static. So a dynamic\n          // resolution landing here is by definition the misrouting the build\n          // guard could not see, because the target was a function until now.\n          if (!dynamic || !batch_handlers.has(stream)) return true;\n          // Say so. The build guard REFUSES this configuration, and dropping\n          // its dynamic twin without a word would leave an operator with a\n          // reaction that silently never runs — the half of #1563 that has no\n          // error, no retry and nothing in `blocked_streams()`.\n          //\n          // A throw is not available here: `:693` hands anything thrown to\n          // the circuit breaker as a store failure, so a config error that\n          // never resolves itself would stall the whole drain on a cooldown\n          // loop. Once per distinct misrouting, because a resolver returning\n          // a bad target does so for every matching event.\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 });\n  }\n\n  const handled = await Promise.all(\n    leased.map((lease) => {\n      // fetch() returns one entry per leased stream — fetch_map.get is\n      // always defined here (asserted with `!`).\n      const entry = fetch_map.get(lease.stream)!;\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  // Finalize the cycle in one atomic store call. Every entry advances the\n  // watermark to the last event fully handled this cycle, and a deferred or\n  // backing-off entry rides the same batch marked with `due` so the store\n  // ALSO persists the schedule — advance and defer are independent legs of\n  // one ack (#1278). A failed finalize lands nothing — the catch in the\n  // controller covers every outcome uniformly. Partial-success-then-block\n  // still lands in both `acked` and `blocked` for the same stream — by design.\n  //\n  // The advance target is `acked_at` (the last fully-handled event) when the\n  // batch made progress, and the pre-fetch watermark `floor` (`leased[i].at`,\n  // a no-op advance) when it did not — because on a no-progress failure\n  // `acked_at` is initialized to the fetch ceiling and would skip the failed\n  // event. `leased[i]` pairs with `handled[i]` (Promise.all preserves order),\n  // so `floor` is the untouched claim watermark.\n  //\n  // Deferring past the succeeded prefix (rather than holding the whole batch)\n  // is the point: the handled events never re-run on redelivery. A backoff\n  // retry carries the climbing `retry` so the budget keeps accruing toward\n  // `blockOnError` and the durable cross-worker window (#1262) survives; an\n  // explicit defer passes `retry: -1` because a defer is not a failure.\n  //\n  // `block` runs BEFORE `ack` (#1296). Both stores gate `block` on the lease\n  // still being held (`WHERE leased_by = by AND blocked = false`), but `ack`\n  // releases the lease (`leased_by = NULL`). A partial-progress-then-block\n  // entry (`handled > 0` AND `block: true` — e.g. a `NonRetryableError` on the\n  // second event of a batch) is passed to BOTH: `block` marks it poison\n  // without touching the watermark, then `ack` advances past the handled\n  // prefix and releases the lease. Acking first would release the lease out\n  // from under `block`, silently dropping it — the stream would re-run its\n  // permanently-failed tail next cycle. Neither store clears the watermark on\n  // `block`, so the ordering leaves both legs intact.\n  const blocked = await ops.block(\n    handled\n      .filter(({ block }) => block)\n      .map(({ lease, error }) => ({ ...lease, error: error! }))\n  );\n\n  if (blocked.length) 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 = await ops.ack(submitted);\n\n  // Every adapter gates `ack` on the lease still being held\n  // (`WHERE leased_by = by`) — correctly, since that is what stops an\n  // evicted holder from regressing a watermark a competitor advanced. But\n  // the loss came back as a SHORT RETURN with no error, and nothing compared\n  // the two, so a worker whose lease was stolen mid-handler discarded a full\n  // round of work with no signal anywhere (#1418).\n  //\n  // Deferred entries are excluded from ack's return by contract, so they are\n  // not \"missing\" — only non-due submissions are counted here.\n  const expected = submitted.filter((l) => l.due === undefined).length;\n  // `warn`, not `error`: the work is redelivered, so nothing is lost and no\n  // operator action is required for this occurrence. Persistent drops are a\n  // sizing problem worth investigating, which is what `warn` is for (#1579).\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  // Collect close requests (#1090). A close result was already acked above\n  // (its event made progress, `defer === undefined`), which advances the\n  // requesting reaction past the terminal event so the close-cycle safety\n  // guard doesn't count it as an in-flight consumer. The orchestrator's\n  // `on_close` runs the actual `run_close_cycle`.\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\n/**\n * Empty drain result returned when the controller short-circuits (not\n * armed, locked out by a concurrent caller, claim returned nothing,\n * cycle threw).\n *\n * @internal\n */\nconst EMPTY_DRAIN: Drain<Schemas> = {\n  fetched: [],\n  leased: [],\n  acked: [],\n  blocked: [],\n};\n\n/**\n * Dependencies the {@link DrainController} needs from the orchestrator.\n * The lifecycle event sinks (`on_acked` / `on_blocked`) are callbacks so\n * this module doesn't reach back into Act's emitter.\n *\n * @internal\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  /**\n   * Close requested by a reaction (#1090). The controller calls this with the\n   * cycle's {@link CloseTarget}s after acks/blocks land; the orchestrator wires\n   * it to its `run_close_cycle` machinery (same path as `app.close`). Awaited so\n   * a slow close doesn't overlap the next cycle's claim on the controller.\n   */\n  readonly on_close: (targets: CloseTarget[]) => Promise<void>;\n  /**\n   * Shared, orchestrator-owned circuit breaker (ACT-984). Trips after\n   * repeated store failures so the drain loop stops hammering a down\n   * backend; closed/half-open let attempts through. It also surfaces each\n   * failure (via its own `on_error`, wired by the orchestrator to the\n   * `error` lifecycle event), so callers just `failed(now, error)`.\n   */\n  readonly breaker: CircuitBreaker;\n  /**\n   * Scope runner (#1191). The per-lane worker (`start`) ticks outside\n   * any caller frame, so its `drain()` must be re-wrapped in the Act's\n   * `_scoped` bag or `store()`/`cache()` resolve to the singleton for a\n   * scoped Act. The orchestrator always threads its `_scoped` (identity\n   * for a non-scoped Act), so it's required.\n   */\n  readonly run_scoped: <T>(fn: () => Promise<T>) => Promise<T>;\n  /** Lane this controller drains. Undefined = spans all lanes (legacy single-controller). */\n  readonly lane?: string;\n  /** Per-lane defaults applied when caller doesn't override via DrainOptions. */\n  readonly defaults?: {\n    readonly streamLimit?: number;\n    readonly eventLimit?: number;\n    readonly leaseMillis?: number;\n  };\n};\n\n/**\n * Stateful driver around {@link run_drain_cycle}. Owns:\n *\n * - `_armed`  — has any commit / reset / cold-start signaled work to do?\n * - `_locked` — concurrent-call guard (overlapping `drain()` calls return\n *               an empty result instead of running twice)\n * - `_ratio`  — adaptive lag-to-lead frontier split, updated per cycle\n *\n * The orchestrator owns commits, lifecycle emission, and `arm()` triggers\n * — the controller owns everything between those edges.\n *\n * @internal\n */\nexport class DrainController<\n  TEvents extends Schemas,\n  TActions extends Schemas,\n  TSchemaReg extends SchemaRegister<TActions>,\n> {\n  private _armed = false;\n  private _locked = false;\n  private _ratio = 0.5;\n  /**\n   * Per-stream re-visit schedule (#1090): `stream → next visit` (ms since\n   * epoch). Holds both retry backoff (`HandleResult.next_attempt_at`) and the\n   * `defer` outcome; cleared on successful ack or terminal block. Lives in\n   * process memory — per-worker pacing by design (see {@link BackoffOptions}\n   * for the multi-worker trade-off). Its wake re-arms drain at the earliest\n   * pending visit.\n   */\n  private readonly _defer = new DeferTimer(() => {\n    this._armed = true;\n  });\n  /** Worker timer (ACT-1103). Set when `start()` is active, undefined otherwise. */\n  private _worker: ReturnType<typeof setTimeout> | undefined;\n  /**\n   * Misroutings this controller has reported (#1563). A resolver returning a\n   * projection's target does so for every matching event; one line per event\n   * would bury the signal it exists to raise.\n   */\n  private readonly _misrouted = new Set<string>();\n  private _stopped = false;\n  /**\n   * Resolves when the cycle currently in flight finishes; `undefined` when\n   * no cycle is running (#1442). `_locked` answers \"is a cycle running?\" for\n   * the overlap guard; this answers \"tell me when it is done\" for a graceful\n   * shutdown, which needs to await the handler rather than abandon it\n   * mid-`await` with the stream still leased. Never rejects — `drain()`\n   * contains its own errors — so awaiting it is always safe.\n   */\n  private _inflight: Promise<void> | undefined;\n  private _inflight_done: (() => void) | 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  /**\n   * Signal that a commit (or reset / cold-start) may have produced work.\n   * Subsequent `drain()` calls will run the pipeline; once the pipeline\n   * settles to no-progress, the controller disarms itself.\n   */\n  arm(): void {\n    this._armed = true;\n  }\n\n  /**\n   * Re-seed a persisted defer schedule into the process-local timer at cold\n   * start (#1221). The `_defer` map lives in worker memory and is empty\n   * after a restart; a stream deferred to a future due-time (e.g. an idle\n   * autoclose aggregate) is durable in the store's `deferred_at` but has\n   * nothing in memory to re-arm the drain at the due-time. The orchestrator\n   * reads the persisted `deferred_at` for this controller's lane and calls\n   * this to park the stream + (re)schedule the shared wake — so the drain\n   * re-arms at the due-time with no intervening commit. `schedule()`\n   * collapses many seeds into one timer, so callers may seed in a loop and\n   * let the earliest due-time win.\n   */\n  seed_defer(stream: string, at: number): void {\n    this._defer.set(stream, at);\n    this._defer.schedule();\n  }\n\n  /** Read-only flag — true while a commit / reset is unprocessed. */\n  get armed(): boolean {\n    return this._armed;\n  }\n\n  /**\n   * The cycle currently in flight, or `undefined` when idle (#1442). A\n   * graceful shutdown awaits this so an in-flight handler reaches its `ack`\n   * — which releases the stream's lease — instead of being abandoned with\n   * the lease held until it expires.\n   */\n  get inflight(): Promise<void> | undefined {\n    return this._inflight;\n  }\n\n  /**\n   * This lane's configured lease budget, or `undefined` when the lane didn't\n   * pin one. It is the operator's own statement of how long a handler may\n   * legitimately hold a stream, which makes it the right basis for a\n   * shutdown grace budget (#1442).\n   */\n  get lease_millis(): number | undefined {\n    return this._deps.defaults?.leaseMillis;\n  }\n\n  /** Lane this controller drains (undefined = legacy single-lane span). */\n  get lane(): string | undefined {\n    return this._deps.lane;\n  }\n\n  /**\n   * Start a per-lane worker that drains at the lane's `cycleMs`\n   * cadence (ACT-1103). When armed, the worker calls `drain()` on every\n   * tick and re-schedules; when not armed, it still re-schedules at\n   * `cycleMs` so a future `arm()` is picked up on the next tick.\n   *\n   * The setTimeout chain uses `unref()` so it doesn't keep the process\n   * alive on its own.\n   */\n  start(cycleMs: number): void {\n    if (this._worker || this._stopped) return;\n    // `drain()` swallows its own errors and returns EMPTY_DRAIN, so the\n    // tick is exception-free by contract. The post-drain `_stopped`\n    // check prevents re-scheduling after `stop()` was called mid-tick;\n    // an already-queued timer that fires before `clearTimeout()` lands\n    // will run at most one extra drain (drain is idempotent against\n    // a non-armed controller and self-disarms when settled).\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 the per-lane worker. Idempotent. */\n  stop(): void {\n    this._stopped = true;\n    if (this._worker) {\n      clearTimeout(this._worker);\n      this._worker = undefined;\n    }\n    // Drop any pending re-visit wake — the parked set is process-local and\n    // rebuilt from the log on the next start (#1090).\n    this._defer.stop();\n  }\n\n  /** Run one drain pass. Short-circuits when not armed or already running. */\n  async drain(options: DrainOptions = {}): Promise<Drain<TEvents>> {\n    if (!this._armed) return EMPTY_DRAIN as Drain<TEvents>;\n    if (this._locked) return EMPTY_DRAIN as Drain<TEvents>;\n    // Circuit open: the store is failing, skip the claim entirely so we\n    // don't hammer a down backend. `_armed` stays set, so the next tick\n    // after the cooldown (half-open) retries.\n    if (this._deps.breaker.state(Date.now()) === \"open\")\n      return EMPTY_DRAIN as Drain<TEvents>;\n\n    const d = this._deps.defaults ?? {};\n    // Per-lane config wins over caller options (ACT-1103). The whole\n    // point of `withLane({leaseMillis: 30_000})` is to give the slow\n    // lane its own budget — a caller-level drain({leaseMillis}) would\n    // erase it. Caller options apply only when the lane didn't pin a\n    // value.\n    const streamLimit = d.streamLimit ?? options.streamLimit ?? 10;\n    const eventLimit = d.eventLimit ?? options.eventLimit ?? 10;\n    const leaseMillis = d.leaseMillis ?? options.leaseMillis ?? 10_000;\n\n    try {\n      this._locked = true;\n      this._inflight = new Promise<void>((done) => {\n        this._inflight_done = done;\n      });\n      const lagging = Math.ceil(streamLimit * this._ratio);\n      const leading = streamLimit - lagging;\n\n      const cycle = await run_drain_cycle(\n        this._deps.ops,\n        this._deps.registry,\n        this._deps.batch_handlers,\n        this._misrouted,\n        this._deps.breaker.failing,\n        this._deps.handle,\n        this._deps.handle_batch,\n        lagging,\n        leading,\n        eventLimit,\n        leaseMillis,\n        (b) => this._deps.on_blocked(b),\n        this._deps.lane\n      );\n\n      // The store responded (claim/fetch/ack+defer/block all succeeded) —\n      // reset the breaker even when there was no work to do. A failed\n      // finalize never reaches here: `Store.ack` applies watermarks and\n      // defer schedules atomically, so it either all landed or the\n      // whole cycle threw into the catch below and nothing did.\n      if (!cycle) {\n        // claim() returned no leases — fully caught up\n        this._deps.breaker.passed();\n        this._armed = false;\n        return EMPTY_DRAIN as Drain<TEvents>;\n      }\n\n      const { leased, fetched, handled, acked, blocked, closeable } = cycle;\n\n      // Cycle-level trace (ACT-1103) — one log line per drain pass:\n      // claim + fetch + outcomes folded together so the operator sees\n      // a single atomic narrative for each cycle. No-op when the\n      // logger isn't at trace level.\n      trace_cycle(this._deps.logger, leased, fetched, handled, acked, blocked);\n\n      // Adapt next cycle's frontier split to where the pressure is.\n      this._ratio = compute_lag_lead_ratio(handled, lagging, leading);\n\n      // Refresh per-stream re-visit state from this cycle's outcomes.\n      // Successful acks and terminal blocks both clear the window;\n      // retry-not-block results carry a `next_attempt_at` set by `_finalize`,\n      // and deferred results carry a `defer` due-time (#1090). Both park the\n      // stream in `_defer` so the shared wake timer re-arms drain at the\n      // earliest pending visit. `handle` already reconciles a stream's\n      // reactions into a single result per cycle, so the value written here\n      // is authoritative for the stream — a plain overwrite, not a merge.\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.block ? undefined : h.next_attempt_at);\n        if (next !== undefined) this._defer.set(h.lease.stream, next);\n      }\n      if (this._defer.size > 0) this._defer.schedule();\n\n      // Lifecycle sinks are contained individually, mirroring the\n      // `notified` handler in `act.ts`. The durable work is already\n      // committed by this point, so a throwing listener must not unwind\n      // into the store-error `catch` below: that would report a store\n      // failure that never happened, return an empty Drain, and — because\n      // `block` is guarded on `blocked = false` and a blocked stream is\n      // excluded from `claim` — permanently lose the `blocked` event and\n      // any reaction-requested close. Listener containment itself lives in\n      // `Act.emit`, which guards each listener individually (#1437) — the\n      // sinks here are plain calls.\n      if (acked.length) this._deps.on_acked(acked);\n      // Run reaction-requested closes after acks land (#1090) — the close\n      // targets were acked above, so the close-cycle guard sees the requesting\n      // reaction as caught up. Awaited so a slow close doesn't overlap the\n      // next claim.\n      // NOT contained: `on_close` runs the close machinery (load,\n      // tombstone, archive, truncate), not an emit. A StoreError raised in\n      // there is a real store failure and must reach the breaker via the\n      // catch below, or an outage silently bricks streams while the\n      // breaker records a success (#1388). The `closed` EMIT is contained\n      // on the Act side, which is the only listener risk on this path.\n      if (closeable.length) await this._deps.on_close(closeable);\n\n      // Recorded after `on_close` so a cycle whose close failed is never\n      // counted as a store success (#1388).\n      this._deps.breaker.passed();\n\n      // Disarm only when fully caught up. Errors keep the flag set so\n      // retries flow through the next drain.\n      const has_errors = handled.some(({ error }) => error);\n      if (!acked.length && !blocked.length && !has_errors) this._armed = false;\n\n      return { fetched, leased, acked, blocked };\n    } catch (error) {\n      // A store op threw (StoreError, or any failure mid-cycle). Record it\n      // on the breaker, which logs it and surfaces the `error` lifecycle\n      // event. `_armed` stays set so the breaker's retry re-attempts after\n      // the cooldown. EMPTY_DRAIN keeps the worker tick exception-free.\n      this._deps.breaker.failed(Date.now(), error);\n      return EMPTY_DRAIN as Drain<TEvents>;\n    } finally {\n      this._locked = false;\n      // Release anyone awaiting this cycle (a graceful shutdown) before the\n      // next one can start.\n      this._inflight = undefined;\n      this._inflight_done?.();\n      this._inflight_done = undefined;\n    }\n  }\n}\n","/**\n * @module defer-timer\n * @category Internal\n *\n * The shared \"next visit time\" primitive (#1090). 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, garbage-collecting the entries that have\n * come due.\n *\n * Two consumers ride it:\n *\n * - the {@link \"drain-cycle\".DrainController} — for per-reaction backoff (a\n *   retry's `next_attempt_at`) and, once handlers can express it, the\n *   `defer` outcome that holds a stream pending without advancing the\n *   watermark or bumping `retry`.\n * - the autoclose controller — to schedule its next eligibility check at the\n *   precise time an `after`-style cooldown elapses, instead of a blind\n *   fixed-interval sweep.\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 * (#1221), so an idle deferred stream re-arms at its due-time with no\n * intervening commit.\n *\n * @internal\n */\n\n/**\n * A min-heap-free scheduler over a small `stream → due-time` map. The maps\n * are bounded by the worker's claim/stream limits, so a linear scan for the\n * earliest entry is cheaper than maintaining a heap.\n *\n * @internal\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 *\n * @internal\n */\nconst MAX_TIMER_DELAY_MS = 2_147_483_647;\n\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   *   after the come-due entries have been removed. Consumers use it to\n   *   re-arm their loop (the drain sets its `armed` flag; autoclose runs a\n   *   tick).\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   * True while `stream` is parked with a due-time still in the future.\n   * Consumers skip work for deferred streams until their window elapses.\n   */\n  is_deferred = (stream: string): boolean => {\n    const next = this._due.get(stream);\n    return next !== undefined && next > Date.now();\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   * (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    // Clamp to setTimeout's 32-bit ceiling (~24.8 days). A longer due-time\n    // (e.g. a 90-day autoclose cooldown) would otherwise overflow and Node\n    // fires it immediately, busy-looping. Instead we wake at the ceiling and\n    // re-arm: the GC below keeps the still-future entry, `on_wake` re-schedules\n    // for the remaining span, and (for persisted defers) `claim` skips the\n    // stream until its real due-time anyway.\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      // Garbage-collect the entries that have come due so the consumer's\n      // next pass sees them as active again.\n      const now = Date.now();\n      let came_due = false;\n      for (const [stream, at] of this._due)\n        if (at <= now) {\n          this._due.delete(stream);\n          came_due = true;\n        }\n      this._on_wake();\n      // Premature ceiling clamp: nothing came due, yet entries remain — the\n      // earliest due-time was past the 32-bit `setTimeout` ceiling, so this\n      // wake fired early. The consumer's `on_wake` won't re-arm (the drain's\n      // just sets its armed flag, and its next pass early-returns while the\n      // stream is still store-excluded), so the primitive must self-re-arm or\n      // a >ceiling defer/cooldown loses its precise wake (#1288). A normal wake\n      // (something came due) leaves re-arming to the consumer, preserving the\n      // fire-once-per-schedule model.\n      if (!came_due && this._due.size > 0) this.schedule();\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 * @module drain-ratio\n * @category Internal\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 * @internal\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 * @module drain\n * @category Internal\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 * @internal\n */\n\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\";\nimport { is_literal_source } from \"../utils.js\";\n\n/** @internal */\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 the has-work probe claimed it for.\n      const stream_exact =\n        source !== undefined && is_literal_source(source) ? true : undefined;\n      await store().query<TEvents>((e) => events.push(e), {\n        stream: source,\n        stream_exact,\n        after: at,\n        limit: eventLimit,\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 * @module event-sourcing\n * @category Internal\n *\n * Pure event-sourcing primitives: `snap` persists state checkpoints, `load`\n * reconstructs state by folding events through reducers, and `action`\n * validates an action, runs invariants, emits events, and commits them\n * atomically. `tombstone` commits the close-the-books guard with optimistic\n * concurrency.\n *\n * These are the bare implementations — observability is layered on top in\n * {@link \"tracing\"} and wired by the orchestrator at construction time.\n * No tracing imports here, no module-level mutable state.\n *\n * @internal\n */\n\nimport { type Patch, patch } from \"@rotorsoft/act-patch\";\nimport { cache, log, SNAP_EVENT, store, TOMBSTONE_EVENT } from \"../ports.js\";\nimport {\n  ConcurrencyError,\n  InvariantError,\n  StreamClosedError,\n} from \"../types/errors.js\";\nimport type {\n  Committed,\n  Correlator,\n  DoOptions,\n  Emitted,\n  EventMeta,\n  EventSource,\n  LoadTarget,\n  ScanOptions,\n  ScanResult,\n  Schema,\n  Schemas,\n  Snapshot,\n  State,\n  Target,\n} from \"../types/index.js\";\nimport { sleep, validate } from \"../utils.js\";\nimport { compute_backoff_delay } from \"./backoff.js\";\nimport { default_correlator } from \"./correlator.js\";\n\n/**\n * The reduction pipeline names three distinct things, and each word means\n * exactly one of them:\n *\n * - a **reducer** is a state's `.patch()` handler — it takes one event and\n *   returns a {@link Patch} *partial*;\n * - a **patch step** ({@link bare_patch} / {@link validating_patch}) merges\n *   that partial into the current state, yielding the next full state;\n * - the **fold** is the loop that applies the patch step across a stream's\n *   events (the reader loop in {@link load} / {@link action}, and the\n *   projection engine in {@link \"projection-fold\"}).\n *\n * `PatchFn` is the per-event patch step. The fold loop calls one of two\n * implementations, selected **once** at construction (in\n * {@link \"tracing\".build_es}) — never branched per event:\n *\n * - {@link bare_patch} — the default. Literally `patch(state, partial)`,\n *   no wrapper. This is the pre-ACT-1238 hot path, byte-for-byte.\n * - {@link validating_patch} — the opt-in `ActOptions.validateFoldedState`\n *   path. Merges, then parses the merged full state against the state's\n *   declared Zod schema.\n *\n * The `me`/`event` arguments are unused by the bare implementation but\n * carried on the shared signature so the fold loop is call-shape-identical\n * regardless of which patch step was selected — the validating\n * implementation needs them to name the failing reduction.\n *\n * @internal\n */\nexport type PatchFn = <\n  TState extends Schema,\n  TEvents extends Schemas,\n  TActions extends Schemas,\n>(\n  me: State<TState, TEvents, TActions>,\n  state: TState,\n  partial: Readonly<Patch<TState>>,\n  event: Committed<TEvents, keyof TEvents>\n) => TState;\n\n/**\n * The default patch step: a bare `patch()` merge with no wrapper and no\n * branch. The off-path is byte-for-byte the pre-ACT-1238 reduction, so an\n * app that leaves `validateFoldedState` off pays nothing — not even a\n * comparison.\n *\n * @internal\n */\nexport const bare_patch: PatchFn = (_me, state, partial) =>\n  patch(state, partial) as typeof state;\n\n/**\n * The opt-in patch step (ACT-1238): merge the partial into state, then\n * parse the merged full state against the owning state's declared Zod\n * schema. A reducer that produces schema-violating state (the calculator\n * divide-by-zero NaN class, #1230) fails here, at the triggering event,\n * instead of propagating and surfacing hops later as a confusing\n * downstream error.\n *\n * The `target` string names the state and the triggering event\n * (`\"<state>.<event>#<id>\"`) so the resulting {@link ValidationError}\n * points straight at the reduction that produced bad state. A debugging /\n * CI aid, not a production guard — selected only when the operator opts\n * in.\n *\n * @internal\n */\nexport const validating_patch: PatchFn = (me, state, partial, event) => {\n  const next = patch(state, partial) as typeof state;\n  return validate(\n    `${me.name}.${String(event.name)}#${event.id}`,\n    next,\n    me.state\n  );\n};\n\n/**\n * Default per-batch row count for the {@link scan} pagination loop\n * (ACT-1133). Callers override via {@link ScanOptions.batch_size}.\n *\n * @internal\n */\nconst DEFAULT_BATCH = 500;\n\n/**\n * Internal action signature seen by the orchestrator — the {@link Correlator}\n * is bound at `build_es` time, so callers don't pass it through.\n *\n * @internal\n */\nexport type 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\n/** @internal */\nexport interface EsOps {\n  snap: typeof snap;\n  load: typeof load;\n  action: BoundAction;\n  tombstone: typeof tombstone;\n}\n\n/**\n * Event sourcing utilities for snapshotting, loading, and committing actions/events.\n * Used internally by Act and state machines.\n */\n\n/**\n * Saves a snapshot of the state to the store.\n *\n * Snapshots are used to optimize state reconstruction for aggregates with long event streams.\n *\n * @template TState The type of state\n * @template TEvents The type of events\n * @param snapshot The snapshot to save\n * @returns Promise that resolves when the snapshot is saved\n *\n * @example\n * await snap(snapshot);\n */\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      stream,\n      [{ name: SNAP_EVENT, data: snapshot.state }],\n      {\n        correlation: meta.correlation,\n        causation: { event: { id, name: name as string, stream } },\n      },\n      version // IMPORTANT! - state events are committed right after the snapshot event\n    );\n    return committed as Committed<TEvents, keyof TEvents>;\n  } catch (error) {\n    // Swallow by design — a failed snapshot must never fail the action.\n    // But surface an operator signal: a persistently failing snapshot\n    // write silently degrades every cold start to full replay.\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 a tombstone event with optimistic concurrency, returning the\n * committed record on success or `undefined` if the stream moved past\n * `expectedVersion` (concurrent write detected). Other store errors\n * propagate.\n *\n * Used by `close()` to guard a stream while archive/truncate runs:\n * subsequent `action()` calls see the tombstone at head and reject with\n * {@link StreamClosedError} until the close completes.\n *\n * @internal\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      stream,\n      [{ name: TOMBSTONE_EVENT, data: {} }],\n      { correlation, causation: {} },\n      expectedVersion\n    );\n    return committed;\n  } catch (error) {\n    if (error instanceof ConcurrencyError) return undefined;\n    throw error;\n  }\n}\n\n/**\n * Per-event blocker check. Categories:\n *\n * - **Negative `version`** — versions are unsigned in the framework\n *   contract.\n * - **Malformed `created`** — `event.created` must be a valid Date\n *   instance. Restore sources stream parsed events; the orchestrator\n *   trusts the caller's iterator did the parsing.\n *\n * Cross-event invariants (duplicate ids, per-stream version gaps) are\n * not the validator's job — DB `UNIQUE(stream, version)` catches\n * duplicates at commit time, and gap detection is a caller-specific\n * policy (partial backups intentionally have gaps).\n *\n * Extension point: per-event Zod schema validation against the active\n * registry will land here — the source-side check is the right layer\n * for it (catches malformed payloads before the sink transaction\n * opens), and adding it keeps the per-event blocker contract in one\n * place.\n *\n * @internal\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 * Scan a restore source event by event. Owns pagination, validation,\n * the `drop_snapshots` filter, the `on_progress` callback, and the\n * causation remap; adapters supply only the per-event insert\n * `callback` via the driver pattern (see {@link Store.restore}).\n *\n * Walks the source in chunks of {@link BATCH} via the existing\n * `EventSource.query` interface — `limit: BATCH` and `after: <last\n * id seen>` per batch (ACT-1133). Stores that respect `limit`\n * (`PostgresStore`) return at most `BATCH` rows per call; sources\n * that ignore the filter (`CsvFile`) stream everything in one call\n * and the loop exits after the first batch when `got > BATCH`. The\n * source's own per-event `await Promise.resolve(callback(event))`\n * provides backpressure — no separate mailbox needed.\n *\n * Throws on the first invalid event (negative version, malformed\n * `created`) with the running index in the message.\n *\n * Returns the partial {@link ScanResult} (without `duration_ms`)\n * — {@link Act.restore} wraps the call with its own timing so the\n * duration covers transaction setup and commit, not just iteration.\n *\n * @internal\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  // Pre-pass for `drop_closed_streams` (ACT-1126). Walk the source\n  // once with a tombstone-name filter to collect closed streams. PG\n  // honors the filter and only the tombstone events come back; sources\n  // that ignore the filter (CsvFile) stream all events but we cheaply\n  // pick out the tombstones in the callback. Either way the cost is\n  // one extra walk, paid only when the operator opts in.\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 source for the highest id once up front. On indexed\n  // stores (PostgresStore, SqliteStore) `{ backward: true, limit: 1 }`\n  // is an index-only seek — O(1) on the (id) index. Sources that\n  // ignore the filter (CsvFile) stream every event from this one\n  // call; we detect that via the returned count and leave max_id\n  // undefined rather than reporting an unreliable value.\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 }\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          // Drop pre-close events but KEEP the tombstone — it's what\n          // makes the stream \"closed\" in the rebuilt store. Without\n          // it, a future `app.do(...)` against this stream name would\n          // succeed because nothing gates it.\n          dropped_closed++;\n          return;\n        }\n        // Migration overlay (ACT-1126): rename + schema-guarded data\n        // transform, then optional stream rename. Applied BEFORE the\n        // causation remap so the id_map (keyed by source id) stays\n        // valid and migrated events land at the new name/data with\n        // their causation chains intact.\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        // Causation remap — rewrite `meta.causation.event.id` to the\n        // new id space if the source pointed at an earlier event's\n        // old id.\n        let remapped = migrated;\n        const caused_by = migrated.meta.causation.event?.id;\n        if (caused_by !== undefined) {\n          const new_caused_by = id_map.get(caused_by);\n          if (new_caused_by !== undefined && new_caused_by !== caused_by) {\n            // Spread `migrated`, not the original `event` (ACT-1192).\n            // Migration + stream_rename already ran above; rebuilding from\n            // `event` here would revert the new name/data/stream for any\n            // event whose causation id shifted — silently undoing the\n            // migration for most rows after the first id shift.\n            remapped = {\n              ...migrated,\n              meta: {\n                ...migrated.meta,\n                causation: {\n                  ...migrated.meta.causation,\n                  event: {\n                    ...migrated.meta.causation.event!,\n                    id: new_caused_by,\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 }\n    );\n\n    // Termination:\n    //   - got < batch: source honored limit but ran out (also covers\n    //     got === 0 — past-the-end on a paginating source).\n    //   - got > batch: source ignored the filter (CsvFile-style). It\n    //     streamed everything in one call; nothing left to ask for.\n    //   Otherwise (got === batch): more events may exist; bump and continue.\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 * Loads a snapshot of the state from the store by folding events through the\n * state's patch reducers.\n *\n * First checks the cache for a checkpoint, then queries the store for events\n * committed after the cached position. On cache miss, replays from the store\n * (using snapshots if available to avoid full replay).\n *\n * @template TState The type of state\n * @template TEvents The type of events\n * @template TActions The type of actions\n * @param me The state machine definition.\n * @param stream The stream (instance) to load\n * @param callback (Optional) Callback to receive the loaded snapshot as it is built\n * @param asOf (Optional) Time-travel cursor; bypasses the cache.\n * @param actor (Optional) Passed through to the state's `view` delegate\n *   when constructing the snapshot.event — semantics are the state's to\n *   define (see {@link state}).\n * @returns The snapshot of the loaded state\n *\n * @example\n * const snapshot = await load(Counter, \"counter1\");\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  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  // replayed counts events processed by THIS load only (snap or patch);\n  // distinct from `patches` (the snap-distance accumulator carried over\n  // from the cache).\n  let replayed = 0;\n  let event: Committed<TEvents, keyof TEvents> | undefined;\n\n  await store().query<TEvents>(\n    (raw) => {\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        // Unknown event — not in this state's reducer map. Causes:\n        // deleted/renamed event in a versioned schema, load() called with\n        // the wrong state, or stream contamination. Skipping silently\n        // would corrupt replay; warn so the operator can investigate.\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      // The snapshot resume floor is a current-state optimization: it only\n      // holds when the load has no window of its own. `time_travel` already\n      // captures that (any `asOf` bound set), so request `with_snaps` only for\n      // a non-time-travel cold load — a bounded load full-scans real events\n      // under its `asOf` filter. This is the single floor-eligibility decision\n      // for the whole system; the stores apply the floor whenever asked and\n      // never re-derive it (RFC 1274).\n      //\n      // The warm path resumes from `after`, and MUST also carry `with_snaps`\n      // (#1345): `after` and `with_snaps` are independent store conditions —\n      // `after` bounds the scan (id > cached.event_id), `with_snaps` keeps\n      // `__snapshot__` rows in the result. A stale (lagging/cross-process)\n      // cache checkpoint can sit below a newer `__snapshot__` boundary, and a\n      // windowed close (`app.close`/`.autocloses({keep})`) may have pruned the\n      // domain events between the checkpoint and that snapshot. Without\n      // `with_snaps` the rebaselining snapshot is filtered out and the fold\n      // silently applies the surviving tail on top of stale state (wrong\n      // count, yet `version` still reports the true head — the concurrency\n      // guard passes). With it, the snapshot in the after-window rebaselines\n      // the fold; when no snapshot falls in the window it is a no-op.\n      ...(cached\n        ? { after: cached.event_id, with_snaps: true }\n        : { ...(time_travel ? {} : { with_snaps: true }), ...asOf }),\n    }\n  );\n\n  // Populate the cache when this load actually processed events. Without\n  // this, read-heavy paths (UI loops calling load() many times between\n  // commits) miss the cache forever — only action() would ever warm it.\n  // No race-protection re-check needed: the cache is a state checkpoint\n  // at (version, event_id), and any subsequent load queries past\n  // event_id (with `with_snaps`, so a rebaselining snapshot above the\n  // checkpoint is still folded even after a windowed close pruned the\n  // events between them — #1345), picks up missed events, and replays — so\n  // an \"older\" cache write from a concurrent slower load is self-correcting\n  // on next access. Time-travel loads bypass cache entirely and skip this too.\n  //\n  // Skip the write when the replayed head is the tombstone (ACT-1188).\n  // During the close guard window (tombstone committed, truncate pending)\n  // a cold load replays real events + the tombstone, so `replayed > 0`.\n  // Caching here would store a checkpoint at the tombstone's (version,\n  // event_id) with no `event` on the entry — the next `action()` would\n  // then get a warm hit where `snapshot.event` is undefined, its\n  // cold-path tombstone check (`snapshot.event?.name === TOMBSTONE_EVENT`)\n  // would go vacuously false, and a commit could land past the tombstone\n  // that the eventual truncate deletes. Leaving the cache cold keeps that\n  // check live on every subsequent load.\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    // Fire-and-forget the checkpoint write, mirroring action() (ACT-1206):\n    // the state is already correctly computed, so a transient failure in a\n    // remote-backed Cache (e.g. a Redis blip) must not fail the read — that\n    // would break plain reads, reaction bound_load dispatches, and the fold\n    // engine's first-sight load. The cache is self-correcting: a subsequent\n    // load queries past `event_id`, replays what it missed, and re-warms.\n    await cache()\n      .set(stream, {\n        stream,\n        state,\n        version: event.version,\n        event_id: event.id,\n        patches,\n        snaps,\n      })\n      .catch((err) =>\n        log().warn(\n          err,\n          \"cache set skipped; the next load re-folds from the store\"\n        )\n      );\n  }\n\n  return {\n    event,\n    state,\n    version: event?.version ?? cached?.version ?? -1,\n    // Head event id, captured atomically with `state`: the last replayed\n    // event's id on a cache miss, or the cached checkpoint's event_id on a\n    // warm hit with no new events. Consumers read this instead of a\n    // separate cache lookup that could race a concurrent commit (ACT-1204).\n    id: event?.id ?? cached?.event_id ?? -1,\n    patches,\n    snaps,\n    cache_hit,\n    replayed,\n  };\n}\n\n/**\n * Executes an action and emits an event to be committed by the store.\n *\n * Validates the action, applies business invariants, emits events, and\n * commits them to the event store. When the action's\n * {@link ActionOptions} declare a retry budget, the orchestrator owns\n * the loop on {@link ConcurrencyError}: cache is invalidated, optional\n * `backoff` delay is applied, and the action re-runs from `load`. Any\n * other error rethrows immediately and does not consume the budget.\n *\n * Reactions skip optimistic concurrency (commit below passes\n * `undefined` as `expectedVersion` when `reactingTo` is set), so\n * `ConcurrencyError` cannot fire on the reaction-driven path — the\n * loop is naturally a no-op there.\n *\n * @template TState The type of state\n * @template TEvents The type of events\n * @template TActions The type of action_schemas\n * @template TKey The type of action to execute\n * @param me The state machine definition\n * @param action The action to execute\n * @param target The target (stream, actor, etc.)\n * @param payload The payload of the action\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 snapshot of the committed event\n *\n * @example\n * const snapshot = await action(Counter, \"increment\", { stream: \"counter1\", actor }, { by: 1 });\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  // Resolved by the caller. `Act.do` supplies the ambient reaction context\n  // when a handler dispatched without naming one; nothing is read from\n  // outside this call.\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\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      // snapshot.version is the head version even on a warm cache hit,\n      // where snapshot.event is undefined — using the event would\n      // silently drop the optimistic guard for every cached stream.\n      // A brand-new stream (-1) stays unguarded: creations append.\n      const expected =\n        expectedVersion ??\n        (snapshot.version >= 0 ? snapshot.version : undefined);\n\n      if (me.given) {\n        const invariants = me.given[action] || [];\n        invariants.forEach(({ valid, description }) => {\n          if (!valid(snapshot.state, actor))\n            throw new InvariantError(\n              action,\n              validated,\n              target,\n              snapshot,\n              description\n            );\n        });\n      }\n\n      const result = me.on[action](validated, snapshot, target);\n      if (!result) return [snapshot];\n\n      // An empty array means no events were emitted\n      if (Array.isArray(result) && result.length === 0) {\n        return [snapshot];\n      }\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      const valid = tuples.map(([name, data]) => ({\n        name,\n        data: validate(name as string, data, me.events[name]),\n      }));\n      const emitted = valid.map((e) => me.message(e));\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 from causation metadata —\n            // callers correlate via the correlation id when they need it.\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      let committed: Committed<TEvents, keyof TEvents>[];\n      try {\n        committed = await store().commit(\n          stream,\n          emitted,\n          meta,\n          // Reactions skip the INFERRED guard: they always append against the\n          // current head. Stream leasing already serializes concurrent reactions,\n          // and forcing version checks here would turn ordinary catch-up into\n          // spurious retries. An expectedVersion the caller passed explicitly is\n          // still honored — dropping a guard the caller asked for is silent data\n          // loss, and the reaction context can reach further than the handler\n          // (detached timers, settle cycles) where the caller never intended a\n          // reaction's semantics at all.\n          reactingTo ? expectedVersion : expected\n        );\n      } catch (error) {\n        // Invalidate cache on concurrency errors — cached state is stale.\n        //\n        // Contained and NOT awaited, matching every other cache write on this\n        // path (the load checkpoint, the action checkpoint, the gapped-commit\n        // invalidate): a transient failure in a remote-backed Cache must not\n        // fail the operation. Awaiting it unguarded here did two kinds of\n        // damage (#1438). The caller got the cache's error instead of the\n        // `ConcurrencyError`, so transports mapped a Redis blip to 500 rather\n        // than 412. Worse, the substituted error failed the\n        // `instanceof ConcurrencyError` test in the retry loop below, so a\n        // conflict that would have resolved on reload+retry became a\n        // permanent failure with the work lost.\n        //\n        // The invalidate is defensive anyway: the cache is self-correcting,\n        // since a stale checkpoint is re-folded from `after: event_id`.\n        if (error instanceof ConcurrencyError) {\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        throw error;\n      }\n\n      let { state, patches } = snapshot;\n      const snapshots = committed.map((row, i) => {\n        // Actions originate from the caller — they already hold the\n        // plaintext payload they sent. No view/gate round-trip is\n        // useful; the reducer and the returned snapshot see the\n        // pre-split event directly. pii_split (in `me.message`) above\n        // is the only PII operation on the action path.\n        const event = { ...row, data: valid[i].data };\n        const p = me.patch[event.name](event, state);\n        state = patch_fn(me, state, p, event);\n        patches++;\n        return {\n          event,\n          state,\n          version: event.version,\n          id: event.id,\n          patches,\n          snaps: snapshot.snaps,\n          patch: p,\n          cache_hit: snapshot.cache_hit,\n          replayed: snapshot.replayed,\n        };\n      });\n\n      // fire and forget snaps\n      const last = snapshots.at(-1)!;\n      // Guardless commits (reactions append at head by design) can land\n      // past events this fold never saw. A gapped fold must not become\n      // a snapshot event or a cache entry — both would lie at the head\n      // position. Contiguity is cheap to prove: the first committed\n      // version extends the loaded one.\n      const contiguous = committed[0].version === snapshot.version + 1;\n      const snapped = contiguous && me.snap?.(last);\n\n      // Persist the snapshot before caching. Awaited on purpose: the\n      // snapshot event occupies the next version slot, so a follow-up\n      // action loading a pre-snap checkpoint from the cache would collide\n      // with the framework's own bookkeeping. Caching the snap checkpoint\n      // before the action returns keeps sequential callers from ever\n      // seeing a conflict they didn't cause. Failures are still\n      // swallowed inside snap() — the action never fails on it, and the\n      // cache then keeps the pre-snap checkpoint, which stays correct.\n      const snap_event = snapped ? await snap(last) : undefined;\n\n      // #861: pii-aware states (any event declaring `sensitive(...)`\n      // fields) never populate the snapshot cache — state evolves from\n      // the actor-gated event view, so the cached state would vary by\n      // caller. Pure states cache normally.\n      // Fire-and-forget — log but don't fail the action on cache write errors\n      // (e.g., transient network failures in a custom Cache adapter).\n      if (!me.pii_aware) {\n        if (contiguous)\n          cache()\n            .set<TState>(stream, {\n              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            .catch((err) =>\n              log().warn(\n                err,\n                \"cache set skipped; the next load re-folds from the store\"\n              )\n            );\n        // A gapped entry would sit at the head position with unfolded\n        // events baked in — drop the checkpoint and let the next load\n        // replay to truth instead.\n        else\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\n      return snapshots;\n    } catch (error) {\n      if (!(error instanceof ConcurrencyError)) throw error;\n      // A caller-pinned expectedVersion is a fixed target: every retry\n      // reloads and re-commits against the SAME pinned version, so the\n      // conflict is guaranteed to recur — retrying only burns the budget\n      // and sleeps out the backoff before surfacing the same terminal\n      // error. Rethrow immediately (ACT-1208). The retry loop exists to\n      // absorb races on framework-derived versions (a concurrent writer\n      // advanced the head), where the reload picks up the new head\n      // version and the next attempt can succeed.\n      if (expectedVersion !== undefined) 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 * @module tracing\n * @category Internal\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` carries both an entry log\n * and a post-commit log to preserve the diagnostic value of the historical\n * mid-function trace points.\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 * @internal\n */\n\nimport { config } from \"../config.js\";\nimport type { AsOf, Correlator, Logger, Schemas } from \"../types/index.js\";\nimport { default_correlator } from \"./correlator.js\";\nimport type { DrainOps } from \"./drain.js\";\nimport * as drain from \"./drain.js\";\nimport type { EsOps, PatchFn } 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 * (ACT-1103) 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 *\n * @internal\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 *\n * @internal\n */\nexport function build_es(\n  logger: Logger,\n  correlator: Correlator = default_correlator,\n  patch_fn: PatchFn = es.bare_patch\n): EsOps {\n  // Bake the orchestrator-level `correlator` into every `action()` call\n  // so EsOps callers don't need to thread it. A per-call\n  // `options.correlator` still wins — the orchestrator default fills in\n  // only when the caller didn't supply one.\n  //\n  // ACT-1238: the per-event patch step is selected ONCE by the builder\n  // (`act-builder.ts`) — bare vs validating — and passed in here already\n  // bound, so this factory stays agnostic to `validateFoldedState`. It\n  // just bakes the given `patch_fn` into the load/action closures, so\n  // the projection-fold engine and close-cycle callers inherit the same\n  // choice without threading anything through their own signatures. The\n  // default (`bare_patch`) keeps direct callers on the pre-#1238 path.\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      { correlator, ...options },\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, _me, _action, target) => {\n        const committed = snapshots.filter((s) => s.event);\n        if (committed.length) {\n          logger.trace(\n            committed.map((s) => s.event!.data),\n            es_caption(\n              \"committed\",\n              C_ORANGE,\n              `${target.stream}.${committed.map((s) => s.event!.name).join(\", \")}`\n            )\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 *\n * @internal\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 *\n * @internal\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 * @module projection-fold\n * @category Internal\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 (ACT-1204). 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, type PatchFn } from \"./event-sourcing.js\";\nimport { pii_strip } from \"./sensitive.js\";\n\n// The fold config schema, defaults, and resolver live in `./config.js` (the\n// single home for builder-facing config bags). This module keeps the fold\n// engine that consumes the resolved config.\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 (#1466).\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  patch_fn: PatchFn = bare_patch,\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 (#1320).\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 (ACT-1204) 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 }, undefined, patch_fn);\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 (#1465). 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 = patch_fn(\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 * @module settle\n * @category Internal\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 reentrancy flag. Everything else is\n * supplied via the `SettleDeps` callbacks so this module stays free of\n * orchestrator state.\n *\n * @internal\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\";\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 *\n * @internal\n */\nexport type SettleDeps<TEvents extends Schemas> = {\n  readonly init: () => Promise<void>;\n  readonly checkpoint: () => number;\n  readonly correlate: (\n    query: Query\n  ) => Promise<{ subscribed: number; last_id: number; scanned?: boolean }>;\n  readonly drain: (options: DrainOptions) => Promise<Drain<TEvents>>;\n  readonly on_settled: (drain: Drain<TEvents>) => void;\n  /**\n   * Shared orchestrator circuit breaker (ACT-984). The settle loop's\n   * `correlate` (subscribe + query) is a store consumer too: a successful\n   * pass records `passed()`, a failed one `failed(now, err)` — feeding the\n   * same breaker that paces the drain loop, which also surfaces the failure\n   * to the `error` lifecycle event.\n   */\n  readonly breaker: CircuitBreaker;\n};\n\n/**\n * Drives the debounced correlate→drain catch-up cycle. One instance per\n * Act orchestrator.\n *\n * @internal\n */\nexport class SettleLoop<TEvents extends Schemas> {\n  private _timer: ReturnType<typeof setTimeout> | undefined = undefined;\n  private _running = false;\n  /**\n   * Resolves when the cycle currently in flight finishes; `undefined` when\n   * idle (#1468). `_running` answers \"is a cycle running?\" for the\n   * re-arm bookkeeping; this answers \"tell me when it is done\" for a\n   * graceful shutdown.\n   *\n   * `stop()` only cancels *scheduling* — a cycle already inside its\n   * correlate → drain loop keeps going, and because `DrainController.drain`\n   * does not consult `_stopped`, it can claim a stream after teardown\n   * returned and after the store adapter was disposed. Never rejects: the\n   * cycle's own `catch` contains its errors, so awaiting this is safe.\n   */\n  private _inflight: Promise<void> | undefined;\n  /**\n   * Set when a `schedule()` timer fires while a cycle is still running\n   * (ACT-1205). The in-flight cycle's `finally` re-arms one more pass so\n   * the wake-up isn't dropped — a commit landing during the final\n   * no-progress drain pass would otherwise leave armed controllers with\n   * nothing to re-drain on an instance with no lane `cycleMs` and no\n   * polling. Carries the options of the dropped call so the re-armed\n   * pass honors its `debounceMs`/`maxPasses`/drain overrides.\n   */\n  private _pending: SettleOptions | undefined = undefined;\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. Multiple calls inside the debounce window\n   * coalesce into one cycle. The cycle runs correlate→drain in a loop\n   * until no progress is made (no new subscriptions, no acks, no blocks)\n   * or `maxPasses` is reached, then emits the `\"settled\"` lifecycle event\n   * via {@link SettleDeps.on_settled}.\n   */\n  schedule(options: SettleOptions = {}): void {\n    const {\n      debounceMs = this._default_debounce_ms,\n      correlate: correlate_query = { after: -1, limit: 100 },\n      maxPasses = Infinity,\n      ...drain_options\n    } = options;\n\n    if (this._timer) clearTimeout(this._timer);\n    this._timer = setTimeout(() => {\n      this._timer = undefined;\n      // A cycle is already running. Record this wake-up as pending rather\n      // than dropping it (ACT-1205) — the running cycle's `finally`\n      // re-schedules it so armed controllers always get one more drain.\n      if (this._running) {\n        this._pending = options;\n        return;\n      }\n      this._running = true;\n\n      let settle_done!: () => void;\n      this._inflight = new Promise<void>((done) => {\n        settle_done = done;\n      });\n\n      (async () => {\n        await this._deps.init();\n        // Accumulated across every pass, so `settled` reports what the\n        // SETTLE did rather than what its last pass did. The loop only\n        // exits on a pass that made no progress, so emitting that pass\n        // alone meant the payload was always empty — while the guide tells\n        // operators to sum `drain.fetched` for throughput (#1383).\n        let settled_drain: Drain<TEvents> | undefined;\n        // Loop correlate→drain until a pass produces no work — this fully\n        // catches up paginated streams (e.g. after `reset()` on a long\n        // projection) without forcing callers to roll their own loop.\n        // `maxPasses` caps runtime in pathological cases.\n        for (let i = 0; i < maxPasses; i++) {\n          const after_before = this._deps.checkpoint();\n          const { subscribed, last_id, scanned } = await this._deps.correlate({\n            ...correlate_query,\n            after: after_before,\n          });\n          // A scan that reached the store and came back is a real health\n          // signal; a disarmed pass that returned without touching it is not.\n          // Recording the latter would re-close an OPEN breaker mid-outage and\n          // let the drain below hammer a store nobody has heard from — the\n          // #1329 bug, which #1487 closed by making correlate always scan and\n          // #1510 reopened by letting it skip. So the question is asked per\n          // pass now, which is more accurate than either static answer.\n          if (scanned) this._deps.breaker.passed();\n          const drain = await this._deps.drain(drain_options);\n          settled_drain = settled_drain\n            ? {\n                fetched: [...settled_drain.fetched, ...drain.fetched],\n                leased: [...settled_drain.leased, ...drain.leased],\n                acked: [...settled_drain.acked, ...drain.acked],\n                blocked: [...settled_drain.blocked, ...drain.blocked],\n              }\n            : drain;\n          // `last_id > after_before` counts correlate consuming events as\n          // progress even when nothing subscribed or drained this pass — a\n          // bounded correlate window (`limit`) full of inert events would\n          // otherwise break the loop before a reactive event just past the\n          // window is ever scanned. Terminates: ids are monotonic and\n          // finite, so once no events remain `last_id === after_before`.\n          const made_progress =\n            subscribed > 0 ||\n            drain.acked.length > 0 ||\n            drain.blocked.length > 0 ||\n            last_id > after_before;\n          if (!made_progress) break;\n        }\n        // The `.catch` below treats anything it sees as a store failure,\n        // because everything else in this block is one. An uncontained\n        // listener throw was therefore recorded via `breaker.failed()` —\n        // surfacing a spurious `error` event on every settle, and, at\n        // `failureThreshold: 1`, opening the breaker so `drain` returned\n        // EMPTY_DRAIN for the whole cooldown. Each half-open recovery\n        // re-tripped it, so a broken metrics bridge stalled the reaction\n        // pipeline indefinitely (#1436). Containment now lives in\n        // `Act.emit`, which guards each listener individually (#1437), so\n        // no throw escapes `on_settled` to reach that catch.\n        if (settled_drain) this._deps.on_settled(settled_drain);\n      })()\n        .catch((err) => {\n          // correlate / init failed (a store op). Record on the shared\n          // breaker, which logs it and surfaces the `error` event; the\n          // drain loop reads the same breaker to pace itself.\n          this._deps.breaker.failed(Date.now(), err);\n        })\n        .finally(() => {\n          this._running = false;\n          this._inflight = undefined;\n          settle_done();\n          // A wake-up arrived mid-cycle. Re-arm one more pass with its\n          // options so the requested drain actually happens (ACT-1205).\n          const pending = this._pending;\n          if (pending !== undefined) {\n            this._pending = undefined;\n            this.schedule(pending);\n          }\n        });\n    }, debounceMs);\n  }\n\n  /**\n   * The cycle currently in flight, or `undefined` when idle (#1468). 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  /** Cancel any pending or active settle cycle. Idempotent. */\n  stop(): void {\n    // Drop a mid-cycle wake-up too — a stopped loop must not re-arm from\n    // the running cycle's `finally` (ACT-1205).\n    this._pending = undefined;\n    if (this._timer) {\n      clearTimeout(this._timer);\n      this._timer = undefined;\n    }\n  }\n}\n","/**\n * @module reaction-builder\n * @category Internal\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 share `_finalize`, which collapses the retry-vs-block decision and\n * the \"report error only when nothing was handled\" rule.\n *\n * @internal\n */\n\nimport {\n  CloseSignal,\n  compute_backoff_delay,\n  DeferSignal,\n  type Handle,\n  type HandleBatch,\n  type HandleResult,\n  resolve_defer_at,\n} from \"../internal/index.js\";\n\nimport type { ReactionScope } from \"../scoped.js\";\nimport {\n  type Actor,\n  type BatchHandler,\n  type Committed,\n  type Lease,\n  type Logger,\n  NonRetryableError,\n  type ReactionOptions,\n  type ReactionPayload,\n  type Schemas,\n} from \"../types/index.js\";\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 *\n * @internal\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 * Shared finalization: log the error and decide retry vs. block. The\n * error string is *always* surfaced on the failure path — drain-cycle\n * uses `handled > 0` (not `error` presence) to decide whether to ack\n * the partial progress, so the message can travel for trace + blocked\n * record without affecting the ack/skip choice.\n */\nfunction 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  // Backoff applies only on retry paths — successful handles and terminal\n  // blocks never defer. `lease.retry` here is the just-failed attempt's\n  // counter, so the delay paces the *next* attempt.\n  const next_attempt_at =\n    !block && options.backoff\n      ? Date.now() + compute_backoff_delay(lease.retry, options.backoff)\n      : undefined;\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/**\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` (#587, #1541). Ambient\n * rather than bound to the `IAct` argument, so a handler that dispatches\n * through a captured `app` inherits the chain too.\n *\n * @internal\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 (#1179). 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 (#1090). `acked_at` is unused on\n        // the defer path — drain never acks a deferred result.\n        if (error instanceof DeferSignal)\n          return {\n            lease,\n            handled,\n            acked_at: at,\n            defer: resolve_defer_at<TEvents>(error.when, event),\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 (#1090).\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            // 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 *\n * @internal\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    const events = payloads.map(\n      (p) => 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 * @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 type { Schema, State } from \"../types/index.js\";\nimport type { Projection } from \"./projection-builder.js\";\n\n/**\n * Unwraps wrapper types (ZodOptional, ZodNullable, ZodDefault, ZodReadonly)\n * to find the base type name, e.g. `z.string().optional()` -> `\"ZodString\"`.\n */\nfunction base_type_name(zodType: ZodType): string {\n  let t: any = zodType;\n  while (typeof t.unwrap === \"function\") {\n    t = t.unwrap();\n  }\n  return t.constructor.name;\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()`. Falls back to keeping existing\n * schema if either is not a ZodObject.\n */\nfunction merge_schemas(\n  existing: ZodType,\n  incoming: ZodType,\n  state_name: string\n): ZodType {\n  if (existing instanceof ZodObject && incoming instanceof ZodObject) {\n    const existing_shape = existing.shape as Record<string, ZodType>;\n    const incoming_shape = incoming.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.extend(incoming_shape);\n  }\n  return existing;\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 (#1645).\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\" | \"autoclose_after_days\" | \"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_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    // Same schema reference means the same partial re-registered via another slice\n    if (existing.actions[name] === state.actions[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    given: { ...existing.given, ...state.given },\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 (ACT-979). 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 (#1439).\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  assert_defer_when,\n  type DeferSchedule,\n  make_deferred,\n  resolveReactionConfig,\n} from \"../internal/index.js\";\nimport { DEFAULT_LANE } from \"../ports.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 { _this_ } from \"./merge.js\";\n\n/**\n * Validate and register a drain lane (ACT-1103): the `\"default\"` name is\n * reserved and each lane name must be unique. Mutates `lanes` in place; the\n * caller returns its own builder for chaining.\n *\n * @internal\n */\nexport function register_lane(config: LaneConfig, lanes: LaneConfig[]): void {\n  if (config.name === DEFAULT_LANE)\n    throw new Error(`Lane \"${DEFAULT_LANE}\" is reserved`);\n  if (lanes.some((l) => l.name === config.name))\n    throw new Error(`Lane \"${config.name}\" was already declared`);\n  lanes.push(config);\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,\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    if (!handler.name)\n      throw new Error(\n        `Reaction handler for \"${String(event)}\" must be a named function`\n      );\n    if (events[event].reactions.has(handler.name))\n      throw new Error(\n        `Duplicate reaction \"${handler.name}\" for event \"${String(event)}\". ` +\n          `Reaction handlers are keyed by function name; rename one of them.`\n      );\n    // Fail fast on a bad literal schedule; the function form is checked when it\n    // runs (no event to resolve against at build time).\n    if (schedule && typeof schedule !== \"function\") assert_defer_when(schedule);\n    const reaction: Reaction<TEvents, TKey> = {\n      handler: schedule ? make_deferred(handler, schedule) : handler,\n      resolver: _this_,\n      // #1269: 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 ?? true,\n        maxRetries: options?.maxRetries ?? 3,\n        backoff: options?.backoff,\n      }),\n    };\n    // Register once with the default _this_ resolver. If `.to()` is chained\n    // next, it patches the same reaction's resolver in place — no second\n    // Map.set() round-trip.\n    events[event].reactions.set(handler.name, reaction);\n    return Object.assign(builder as object, {\n      to(resolver: ReactionResolver<TEvents, TKey> | string) {\n        reaction.resolver =\n          typeof resolver === \"string\" ? { target: resolver } : resolver;\n        return builder;\n      },\n    });\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. `internal/sensitive.ts`\n * owns the other two halves — the `sensitive(...)` marker itself, and the\n * runtime transforms (`pii_gate`, `pii_strip`, `pii_split`) that a reader is\n * 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/index.js\";\nimport {\n  type EventGate,\n  IDENTITY_GATE,\n  make_gate,\n  pii_schemas,\n  pii_split,\n  pii_strip,\n} from \"../internal/sensitive.js\";\nimport { DEFAULT_LANE, SNAP_EVENT } from \"../ports.js\";\nimport type { Actor, LaneConfig, Registry } from \"../types/index.js\";\n\n/** What one pass over an event's schema resolves. @internal */\nexport type EventTags = {\n  /** Keys marked `sensitive(...)`, top level (and across union variants). */\n  readonly sensitive: readonly string[];\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 ([#1417](https://github.com/Rotorsoft/act-root/issues/1417)).\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: Object.keys(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 */\nexport function make_event_reader(\n  tags: EventTags,\n  disclosure: Disclosure,\n  predicate: ((event: never, actor: Actor) => boolean) | null = null\n): EventGate | undefined {\n  const { sensitive, date_reviver, pii_date_reviver } = tags;\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  /** 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 && !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    if (event.sensitive.length > 0) sensitive.set(event_name, event.sensitive);\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  for (const state of states.values()) {\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) state_fields.set(event_name, fields);\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  return { sensitive, query_readers, handler_readers };\n}\n","/**\n * @module act-builder\n * @category Builders\n *\n * Fluent builder for composing event-sourced applications.\n */\nimport { Act, type ActOptions } from \"../act.js\";\nimport {\n  bare_patch,\n  current_version_of,\n  deprecated_event_names,\n  type EventGate,\n  FOLD_RESET,\n  IDENTITY_GATE,\n  make_fold_handler,\n  type PatchFn,\n  type ResettableBatchHandler,\n  resolveActConfig,\n  resolveLaneConfig,\n  synthesize_autoclose_reactions,\n  validating_patch,\n} from \"../internal/index.js\";\nimport { type DEFAULT_LANE, log } from \"../ports.js\";\nimport { current_autoclose_window } from \"../scoped.js\";\nimport type {\n  Actor,\n  BatchHandler,\n  LaneConfig,\n  Registry,\n  Schema,\n  SchemaRegister,\n  Schemas,\n  State,\n} from \"../types/index.js\";\nimport type { BuilderBase } from \"./builder-base.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\";\nimport type { Projection } from \"./projection-builder.js\";\nimport type { Slice } from \"./slice-builder.js\";\n\n/**\n * Registers a projection's batch handler against its target stream, throwing\n * if a different handler is already registered for the same target. Two\n * projections silently overwriting each other's batch handlers used to be a\n * latent footgun.\n *\n * This half covers batch x batch only. A fold projection (`.of(...)`) has a\n * target but no batch handler, so it early-returns here — the fold side of\n * the guard lives at the `fold_specs.push` site in `build()`, which sees a\n * fully-populated `batch_handlers` and so catches both orders (#1440).\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 * Fluent builder interface for composing event-sourced applications.\n *\n * Provides a chainable API for:\n * - Registering states via `.withState()`\n * - Registering slices via `.withSlice()`\n * - Registering projections via `.withProjection()`\n * - Locking a custom actor type via `.withActor<TActor>()`\n * - Declaring drain lanes via `.withLane({name, ...})` (ACT-1103)\n * - Defining event reactions via `.on()` → `.do()` → `.to()`\n * - Building the orchestrator via `.build()`\n *\n * @template TSchemaReg - Schema register for states (maps action names to state schemas)\n * @template TEvents - Event schemas (maps event names to event data schemas)\n * @template TActions - Action schemas (maps action names to action payload schemas)\n * @template TStateMap - Map of state names to state schemas\n * @template TActor - Actor type extending base Actor\n * @template TLanes - Union of declared lane names (ACT-1103). Narrowed by\n *   `.withLane({name})` calls so `.to({lane})` and `ActOptions.onlyLanes`\n *   reject typos at compile time. Starts at `\"default\"`.\n *\n * @see {@link act} for usage examples\n * @see {@link Act} for the built orchestrator API\n */\nexport interface ActBuilder<\n  TSchemaReg extends SchemaRegister<TActions>,\n  TEvents extends Schemas,\n  TActions extends Schemas,\n  // eslint-disable-next-line @typescript-eslint/no-empty-object-type\n  TStateMap extends Record<string, Schema> = {},\n  TActor extends Actor = Actor,\n  TLanes extends string = typeof DEFAULT_LANE,\n> extends BuilderBase<\n    ActBuilder<TSchemaReg, TEvents, TActions, TStateMap, TActor, TLanes>,\n    TEvents,\n    TActions,\n    TActor,\n    TLanes\n  > {\n  /**\n   * Registers a state definition with the builder.\n   *\n   * State names, action names, and event names must be unique across the\n   * application (partial states with the same name are merged automatically).\n   *\n   * @throws {Error} If duplicate action or event names are detected\n   */\n  withState: <\n    TNewState extends Schema,\n    TNewEvents extends Schemas,\n    TNewActions extends Schemas,\n    TNewName extends string = string,\n  >(\n    state: State<TNewState, TNewEvents, TNewActions, TNewName>\n  ) => ActBuilder<\n    TSchemaReg & { [K in keyof TNewActions]: TNewState },\n    TEvents & TNewEvents,\n    TActions & TNewActions,\n    TStateMap & { [K in TNewName]: TNewState },\n    TActor,\n    TLanes\n  >;\n  /**\n   * Registers a slice with the builder.\n   *\n   * Merges all the slice's states and reactions into the application.\n   * State names, action names, and event names must be unique across the\n   * application (partial states with the same name are merged automatically).\n   *\n   * @throws {Error} If duplicate action or event names are detected\n   */\n  withSlice: <\n    TNewSchemaReg extends SchemaRegister<TNewActions>,\n    TNewEvents extends Schemas,\n    TNewActions extends Schemas,\n    TNewMap extends Record<string, Schema>,\n    TNewLanes extends string,\n  >(\n    slice: Slice<\n      TNewSchemaReg,\n      TNewEvents,\n      TNewActions,\n      TNewMap,\n      Actor,\n      TNewLanes\n    >\n  ) => ActBuilder<\n    TSchemaReg & TNewSchemaReg,\n    TEvents & TNewEvents,\n    TActions & TNewActions,\n    TStateMap & TNewMap,\n    TActor,\n    TLanes | TNewLanes\n  >;\n  /**\n   * Locks a custom actor type for this application.\n   *\n   * This is a pure type-level method — it returns the same builder at\n   * runtime but narrows the `TActor` generic so that `app.do()` and\n   * reaction dispatchers require the richer actor shape.\n   *\n   * @template TNewActor - Custom actor type extending base Actor\n   * @returns The same builder with `TActor` locked to `TNewActor`\n   *\n   * @example\n   * ```typescript\n   * type MyActor = { id: string; name: string; role: string; tenantId: string };\n   *\n   * const app = act()\n   *   .withActor<MyActor>()\n   *   .withState(Counter)\n   *   .build();\n   *\n   * // Now app.do() requires MyActor in the target\n   * await app.do(\"increment\", {\n   *   stream: \"counter-1\",\n   *   actor: { id: \"1\", name: \"Alice\", role: \"admin\", tenantId: \"t1\" }\n   * }, { by: 5 });\n   * ```\n   */\n  withActor: <TNewActor extends Actor>() => ActBuilder<\n    TSchemaReg,\n    TEvents,\n    TActions,\n    TStateMap,\n    TNewActor,\n    TLanes\n  >;\n  /**\n   * Declares a drain lane (ACT-1103). Lane name narrows `TLanes` so\n   * `.to({lane})` and `ActOptions.onlyLanes` type-check against it.\n   *\n   * @example\n   * ```typescript\n   * const app = act()\n   *   .withState(Counter)\n   *   .withLane({ name: \"slow\", leaseMillis: 60_000, streamLimit: 5 })\n   *   .on(\"OrderConfirmed\")\n   *     .do(deliverWebhook)\n   *     .to({ target: \"webhooks-out\", lane: \"slow\" })\n   *   .build();\n   * ```\n   */\n  withLane: <const TConfig extends LaneConfig>(\n    config: TConfig\n  ) => ActBuilder<\n    TSchemaReg,\n    TEvents,\n    TActions,\n    TStateMap,\n    TActor,\n    TLanes | TConfig[\"name\"]\n  >;\n  /**\n   * Builds and returns the Act orchestrator instance.\n   *\n   * @param options - Optional runtime overrides (see {@link ActOptions}).\n   *   `options.onlyLanes` is narrowed to the declared `TLanes` union, so\n   *   `onlyLanes: [\"typo\"]` is a compile error when the lane wasn't\n   *   declared via `.withLane(...)`.\n   * @returns The Act orchestrator instance\n   *\n   * @see {@link Act} for available orchestrator methods\n   */\n  build: (\n    options?: ActOptions<TLanes>\n  ) => Act<TSchemaReg, TEvents, TActions, TStateMap, TActor>;\n}\n\n/* eslint-disable @typescript-eslint/no-empty-object-type -- {} used as generic defaults */\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 * @example Application with custom actor type\n * ```typescript\n * type MyActor = { id: string; name: string; role: string };\n *\n * const app = act()\n *   .withActor<MyActor>()\n *   .withState(Counter)\n *   .build();\n * ```\n *\n * @example Application with slices (vertical slice architecture)\n * ```typescript\n * const CounterSlice = slice()\n *   .withState(Counter)\n *   .on(\"Incremented\")\n *     .do(async (event) => { console.log(\"incremented!\"); })\n *     .to(\"counter-target\")\n *   .build();\n *\n * const app = act()\n *   .withSlice(CounterSlice)\n *   .build();\n * ```\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<\n  // @ts-expect-error empty schema\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 registry.sensitive_fields / registry.disclosure_predicate /\n  // registry.deprecated_events / registry.autoclose_policy. Populated\n  // on the first .build() call.\n  // One pass over each event's schema, and the single source for everything\n  // derived from it: the sensitive-field list the write path splits on, and\n  // the per-surface readers (query, per-state view, handler strip) composed\n  // below. Nothing walks a schema twice.\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   * Reaction objects contributed BY projections. A projection's own\n   * reactions legitimately target it; anything else pointed at a target a\n   * projection serves is the #1467 collision. Recorded at registration\n   * because projections arrive through two doors (`withProjection` merges\n   * immediately, `withSlice` defers to build) and neither retains them.\n   * Identity is the same test `merge_projection` uses.\n   */\n  const projection_reactions = new Set<unknown>();\n  const record_projection_reactions = (proj: Projection<any>) => {\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  // 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 (#1469). */\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 (#1466). 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 projection handlers are shared\n   * with the builder (they carry no state, and `register_batch_handler`\n   * already rejects duplicate targets); state-projection FOLD handlers\n   * are constructed fresh for every `.build()`.\n   *\n   * A fold handler owns a mutable per-stream cache of folded state\n   * (`projection-fold.ts`), keyed on stream name alone. Sharing one\n   * instance across Acts built from the same builder — the documented\n   * multi-tenant pattern, and every `fixture(builder)` test — let one\n   * Act's folded rows surface in another Act's sink, and made the\n   * frontier guard compare event ids originating in different stores.\n   * The cache still spans drain cycles within one Act, so the warm-fold\n   * performance property is unchanged.\n   *\n   * Building here also means each Act's fold handlers observe that\n   * build's own `patch_fn` (`validateFoldedState` is a per-build\n   * option), instead of freezing the first build's choice.\n   */\n  const make_batch_handlers = (patch_fn: PatchFn) => {\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            patch_fn,\n            // Head loads strip sensitive keys like the warm path (#1320).\n            registry.sensitive_fields\n          )\n        ) as never\n      );\n    }\n    return handlers;\n  };\n\n  // ACT-403: auto-deprecation enforcement. Groups each state's events\n  // by base name + `_v<digits>`; the highest version is current, all\n  // lower ones are deprecated. Stashes the deprecation set on the\n  // registry (`registry.deprecated_events(state_name)`) so the\n  // orchestrator can warn post-commit when an action emits one.\n  // Scans static `.emit(\"X\")` markers across every state and throws\n  // if any target a deprecated event — the only legitimate use of a\n  // deprecated event is on the reduce path. Finally, surfaces a\n  // one-line startup advisory so operators can see \"your app has\n  // legacy events kept for the read path, here's where they live.\"\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  // 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        register_state(state, states, registry.actions, registry.events);\n        return builder as never;\n      },\n      withSlice: (input) => {\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 slice_lane of input.lanes) {\n          const existing = lanes.find((l) => l.name === slice_lane.name);\n          if (!existing) {\n            lanes.push(slice_lane);\n            continue;\n          }\n          if (\n            existing.leaseMillis !== slice_lane.leaseMillis ||\n            existing.streamLimit !== slice_lane.streamLimit ||\n            existing.cycleMs !== slice_lane.cycleMs\n          ) {\n            throw new Error(\n              `Lane \"${slice_lane.name}\" was already declared with a different config`\n            );\n          }\n        }\n        return builder as never;\n      },\n      withProjection: (proj) => {\n        record_projection_reactions(proj as Projection<any>);\n        merge_projection(proj as Projection<any>, registry.events);\n        register_batch_handler(proj as Projection<any>, batch_handlers);\n        if ((proj as Projection<any>).fold)\n          fold_projections.push(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        // Validate the lane bag at declaration (a bad leaseMillis/streamLimit\n        // throws ZodError at build, not on the first cycle).\n        register_lane(resolveLaneConfig(config), lanes);\n        return builder as never;\n      },\n      on: <TKey extends keyof TEvents>(event: TKey) =>\n        reaction_on(event, registry.events, builder) as never,\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        // ACT-1238: select the per-event patch step ONCE here — the\n        // single selection site. `bare_patch` (the literal pre-#1238\n        // `patch()` merge) when `validateFoldedState` is off, else\n        // `validating_patch`. The same selected value feeds BOTH the\n        // projection-fold handlers below and `build_es` (via the Act\n        // constructor), so the command/load paths and the projection\n        // path share one choice and neither branches per event.\n        const patch_fn: PatchFn =\n          options?.validateFoldedState === true ? validating_patch : bare_patch;\n        // One-time finalize: merge pending projections and run the\n        // deprecation scan + advisory log exactly once. Calling\n        // `.build({scoped: ...})` repeatedly (e.g., per tenant) is\n        // supported — see extension-points.md § Scoped ports. Without\n        // this guard, `merge_projection` would re-add reactions to the\n        // shared registry on every call (accumulating `_p`/`_p_p`\n        // dedupe suffixes), and the deprecation advisory would log on\n        // every tenant.\n        if (!_built) {\n          for (const proj of pending_projections) {\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          // 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          // The `patch_fn` selected once at the top of `build()` feeds the\n          // fold handlers, matching the command/load paths (ACT-1238).\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 may be claimed exactly once, by a batch handler OR by\n            // a fold — `make_batch_handlers` does an unconditional\n            // `handlers.set(spec.target, …)`, so without this the last\n            // registration silently won (#1440).\n            //\n            // `register_batch_handler` cannot catch these: it early-returns\n            // on `!proj.batchHandler`, and a fold projection has a target but\n            // no batch handler, so the fold path bypassed the guard in both\n            // directions. The damage was worse than a dead projection — the\n            // fold cold-loads the losing target's streams through the\n            // stream-keyed cache, so it received the OTHER projection's\n            // aggregates and wrote them into its own read table.\n            //\n            // With this check all four {batch, fold}² pairings throw;\n            // previously only batch × batch did.\n            // Re-registering the SAME projection object is a no-op, not a\n            // duplicate (#1469) — a projection exported from a module and\n            // embedded by two slices, or a `.withProjection(p)` written\n            // twice, is a legitimate pattern that both sibling paths\n            // (`merge_projection`, `register_batch_handler`) already treat\n            // as idempotent. Only two DIFFERENT claimants on one target are\n            // an error.\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          // A target is served by ONE thing (#1467). The guard above covers\n          // projection-vs-projection; this covers the third claimant a\n          // projection has no way to see: an ordinary reaction pointed at a\n          // target a batch handler or fold already owns.\n          //\n          // The drain dispatches a stream with a batch handler through that\n          // handler and nothing else (`drain-cycle.ts`), so the foreign\n          // reaction never runs — silently, with no error, retry or block —\n          // and the fold cold-loads the foreign event's stream as ITS state,\n          // writing another aggregate's row into its read table. Exactly the\n          // #1440 damage through the seam that fix did not reach.\n          //\n          // A projection's OWN reactions legitimately target it, so they are\n          // excluded by object identity — the same test `merge_projection`\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\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          // Repeat builds (per-tenant scoped Acts) share the registry and\n          // these reactions with it, so nothing per-Act may be captured\n          // here. The off-hours window is read from the running Act's\n          // frame instead, which each Act installs for itself (#1615).\n          synthesize_autoclose_reactions(\n            registry,\n            states,\n            current_autoclose_window\n          );\n          // The registry is complete: freeze the containers so any later\n          // registration or orchestrator-side mutation throws instead of\n          // silently diverging from what was classified. (Reaction maps\n          // remain Map instances — the freeze guards the object shape,\n          // convention guards the maps.)\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(patch_fn),\n          options,\n          lanes,\n          patch_fn\n        );\n      },\n      events: registry.events,\n    };\n  return builder;\n}\n","/**\n * @module projection-builder\n * @category Builders\n *\n * Fluent builder for composing projection handlers — read-model updaters\n * that react to events and update external state (databases, caches, etc.).\n *\n * Projections differ from slices: they don't contain states, don't dispatch\n * actions, and are pure side-effect handlers routed to a named stream.\n */\nimport type { ZodType } from \"zod\";\nimport { type FoldConfig, resolveFoldConfig } from \"../internal/index.js\";\nimport type {\n  BatchHandler,\n  CacheEntry,\n  Committed,\n  EventRegister,\n  FoldOptions,\n  Reaction,\n  ReactionResolver,\n  Schema,\n  Schemas,\n  State,\n} from \"../types/index.js\";\nimport { _this_ } from \"./merge.js\";\n\n/**\n * A self-contained projection grouping read-model update handlers.\n * Projections are composed into an Act orchestrator via `act().withProjection(projection)`.\n *\n * @template TEvents - Event schemas handled by this projection\n */\nexport type Projection<TEvents extends Schemas> = {\n  readonly _tag: \"Projection\";\n  readonly events: EventRegister<TEvents>;\n  readonly target?: string;\n  readonly batchHandler?: BatchHandler<TEvents>;\n  /**\n   * State-fold spec from `.of()`. The builder only records intent — the\n   * orchestrator resolves the REGISTRY-MERGED full state at\n   * `act().build()` and synthesizes the batch handler there, so the\n   * fold always covers every reducer of the state, including partials\n   * merged by slices the projection never saw.\n   * @internal\n   */\n  readonly fold?: {\n    readonly name: string;\n    readonly flush: (rows: ReadonlyArray<CacheEntry<any>>) => Promise<void>;\n    readonly config: FoldConfig;\n  };\n};\n\n/**\n * The `.of()` continuation: state projections flush the cache layer\n * outward — the rows ARE the streams' {@link CacheEntry} values, one\n * per dirty stream per flush round. Must be an idempotent upsert keyed\n * on `stream` (guard with `event_id` for order safety when a rebuild\n * races a live worker).\n */\ntype FoldFlush<TState extends Schema, TE extends Schemas> = {\n  flush: (\n    handler: (rows: ReadonlyArray<CacheEntry<TState>>) => Promise<void>\n  ) => {\n    build: () => Projection<TE>;\n  };\n};\n\n/**\n * `.of()` accepts the partials of ONE state (same name, enforced at the\n * type level via `TName`) purely for typing and event registration —\n * the fold itself always runs on the registry-merged full state,\n * resolved at `act().build()`. Passing every partial is required: the\n * orchestrator validates completeness at build and throws on missing\n * events.\n */\ntype OfSignatures = {\n  <\n    TS1 extends Schema,\n    TE1 extends Schemas,\n    TA1 extends Schemas,\n    TN extends string,\n  >(\n    s1: State<TS1, TE1, TA1, TN>,\n    options?: FoldOptions\n  ): FoldFlush<TS1, TE1>;\n  <\n    TS1 extends Schema,\n    TE1 extends Schemas,\n    TA1 extends Schemas,\n    TS2 extends Schema,\n    TE2 extends Schemas,\n    TA2 extends Schemas,\n    TN extends string,\n  >(\n    s1: State<TS1, TE1, TA1, TN>,\n    s2: State<TS2, TE2, TA2, TN>,\n    options?: FoldOptions\n  ): FoldFlush<TS1 & TS2, TE1 & TE2>;\n  <\n    TS1 extends Schema,\n    TE1 extends Schemas,\n    TA1 extends Schemas,\n    TS2 extends Schema,\n    TE2 extends Schemas,\n    TA2 extends Schemas,\n    TS3 extends Schema,\n    TE3 extends Schemas,\n    TA3 extends Schemas,\n    TN extends string,\n  >(\n    s1: State<TS1, TE1, TA1, TN>,\n    s2: State<TS2, TE2, TA2, TN>,\n    s3: State<TS3, TE3, TA3, TN>,\n    options?: FoldOptions\n  ): FoldFlush<TS1 & TS2 & TS3, TE1 & TE2 & TE3>;\n  <\n    TS1 extends Schema,\n    TE1 extends Schemas,\n    TA1 extends Schemas,\n    TS2 extends Schema,\n    TE2 extends Schemas,\n    TA2 extends Schemas,\n    TS3 extends Schema,\n    TE3 extends Schemas,\n    TA3 extends Schemas,\n    TS4 extends Schema,\n    TE4 extends Schemas,\n    TA4 extends Schemas,\n    TN extends string,\n  >(\n    s1: State<TS1, TE1, TA1, TN>,\n    s2: State<TS2, TE2, TA2, TN>,\n    s3: State<TS3, TE3, TA3, TN>,\n    s4: State<TS4, TE4, TA4, TN>,\n    options?: FoldOptions\n  ): FoldFlush<TS1 & TS2 & TS3 & TS4, TE1 & TE2 & TE3 & TE4>;\n};\n\n/** Helper: a single-key record mapping an event name to its Zod schema. */\ntype EventEntry<TKey extends string = string, TData extends Schema = Schema> = {\n  [P in TKey]: ZodType<TData>;\n};\n\n/** Infer the handler-result type after registering one event. */\ntype DoResult<\n  TEvents extends Schemas,\n  TKey extends string,\n  TData extends Schema,\n  TTarget extends string | undefined = undefined,\n> = ProjectionBuilder<TEvents & { [P in TKey]: TData }, TTarget, true> & {\n  to: (\n    resolver: ReactionResolver<TEvents & { [P in TKey]: TData }, TKey> | string\n  ) => ProjectionBuilder<TEvents & { [P in TKey]: TData }, TTarget, true>;\n};\n\n/**\n * Fluent builder interface for composing projections.\n *\n * When a static target is provided via `projection(\"target\")`, the builder\n * exposes a `.batch()` method for registering a batch handler that processes\n * all events in a single call.\n *\n * @template TEvents - Event schemas\n * @template TTarget - Static target string or undefined\n */\nexport type ProjectionBuilder<\n  TEvents extends Schemas,\n  TTarget extends string | undefined = undefined,\n  THasHandlers extends boolean = false,\n> = {\n  /**\n   * Begins defining a projection handler for a specific event.\n   *\n   * Pass a `{ EventName: schema }` record — use shorthand `{ EventName }`\n   * when the variable name matches the event name. The key becomes the\n   * event name, the value the Zod schema.\n   */\n  on: <TKey extends string, TData extends Schema>(\n    entry: EventEntry<TKey, TData>\n  ) => {\n    do: (\n      handler: (\n        event: Committed<TEvents & { [P in TKey]: TData }, TKey>,\n        stream: string\n      ) => Promise<void>\n    ) => DoResult<TEvents, TKey, TData, TTarget>;\n  };\n  /**\n   * Builds and returns the Projection data structure.\n   */\n  build: () => Projection<TEvents>;\n  /**\n   * The registered event schemas and their reaction maps.\n   */\n  readonly events: EventRegister<TEvents>;\n} & (TTarget extends string\n  ? {\n      /**\n       * Registers a batch handler that processes all events in a single call.\n       *\n       * Only available on projections with a static target (`projection(\"target\")`).\n       * The handler receives a discriminated union of all declared events,\n       * enabling bulk DB operations in a single transaction.\n       *\n       * When defined, the batch handler is always called — even for a single event.\n       * Individual `.do()` handlers serve as fallback for projections without `.batch()`.\n       */\n      batch: (handler: BatchHandler<TEvents>) => {\n        build: () => Projection<TEvents>;\n      };\n    } & (THasHandlers extends false\n      ? {\n          /**\n           * Declares a state projection: fold every event of the given\n           * state through its own reducers and flush one row per stream —\n           * the queryable list of the aggregates themselves.\n           *\n           * The state is the filter: the projection consumes exactly the\n           * state's event register, so in a multi-state app only that\n           * state's streams are folded — and every event of a folded\n           * stream reaches the reducer. Write amplification tracks the\n           * distinct stream count, not the event count; `app.reset`\n           * rebuilds in O(streams) upserts.\n           *\n           * The fluent chain enforces the shape: `.of()` is only offered\n           * before any `.on()` handler, and narrows to `.flush()` +\n           * `.build()` — a projection either folds a state or declares\n           * handlers, never both.\n           */\n          of: OfSignatures;\n        }\n      : // eslint-disable-next-line @typescript-eslint/no-empty-object-type\n        {})\n  : // eslint-disable-next-line @typescript-eslint/no-empty-object-type\n    {});\n\n/* eslint-disable @typescript-eslint/no-empty-object-type -- {} used as generic defaults */\n\n/**\n * Creates a new projection builder for composing read-model update handlers.\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.\n *\n * Pass a target stream name to `projection(\"target\")` so every handler\n * inherits that resolver automatically. Omit it and use per-handler\n * `.to()` when handlers route to different streams.\n *\n * @param target - Optional default 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 ({ stream, data }) => {\n *       await db.insert(tickets).values({ id: stream, ...data });\n *     })\n *   .on({ TicketClosed })\n *     .do(async ({ stream, data }) => {\n *       await db.update(tickets).set(data).where(eq(tickets.id, stream));\n *     })\n *   .build();\n * ```\n *\n * @example Per-handler routing\n * ```typescript\n * const MultiProjection = projection()\n *   .on({ OrderPlaced })\n *     .do(async (event) => { ... })\n *     .to(\"orders\")\n *   .on({ PaymentReceived })\n *     .do(async (event) => { ... })\n *     .to(\"payments\")\n *   .build();\n * ```\n *\n * @see {@link ProjectionBuilder} for builder methods\n * @see {@link Projection} for the output type\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          const reaction: Reaction<TEvents & { [P in TKey]: TData }, TKey> = {\n            handler,\n            resolver: default_resolver ?? _this_,\n            options: {\n              blockOnError: true,\n              maxRetries: 3,\n            },\n          };\n          const register = (events as Record<string, any>)[event];\n          if (!handler.name)\n            throw new Error(\n              `Projection handler for \"${event}\" must be a named function`\n            );\n          if (register.reactions.has(handler.name))\n            throw new Error(\n              `Duplicate projection handler \"${handler.name}\" for event \"${event}\". ` +\n                `Projection handlers are keyed by function name; rename one of them.`\n            );\n          register.reactions.set(handler.name, reaction);\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 Object.assign(widened, {\n            to(\n              resolver:\n                | ReactionResolver<TEvents & { [P in TKey]: TData }, TKey>\n                | string\n            ) {\n              // Patch the same reaction in place — no second Map.set().\n              reaction.resolver =\n                typeof resolver === \"string\" ? { target: resolver } : resolver;\n              return widened;\n            },\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: { blockOnError: true, maxRetries: 3 },\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 with a static target stream.\n *\n * All handlers inherit the target resolver automatically. Enables `.batch()`\n * for bulk event processing in a single transaction.\n *\n * @param target - Static target stream for all handlers\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 { DEFAULT_LANE } from \"../ports.js\";\nimport type {\n  Actor,\n  EventRegister,\n  LaneConfig,\n  Schema,\n  SchemaRegister,\n  Schemas,\n  State,\n} from \"../types/index.js\";\nimport type { BuilderBase } from \"./builder-base.js\";\nimport { reaction_on, register_lane } from \"./builder-utils.js\";\nimport { register_state } from \"./merge.js\";\nimport type { Projection } from \"./projection-builder.js\";\n\n/**\n * A self-contained functional slice grouping partial states with their\n * scoped reactions. Slices are composed into an Act orchestrator via\n * `act().withSlice(slice)`.\n *\n * @template TSchemaReg - Schema register for states\n * @template TEvents - Event schemas from this slice's states\n * @template TActions - Action schemas from this slice's states\n * @template TStateMap - Map of state names to state schemas\n * @template TActor - Actor type extending base Actor\n */\nexport type Slice<\n  TSchemaReg extends SchemaRegister<TActions>,\n  TEvents extends Schemas,\n  TActions extends Schemas,\n  // eslint-disable-next-line @typescript-eslint/no-empty-object-type\n  TStateMap extends Record<string, Schema> = {},\n  TActor extends Actor = Actor,\n  TLanes extends string = typeof DEFAULT_LANE,\n> = {\n  readonly _tag: \"Slice\";\n  readonly states: Map<string, State<any, any, any>>;\n  readonly events: EventRegister<TEvents>;\n  readonly projections: ReadonlyArray<Projection<any>>;\n  /**\n   * Drain lanes declared on this slice via `.withLane(...)` (ACT-1103).\n   * `act().withSlice(slice)` merges these into the Act's lane set so\n   * `.to({lane})` is statically checked at the slice's call site against\n   * the lanes the slice itself declared.\n   */\n  readonly lanes: ReadonlyArray<LaneConfig>;\n  /** @internal phantom field for type-level state schema tracking */\n  readonly _S?: TSchemaReg;\n  /** @internal phantom field for type-level state name tracking */\n  readonly _M?: TStateMap;\n  /** @internal phantom field for type-level actor tracking */\n  readonly _TActor?: TActor;\n  /** @internal phantom field for type-level lane union tracking */\n  readonly _TLanes?: TLanes;\n};\n\n/**\n * Fluent builder interface for composing functional slices.\n *\n * Provides a chainable API for registering states and projections,\n * and defining reactions scoped to the slice's own events.\n *\n * @template TSchemaReg - Schema register for states\n * @template TEvents - Event schemas\n * @template TActions - Action schemas\n * @template TStateMap - Map of state names to state schemas\n * @template TActor - Actor type extending base Actor\n */\nexport interface SliceBuilder<\n  TSchemaReg extends SchemaRegister<TActions>,\n  TEvents extends Schemas,\n  TActions extends Schemas,\n  // eslint-disable-next-line @typescript-eslint/no-empty-object-type\n  TStateMap extends Record<string, Schema> = {},\n  TActor extends Actor = Actor,\n  TLanes extends string = typeof DEFAULT_LANE,\n> extends BuilderBase<\n    SliceBuilder<TSchemaReg, TEvents, TActions, TStateMap, TActor, TLanes>,\n    TEvents,\n    TActions,\n    TActor,\n    TLanes\n  > {\n  /**\n   * Registers a state definition with the slice.\n   *\n   * Include every state whose actions your reaction handlers need to\n   * dispatch. Duplicate registrations (same state in multiple slices)\n   * are handled automatically at composition time.\n   */\n  withState: <\n    TNewState extends Schema,\n    TNewEvents extends Schemas,\n    TNewActions extends Schemas,\n    TNewName extends string = string,\n  >(\n    state: State<TNewState, TNewEvents, TNewActions, TNewName>\n  ) => SliceBuilder<\n    TSchemaReg & { [K in keyof TNewActions]: TNewState },\n    TEvents & TNewEvents,\n    TActions & TNewActions,\n    TStateMap & { [K in TNewName]: TNewState },\n    TActor,\n    TLanes\n  >;\n  /**\n   * Declares a drain lane on this slice (ACT-1103). Merged into the\n   * parent Act's lane set by `act().withSlice(slice)`.\n   */\n  withLane: <const TConfig extends LaneConfig>(\n    config: TConfig\n  ) => SliceBuilder<\n    TSchemaReg,\n    TEvents,\n    TActions,\n    TStateMap,\n    TActor,\n    TLanes | TConfig[\"name\"]\n  >;\n  /**\n   * Builds and returns the Slice data structure.\n   */\n  build: () => Slice<TSchemaReg, TEvents, TActions, TStateMap, TActor, TLanes>;\n}\n\n/* eslint-disable @typescript-eslint/no-empty-object-type -- {} used as generic defaults */\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 (event, _stream, app) => {\n *       await app.do(\"reset\", target, {});\n *     })\n *     .to(\"counter-target\")\n *   .build();\n * ```\n *\n * @example Cross-state dispatch (include both states)\n * ```typescript\n * const CreationSlice = slice()\n *   .withState(TicketCreation)\n *   .withState(TicketOperations) // handler can dispatch AssignTicket\n *   .on(\"TicketOpened\").do(async (event, _stream, app) => {\n *     await app.do(\"AssignTicket\", target, payload, { reactingTo: event });\n *   })\n *   .build();\n * ```\n *\n * @see {@link SliceBuilder} for builder methods\n * @see {@link Slice} for the output type\n */\nexport function slice<\n  // @ts-expect-error empty schema\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  type AutoclosePolicy,\n  compile_autoclose_policy,\n  policy_keep_days,\n  policy_min_after_days,\n  resolveActionConfig,\n} from \"../internal/index.js\";\nimport type {\n  ActionHandler,\n  ActionOptions,\n  Actor,\n  AutocloseArchiver,\n  AutoclosePredicate,\n  Committed,\n  GivenHandlers,\n  Invariant,\n  PassthroughPatchHandler,\n  PatchHandlers,\n  Schema,\n  Schemas,\n  Snapshot,\n  State,\n  ZodTypes,\n} from \"../types/index.js\";\n\n/**\n * Builder interface for defining a state with event sourcing.\n *\n * Provides a fluent API to configure the initial state, event types,\n * and event handlers (reducers) before moving to action configuration.\n *\n * @template TState - State schema type\n * @template TName - State name literal type\n *\n * @see {@link state} for usage examples\n * @see {@link ActionBuilder} for action configuration\n */\nexport type StateBuilder<\n  TState extends Schema,\n  TName extends string = string,\n> = {\n  /**\n   * Defines the initial state for new state instances.\n   *\n   * The init function is called when a new stream is created (first event).\n   * It can accept initial data or return a default state.\n   *\n   * @param init - Function returning the initial state\n   * @returns A builder with `.emits()` to declare event types\n   *\n   * @example\n   * ```typescript\n   * .init(() => ({ count: 0, created: new Date() }))\n   * ```\n   *\n   * @example With initial data\n   * ```typescript\n   * .init((data) => ({ ...data, createdAt: new Date() }))\n   * ```\n   */\n  init: (init: () => Readonly<TState>) => {\n    /**\n     * Declares the event types that this state can emit.\n     *\n     * Events represent facts that have happened - they should be named in past tense.\n     * Each event is defined with a Zod schema for type safety and runtime validation.\n     *\n     * @template TEvents - Event schemas type\n     * @param events - Object mapping event names to Zod schemas\n     * @returns An ActionBuilder (with optional `.patch()` to override specific reducers)\n     *\n     * @example\n     * ```typescript\n     * .emits({\n     *   Incremented: z.object({ amount: z.number() }),\n     *   Decremented: z.object({ amount: z.number() }),\n     *   Reset: z.object({})\n     * })\n     * ```\n     */\n    emits: <TEvents extends Schemas>(\n      events: ZodTypes<TEvents>\n      // eslint-disable-next-line @typescript-eslint/no-empty-object-type -- {} avoids string index signature that Record<string, never> would add, keeping keyof A precise\n    ) => ActionBuilder<TState, TEvents, {}, TName> & {\n      /**\n       * Overrides specific event reducers. Events without a custom patch\n       * default to passthrough: `({ data }) => data` (event data merges\n       * into state).\n       *\n       * @param patch - Partial map of event names to patch handler functions\n       * @returns An ActionBuilder for defining actions\n       *\n       * @example Only override the events that need custom logic\n       * ```typescript\n       * .emits({ TicketOpened, TicketClosed, TicketResolved })\n       * .patch({\n       *   TicketOpened: ({ data }) => {\n       *     const { message, messageId, userId, ...other } = data;\n       *     return { ...other, userId, messages: { [messageId]: { ... } } };\n       *   },\n       * })\n       * // TicketClosed and TicketResolved use passthrough\n       * ```\n       */\n      patch: (\n        patch: Partial<PatchHandlers<TState, TEvents>>\n        // eslint-disable-next-line @typescript-eslint/no-empty-object-type -- {} avoids string index signature that Record<string, never> would add, keeping keyof A precise\n      ) => ActionBuilder<TState, TEvents, {}, TName>;\n    };\n  };\n};\n\n/** Helper: a single-key record mapping a state name to its Zod schema. */\ntype StateEntry<\n  TKey extends string = string,\n  TState extends Schema = Schema,\n> = {\n  [P in TKey]: ZodType<TState>;\n};\n\n/** Helper: a single-key record mapping an action name to its Zod schema. */\ntype ActionEntry<\n  TKey extends string = string,\n  TNewActions extends Schema = Schema,\n> = {\n  [P in TKey]: ZodType<TNewActions>;\n};\n\n/**\n * Builder interface for defining actions (commands) on a state.\n *\n * Actions represent user/system intents to modify state. Each action is validated\n * against a schema, can have business rule invariants, and must emit one or more events.\n *\n * @template TState - State schema type\n * @template TEvents - Event schemas type\n * @template TActions - Action schemas type\n * @template TName - State name literal type\n * @template TSnap - `true` once `.snap(...)` has been called. Gates the\n *   `.autocloses({ keep })` rolling-window option — a windowed close is\n *   meaningless without snapshots, so `keep` only typechecks after\n *   `.snap` in the chain.\n *\n * @see {@link state} for complete usage examples\n */\nexport type ActionBuilder<\n  TState extends Schema,\n  TEvents extends Schemas,\n  TActions extends Schemas,\n  TName extends string = string,\n  TSnap extends boolean = false,\n> = {\n  /**\n   * Defines an action (command) that can be executed on this state.\n   *\n   * Actions represent intents to change state - they should be named in imperative form\n   * (e.g., \"CreateUser\", \"IncrementCounter\", \"PlaceOrder\"). Actions are validated against\n   * their schema and must emit at least one event.\n   *\n   * Pass a `{ ActionName: schema }` record — use shorthand `{ ActionName }`\n   * when the variable name matches the action name. The key becomes the\n   * action name, the value the Zod schema.\n   *\n   * Pass an optional second argument to declare a per-action retry\n   * policy — the orchestrator retries this action on\n   * {@link ConcurrencyError} up to `maxRetries` extra times, applying\n   * `backoff` between attempts when set. Omit the argument to keep the\n   * current single-attempt behavior (`ConcurrencyError` surfaces on\n   * first conflict).\n   *\n   * @template TKey - Action name (string literal type)\n   * @template TNewActions - Action payload schema type\n   * @param entry - Single-key record `{ ActionName: schema }`\n   * @param options - Optional per-action retry policy\n   *   ({@link ActionOptions}).\n   * @returns An object with `.given()` and `.emit()` for further configuration\n   *\n   * @example Simple action without invariants\n   * ```typescript\n   * .on({ increment: z.object({ by: z.number() }) })\n   *   .emit((action) => [\"Incremented\", { amount: action.by }])\n   * ```\n   *\n   * @example Hot-stream action with retry + jittered exponential backoff\n   * ```typescript\n   * .on(\n   *   { transfer: z.object({ amount: z.number() }) },\n   *   {\n   *     maxRetries: 5,\n   *     backoff: { strategy: \"exponential\", baseMs: 10, maxMs: 200, jitter: true },\n   *   }\n   * )\n   *   .emit((action) => [\"Transferred\", { amount: action.amount }])\n   * ```\n   *\n   * @example Action with business rules\n   * ```typescript\n   * .on({ withdraw: z.object({ amount: z.number() }) })\n   *   .given([\n   *     { description: \"Account must be open\", valid: (state) => state.status === \"open\" },\n   *     { description: \"Funds must be available\", valid: (state) => state.balance > 0 }\n   *   ])\n   *   .emit((action) => [\"Withdrawn\", { amount: action.amount }])\n   * ```\n   *\n   * @example Action with shorthand (variable name matches action name)\n   * ```typescript\n   * const OpenTicket = z.object({ title: z.string() });\n   * .on({ OpenTicket })\n   *   .emit((action) => [\"TicketOpened\", { title: action.title }])\n   * ```\n   */\n  on: <TKey extends string, TNewActions extends Schema>(\n    entry: ActionEntry<TKey, TNewActions>,\n    options?: ActionOptions\n  ) => {\n    /**\n     * Adds business rule invariants that must hold before the action can execute.\n     *\n     * Invariants are checked after loading the current state but before emitting\n     * events. Each invariant pairs a `description` with a `valid(state, actor?)`\n     * predicate — when a predicate returns `false`, the action throws\n     * `InvariantError` carrying the description. All invariants must pass for\n     * the action to succeed.\n     *\n     * @param rules - Array of {@link Invariant} objects (`{ description, valid }`)\n     * @returns An object with `.emit()` to finalize the action\n     *\n     * @example\n     * ```typescript\n     * .given([\n     *   { description: \"Must be active\", valid: (state) => state.status === \"active\" },\n     *   { description: \"Must be the owner\", valid: (state, actor) => state.ownerId === actor?.id }\n     * ])\n     * ```\n     */\n    given: (rules: Invariant<TState>[]) => {\n      /**\n       * Defines the action handler that emits events.\n       *\n       * The handler receives the action payload and current state snapshot,\n       * and must return one or more events to emit. Events are applied to state\n       * via the patch handlers defined earlier.\n       *\n       * Pass a string event name for passthrough: the action payload becomes\n       * the event data directly.\n       *\n       * @param handler - Function that returns events to emit, or event name string for passthrough\n       * @returns The ActionBuilder for chaining more actions\n       *\n       * @example Custom handler\n       * ```typescript\n       * .emit((action, snapshot) => {\n       *   const newBalance = snapshot.state.balance + action.amount;\n       *   return [\"Deposited\", { amount: action.amount, newBalance }];\n       * })\n       * ```\n       *\n       * @example Passthrough (action payload = event data)\n       * ```typescript\n       * .emit(\"TicketAssigned\")\n       * ```\n       */\n      emit: {\n        /** Custom handler — receives `(action, snapshot)` and returns one\n         *  or more `[EventName, data]` tuples (or `undefined`). */\n        (\n          handler: ActionHandler<\n            TState,\n            TEvents,\n            { [P in TKey]: TNewActions },\n            TKey\n          >\n        ): ActionBuilder<\n          TState,\n          TEvents,\n          TActions & { [P in TKey]: TNewActions },\n          TName,\n          TSnap\n        >;\n        /** Passthrough — the action payload becomes the event data\n         *  directly. Must reference an event declared in `.emits()`. */\n        (\n          event_name: keyof TEvents & string\n        ): ActionBuilder<\n          TState,\n          TEvents,\n          TActions & { [P in TKey]: TNewActions },\n          TName,\n          TSnap\n        >;\n      };\n    };\n    /**\n     * Defines the action handler that emits events. Same two overloads as\n     * the post-`.given()` form above:\n     *\n     * - **Function** — receives `(action, snapshot)` and returns one or\n     *   more `[EventName, data]` tuples (or `undefined`).\n     * - **String** — passthrough: the action payload becomes the event\n     *   data directly. Must reference an event declared in `.emits()`.\n     *\n     * The two overloads are kept separate (rather than merged into a\n     * `handler | string` union) so that TS contextual typing of the\n     * function alternative isn't degraded by considering the string\n     * branch — under the union form `TState` could collapse to its\n     * `Schema` constraint inside the callback.\n     *\n     * @example Passthrough (action payload = event data)\n     * ```typescript\n     * .emit(\"Incremented\")\n     * ```\n     *\n     * @example Single event\n     * ```typescript\n     * .emit((action) => [\"Incremented\", { amount: action.by }])\n     * ```\n     *\n     * @example Multiple events\n     * ```typescript\n     * .emit((action) => [\n     *   [\"Incremented\", { amount: action.by }],\n     *   [\"LogUpdated\", { message: `Incremented by ${action.by}` }]\n     * ])\n     * ```\n     */\n    emit: {\n      (\n        handler: ActionHandler<\n          TState,\n          TEvents,\n          { [P in TKey]: TNewActions },\n          TKey\n        >\n      ): ActionBuilder<\n        TState,\n        TEvents,\n        TActions & { [P in TKey]: TNewActions },\n        TName,\n        TSnap\n      >;\n      (\n        event_name: keyof TEvents & string\n      ): ActionBuilder<\n        TState,\n        TEvents,\n        TActions & { [P in TKey]: TNewActions },\n        TName,\n        TSnap\n      >;\n    };\n  };\n  /**\n   * Defines a snapshotting strategy to optimize state reconstruction.\n   *\n   * Snapshots store the current state at a point in time, allowing faster state loading\n   * by avoiding replaying all events from the beginning. The snap function is called\n   * after each event is applied and should return `true` when a snapshot should be taken.\n   *\n   * @param snap - Predicate function that returns true when a snapshot should be taken\n   * @returns The ActionBuilder for chaining\n   *\n   * @example Snapshot every 10 events\n   * ```typescript\n   * .snap((snapshot) => snapshot.patches >= 10)\n   * ```\n   *\n   * @example Snapshot based on state size\n   * ```typescript\n   * .snap((snapshot) => {\n   *   const estimatedSize = JSON.stringify(snapshot.state).length;\n   *   return estimatedSize > 10000 || snapshot.patches >= 50;\n   * })\n   * ```\n   *\n   * @example Time-based snapshotting\n   * ```typescript\n   * .snap((snapshot) => {\n   *   const hoursSinceLastSnapshot = snapshot.patches * 0.1; // Estimate\n   *   return hoursSinceLastSnapshot >= 24;\n   * })\n   * ```\n   */\n  snap: (\n    snap: (snapshot: Snapshot<TState, TEvents>) => boolean\n  ) => ActionBuilder<TState, TEvents, TActions, TName, true>;\n  /**\n   * Declares the disclosure predicate for `sensitive(...)`-marked event\n   * fields. Gates external reads: returning `true` allows the actor to see\n   * plaintext on the event; returning `false` substitutes `\"[REDACTED]\"`.\n   * When absent, the framework default-denies on every external read —\n   * fail-safe.\n   *\n   * One predicate per state. A second `.discloses(...)` call replaces the\n   * first (same shape as snapshots being state-level, not per-event).\n   *\n   * The predicate receives the full event including merged PII so it can\n   * branch on the payload itself (e.g.\n   * `event.data.ownerId === actor.id`). Reducers, projections, and\n   * reactions are unaffected — they follow separate visibility rules\n   * documented in #855.\n   *\n   * @param disclose - Predicate `(event, actor) => boolean`. `true` =\n   *   plaintext, `false` = `\"[REDACTED]\"` substitution.\n   * @returns The ActionBuilder for chaining.\n   *\n   * @example Owner-or-admin disclosure\n   * ```typescript\n   * state({ User: userSchema })\n   *   .init(() => ({ ... }))\n   *   .emits({ UserRegistered: z.object({ email: sensitive(z.string()) }) })\n   *   .discloses((event, actor) =>\n   *     actor.id === event.stream || actor.roles?.includes(\"admin\"))\n   * ```\n   */\n  discloses: (\n    disclose: (\n      event: Committed<TEvents, keyof TEvents & string>,\n      actor: Actor\n    ) => boolean\n  ) => ActionBuilder<TState, TEvents, TActions, TName, TSnap>;\n  /**\n   * Declares the online close predicate for this state. The\n   * orchestrator's autoclose cycle iterates the state's streams once\n   * per tick and calls the predicate per candidate; truthy results are\n   * scheduled for atomic truncate-and-seed via `Store.truncate` on the\n   * next batch.\n   *\n   * One predicate per state. A second `.autocloses(...)` call replaces\n   * the first (same shape as `.snap` / `.discloses` — state-level, not\n   * per-event). Absent → the state opts out of online close entirely;\n   * the cycle skips it and pays zero per-tick cost for it.\n   *\n   * Pass a declarative {@link AutoclosePolicy} object literal covering the\n   * three operational pressure points (`after`, `is`, `reaches`). Top-level\n   * fields combine with AND; an optional `or: {...}` block opens an\n   * alternative OR path. Validated via Zod at build time; misconfiguration\n   * throws before `act().build()` completes.\n   *\n   * Under the hood this compiles to a synthesized reaction (#1090) that runs\n   * on a per-aggregate synthetic stream: it defers to `head.created + the\n   * policy's min after` while the cooldown holds and closes the stream once\n   * the policy matches. There is no background sweep.\n   *\n   * **The function-predicate form was removed (#1090).** `.autocloses` no\n   * longer accepts `(stream, head, count) => boolean`; an opaque predicate has\n   * no derivable due-time or terminal event to react to. For conditions the\n   * declarative form can't express, call `app.close(...)` from your own logic.\n   *\n   * @param policy The declarative {@link AutoclosePolicy} bag.\n   * @returns The ActionBuilder for chaining.\n   *\n   * @example Declarative — cooldown after terminal (a Ticket closes\n   *   90 days after resolution).\n   * ```typescript\n   * .autocloses({ is: \"TicketResolved\", after: { days: 90 } })\n   * ```\n   *\n   * @example Declarative — multi-terminal (an Order closes on any of\n   *   three terminal events, no cooldown).\n   * ```typescript\n   * .autocloses({ is: [\"Shipped\", \"Delivered\", \"Cancelled\"] })\n   * ```\n   *\n   * @example Declarative — time-only retention (a Session closes\n   *   after 24h regardless of head event).\n   * ```typescript\n   * .autocloses({ after: { days: 1 } })\n   * ```\n   *\n   * @example Declarative — pure cardinality cap.\n   * ```typescript\n   * .autocloses({ reaches: 10_000 })\n   * ```\n   *\n   * @example Declarative — primary cooldown + safety-net backstop.\n   * ```typescript\n   * .autocloses({\n   *   is: \"TicketResolved\",     // primary trigger\n   *   after: { days: 90 },      // AND aged 90 days\n   *   or: { reaches: 10_000 },  // OR cardinality safety net\n   * })\n   * ```\n   *\n   * @example Declarative — pure OR (only backstops, no primary\n   *   cooldown).\n   * ```typescript\n   * .autocloses({ or: { is: \"TicketResolved\", reaches: 10_000 } })\n   * ```\n   *\n   * @example Rolling window — keep the last 180 days of real events on a\n   *   live stream (requires `.snap(...)` earlier in the chain; `keep`\n   *   won't typecheck without it). Each eligible cycle prunes the prefix\n   *   below the closest safe snapshot older than `now − keep`.\n   * ```typescript\n   * .snap((s) => s.patches >= 100)\n   * .autocloses({ keep: { days: 180 } })\n   * ```\n   *\n   * @example Terminate AND prune — close 90 days after resolution,\n   *   meanwhile keep open streams pruned to a 180-day window.\n   * ```typescript\n   * .snap((s) => s.patches >= 100)\n   * .autocloses({ is: \"TicketResolved\", after: { days: 90 }, keep: { days: 180 } })\n   * ```\n   */\n  autocloses: (\n    policy: [TSnap] extends [true]\n      ? AutoclosePolicy\n      : Omit<AutoclosePolicy, \"keep\"> & {\n          /** Rolling-window retention requires `.snap(...)` earlier in\n           *  the builder chain — a windowed close prunes behind a real\n           *  snapshot, so a state that never snapshots has nothing to\n           *  prune behind. */\n          keep?: never;\n        }\n  ) => ActionBuilder<TState, TEvents, TActions, TName, TSnap>;\n  /**\n   * Declares the archiver the online close cycle runs **before**\n   * truncating a stream this state's `.autocloses(...)` predicate\n   * accepted. Hosts use it to write events to durable storage (S3,\n   * an analytics warehouse, cold tier) before the tombstone lands,\n   * so the truncate doesn't lose history that the operator still\n   * needs.\n   *\n   * Threads into `CloseTarget.archive` via the same plumbing\n   * `app.close({ stream, archive })` already uses — the cycle holds\n   * the stream's guard while the archiver runs, and a thrown\n   * archiver leaves the stream guarded but un-truncated. No partial\n   * truncate state, no data loss; the cycle retries the candidate\n   * on the next tick.\n   *\n   * One archiver per state. A second `.archives(...)` call replaces\n   * the first (same shape as `.snap` / `.discloses` /\n   * `.autocloses`). Absent → the cycle truncates without an archive\n   * step.\n   *\n   * @param archive `(stream, head) => Promise<void>`. Runs while\n   *   the stream is locked against new writes; the truncate runs\n   *   immediately after a successful resolve.\n   * @returns The ActionBuilder for chaining.\n   *\n   * @example Archive to S3 before truncate.\n   * ```typescript\n   * state({ Ticket: ticketSchema })\n   *   .emits({ TicketOpened, TicketResolved })\n   *   // ...\n   *   .autocloses({ is: \"TicketResolved\" })\n   *   .archives(async (stream) => {\n   *     const events = await loadEvents(stream);\n   *     await s3.upload(`tickets/${stream}.jsonl`, events);\n   *   })\n   * ```\n   */\n  archives: (\n    archive: AutocloseArchiver<TEvents>\n  ) => ActionBuilder<TState, TEvents, TActions, TName, TSnap>;\n  /**\n   * Finalizes and builds the state definition.\n   *\n   * Call this method after defining all actions, invariants, and patches to create\n   * the complete State object that can be registered with Act.\n   *\n   * @returns The complete strongly-typed State definition\n   *\n   * @example\n   * ```typescript\n   * const Counter = state({ Counter: schema })\n   *   .init(() => ({ count: 0 }))\n   *   .emits({ Incremented: z.object({ amount: z.number() }) })\n   *   .patch({ Incremented: ({ data }, state) => ({ count: state.count + data.amount }) })\n   *   .on({ increment: z.object({ by: z.number() }) })\n   *     .emit((action) => [\"Incremented\", { amount: action.by }])\n   *   .build(); // Returns State<TState, TEvents, TActions, TName>\n   * ```\n   */\n  build: () => State<TState, TEvents, TActions, TName>;\n};\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 (invariants) via `.given()`\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 * @example Passthrough state (no custom patch or emit needed)\n * ```typescript\n * const DigitBoard = state({ DigitBoard: z.object({ digit: z.string() }) })\n *   .init(() => ({ digit: \"\" }))\n *   .emits({ DigitCounted: z.object({ digit: z.string() }) })\n *   // no .patch() — passthrough is the default (event data merges into state)\n *   .on({ CountDigit: z.object({ digit: z.string() }) })\n *     .emit(\"DigitCounted\")  // string passthrough — action payload becomes event data\n *   .build();\n * ```\n *\n * @example State with multiple events and invariants\n * ```typescript\n * const BankAccount = state({ BankAccount: z.object({\n *   balance: z.number(),\n *   currency: z.string(),\n *   status: z.enum([\"open\", \"closed\"])\n * }) })\n *   .init(() => ({ balance: 0, currency: \"USD\", status: \"open\" }))\n *   .emits({\n *     Deposited: z.object({ amount: z.number() }),\n *     Withdrawn: z.object({ amount: z.number() }),\n *     Closed: z.object({})\n *   })\n *   .patch({  // only override events needing custom logic\n *     Deposited: ({ data }, state) => ({ balance: state.balance + data.amount }),\n *     Withdrawn: ({ data }, state) => ({ balance: state.balance - data.amount }),\n *     Closed: () => ({ status: \"closed\", balance: 0 })\n *   })\n *   .on({ deposit: z.object({ amount: z.number() }) })\n *     .given([\n *       { description: \"Account must be open\", valid: (state) => state.status === \"open\" }\n *     ])\n *     .emit(\"Deposited\")  // passthrough — action payload { amount } becomes event data\n *   .on({ withdraw: z.object({ amount: z.number() }) })\n *     .given([\n *       { description: \"Account must be open\", valid: (state) => state.status === \"open\" },\n *       { description: \"Funds must be available\", valid: (state) => state.balance > 0 }\n *     ])\n *     .emit(\"Withdrawn\")\n *   .on({ close: z.object({}) })\n *     .given([\n *       { description: \"Account must be open\", valid: (state) => state.status === \"open\" },\n *       { description: \"Balance must be zero\", valid: (state) => state.balance === 0 }\n *     ])\n *     .emit(\"Closed\")\n *   .build();\n * ```\n *\n * @example State with snapshotting\n * ```typescript\n * const User = state({ User: z.object({\n *   name: z.string(),\n *   email: z.string(),\n *   loginCount: z.number()\n * }) })\n *   .init((data) => ({ ...data, loginCount: 0 }))\n *   .emits({\n *     UserCreated: z.object({ name: z.string(), email: z.string() }),\n *     UserLoggedIn: z.object({})\n *   })\n *   .patch({  // only override events needing custom logic\n *     UserLoggedIn: (_, state) => ({ loginCount: state.loginCount + 1 })\n *   })\n *   // UserCreated uses passthrough — event data merges into state\n *   .on({ createUser: z.object({ name: z.string(), email: z.string() }) })\n *     .emit(\"UserCreated\")  // passthrough\n *   .on({ login: z.object({}) })\n *     .emit(\"UserLoggedIn\")\n *   .snap((snap) => snap.patches >= 10) // Snapshot every 10 events\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          // eslint-disable-next-line @typescript-eslint/no-empty-object-type -- {} avoids string index signature\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        // #1269: 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      function given(rules: Invariant<TState>[]) {\n        internal.given ??= {} as GivenHandlers<TState, Schemas>;\n        (internal.given as Record<string, Invariant<TState>[]>)[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 detect emissions of deprecated events\n          // at build time (ACT-403). Dynamic forms — where the\n          // returned event name is computed inside the user's\n          // function — can't be inspected statically; they're caught\n          // by the runtime warning in event-sourcing.ts.\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      return { given, emit };\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 (#1090). 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, and\n      // cache the policy's min `after` window so the reaction knows whether\n      // to park on a due-time or wait for the next event; `keep` resolves\n      // to the rolling-window width the reaction prunes against.\n      internal.autoclose = compile_autoclose_policy(\n        policy\n      ) as AutoclosePredicate<TEvents>;\n      internal.autoclose_after_days = policy_min_after_days(policy);\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 (ACT-1128 / #788).\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  EventSink,\n  EventSource,\n  Query,\n  Schemas,\n} from \"./types/action.js\";\n\n/**\n * Construct a {@link CsvFile} from either a filesystem path (for\n * reading and/or writing through the OS) or an in-memory blob (a\n * pre-loaded CSV string, used by the inspector when a CSV arrives\n * over the wire via tRPC).\n *\n * Both modes share the same on-disk format, so the same blob shape\n * can be round-tripped through the transfer pipeline.\n */\nexport type CsvFileOptions = { path: string } | { blob: string };\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 (#1399). 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"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,eAAAA;AAAA,EAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,eAAAC;AAAA,EAAA;AAAA;AAAA;;;ACYA,IAAM,eA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ACf,eAAO,KAAK,KAAK,MAAM,CAAC,CAAC;AACzB,YAAI,KAAK;AAAA,MACX,OAAO;AACL,eAAO,KAAK,KAAK,MAAM,GAAG,IAAI,CAAC;AAC/B,YAAI,OAAO;AAAA,MACb;AAAA,IACF;AAAA,EACF;AACA,SAAO;AACT;AAEA,SAAS,WAAW,OAAuB;AACzC,MAAI,WAAW,KAAK,KAAK,EAAG,QAAO,IAAI,MAAM,QAAQ,MAAM,IAAI,CAAC;AAChE,SAAO;AACT;AAEA,SAAS,WAAW,QAAqB,MAA6B;AACpE,SAAO,IAAI,QAAc,CAAC,SAAS,WAAW;AAC5C,WAAO,MAAM,GAAG,IAAI;AAAA,GAAM,CAAC,QAAQ;AACjC,UAAI,IAAK,QAAO,GAAG;AAAA,UACd,SAAQ;AAAA,IACf,CAAC;AAAA,EACH,CAAC;AACH;","names":["cache","store","action","import_zod","import_zod","import_zod","correlated_at","log","store","cache","store","state","sensitive","deps","import_zod","store","config","store","tombstone","load","snap","state","cache","import_zod","store","import_node_crypto","state","action","import_zod","import_zod","import_node_crypto","store","state","store","cache","action","valid","action","block","config","cache","row","block","EventEmitter","store","action","cache","import_zod","state","config","import_zod","schema","sensitive","state","snap","state","config","config","noop","state","config","state","action","snap"]}