@demlik/tea 0.1.2 → 0.3.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +49 -0
- package/dist/agent/index.d.ts +16 -770
- package/dist/agent/index.js +18 -16
- package/dist/authed-call/index.d.ts +3 -3
- package/dist/authed-call/index.js +22 -36
- package/dist/authed-call/index.js.map +1 -1
- package/dist/await-terminal/index.d.ts +2 -2
- package/dist/await-terminal/index.js +2 -2
- package/dist/batch-window/index.d.ts +3 -3
- package/dist/batch-window/index.js +3 -3
- package/dist/cache/index.d.ts +2 -2
- package/dist/cache/index.js +5 -2
- package/dist/{chunk-3545BOYL.js → chunk-25LBDCBC.js} +6 -5
- package/dist/chunk-25LBDCBC.js.map +1 -0
- package/dist/{chunk-IN33Q4VJ.js → chunk-2KNLKQVN.js} +3 -3
- package/dist/{chunk-IN33Q4VJ.js.map → chunk-2KNLKQVN.js.map} +1 -1
- package/dist/{chunk-MMH7CW5K.js → chunk-BP2R7TPP.js} +216 -157
- package/dist/chunk-BP2R7TPP.js.map +1 -0
- package/dist/chunk-C6QC273X.js +71 -0
- package/dist/chunk-C6QC273X.js.map +1 -0
- package/dist/{chunk-7W4LMPUW.js → chunk-CAXMQJJ3.js} +17 -24
- package/dist/chunk-CAXMQJJ3.js.map +1 -0
- package/dist/{chunk-UV6UWGEO.js → chunk-D736QUGF.js} +6 -5
- package/dist/chunk-D736QUGF.js.map +1 -0
- package/dist/chunk-EWJP3YYP.js +21 -0
- package/dist/chunk-EWJP3YYP.js.map +1 -0
- package/dist/{chunk-TGG26XMK.js → chunk-FV3Z5MBE.js} +10 -5
- package/dist/chunk-FV3Z5MBE.js.map +1 -0
- package/dist/chunk-G5E74IJB.js +8 -0
- package/dist/chunk-G5E74IJB.js.map +1 -0
- package/dist/{chunk-27N2SPTN.js → chunk-IXBKFQH5.js} +12 -11
- package/dist/chunk-IXBKFQH5.js.map +1 -0
- package/dist/{chunk-SQTCS44W.js → chunk-JFFVBEDI.js} +3 -3
- package/dist/{chunk-SQTCS44W.js.map → chunk-JFFVBEDI.js.map} +1 -1
- package/dist/chunk-LYLDCIPH.js +365 -0
- package/dist/chunk-LYLDCIPH.js.map +1 -0
- package/dist/{chunk-HJO6VNQI.js → chunk-MU6MCIAC.js} +3 -3
- package/dist/{chunk-HJO6VNQI.js.map → chunk-MU6MCIAC.js.map} +1 -1
- package/dist/{chunk-UYWUVEP6.js → chunk-MUUROGIH.js} +2 -2
- package/dist/chunk-MUUROGIH.js.map +1 -0
- package/dist/{chunk-EHIX7NYZ.js → chunk-MVY5DAMF.js} +4 -4
- package/dist/{chunk-EHIX7NYZ.js.map → chunk-MVY5DAMF.js.map} +1 -1
- package/dist/{chunk-LP7VQBRG.js → chunk-NPERUUUE.js} +76 -95
- package/dist/chunk-NPERUUUE.js.map +1 -0
- package/dist/{chunk-QLA76GIT.js → chunk-PBDYW2TU.js} +68 -9
- package/dist/chunk-PBDYW2TU.js.map +1 -0
- package/dist/{chunk-5VNWZADP.js → chunk-Q2UM7BXU.js} +18 -7
- package/dist/chunk-Q2UM7BXU.js.map +1 -0
- package/dist/chunk-RMX4EOQK.js +26 -0
- package/dist/chunk-RMX4EOQK.js.map +1 -0
- package/dist/{chunk-2YOE5PIS.js → chunk-S2EGRPCM.js} +8 -6
- package/dist/chunk-S2EGRPCM.js.map +1 -0
- package/dist/{chunk-ON24RKSE.js → chunk-S4O26D7B.js} +7 -14
- package/dist/chunk-S4O26D7B.js.map +1 -0
- package/dist/{chunk-3XJWC7VW.js → chunk-SK5JGUY7.js} +3 -3
- package/dist/{chunk-3XJWC7VW.js.map → chunk-SK5JGUY7.js.map} +1 -1
- package/dist/{chunk-5DEQ5I3U.js → chunk-TPGASTFF.js} +8 -10
- package/dist/chunk-TPGASTFF.js.map +1 -0
- package/dist/{chunk-SC3FAFZN.js → chunk-UF4MZSLT.js} +2 -2
- package/dist/chunk-UF4MZSLT.js.map +1 -0
- package/dist/{chunk-PS23H6KQ.js → chunk-VBUCHVCV.js} +6 -5
- package/dist/chunk-VBUCHVCV.js.map +1 -0
- package/dist/{chunk-S3FQN4SL.js → chunk-WGGAMW7Y.js} +191 -178
- package/dist/chunk-WGGAMW7Y.js.map +1 -0
- package/dist/chunk-ZJ5AOYBH.js +8 -0
- package/dist/chunk-ZJ5AOYBH.js.map +1 -0
- package/dist/{chunk-LEC4U6CX.js → chunk-ZVJZ72HY.js} +3 -3
- package/dist/{chunk-LEC4U6CX.js.map → chunk-ZVJZ72HY.js.map} +1 -1
- package/dist/circuit-breaker/index.d.ts +1 -0
- package/dist/circuit-breaker/index.js +1 -1
- package/dist/{core-BoB6t7dB.d.ts → core-42kapW0n.d.ts} +105 -6
- package/dist/deadline/index.d.ts +77 -11
- package/dist/deadline/index.js +3 -3
- package/dist/devtools/index.js +8 -28
- package/dist/devtools/index.js.map +1 -1
- package/dist/do/index.d.ts +483 -339
- package/dist/do/index.js +244 -214
- package/dist/do/index.js.map +1 -1
- package/dist/{durable-effects-CO9Uh971.d.ts → durable-effects-CFRngTNA.d.ts} +3 -3
- package/dist/extension/index.d.ts +25 -7
- package/dist/extension/index.js +4 -3
- package/dist/extension/index.js.map +1 -1
- package/dist/extension/react.js +4 -3
- package/dist/extension/react.js.map +1 -1
- package/dist/extension/subs/index.d.ts +2 -2
- package/dist/extension/subs/index.js +7 -10
- package/dist/extension/subs/index.js.map +1 -1
- package/dist/fan-out/index.d.ts +10 -10
- package/dist/fan-out/index.js +3 -3
- package/dist/idempotent-intake/index.d.ts +2 -2
- package/dist/idempotent-intake/index.js +3 -3
- package/dist/index.d.ts +50 -472
- package/dist/index.js +2 -2
- package/dist/llm-call/index.d.ts +3 -2
- package/dist/llm-call/index.js +12 -10
- package/dist/machine-B_BF4jij.d.ts +804 -0
- package/dist/machine-viz/index.d.ts +1 -1
- package/dist/machine-viz/index.js +2 -2
- package/dist/mem/index.d.ts +3 -2
- package/dist/mem/index.js.map +1 -1
- package/dist/monitored-run/index.d.ts +54 -30
- package/dist/monitored-run/index.js +7 -7
- package/dist/node/index.d.ts +3 -2
- package/dist/node/index.js +2 -3
- package/dist/node/index.js.map +1 -1
- package/dist/paginated-walk/index.d.ts +2 -2
- package/dist/paginated-walk/index.js +11 -10
- package/dist/parity/index.d.ts +6 -5
- package/dist/parity/index.js +5 -4
- package/dist/parity/index.js.map +1 -1
- package/dist/pbt/arbitraries/index.d.ts +1 -1
- package/dist/pbt/index.d.ts +1 -1
- package/dist/pbt/index.js +3 -3
- package/dist/pbt/index.js.map +1 -1
- package/dist/pbt/runners/index.d.ts +1 -1
- package/dist/pbt/runners/index.js +3 -3
- package/dist/poller/index.d.ts +59 -17
- package/dist/poller/index.js +56 -20
- package/dist/poller/index.js.map +1 -1
- package/dist/prediction/index.d.ts +1 -1
- package/dist/prediction/index.js +2 -2
- package/dist/pure/index.d.ts +1 -1
- package/dist/pure/index.js +2 -2
- package/dist/rate-limit/index.d.ts +2 -2
- package/dist/rate-limit/index.js +1 -1
- package/dist/react/index.d.ts +3 -2
- package/dist/react/index.js +2 -2
- package/dist/react/index.js.map +1 -1
- package/dist/reconciler/index.d.ts +2 -2
- package/dist/reconciler/index.js +13 -15
- package/dist/reconciler/index.js.map +1 -1
- package/dist/recorder/index.d.ts +20 -20
- package/dist/recorder/index.js +1 -1
- package/dist/resilient-call/index.d.ts +31 -6
- package/dist/resilient-call/index.js +10 -9
- package/dist/retry-backoff/index.d.ts +191 -14
- package/dist/retry-backoff/index.js +1 -1
- package/dist/retry-to-success/index.js +1 -1
- package/dist/runtime-types-gsog27b6.d.ts +337 -0
- package/dist/saga/index.d.ts +3 -2
- package/dist/saga/index.js +2 -2
- package/dist/saga/index.js.map +1 -1
- package/dist/snapshot/index.d.ts +1 -1
- package/dist/snapshot/index.js +3 -3
- package/dist/subs/index.d.ts +372 -4
- package/dist/subs/index.js +4 -1
- package/dist/testing/index.d.ts +2 -2
- package/dist/testing/index.js +2 -2
- package/dist/throttled-input/index.d.ts +2 -2
- package/dist/throttled-input/index.js +14 -13
- package/dist/throttled-input/index.js.map +1 -1
- package/dist/token-refresh/index.d.ts +1 -1
- package/dist/token-refresh/index.js +3 -3
- package/dist/trace-replay/index.d.ts +12 -7
- package/dist/trace-replay/index.js +4 -3
- package/dist/{types-B-8bcAp8.d.ts → types-KbL3W1mj.d.ts} +1 -1
- package/dist/with-deadline/index.d.ts +1 -1
- package/dist/with-deadline/index.js +2 -2
- package/dist/with-resilience/index.d.ts +21 -2
- package/dist/with-resilience/index.js +12 -23
- package/dist/with-resilience/index.js.map +1 -1
- package/dist/with-telemetry/index.d.ts +1 -1
- package/dist/with-telemetry/index.js +2 -2
- package/dist/work-queue/adapter.d.ts +2 -2
- package/dist/work-queue/adapter.js +2 -2
- package/dist/work-queue/index.d.ts +3 -2
- package/dist/work-queue/index.js +1 -1
- package/dist/work-queue/index.js.map +1 -1
- package/dist/work-queue/ops.d.ts +2 -2
- package/dist/work-queue/ops.js +1 -1
- package/dist/workflow/index.d.ts +51 -19
- package/dist/workflow/index.js +71 -52
- package/dist/workflow/index.js.map +1 -1
- package/package.json +4 -19
- package/dist/chunk-27N2SPTN.js.map +0 -1
- package/dist/chunk-2YOE5PIS.js.map +0 -1
- package/dist/chunk-3545BOYL.js.map +0 -1
- package/dist/chunk-5DEQ5I3U.js.map +0 -1
- package/dist/chunk-5VNWZADP.js.map +0 -1
- package/dist/chunk-6RGBKODV.js +0 -268
- package/dist/chunk-6RGBKODV.js.map +0 -1
- package/dist/chunk-7W4LMPUW.js.map +0 -1
- package/dist/chunk-DILMKOZ7.js +0 -91
- package/dist/chunk-DILMKOZ7.js.map +0 -1
- package/dist/chunk-K7Q23EQ4.js +0 -20
- package/dist/chunk-K7Q23EQ4.js.map +0 -1
- package/dist/chunk-LP7VQBRG.js.map +0 -1
- package/dist/chunk-MMH7CW5K.js.map +0 -1
- package/dist/chunk-NSDFA6M6.js +0 -198
- package/dist/chunk-NSDFA6M6.js.map +0 -1
- package/dist/chunk-ON24RKSE.js.map +0 -1
- package/dist/chunk-PS23H6KQ.js.map +0 -1
- package/dist/chunk-QLA76GIT.js.map +0 -1
- package/dist/chunk-S3FQN4SL.js.map +0 -1
- package/dist/chunk-SC3FAFZN.js.map +0 -1
- package/dist/chunk-TGG26XMK.js.map +0 -1
- package/dist/chunk-UV6UWGEO.js.map +0 -1
- package/dist/chunk-UYWUVEP6.js.map +0 -1
- package/dist/chunk-VLGARN6H.js +0 -202
- package/dist/chunk-VLGARN6H.js.map +0 -1
- package/dist/raft/demo.d.ts +0 -105
- package/dist/raft/demo.js +0 -172
- package/dist/raft/demo.js.map +0 -1
- package/dist/raft/index.d.ts +0 -548
- package/dist/raft/index.js +0 -7
- package/dist/raft/index.js.map +0 -1
- package/dist/raft/sim.d.ts +0 -222
- package/dist/raft/sim.js +0 -8
- package/dist/raft/sim.js.map +0 -1
- package/dist/raft/timeline.d.ts +0 -46
- package/dist/raft/timeline.js +0 -62
- package/dist/raft/timeline.js.map +0 -1
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/observability.ts","../src/runtime-types.ts","../src/run.ts"],"names":["opts"],"mappings":";;;;AAsDO,SAAS,cAAA,CACd,SACA,IAAA,EACsB;AACtB,EAAA,MAAM,SAAwC,EAAC;AAC/C,EAAA,IAAI,OAAA,GAAU,KAAA;AAEd,EAAA,MAAM,IAAA,GAAO,CAAC,KAAA,KAA6C;AACzD,IAAA,MAAA,CAAO,KAAK,KAAK,CAAA;AACjB,IAAA,IAAI,MAAA,CAAO,MAAA,GAAS,IAAA,EAAM,MAAA,CAAO,KAAA,EAAM;AAAA,EACzC,CAAA;AAMA,EAAA,MAAM,SAAA,GACJ,IAAA,IAAQ,CAAA,GACJ,MAAY;AAAA,EAAC,CAAA,GACb,OAAA,CAAQ,OAAA,CAAQ,CAAC,KAAK,KAAA,KAAU;AAC9B,IAAA,IAAA,CAAK,EAAE,GAAA,EAAK,KAAA,EAAO,CAAA;AAAA,EACrB,CAAC,CAAA;AACP,EAAA,MAAM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F,UAAA,MAAM,KAAA,CAAM,KAAK,KAAK,CAAA;AAAA,QACxB,SAAS,KAAA,EAAO;AACd,UAAA,WAAA,CAAY,KAAA,EAAO,EAAE,KAAA,EAAO,WAAA,EAAa,CAAA;AAAA,QAC3C;AAAA,MACF;AAAA,IACF;AAAA,GACF;AAEA,EAAA,OAAO,OAAA;AACT","file":"chunk-BP2R7TPP.js","sourcesContent":["import type { BootingRuntime } from \"./runtime-types\";\n\n// === historyTracker: composable observability helper ===\n//\n// A bounded ring buffer of recent `(msg, state)` transitions, built on the\n// Runtime's public `observe` API. The substrate itself stays minimal — it has\n// no notion of history, no opt to enable one, no method on the Runtime\n// interface to read one. Anything that wants \"recent transitions\" composes via\n// this helper.\n//\n// Why not put this on the Runtime interface as `runtime.history()`? Because\n// history is derivable. Putting it on the Runtime privileges one use case\n// (debug inspectors) at the substrate level and grows the interface for\n// everyone; the composition shape stays out of the dispatch loop entirely, so\n// the substrate's hot path pays no cost for a feature it doesn't need.\n\nexport interface HistoryTracker<S, M extends { type: string }> {\n /**\n * Snapshot of recorded transitions, oldest first. Each entry is\n * `{ msg, state }`: `msg` is `null` for the boot transition (recorded via\n * `onBoot`) and the applied Msg for every other (recorded via `observe`).\n *\n * Returns a shallow copy: the array is fresh on every call (callers may\n * iterate, slice, or replay without affecting the tracker's buffer).\n * Entry values are references to the originals (TEA states/msgs are\n * conventionally immutable; do not mutate them if your S/M is not).\n */\n snapshot(): readonly { readonly msg: M | null; readonly state: S }[];\n /**\n * Detach the underlying observer. After `stop()`:\n * - No new transitions are recorded.\n * - `snapshot()` continues to work and returns the buffer's contents\n * at the moment of stop (useful for post-hoc inspection in tests).\n * - The tracker holds no references that would prevent GC of the\n * `runtime` argument other than the entries already buffered.\n *\n * Idempotent — subsequent calls are no-ops.\n */\n stop(): void;\n}\n\n/**\n * Create a bounded history tracker over a Runtime. The tracker subscribes to\n * the runtime via `observe(...)` and retains the last `size` `(msg, state)`\n * transitions in a FIFO ring buffer.\n *\n * @param runtime Any `BootingRuntime<S, M>` (a full `Runtime` satisfies it).\n * The tracker uses only `observe`, which is total before boot —\n * attach it to the synchronous `run()` handle to record the\n * boot transition.\n * @param size Buffer cap. `size <= 0` produces an inert no-op tracker:\n * no observer is attached to the runtime, `snapshot()` is\n * always `[]`, and `stop()` is a no-op.\n */\nexport function historyTracker<S, M extends { type: string }>(\n runtime: BootingRuntime<S, M>,\n size: number,\n): HistoryTracker<S, M> {\n const buffer: { msg: M | null; state: S }[] = [];\n let stopped = false;\n\n const push = (entry: { msg: M | null; state: S }): void => {\n buffer.push(entry);\n if (buffer.length > size) buffer.shift();\n };\n\n // The boot transition (the `{ msg: null, state }` head entry) arrives via\n // `onBoot`; applied transitions arrive via `observe` with a total `msg`. The\n // public snapshot shape (`msg: M | null`) is unchanged — boot is still\n // `msg: null`.\n const unobserve =\n size <= 0\n ? (): void => {}\n : runtime.observe((msg, state) => {\n push({ msg, state });\n });\n const unboot =\n size <= 0\n ? (): void => {}\n : runtime.onBoot((state) => {\n push({ msg: null, state });\n });\n\n return {\n snapshot() {\n // Shallow copy — callers may freely iterate or mutate the returned\n // array. Entry values are references; see HistoryTracker docs.\n return buffer.slice();\n },\n stop() {\n if (stopped) return;\n stopped = true;\n unobserve();\n unboot();\n },\n };\n}\n","/**\n * @demlik/tea runtime interface surface + pure helpers — the public types,\n * interfaces, and construction/composition helpers the runtime (`./run`)\n * implements against: `Store`, the error-sink and supervision contracts, the\n * `RuntimeRef` / `BootingRuntime` / `Runtime` handle hierarchy, `definePort`, the\n * identity-typed constructors `defineMachine` / `asReducer`, and the pure tools\n * `replay` (compose without running) and `tryInterpret` (Railway).\n */\n\nimport { Result } from \"better-result\";\nimport type {\n InterpretDetached,\n Machine,\n Port,\n PortEmitter,\n Reducer,\n Sub,\n Transitions,\n} from \"./pure/core\";\nimport {\n type Cmd,\n detectUpdateForm,\n foldUpdates,\n structuralHash,\n} from \"./pure/core\";\n\n// The nominal brand minted ONLY through the validated construction path\n// (`asReducer` / `defineMachine`). A raw record of handlers is a structural\n// `Reducer<S, M, C>`; a branded one has passed through the single minting\n// boundary. The brand is an *optional* phantom so the structural annotation form\n// (`const update: Reducer<...> = { ... }`) keeps accepting plain object literals\n// — the guard that rejects an async reducer is `SyncReturn`'s non-thenable\n// return, enforced on every cell.\ndeclare const ReducerBrand: unique symbol;\n\n// A `Reducer` (or `Transitions`) minted through `asReducer` / `defineMachine`.\n// Carries the phantom brand; otherwise identical to its structural counterpart.\nexport type Branded<T> = T & { readonly [ReducerBrand]: true };\n\n/**\n * Compile-time exhaustiveness assertion for default branches of switches over\n * discriminated unions narrowed by hand (Sub handlers, message-bridge\n * dispatchers, port fanouts) — TS narrows the operand to `never` only if every\n * variant is covered, so adding one produces a compile error at the `absurd(x)`\n * site. Strengthens invariant 7 (identity is explicit).\n *\n * @example\n * switch (msg.type) {\n * case \"a\": return ...;\n * case \"b\": return ...;\n * default: return absurd(msg); // compile error if a \"c\" is added\n * }\n */\nexport function absurd(x: never): never {\n throw new Error(`unreachable: ${JSON.stringify(x)}`);\n}\n\n// The explicit \"this cell ignores this msg\" helper. Naming the no-op forces the\n// author to *decide* \"this cell does nothing\" (a real decision), distinct from\n// \"I forgot to write this cell\" (which the mapped type rejects); an implicit\n// wildcard would silently swallow a future Msg variant that should be handled.\n// Assignable to any Transitions cell regardless of S/M/C concrete types.\nexport const noop = <S, M, C extends Cmd>(\n state: S,\n _msg: M,\n): readonly [S, readonly C[]] => [state, []];\n\n// Module-level registry — process-scope, identity-by-name. The runtime witness\n// that every port name in this process is unique. Cleared only by the test-only\n// `__resetPortRegistry()` helper.\nconst definedPortNames = new Set<string>();\n\n/**\n * Thrown by `definePort` when a name has already been registered in the current\n * process. Symmetric with `SubIdCollisionError` (thrown by `reconcileSubs`) —\n * both mechanize invariant 7 (identity is explicit) at the runtime layer the\n * type system cannot reach (string names compared at runtime).\n */\nexport class PortNameCollisionError extends Error {\n override readonly name = \"PortNameCollisionError\";\n readonly _tag = \"PortNameCollisionError\" as const;\n constructor(portName: string) {\n super(\n `definePort: a port named \"${portName}\" was already defined. ` +\n `Each definePort call must use a unique name. ` +\n `If two modules need the same port, export it from one module and import it.`,\n );\n }\n}\n\n/**\n * Thrown by `reconcileSubs` when, within ONE desired subscription set, two subs\n * share an `id` but declare different `type`s — a silent bug class the type\n * system cannot reach (ids are strings compared at runtime). The symmetric twin\n * of `PortNameCollisionError`: both mechanize invariant 7 (identity is explicit)\n * at the runtime layer. Same id across transitions is the no-churn case and does\n * NOT throw; only a within-set type conflict does.\n */\nexport class SubIdCollisionError extends Error {\n override readonly name = \"SubIdCollisionError\";\n readonly _tag = \"SubIdCollisionError\" as const;\n constructor(id: string, declaredType: string, conflictingType: string) {\n super(\n `@demlik/tea: Sub.id collision: id=\"${id}\" declared as ` +\n `type=\"${declaredType}\" and type=\"${conflictingType}\"`,\n );\n }\n}\n\n/**\n * Test-only escape hatch — clears the module-level port-name registry so the\n * collision assert in `definePort` doesn't false-positive across vitest's\n * non-isolated runs. Production code MUST NOT call this.\n *\n * @internal test-only\n */\nexport function __resetPortRegistry(): void {\n definedPortNames.clear();\n}\n\n/**\n * Which otherwise-unattributable runtime path produced an error. Every fanout is\n * throw-isolated so one bad consumer never strands its siblings, and the\n * isolated throw routes to the `OnError` sink rather than a bare `console.error`.\n *\n * - `\"follow-up\"` — a follow-up Msg an interpret handler returned rejected when\n * re-dispatched (the original dispatcher already resolved, so no caller).\n * - `\"stop-save\"` — the final `store.save(state)` inside `stop()` threw\n * (`stop()` resolves regardless, so without the sink this was silent loss).\n * - `\"reduce\"` — the pure `update` (reducer) threw synchronously; the configured\n * `Supervision` strategy decides what happens next, but the throw is surfaced\n * here as data first.\n * - `\"listener\"` — a `runtime.subscribe(...)` listener threw during fanout.\n * - `\"observer\"` — a `runtime.observe(...)` observer threw during fanout.\n * - `\"event\"` — the `events` projector or an `on(type, ...)` handler threw.\n * - `\"boot\"` — an `onBoot` handler threw (boot fanout, or a late registration).\n * - `\"port-emit\"` — a `subscribePort` listener threw during a port emission.\n * - `\"sub-cleanup\"` — a subscription's cleanup threw (reconcile-removal or\n * `stop()` teardown).\n */\nexport type RuntimeErrorPhase =\n | \"follow-up\"\n | \"stop-save\"\n | \"reduce\"\n | \"listener\"\n | \"observer\"\n | \"event\"\n | \"boot\"\n | \"port-emit\"\n | \"sub-cleanup\";\n\n/** Context handed to an `OnError` sink alongside the error itself. */\nexport interface RuntimeErrorContext {\n readonly phase: RuntimeErrorPhase;\n}\n\n/**\n * Sink for runtime failures that have no caller to reject at. Configured via\n * `run(machine, { onError })`. Should be total — a throw inside the sink is\n * itself surfaced via the default sink, so it can never re-introduce a silent\n * failure.\n */\nexport type OnError = (error: unknown, context: RuntimeErrorContext) => void;\n\n// === Supervision: declared policy for a reducer throw ===\n//\n// A throw inside the pure `update` is a synchronous throw (the reentrancy brand\n// makes a reducer provably synchronous), catchable in the dispatch loop — the\n// seam Akka supervisor strategies / Erlang-OTP supervision trees occupy: \"let it\n// crash\" becomes CONFIG. Every strategy routes the failure to `onError` with\n// `phase: \"reduce\"` FIRST (invariant 6), then differs in what happens next:\n//\n// - `stop` — halt (SAFE DEFAULT). State is NOT advanced; the dispatch\n// promise rejects; every subsequent dispatch rejects. Never a\n// silent resume.\n// - `escalate`— surface + propagate: the dispatch promise rejects so the\n// failure bubbles to a parent supervisor. The runtime stays live.\n// - `restart` — re-init from a host-provided last-known-good state and keep\n// folding. The core owns no snapshot logic — the host supplies\n// `rehydrate()`, the core installs its result and continues.\n\n/** The three declared reducer-throw supervision strategies. */\nexport type SupervisionStrategy = \"stop\" | \"escalate\" | \"restart\";\n\n/**\n * Declared supervision policy for a reducer (`update`) throw, at\n * `run(machine, { supervision })`. The bare-string shorthands (`\"stop\"` /\n * `\"escalate\"`) are accepted for the two strategies that need no host data;\n * `restart` MUST be the object form because it carries the `rehydrate` callback,\n * which MUST return a valid `S` synchronously (the reducer is synchronous, so\n * recovery is too — no suspension across the single-writer slot).\n */\nexport type Supervision<S, M extends { type: string }> =\n | \"stop\"\n | \"escalate\"\n | { readonly strategy: \"stop\" }\n | { readonly strategy: \"escalate\" }\n | {\n readonly strategy: \"restart\";\n /**\n * Host-provided rehydration to last-known-good state. Invoked when the\n * reducer throws; its return value becomes the new state and the transition\n * continues from there. Receives the pre-throw `state`, the `msg` that\n * triggered the throw, and the thrown `error` so the host can route by\n * cause.\n */\n readonly rehydrate: (state: S, msg: M, error: unknown) => S;\n };\n\n/**\n * Raised by `idle()` when the quiescence wait hits its iteration cap without the\n * dispatch tail stabilizing — `idle()` REJECTS rather than silently resolving,\n * so a livelocking machine surfaces instead of masquerading as quiescent.\n * Mechanizes invariant 6 at the runtime layer, the role `PortNameCollisionError`\n * plays for invariant 7.\n */\nexport class QuiescenceTimeoutError extends Error {\n override readonly name = \"QuiescenceTimeoutError\";\n readonly _tag = \"QuiescenceTimeoutError\" as const;\n constructor(public readonly iterations: number) {\n super(\n `@demlik/tea: idle() did not reach quiescence after ${iterations} ` +\n `iterations — the dispatch tail kept advancing. The machine is ` +\n `likely livelocking (an interpret handler enqueues a follow-up Msg ` +\n `that enqueues another, without end). Bound the follow-up chain in ` +\n `the reducer, or stop the runtime.`,\n );\n }\n}\n\n/**\n * Define a typed port. `name` is metadata (devtools / debug logs); port identity\n * is by reference. Each definePort call must use a unique `name` — a second call\n * with the same name throws `PortNameCollisionError`. Use ports for \"data leaving\n * the runtime selectively\" (cursor announcements, DOM-mutation broadcasts,\n * telemetry) that should NOT be folded into State. Strengthens invariant 7.\n */\nexport function definePort<T>(name: string): Port<T> {\n // HMR skip — Vite / dev servers re-import the module on hot reload, which\n // would otherwise false-positive on every definePort across reloads. The\n // try/catch is load-bearing for service-worker bundles: Vite polyfills\n // `import.meta.url` via `document.baseURI`, which throws ReferenceError in\n // an MV3 service worker. A throw here would abort SW install (Chrome\n // surfaces it as \"registration failed status 15\"). Catching it = \"no HMR\n // detected\" = the collision check applies, which is the correct SW\n // behavior (SWs reload via chrome.runtime.reload, not module HMR).\n let isHmr = false;\n try {\n const meta = import.meta as { hot?: unknown };\n isHmr = meta?.hot !== undefined && meta?.hot !== null;\n } catch {\n isHmr = false;\n }\n if (!isHmr && definedPortNames.has(name)) {\n throw new PortNameCollisionError(name);\n }\n definedPortNames.add(name);\n return { __brand: \"port\", name } as Port<T>;\n}\n\n// === Store: pluggable persistence adapter ===\n//\n// `load()` returns `unknown` because storage genuinely doesn't know `S` —\n// chrome.storage returns whatever JSON lives at the key, DurableObjectStorage\n// returns whatever bytes were serialized. Casting raw storage to `S` at the\n// adapter boundary is the exact `as S` move forbidden by invariant 8\n// everywhere else in the substrate. `load()` returning `unknown` makes the\n// substrate stop pretending.\n//\n// `migrate(raw)` is the boundary parse. Returns `S` on a recognized shape —\n// the substrate passes it to `init` as `loaded`. Returns `null` on any\n// unrecognized shape — the substrate passes `null` to `init`, fresh-boot\n// path. Must NOT throw: if a future shape is unrecognizable, returning\n// `null` boots clean from a known-good path. Throwing here would\n// indistinguishably collapse \"storage corruption\" and \"schema migration not\n// yet written\" — both are runtime decisions, not panics.\n//\n// Strengthens invariant 8 (the boundary parses; the core trusts) — the\n// substrate now enforces the parse instead of relying on every adapter\n// remembering to.\nexport interface Store<S> {\n load(): Promise<unknown>;\n save(state: S): Promise<void>;\n migrate(raw: unknown): S | null;\n}\n\n// === Schema-derived migrate: single-source the durable State ===\n//\n// The boundary parse `migrate(raw)` is two jobs glued together:\n// 1. STRUCTURAL VALIDATION — \"is this the current shape?\" 100% derivable\n// from the State type, pure boilerplate, the part that drifts when a\n// field is added to a variant but the hand-written parser isn't updated.\n// 2. VERSION MIGRATION — \"upgrade an OLD shape to the current one\" (default a\n// missing field, drop a dead one, remap a removed enum). Genuine logic.\n// Encodes decisions about how past rows map forward. NOT derivable.\n//\n// `schemaMigrate` derives job 1 from a schema and isolates job 2 in a thin,\n// explicit `upcast` run BEFORE the parse. When the State type is itself\n// `Schema<S>`-inferred (`type S = SchemaOutput<typeof schema>`), the type and\n// the validator are the SAME declaration — you cannot add a field to the type\n// without it being in the schema, so the parse always enforces the current\n// shape. The `as S` an adapter would otherwise write on `safeParse().data` is\n// deleted: the schema's output IS `S`.\n//\n// The kernel stays library-agnostic — `Schema<S>` is the minimal Standard-\n// Schema-shaped surface (`safeParse`) that both zod 3 and zod 4 satisfy. No\n// validator is imported here; the consumer supplies one.\n//\n// Strengthens invariant 8 (the boundary parses; the core trusts) and invariant\n// 1 (state is a value — one declaration sources both type and parser).\nexport interface Schema<S> {\n safeParse(raw: unknown): { success: true; data: S } | { success: false };\n}\n\n/**\n * Build a `Store.migrate` from a schema (job 1) and an optional thin `upcast`\n * (job 2). `upcast` maps a recognized-but-OLD raw shape forward into the shape\n * the schema validates; it defaults to identity (no version migration yet).\n *\n * Never throws — a shape the schema rejects returns `null`, the substrate's\n * fresh-boot path, per the `Store.migrate` contract. An `upcast` that itself\n * throws on a corrupt blob is caught and collapses to `null` (same posture).\n */\nexport function schemaMigrate<S>(\n schema: Schema<S>,\n upcast: (raw: unknown) => unknown = (raw) => raw,\n): (raw: unknown) => S | null {\n return (raw: unknown): S | null => {\n let migrated: unknown;\n try {\n migrated = upcast(raw);\n } catch {\n return null;\n }\n const parsed = schema.safeParse(migrated);\n return parsed.success ? parsed.data : null;\n };\n}\n\n// === DispatchSettle: how far a dispatch awaits ===\n//\n// The default is the SAFE one, `\"quiescent\"` — `dispatch` resolves only once the\n// entire transitive follow-up chain has drained (the same drain `idle()`\n// performs). Were the default one transition, an `interpret` follow-up Msg would\n// enqueue a fresh transition fire-and-forget relative to the original\n// `dispatch`, resolving \"early\". The rare single-step case opts in with `\"once\"`\n// (or the `dispatchOnce` convenience).\nexport type DispatchSettle = \"quiescent\" | \"once\";\n\n// === RuntimeRef<M>: typed sibling-runtime handle ===\n//\n// Exposes only the inbox of a Runtime — `dispatch` / `dispatchOnce`. Use it as\n// the field type when one runtime holds a *sibling* (composition by reduction\n// across orthogonal lifecycles — invariant 5): the holder learns the Msg shape\n// it can send, nothing about the referenced runtime's State/Cmd/Sub/Ctx/\n// observers/Port fanout. `Runtime<S, M>` extends `RuntimeRef<M>` structurally.\nexport interface RuntimeRef<M extends { type: string }> {\n /**\n * Put a Msg in the runtime's inbox and resolve once processed. Runs to\n * QUIESCENCE by default: settles only after the dispatched Msg AND every\n * transitive interpret follow-up has drained. Pass `{ settle: \"once\" }` (or\n * call `dispatchOnce`) for the single-step case.\n *\n * Rejection ordering: the ONE dispatched transition's own failure surfaces\n * first, here. If it succeeds but the follow-up chain never stabilizes, the\n * quiescent drain rejects with `QuiescenceTimeoutError`. Follow-up Msg\n * rejections themselves route to the `onError` sink, never here.\n */\n dispatch(msg: M, opts?: { readonly settle?: DispatchSettle }): Promise<void>;\n /**\n * Dispatch `msg` and resolve after exactly ONE transition's effects settle,\n * WITHOUT draining the follow-up chain — equivalent to\n * `dispatch(msg, { settle: \"once\" })`. Prefer plain `dispatch` unless you will\n * `await runtime.idle()` yourself; the un-awaited follow-up chain is the\n * footgun the quiescent default removed.\n */\n dispatchOnce(msg: M): Promise<void>;\n}\n\n// === BootingRuntime: handle returned SYNCHRONOUSLY from run() ===\n//\n// `run()` returns a `BootingRuntime<S, M>` the instant it is called, while boot\n// is still in flight. It exposes exactly the surface TOTAL before boot: queue a\n// dispatch, subscribe, observe, wire a Port, stop. What you may NOT do is read\n// State (`getState`) or wait for quiescence (`idle`) — those need the initial\n// State to exist, and are the difference between a BootingRuntime and a\n// `Runtime`, enforced at the type level so \"read State before boot\" is a COMPILE\n// error, not a runtime throw.\n//\n// `subscribe` is the React-shaped change notifier (zero-arg, paired with\n// `getState()`). `observe` is the devtools-shaped trace hook — `(msg, state)`\n// for every APPLIED transition; boot is delivered via `onBoot` instead, so\n// `observe`'s `msg` is total (never `null`). `on(type, handler)` is the SEMANTIC\n// event channel: only the public, `type`-narrowed events a machine projects,\n// never its PRIVATE Msg vocabulary. `E` defaults to `never` (no projector → `on`\n// uncallable).\nexport interface BootingRuntime<\n S,\n M extends { type: string },\n E extends { type: string } = never,\n> extends RuntimeRef<M> {\n dispatch(msg: M, opts?: { readonly settle?: DispatchSettle }): Promise<void>;\n dispatchOnce(msg: M): Promise<void>;\n subscribe(listener: () => void): () => void;\n observe(observer: (msg: M, state: S) => void): () => void;\n /**\n * Subscribe to the INITIAL State — the boot transition. Fires exactly once:\n * immediately if boot already completed (so a late subscriber never misses\n * it), otherwise on the boot fanout. Returns a cleanup (a no-op once fired).\n */\n onBoot(handler: (state: S) => void): () => void;\n /**\n * Subscribe to a SEMANTIC event of `type`. The handler receives exactly the\n * `E` member whose `type` matches `K`, so a consumer never touches another\n * event's shape and never references the machine's PRIVATE Msg names. Multiple\n * handlers per type; fanout is synchronous and throw-isolated. Fires only when\n * the machine's `events` projector (wired on `run`) emits that type.\n */\n on<K extends E[\"type\"]>(\n type: K,\n handler: (event: Extract<E, { type: K }>) => void,\n ): () => void;\n /**\n * Subscribe to a typed Port. Multiple listeners per port; fanout is synchronous\n * and isolated. Ports are for \"data leaving the runtime selectively\" (see\n * `definePort`) — distinct from `observe` (every transition) and State.\n */\n subscribePort<T>(port: Port<T>, listener: (value: T) => void): () => void;\n /**\n * Emit a value on a Port from OUTSIDE an interpret handler — same synchronous\n * fanout as `ctx.emit`. The canonical use is `observe`-driven emission (one\n * runtime publishing a state-derived signal another subscribes to via\n * `subscribePort`) without spawning a \"tell the outside world\" Cmd per\n * transition.\n */\n emitPort<T>(port: Port<T>, value: T): void;\n /**\n * Resolves to the booted `Runtime<S, M>` after boot completes (or rejects with\n * the boot error). This is the ONLY way to obtain a `Runtime` — and a\n * `Runtime` is the only handle whose `getState()` is total. Awaiting `ready` is\n * the single gate between \"boot in flight\" and \"State exists\":\n *\n * ```ts\n * const runtime = await run(machine, opts).ready;\n * runtime.getState(); // total — never throws-before-boot\n * ```\n *\n * Idempotent — the same settled promise, resolving to the same `Runtime`, comes\n * back on every read. Expresses canon §2.3 (boot is a named, awaitable moment).\n */\n ready: Promise<Runtime<S, M, E>>;\n stop(): Promise<void>;\n}\n\n// === Runtime: the BOOTED handle `ready` resolves to ===\n//\n// A `BootingRuntime<S, M>` whose boot has completed. It adds the two members\n// only meaningful once the initial State exists — `getState()` (total) and\n// `idle()` (quiescence) — and narrows `ready` to resolve to itself. You never\n// construct one directly; you obtain it via `await bootingRuntime.ready`, which\n// makes \"read State before boot\" unrepresentable rather than merely discouraged.\nexport interface Runtime<\n S,\n M extends { type: string },\n E extends { type: string } = never,\n> extends BootingRuntime<S, M, E> {\n /**\n * The current State. TOTAL — never throws. Obtaining a `Runtime` requires\n * awaiting `ready`, which only resolves AFTER boot has run `init` and set the\n * initial State.\n */\n getState(): S;\n /** Resolves to this same `Runtime` once boot completes. Idempotent. */\n ready: Promise<Runtime<S, M, E>>;\n /**\n * Resolves once the runtime has reached QUIESCENCE — every dispatched Msg AND\n * every transitive interpret follow-up has been processed, with no further step\n * pending on the tail. Since plain `dispatch` already runs to quiescence, this\n * is mainly for follow-ups left by a `dispatchOnce` single step, or a chain\n * kicked off by a Sub / boot `init` cmds with no `dispatch` to await.\n *\n * Idempotent and re-entrant-safe. Tail rejections are NOT surfaced here (a\n * failing dispatch surfaces on its OWN promise; follow-up rejections route to\n * `onError`). The one rejection `idle()` produces is `QuiescenceTimeoutError`\n * on hitting the iteration cap — so a livelock stays distinguishable from a\n * genuine quiesce (invariant 6). A poll is still correct when waiting on an\n * EXTERNAL event the runtime cannot enqueue itself.\n */\n idle(): Promise<void>;\n /**\n * The terminal State of the run, or `undefined` while in flight — \"terminal\"\n * per the `terminal` predicate passed to `run()` (no predicate → never\n * terminal → always `undefined`). The first-class result read: the run's\n * product off the State the machine already owns, NOT scraped off the `observe`\n * firehose by matching an internal Msg name. Total — never throws.\n */\n result(): S | undefined;\n /**\n * Resolves with the terminal State the first time the run reaches one (per the\n * `terminal` predicate). If ALREADY terminal, resolves immediately; otherwise\n * on the transition that first makes `terminal` hold. The awaitable companion\n * to `result()`. With no predicate this never resolves. Idempotent and\n * multi-caller safe.\n */\n done(): Promise<S>;\n}\n\n// === defineMachine: identity-typed pass-through ===\n//\n// Overloads enforce exactly one `update` shape per call so consumers see a\n// concrete type, not the internal union. Runtime is identity — `run` branches on\n// the structural shape of `update` (Reducer = record of functions; Transitions =\n// record of records) when dispatching, so overload resolution picks the right\n// branch by value shape. Strengthens invariant 2 (record forms have no\n// fall-through default) and invariant 7 (the variant set is load-bearing).\n\n// Transitions-form overload — 2D table keyed by State.type then Msg.type.\n// Declared FIRST (most specific). The S constraint is a conditional (`S extends\n// { type: string } ? Transitions<...> : never`) not a generic-parameter\n// constraint, so `S` stays unconstrained at the signature and the public\n// `Parameters<typeof defineMachine<NonDiscriminatedS, ...>>` pattern skips this\n// overload (update becomes `never`) instead of failing.\nexport function defineMachine<\n S,\n M extends { type: string },\n C extends Cmd,\n U extends Sub,\n Ctx,\n>(\n m: Omit<Machine<S, M, C, U, Ctx>, \"update\"> & {\n // `[S]` tuple-wrap disables distributive conditional behavior — see\n // the comment on `Machine.update` for why distribution is wrong here.\n update: [S] extends [{ type: string }] ? Transitions<S, M, C> : never;\n },\n): Machine<S, M, C, U, Ctx>;\n// Reducer-form overload — flat record keyed by Msg.type.\nexport function defineMachine<\n S,\n M extends { type: string },\n C extends Cmd,\n U extends Sub,\n Ctx,\n>(\n m: Omit<Machine<S, M, C, U, Ctx>, \"update\"> & {\n update: Reducer<S, M, C>;\n },\n): Machine<S, M, C, U, Ctx>;\n// Implementation signature — accepts both via the union on `Machine.update`.\nexport function defineMachine<\n S,\n M extends { type: string },\n C extends Cmd,\n U extends Sub,\n Ctx,\n>(m: Machine<S, M, C, U, Ctx>): Machine<S, M, C, U, Ctx> {\n // Tag the update form ONCE, here at the typed construction boundary, so no\n // downstream reader re-derives it structurally. Non-enumerable so it does not\n // serialize, show up in `Object.keys`, or collide with a Msg.type key.\n // Idempotent under re-wrap (`defineMachine(defineMachine(m))`).\n if (m.__form === undefined) {\n Object.defineProperty(m, \"__form\", {\n value: detectUpdateForm(m.update as object),\n enumerable: false,\n writable: false,\n configurable: true,\n });\n }\n return m;\n}\n\n// === asReducer: the validated minting path for a reducer ===\n//\n// Turns a raw record of handlers into a branded `Reducer<S, M, C>`. The\n// parameter type's every cell returns the non-thenable `SyncReturn<S, C>`, so\n// the reentrancy guard fires HERE, at construction: an `async` cell returns\n// `Promise<...>`, not assignable to `SyncReturn`, and `tsc` rejects it. PURE —\n// identity at runtime (the brand is phantom). `defineMachine` brands its\n// `update` internally the same way, so this exists for the standalone `const\n// update = asReducer<...>({ ... })` form.\nexport function asReducer<S, M extends { type: string }, C extends Cmd>(\n reducer: Reducer<S, M, C>,\n): Branded<Reducer<S, M, C>> {\n return reducer as Branded<Reducer<S, M, C>>;\n}\n\n// === CtxArg<Ctx>: the `ctx` field of `run`'s opts, conditionally optional ===\n//\n// A PURE machine reads nothing from `ctx` (its `Ctx` is `NoCtx` /\n// `Record<string, never>` / `unknown`); forcing `ctx: {}` is ceremony for a\n// value the type already pins as empty. So `ctx` is CONDITIONALLY optional: when\n// `{}` satisfies `Ctx` it may be OMITTED (defaulted to `{}`), so a pure reducer\n// runs as `run(machine)`; when `Ctx` carries a field a handler reads, `ctx` stays\n// REQUIRED. `[Record<never, never>] extends [Ctx]` reads as \"is `{}` assignable\n// to `Ctx`\" — true for the context-free shapes, false for `{ db: … }`; the\n// tuple-wrap disables distributive conditional behavior.\nexport type CtxArg<Ctx> = [Record<never, never>] extends [Ctx]\n ? { ctx?: Ctx }\n : { ctx: Ctx };\n\n// === replay: pure unit-test helper ===\n//\n// Composes `init(loaded ?? null, ctx)` then `update(state, msg)` for each msg.\n// Returns the final state plus the cmds that *would* have been emitted and the\n// subs that *would* have been desired at the final state. It does NOT call any\n// `interpret[type]` handler, does NOT touch `Store`, and does NOT start any\n// subscription. `subscriptions` IS called to derive `subs` — that lets tests\n// assert what would be wired up without actually wiring it.\n//\n// Dep-keyed Subs are reported in `depSubs`: for each `machine.subs` entry\n// active at the FINAL state (its `deps` non-null), the entry's `index` and the\n// derived `id` (`structuralHash(deps)`) — so a test can assert \"the deadline +\n// checkpoint + bridge dep-subs are armed in `running`\" without wiring any\n// source. Same intent as `subs` for the manual path: assert the desired set\n// purely. `source` is NEVER called (replay starts no subscription).\nexport function replay<\n S,\n M extends { type: string },\n C extends Cmd,\n U extends Sub,\n Ctx,\n>(\n machine: Machine<S, M, C, U, Ctx>,\n opts: { msgs: readonly M[]; ctx: Ctx; loaded?: S | null },\n): {\n state: S;\n cmds: C[];\n subs: U[];\n depSubs: { index: number; id: string }[];\n} {\n // Coerce undefined → null so `replay` with `loaded: undefined` calls\n // `init(null, ctx)`.\n const loaded = opts.loaded ?? null;\n const [initialState, initCmds] = machine.init(loaded, opts.ctx);\n\n if (loaded !== null && initCmds.length > 0) {\n throw new Error(\n \"TEA contract violation: machine.init must return [state, []] (no Cmds) \" +\n \"when `loaded` is non-null. Init's rehydrate branch is a pure state \" +\n \"passthrough — the migration/parse boundary, not the boot-effect hook.\\n\\n\" +\n \"Routes for boot effects:\\n\" +\n \" - Stateless infrastructure (e.g. chrome.alarms ensure) → host module \" +\n \"top level, outside TEA.\\n\" +\n \" - State-conditional resume (e.g. re-attach a session) → a `boot` Msg \" +\n \"dispatched once from the host after `run(...)` returns, handled in update.\\n\\n\" +\n \"See .patterns/tea/tea-invariants.md (Invariant 2).\",\n );\n }\n\n // `replay` and `foldMsgs` share ONE internal fold (`foldUpdates`), keyed on\n // `formOf` — the same reader `run` uses — so all three agree on the\n // reducer-vs-transitions form by construction.\n const { state, cmds: foldedCmds } = foldUpdates<S, M, C>(\n machine,\n initialState,\n opts.msgs,\n );\n const cmds: C[] = [...initCmds, ...foldedCmds];\n\n const subs: U[] = machine.subscriptions\n ? [...machine.subscriptions(state)]\n : [];\n\n // The dep-keyed desired set at the final state — `deps` only, never `source`.\n const depSubs: { index: number; id: string }[] = [];\n if (machine.subs) {\n for (const [index, entry] of machine.subs.entries()) {\n const deps = entry.deps(state);\n if (deps !== null) depSubs.push({ index, id: structuralHash(deps) });\n }\n }\n\n return { state, cmds, subs, depSubs };\n}\n\n// === wrapDetached: the typed Cmd→Msg edge for a detached interpret handler ===\n//\n// Adapts an `InterpretDetached<C, Allowed, Ctx>` — a handler that detaches its\n// long-running work (`ctx.waitUntil(...)`) and fires its TERMINAL Msg through\n// the kernel-injected `dispatch` — into a plain `Interpret` cell that drops into\n// the `interpret` dictionary unchanged. The point is the NARROWING: `Allowed`\n// is the subset of the Msg union this Cmd is permitted to produce, and the\n// `dispatch` the handler sees is typed `(msg: Allowed) => void`. A wrong /\n// typo'd terminal Msg from the detached site then fails to compile (rung 2),\n// where today it reaches for a host-wired `ctx.dispatch` typed to the full\n// union and compiles silently (rung 5 — the allowed set on a comment).\n//\n// `Allowed extends M` is the constraint that makes this SOUND at the kernel:\n// the kernel injects the WIDE `dispatch: (msg: M) => void`, the handler only\n// ever calls it with `Allowed` values (its own narrowed signature enforces\n// that), and every `Allowed` is a valid `M`. So passing the wide dispatch into\n// the narrow-expecting handler is type-correct in one direction (the values the\n// handler produces are all `M`) — the narrowing constrains the AUTHOR, not the\n// kernel. No `as` on data: the only widen is the function reference itself\n// (`dispatch` accepting `M` is usable where one accepting `Allowed` is wanted\n// because `Allowed extends M` — contravariant parameter, sound here because the\n// handler never sees a non-`Allowed` value), expressed by the explicit\n// `Allowed`/`M` generic relation, not a cast.\n//\n// Opt-in / additive: a leaf handler that resolves on its own keeps returning\n// `Promise<M | void>` and never touches `wrapDetached`. Only the detached sites\n// adopt it. The wrapped result is structurally a plain cell, so the `interpret`\n// map type is unchanged.\n//\n// Strengthens invariant 3 (effects are data — the detached effect's terminal\n// result feeds back as a Msg, now a TYPED edge) and invariant 7 (identity is\n// explicit — a Cmd's allowed result-Msg set is load-bearing at the type level).\nexport function wrapDetached<\n C extends Cmd,\n M extends { type: string },\n Allowed extends M,\n Ctx,\n>(\n handler: InterpretDetached<C, Allowed, Ctx>,\n): (\n cmd: C,\n ctx: Ctx & PortEmitter,\n dispatch?: (msg: M) => void,\n) => Promise<void> {\n // The injected `dispatch` accepts the full `M`. The handler's signature only\n // lets it call `dispatch` with `Allowed` (⊆ M) values, so handing it the\n // wide fn is sound: `(msg: M) => void` is callable wherever\n // `(msg: Allowed) => void` is wanted, and every value the handler passes is a\n // valid `M`. No data cast — the relation is carried by `Allowed extends M`.\n //\n // `dispatch` is OPTIONAL on the signature to match the `Interpret` cell type\n // (additive — see `Interpret`). The kernel ALWAYS passes it from\n // `runInterpret`; a detached handler invoked WITHOUT a dispatch (only a\n // mis-wired direct caller could do this) has no way to fire its terminal Msg,\n // so we fail loudly (rung 4) rather than silently dropping the seam's result.\n return (cmd, ctx, dispatch) => {\n if (dispatch === undefined) {\n throw new Error(\n \"@demlik/tea: a wrapDetached handler was invoked without the injected dispatch. \" +\n \"The kernel always supplies it; call the handler through the runtime, not directly.\",\n );\n }\n return handler(cmd, ctx, dispatch);\n };\n}\n\n// === tryInterpret: Railway sugar over `Result.tryPromise` ===\n//\n// Wraps a fallible `(cmd, ctx) => Promise<Ok>` into a handler for\n// `interpret[type]`: on success resolves `onOk(value, cmd)`, on rejection\n// `onErr(error, cmd)`. It NEVER rejects (assuming `onOk`/`onErr` are total).\n//\n// We use the `{try, catch: (e) => e}` form (not the one-arg thunk) so the\n// original error passes through untouched — the one-arg form wraps errors in\n// `UnhandledException`, which would break `instanceof` checks inside `onErr`.\nexport function tryInterpret<C extends Cmd, Ok, M, Ctx>(\n work: (cmd: C, ctx: Ctx) => Promise<Ok>,\n onOk: (value: Ok, cmd: C) => M,\n onErr: (error: unknown, cmd: C) => M,\n): (cmd: C, ctx: Ctx) => Promise<M> {\n return async (cmd, ctx) => {\n const result = await Result.tryPromise({\n try: () => work(cmd, ctx),\n catch: (error: unknown): unknown => error,\n });\n return result.match({\n ok: (value) => onOk(value, cmd),\n err: (error) => onErr(error, cmd),\n });\n };\n}\n","/**\n * @demlik/tea runtime — `run`: boot + the serial dispatch loop. The pure helpers\n * that compose against a machine without running it (`replay`, `tryInterpret`)\n * live in `./runtime-types`.\n */\n\nimport type {\n Dispose,\n Interpret,\n Machine,\n Port,\n PortEmitter,\n Sub,\n} from \"./pure/core\";\nimport { applyCellChecked, type Cmd, structuralHash } from \"./pure/core\";\nimport type {\n BootingRuntime,\n CtxArg,\n DispatchSettle,\n OnError,\n Runtime,\n RuntimeErrorContext,\n RuntimeErrorPhase,\n Store,\n Supervision,\n} from \"./runtime-types\";\nimport { QuiescenceTimeoutError, SubIdCollisionError } from \"./runtime-types\";\n\n// Default `onError` sink: re-throw on a fresh macrotask so the failure reaches\n// the host's global error handler instead of vanishing — surface, not swallow\n// (invariant 6).\nfunction defaultOnError(error: unknown, _context: RuntimeErrorContext): void {\n setTimeout(() => {\n throw error;\n }, 0);\n}\n\n// Normalize `Supervision` (bare string or object) so the dispatch loop branches\n// on `.strategy` once. Default `stop`. Derived from `Supervision` — the object\n// arms are exactly its non-string members, so the restart `rehydrate` payload\n// has a single source of truth.\ntype NormalizedSupervision<S, M extends { type: string }> = Extract<\n Supervision<S, M>,\n object\n>;\n\nfunction normalizeSupervision<S, M extends { type: string }>(\n supervision: Supervision<S, M> | undefined,\n): NormalizedSupervision<S, M> {\n if (supervision === undefined) return { strategy: \"stop\" };\n if (typeof supervision === \"string\") return { strategy: supervision };\n return supervision;\n}\n\n// === run ===\n//\n// Returns a `BootingRuntime<S, M>` synchronously; boot runs as the FIRST entry\n// on the serial dispatch tail, awaited implicitly by every public method.\n//\n// Save-then-effects ordering is structural: every transition mutates state,\n// awaits `store.save(newState)`, then reconciles subscriptions, then runs\n// `interpret` for emitted cmds, then fires external listeners. A throw in any\n// effect phase leaves the persisted state ahead of the host's belief about\n// what executed — the Railway discipline (`tryInterpret` in handlers) makes\n// that safe in practice.\nexport function run<\n S,\n M extends { type: string },\n C extends Cmd,\n U extends Sub,\n Ctx,\n E extends { type: string } = never,\n>(\n machine: Machine<S, M, C, U, Ctx>,\n opts: CtxArg<Ctx> & {\n store?: Store<S>;\n onError?: OnError;\n /**\n * The SEMANTIC event projector. Maps one APPLIED transition `(msg, state)`\n * to zero-or-more public events of `E`; `[]` skips the transition. Maps the\n * machine's PRIVATE Msg vocabulary to NAMED events — the private names never\n * reach `on`'s `E` surface. Omit → `E = never` and `on` is uncallable. PURE.\n */\n events?: (msg: M, state: S) => readonly E[];\n /**\n * Declared policy for a reducer (`update`) throw. Always surfaced via\n * `onError` (`phase: \"reduce\"`); the strategy decides what the runtime does\n * next. Defaults to `\"stop\"`. See `Supervision`.\n */\n supervision?: Supervision<S, M>;\n /**\n * The run-terminality predicate — makes the run's outcome first-class. Fed to\n * `Runtime.result()` and `Runtime.done()`. PURE. Omit → never terminal.\n */\n terminal?: (state: S) => boolean;\n /**\n * Iteration cap for `idle()`'s quiescence wait. Defaults to 100_000. Test\n * seam only. Production code must not set it.\n *\n * @internal test-only\n */\n __idleCap?: number;\n },\n): BootingRuntime<S, M, E> {\n const { store } = opts;\n // `ctx` is conditionally optional (see `CtxArg`); default the nullish case to\n // `{}` so the augmented-ctx spread and `init(loaded, ctx)` get a value.\n const ctx = (opts.ctx ?? {}) as Ctx;\n const idleCap = opts.__idleCap ?? 100_000;\n // No projector → `E = never` and `on` is uncallable.\n const projectEvents: (msg: M, state: S) => readonly E[] =\n opts.events ?? (() => []);\n // No predicate → never terminal (`result()` always `undefined`).\n const isTerminal: (state: S) => boolean = opts.terminal ?? (() => false);\n // Absent sink → `defaultOnError` (invariant 6).\n const onError: OnError = opts.onError ?? defaultOnError;\n // A throwing sink routes THAT throw through `defaultOnError` so it can't\n // re-create a silent failure.\n const reportError = (error: unknown, context: RuntimeErrorContext): void => {\n try {\n onError(error, context);\n } catch (sinkError) {\n defaultOnError(sinkError, context);\n }\n };\n\n // Throw-isolated fanout: run `fn` for every item, routing any throw to the\n // sink under `phase` so one bad consumer never strands its siblings\n // (invariant 6). The single home for that isolation discipline — every\n // synchronous listener/observer/handler fanout goes through here.\n function fanout<T>(\n items: Iterable<T>,\n phase: RuntimeErrorPhase,\n fn: (item: T) => void,\n ): void {\n for (const item of items) {\n try {\n fn(item);\n } catch (err) {\n reportError(err, { phase });\n }\n }\n }\n const supervision = normalizeSupervision<S, M>(opts.supervision);\n\n // `state` is late-initialized inside the boot step (the head of the tail).\n let state: S | undefined;\n let bootError: unknown = null;\n let stopped = false;\n\n const subRegistry = new Map<string, () => void>();\n // Dep-keyed Sub registry. One slot per `machine.subs[i]`, keyed by the entry's\n // array index (its stable identity across reconciles — a dep-keyed Sub has no\n // author-supplied id). `runningId` is the `structuralHash(deps)` of the live\n // source; an absent slot means the entry is currently inactive (its `deps`\n // returned null). The same dispose-on-change / dispose-on-null machinery the\n // manual Sub path uses, with the id DERIVED instead of author-supplied.\n const depSubRegistry = new Map<\n number,\n { runningId: string; dispose: Dispose }\n >();\n const listeners = new Set<() => void>();\n // Observers get (msg, state) for every APPLIED transition (boot goes via `onBoot`).\n const observers = new Set<(msg: M, state: S) => void>();\n // `booted` lets an `onBoot` handler registered AFTER boot fire immediately.\n const bootHandlers = new Set<(state: S) => void>();\n let booted = false;\n // Keyed by event `type`, stored monomorphically (per-type safety at `on`).\n const eventHandlers = new Map<string, Set<(event: E) => void>>();\n // `done()` waiters — the first terminal transition drains them.\n const doneWaiters = new Set<(state: S) => void>();\n\n // Keyed by Port reference (identity is by-reference per Elm); per-port type\n // safety is enforced at the call sites.\n const portRegistry = new Map<Port<unknown>, Set<(value: unknown) => void>>();\n\n // `emit` injected onto ctx: synchronous fanout, no-op on no subscribers,\n // listener throws isolated + routed to the sink (invariant 6).\n function portEmit<T>(port: Port<T>, value: T): void {\n const subscribers = portRegistry.get(port as Port<unknown>);\n if (!subscribers || subscribers.size === 0) return;\n fanout(subscribers, \"port-emit\", (listener) => listener(value));\n }\n\n // Spread into a fresh object so handlers get a Ctx & PortEmitter without\n // mutating the caller's ctx (which may be shared across runtimes / tests).\n const augmentedCtx: Ctx & PortEmitter = { ...ctx, emit: portEmit };\n\n // Every step chains onto `tail` — the single concurrency gate.\n let tail: Promise<void> = Promise.resolve();\n\n // Tear down each named sub: run its cleanup (throws isolated + routed to the\n // sink under `\"sub-cleanup\"`), then drop it from the registry regardless of a\n // cleanup throw. The single home for the cleanup-and-delete discipline shared\n // by `reconcileSubs`'s removal pass and `stop()`.\n function stopSubs(ids: Iterable<string>): void {\n for (const id of ids) {\n const cleanup = subRegistry.get(id);\n if (cleanup === undefined) continue;\n try {\n cleanup();\n } catch (err) {\n reportError(err, { phase: \"sub-cleanup\" });\n }\n subRegistry.delete(id);\n }\n }\n\n // Dispose each named dep-keyed slot: run its `Dispose` (throws isolated +\n // routed to the sink under `\"sub-cleanup\"`, exactly as `stopSubs` does for the\n // manual path), then drop the slot regardless of a throw. The single home for\n // the dispose-and-delete discipline shared by `reconcileDepSubs`'s teardown /\n // re-arm passes and `stop()`.\n function disposeDepSubs(indices: Iterable<number>): void {\n for (const index of indices) {\n const running = depSubRegistry.get(index);\n if (running === undefined) continue;\n try {\n running.dispose();\n } catch (err) {\n reportError(err, { phase: \"sub-cleanup\" });\n }\n depSubRegistry.delete(index);\n }\n }\n\n /**\n * Reconcile the dep-keyed Subs (`machine.subs`) against `state`. Runs as the\n * first pass of `reconcileSubs`, sharing the dispose-on-change /\n * dispose-on-null machinery with the manual Sub path. For each entry:\n *\n * - `deps(state)` is null → the Sub is inactive in this state; dispose it\n * if it was running.\n * - `deps(state)` is non-null → `id = structuralHash(deps)`; if no source\n * is running for this entry, or the running id differs (re-arm), dispose\n * the old source and run `source(state, dispatch, ctx)` to open a fresh\n * one (the entry re-derives its own typed slice from `state`).\n * - Unchanged id → leave the source running (the no-churn case).\n *\n * Start throws are collected and returned rather than thrown here (same\n * contract as the manual path) so one bad source doesn't strand the others.\n * A machine that declares no `subs` returns immediately — the pass is inert.\n */\n function reconcileDepSubs(): unknown {\n let firstError: unknown = null;\n const subs = machine.subs;\n if (!subs) return firstError;\n for (const [i, entry] of subs.entries()) {\n const deps = entry.deps(state as S);\n\n if (deps === null) {\n // Inactive in this state — tear down if running.\n disposeDepSubs([i]);\n continue;\n }\n\n const id = structuralHash(deps);\n const running = depSubRegistry.get(i);\n if (running !== undefined && running.runningId === id) {\n // No-churn case: same deps → leave the source running.\n continue;\n }\n // Re-arm (id changed) or first arm — dispose the stale source first.\n disposeDepSubs([i]);\n try {\n const dispose = entry.source(state as S, enqueueDispatch, ctx);\n depSubRegistry.set(i, { runningId: id, dispose });\n } catch (err) {\n if (firstError === null) firstError = err;\n // Do NOT register; continue so other dep-keyed sources still arm.\n }\n }\n return firstError;\n }\n\n /**\n * Reconcile subscriptions against `state`, after every save. Same id old+new →\n * leave running; removed id → cleanup (throws isolated, routed to the sink);\n * new id → start (throw remembered and re-thrown after the loop so all other\n * new subs still register).\n */\n function reconcileSubs(): void {\n // Dep-keyed pass FIRST, then the manual aggregate — ONE reconcile pass over\n // both paths. Its start error is remembered (it happened first) and thrown\n // after the manual pass so a bad dep-keyed source never strands the manual\n // subs, and vice versa.\n const depError = reconcileDepSubs();\n if (!machine.subscriptions) {\n if (depError !== null) throw depError;\n return;\n }\n const desired = machine.subscriptions(state as S);\n const desiredIds = new Set<string>();\n\n // Collision assert: within one desired set, two subs sharing an id but\n // declaring different types is a silent bug class. (Same id across\n // transitions is the no-churn case and MUST NOT throw.)\n const desiredTypeById = new Map<string, string>();\n for (const sub of desired) {\n const existing = desiredTypeById.get(sub.id);\n if (existing !== undefined && existing !== sub.type) {\n throw new SubIdCollisionError(sub.id, existing, sub.type);\n }\n desiredTypeById.set(sub.id, sub.type);\n }\n\n // Removals first — anything in the registry not in `desired` should stop.\n for (const sub of desired) desiredIds.add(sub.id);\n stopSubs([...subRegistry.keys()].filter((id) => !desiredIds.has(id)));\n\n // Additions — anything in `desired` not in the registry should start.\n let firstStartError: unknown = depError;\n for (const sub of desired) {\n if (subRegistry.has(sub.id)) continue;\n const handler = machine.subscribe?.[sub.type as U[\"type\"]];\n if (!handler) {\n // No handler for this sub type — programmer error; skip.\n continue;\n }\n try {\n const cleanup = handler(\n sub as Extract<U, { type: U[\"type\"] }>,\n ctx,\n enqueueDispatch,\n );\n subRegistry.set(sub.id, cleanup);\n } catch (err) {\n if (firstStartError === null) firstStartError = err;\n // Do NOT register; continue to next sub so other starts still run.\n }\n }\n if (firstStartError !== null) throw firstStartError;\n }\n\n // `interpret` is optional when `C extends Cmd<never>`; default a missing map to\n // `{}` — the per-cmd `if (!handler) continue` preserves invariant-6 forward\n // progress for a miswired consumer.\n const interpretMap: Interpret<M, C, Ctx> =\n (machine as { interpret?: Interpret<M, C, Ctx> }).interpret ??\n ({} as Interpret<M, C, Ctx>);\n\n // The injected dispatch for DETACHED handlers. Same serial-tail enqueue every\n // other dispatch uses (`enqueueDispatch` chains on `tail`), wrapped to a sync\n // `(msg) => void` so a detached handler's `ctx.waitUntil(...)` tail can fire\n // its terminal Msg without awaiting the runtime. The rejection has no caller\n // (the original dispatcher already resolved), so it routes to the sink under\n // `\"follow-up\"` — the same phase the returned-follow-up path uses. A handler\n // authored via `wrapDetached` receives a NARROWED view of this fn (only its\n // declared result-Msg set); a plain leaf handler ignores it entirely.\n const interpretDispatch = (msg: M): void => {\n enqueueDispatch(msg).catch((error: unknown) => {\n reportError(error, { phase: \"follow-up\" });\n });\n };\n\n /**\n * Run `interpret` for each emitted cmd. A returned follow-up Msg is enqueued\n * onto the tail (NOT dispatched re-entrantly). The first error stops further\n * handlers in this transition.\n */\n async function runInterpret(cmds: readonly C[]): Promise<void> {\n for (const cmd of cmds) {\n const handler = interpretMap[cmd.type as C[\"type\"]];\n if (!handler) continue;\n const follow = await handler(\n cmd as Extract<C, { type: C[\"type\"] }>,\n augmentedCtx,\n interpretDispatch,\n );\n if (follow !== undefined && follow !== null) {\n // The follow-up's rejection has no caller (the original dispatcher\n // resolved), so route it to the sink (invariant 6); name a failure Msg\n // via `tryInterpret` to fold it back into state.\n enqueueDispatch(follow as M).catch((error: unknown) => {\n reportError(error, { phase: \"follow-up\" });\n });\n }\n }\n }\n\n // Throws isolated so one bad listener does not strand the others.\n function fireListeners(): void {\n fanout(listeners, \"listener\", (listener) => listener());\n }\n\n // After `fireListeners` so observers see what subscribers see. APPLIED\n // transitions only — `msg` is total (boot routes to `fireBoot`).\n function fireObservers(msg: M): void {\n if (observers.size === 0 || state === undefined) return;\n const snapshot = state;\n fanout(observers, \"observer\", (observer) => observer(msg, snapshot));\n }\n\n // Project the transition to semantic events and fan each to its `on(...)`\n // handlers; a throw in the projector OR a handler is isolated.\n function fireEvents(msg: M): void {\n if (eventHandlers.size === 0 || state === undefined) return;\n let events: readonly E[];\n try {\n events = projectEvents(msg, state);\n } catch (err) {\n reportError(err, { phase: \"event\" });\n return;\n }\n for (const event of events) {\n const bucket = eventHandlers.get(event.type);\n if (bucket === undefined) continue;\n fanout(bucket, \"event\", (handler) => handler(event));\n }\n }\n\n // Fire every `onBoot` handler with the initial State ONCE and flip `booted`.\n function fireBoot(): void {\n booted = true;\n if (bootHandlers.size === 0 || state === undefined) return;\n const snapshot = state;\n fanout(bootHandlers, \"boot\", (handler) => handler(snapshot));\n }\n\n // Resolve every parked `done()` waiter iff the just-folded State is terminal —\n // so `done()` settles on the same transition `result()` first returns it.\n function settleDoneWaiters(): void {\n if (doneWaiters.size === 0 || state === undefined) return;\n if (!isTerminal(state)) return;\n const snapshot = state;\n const parked = [...doneWaiters];\n doneWaiters.clear();\n for (const resolve of parked) resolve(snapshot);\n }\n\n // The post-transition commit tail: install state, then save → reconcile subs →\n // interpret → fire fanout → settle done-waiters. Save-before-effects is the\n // hard ordering; tests pin it. The normal transition and the `restart`\n // supervision branch both end here.\n async function commit(next: S, msg: M, cmds: readonly C[]): Promise<void> {\n state = next;\n if (store) await store.save(next);\n reconcileSubs();\n await runInterpret(cmds);\n fireListeners();\n fireObservers(msg);\n fireEvents(msg);\n settleDoneWaiters();\n }\n\n /**\n * One full transition: update → save → reconcile subs → interpret → fire.\n * Save-before-effects is the hard ordering; tests pin it. A `save` throw\n * propagates after the in-memory `state` is advanced; reconcile/interpret\n * throws after `save` has succeeded.\n */\n async function stepDispatch(msg: M): Promise<void> {\n if (state === undefined) {\n throw new Error(\"@demlik/tea: runtime not booted\");\n }\n // Instance-identity filter. When the machine declares an `identity`, a\n // message addressed to a DIFFERENT identity is dropped here — before\n // `update` runs, so the reducer never sees a foreign-instance message and\n // no cell needs a `msg.runId !== state.runId` guard. A message with no\n // identity (`ofMsg` undefined) is identity-agnostic and always proceeds.\n // The drop resolves the dispatch (no throw) and advances nothing: no save,\n // no reconcile, no interpret, no listener/observer/event fire, no\n // done-waiter settle. Identity is explicit (invariant 7) and the drop is\n // the one observable enforcement point (invariant 6).\n if (machine.identity !== undefined) {\n const addressed = machine.identity.ofMsg(msg);\n if (addressed !== undefined) {\n const own = machine.identity.ofState(state);\n // `own === undefined` ⇒ this instance has no identity to defend yet\n // (e.g. an `idle` state before any run is established). An addressed\n // message in that state is identity-establishing, not foreign — never\n // dropped. Drop only when BOTH identities are present and differ.\n if (\n own !== undefined &&\n structuralHash(addressed) !== structuralHash(own)\n ) {\n return;\n }\n }\n }\n // The reducer is the only synchronous user code; the reentrancy brand\n // guarantees it cannot suspend, so a throw here is clean with `state` still\n // pre-transition. Route it to the supervision strategy. Dispatch goes\n // through `applyCellChecked` — the single dev-checked reducer-vs-transitions\n // primitive `foldUpdates` also folds through (see `pure/core.ts`).\n let next: S;\n let cmds: readonly C[];\n try {\n [next, cmds] = applyCellChecked<S, M, C>(machine, state, msg);\n } catch (reduceError) {\n // Invariant 6 — surface the failure as data FIRST, for every strategy.\n reportError(reduceError, { phase: \"reduce\" });\n switch (supervision.strategy) {\n case \"restart\": {\n // Host supplies last-known-good state; core installs it and KEEPS\n // FOLDING from there with no cmds (the throwing reduce produced none).\n // A throw inside `rehydrate` is NOT caught — it surfaces to the caller.\n await commit(supervision.rehydrate(state, msg, reduceError), msg, []);\n return;\n }\n case \"escalate\":\n // Surface + propagate; the runtime stays live for a parent supervisor.\n throw reduceError;\n default:\n // `stop` (safe default): halt. State is NOT advanced; propagate so THIS\n // dispatch also rejects — the halt is observable, never a silent resume.\n stopped = true;\n throw reduceError;\n }\n }\n await commit(next, msg, cmds);\n }\n\n // Boot has two phases. With NO store, `loaded = null` without an await — run\n // `init(null, ctx)` IMMEDIATELY so `getState()` is observable synchronously\n // (what `useSyncExternalStore` consumers need to render the first commit\n // without a flicker). The async remainder runs in `stepBootEffects` as the\n // first tail entry. With a store we cannot `init` synchronously (we'd invent a\n // loaded value), so the full path runs there; `store.load` throws propagate\n // via the boot promise.\n let pendingInitCmds: readonly C[] = [];\n if (!store) {\n const [initialState, initCmds] = machine.init(null, ctx);\n state = initialState;\n pendingInitCmds = initCmds;\n }\n\n async function stepBootEffects(): Promise<void> {\n if (store) {\n // Boundary parse (invariant 8): `store.load()` returns `unknown`;\n // `store.migrate(raw)` is the required parse — `S` on recognized shape,\n // `null` on unrecognized (boots fresh). `migrate` MUST NOT throw; if it\n // does we surface via the boot promise (same as a `load` throw).\n const raw = await store.load();\n const parsed = store.migrate(raw);\n const [initialState, initCmds] = machine.init(parsed, ctx);\n state = initialState;\n pendingInitCmds = initCmds;\n await store.save(state);\n }\n reconcileSubs();\n await runInterpret(pendingInitCmds);\n fireListeners();\n // Boot has no applied Msg — deliver the initial State via `onBoot`, not\n // `observe`, and project no semantic event.\n fireBoot();\n // A rehydrated boot can land terminal — settle any pre-boot `done()` waiter.\n settleDoneWaiters();\n }\n\n /**\n * Enqueue a dispatch on the tail — the single gate re-entrant interpret /\n * subscribe calls also go through. Rejects when the runtime is stopped, boot\n * failed, or the reducer / save / sub start / interpret throws.\n */\n function enqueueDispatch(msg: M): Promise<void> {\n if (stopped)\n return Promise.reject(new Error(\"@demlik/tea: runtime stopped\"));\n const next = tail.then(() => {\n if (bootError !== null) throw bootError;\n return stepDispatch(msg);\n });\n // Swallow the rejection on the tail so one failing dispatch does NOT poison\n // every subsequent one. The original `next` still rejects for the caller.\n tail = next.catch(() => {});\n return next;\n }\n\n /**\n * Drain the serial tail to quiescence. Every interpret follow-up calls\n * `enqueueDispatch`, which reassigns `tail` SYNCHRONOUSLY before the parent\n * step resolves, so awaiting the current `tail` and re-reading it catches every\n * transitively enqueued follow-up; loop until the reference is stable. Bounded\n * by `idleCap` — on cap REJECT with `QuiescenceTimeoutError` (never a silent\n * resolve), keeping a livelock distinguishable from quiescence (invariant 6).\n */\n async function drainToQuiescence(): Promise<void> {\n for (let i = 0; i < idleCap; i++) {\n const observed = tail;\n await observed;\n if (tail === observed) return;\n }\n throw new QuiescenceTimeoutError(idleCap);\n }\n\n /**\n * The public `dispatch`: run-to-quiescence by default. Await the Msg's OWN\n * transition first (so a reducer / save / interpret throw on THIS Msg surfaces\n * before any drain), then — unless `{ settle: \"once\" }` — drain the transitive\n * follow-up chain.\n */\n async function dispatchToQuiescence(\n msg: M,\n opts?: { readonly settle?: DispatchSettle },\n ): Promise<void> {\n await enqueueDispatch(msg);\n if (opts?.settle === \"once\") return;\n await drainToQuiescence();\n }\n\n // `bootPromise` is the un-swallowed promise `runtime.ready` chains off (so\n // callers see the boot error directly); `tail` gets the swallowed branch so a\n // boot failure does NOT poison every subsequent dispatch's chain (each surfaces\n // `bootError` in `enqueueDispatch`).\n const bootPromise = stepBootEffects();\n tail = bootPromise.catch((err) => {\n bootError = err;\n });\n\n // `ready` chains off `bootPromise` so a failed boot never hands out a `Runtime`\n // (keeping `getState()` total). The `runtime` forward reference resolves at\n // `.then` time, after the literal below initializes. Idempotent.\n const readyPromise: Promise<Runtime<S, M, E>> = bootPromise.then(\n () => runtime,\n );\n\n const runtime: Runtime<S, M, E> = {\n dispatch: dispatchToQuiescence,\n dispatchOnce: enqueueDispatch,\n getState(): S {\n // TOTAL. A `Runtime` is only obtainable by awaiting `ready`, which resolves\n // AFTER boot set `state`; a failed boot rejects `ready`, so no `Runtime` is\n // handed out then. The cast encodes that invariant.\n return state as S;\n },\n subscribe(listener: () => void): () => void {\n listeners.add(listener);\n return () => {\n listeners.delete(listener);\n };\n },\n observe(observer: (msg: M, state: S) => void): () => void {\n observers.add(observer);\n return () => {\n observers.delete(observer);\n };\n },\n onBoot(handler: (state: S) => void): () => void {\n // Already booted → fire immediately (cleanup is a no-op) so a late\n // subscriber never misses the one-shot boot.\n if (booted && state !== undefined) {\n const snapshot = state;\n fanout([handler], \"boot\", (h) => h(snapshot));\n return () => {};\n }\n bootHandlers.add(handler);\n return () => {\n bootHandlers.delete(handler);\n };\n },\n on<K extends E[\"type\"]>(\n type: K,\n handler: (event: Extract<E, { type: K }>) => void,\n ): () => void {\n // Monomorphic registry; per-type narrowing lives at THIS call site, and\n // `fireEvents` only routes an event to its own bucket, so the erased call\n // is sound.\n let bucket = eventHandlers.get(type);\n if (bucket === undefined) {\n bucket = new Set<(event: E) => void>();\n eventHandlers.set(type, bucket);\n }\n const erased = handler as (event: E) => void;\n bucket.add(erased);\n return () => {\n const set = eventHandlers.get(type);\n if (set === undefined) return;\n set.delete(erased);\n if (set.size === 0) eventHandlers.delete(type);\n };\n },\n subscribePort<T>(port: Port<T>, listener: (value: T) => void): () => void {\n const key = port as Port<unknown>;\n let bucket = portRegistry.get(key);\n if (!bucket) {\n bucket = new Set<(value: unknown) => void>();\n portRegistry.set(key, bucket);\n }\n // Bucket stores `(value: unknown) => void`; per-port type safety at this site.\n const erased = listener as (value: unknown) => void;\n bucket.add(erased);\n return () => {\n const set = portRegistry.get(key);\n if (!set) return;\n set.delete(erased);\n if (set.size === 0) portRegistry.delete(key);\n };\n },\n emitPort<T>(port: Port<T>, value: T): void {\n // Lets `observe`-driven Port emission work without a per-transition Cmd.\n portEmit(port, value);\n },\n ready: readyPromise,\n idle(): Promise<void> {\n return drainToQuiescence();\n },\n result(): S | undefined {\n // TOTAL. No predicate → `isTerminal` is `() => false`, so a non-terminating\n // machine reads `undefined` forever.\n const current = state as S;\n return isTerminal(current) ? current : undefined;\n },\n done(): Promise<S> {\n // Already terminal → resolve at once (never parks, so it can't miss the\n // terminal transition). Otherwise park a resolver for `settleDoneWaiters`.\n const current = state as S;\n if (isTerminal(current)) return Promise.resolve(current);\n return new Promise<S>((resolve) => {\n doneWaiters.add(resolve);\n });\n },\n async stop(): Promise<void> {\n stopped = true;\n // Drain in-flight work. Tail rejections were swallowed at enqueue time, so\n // this await always resolves.\n await tail;\n // Run every active sub cleanup; throws isolated and routed to the sink.\n stopSubs([...subRegistry.keys()]);\n // Dispose every live dep-keyed source too (same throw-isolation).\n disposeDepSubs([...depSubRegistry.keys()]);\n // Flush final state. A save throw here does not reject `stop()` (contract:\n // resolves regardless) but IS loss of the last write, so route it to the\n // sink rather than swallowing it (invariant 6).\n if (store && state !== undefined && bootError === null) {\n try {\n await store.save(state);\n } catch (error) {\n reportError(error, { phase: \"stop-save\" });\n }\n }\n },\n };\n\n return runtime;\n}\n"]}
|
|
@@ -0,0 +1,71 @@
|
|
|
1
|
+
import { replay } from './chunk-BP2R7TPP.js';
|
|
2
|
+
import { applyCell } from './chunk-PBDYW2TU.js';
|
|
3
|
+
import * as fc from 'fast-check';
|
|
4
|
+
|
|
5
|
+
// src/pbt/runners/replay-fold.ts
|
|
6
|
+
function foldEvents(machine, ctx, loaded, msgs) {
|
|
7
|
+
const { state: initialState } = replay(machine, {
|
|
8
|
+
msgs: [],
|
|
9
|
+
ctx,
|
|
10
|
+
loaded: loaded ?? null
|
|
11
|
+
});
|
|
12
|
+
const states = [initialState];
|
|
13
|
+
const steps = [];
|
|
14
|
+
let current = initialState;
|
|
15
|
+
for (const msg of msgs) {
|
|
16
|
+
const [next, emitted] = applyCell(machine, current, msg);
|
|
17
|
+
steps.push({ prev: current, msg, next, cmds: [...emitted] });
|
|
18
|
+
states.push(next);
|
|
19
|
+
current = next;
|
|
20
|
+
}
|
|
21
|
+
return { states, steps, finalState: current };
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
// src/pbt/runners/property.ts
|
|
25
|
+
function resolveFcParams(opts) {
|
|
26
|
+
return {
|
|
27
|
+
numRuns: opts?.numRuns ?? 200,
|
|
28
|
+
...opts?.seed !== void 0 ? { seed: opts.seed } : {}
|
|
29
|
+
};
|
|
30
|
+
}
|
|
31
|
+
function runProperty(machine, ctx, seqArb, opts, check) {
|
|
32
|
+
fc.assert(
|
|
33
|
+
fc.property(seqArb, (msgs) => {
|
|
34
|
+
check(foldEvents(machine, ctx, opts?.loaded ?? null, msgs));
|
|
35
|
+
}),
|
|
36
|
+
resolveFcParams(opts)
|
|
37
|
+
);
|
|
38
|
+
}
|
|
39
|
+
function propertyTerminates(machine, ctx, seqArb, terminal, opts) {
|
|
40
|
+
runProperty(machine, ctx, seqArb, opts, ({ finalState }) => {
|
|
41
|
+
if (!terminal(finalState)) {
|
|
42
|
+
throw new Error(
|
|
43
|
+
`propertyTerminates: final state did not match terminal predicate. Final: ${JSON.stringify(finalState)}`
|
|
44
|
+
);
|
|
45
|
+
}
|
|
46
|
+
});
|
|
47
|
+
}
|
|
48
|
+
function propertyInvariant(machine, ctx, seqArb, invariant, opts) {
|
|
49
|
+
runProperty(machine, ctx, seqArb, opts, ({ steps }) => {
|
|
50
|
+
for (const step of steps) {
|
|
51
|
+
if (!invariant(step)) {
|
|
52
|
+
throw new Error(
|
|
53
|
+
`propertyInvariant: failed at step msg=${JSON.stringify(step.msg)} prev=${JSON.stringify(step.prev)} next=${JSON.stringify(step.next)} cmds=${JSON.stringify(step.cmds)}`
|
|
54
|
+
);
|
|
55
|
+
}
|
|
56
|
+
}
|
|
57
|
+
});
|
|
58
|
+
}
|
|
59
|
+
function propertyTrace(machine, ctx, seqArb, predicate, opts) {
|
|
60
|
+
runProperty(machine, ctx, seqArb, opts, ({ steps, finalState }) => {
|
|
61
|
+
if (!predicate(steps, finalState)) {
|
|
62
|
+
throw new Error(
|
|
63
|
+
`propertyTrace: predicate failed on trace length=${steps.length}, final=${JSON.stringify(finalState)}`
|
|
64
|
+
);
|
|
65
|
+
}
|
|
66
|
+
});
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
export { foldEvents, propertyInvariant, propertyTerminates, propertyTrace };
|
|
70
|
+
//# sourceMappingURL=chunk-C6QC273X.js.map
|
|
71
|
+
//# sourceMappingURL=chunk-C6QC273X.js.map
|
|
@@ -0,0 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MAAA,EACA,WAIA,IAAA,EACM;AACN,EAAA,WAAA,CAAY,OAAA,EAAS,KAAK,MAAA,EAAQ,IAAA,EAAM,CAAC,EAAE,KAAA,EAAO,YAAW,KAAM;AACjE,IAAA,IAAI,CAAC,SAAA,CAAU,KAAA,EAAO,UAAU,CAAA,EAAG;AACjC,MAAA,MAAM,IAAI,KAAA;AAAA,QACR,mDAAmD,KAAA,CAAM,MAAM,WACpD,IAAA,CAAK,SAAA,CAAU,UAAU,CAAC,CAAA;AAAA,OACvC;AAAA,IACF;AAAA,EACF,CAAC,CAAA;AACH","file":"chunk-C6QC273X.js","sourcesContent":["// ---------------------------------------------------------------------------\n// `foldEvents` — pure deterministic fold over a Msg sequence.\n//\n// PBT needs the per-step (prev/msg/next/cmds) structure to assert\n// step-shaped invariants. The substrate's `replay(machine, opts)` returns\n// only final state + cumulative cmds — insufficient. We use `replay` for\n// the boot step (calls `machine.init(loaded, ctx)` faithfully) then walk\n// msgs ourselves through `applyCell`, the substrate's own cell dispatch.\n//\n// Why walk cells directly instead of looping `replay` once per msg with\n// `loaded: prevState`? Because `init(loaded)` runs every call, and on\n// machines with non-trivial init transforms (e.g. the audit machine's\n// `auditing → attach_debugger` resume cell) that would either (a) re-fire\n// the transform on every step, or (b) require fragile cmd-subtraction to\n// isolate this step's cmds. Calling the cells directly keeps the fold pure\n// and the cmds per-step exactly.\n//\n// Dispatches through `applyCell` — the single primitive `run`/`replay` use —\n// so form classification agrees with production by construction (#275).\n//\n// `foldEvents` does NOT call `interpret`, does NOT touch a Store, does NOT\n// start Subs. The reducer surface is the contract.\n// ---------------------------------------------------------------------------\n\nimport {\n applyCell,\n type Cmd,\n type Machine,\n replay,\n type Sub,\n} from \"../../index\";\n\n/**\n * One unit in a fold trace — the four pieces of data a property\n * invariant typically asserts on. `prev` is the state before the msg\n * applied; `next` is the state after; `cmds` is the cmds emitted by this\n * single step (NOT the running total).\n */\nexport interface Step<S, M, C> {\n readonly prev: S;\n readonly msg: M;\n readonly next: S;\n readonly cmds: readonly C[];\n}\n\n/**\n * Fold a Msg sequence through a machine's pure reducer, returning the\n * per-step trace, every state in order, and the final state. Initial\n * state comes from `replay(machine, { msgs: [], ctx, loaded })` — i.e.\n * `machine.init(loaded ?? null, ctx)` faithfully. Init's emitted cmds\n * are NOT included in any `Step` (they're the boot moment, not a Msg).\n *\n * @param machine The machine under test.\n * @param ctx The Ctx — typically `stubCtxThrowingProxy<Ctx>()` when\n * init is pure. Pass a real ctx if init reads from it.\n * @param loaded Optional pre-init snapshot (the `loaded` arg to\n * `machine.init`). Defaults to `null` (fresh boot).\n * @param msgs The Msg sequence to fold.\n *\n * @example\n * const { states, steps, finalState } = foldEvents(machine, ctx, null, [\n * { type: \"start\" }, { type: \"tick\" }, { type: \"stop\" },\n * ]);\n * // steps[1] = { prev: { type: \"counting\", n: 0 }, msg: { type: \"tick\" }, ... }\n */\nexport function foldEvents<\n S,\n M extends { type: string },\n C extends Cmd,\n U extends Sub,\n Ctx,\n>(\n machine: Machine<S, M, C, U, Ctx>,\n ctx: NoInfer<Ctx>,\n loaded: NoInfer<S> | null,\n msgs: readonly NoInfer<M>[],\n): {\n readonly states: readonly S[];\n readonly steps: readonly Step<S, M, C>[];\n readonly finalState: S;\n} {\n // Boot through `replay` so `init` runs faithfully and we honor the\n // substrate's loaded-snapshot contract (init may transform the loaded\n // value before the first Msg lands — e.g. the audit machine flips\n // `debuggerAttached: false` on resume).\n const { state: initialState } = replay(machine, {\n msgs: [],\n ctx,\n loaded: loaded ?? null,\n });\n\n // Per-msg dispatch goes through `applyCell` — the same primitive `run` and\n // `replay` use — so this runner classifies the update form identically to\n // production (`formOf` honors the `__form` tag; #275).\n const states: S[] = [initialState];\n const steps: Step<S, M, C>[] = [];\n let current = initialState;\n\n for (const msg of msgs) {\n const [next, emitted] = applyCell<S, M, C>(machine, current, msg);\n steps.push({ prev: current, msg, next, cmds: [...emitted] });\n states.push(next);\n current = next;\n }\n\n return { states, steps, finalState: current };\n}\n","// ---------------------------------------------------------------------------\n// Property runners — three thin wrappers over `fc.assert(fc.property(...))`\n// that fold a generated Msg sequence through the machine via `foldEvents`\n// and pipe the result into a TEA-shaped predicate.\n//\n// - `propertyTerminates` — every sequence ends in a terminal state.\n// - `propertyInvariant` — predicate holds on every (prev, msg, next, cmds) step.\n// - `propertyTrace` — predicate holds on the full (trace, final) shape.\n//\n// Each runner accepts `numRuns` (passed through to fast-check), an optional\n// `loaded` snapshot (forwarded to `foldEvents`), and the Msg-sequence\n// arbitrary. They return `void`; failures throw via fast-check's standard\n// shrinking output.\n//\n// Default shrinker is fast-check's built-in (open question 4): drop-msg /\n// prefix shrinkers can be layered later but are opt-in, not default. The\n// built-in shrinker handles array-shape shrinking + per-element variant\n// shrinking automatically.\n// ---------------------------------------------------------------------------\n\nimport * as fc from \"fast-check\";\nimport type { Cmd, Machine, Sub } from \"../../index\";\nimport { foldEvents, type Step } from \"./replay-fold\";\n\n/** Common options shared by every property runner. */\ninterface PropertyOpts<S> {\n /** Pre-init snapshot — passed to `machine.init(loaded, ctx)`. Default `null`. */\n readonly loaded?: S | null;\n /** Number of generated sequences to test. Forwarded to `fc.assert`. */\n readonly numRuns?: number;\n /** Optional fast-check seed for reproducibility. */\n readonly seed?: number;\n}\n\n/** The `foldEvents` result a runner's `check` inspects. */\ntype FoldResult<S, M, C> = {\n readonly states: readonly S[];\n readonly steps: readonly Step<S, M, C>[];\n readonly finalState: S;\n};\n\n/**\n * Build the fast-check parameters shared by every runner: the 200-default\n * `numRuns` plus an optional `seed`. Single source of truth so a change to\n * the default lands in one place.\n */\nfunction resolveFcParams<M>(\n opts: PropertyOpts<unknown> | undefined,\n): fc.Parameters<[readonly M[]]> {\n return {\n numRuns: opts?.numRuns ?? 200,\n ...(opts?.seed !== undefined ? { seed: opts.seed } : {}),\n };\n}\n\n/**\n * The fold+assert core every runner shares: assert `check` over each\n * generated Msg sequence, folded once through the machine via `foldEvents`.\n * `check` throws on failure so the error message carries the offending\n * shape into fast-check's shrunk counter-example.\n */\nfunction runProperty<\n S,\n M extends { type: string },\n C extends Cmd,\n U extends Sub,\n Ctx,\n>(\n machine: Machine<S, M, C, U, Ctx>,\n ctx: Ctx,\n seqArb: fc.Arbitrary<readonly M[]>,\n opts: PropertyOpts<S> | undefined,\n check: (result: FoldResult<S, M, C>) => void,\n): void {\n fc.assert(\n fc.property(seqArb, (msgs) => {\n check(foldEvents(machine, ctx, opts?.loaded ?? null, msgs));\n }),\n resolveFcParams<M>(opts),\n );\n}\n\n/**\n * Assert every generated Msg sequence ends in a terminal state. `terminal`\n * is the predicate that names the acceptable final states (often\n * `(s) => s.type === \"done\" || s.type === \"idle\"`).\n *\n * The \"every sequence\" property catches stuck states (machine gets to a\n * non-terminal state and no further msg can escape) AND silent loops\n * (every msg variant is a noop from a given state).\n *\n * @example\n * propertyTerminates(\n * auditBackgroundMachine,\n * stubCtxThrowingProxy<BackgroundCtx>(),\n * arbMsgSequence(msgArb, { minLength: 1, maxLength: 30 }),\n * (s) => s.type === \"done\" || s.type === \"idle\",\n * { loaded: auditingState, numRuns: 500 },\n * );\n */\nexport function propertyTerminates<\n S,\n M extends { type: string },\n C extends Cmd,\n U extends Sub,\n Ctx,\n>(\n machine: Machine<S, M, C, U, Ctx>,\n ctx: NoInfer<Ctx>,\n seqArb: fc.Arbitrary<readonly NoInfer<M>[]>,\n terminal: (state: NoInfer<S>) => boolean,\n opts?: NoInfer<PropertyOpts<S>>,\n): void {\n runProperty(machine, ctx, seqArb, opts, ({ finalState }) => {\n if (!terminal(finalState)) {\n // Throwing here (vs returning false) lets the error message carry\n // the offending final state — fast-check pretty-prints it inside\n // the shrunk counter-example.\n throw new Error(\n `propertyTerminates: final state did not match terminal predicate. ` +\n `Final: ${JSON.stringify(finalState)}`,\n );\n }\n });\n}\n\n/**\n * Assert a predicate holds on EVERY transition step in a generated\n * sequence. The predicate sees `{ prev, msg, next, cmds }` per step;\n * return true to accept, false (or throw) to fail.\n *\n * Use to pin a \"when X happens in state Y, cmd Z must be emitted\" rule.\n * The shrinker minimizes the offending sequence to the smallest Msg list\n * that still violates the predicate.\n *\n * @example\n * // Pin the resume-handshake fix: `ws:client:hello` in auditing must\n * // emit `send_ws { client:ready }`.\n * propertyInvariant(\n * auditBackgroundMachine, ctx,\n * arbMsgSequence(msgArb, { prefix: [{ type: \"ws:client:hello\" }] }),\n * ({ prev, msg, cmds }) =>\n * !(prev.type === \"auditing\" && msg.type === \"ws:client:hello\") ||\n * cmds.some((c) => c.type === \"send_ws\" && c.msg.type === \"client:ready\"),\n * { loaded: auditingState, numRuns: 200 },\n * );\n */\nexport function propertyInvariant<\n S,\n M extends { type: string },\n C extends Cmd,\n U extends Sub,\n Ctx,\n>(\n machine: Machine<S, M, C, U, Ctx>,\n ctx: NoInfer<Ctx>,\n seqArb: fc.Arbitrary<readonly NoInfer<M>[]>,\n invariant: (step: Step<NoInfer<S>, NoInfer<M>, NoInfer<C>>) => boolean,\n opts?: NoInfer<PropertyOpts<S>>,\n): void {\n runProperty(machine, ctx, seqArb, opts, ({ steps }) => {\n for (const step of steps) {\n if (!invariant(step)) {\n throw new Error(\n `propertyInvariant: failed at step msg=${JSON.stringify(step.msg)} ` +\n `prev=${JSON.stringify(step.prev)} next=${JSON.stringify(step.next)} ` +\n `cmds=${JSON.stringify(step.cmds)}`,\n );\n }\n }\n });\n}\n\n/**\n * Assert a predicate over the full trace plus the final state. Use when\n * the property is \"some Msg appeared in the trace before reaching the\n * final state\" or \"no two consecutive steps had the same state.type\" —\n * predicates that need the full sequence, not a single step.\n *\n * @example\n * propertyTrace(\n * machine, ctx, seqArb,\n * (steps, final) =>\n * final.type !== \"done\" ||\n * steps.some((step) => step.msg.type === \"ws:audit:done\"),\n * { loaded: auditingState, numRuns: 500 },\n * );\n */\nexport function propertyTrace<\n S,\n M extends { type: string },\n C extends Cmd,\n U extends Sub,\n Ctx,\n>(\n machine: Machine<S, M, C, U, Ctx>,\n ctx: NoInfer<Ctx>,\n seqArb: fc.Arbitrary<readonly NoInfer<M>[]>,\n predicate: (\n steps: readonly Step<NoInfer<S>, NoInfer<M>, NoInfer<C>>[],\n finalState: NoInfer<S>,\n ) => boolean,\n opts?: NoInfer<PropertyOpts<S>>,\n): void {\n runProperty(machine, ctx, seqArb, opts, ({ steps, finalState }) => {\n if (!predicate(steps, finalState)) {\n throw new Error(\n `propertyTrace: predicate failed on trace length=${steps.length}, ` +\n `final=${JSON.stringify(finalState)}`,\n );\n }\n });\n}\n"]}
|
|
@@ -1,6 +1,6 @@
|
|
|
1
|
-
import { createSnapshot } from './chunk-
|
|
2
|
-
import { deadlineSub } from './chunk-
|
|
3
|
-
import { queueAdapter } from './chunk-
|
|
1
|
+
import { createSnapshot } from './chunk-MVY5DAMF.js';
|
|
2
|
+
import { deadlineSub } from './chunk-RMX4EOQK.js';
|
|
3
|
+
import { queueAdapter } from './chunk-MU6MCIAC.js';
|
|
4
4
|
|
|
5
5
|
// src/monitored-run/index.ts
|
|
6
6
|
function safetyTimerId(runId, progressSeq) {
|
|
@@ -14,19 +14,18 @@ function createMonitoredRun(config = {}) {
|
|
|
14
14
|
every: config.snapshotEvery,
|
|
15
15
|
...config.snapshotKey !== void 0 ? { key: config.snapshotKey } : {}
|
|
16
16
|
}) : null;
|
|
17
|
+
const activeSnap = snap ?? createSnapshot({ every: 1 });
|
|
17
18
|
function init() {
|
|
18
19
|
return {
|
|
19
|
-
phase: "
|
|
20
|
-
runId: "",
|
|
20
|
+
phase: "idle",
|
|
21
21
|
stepStates: [],
|
|
22
22
|
startedAt: 0,
|
|
23
23
|
lastProgressAt: 0,
|
|
24
24
|
progressSeq: 0,
|
|
25
|
-
failure: null,
|
|
26
25
|
// A default snapshot slice even without the brick → uniform shape. When
|
|
27
|
-
// `snap` is null the
|
|
28
|
-
// `record` is never called, so the cadence value is
|
|
29
|
-
snapshot:
|
|
26
|
+
// `snap` is null the inert `activeSnap` default supplies the slice; its
|
|
27
|
+
// `record` is never called, so the cadence value is immaterial.
|
|
28
|
+
snapshot: activeSnap.init()
|
|
30
29
|
};
|
|
31
30
|
}
|
|
32
31
|
function seedStages(at) {
|
|
@@ -42,14 +41,13 @@ function createMonitoredRun(config = {}) {
|
|
|
42
41
|
}
|
|
43
42
|
function start(s, runId, at) {
|
|
44
43
|
const next = {
|
|
45
|
-
...s,
|
|
46
44
|
phase: "running",
|
|
47
45
|
runId,
|
|
48
46
|
stepStates: isPipeline ? seedStages(at) : [],
|
|
49
47
|
startedAt: at,
|
|
50
48
|
lastProgressAt: at,
|
|
51
49
|
progressSeq: 0,
|
|
52
|
-
|
|
50
|
+
snapshot: s.snapshot
|
|
53
51
|
};
|
|
54
52
|
return [next, []];
|
|
55
53
|
}
|
|
@@ -62,7 +60,7 @@ function createMonitoredRun(config = {}) {
|
|
|
62
60
|
return [{ ...s, snapshot }, cmds];
|
|
63
61
|
}
|
|
64
62
|
function progress(s, payload, at) {
|
|
65
|
-
if (s.phase
|
|
63
|
+
if (s.phase !== "running" && s.phase !== "stale") return [s, []];
|
|
66
64
|
const bumped = {
|
|
67
65
|
...bumpProgress(s, at),
|
|
68
66
|
phase: "running"
|
|
@@ -74,7 +72,7 @@ function createMonitoredRun(config = {}) {
|
|
|
74
72
|
return [{ ...s, phase: "stale" }, []];
|
|
75
73
|
}
|
|
76
74
|
function advance(s, payload, result, at) {
|
|
77
|
-
if (s.phase
|
|
75
|
+
if (s.phase !== "running" && s.phase !== "stale") return [s, []];
|
|
78
76
|
if (result.kind === "fail") {
|
|
79
77
|
const failed = {
|
|
80
78
|
...s,
|
|
@@ -115,8 +113,7 @@ function createMonitoredRun(config = {}) {
|
|
|
115
113
|
return [{ ...s, snapshot }, cmds];
|
|
116
114
|
}
|
|
117
115
|
function onDeadline(s, msg) {
|
|
118
|
-
if (s.phase
|
|
119
|
-
if (s.runId === "") return [s, []];
|
|
116
|
+
if (s.phase !== "running" && s.phase !== "stale") return [s, []];
|
|
120
117
|
if (msg.id !== safetyTimerId(s.runId, s.progressSeq)) return [s, []];
|
|
121
118
|
const failed = {
|
|
122
119
|
...s,
|
|
@@ -126,10 +123,8 @@ function createMonitoredRun(config = {}) {
|
|
|
126
123
|
return [failed, []];
|
|
127
124
|
}
|
|
128
125
|
function boot(s, at) {
|
|
129
|
-
if (s.phase
|
|
130
|
-
const [bootedSnapshot] =
|
|
131
|
-
s.snapshot
|
|
132
|
-
);
|
|
126
|
+
if (s.phase !== "running" && s.phase !== "stale") return [s, []];
|
|
127
|
+
const [bootedSnapshot] = activeSnap.boot(s.snapshot);
|
|
133
128
|
const reseeded = {
|
|
134
129
|
...s,
|
|
135
130
|
phase: "running",
|
|
@@ -146,7 +141,6 @@ function createMonitoredRun(config = {}) {
|
|
|
146
141
|
}
|
|
147
142
|
function subs(s) {
|
|
148
143
|
if (config.deadlineMs === void 0) return [];
|
|
149
|
-
if (s.runId === "") return [];
|
|
150
144
|
if (s.phase !== "running" && s.phase !== "stale") return [];
|
|
151
145
|
return [
|
|
152
146
|
deadlineSub(
|
|
@@ -156,8 +150,7 @@ function createMonitoredRun(config = {}) {
|
|
|
156
150
|
];
|
|
157
151
|
}
|
|
158
152
|
function handlers(ports) {
|
|
159
|
-
|
|
160
|
-
return active.handlers({ store: ports.store });
|
|
153
|
+
return activeSnap.handlers({ store: ports.store });
|
|
161
154
|
}
|
|
162
155
|
function confirmSnapshot(s, msg) {
|
|
163
156
|
if (snap === null) return s;
|
|
@@ -182,5 +175,5 @@ function liftRun(state, [slice, cmds]) {
|
|
|
182
175
|
}
|
|
183
176
|
|
|
184
177
|
export { createMonitoredRun, liftRun };
|
|
185
|
-
//# sourceMappingURL=chunk-
|
|
186
|
-
//# sourceMappingURL=chunk-
|
|
178
|
+
//# sourceMappingURL=chunk-CAXMQJJ3.js.map
|
|
179
|
+
//# sourceMappingURL=chunk-CAXMQJJ3.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/monitored-run/index.ts"],"names":[],"mappings":";;;;;AA6RA,SAAS,aAAA,CAAc,OAAe,WAAA,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A,EAAO,CAAA,CAAE,WAAW,CAAA;AAAA,QACpC,CAAA,CAAE,iBAAiB,MAAA,CAAO;AAAA;AAC5B,KACF;AAAA,EACF;AAeA,EAAA,SAAS,SACP,KAAA,EAQA;AACA,IAAA,OAAO,WAAW,QAAA,CAAS,EAAE,KAAA,EAAO,KAAA,CAAM,OAAO,CAAA;AAAA,EACnD;AAOA,EAAA,SAAS,eAAA,CACP,GACA,GAAA,EAC0B;AAC1B,IAAA,IAAI,IAAA,KAAS,MAAM,OAAO,CAAA;AAK1B,IAAA,MAAM,CAAC,SAAS,CAAA,GAAI,KAAK,OAAA,CAAQ,CAAA,CAAE,UAAU,GAAG,CAAA;AAChD,IAAA,OAAO,EAAE,GAAG,CAAA,EAAG,QAAA,EAAU,SAAA,EAAU;AAAA,EACrC;AAEA,EAAA,OAAO;AAAA,IACL,IAAA;AAAA,IACA,KAAA;AAAA,IACA,QAAA;AAAA,IACA,SAAA;AAAA,IACA,OAAA;AAAA,IACA,UAAA;AAAA,IACA,IAAA;AAAA,IACA,eAAA;AAAA,IACA,IAAA;AAAA,IACA;AAAA,GACF;AACF;AAQO,SAAS,OAAA,CAKd,KAAA,EACA,CAAC,KAAA,EAAO,IAAI,CAAA,EACgB;AAC5B,EAAA,OAAO,CAAC,EAAE,GAAG,OAAO,GAAA,EAAK,KAAA,IAAS,IAAI,CAAA;AACxC","file":"chunk-CAXMQJJ3.js","sourcesContent":["/**\n * @demlik/tea/monitored-run — a long-running operation that is BOTH staged and\n * watched: an ordered stage pipeline whose POSITION survives eviction, wrapped\n * by a no-progress safety deadline and (optionally) a periodic durable\n * checkpoint.\n *\n * This is the merge of two field-guide concerns the audit-agent machine\n * hand-wired together (`seed/audit-agent-machine`): the OUTER pipeline position\n * (`RunStage` — planning → testing → summarizing → reporting, replayed on cold\n * wake by re-emitting the one outstanding effect) and the no-progress safety\n * alarm (`subs.ts`, keyed on `progressSeq` so every progress event retires the\n * old alarm and arms a fresh one). `monitored-run` lifts both into one config-\n * driven knob with the uniform L2 contract `resilient-call` established:\n * `init()`, the verbs (`start` / `advance` / `progress` / `onDeadline` /\n * `boot`), `subs(state)`, and `handlers(ports)`.\n *\n * - It is **staged, optionally**. Omit `stages` and the run is single-shot:\n * `start` enters `running`, `advance` finishes it to `done`. Provide\n * `stages` and it becomes an ordered pipeline — each `advance` retires the\n * current stage and claims the next, finishing to `done` only when the last\n * stage is retired. The pipeline POSITION lives in the Model (a\n * `work-queue` of stage items), so an eviction mid-pipeline resumes at the\n * same stage via `boot` — the audit machine's \"pipeline position survives\n * eviction\" property, generalized.\n * - It is **watched**. While `running`, a no-progress deadline is armed at\n * `lastProgressAt + deadlineMs` and keyed on `progressSeq`. Every\n * `progress` / `advance` bumps the seq, so the substrate retires the old\n * alarm and arms a new one — a self-rearming watchdog. If the alarm fires\n * (`onDeadline`) the run goes `failed` with a deadline reason. Omit\n * `deadlineMs` → no watchdog (the `stale` phase is never reachable).\n * - It **checkpoints, optionally**. Provide `snapshotEvery` and every\n * progress unit is accounted to a `../snapshot` slice; once the cadence is\n * reached a checkpoint Cmd is emitted (interpreted by the spliced snapshot\n * `handlers`), so a crashed run restarts from the last durable checkpoint\n * rather than from zero. Omit it → no checkpointing.\n *\n * ## Why the run lifecycle is INLINE (run-tracker not extracted)\n *\n * The phase union (`idle` / `running` / `stale` / `done` / `failed`, a\n * discriminated union carrying only each phase's own data) and its bookkeeping\n * (`runId`, `startedAt`, `lastProgressAt`, `progressSeq`) live directly on this\n * slice rather than behind a `run-tracker` sub-knob.\n * Extraction earns its keep when two independent axes vary; here the lifecycle\n * has exactly one anchoring axis (this run), so a separate module would be a\n * premature seam. The two genuinely independent axes — the safety DEADLINE and\n * the periodic SNAPSHOT — ARE extracted (`../deadline`, `../snapshot`), and the\n * stage list is a `../work-queue` slice (`QueueItem<Stage>[]`) whose every\n * status flip is DELEGATED to the blessed `../work-queue/ops` (`enqueueOp` /\n * `claimNextOp` / `markDoneOp`) — never re-rolled here. The lifecycle is the\n * glue between them.\n *\n * ## The two non-negotiables (canon)\n *\n * - **Durable** — the slice is plain data (the stage queue is a\n * JSON-serializable `QueueItem<Stage>[]`, the snapshot slice is plain\n * numbers), so it survives DO eviction / reload.\n * - **Replayable** — every transition is a pure verb returning new state +\n * Cmds; nothing here reads the clock or RNG. Time arrives as an `at` / `atMs`\n * parameter; the only clock read is `Date.now()` inside the snapshot\n * `handlers` port (the effect boundary), exactly as `../snapshot` stamps it.\n *\n * ## Typical wiring\n *\n * const run = createMonitoredRun<MyStage, MyState>({\n * stages: [\"plan\", \"test\", \"report\"],\n * deadlineMs: 10 * 60_000,\n * snapshotEvery: 25,\n * });\n *\n * init: (loaded) => loaded ? [loaded, []] : [{ run: run.init() }, []],\n * update: {\n * begin: (s, m) => lift(s, run.start(s.run, m.runId, m.at)),\n * advance: (s, m) => lift(s, run.advance(s.run, checkpoint(s), m.result, m.at)),\n * progress: (s, m) => lift(s, run.progress(s.run, checkpoint(s), m.at)),\n * run_deadline: (s, m) => lift(s, run.onDeadline(s.run, m)),\n * boot: (s, m) => lift(s, run.boot(s.run, m.at)),\n * },\n * subscriptions: (s) => run.subs(s.run),\n * subscribe: { deadline: subscribeDeadline },\n * interpret: run.handlers({ store: r2 }),\n */\n\nimport {\n type DeadlineExceeded,\n type DeadlineSub,\n deadlineSub,\n subscribeDeadline,\n} from \"../deadline\";\nimport type { Cmd, Interpret } from \"../index\";\nimport {\n createSnapshot,\n type SnapshotFailedMsg,\n type SnapshotLoadCmd,\n type SnapshotLoadedMsg,\n type SnapshotLoadFailedMsg,\n type SnapshotSavedMsg,\n type SnapshotState,\n type SnapshotStore,\n type SnapshotWriteCmd,\n} from \"../snapshot\";\nimport type { QueueItem } from \"../work-queue\";\nimport { queueAdapter } from \"../work-queue/adapter\";\n\n// ===========================================================================\n// Config — the knob. Every field optional; omit a field → omit its gate.\n// ===========================================================================\n\n/**\n * The monitored-run knob. EVERY field is optional:\n * - omit `stages` → single-shot run (no pipeline; one `advance` finishes).\n * - omit `deadlineMs` → no no-progress watchdog (the run is never auto-failed).\n * - omit `snapshotEvery`→ no periodic checkpoint (no `snapshot_write` Cmds).\n *\n * An empty config `{}` is a valid single-shot, unwatched, uncheckpointed run.\n *\n * `Stage` is the consumer's stage identifier — any JSON-serializable value\n * (a string id, a `{ kind, ... }` record). It rides through the stage queue\n * unchanged so the consumer's reducer can branch on the current stage to emit\n * that stage's outstanding effect (the audit machine's `outstandingEffect`).\n */\nexport interface MonitoredRunConfig<Stage> {\n /**\n * The ordered stages of the pipeline. Position survives eviction (lives in\n * the Model's stage queue). Omit for a single-shot run. An empty array is\n * treated as single-shot too — there is nothing to pipeline through.\n */\n readonly stages?: readonly Stage[];\n /**\n * No-progress watchdog budget, in ms. The safety deadline is armed at\n * `lastProgressAt + deadlineMs` and re-armed on every progress event. Omit\n * for no watchdog.\n */\n readonly deadlineMs?: number;\n /**\n * Checkpoint cadence — write a durable snapshot once this many progress\n * units have accumulated. Threaded straight into `../snapshot`'s `every`.\n * Omit for no checkpointing.\n */\n readonly snapshotEvery?: number;\n /**\n * Store key the rolling checkpoint is written under. Forwarded to\n * `../snapshot`'s `key`; defaults to that module's `@@snapshot`. Ignored\n * when `snapshotEvery` is omitted.\n */\n readonly snapshotKey?: string;\n}\n\n// ===========================================================================\n// Slice — the Model field this knob owns. Run lifecycle INLINE + composed bricks.\n// ===========================================================================\n\n/**\n * Why a run terminated as `failed`. Discriminated so each reason carries only\n * its own data (pattern 11):\n * - `deadline` — the no-progress watchdog fired (`onDeadline`).\n * - `stage` — the consumer reported a stage failure via `advance(..., fail)`.\n *\n * `stale` is a SEPARATE phase (not a fail reason): a run is `stale` only by an\n * explicit consumer signal that progress has wedged WITHOUT the deadline having\n * fired — a soft, recoverable observation. The deadline firing is a hard\n * terminal (`failed { reason: \"deadline\" }`).\n *\n * The `stage` variant carries the FAILING STAGE VALUE (the `Stage` itself), not\n * a positional index: done stages leave the queue (`markDoneOp` filters them),\n * so a residual index drifts as the pipeline advances. The stage value is the\n * stable, meaningful identifier — `undefined` for a single-shot run (no stage).\n */\nexport type RunFailure<Stage> =\n | { readonly reason: \"deadline\"; readonly at: number }\n | {\n readonly reason: \"stage\";\n readonly stage: Stage | undefined;\n readonly error: unknown;\n };\n\n/**\n * The run bookkeeping every phase carries in common, split out so each arm of\n * the `MonitoredRunState` discriminated union names only the data it ADDS\n * (`runId` on started phases, `failure` on `failed`) — the same discipline the\n * sibling `PaginatorState` uses for its shared `seen` / `pages` counters. Plain\n * data end to end so the whole slice survives DO eviction / reload:\n *\n * - `stepStates` — the stage pipeline as a `work-queue` of stage items.\n * Empty for a single-shot run. The ONE `running` item is\n * the current stage; `done` items are retired stages\n * (they leave the queue via `markDoneOp`, so the queue\n * shrinks as the pipeline advances and is empty at\n * `done`). POSITION survives eviction because this list\n * is durable.\n * - `startedAt` — `at` of `start`. Observability; never compared in a verb.\n * - `lastProgressAt` — `at` of the most recent progress event; the watchdog\n * base. Re-armed by `progress` / `advance`.\n * - `progressSeq` — monotonic progress counter; keys the safety alarm Sub\n * id so every bump retires the old alarm and arms a new\n * one (the audit subs' `safety:{progressSeq}` discipline).\n * - `snapshot` — the `../snapshot` slice (cadence counter + durable\n * watermark). Always present (uniform shape); the gate\n * is simply never driven when `snapshotEvery` is omitted.\n */\ninterface RunCore<Stage> {\n readonly stepStates: readonly QueueItem<Stage>[];\n readonly startedAt: number;\n readonly lastProgressAt: number;\n readonly progressSeq: number;\n readonly snapshot: SnapshotState;\n}\n\n/**\n * The slice — a discriminated union on `phase` so each phase carries ONLY its\n * own data and impossible combinations are unrepresentable (pattern 11), the\n * same idiom the sibling `CircuitState` / `PaginatorState` / `RunFailure` follow:\n *\n * - `idle` — created but never started. Carries no `runId` (identity is\n * host-minted at `start`) and no `failure`: \"not started\" is its\n * OWN phase, not a `running` run wearing an empty-string `runId`\n * sentinel. `start` is the only transition out, so no verb has to\n * guard \"has this actually started?\" — `phase === \"idle\"` says it.\n * - `running` — the run is live. Carries the host-minted `runId` and the\n * `RunCore` pipeline position + watchdog bookkeeping.\n * - `stale` — a soft \"no progress observed\" mark the consumer can set and\n * clear; still resumable (a `progress` clears it back to\n * `running`). Distinct from a fired deadline, which is terminal.\n * - `done` — every stage retired (or the single-shot `advance` landed).\n * - `failed` — terminal failure; the typed `failure` reason rides ONLY this\n * arm, so it is present iff `phase === \"failed\"` BY CONSTRUCTION —\n * there is no nullable side field to keep in sync.\n *\n * `runId` is the host-minted run identity, stamped at `start` (the machine never\n * mints — see the audit seed's \"run identity is host-minted\"). It rides every\n * started phase, but not `idle`.\n */\nexport type MonitoredRunState<Stage> =\n | (RunCore<Stage> & { readonly phase: \"idle\" })\n | (RunCore<Stage> & { readonly phase: \"running\"; readonly runId: string })\n | (RunCore<Stage> & { readonly phase: \"stale\"; readonly runId: string })\n | (RunCore<Stage> & { readonly phase: \"done\"; readonly runId: string })\n | (RunCore<Stage> & {\n readonly phase: \"failed\";\n readonly runId: string;\n readonly failure: RunFailure<Stage>;\n });\n\n/**\n * The live (still-timed) phases — `running` or `stale`. The verbs narrow to this\n * before touching the watchdog bookkeeping (`runId` / `progressSeq`), so a\n * settled (`done` / `failed`) or never-started (`idle`) slice can never be bumped\n * — the narrow replaces the old `runId === \"\"` born-live guard.\n */\ntype LiveRun<Stage> = Extract<\n MonitoredRunState<Stage>,\n { readonly phase: \"running\" | \"stale\" }\n>;\n\n/**\n * The outcome a consumer reports to `advance`: the current stage either\n * succeeded (retire it, claim the next) or failed (terminate the run). Plain\n * data — the consumer parses its stage result at its own boundary and hands a\n * settled outcome here.\n */\nexport type StageResult =\n | { readonly kind: \"ok\" }\n | { readonly kind: \"fail\"; readonly error: unknown };\n\n// ===========================================================================\n// Cmd + Msg — re-exported from the composed bricks so consumers wire one import.\n// ===========================================================================\n\n/** The checkpoint-write Cmd, generic over the consumer's checkpoint value `V`. */\nexport type MonitoredRunCmd<V> = SnapshotWriteCmd<V>;\n\n/** The deadline Msg the safety alarm dispatches when the watchdog fires. */\nexport type MonitoredRunTimerMsg = DeadlineExceeded;\n\n/** Ports the consumer supplies to `handlers` — just the checkpoint store. */\nexport interface MonitoredRunPorts<V> {\n /** Where periodic checkpoints are written (R2 / KV / DO sub-key / Map). */\n readonly store: SnapshotStore<V>;\n}\n\n// ===========================================================================\n// Sub-id family. The safety alarm is keyed on `progressSeq` so a progress\n// event retires the old alarm and arms a new one (single-shot, re-armed by id\n// bump — the audit subs discipline).\n// ===========================================================================\n\nfunction safetyTimerId(runId: string, progressSeq: number): string {\n return `monitored:safety:${runId}:${progressSeq}`;\n}\n\n// ===========================================================================\n// The knob factory.\n// ===========================================================================\n\n/**\n * Build a monitored-run knob from `config`. `Stage` is the consumer's stage\n * identifier type; `V` is the consumer's checkpoint value type (what\n * `snapshotEvery` checkpoints). Returns the uniform L2 knob contract.\n *\n * No `rng` parameter: unlike `resilient-call`, nothing here jitters — the only\n * external inputs are time (an `at` / `atMs` parameter) and the consumer's\n * stage outcomes. The clock is read only inside the snapshot `handlers` port.\n */\nexport function createMonitoredRun<Stage, V = unknown>(\n config: MonitoredRunConfig<Stage> = {},\n) {\n const stages = config.stages ?? [];\n const isPipeline = stages.length > 0;\n\n // The stage-queue seam, bound once. Every stage status flip delegates to the\n // `QueueAdapter` verbs (`wq.enqueue` / `wq.claim` / `wq.markDone`), so the\n // `QueueItem<Stage>` shape stays insulated behind them.\n const wq = queueAdapter<Stage>();\n\n // The snapshot sub-knob is built only when `snapshotEvery` is configured;\n // absence is `null` so the progress gate short-circuits to \"no checkpoint\".\n // When present, the slice still carries a default SnapshotState so the shape\n // is uniform across configs — the gate simply never records into it.\n const snap =\n config.snapshotEvery !== undefined\n ? createSnapshot<V>({\n every: config.snapshotEvery,\n ...(config.snapshotKey !== undefined\n ? { key: config.snapshotKey }\n : {}),\n })\n : null;\n\n // The snapshot knob to actually drive: `snap` when configured, else a single\n // inert default (`every: 1`) bound ONCE here. Its `record` is never invoked\n // (the progress gate short-circuits when `snap` is null), so the cadence value\n // is immaterial — one shared stateless knob of pure functions stands in for\n // the disabled-checkpoint case across init/boot/handlers.\n const activeSnap = snap ?? createSnapshot<V>({ every: 1 });\n\n /** The starting slice for a never-started run: the `idle` phase, no `runId`. */\n function init(): MonitoredRunState<Stage> {\n return {\n phase: \"idle\",\n stepStates: [],\n startedAt: 0,\n lastProgressAt: 0,\n progressSeq: 0,\n // A default snapshot slice even without the brick → uniform shape. When\n // `snap` is null the inert `activeSnap` default supplies the slice; its\n // `record` is never called, so the cadence value is immaterial.\n snapshot: activeSnap.init(),\n };\n }\n\n /**\n * Seed the stage queue from the configured stages: every stage enqueued\n * `pending`, then the first claimed `running`. `at` stamps the claim. PURE —\n * the work-queue ops are pure array transforms; ids are positional (`stage:i`)\n * so they are deterministic and replayable (no `crypto`, no `Math.random`).\n */\n function seedStages(at: number): readonly QueueItem<Stage>[] {\n let queue: readonly QueueItem<Stage>[] = [];\n stages.forEach((stage, i) => {\n queue = wq.enqueue(queue, stage, at, `stage:${i}`).next;\n });\n // Claim the first stage as the running position. A non-empty pipeline always\n // has a pending head here, so the claim succeeds.\n const claimed = wq.claim(queue, at);\n return claimed ? claimed.next : queue;\n }\n\n /** The current (running) stage item, or `undefined` for a single-shot run. */\n function currentStage(\n s: MonitoredRunState<Stage>,\n ): QueueItem<Stage> | undefined {\n return s.stepStates.find((i) => i.status === \"running\");\n }\n\n // === Verb: start =========================================================\n\n /**\n * Start (or restart) the run for `runId` at time `at`. Seeds the stage queue\n * (if a pipeline) and enters `running` with the watchdog clock primed. Stamps\n * `runId` from the host — the machine never mints (invariant: identity is\n * host-minted, parsed at the boundary). PURE.\n */\n function start(\n s: MonitoredRunState<Stage>,\n runId: string,\n at: number,\n ): readonly [MonitoredRunState<Stage>, readonly MonitoredRunCmd<V>[]] {\n // Build the `running` arm explicitly rather than spreading `...s`: a restart\n // from `failed` must NOT carry the old `failure` field forward (the `running`\n // arm has none), and a start from `idle` has no `runId` to preserve. Only the\n // snapshot slice threads through.\n const next: MonitoredRunState<Stage> = {\n phase: \"running\",\n runId,\n stepStates: isPipeline ? seedStages(at) : [],\n startedAt: at,\n lastProgressAt: at,\n progressSeq: 0,\n snapshot: s.snapshot,\n };\n return [next, []];\n }\n\n /**\n * Bump the watchdog clock: set `lastProgressAt`/`progressSeq` so the safety\n * alarm Sub id changes and the substrate re-arms a fresh deadline. Shared by\n * `progress` and `advance`. PURE.\n */\n function bumpProgress(s: LiveRun<Stage>, at: number): LiveRun<Stage> {\n return { ...s, lastProgressAt: at, progressSeq: s.progressSeq + 1 };\n }\n\n /**\n * Account one progress unit to the snapshot slice (when the brick is\n * configured), returning the new slice + any checkpoint Cmd. `payload` is the\n * consumer's checkpoint value to persist. PURE — `snap.record` is pure, the\n * write is realized only when the runtime performs the emitted Cmd.\n */\n function recordSnapshot(\n s: MonitoredRunState<Stage>,\n payload: V,\n at: number,\n ): readonly [MonitoredRunState<Stage>, readonly MonitoredRunCmd<V>[]] {\n if (snap === null) return [s, []];\n const [snapshot, cmds] = snap.record(s.snapshot, payload, at);\n // `snap.record` only ever emits `SnapshotWriteCmd<V>` (its sole Cmd), but\n // its signature widens to `readonly Cmd[]`. Narrow back to this knob's\n // precise Cmd union so a consumer's host Cmd type can stay exact.\n return [{ ...s, snapshot }, cmds as readonly MonitoredRunCmd<V>[]];\n }\n\n // === Verb: progress ======================================================\n\n /**\n * Record forward progress: bump the watchdog (re-arming the safety alarm),\n * clear any `stale` mark back to `running`, and account a snapshot unit\n * (emitting a checkpoint Cmd on a cadence hit). A no-op unless the run is live\n * (`running` / `stale`) — a late progress event on a settled (`done` /\n * `failed`) or never-started (`idle`) run is ignored. PURE.\n */\n function progress(\n s: MonitoredRunState<Stage>,\n payload: V,\n at: number,\n ): readonly [MonitoredRunState<Stage>, readonly MonitoredRunCmd<V>[]] {\n if (s.phase !== \"running\" && s.phase !== \"stale\") return [s, []];\n const bumped: MonitoredRunState<Stage> = {\n ...bumpProgress(s, at),\n phase: \"running\",\n };\n return recordSnapshot(bumped, payload, at);\n }\n\n // === Verb: markStale =====================================================\n\n /**\n * Mark the run `stale` — a soft \"no progress observed\" signal the consumer\n * raises WITHOUT the deadline having fired (e.g. an upstream heartbeat gap).\n * Recoverable: the next `progress` flips it back to `running`. A no-op unless\n * the run is currently `running` (a settled run cannot go stale). Does NOT\n * touch `progressSeq` — going stale is not progress, so the armed deadline\n * keeps counting toward the hard terminal. PURE.\n */\n function markStale(\n s: MonitoredRunState<Stage>,\n ): readonly [MonitoredRunState<Stage>, readonly MonitoredRunCmd<V>[]] {\n if (s.phase !== \"running\") return [s, []];\n return [{ ...s, phase: \"stale\" }, []];\n }\n\n // === Verb: advance =======================================================\n\n /**\n * Advance the pipeline on a stage outcome:\n *\n * - `result.kind === \"fail\"` → terminate `failed { reason: \"stage\" }`,\n * carrying the failing stage index + error. No further stages run.\n * - `result.kind === \"ok\"`:\n * - single-shot run → finish to `done` (and force a final checkpoint\n * when checkpointing, so the last durable snapshot is the terminal\n * state).\n * - pipeline → retire the current stage (`markDoneOp`) and claim the\n * next (`claimNextOp`). If none remain, finish to `done`. The new\n * position survives eviction.\n *\n * An advance is itself a progress event, so it bumps the watchdog (re-arming\n * the alarm at the new stage) and accounts a snapshot unit. A no-op on a\n * settled (`done` / `failed`) or never-started (`idle`) run. PURE — `at` is the\n * only clock, ids are positional.\n */\n function advance(\n s: MonitoredRunState<Stage>,\n payload: V,\n result: StageResult,\n at: number,\n ): readonly [MonitoredRunState<Stage>, readonly MonitoredRunCmd<V>[]] {\n if (s.phase !== \"running\" && s.phase !== \"stale\") return [s, []];\n\n // Stage failure → hard terminal. Carry the failing stage VALUE (stable),\n // `undefined` for a single-shot run with no stage.\n if (result.kind === \"fail\") {\n const failed: MonitoredRunState<Stage> = {\n ...s,\n phase: \"failed\",\n failure: {\n reason: \"stage\",\n stage: currentStage(s)?.input,\n error: result.error,\n },\n };\n return [failed, []];\n }\n\n // Success: bump the watchdog first (an advance is progress), then move the\n // pipeline position.\n const bumped = bumpProgress(s, at);\n\n // Single-shot: one advance finishes the run.\n if (!isPipeline) {\n const done: MonitoredRunState<Stage> = { ...bumped, phase: \"done\" };\n // Force a terminal checkpoint so the last durable snapshot is `done`,\n // not whatever the cadence happened to land on.\n return finishWithSnapshot(done, payload, at);\n }\n\n // Pipeline: retire the running stage, claim the next.\n const current = currentStage(s);\n const afterDone =\n current !== undefined\n ? wq.markDone(s.stepStates, current.id).next\n : s.stepStates;\n const claimed = wq.claim(afterDone, at);\n\n if (claimed === null) {\n // No more stages — the pipeline is complete.\n const done: MonitoredRunState<Stage> = {\n ...bumped,\n phase: \"done\",\n stepStates: afterDone,\n };\n return finishWithSnapshot(done, payload, at);\n }\n\n // Advance to the next stage — POSITION now points at the claimed item.\n const moved: MonitoredRunState<Stage> = {\n ...bumped,\n stepStates: claimed.next,\n };\n return recordSnapshot(moved, payload, at);\n }\n\n /**\n * Finish helper: force a terminal checkpoint when checkpointing is enabled\n * (so the durable snapshot is the terminal state), else just settle. Shared\n * by single-shot finish and pipeline completion. PURE.\n */\n function finishWithSnapshot(\n s: MonitoredRunState<Stage>,\n payload: V,\n at: number,\n ): readonly [MonitoredRunState<Stage>, readonly MonitoredRunCmd<V>[]] {\n if (snap === null) return [s, []];\n const [snapshot, cmds] = snap.force(s.snapshot, payload, at);\n // Same narrowing as `recordSnapshot`: `snap.force` emits only the write Cmd.\n return [{ ...s, snapshot }, cmds as readonly MonitoredRunCmd<V>[]];\n }\n\n // === Verb: onDeadline ====================================================\n\n /**\n * The safety alarm fired. Two outcomes by Sub-id match:\n *\n * - the alarm matches the CURRENT `progressSeq` (no progress since it was\n * armed) → the run is wedged → terminate `failed { reason: \"deadline\" }`.\n * - the alarm matches an OLDER seq → a stale fire racing a progress event\n * that already re-armed the alarm → no-op (the substrate retired this id;\n * tolerate a fire still in flight defensively).\n *\n * A no-op on a settled run (its alarm was reconciled away; tolerate a stale\n * fire) and on a NEVER-STARTED (`idle`) run (`subs` armed nothing for it, so\n * any alarm reaching it is a rogue fire that must not un-start it). PURE —\n * `msg.atMs` stamps the failure.\n */\n function onDeadline(\n s: MonitoredRunState<Stage>,\n msg: MonitoredRunTimerMsg,\n ): readonly [MonitoredRunState<Stage>, readonly MonitoredRunCmd<V>[]] {\n // Only a live (`running` / `stale`) run is watched. A settled (`done` /\n // `failed`) run's alarm was reconciled away, and a never-started (`idle`) run\n // — which has no host-minted `runId` and armed nothing — must not be\n // un-started by a born-live/rogue fire. The phase narrow IS the guard the old\n // `runId === \"\"` sentinel stood in for.\n if (s.phase !== \"running\" && s.phase !== \"stale\") return [s, []];\n // Only the alarm armed against the current progressSeq is live. A bumped\n // seq means progress re-armed it; an older fire is stale.\n if (msg.id !== safetyTimerId(s.runId, s.progressSeq)) return [s, []];\n const failed: MonitoredRunState<Stage> = {\n ...s,\n phase: \"failed\",\n failure: { reason: \"deadline\", at: msg.atMs },\n };\n return [failed, []];\n }\n\n // === Verb: boot ==========================================================\n\n /**\n * Resume after a reload (cold wake). Re-seeds the watchdog clock to `at` so\n * the safety alarm re-arms from NOW (the pre-crash `lastProgressAt` would\n * immediately fire a deadline that already elapsed during downtime — a cold\n * wake is not a no-progress wedge). Bumps `progressSeq` so the alarm gets a\n * fresh id, and resets the snapshot cadence counter (un-checkpointed\n * pre-crash progress is moot — recovery resumes from the last durable\n * checkpoint). The pipeline POSITION (`stepStates`) is preserved untouched —\n * that is the whole point of staging: resume at the same stage.\n *\n * A no-op on a settled (`done` / `failed`) or never-started (`idle`) run. Emits\n * NO Cmd — re-emitting the current stage's outstanding effect is the CONSUMER's\n * job (it knows the per-stage Cmd), the audit machine's `outstandingEffect(stage)`\n * pattern. PURE.\n */\n function boot(\n s: MonitoredRunState<Stage>,\n at: number,\n ): readonly [MonitoredRunState<Stage>, readonly MonitoredRunCmd<V>[]] {\n if (s.phase !== \"running\" && s.phase !== \"stale\") return [s, []];\n // `snap.boot` returns the reducer-cell shape `[SnapshotState, Cmd[]]`\n // (uniform across every sibling knob); a boot emits no Cmd, so take only the\n // slice. Assigning the tuple itself would put an ARRAY where a SnapshotState\n // belongs — a type error AND a non-round-trippable slice.\n const [bootedSnapshot] = activeSnap.boot(s.snapshot);\n const reseeded: MonitoredRunState<Stage> = {\n ...s,\n phase: \"running\",\n lastProgressAt: at,\n progressSeq: s.progressSeq + 1,\n snapshot: bootedSnapshot,\n // Any stage left `running` mid-flight stays the running position; the\n // queue is already correct (a single in-flight stage). resetRunningOp is\n // NOT applied — unlike a work pool, a monitored run has exactly one\n // in-flight stage and resuming it (not re-queuing it) is the correct\n // cold-wake behavior.\n };\n return [reseeded, []];\n }\n\n // === Subs ================================================================\n\n /**\n * Pre-wired subscriptions: the no-progress safety deadline, armed only while\n * the run is live (`running` / `stale`) AND a `deadlineMs` is configured. The\n * Sub id is keyed on `progressSeq`, so every progress event retires the old\n * alarm and the substrate arms a fresh one at the new `lastProgressAt +\n * deadlineMs` — a self-rearming watchdog with no manual `clearTimeout`. A\n * settled run desires no subs. Wire `subscribe: { deadline: subscribeDeadline }`.\n *\n * A NEVER-STARTED slice (`init()`) is its OWN `idle` phase, not a `running` run\n * with an empty `runId`. The `phase !== \"running\" && phase !== \"stale\"` narrow\n * therefore excludes it structurally — no separate `runId === \"\"` sentinel gate\n * is needed. Were `idle` armed, it would fire a deadline at `0 + deadlineMs`\n * (already in the past) and auto-fail a run that never began — the \"born live\"\n * defect. `start` is the only transition out of `idle`, so the watchdog exists\n * exactly once a real run is in flight.\n */\n function subs(s: MonitoredRunState<Stage>): readonly DeadlineSub[] {\n if (config.deadlineMs === undefined) return [];\n if (s.phase !== \"running\" && s.phase !== \"stale\") return [];\n return [\n deadlineSub(\n safetyTimerId(s.runId, s.progressSeq),\n s.lastProgressAt + config.deadlineMs,\n ),\n ];\n }\n\n // === Handlers ============================================================\n\n /**\n * Pre-wired interpret handler for the checkpoint write. Delegates wholesale to\n * `../snapshot`'s `handlers` (which performs the `put` and routes Ok →\n * `snapshot_saved` / Err → `snapshot_failed` via Railway — the write never\n * rejects into the runtime). When checkpointing is disabled (`snapshotEvery`\n * omitted), no `snapshot_write` Cmd is ever emitted, so the returned map is an\n * inert no-op handler — kept for a uniform `handlers(ports)` call shape.\n *\n * Fold the `snapshot_saved` Msg back through this knob's `confirmSnapshot`\n * verb to advance the durable watermark.\n */\n function handlers(\n ports: MonitoredRunPorts<V>,\n ): Interpret<\n | SnapshotSavedMsg\n | SnapshotFailedMsg\n | SnapshotLoadedMsg<V>\n | SnapshotLoadFailedMsg,\n SnapshotWriteCmd<V> | SnapshotLoadCmd,\n unknown\n > {\n return activeSnap.handlers({ store: ports.store });\n }\n\n /**\n * Fold a confirmed checkpoint write into the slice — advances the snapshot\n * watermark (forward-only). A no-op pass-through when checkpointing is\n * disabled. PURE. Fold the `snapshot_saved` Msg here.\n */\n function confirmSnapshot(\n s: MonitoredRunState<Stage>,\n msg: SnapshotSavedMsg,\n ): MonitoredRunState<Stage> {\n if (snap === null) return s;\n // `snap.confirm` returns the reducer-cell shape `[SnapshotState, Cmd[]]`\n // (an ack emits nothing). Take only the slice — folding the whole tuple into\n // `snapshot` would store an ARRAY where a SnapshotState belongs (a type error\n // and a non-round-trippable slice).\n const [confirmed] = snap.confirm(s.snapshot, msg);\n return { ...s, snapshot: confirmed };\n }\n\n return {\n init,\n start,\n progress,\n markStale,\n advance,\n onDeadline,\n boot,\n confirmSnapshot,\n subs,\n handlers,\n };\n}\n\n/**\n * Lift a knob result `[slice, cmds]` into a host `[State, cmds]` where the\n * slice lives at `state.run`. Convenience for the common single-slice host;\n * hosts with a differently-named field spread by hand. PURE — a thin record\n * rebuild, no clock / RNG.\n */\nexport function liftRun<\n S extends { run: MonitoredRunState<Stage> },\n Stage,\n C extends Cmd,\n>(\n state: S,\n [slice, cmds]: readonly [MonitoredRunState<Stage>, readonly C[]],\n): readonly [S, readonly C[]] {\n return [{ ...state, run: slice }, cmds];\n}\n\n/**\n * Re-export the deadline Sub primitives so consumers (and tests) wire one\n * import: `subscribeDeadline` is the `subscribe` cell, `deadlineSub` builds the\n * Sub literal this knob's `subs` emits.\n */\nexport { subscribeDeadline, deadlineSub };\nexport type {\n DeadlineSub,\n DeadlineExceeded,\n SnapshotSavedMsg,\n SnapshotWriteCmd,\n};\n"]}
|
|
@@ -1,4 +1,5 @@
|
|
|
1
|
-
import { queueAdapter } from './chunk-
|
|
1
|
+
import { queueAdapter } from './chunk-MU6MCIAC.js';
|
|
2
|
+
import { at } from './chunk-FV3Z5MBE.js';
|
|
2
3
|
|
|
3
4
|
// src/fan-out/index.ts
|
|
4
5
|
function launchBudget(concurrency) {
|
|
@@ -47,7 +48,7 @@ function launchUpTo(state, config) {
|
|
|
47
48
|
}
|
|
48
49
|
function settleOne(state, id, status, idOf) {
|
|
49
50
|
const runIdx = state.running.findIndex((item) => idOf(item) === id);
|
|
50
|
-
const input =
|
|
51
|
+
const input = at(state.running, runIdx);
|
|
51
52
|
if (input === void 0) return void 0;
|
|
52
53
|
const running = [
|
|
53
54
|
...state.running.slice(0, runIdx),
|
|
@@ -56,7 +57,7 @@ function settleOne(state, id, status, idOf) {
|
|
|
56
57
|
const ledgerIdx = state.items.findIndex(
|
|
57
58
|
(item) => item.id === id && item.status === "running"
|
|
58
59
|
);
|
|
59
|
-
const ledger =
|
|
60
|
+
const ledger = at(state.items, ledgerIdx);
|
|
60
61
|
const items = ledger === void 0 ? state.items : [
|
|
61
62
|
...state.items.slice(0, ledgerIdx),
|
|
62
63
|
{ ...ledger, status },
|
|
@@ -143,5 +144,5 @@ function createFanOut(config) {
|
|
|
143
144
|
}
|
|
144
145
|
|
|
145
146
|
export { createFanOut, initFanOut, isComplete };
|
|
146
|
-
//# sourceMappingURL=chunk-
|
|
147
|
-
//# sourceMappingURL=chunk-
|
|
147
|
+
//# sourceMappingURL=chunk-D736QUGF.js.map
|
|
148
|
+
//# sourceMappingURL=chunk-D736QUGF.js.map
|