@demlik/tea 0.15.0 → 0.16.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.
Files changed (115) hide show
  1. package/README.md +30 -7
  2. package/dist/agent/index.d.ts +49 -37
  3. package/dist/agent/index.js +12 -8
  4. package/dist/chunk-4LPY67E4.js +18 -0
  5. package/dist/chunk-4LPY67E4.js.map +1 -0
  6. package/dist/chunk-5XU6ZJO2.js +533 -0
  7. package/dist/chunk-5XU6ZJO2.js.map +1 -0
  8. package/dist/{chunk-AYS5N6WY.js → chunk-6NG4V5SB.js} +62 -172
  9. package/dist/chunk-6NG4V5SB.js.map +1 -0
  10. package/dist/{chunk-3B5X7SBB.js → chunk-7MGXQZPW.js} +11 -9
  11. package/dist/chunk-7MGXQZPW.js.map +1 -0
  12. package/dist/{chunk-V46HSVCK.js → chunk-BCTEOVOU.js} +3 -3
  13. package/dist/{chunk-V46HSVCK.js.map → chunk-BCTEOVOU.js.map} +1 -1
  14. package/dist/chunk-CH5KTOEZ.js +710 -0
  15. package/dist/chunk-CH5KTOEZ.js.map +1 -0
  16. package/dist/chunk-CIHSHLQX.js +64 -0
  17. package/dist/chunk-CIHSHLQX.js.map +1 -0
  18. package/dist/{chunk-TCLBCERH.js → chunk-EHUDXAKC.js} +238 -212
  19. package/dist/chunk-EHUDXAKC.js.map +1 -0
  20. package/dist/chunk-GOX2CYIM.js +380 -0
  21. package/dist/chunk-GOX2CYIM.js.map +1 -0
  22. package/dist/{chunk-22POWGFA.js → chunk-IVJP3GKJ.js} +46 -20
  23. package/dist/chunk-IVJP3GKJ.js.map +1 -0
  24. package/dist/{chunk-QPEVCJ5Q.js → chunk-MVZS5FDM.js} +13 -6
  25. package/dist/chunk-MVZS5FDM.js.map +1 -0
  26. package/dist/{chunk-VTQI2NHP.js → chunk-MYNLY3HP.js} +9 -8
  27. package/dist/chunk-MYNLY3HP.js.map +1 -0
  28. package/dist/{chunk-Q5CQTBFA.js → chunk-NSIAORRY.js} +20 -30
  29. package/dist/chunk-NSIAORRY.js.map +1 -0
  30. package/dist/{chunk-MYXFNWAJ.js → chunk-QNGYQMZB.js} +4 -4
  31. package/dist/chunk-QNGYQMZB.js.map +1 -0
  32. package/dist/chunk-WT5PBPLB.js +98 -0
  33. package/dist/chunk-WT5PBPLB.js.map +1 -0
  34. package/dist/{core-DnzqWy6u.d.ts → core-BbgtiXdg.d.ts} +231 -139
  35. package/dist/do/index.d.ts +37 -33
  36. package/dist/do/index.js +21 -14
  37. package/dist/do/index.js.map +1 -1
  38. package/dist/{durable-effects-CWzA-o2B.d.ts → durable-effects-7MTK_jnj.d.ts} +1 -1
  39. package/dist/effect/index.d.ts +151 -0
  40. package/dist/effect/index.js +98 -0
  41. package/dist/effect/index.js.map +1 -0
  42. package/dist/extension/index.d.ts +6 -7
  43. package/dist/extension/index.js +3 -2
  44. package/dist/extension/index.js.map +1 -1
  45. package/dist/flow/index.d.ts +68 -59
  46. package/dist/flow/index.js +32 -27
  47. package/dist/flow/index.js.map +1 -1
  48. package/dist/idempotency/index.d.ts +6 -7
  49. package/dist/idempotency/index.js +4 -2
  50. package/dist/{index-CSyMYDAB.d.ts → index-7vV8xmsD.d.ts} +1 -1
  51. package/dist/{index-KXqTRJyb.d.ts → index-Bz5Rh9Ga.d.ts} +19 -96
  52. package/dist/index-CjFDUBeq.d.ts +207 -0
  53. package/dist/{index-CuNO9m8i.d.ts → index-CkFYA9Y6.d.ts} +14 -16
  54. package/dist/{index-CA_7I5g9.d.ts → index-Cou86-GX.d.ts} +137 -246
  55. package/dist/{index-DrIRb_Ch.d.ts → index-DU6JpQ8G.d.ts} +1 -1
  56. package/dist/{index-HSYgG2Yt.d.ts → index-Xufl55W8.d.ts} +247 -211
  57. package/dist/{index-C2DwkjlP.d.ts → index-_dOR3xqA.d.ts} +57 -45
  58. package/dist/index.d.ts +121 -385
  59. package/dist/index.js +2 -1
  60. package/dist/jev/index.d.ts +133 -97
  61. package/dist/jev/index.js +205 -161
  62. package/dist/jev/index.js.map +1 -1
  63. package/dist/{machine-DGlPWCWI.d.ts → machine-BQzTV8On.d.ts} +171 -288
  64. package/dist/machine-viz/index.d.ts +5 -5
  65. package/dist/machine-viz/index.js +8 -4
  66. package/dist/machine-viz/index.js.map +1 -1
  67. package/dist/mem/index.d.ts +3 -4
  68. package/dist/mem/index.js +2 -1
  69. package/dist/mem/index.js.map +1 -1
  70. package/dist/node/index.d.ts +119 -78
  71. package/dist/node/index.js +52 -38
  72. package/dist/node/index.js.map +1 -1
  73. package/dist/paginate/index.d.ts +27 -22
  74. package/dist/paginate/index.js +6 -4
  75. package/dist/parity/index.d.ts +4 -5
  76. package/dist/parity/index.js +3 -2
  77. package/dist/parity/index.js.map +1 -1
  78. package/dist/pbt/index.d.ts +2 -2
  79. package/dist/pbt/index.js +2 -1
  80. package/dist/pbt/index.js.map +1 -1
  81. package/dist/persistence/index.d.ts +6 -7
  82. package/dist/persistence/index.js +5 -3
  83. package/dist/promise/index.d.ts +186 -0
  84. package/dist/promise/index.js +5 -0
  85. package/dist/promise/index.js.map +1 -0
  86. package/dist/{protocol-D8VbH-VH.d.ts → protocol-ClRZBhHQ.d.ts} +7 -8
  87. package/dist/react/index.d.ts +36 -17
  88. package/dist/react/index.js +27 -4
  89. package/dist/react/index.js.map +1 -1
  90. package/dist/resilience/index.d.ts +63 -456
  91. package/dist/resilience/index.js +37 -483
  92. package/dist/resilience/index.js.map +1 -1
  93. package/dist/{runtime-types-CMF13BBh.d.ts → runtime-types-CiVpC0HN.d.ts} +131 -388
  94. package/dist/testing/index.d.ts +22 -16
  95. package/dist/testing/index.js +15 -7
  96. package/dist/testing/index.js.map +1 -1
  97. package/dist/timing/index.d.ts +25 -22
  98. package/dist/timing/index.js +4 -3
  99. package/dist/timing/index.js.map +1 -1
  100. package/dist/{types-BseNPIhr.d.ts → types-LxZxGYda.d.ts} +2 -2
  101. package/dist/work-queue/index.d.ts +5 -6
  102. package/package.json +18 -5
  103. package/dist/chunk-22POWGFA.js.map +0 -1
  104. package/dist/chunk-3B5X7SBB.js.map +0 -1
  105. package/dist/chunk-66PY5WYF.js +0 -1816
  106. package/dist/chunk-66PY5WYF.js.map +0 -1
  107. package/dist/chunk-AYS5N6WY.js.map +0 -1
  108. package/dist/chunk-L3TND7LA.js +0 -97
  109. package/dist/chunk-L3TND7LA.js.map +0 -1
  110. package/dist/chunk-MYXFNWAJ.js.map +0 -1
  111. package/dist/chunk-Q5CQTBFA.js.map +0 -1
  112. package/dist/chunk-QPEVCJ5Q.js.map +0 -1
  113. package/dist/chunk-TCLBCERH.js.map +0 -1
  114. package/dist/chunk-VTQI2NHP.js.map +0 -1
  115. package/dist/index-ZCMhnVKN.d.ts +0 -272
@@ -1,7 +1,6 @@
1
- import { C as Cmd, S as Sub, M as Machine, I as Interpret } from '../core-DnzqWy6u.js';
2
- import { C as CtxArg, R as Runtime } from '../runtime-types-CMF13BBh.js';
3
- import 'zod';
4
- import 'better-result';
1
+ import { C as Cmd, S as Sub, M as Machine, a as BuiltinSub, p as Interpret } from '../core-BbgtiXdg.js';
2
+ import { C as CtxArg, R as Runtime } from '../runtime-types-CiVpC0HN.js';
3
+ import '@standard-schema/spec';
5
4
 
6
5
  /**
7
6
  * The composed Model shape every `withX` wrapper produces: the base machine's
@@ -31,10 +30,10 @@ interface AssertWrapperFaithfulOpts<S, WM, BaseM, BaseCtx, WrapperCtx> {
31
30
  */
32
31
  readonly baseLoaded?: S | null;
33
32
  /**
34
- * Opt-in relaxation for an INTERCEPTING wrapper (e.g. `withResilience`).
33
+ * Opt-in relaxation for an INTERCEPTING wrapper (e.g. a retry wrapper).
35
34
  *
36
- * DEFAULT (`undefined` / `false`) — the OBSERVE-ONLY contract that
37
- * `withTelemetry` and `withDeadline` satisfy: every bare base Cmd must appear
35
+ * DEFAULT (`undefined` / `false`) — the OBSERVE-ONLY contract that a
36
+ * deadline wrapper satisfies: every bare base Cmd must appear
38
37
  * UNCHANGED, in order, as a subsequence of the wrapped Cmd stream (properties
39
38
  * 1 and 3b). The wrapper may APPEND its own Cmds but may NOT alter, drop, or
40
39
  * retime a base Cmd. This is the strict default and it is NOT weakened.
@@ -58,7 +57,7 @@ interface AssertWrapperFaithfulOpts<S, WM, BaseM, BaseCtx, WrapperCtx> {
58
57
  * Cmd in its window is a SWALLOW betrayal and still fails the gate.
59
58
  *
60
59
  * Provide the field names the carrier uses so the gate can unwrap it
61
- * structurally without hard-coding `withResilience`'s vocabulary.
60
+ * structurally without hard-coding any one wrapper's vocabulary.
62
61
  */
63
62
  readonly intercepting?: InterceptingOpt;
64
63
  }
@@ -94,10 +93,11 @@ interface InterceptingOpt {
94
93
  *
95
94
  * @param base the bare base `Machine`.
96
95
  * @param makeWrapped a thunk that wraps `base` and returns the composed machine
97
- * (e.g. `() => withTelemetry(base, cfg)`). A thunk — not the wrapped value —
98
- * so a wrapper that registers process-scoped ports (`definePort`) is
99
- * constructed inside the assertion's control, and so the same betrayal-
100
- * detector reads as `assertWrapperFaithful(base, () => withX(base, cfg), ...)`
96
+ * (e.g. `() => withTimeout(wired, cfg).machine`, where `wired.machine` is
97
+ * `base`). A thunk — not the wrapped value — so a wrapper that registers
98
+ * process-scoped ports (`definePort`) is constructed inside the assertion's
99
+ * control, and so the same betrayal-detector reads as
100
+ * `assertWrapperFaithful(wired.machine, () => withX(wired, cfg).machine, ...)`
101
101
  * at every wrapper's test site.
102
102
  * @param opts the conformance replay options.
103
103
  */
@@ -239,7 +239,7 @@ interface BoundMachine<S, M extends {
239
239
  * Assert the exact set of subs desired at the final state. Mirrors the
240
240
  * free `expectActiveSubs(machine, opts, expected)`.
241
241
  */
242
- expectActiveSubs(opts: BoundOpts<S, M>, expected: readonly NoInfer<U>[]): void;
242
+ expectActiveSubs(opts: BoundOpts<S, M>, expected: readonly NoInfer<U | BuiltinSub<M>>[]): void;
243
243
  /**
244
244
  * Bound `replay` — returns `{ state, cmds, subs }` for the given opts.
245
245
  * Use for the "narrow-then-assert" pattern where the test inspects a
@@ -248,7 +248,7 @@ interface BoundMachine<S, M extends {
248
248
  replay(opts: BoundOpts<S, M>): {
249
249
  state: S;
250
250
  cmds: readonly C[];
251
- subs: readonly U[];
251
+ subs: readonly (U | BuiltinSub<M>)[];
252
252
  };
253
253
  }
254
254
  /**
@@ -324,6 +324,12 @@ type DriveOptions<Ctx> = DriveCtxArg<Ctx> & {
324
324
  * {@link DEFAULT_MAX_ROUNDS} (100).
325
325
  */
326
326
  readonly maxRounds?: number;
327
+ /**
328
+ * The clock that stamps `at` on a `Cmd.define`d Cmd's minted `_ok` / `_err`
329
+ * Msg — the one `run` takes. Defaults to `Date.now`; pin it for a test that
330
+ * asserts on `at`.
331
+ */
332
+ readonly clock?: () => number;
327
333
  };
328
334
  /**
329
335
  * Raised when a driven machine is still emitting work after `maxRounds` rounds.
@@ -386,8 +392,8 @@ declare function driveTraceOf<M, C>(err: unknown): readonly DriveTraceEntry<M, C
386
392
  * `handlers`, feeding every settle Msg back until the machine goes quiet, and
387
393
  * hand back the settled state together with the whole history.
388
394
  *
389
- * `handlers` is the same record the machine declares as its `interpret` (e.g.
390
- * `ask.handlers()` for a jev knob), so the test drives the real interpreter and
395
+ * `handlers` is the same table a host hands `run` as its `interpret` (e.g.
396
+ * a jev knob's `resilient_run` handler), so the test drives the real interpreter and
391
397
  * mocks only the port beneath it.
392
398
  *
393
399
  * One round is: fold every pending Msg, then await a handler for every Cmd
@@ -1,4 +1,5 @@
1
- import { replay } from '../chunk-66PY5WYF.js';
1
+ import '../chunk-GOX2CYIM.js';
2
+ import { replay, cmdEdgeOver, Outcome, cmdEdge } from '../chunk-CH5KTOEZ.js';
2
3
  import { expect, vi } from 'vitest';
3
4
 
4
5
  function assertWrapperFaithful(base, makeWrapped, opts) {
@@ -116,7 +117,7 @@ function wrapperSliceKey(model) {
116
117
  const dollarKeys = Object.keys(model).filter((k) => k.startsWith("$"));
117
118
  if (dollarKeys.length !== 1) {
118
119
  throw new Error(
119
- `assertWrapperFaithful: expected exactly one "$"-prefixed wrapper slice on the composed Model, found ${dollarKeys.length} (${dollarKeys.join(", ") || "none"}). Every withX wrapper owns exactly one named slice (e.g. "$telemetry").`
120
+ `assertWrapperFaithful: expected exactly one "$"-prefixed wrapper slice on the composed Model, found ${dollarKeys.length} (${dollarKeys.join(", ") || "none"}). Every withX wrapper owns exactly one named slice (e.g. "$deadline").`
120
121
  );
121
122
  }
122
123
  return dollarKeys[0];
@@ -263,10 +264,14 @@ async function drive(machine, initial, msg, handlers, ...[opts]) {
263
264
  const options = opts ?? {};
264
265
  const maxRounds = options.maxRounds ?? DEFAULT_MAX_ROUNDS;
265
266
  const bound = bindMachine(machine, options.ctx);
267
+ const settle = cmdEdgeOver(machine.cmds ?? [], options.clock ?? Date.now);
266
268
  const noopEmit = { emit: () => {
267
269
  } };
268
270
  const handlerCtx = {
269
271
  ...noopEmit,
272
+ ok: Outcome.ok,
273
+ err: Outcome.err,
274
+ [cmdEdge]: settle,
270
275
  ...options.ctx
271
276
  };
272
277
  const cells = handlers;
@@ -294,11 +299,14 @@ async function drive(machine, initial, msg, handlers, ...[opts]) {
294
299
  if (cell === void 0) {
295
300
  throw new DriveNoHandlerError(cmd.type, trace);
296
301
  }
297
- let settle;
302
+ let settled;
298
303
  try {
299
- settle = await cell(cmd, handlerCtx, (fired) => {
300
- pending.push(fired);
301
- });
304
+ settled = settle(
305
+ cmd,
306
+ await cell(cmd, handlerCtx, (fired) => {
307
+ pending.push(fired);
308
+ })
309
+ );
302
310
  } catch (err) {
303
311
  if (typeof err === "object" && err !== null) {
304
312
  Object.defineProperty(err, TRACE_KEY, {
@@ -310,7 +318,7 @@ async function drive(machine, initial, msg, handlers, ...[opts]) {
310
318
  }
311
319
  throw err;
312
320
  }
313
- if (settle !== void 0) pending.push(settle);
321
+ if (settled !== void 0) pending.push(settled);
314
322
  }
315
323
  }
316
324
  return { state, trace };
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/testing/assert-wrapper-faithful.ts","../../src/testing/assertions.ts","../../src/testing/bind-machine.ts","../../src/testing/drive.ts","../../src/testing/noop-runtime.ts","../../src/testing/state-factory.ts"],"names":["step","expect"],"mappings":";;;AAiJO,SAAS,qBAAA,CAYd,IAAA,EACA,WAAA,EACA,IAAA,EACM;AACN,EAAA,MAAM,OAAA,GAAW,IAAA,CAAK,OAAA,IAAY,IAAA,CAAK,GAAA;AACvC,EAAA,MAAM,cAAc,IAAA,CAAK,IAAA;AACzB,EAAA,MAAM,UAAA,GACJ,KAAK,UAAA,KAAe,IAAA,CAAK,UAAU,IAAA,GAAQ,IAAA,CAAK,OAAO,IAAA,GAAa,IAAA,CAAA;AAStE,EAAA,MAAM,EAAA,GAAK,EAAE,GAAA,EAAK,GAAA,EAAW,KAAK,KAAA,EAAM;AACxC,EAAA,MAAM,EAAA,GAAK,EAAE,GAAA,EAAK,OAAA,EAAW,KAAK,KAAA,EAAM;AAIxC,EAAA,MAAM,IAAA,GAAO,YAAA;AAAA,IAAa,EAAA;AAAA,IAAI,MAC5B,MAAA,CAAO,IAAA,EAAM,EAAE,IAAA,EAAM,IAAA,CAAK,IAAA,EAAM,GAAA,EAAK,OAAA,EAAS,MAAA,EAAQ,UAAA,EAAY;AAAA,GACpE;AACA,EAAA,MAAM,OAAA,GAAU,YAAA,CAAa,EAAA,EAAI,MAAM,aAAa,CAAA;AACpD,EAAA,MAAM,QAAA,GAAW,YAAA;AAAA,IAAa,EAAA;AAAA,IAAI,MAChC,OAAO,OAAA,EAAS;AAAA,MACd,IAAA,EAAM,WAAA;AAAA,MACN,KAAK,IAAA,CAAK,GAAA;AAAA,MACV,MAAA,EAAQ,KAAK,MAAA,IAAU;AAAA,KACxB;AAAA,GACH;AAIA,EAAA,MAAM,QAAA,GAAW,YAAA;AAAA,IAAa,EAAA;AAAA,IAAI,MAChC,MAAA,CAAO,WAAA,EAAY,EAAG;AAAA,MACpB,IAAA,EAAM,WAAA;AAAA,MACN,KAAK,IAAA,CAAK,GAAA;AAAA,MACV,MAAA,EAAQ,KAAK,MA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AAA;AAAA,IAGA,KAAA,EAAO,MAAA;AAAA,IACP,MAAM,IAAA,GAAsB;AAAA,IAE5B;AAAA,GACF;AAEA,EAAA,OAAA,CAAQ,KAAA,GAAQ,OAAA,CAAQ,OAAA,CAAQ,OAAO,CAAA;AACvC,EAAA,OAAO,OAAA;AACT;;;ACpCA,SAAS,eAAiC,GAAA,EAAoB;AAC5D,EAAA,MAAM,MAAkB,EAAC;AACzB,EAAA,KAAA,MAAW,GAAA,IAAO,MAAA,CAAO,IAAA,CAAK,GAAG,CAAA,EAAkB;AACjD,IAAA,MAAM,KAAA,GAAQ,IAAI,GAAG,CAAA;AACrB,IAAA,IAAI,UAAU,MAAA,EAAW;AACvB,MAAA,GAAA,CAAI,GAAG,CAAA,GAAI,KAAA;AAAA,IACb;AAAA,EACF;AACA,EAAA,OAAO,GAAA;AACT;AAeO,SAAS,aACd,QAAA,EACoB;AAIpB,EAAA,MAAM,MAAM,EAAC;AACb,EAAA,KAAA,MAAW,OAAO,MAAA,CAAO,IAAA;AAAA,IACvB;AAAA,GACF,EAAwC;AACtC,IAAA,MAAM,aAAA,GAAgB,SAAS,GAAG,CAAA;AAClC,IAAA,GAAA,CAAI,GAAa,CAAA,GAAI,CAAC,SAAA,KAAuB;AAG3C,MAAA,MAAM,gBAAA,GAAmB,SAAA,GAAY,cAAA,CAAe,SAAS,IAAI,EAAC;AAClE,MAAA,OAAO,EAAE,IAAA,EAAM,GAAA,EAAK,GAAG,aAAA,EAAe,GAAG,gBAAA,EAAiB;AAAA,IAC5D,CAAA;AAAA,EACF;AACA,EAAA,OAAO,GAAA;AACT","file":"index.js","sourcesContent":["// ---------------------------------------------------------------------------\n// `assertWrapperFaithful` — the shared conformance gate for the wrapper tier.\n//\n// A `withX` wrapper bolts a cross-cutting concern (telemetry, deadline,\n// resilience) onto a base machine as an AUTHORING property — the base's source\n// never hand-wires it. The DANGER is the runtime betrayal: hiding wrapper state\n// in a closure, or silently swallowing / retiming a base Cmd, so the wrapper's\n// behavior is invisible to the reducer + Msg log. This helper is the binary\n// betrayal-detector every wrapper inherits. Pass = TEA-faithful, ship it.\n// Fail = betrayal, does not merge.\n//\n// It asserts, by `replay` (which composes `init` + `update` only — the\n// conformance path):\n//\n// 1. **Base behavior byte-identical.** `replay(wrapped).state.base` deep-\n// equals `replay(base).state`. The wrapper never alters base behavior.\n// 2. **Slice AND wrapper Cmds reconstruct under any ambient clock/RNG.**\n// Replaying the SAME msgs under a DIFFERENT global wall-clock + RNG yields\n// a deep-equal wrapper slice AND a deep-equal `$x:*` wrapper-Cmd subset —\n// BOTH halves of the wrapper's output (state slice + emitted Cmds) are a\n// pure function of the Msg log, NOT of `Date.now()` / `Math.random()`.\n// (`update` cells never receive `ctx`, so an impure update read reaches for\n// the GLOBAL ambient; stubbing two distinct ambients and comparing catches\n// a folded wall-clock read that two back-to-back replays under one ambient\n// would hide.) The slice comparison alone has a blind spot: a clock/RNG\n// read folded into a wrapper Cmd PAYLOAD (not the slice) leaves the slice\n// identical, so we ALSO compare the `$x:*` Cmds across the two ambients.\n// Legit time enters only as Msg `at` payloads, identical across replays.\n// 3. **Every wrapper decision is in the log.** At least one wrapper-tagged\n// Cmd (`$x:*`) or Msg appears in the replayed Cmd stream whenever there is\n// a transition — the wrapper's decisions are visible, not off-ledger.\n// PLUS a PER-TRANSITION check: at each step the bare machine's step-i Cmds\n// are an ordered subsequence of the wrapped machine's step-i Cmds, so a\n// base Cmd deferred to a LATER transition (intra-window retiming a\n// flattened subsequence would miss) surfaces as a step-level failure.\n// 4. **Slice is JSON-round-trip equal.** `$x` survives\n// `JSON.parse(JSON.stringify(...))` — durable across DO eviction / reload,\n// never a closure.\n//\n// Strengthens invariant 9 (the testing surface is named and small) and is the\n// mechanical CI form of the wrapper-tier conformance gate.\n// ---------------------------------------------------------------------------\n\nimport { expect, vi } from \"vitest\";\nimport { type Cmd, type Machine, replay, type Sub } from \"../index\";\n\n/**\n * The composed Model shape every `withX` wrapper produces: the base machine's\n * state nested under `base`, and the wrapper's own NAMED, serializable slice\n * under a single `$`-prefixed key. This helper does not care WHICH `$`-key the\n * wrapper uses — it discovers it structurally (the one non-`base` field).\n */\nexport type WrapperModel<S> = {\n readonly base: S;\n} & { readonly [K: `$${string}`]: unknown };\n\n/** Options for the conformance replay. Mirrors `replay`'s second argument. */\nexport interface AssertWrapperFaithfulOpts<S, WM, BaseM, BaseCtx, WrapperCtx> {\n /** The Msg sequence to fold through BOTH machines. Use the base's Msgs. */\n readonly msgs: readonly BaseM[];\n /** Ctx for the WRAPPED machine (base ctx + wrapper ports). */\n readonly ctx: WrapperCtx;\n /** Ctx for the BARE base machine. Defaults to `ctx` when omitted. */\n readonly baseCtx?: BaseCtx;\n /** Optional pre-`init` snapshot of the COMPOSED Model (wrapped rehydrate). */\n readonly loaded?: WM | null;\n /**\n * Optional pre-`init` snapshot of the BARE base state. Supply when the\n * wrapped `loaded` is non-null so the base-equivalence check rehydrates the\n * base machine from the matching nested slice. Defaults to `loaded?.base`.\n */\n readonly baseLoaded?: S | null;\n /**\n * Opt-in relaxation for an INTERCEPTING wrapper (e.g. `withResilience`).\n *\n * DEFAULT (`undefined` / `false`) — the OBSERVE-ONLY contract that\n * `withTelemetry` and `withDeadline` satisfy: every bare base Cmd must appear\n * UNCHANGED, in order, as a subsequence of the wrapped Cmd stream (properties\n * 1 and 3b). The wrapper may APPEND its own Cmds but may NOT alter, drop, or\n * retime a base Cmd. This is the strict default and it is NOT weakened.\n *\n * WHEN SET — for a wrapper whose whole job is to INTERCEPT a chosen base Cmd\n * (retag it into a wrapper-owned carrier so the concern — cache / breaker /\n * rate-limit / retry — can gate it), a target base Cmd LEGITIMATELY does not\n * appear raw at the top level of the wrapped stream. The contract is still\n * **retag-and-re-emit, never swallow** (rule 2): the Cmd must be RECORDED, not\n * vanished. So when a bare base Cmd is ABSENT from the top-level wrapped\n * subsequence, this option accepts it IFF, in that SAME transition window, it\n * is recorded by the wrapper as one of:\n *\n * - the inner payload of a `$x:*` \"run\" carrier Cmd (`carrierCmdType` +\n * `innerField`) — the retag path; OR\n * - any other `$x:*` divergence Cmd whose `recordsField` deep-equals the\n * base Cmd — the gate/defer path (e.g. a \"fast-failed\" or \"deferred\"\n * record Cmd that carries the base Cmd it diverged on).\n *\n * A target base Cmd that is NEITHER present raw NOR recorded by any `$x:*`\n * Cmd in its window is a SWALLOW betrayal and still fails the gate.\n *\n * Provide the field names the carrier uses so the gate can unwrap it\n * structurally without hard-coding `withResilience`'s vocabulary.\n */\n readonly intercepting?: InterceptingOpt;\n}\n\n/**\n * Configures the intercepting relaxation (see\n * `AssertWrapperFaithfulOpts.intercepting`). All fields name the carrier /\n * divergence shape so the gate can structurally find a retagged base Cmd\n * inside a `$x:*` Cmd. The gate only EVER inspects `$x:*`-prefixed wrapped\n * Cmds for a recorded base Cmd — it never relaxes the check for a base Cmd\n * that appears under any non-wrapper Cmd type.\n */\nexport interface InterceptingOpt {\n /**\n * The `Cmd.type` of the wrapper's run-carrier (e.g. `\"$resilience:run\"`).\n * A bare base Cmd that is retagged appears as `carrier[innerField]`.\n */\n readonly carrierCmdType: string;\n /** The field on the carrier Cmd that holds the original base Cmd. */\n readonly innerField: string;\n /**\n * OPTIONAL field on ANY OTHER `$x:*` Cmd that records a base Cmd the wrapper\n * gated/deferred without running it (e.g. a fast-fail record). When present\n * on a `$x:*` Cmd and deep-equal to the missing base Cmd, it counts as a\n * recorded divergence. Omit when the wrapper only ever retags via the\n * carrier.\n */\n readonly recordsField?: string;\n}\n\n/**\n * Assert a `withX` wrapper is TEA-faithful. Replays the wrapped machine and the\n * bare base machine over the same Msgs and checks the four conformance\n * properties (see file header).\n *\n * @param base the bare base `Machine`.\n * @param makeWrapped a thunk that wraps `base` and returns the composed machine\n * (e.g. `() => withTelemetry(base, cfg)`). A thunk — not the wrapped value —\n * so a wrapper that registers process-scoped ports (`definePort`) is\n * constructed inside the assertion's control, and so the same betrayal-\n * detector reads as `assertWrapperFaithful(base, () => withX(base, cfg), ...)`\n * at every wrapper's test site.\n * @param opts the conformance replay options.\n */\nexport function assertWrapperFaithful<\n S,\n BaseM extends { type: string },\n BaseC extends Cmd,\n BaseU extends Sub,\n BaseCtx,\n WM extends WrapperModel<S>,\n WrapperM extends { type: string },\n WrapperC extends Cmd,\n WrapperU extends Sub,\n WrapperCtx,\n>(\n base: Machine<S, BaseM, BaseC, BaseU, BaseCtx>,\n makeWrapped: () => Machine<WM, WrapperM, WrapperC, WrapperU, WrapperCtx>,\n opts: AssertWrapperFaithfulOpts<S, WM, BaseM, BaseCtx, WrapperCtx>,\n): void {\n const baseCtx = (opts.baseCtx ?? (opts.ctx as unknown as BaseCtx)) as BaseCtx;\n const wrappedMsgs = opts.msgs as unknown as readonly WrapperM[];\n const baseLoaded =\n opts.baseLoaded ?? (opts.loaded != null ? (opts.loaded.base as S) : null);\n\n // Two DISTINCT global ambients (wall-clock + RNG). `replay` composes only\n // `init` + `update`, and `update` cells are `(state, msg)` — they never\n // receive `ctx`. So an impure update read reaches for the GLOBAL `Date.now()`\n // / `Math.random()`, not an injected clock. Running the two determinism\n // replays under DIFFERENT ambients turns a folded wall-clock read into an\n // OBSERVABLE slice divergence (property 2) — a single fixed ambient (two\n // back-to-back replays) would return the same ms both times and hide it.\n const A0 = { now: 1_000_000, rng: 0.123 };\n const A1 = { now: 9_876_543, rng: 0.987 };\n\n // The bare baseline, `wrappedA`, and every per-transition baseline (props 3/4)\n // run under the SAME fixed ambient A0 so their cmds/state are deterministic.\n const bare = underAmbient(A0, () =>\n replay(base, { msgs: opts.msgs, ctx: baseCtx, loaded: baseLoaded }),\n );\n const wrapped = underAmbient(A0, () => makeWrapped());\n const wrappedA = underAmbient(A0, () =>\n replay(wrapped, {\n msgs: wrappedMsgs,\n ctx: opts.ctx,\n loaded: opts.loaded ?? null,\n }),\n );\n // The second determinism replay runs under a DISTINCT ambient A1. A faithful\n // wrapper's slice (a pure function of the Msg log) is identical under A0 and\n // A1; an impure update that folds `Date.now()` / `Math.random()` diverges.\n const wrappedB = underAmbient(A1, () =>\n replay(makeWrapped(), {\n msgs: wrappedMsgs,\n ctx: opts.ctx,\n loaded: opts.loaded ?? null,\n }),\n );\n\n // --- Property 1: base behavior byte-identical -----------------------------\n // `state.base` after wrapping === state after running the base alone. The\n // wrapper observes; it does not alter base behavior.\n expect(wrappedA.state.base).toEqual(bare.state);\n // The base's OWN Cmds appear in the wrapped Cmd stream unchanged: every bare\n // Cmd is present, in order, among the wrapped Cmds (with wrapper Cmds\n // interleaved). We assert the bare Cmds are a subsequence of the wrapped ones.\n // For an INTERCEPTING wrapper (`opts.intercepting` set) a target base Cmd is\n // accepted when it appears RETAGGED inside a `$x:*` carrier / recorded by a\n // `$x:*` divergence Cmd instead of raw — retag, not swallow.\n expectCmdSubsequence(bare.cmds, wrappedA.cmds, undefined, opts.intercepting);\n\n // --- Property 2: slice reconstructs under any ambient clock/RNG -----------\n // Replaying the same Msgs under a DIFFERENT global ambient yields a deep-equal\n // wrapper SLICE — the slice is a pure function of the Msg log, never of\n // `Date.now()` / `Math.random()`. We compare the single `$`-slice (not the\n // whole composed state) because comparing whole state would FALSE-POSITIVE\n // when the BASE machine reads the clock — that is the base's behavior, not the\n // wrapper's fault, and the wrapper's faithfulness is precisely what its own\n // slice records.\n const sliceKey = wrapperSliceKey(wrappedA.state);\n expect(\n sliceOf(wrappedB.state, sliceKey),\n `wrapper slice changed under a different ambient clock/RNG → update is ` +\n `reading Date.now()/Math.random(); time must enter only as Msg \\`at\\` data`,\n ).toEqual(sliceOf(wrappedA.state, sliceKey));\n\n // ...AND the wrapper-tagged Cmds reconstruct under any ambient too. The slice\n // is only HALF the wrapper's output — the other half is its emitted Cmds. A\n // wall-clock / RNG read folded into a wrapper Cmd PAYLOAD (not the state\n // slice) escapes the slice comparison above: the slice stays identical while\n // the Cmd carries a leaked `Date.now()` / `Math.random()`. So mirror the\n // slice check on the `$x:*` subset of the replayed Cmd stream — a faithful\n // wrapper emits Cmds that are a pure function of the Msg log, identical under\n // A0 and A1. Only Msg `at` payloads (identical across both replays) may carry\n // time; if a wrapper Cmd diverges between ambients, the wrapper read the\n // ambient clock/RNG into a Cmd. (Base Cmds are EXCLUDED — a base machine that\n // reads the clock is the base's behavior, not the wrapper's, exactly as the\n // slice comparison excludes whole-state.)\n const wrapperFamily = `${sliceKey}:`;\n const wrapperCmdsA = wrappedA.cmds.filter((c) =>\n c.type.startsWith(wrapperFamily),\n );\n const wrapperCmdsB = wrappedB.cmds.filter((c) =>\n c.type.startsWith(wrapperFamily),\n );\n expect(\n wrapperCmdsB,\n `wrapper Cmds (\"${wrapperFamily}*\") changed under a different ambient ` +\n `clock/RNG → a wrapper Cmd PAYLOAD is reading Date.now()/Math.random(); ` +\n `wrapper Cmds must be a pure function of the Msg log, time entering only ` +\n `as Msg \\`at\\` data`,\n ).toEqual(wrapperCmdsA);\n\n // --- Property 3: every wrapper decision appears as an XMsg/XCmd in the log -\n // The composed Model's wrapper slice is the single non-`base` `$`-key. We\n // discover its key family (`$telemetry` → `$telemetry:*`) and require that,\n // whenever there is at least one transition, the replayed Cmd stream carries\n // at least one wrapper-tagged Cmd. (Wrappers whose decisions are Msgs route\n // them through the SAME log; for a Cmd-emitting wrapper like withTelemetry the\n // decision is the `$x:emit` Cmd.) A wrapper that performed its work off-ledger\n // would have an EMPTY wrapper-Cmd set here despite real transitions — the\n // exact betrayal this gate exists to catch.\n if (opts.msgs.length > 0) {\n expect(\n wrapperCmdsA.length,\n `expected at least one \"${wrapperFamily}*\" wrapper-decision Cmd in the replay log ` +\n `(found none across ${opts.msgs.length} transition(s)) — a wrapper whose ` +\n `decisions are invisible to the Msg/Cmd log has betrayed total visibility`,\n ).toBeGreaterThan(0);\n }\n\n // --- Property 3b: per-transition Cmd subsequence --------------------------\n // The flattened subsequence (property 1) misses INTRA-WINDOW retiming — a\n // base Cmd that a saga-style wrapper DEFERS to a later transition still drains\n // within the replay, so the flattened bare-Cmd set stays an ordered\n // subsequence and slips through. Pin it per step: for each transition i, the\n // bare machine's step-i Cmds must be an ordered subsequence of the wrapped\n // machine's step-i Cmds. A deferred base Cmd is then visible as a step-i\n // subsequence failure (it shows up at i+1 in the wrapped run but at i in the\n // bare run). Prefix replays run under the fixed ambient A0 for determinism.\n for (let i = 0; i < opts.msgs.length; i++) {\n const bareStep = stepCmds(\n () =>\n underAmbient(A0, () =>\n replay(base, {\n msgs: opts.msgs.slice(0, i),\n ctx: baseCtx,\n loaded: baseLoaded,\n }),\n ).cmds,\n () =>\n underAmbient(A0, () =>\n replay(base, {\n msgs: opts.msgs.slice(0, i + 1),\n ctx: baseCtx,\n loaded: baseLoaded,\n }),\n ).cmds,\n );\n const wrappedStep = stepCmds(\n () =>\n underAmbient(A0, () =>\n replay(wrapped, {\n msgs: wrappedMsgs.slice(0, i),\n ctx: opts.ctx,\n loaded: opts.loaded ?? null,\n }),\n ).cmds,\n () =>\n underAmbient(A0, () =>\n replay(wrapped, {\n msgs: wrappedMsgs.slice(0, i + 1),\n ctx: opts.ctx,\n loaded: opts.loaded ?? null,\n }),\n ).cmds,\n );\n expectCmdSubsequence(bareStep, wrappedStep, i, opts.intercepting);\n }\n\n // --- Property 4: slice is JSON-round-trip equal ---------------------------\n // The wrapper slice survives JSON.parse(JSON.stringify(...)) — durable across\n // DO eviction / reload, never a closure.\n const slice = sliceOf(wrappedA.state, sliceKey);\n expect(JSON.parse(JSON.stringify(slice))).toEqual(slice);\n}\n\n/**\n * Run `fn` with the GLOBAL `Date.now` and `Math.random` stubbed to fixed\n * values, restoring them in a `finally` so the stub never leaks across\n * assertions or tests. `update` cells receive no `ctx`, so an impure read\n * inside one resolves to these globals — the lever this gate pulls to make a\n * folded wall-clock / RNG read observable in the wrapper slice.\n */\nfunction underAmbient<T>(\n ambient: { readonly now: number; readonly rng: number },\n fn: () => T,\n): T {\n const nowSpy = vi.spyOn(Date, \"now\").mockReturnValue(ambient.now);\n const rngSpy = vi.spyOn(Math, \"random\").mockReturnValue(ambient.rng);\n try {\n return fn();\n } finally {\n nowSpy.mockRestore();\n rngSpy.mockRestore();\n }\n}\n\n/** The wrapper slice value (the single `$`-key) on a composed Model. */\nfunction sliceOf(model: object, sliceKey: string): unknown {\n return (model as Record<string, unknown>)[sliceKey];\n}\n\n/**\n * The Cmds a single transition `i` emitted: the suffix of the cmds after\n * `msgs.slice(0, i+1)` past the cmds after `msgs.slice(0, i)`. Cmds accumulate\n * in order across `replay`, so the longer run is a prefix-extension of the\n * shorter one and the suffix is exactly step `i`'s contribution.\n */\nfunction stepCmds(\n prefixCmds: () => readonly Cmd[],\n throughCmds: () => readonly Cmd[],\n): readonly Cmd[] {\n const before = prefixCmds();\n const after = throughCmds();\n return after.slice(before.length);\n}\n\n/**\n * The wrapper slice key on a composed Model — the single own enumerable field\n * whose name starts with `$`. Throws if zero or more than one is found, because\n * the wrapper-tier contract is exactly one named `$`-slice per wrapper.\n */\nfunction wrapperSliceKey(model: object): string {\n const dollarKeys = Object.keys(model).filter((k) => k.startsWith(\"$\"));\n if (dollarKeys.length !== 1) {\n throw new Error(\n `assertWrapperFaithful: expected exactly one \"$\"-prefixed wrapper slice ` +\n `on the composed Model, found ${dollarKeys.length} (${dollarKeys.join(\", \") || \"none\"}). ` +\n `Every withX wrapper owns exactly one named slice (e.g. \"$telemetry\").`,\n );\n }\n // biome-ignore lint/style/noNonNullAssertion: length checked to be exactly 1 above\n return dollarKeys[0]!;\n}\n\n/**\n * Assert `needle` is an (order-preserving) subsequence of `haystack` by deep\n * equality — every base Cmd appears, in order, somewhere in the wrapped Cmd\n * stream (wrapper Cmds may be interleaved). This is the \"base Cmds pass through\n * UNCHANGED\" check that tolerates the wrapper's own appended Cmds without\n * requiring an exact-equal stream. When `step` is supplied the message names\n * the transition index, so a per-transition retiming failure points at the\n * exact step a base Cmd was deferred away from.\n *\n * `intercepting` (default `undefined` → the strict OBSERVE-ONLY check above)\n * relaxes the match for a base Cmd that an INTERCEPTING wrapper retags: when a\n * needle Cmd is NOT found raw in `haystack`, it is accepted IFF some `$x:*`\n * wrapper Cmd in `haystack` RECORDS it — as the carrier's `innerField` payload\n * (retag) or another `$x:*` Cmd's `recordsField` (recorded gate/defer). The\n * relaxation ONLY ever looks inside `$x:*` Cmds, so a base Cmd that vanished\n * with no `$x:*` record still fails. The order check is preserved: the carrier\n * / divergence Cmd must come at or after the cursor, exactly like a raw match.\n */\nfunction expectCmdSubsequence(\n needle: readonly Cmd[],\n haystack: readonly Cmd[],\n step?: number,\n intercepting?: InterceptingOpt,\n): void {\n let i = 0;\n for (const cmd of haystack) {\n if (i >= needle.length) break;\n if (__deepEqual(needle[i], cmd)) {\n i++;\n continue;\n }\n // Intercepting relaxation: the base Cmd at the cursor may legitimately be\n // absent raw because the wrapper RETAGGED it. Accept this haystack Cmd as\n // the matching slot IFF it is a `$x:*` wrapper Cmd that records `needle[i]`.\n if (\n intercepting !== undefined &&\n recordsBaseCmd(cmd, needle[i] as Cmd, intercepting)\n ) {\n i++;\n }\n }\n const where =\n step === undefined\n ? \"the wrapped Cmd stream\"\n : `the wrapped Cmd stream AT TRANSITION ${step} (a base Cmd deferred to a ` +\n `later transition is an intra-window retiming betrayal)`;\n const swallowHint =\n intercepting === undefined\n ? \"a missing/rewritten/retimed base Cmd is a swallow betrayal\"\n : `an intercepting wrapper must RETAG each target base Cmd into a ` +\n `\"${intercepting.carrierCmdType}\" carrier (inner field ` +\n `\"${intercepting.innerField}\") or record it on a \"$*:\" divergence Cmd ` +\n `— a base Cmd neither present raw NOR recorded by any \"$*:\" Cmd is a ` +\n `swallow betrayal`;\n expect(\n i,\n `expected every base Cmd to pass through unchanged (matched ${i} of ` +\n `${needle.length} base Cmds as an ordered subsequence of ${where}) — ` +\n `${swallowHint}`,\n ).toBe(needle.length);\n}\n\n/**\n * Does the wrapped Cmd `cmd` RECORD the base Cmd `baseCmd` under the\n * intercepting contract? True iff `cmd` is a `$`-prefixed wrapper Cmd AND\n * either:\n * - `cmd.type === carrierCmdType` and `cmd[innerField]` deep-equals\n * `baseCmd` (the retag carrier), OR\n * - `recordsField` is configured and `cmd[recordsField]` deep-equals\n * `baseCmd` (a recorded gate/defer divergence on any `$x:*` Cmd).\n *\n * The `$`-prefix guard is load-bearing: the relaxation must NEVER accept a base\n * Cmd hidden inside a NON-wrapper Cmd — that would let a wrapper launder a\n * swallowed base Cmd through an arbitrary re-emit. Only the wrapper's own\n * `$x:*` family may carry a retagged base Cmd.\n */\nfunction recordsBaseCmd(cmd: Cmd, baseCmd: Cmd, opt: InterceptingOpt): boolean {\n if (!cmd.type.startsWith(\"$\")) return false;\n const rec = cmd as unknown as Record<string, unknown>;\n if (\n cmd.type === opt.carrierCmdType &&\n __deepEqual(rec[opt.innerField], baseCmd)\n )\n return true;\n if (\n opt.recordsField !== undefined &&\n __deepEqual(rec[opt.recordsField], baseCmd)\n )\n return true;\n return false;\n}\n\n/**\n * Structural deep equality for plain Cmd data.\n *\n * NOT `JSON.stringify` equality: `JSON.stringify` DROPS undefined-valued fields,\n * so `{ type: \"x\" }` would falsely equal `{ type: \"x\", foo: undefined }` and the\n * gate could accept a wrapper that smuggles an extra (undefined) field into a\n * \"byte-identical\" base Cmd or a retag carrier. This walk distinguishes an\n * ABSENT key from an `undefined`-VALUED key by comparing the full own-enumerable\n * key SET (not just the defined values) in both directions, then recursing.\n *\n * Cmds are plain data — primitives, `null`, arrays, and plain objects — so this\n * intentionally does not model `Date`, `Map`, `Set`, cycles, or class instances.\n *\n * Exported under the `__` test-only convention so the conformance suite can\n * pin the absent-vs-undefined distinction directly. Not part of the public API.\n *\n * @internal test-only\n */\nexport function __deepEqual(a: unknown, b: unknown): boolean {\n if (Object.is(a, b)) return true;\n\n // Past the identity check, equality requires same kind on both sides. Anything\n // non-object (primitive, function, symbol) that wasn't `Object.is`-equal above\n // is unequal. `null` is `typeof \"object\"` but only equals `null` (caught by\n // `Object.is`), so screen it out explicitly.\n if (\n typeof a !== \"object\" ||\n typeof b !== \"object\" ||\n a === null ||\n b === null\n ) {\n return false;\n }\n\n const aIsArray = Array.isArray(a);\n if (aIsArray !== Array.isArray(b)) return false;\n\n if (aIsArray) {\n const bArr = b as unknown[];\n if (a.length !== bArr.length) return false;\n for (let i = 0; i < a.length; i++) {\n if (!__deepEqual(a[i], bArr[i])) return false;\n }\n return true;\n }\n\n // Plain objects: compare the own-enumerable key SET first so a key present on\n // one side with an `undefined` value (and absent on the other) is caught —\n // the betrayal `JSON.stringify` hid. Then recurse on every value.\n const aRec = a as Record<string, unknown>;\n const bRec = b as Record<string, unknown>;\n const aKeys = Object.keys(aRec);\n const bKeys = Object.keys(bRec);\n if (aKeys.length !== bKeys.length) return false;\n for (const key of aKeys) {\n if (!Object.hasOwn(bRec, key)) return false;\n if (!__deepEqual(aRec[key], bRec[key])) return false;\n }\n return true;\n}\n","// ---------------------------------------------------------------------------\n// Test-side assertions over `replay`. Each helper composes the replay call\n// with a single `expect(...)` so consumers stop hand-rolling the 5-line\n// \"destructure { state, cmds } → expect.toBe / toEqual / toContainEqual\"\n// boilerplate at every test site.\n//\n// Each helper is a thin wrapper that:\n// 1. Calls `replay(machine, opts)` once.\n// 2. Pipes the result into a single vitest `expect(...)` matcher.\n//\n// All helpers return `void` — assertions throw on failure (vitest contract).\n// No mutation of the machine or opts. Pure test ergonomics.\n//\n// Type-inference note: each helper anchors its generic parameters to the\n// `machine` argument. The `expected` (and `opts.msgs`) arguments are wrapped\n// in `NoInfer<...>` so they do NOT participate in inference — otherwise a\n// `[]`-shaped `expected` would force `C = never` and reject a machine whose\n// real Cmd union is non-empty. Anchoring inference to the machine is the\n// same discipline `replay` uses (it has nothing but the machine and opts).\n//\n// Strengthens invariant 9 (the testing surface is named, small, and forks\n// nothing of the substrate's purity guarantees).\n// ---------------------------------------------------------------------------\n\nimport { expect } from \"vitest\";\nimport { type Cmd, type Machine, replay, type Sub } from \"../index\";\n\n// `NoInfer<T>` is the built-in TypeScript 5.4+ intrinsic that blocks\n// inference from a generic parameter at a position. We use it on `expected`\n// and `opts` so inference flows purely FROM the machine — `[]`-shaped\n// `expected` no longer drags `C` down to `never` and rejects the machine.\n\n/**\n * Shared options shape for every test assertion below. Mirrors the\n * second argument of `replay(machine, opts)` — `msgs` is the sequence to\n * fold over (may be empty for init-only assertions), `ctx` is the\n * substrate-required ctx value, `loaded` is the optional pre-`init`\n * snapshot (omit / pass `null` for fresh boot).\n */\nexport interface ReplayOpts<S, M, Ctx> {\n readonly msgs: readonly M[];\n readonly ctx: Ctx;\n readonly loaded?: S | null;\n}\n\n/**\n * Assert the final state after replaying `opts.msgs` equals `expected`.\n * Replaces the boilerplate:\n *\n * const { state } = replay(machine, opts);\n * expect(state).toEqual(expected);\n *\n * Uses `toEqual` (deep structural). For type-narrowing assertions that\n * branch on `state.type` afterwards, fall back to plain `replay` —\n * `expectFinalState` is the \"exact match\" tool.\n */\nexport function expectFinalState<\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: NoInfer<ReplayOpts<S, M, Ctx>>,\n expected: NoInfer<S>,\n): void {\n const { state } = replay(machine, opts);\n expect(state).toEqual(expected);\n}\n\n/**\n * Assert that `cmd` appears at least once in the cmds array produced by\n * replaying `opts.msgs`. Uses `toContainEqual` (deep structural). Order\n * and surrounding cmds are not asserted — use `expectCmdSequence` for\n * exact ordered match.\n *\n * Replaces:\n *\n * const { cmds } = replay(machine, opts);\n * expect(cmds).toContainEqual(cmd);\n */\nexport function expectCmdEmitted<\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: NoInfer<ReplayOpts<S, M, Ctx>>,\n cmd: NoInfer<C>,\n): void {\n const { cmds } = replay(machine, opts);\n expect(cmds).toContainEqual(cmd);\n}\n\n/**\n * Assert the exact ordered sequence of cmds emitted by replaying\n * `opts.msgs`. Uses `toEqual` against the full cmds array — extra cmds\n * fail the assertion, missing cmds fail the assertion, wrong order\n * fails the assertion.\n *\n * Replaces:\n *\n * const { cmds } = replay(machine, opts);\n * expect(cmds).toEqual(expected);\n */\nexport function expectCmdSequence<\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: NoInfer<ReplayOpts<S, M, Ctx>>,\n expected: NoInfer<readonly C[]>,\n): void {\n const { cmds } = replay(machine, opts);\n expect(cmds).toEqual(expected);\n}\n\n/**\n * Assert the exact set of subs desired at the final state after\n * replaying `opts.msgs`. Uses `toEqual` against the full subs array.\n *\n * Replaces:\n *\n * const { subs } = replay(machine, opts);\n * expect(subs).toEqual(expected);\n */\nexport function expectActiveSubs<\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: NoInfer<ReplayOpts<S, M, Ctx>>,\n expected: NoInfer<readonly U[]>,\n): void {\n const { subs } = replay(machine, opts);\n expect(subs).toEqual(expected);\n}\n\n/**\n * Single-msg step helper — feeds `loaded → msg → next state + cmds emitted by\n * that msg`. Returns a readonly tuple in the shape consumers used before the\n * substrate (`[state, cmds]`), so existing tests that destructure with\n * `[next, cmds]` can swap `reduce(state, msg)` for `step(machine, state, msg,\n * ctx)` without changing the assertion code.\n *\n * Internally a `replay` call with `loaded: prevState` and a single-element\n * `msgs` array. The cmds returned are exactly the cmds emitted by THIS msg\n * (init emits no cmds when `loaded` is provided, so the slice is the entire\n * array).\n *\n * Use when consumers want to walk a machine one msg at a time and assert per\n * step. For one-shot \"final state after N msgs\" assertions, prefer\n * `expectFinalState`.\n */\nexport function step<\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 loaded: NoInfer<S>,\n msg: NoInfer<M>,\n ctx: NoInfer<Ctx>,\n): readonly [S, readonly C[]] {\n const { state, cmds } = replay(machine, { msgs: [msg], ctx, loaded });\n return [state, cmds] as const;\n}\n","// ---------------------------------------------------------------------------\n// `bindMachine(machine, ctx)` — bound test harness over the free-function\n// assertions in `./assertions.ts`. Closes over the `machine` and `ctx` once\n// so per-test callsites stop repeating both at every invocation.\n//\n// Why this exists: every consumer test file ends up hand-rolling a local\n// two-arg `step(state, msg)` wrapper around `step(machine, state, msg, ctx)`,\n// and the four `expect*` assertions repeat `machine` + `ctx` at every\n// callsite. The bound form pulls both into one place and gives every\n// per-test call its tightest possible shape (2-arg max).\n//\n// `bindMachine` is built ON TOP of the free helpers — it does not replace\n// them. Both forms coexist; pick the one that fits the call site:\n//\n// - Free form → one-off call inside a helper that isn't bound to one\n// machine (e.g. cross-machine integration test).\n// - Bound form → a `describe` block runs many assertions against one\n// machine + ctx. The bound form is the common case.\n//\n// Strengthens invariant 9 (the testing surface is named, small, and forks\n// nothing of the substrate's purity guarantees).\n// ---------------------------------------------------------------------------\n\nimport { expect } from \"vitest\";\nimport { type Cmd, type Machine, replay, type Sub } from \"../index\";\n\n/**\n * Replay options shape used by every bound method. `ctx` is captured by\n * `bindMachine`; the per-call opts only need `msgs` and an optional\n * `loaded` snapshot. (Compare `ReplayOpts` in `./assertions.ts`, which\n * still takes `ctx` because the free helpers cannot capture it.)\n */\ninterface BoundOpts<S, M> {\n readonly msgs: readonly M[];\n readonly loaded?: S | null;\n}\n\n/**\n * The bound testing surface. Every method is 2-arg max — `ctx` and\n * `machine` are captured by `bindMachine`.\n *\n * `NoInfer<...>` on `expected` / `cmd` arguments mirrors the discipline\n * the free helpers use (see `./assertions.ts`): inference flows purely\n * FROM the machine, so a `[]`-shaped expected does not drag `C` down to\n * `never` and reject the machine.\n */\nexport interface BoundMachine<\n S,\n M extends { type: string },\n C extends Cmd,\n U extends Sub,\n // `Ctx` is a phantom-style parameter — present for consumers that want to\n // spell `BoundMachine<S, M, C, U, Ctx>` explicitly, mirroring `Machine`.\n // biome-ignore lint/correctness/noUnusedVariables: phantom type param (see above)\n Ctx,\n> {\n /**\n * Single-msg step — feeds `loaded → msg → [next state, cmds emitted by\n * that msg]`. Mirrors the free `step(machine, loaded, msg, ctx)`.\n */\n step(loaded: S, msg: M): readonly [S, readonly C[]];\n /**\n * Assert the final state after replaying `opts.msgs` deep-equals\n * `expected`. Mirrors the free `expectFinalState(machine, opts, expected)`.\n */\n expectFinalState(opts: BoundOpts<S, M>, expected: NoInfer<S>): void;\n /**\n * Assert `cmd` appears at least once in the emitted cmd list. Order is\n * not asserted. Mirrors the free `expectCmdEmitted(machine, opts, cmd)`.\n */\n expectCmdEmitted(opts: BoundOpts<S, M>, cmd: NoInfer<C>): void;\n /**\n * Assert the exact ordered sequence of cmds emitted by replaying\n * `opts.msgs`. Mirrors the free `expectCmdSequence(machine, opts, expected)`.\n */\n expectCmdSequence(\n opts: BoundOpts<S, M>,\n expected: readonly NoInfer<C>[],\n ): void;\n /**\n * Assert the exact set of subs desired at the final state. Mirrors the\n * free `expectActiveSubs(machine, opts, expected)`.\n */\n expectActiveSubs(\n opts: BoundOpts<S, M>,\n expected: readonly NoInfer<U>[],\n ): void;\n /**\n * Bound `replay` — returns `{ state, cmds, subs }` for the given opts.\n * Use for the \"narrow-then-assert\" pattern where the test inspects a\n * specific field after `state.type === \"...\"` discrimination.\n */\n replay(opts: BoundOpts<S, M>): {\n state: S;\n cmds: readonly C[];\n subs: readonly U[];\n };\n}\n\n/**\n * Bind a machine + ctx into a small bag of 2-arg helpers. Each method\n * delegates to `replay(machine, { ...opts, ctx })` and pipes the result\n * through a single `expect(...)` matcher (or returns the raw tuple, for\n * `step` and `replay`).\n *\n * Use one bind per `describe` block (or per file) when many assertions\n * share the same machine + ctx. For one-off cross-machine calls, stick\n * with the free helpers from `./assertions.ts`.\n */\nexport function bindMachine<\n S,\n M extends { type: string },\n C extends Cmd,\n U extends Sub,\n Ctx,\n>(machine: Machine<S, M, C, U, Ctx>, ctx: Ctx): BoundMachine<S, M, C, U, Ctx> {\n return {\n step(loaded, msg) {\n const { state, cmds } = replay(machine, { msgs: [msg], ctx, loaded });\n return [state, cmds] as const;\n },\n expectFinalState(opts, expected) {\n const { state } = replay(machine, { ...opts, ctx });\n expect(state).toEqual(expected);\n },\n expectCmdEmitted(opts, cmd) {\n const { cmds } = replay(machine, { ...opts, ctx });\n expect(cmds).toContainEqual(cmd);\n },\n expectCmdSequence(opts, expected) {\n const { cmds } = replay(machine, { ...opts, ctx });\n expect(cmds).toEqual(expected);\n },\n expectActiveSubs(opts, expected) {\n const { subs } = replay(machine, { ...opts, ctx });\n expect(subs).toEqual(expected);\n },\n replay(opts) {\n return replay(machine, { ...opts, ctx });\n },\n };\n}\n","// ---------------------------------------------------------------------------\n// `drive(machine, initial, msg, handlers, opts)` — the runtime's own loop,\n// said once, for a test.\n//\n// `bindMachine` hands back the Cmds a fold emitted and stops there; performing\n// them is the caller's. So every consumer test that exercises a Cmd-emitting\n// machine hand-writes the same fixture: step the Msg, await the real interpret\n// handler over each emitted Cmd, feed the settle Msg back, repeat until quiet,\n// with a hand-picked guard bound in the loop header. The guard count, the\n// accumulate-then-swap order and the \"did I drain this round before starting\n// the next\" question are re-decided at every copy site, and one of those copies\n// ships in `docs/how-to/ask-jev-a-typed-question.md`.\n//\n// `drive` is that fixture as one call. It composes `bindMachine`'s synchronous\n// 2-arg `step` and adds NO second reducer path — there is no `Runtime` here, no\n// observation, no clock, and nothing borrowed from the internal flow helpers.\n// The only impure thing it does is `await` the handler the caller handed it.\n//\n// **It returns the history, not just the endpoint.** `{ state, trace }`, where\n// `trace` is every Msg folded and every Cmd dispatched in order, is what makes\n// this worth a stable export rather than a snippet: a test asserts on the\n// SEQUENCE as well as the settled state — which handler ran, in which round,\n// and what came back — and the same trace's Msgs replayed through `replay` from\n// the same initial state reproduce the returned state exactly.\n//\n// Prior art converged on the same answer: Temporal's `TestWorkflowEnvironment`\n// hands a test the event history rather than the final result, and Effect's\n// `TestClock` runs make the effect log inspectable rather than opaque.\n//\n// **Exhausting `maxRounds` THROWS.** A driver that quietly returns a\n// half-driven state lets a test assert green on a machine that never settled —\n// the exact failure a hand-rolled `guard < 10` already risks.\n//\n// Strengthens invariant 9 (the testing surface is named and small).\n// ---------------------------------------------------------------------------\n\nimport type {\n Cmd,\n CtxArg,\n Interpret,\n Machine,\n PortEmitter,\n Sub,\n} from \"../index\";\nimport { bindMachine } from \"./bind-machine\";\n\n/**\n * The default round bound when `opts.maxRounds` is omitted: **100**.\n *\n * A round is one drain of the pending Msgs plus one drain of the Cmds those\n * folds emitted, so a settling machine costs a handful; 100 is loose enough\n * that a legitimate retry ladder finishes inside it and tight enough that a\n * genuine cycle stops rather than hangs.\n */\nexport const DEFAULT_MAX_ROUNDS = 100;\n\n/**\n * One entry of a driven run's history, in dispatch order.\n *\n * - `msg` — a Msg folded through the machine's reducer. The seed Msg is the\n * first entry of every trace; every later one is a settle Msg a handler\n * returned (or fired through its injected `dispatch`).\n * - `cmd` — a Cmd handed to an interpret handler. It is recorded BEFORE the\n * handler is awaited, so a trace recovered from a rejected handler names the\n * Cmd that rejected as its last entry.\n */\nexport type DriveTraceEntry<M, C> =\n | { readonly kind: \"msg\"; readonly msg: M }\n | { readonly kind: \"cmd\"; readonly cmd: C };\n\n/** What a settled {@link drive} hands back. */\nexport interface DriveResult<S, M, C> {\n /** The state after the machine went quiet — no Msg pending, no Cmd unperformed. */\n readonly state: S;\n /**\n * Every Msg folded and every Cmd dispatched, in order. Filtering it to its\n * `msg` entries and replaying those through `replay` from the same initial\n * state reproduces {@link DriveResult.state}.\n */\n readonly trace: readonly DriveTraceEntry<M, C>[];\n}\n\n/**\n * {@link drive}'s `ctx` field. `CtxArg` widened by exactly one case: a machine\n * declaring `ctx: undefined` in its `types` block — the pure shape every\n * how-to on this package writes — may omit it too. `CtxArg` alone keeps `ctx`\n * REQUIRED there, because `{}` is not assignable to `undefined`, which would\n * make the common pure call site spell `{ ctx: undefined }` to say nothing.\n * A machine whose `Ctx` carries a field a handler reads still requires it.\n */\nexport type DriveCtxArg<Ctx> = [undefined] extends [Ctx]\n ? { readonly ctx?: Ctx }\n : CtxArg<Ctx>;\n\n/**\n * {@link drive}'s options. `ctx` is conditionally optional (see\n * {@link DriveCtxArg}).\n */\nexport type DriveOptions<Ctx> = DriveCtxArg<Ctx> & {\n /**\n * The round bound. Exceeding it throws {@link DriveRoundsExceededError};\n * `drive` never returns a half-driven state. Defaults to\n * {@link DEFAULT_MAX_ROUNDS} (100).\n */\n readonly maxRounds?: number;\n};\n\n/**\n * Raised when a driven machine is still emitting work after `maxRounds` rounds.\n * Follows the tea error dialect (`override readonly name`) and carries a `_tag`\n * discriminant, so a test branches on it by `instanceof` or on the tag.\n *\n * It carries the round count it stopped at and the PARTIAL trace up to that\n * point, which is what a test needs to see the cycle — the bound alone says\n * only that one exists.\n */\nexport class DriveRoundsExceededError<M, C> extends Error {\n override readonly name = \"DriveRoundsExceededError\";\n readonly _tag = \"DriveRoundsExceededError\" as const;\n constructor(\n /** The bound that was exceeded. */\n public readonly maxRounds: number,\n /** The round the driver stopped at — always `maxRounds + 1`. */\n public readonly rounds: number,\n /** Every Msg folded and Cmd dispatched before the driver gave up. */\n public readonly trace: readonly DriveTraceEntry<M, C>[],\n ) {\n super(\n `@demlik/tea: drive did not settle within ${maxRounds} round(s) — the ` +\n `machine was still emitting work at round ${rounds}. The partial ` +\n `trace (${trace.length} entr${trace.length === 1 ? \"y\" : \"ies\"}) is ` +\n `on the error's \\`trace\\` field.`,\n );\n }\n}\n\n/**\n * Raised when a Cmd reaches {@link drive} with no handler for its `type` in the\n * `handlers` record. `Interpret`'s mapped type makes that a compile error at a\n * well-typed call site; this is the runtime arm for a handler record assembled\n * dynamically or cast.\n */\nexport class DriveNoHandlerError<M, C> extends Error {\n override readonly name = \"DriveNoHandlerError\";\n readonly _tag = \"DriveNoHandlerError\" as const;\n constructor(\n /** The Cmd `type` nothing in the handler record answered. */\n public readonly cmdType: string,\n /** Every Msg folded and Cmd dispatched before the miss. */\n public readonly trace: readonly DriveTraceEntry<M, C>[],\n ) {\n super(\n `@demlik/tea: drive found no interpret handler for Cmd type ` +\n `\"${cmdType}\" — the handlers record must answer every Cmd the ` +\n `machine emits.`,\n );\n }\n}\n\n/** The key `drive` hangs a partial trace off a rejected handler's error under. */\nconst TRACE_KEY = \"driveTrace\";\n\n/**\n * Read back the partial trace `drive` attached to an error a handler rejected\n * with. Returns `undefined` for anything `drive` did not annotate.\n *\n * A rejecting handler's error propagates out of `drive` UNSWALLOWED — same\n * value, same `instanceof`, same `_tag` — so a test that already branches on\n * the handler's own error type keeps doing so. The trace rides along on a\n * non-enumerable property so it is recoverable without changing how the error\n * prints or serializes.\n */\nexport function driveTraceOf<M, C>(\n err: unknown,\n): readonly DriveTraceEntry<M, C>[] | undefined {\n if (typeof err !== \"object\" || err === null) return undefined;\n const carried = (err as Record<string, unknown>)[TRACE_KEY];\n return Array.isArray(carried)\n ? (carried as readonly DriveTraceEntry<M, C>[])\n : undefined;\n}\n\n/**\n * Drive `machine` from `initial` through `msg` against the REAL interpret\n * `handlers`, feeding every settle Msg back until the machine goes quiet, and\n * hand back the settled state together with the whole history.\n *\n * `handlers` is the same record the machine declares as its `interpret` (e.g.\n * `ask.handlers()` for a jev knob), so the test drives the real interpreter and\n * mocks only the port beneath it.\n *\n * One round is: fold every pending Msg, then await a handler for every Cmd\n * those folds emitted. A Msg a handler returns — or fires through its injected\n * `dispatch` — is pending for the next round. A machine that emits no Cmd for\n * its seed Msg therefore settles in ONE round and never awaits a handler at\n * all.\n *\n * The `ctx` handed to each handler is `opts.ctx` augmented with a NO-OP `emit`,\n * so a handler that emits to a `Port` runs without a live runtime; nothing here\n * observes ports. Supply your own `emit` on `ctx` to capture them.\n *\n * @throws {DriveRoundsExceededError} when the machine is still emitting work\n * after `opts.maxRounds` rounds. It never returns a half-driven state.\n * @throws whatever a handler rejects with, unchanged — annotated with the\n * partial trace, readable via {@link driveTraceOf}.\n */\nexport async function drive<\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 initial: S,\n msg: M,\n handlers: Interpret<M, C, Ctx>,\n ...[opts]: Record<never, never> extends DriveOptions<Ctx>\n ? [opts?: DriveOptions<Ctx>]\n : [opts: DriveOptions<Ctx>]\n): Promise<DriveResult<S, M, C>> {\n const options = (opts ?? {}) as { ctx?: Ctx; maxRounds?: number };\n const maxRounds = options.maxRounds ?? DEFAULT_MAX_ROUNDS;\n const bound = bindMachine(machine, options.ctx as Ctx);\n\n // A handler's ctx is `Ctx & RequirementsOf<C> & PortEmitter`. The Ctx half is\n // the caller's; the PortEmitter half is the kernel's, and a driven test has\n // no kernel — so a no-op `emit` stands in, placed FIRST so a caller's own\n // `emit` wins.\n const noopEmit: PortEmitter = { emit: () => {} };\n const handlerCtx = {\n ...noopEmit,\n ...(options.ctx as unknown as Record<string, unknown> | undefined),\n };\n\n // Indexed dynamically: `Interpret`'s mapped type already proved every Cmd\n // variant has a cell, but `cmd.type` is a union at the value level and TS\n // cannot correlate the two sides of that index.\n const cells = handlers as unknown as Record<\n string,\n | ((\n cmd: C,\n ctx: unknown,\n dispatch?: (msg: M) => void,\n // biome-ignore lint/suspicious/noConfusingVoidType: mirrors `Interpret`'s own cell return — a follow-up Msg, or nothing\n ) => Promise<M | void>)\n | undefined\n >;\n\n const trace: DriveTraceEntry<M, C>[] = [];\n let state = initial;\n let pending: M[] = [msg];\n let round = 0;\n\n while (pending.length > 0) {\n round += 1;\n if (round > maxRounds) {\n throw new DriveRoundsExceededError<M, C>(maxRounds, round, trace);\n }\n\n // Drain the round's Msgs first, THEN its Cmds. Swapping the buffer before\n // the fold is what keeps a settle Msg out of the round that produced it —\n // the ordering question every hand-rolled copy of this loop re-answers.\n const folding = pending;\n pending = [];\n const emitted: C[] = [];\n for (const next of folding) {\n trace.push({ kind: \"msg\", msg: next });\n const [advanced, cmds] = bound.step(state, next);\n state = advanced;\n emitted.push(...cmds);\n }\n\n for (const cmd of emitted) {\n trace.push({ kind: \"cmd\", cmd });\n const cell = cells[cmd.type];\n if (cell === undefined) {\n throw new DriveNoHandlerError<M, C>(cmd.type, trace);\n }\n // biome-ignore lint/suspicious/noConfusingVoidType: mirrors `Interpret`'s own cell return — a follow-up Msg, or nothing\n let settle: M | void;\n try {\n settle = await cell(cmd, handlerCtx, (fired) => {\n pending.push(fired);\n });\n } catch (err) {\n // Unswallowed: the handler's own error is what leaves `drive`, so a\n // test's `instanceof` / `_tag` branch still lands. The trace rides on\n // a non-enumerable property (see `driveTraceOf`).\n if (typeof err === \"object\" && err !== null) {\n Object.defineProperty(err, TRACE_KEY, {\n value: [...trace],\n enumerable: false,\n configurable: true,\n writable: true,\n });\n }\n throw err;\n }\n if (settle !== undefined) pending.push(settle);\n }\n }\n\n return { state, trace };\n}\n","// ---------------------------------------------------------------------------\n// noopRuntime — a Runtime<S, M>-shaped value whose every method is inert.\n//\n// The motivating callsite: a machine's `ctx` requires a sibling Runtime<S,\n// M> reference (e.g. the queue runtime in extension/lib/queue-machine\n// reaches into an `auditRuntime: Runtime<...>` slot on its ctx so its\n// interpret handlers can dispatch into the audit machine). When the test\n// replays such a machine, `replay` never actually invokes `interpret`, so\n// the runtime reference is never dereferenced — but the type system\n// still requires a value of `Runtime<S, M>` shape at the ctx slot. Tests\n// today work around this with a hand-rolled 12-line NOOP_AUDIT_RUNTIME\n// const cast through `as unknown as Runtime<...>`.\n//\n// `noopRuntime<S, M>()` is that hand-roll, named once. It returns a real\n// Runtime<S, M> value whose every method is a structurally-correct no-op:\n//\n// - `dispatch`: resolves immediately, never advances state.\n// - `getState`: returns the optional `initialState` argument (or a\n// deliberate `undefined` cast as S — the function lies about its\n// return type when no initial state is provided; this is the trade-off\n// we accept for an ergonomic test substrate).\n// - `subscribe` / `observe` / `subscribePort`: register the listener,\n// return a no-op unsubscribe. The listener is never fired because the\n// state never changes.\n// - `emitPort`: no-op.\n// - `ready`: a Promise that resolves to the no-op runtime itself (the #45\n// `ready: Promise<Runtime<S, M>>` shape — already booted, nothing to wait\n// for).\n// - `stop`: resolved Promise<void>.\n//\n// Strengthens invariant 9 (the testing surface is named and small).\n// ---------------------------------------------------------------------------\n\nimport type { Port, Runtime } from \"../index\";\n\n/**\n * Construct an inert `Runtime<S, M>` value. Use at ctx sites that require\n * a Runtime reference but where the test never invokes `interpret` (so\n * the runtime is never dereferenced in practice).\n *\n * @param opts.initialState Optional value returned by `getState()`. Omit\n * when the test never calls `getState()` on the no-op runtime — most\n * tests only need the type-level slot filled.\n */\nexport function noopRuntime<S, M extends { type: string }>(opts?: {\n initialState?: S;\n}): Runtime<S, M> {\n const initialState = opts?.initialState;\n // Single source of truth for the \"do-nothing\" unsubscribe so multiple\n // subscribe call sites share the same function instance — purely cosmetic\n // (the function would be a no-op either way).\n const noopUnsubscribe = (): void => {};\n const runtime: Runtime<S, M> = {\n async dispatch(_msg: M): Promise<void> {\n // Resolves immediately. State never advances; listeners never fire.\n // Quiescent by default (#50), but the no-op has no follow-up chain to\n // drain, so single-step and run-to-quiescence collapse to the same no-op.\n },\n async dispatchOnce(_msg: M): Promise<void> {\n // Single-step sibling of `dispatch` (#50). Same no-op for the no-op\n // runtime — there is no tail to leave in flight.\n },\n async idle(): Promise<void> {\n // No tail to drain — the no-op runtime never enqueues a follow-up.\n },\n result(): S | undefined {\n // The no-op runtime never advances, so it is never terminal (#46).\n return undefined;\n },\n done(): Promise<S> {\n // Never terminal → the awaitable never settles, matching `run()` with no\n // `terminal` predicate. Returned as a never-resolving promise.\n return new Promise<S>(() => {});\n },\n getState(): S {\n // Lie if no initial state was provided. The caller's contract is\n // \"you accept the lie because you know replay never invokes\n // interpret and therefore never reads this.\" When the caller DOES\n // pass an initialState the lie collapses to truth.\n return initialState as S;\n },\n subscribe(_listener: () => void): () => void {\n return noopUnsubscribe;\n },\n observe(_observer: (msg: M, state: S) => void): () => void {\n return noopUnsubscribe;\n },\n onBoot(_handler: (state: S) => void): () => void {\n // Boot never fires on the inert runtime — it is \"already booted\" with no\n // initial fanout, so the handler is registered and never called (#47).\n return noopUnsubscribe;\n },\n on<K extends never>(\n _type: K,\n _handler: (event: never) => void,\n ): () => void {\n // The no-op runtime's event surface is `never` (no `events` projector),\n // so `on` is structurally present but uncallable — there is no `K` to\n // pass. The body is unreachable; it returns the shared no-op unsubscribe.\n return noopUnsubscribe;\n },\n subscribePort<T>(\n _port: Port<T>,\n _listener: (value: T) => void,\n ): () => void {\n return noopUnsubscribe;\n },\n emitPort<T>(_port: Port<T>, _value: T): void {\n // No-op. No subscribers to fan out to; nothing to do.\n },\n // Assigned just below — `ready` must resolve to `runtime` itself, which\n // can't be referenced inside its own object literal.\n ready: undefined as unknown as Promise<Runtime<S, M>>,\n async stop(): Promise<void> {\n // Resolves immediately. No in-flight tail to drain, no subs to clean.\n },\n };\n // Already \"booted\" — `ready` hands back the same runtime synchronously.\n runtime.ready = Promise.resolve(runtime);\n return runtime;\n}\n","// ---------------------------------------------------------------------------\n// stateFactory — typed phase-constructor API for a discriminated-union State.\n//\n// The motivating callsite: every reducer test today opens with ~60–80 lines\n// of hand-rolled factory functions, one per phase, each one's defaults\n// duplicated across files:\n//\n// function idleState() { return { type: \"idle\" }; }\n// function creatingWindowState(overrides?: Partial<...>) {\n// return { type: \"creating_window\", auditId: ..., wsUrl: ..., ...overrides };\n// }\n// ...\n//\n// `stateFactory<BackgroundState>({...})` collapses the whole block to one\n// declaration: pass each phase's REQUIRED defaults once (the type system\n// enforces every phase has an entry), and the helper builds an API of\n// `factory.idle()`, `factory.creating_window({...})`, etc.\n//\n// Two type-level guarantees:\n//\n// 1. Every phase has a defaults entry — `StateFactoryDefaults<S>` is a\n// mapped type keyed by every `S[\"type\"]`. Missing an entry is a\n// compile error (the @ts-expect-error in testing.spec.ts pins this).\n//\n// 2. Each phase's defaults match that phase's required shape minus the\n// `type` discriminator. Passing wrong fields fails to compile.\n//\n// The runtime is pure data:\n//\n// api[k] = (overrides) => ({\n// type: k,\n// ...defaults[k],\n// ...stripUndefined(overrides ?? {}),\n// })\n//\n// The `stripUndefined` pass is what preserves `exactOptionalPropertyTypes`\n// assignability — without it, calling `factory.creating_window({\n// queueItemId: undefined })` would land an explicit `queueItemId: undefined`\n// on the object, which is NOT assignable to `queueItemId?: string` under\n// `exactOptionalPropertyTypes`. Stripping undefineds before spread keeps\n// the boundary clean.\n//\n// `stripUndefined` is inlined (not imported from a shared stdlib) so this\n// package can stay dep-free of stdlib.\n// ---------------------------------------------------------------------------\n\n/** A factory-constructed phase: `S` narrowed to the arm whose discriminator equals `K`. */\ntype StateOf<S, K> = Extract<S, { type: K }>;\n\n/** A factory-constructed phase with the `type` discriminator removed — the \"fields the caller cares about\" half. */\ntype RequiredFields<T> = Omit<T, \"type\">;\n\n/**\n * Defaults shape passed to `stateFactory`. Mapped type over the discriminant\n * set: every phase MUST have an entry, and that entry MUST match the phase's\n * required fields minus the `type` discriminator.\n */\nexport type StateFactoryDefaults<S extends { type: string }> = {\n readonly [K in S[\"type\"]]: RequiredFields<StateOf<S, K>>;\n};\n\n/**\n * The API returned by `stateFactory`. One method per phase; calling it with\n * no args returns the default snapshot, calling it with a partial overrides\n * object merges those overrides in (with undefineds stripped — see\n * stripUndefined below).\n */\nexport type StateFactoryAPI<S extends { type: string }> = {\n readonly [K in S[\"type\"]]: (\n overrides?: Partial<RequiredFields<StateOf<S, K>>>,\n ) => StateOf<S, K>;\n};\n\n/**\n * Strip own-enumerable properties whose value is `undefined`. Used inside\n * the factory's spread chain so callers can pass `{ queueItemId: undefined }`\n * without the explicit-undefined landing on the result object (which would\n * fail to assign to a `queueItemId?: string` field under\n * `exactOptionalPropertyTypes`).\n *\n * Inlined (not imported from `a shared stdlib`) so `@demlik/tea/testing` can stay\n * dependency-free of stdlib. The 8-line cost of duplication is cheaper than\n * a package-graph edge.\n */\nfunction stripUndefined<T extends object>(obj: T): Partial<T> {\n const out: Partial<T> = {};\n for (const key of Object.keys(obj) as (keyof T)[]) {\n const value = obj[key];\n if (value !== undefined) {\n out[key] = value;\n }\n }\n return out;\n}\n\n/**\n * Build a typed phase-constructor API from per-phase defaults. The defaults\n * object MUST have one entry per `S[\"type\"]` discriminant; the returned API\n * has one method per phase. Each method merges the defaults with optional\n * overrides (undefineds stripped), then stamps the `type` discriminator.\n *\n * @example\n * type S = { type: \"a\"; n: number } | { type: \"b\"; s: string };\n * const f = stateFactory<S>({ a: { n: 0 }, b: { s: \"\" } });\n * f.a(); // { type: \"a\", n: 0 }\n * f.a({ n: 42 }); // { type: \"a\", n: 42 }\n * f.b({ s: \"hi\" }); // { type: \"b\", s: \"hi\" }\n */\nexport function stateFactory<S extends { type: string }>(\n defaults: StateFactoryDefaults<S>,\n): StateFactoryAPI<S> {\n // Build the API by walking the defaults' own keys. Each key corresponds\n // to one phase discriminator; the constructor closes over both the key\n // (for the `type` stamp) and that phase's defaults snapshot.\n const api = {} as { [k: string]: (overrides?: object) => unknown };\n for (const key of Object.keys(\n defaults,\n ) as (keyof StateFactoryDefaults<S>)[]) {\n const phaseDefaults = defaults[key];\n api[key as string] = (overrides?: object) => {\n // The strip-undefined pass lives here, not at the caller. See the\n // module header for the `exactOptionalPropertyTypes` rationale.\n const cleanedOverrides = overrides ? stripUndefined(overrides) : {};\n return { type: key, ...phaseDefaults, ...cleanedOverrides };\n };\n }\n return api as StateFactoryAPI<S>;\n}\n"]}
1
+ {"version":3,"sources":["../../src/testing/assert-wrapper-faithful.ts","../../src/testing/assertions.ts","../../src/testing/bind-machine.ts","../../src/testing/drive.ts","../../src/testing/noop-runtime.ts","../../src/testing/state-factory.ts"],"names":["step","expect"],"mappings":";;;;AAiJO,SAAS,qBAAA,CAYd,IAAA,EACA,WAAA,EACA,IAAA,EACM;AACN,EAAA,MAAM,OAAA,GAAW,IAAA,CAAK,OAAA,IAAY,IAAA,CAAK,GAAA;AACvC,EAAA,MAAM,cAAc,IAAA,CAAK,IAAA;AACzB,EAAA,MAAM,UAAA,GACJ,KAAK,UAAA,KAAe,IAAA,CAAK,UAAU,IAAA,GAAQ,IAAA,CAAK,OAAO,IAAA,GAAa,IAAA,CAAA;AAStE,EAAA,MAAM,EAAA,GAAK,EAAE,GAAA,EAAK,GAAA,EAAW,KAAK,K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O,OAAA;AACT;;;ACpCA,SAAS,eAAiC,GAAA,EAAoB;AAC5D,EAAA,MAAM,MAAkB,EAAC;AACzB,EAAA,KAAA,MAAW,GAAA,IAAO,MAAA,CAAO,IAAA,CAAK,GAAG,CAAA,EAAkB;AACjD,IAAA,MAAM,KAAA,GAAQ,IAAI,GAAG,CAAA;AACrB,IAAA,IAAI,UAAU,MAAA,EAAW;AACvB,MAAA,GAAA,CAAI,GAAG,CAAA,GAAI,KAAA;AAAA,IACb;AAAA,EACF;AACA,EAAA,OAAO,GAAA;AACT;AAeO,SAAS,aACd,QAAA,EACoB;AAIpB,EAAA,MAAM,MAAM,EAAC;AACb,EAAA,KAAA,MAAW,OAAO,MAAA,CAAO,IAAA;AAAA,IACvB;AAAA,GACF,EAAwC;AACtC,IAAA,MAAM,aAAA,GAAgB,SAAS,GAAG,CAAA;AAClC,IAAA,GAAA,CAAI,GAAa,CAAA,GAAI,CAAC,SAAA,KAAuB;AAG3C,MAAA,MAAM,gBAAA,GAAmB,SAAA,GAAY,cAAA,CAAe,SAAS,IAAI,EAAC;AAClE,MAAA,OAAO,EAAE,IAAA,EAAM,GAAA,EAAK,GAAG,aAAA,EAAe,GAAG,gBAAA,EAAiB;AAAA,IAC5D,CAAA;AAAA,EACF;AACA,EAAA,OAAO,GAAA;AACT","file":"index.js","sourcesContent":["// ---------------------------------------------------------------------------\n// `assertWrapperFaithful` — the shared conformance gate for the wrapper tier.\n//\n// A `withX` wrapper bolts a cross-cutting concern (deadline, resilience) onto a base machine as an AUTHORING property — the base's source\n// never hand-wires it. The DANGER is the runtime betrayal: hiding wrapper state\n// in a closure, or silently swallowing / retiming a base Cmd, so the wrapper's\n// behavior is invisible to the reducer + Msg log. This helper is the binary\n// betrayal-detector every wrapper inherits. Pass = TEA-faithful, ship it.\n// Fail = betrayal, does not merge.\n//\n// It asserts, by `replay` (which composes `init` + `update` only — the\n// conformance path):\n//\n// 1. **Base behavior byte-identical.** `replay(wrapped).state.base` deep-\n// equals `replay(base).state`. The wrapper never alters base behavior.\n// 2. **Slice AND wrapper Cmds reconstruct under any ambient clock/RNG.**\n// Replaying the SAME msgs under a DIFFERENT global wall-clock + RNG yields\n// a deep-equal wrapper slice AND a deep-equal `$x:*` wrapper-Cmd subset —\n// BOTH halves of the wrapper's output (state slice + emitted Cmds) are a\n// pure function of the Msg log, NOT of `Date.now()` / `Math.random()`.\n// (`update` cells never receive `ctx`, so an impure update read reaches for\n// the GLOBAL ambient; stubbing two distinct ambients and comparing catches\n// a folded wall-clock read that two back-to-back replays under one ambient\n// would hide.) The slice comparison alone has a blind spot: a clock/RNG\n// read folded into a wrapper Cmd PAYLOAD (not the slice) leaves the slice\n// identical, so we ALSO compare the `$x:*` Cmds across the two ambients.\n// Legit time enters only as Msg `at` payloads, identical across replays.\n// 3. **Every wrapper decision is in the log.** At least one wrapper-tagged\n// Cmd (`$x:*`) or Msg appears in the replayed Cmd stream whenever there is\n// a transition — the wrapper's decisions are visible, not off-ledger.\n// PLUS a PER-TRANSITION check: at each step the bare machine's step-i Cmds\n// are an ordered subsequence of the wrapped machine's step-i Cmds, so a\n// base Cmd deferred to a LATER transition (intra-window retiming a\n// flattened subsequence would miss) surfaces as a step-level failure.\n// 4. **Slice is JSON-round-trip equal.** `$x` survives\n// `JSON.parse(JSON.stringify(...))` — durable across DO eviction / reload,\n// never a closure.\n//\n// Strengthens invariant 9 (the testing surface is named and small) and is the\n// mechanical CI form of the wrapper-tier conformance gate.\n// ---------------------------------------------------------------------------\n\nimport { expect, vi } from \"vitest\";\nimport { type Cmd, type Machine, replay, type Sub } from \"../index\";\n\n/**\n * The composed Model shape every `withX` wrapper produces: the base machine's\n * state nested under `base`, and the wrapper's own NAMED, serializable slice\n * under a single `$`-prefixed key. This helper does not care WHICH `$`-key the\n * wrapper uses — it discovers it structurally (the one non-`base` field).\n */\nexport type WrapperModel<S> = {\n readonly base: S;\n} & { readonly [K: `$${string}`]: unknown };\n\n/** Options for the conformance replay. Mirrors `replay`'s second argument. */\nexport interface AssertWrapperFaithfulOpts<S, WM, BaseM, BaseCtx, WrapperCtx> {\n /** The Msg sequence to fold through BOTH machines. Use the base's Msgs. */\n readonly msgs: readonly BaseM[];\n /** Ctx for the WRAPPED machine (base ctx + wrapper ports). */\n readonly ctx: WrapperCtx;\n /** Ctx for the BARE base machine. Defaults to `ctx` when omitted. */\n readonly baseCtx?: BaseCtx;\n /** Optional pre-`init` snapshot of the COMPOSED Model (wrapped rehydrate). */\n readonly loaded?: WM | null;\n /**\n * Optional pre-`init` snapshot of the BARE base state. Supply when the\n * wrapped `loaded` is non-null so the base-equivalence check rehydrates the\n * base machine from the matching nested slice. Defaults to `loaded?.base`.\n */\n readonly baseLoaded?: S | null;\n /**\n * Opt-in relaxation for an INTERCEPTING wrapper (e.g. a retry wrapper).\n *\n * DEFAULT (`undefined` / `false`) — the OBSERVE-ONLY contract that a\n * deadline wrapper satisfies: every bare base Cmd must appear\n * UNCHANGED, in order, as a subsequence of the wrapped Cmd stream (properties\n * 1 and 3b). The wrapper may APPEND its own Cmds but may NOT alter, drop, or\n * retime a base Cmd. This is the strict default and it is NOT weakened.\n *\n * WHEN SET — for a wrapper whose whole job is to INTERCEPT a chosen base Cmd\n * (retag it into a wrapper-owned carrier so the concern — cache / breaker /\n * rate-limit / retry — can gate it), a target base Cmd LEGITIMATELY does not\n * appear raw at the top level of the wrapped stream. The contract is still\n * **retag-and-re-emit, never swallow** (rule 2): the Cmd must be RECORDED, not\n * vanished. So when a bare base Cmd is ABSENT from the top-level wrapped\n * subsequence, this option accepts it IFF, in that SAME transition window, it\n * is recorded by the wrapper as one of:\n *\n * - the inner payload of a `$x:*` \"run\" carrier Cmd (`carrierCmdType` +\n * `innerField`) — the retag path; OR\n * - any other `$x:*` divergence Cmd whose `recordsField` deep-equals the\n * base Cmd — the gate/defer path (e.g. a \"fast-failed\" or \"deferred\"\n * record Cmd that carries the base Cmd it diverged on).\n *\n * A target base Cmd that is NEITHER present raw NOR recorded by any `$x:*`\n * Cmd in its window is a SWALLOW betrayal and still fails the gate.\n *\n * Provide the field names the carrier uses so the gate can unwrap it\n * structurally without hard-coding any one wrapper's vocabulary.\n */\n readonly intercepting?: InterceptingOpt;\n}\n\n/**\n * Configures the intercepting relaxation (see\n * `AssertWrapperFaithfulOpts.intercepting`). All fields name the carrier /\n * divergence shape so the gate can structurally find a retagged base Cmd\n * inside a `$x:*` Cmd. The gate only EVER inspects `$x:*`-prefixed wrapped\n * Cmds for a recorded base Cmd — it never relaxes the check for a base Cmd\n * that appears under any non-wrapper Cmd type.\n */\nexport interface InterceptingOpt {\n /**\n * The `Cmd.type` of the wrapper's run-carrier (e.g. `\"$resilience:run\"`).\n * A bare base Cmd that is retagged appears as `carrier[innerField]`.\n */\n readonly carrierCmdType: string;\n /** The field on the carrier Cmd that holds the original base Cmd. */\n readonly innerField: string;\n /**\n * OPTIONAL field on ANY OTHER `$x:*` Cmd that records a base Cmd the wrapper\n * gated/deferred without running it (e.g. a fast-fail record). When present\n * on a `$x:*` Cmd and deep-equal to the missing base Cmd, it counts as a\n * recorded divergence. Omit when the wrapper only ever retags via the\n * carrier.\n */\n readonly recordsField?: string;\n}\n\n/**\n * Assert a `withX` wrapper is TEA-faithful. Replays the wrapped machine and the\n * bare base machine over the same Msgs and checks the four conformance\n * properties (see file header).\n *\n * @param base the bare base `Machine`.\n * @param makeWrapped a thunk that wraps `base` and returns the composed machine\n * (e.g. `() => withTimeout(wired, cfg).machine`, where `wired.machine` is\n * `base`). A thunk — not the wrapped value — so a wrapper that registers\n * process-scoped ports (`definePort`) is constructed inside the assertion's\n * control, and so the same betrayal-detector reads as\n * `assertWrapperFaithful(wired.machine, () => withX(wired, cfg).machine, ...)`\n * at every wrapper's test site.\n * @param opts the conformance replay options.\n */\nexport function assertWrapperFaithful<\n S,\n BaseM extends { type: string },\n BaseC extends Cmd,\n BaseU extends Sub,\n BaseCtx,\n WM extends WrapperModel<S>,\n WrapperM extends { type: string },\n WrapperC extends Cmd,\n WrapperU extends Sub,\n WrapperCtx,\n>(\n base: Machine<S, BaseM, BaseC, BaseU, BaseCtx>,\n makeWrapped: () => Machine<WM, WrapperM, WrapperC, WrapperU, WrapperCtx>,\n opts: AssertWrapperFaithfulOpts<S, WM, BaseM, BaseCtx, WrapperCtx>,\n): void {\n const baseCtx = (opts.baseCtx ?? (opts.ctx as unknown as BaseCtx)) as BaseCtx;\n const wrappedMsgs = opts.msgs as unknown as readonly WrapperM[];\n const baseLoaded =\n opts.baseLoaded ?? (opts.loaded != null ? (opts.loaded.base as S) : null);\n\n // Two DISTINCT global ambients (wall-clock + RNG). `replay` composes only\n // `init` + `update`, and `update` cells are `(state, msg)` — they never\n // receive `ctx`. So an impure update read reaches for the GLOBAL `Date.now()`\n // / `Math.random()`, not an injected clock. Running the two determinism\n // replays under DIFFERENT ambients turns a folded wall-clock read into an\n // OBSERVABLE slice divergence (property 2) — a single fixed ambient (two\n // back-to-back replays) would return the same ms both times and hide it.\n const A0 = { now: 1_000_000, rng: 0.123 };\n const A1 = { now: 9_876_543, rng: 0.987 };\n\n // The bare baseline, `wrappedA`, and every per-transition baseline (props 3/4)\n // run under the SAME fixed ambient A0 so their cmds/state are deterministic.\n const bare = underAmbient(A0, () =>\n replay(base, { msgs: opts.msgs, ctx: baseCtx, loaded: baseLoaded }),\n );\n const wrapped = underAmbient(A0, () => makeWrapped());\n const wrappedA = underAmbient(A0, () =>\n replay(wrapped, {\n msgs: wrappedMsgs,\n ctx: opts.ctx,\n loaded: opts.loaded ?? null,\n }),\n );\n // The second determinism replay runs under a DISTINCT ambient A1. A faithful\n // wrapper's slice (a pure function of the Msg log) is identical under A0 and\n // A1; an impure update that folds `Date.now()` / `Math.random()` diverges.\n const wrappedB = underAmbient(A1, () =>\n replay(makeWrapped(), {\n msgs: wrappedMsgs,\n ctx: opts.ctx,\n loaded: opts.loaded ?? null,\n }),\n );\n\n // --- Property 1: base behavior byte-identical -----------------------------\n // `state.base` after wrapping === state after running the base alone. The\n // wrapper observes; it does not alter base behavior.\n expect(wrappedA.state.base).toEqual(bare.state);\n // The base's OWN Cmds appear in the wrapped Cmd stream unchanged: every bare\n // Cmd is present, in order, among the wrapped Cmds (with wrapper Cmds\n // interleaved). We assert the bare Cmds are a subsequence of the wrapped ones.\n // For an INTERCEPTING wrapper (`opts.intercepting` set) a target base Cmd is\n // accepted when it appears RETAGGED inside a `$x:*` carrier / recorded by a\n // `$x:*` divergence Cmd instead of raw — retag, not swallow.\n expectCmdSubsequence(bare.cmds, wrappedA.cmds, undefined, opts.intercepting);\n\n // --- Property 2: slice reconstructs under any ambient clock/RNG -----------\n // Replaying the same Msgs under a DIFFERENT global ambient yields a deep-equal\n // wrapper SLICE — the slice is a pure function of the Msg log, never of\n // `Date.now()` / `Math.random()`. We compare the single `$`-slice (not the\n // whole composed state) because comparing whole state would FALSE-POSITIVE\n // when the BASE machine reads the clock — that is the base's behavior, not the\n // wrapper's fault, and the wrapper's faithfulness is precisely what its own\n // slice records.\n const sliceKey = wrapperSliceKey(wrappedA.state);\n expect(\n sliceOf(wrappedB.state, sliceKey),\n `wrapper slice changed under a different ambient clock/RNG → update is ` +\n `reading Date.now()/Math.random(); time must enter only as Msg \\`at\\` data`,\n ).toEqual(sliceOf(wrappedA.state, sliceKey));\n\n // ...AND the wrapper-tagged Cmds reconstruct under any ambient too. The slice\n // is only HALF the wrapper's output — the other half is its emitted Cmds. A\n // wall-clock / RNG read folded into a wrapper Cmd PAYLOAD (not the state\n // slice) escapes the slice comparison above: the slice stays identical while\n // the Cmd carries a leaked `Date.now()` / `Math.random()`. So mirror the\n // slice check on the `$x:*` subset of the replayed Cmd stream — a faithful\n // wrapper emits Cmds that are a pure function of the Msg log, identical under\n // A0 and A1. Only Msg `at` payloads (identical across both replays) may carry\n // time; if a wrapper Cmd diverges between ambients, the wrapper read the\n // ambient clock/RNG into a Cmd. (Base Cmds are EXCLUDED — a base machine that\n // reads the clock is the base's behavior, not the wrapper's, exactly as the\n // slice comparison excludes whole-state.)\n const wrapperFamily = `${sliceKey}:`;\n const wrapperCmdsA = wrappedA.cmds.filter((c) =>\n c.type.startsWith(wrapperFamily),\n );\n const wrapperCmdsB = wrappedB.cmds.filter((c) =>\n c.type.startsWith(wrapperFamily),\n );\n expect(\n wrapperCmdsB,\n `wrapper Cmds (\"${wrapperFamily}*\") changed under a different ambient ` +\n `clock/RNG → a wrapper Cmd PAYLOAD is reading Date.now()/Math.random(); ` +\n `wrapper Cmds must be a pure function of the Msg log, time entering only ` +\n `as Msg \\`at\\` data`,\n ).toEqual(wrapperCmdsA);\n\n // --- Property 3: every wrapper decision appears as an XMsg/XCmd in the log -\n // The composed Model's wrapper slice is the single non-`base` `$`-key. We\n // discover its key family (`$deadline` → `$deadline:*`) and require that,\n // whenever there is at least one transition, the replayed Cmd stream carries\n // at least one wrapper-tagged Cmd. (Wrappers whose decisions are Msgs route\n // them through the SAME log; for a Cmd-emitting wrapper the decision is its\n // `$x:*` Cmd.) A wrapper that performed its work off-ledger\n // would have an EMPTY wrapper-Cmd set here despite real transitions — the\n // exact betrayal this gate exists to catch.\n if (opts.msgs.length > 0) {\n expect(\n wrapperCmdsA.length,\n `expected at least one \"${wrapperFamily}*\" wrapper-decision Cmd in the replay log ` +\n `(found none across ${opts.msgs.length} transition(s)) — a wrapper whose ` +\n `decisions are invisible to the Msg/Cmd log has betrayed total visibility`,\n ).toBeGreaterThan(0);\n }\n\n // --- Property 3b: per-transition Cmd subsequence --------------------------\n // The flattened subsequence (property 1) misses INTRA-WINDOW retiming — a\n // base Cmd that a saga-style wrapper DEFERS to a later transition still drains\n // within the replay, so the flattened bare-Cmd set stays an ordered\n // subsequence and slips through. Pin it per step: for each transition i, the\n // bare machine's step-i Cmds must be an ordered subsequence of the wrapped\n // machine's step-i Cmds. A deferred base Cmd is then visible as a step-i\n // subsequence failure (it shows up at i+1 in the wrapped run but at i in the\n // bare run). Prefix replays run under the fixed ambient A0 for determinism.\n for (let i = 0; i < opts.msgs.length; i++) {\n const bareStep = stepCmds(\n () =>\n underAmbient(A0, () =>\n replay(base, {\n msgs: opts.msgs.slice(0, i),\n ctx: baseCtx,\n loaded: baseLoaded,\n }),\n ).cmds,\n () =>\n underAmbient(A0, () =>\n replay(base, {\n msgs: opts.msgs.slice(0, i + 1),\n ctx: baseCtx,\n loaded: baseLoaded,\n }),\n ).cmds,\n );\n const wrappedStep = stepCmds(\n () =>\n underAmbient(A0, () =>\n replay(wrapped, {\n msgs: wrappedMsgs.slice(0, i),\n ctx: opts.ctx,\n loaded: opts.loaded ?? null,\n }),\n ).cmds,\n () =>\n underAmbient(A0, () =>\n replay(wrapped, {\n msgs: wrappedMsgs.slice(0, i + 1),\n ctx: opts.ctx,\n loaded: opts.loaded ?? null,\n }),\n ).cmds,\n );\n expectCmdSubsequence(bareStep, wrappedStep, i, opts.intercepting);\n }\n\n // --- Property 4: slice is JSON-round-trip equal ---------------------------\n // The wrapper slice survives JSON.parse(JSON.stringify(...)) — durable across\n // DO eviction / reload, never a closure.\n const slice = sliceOf(wrappedA.state, sliceKey);\n expect(JSON.parse(JSON.stringify(slice))).toEqual(slice);\n}\n\n/**\n * Run `fn` with the GLOBAL `Date.now` and `Math.random` stubbed to fixed\n * values, restoring them in a `finally` so the stub never leaks across\n * assertions or tests. `update` cells receive no `ctx`, so an impure read\n * inside one resolves to these globals — the lever this gate pulls to make a\n * folded wall-clock / RNG read observable in the wrapper slice.\n */\nfunction underAmbient<T>(\n ambient: { readonly now: number; readonly rng: number },\n fn: () => T,\n): T {\n const nowSpy = vi.spyOn(Date, \"now\").mockReturnValue(ambient.now);\n const rngSpy = vi.spyOn(Math, \"random\").mockReturnValue(ambient.rng);\n try {\n return fn();\n } finally {\n nowSpy.mockRestore();\n rngSpy.mockRestore();\n }\n}\n\n/** The wrapper slice value (the single `$`-key) on a composed Model. */\nfunction sliceOf(model: object, sliceKey: string): unknown {\n return (model as Record<string, unknown>)[sliceKey];\n}\n\n/**\n * The Cmds a single transition `i` emitted: the suffix of the cmds after\n * `msgs.slice(0, i+1)` past the cmds after `msgs.slice(0, i)`. Cmds accumulate\n * in order across `replay`, so the longer run is a prefix-extension of the\n * shorter one and the suffix is exactly step `i`'s contribution.\n */\nfunction stepCmds(\n prefixCmds: () => readonly Cmd[],\n throughCmds: () => readonly Cmd[],\n): readonly Cmd[] {\n const before = prefixCmds();\n const after = throughCmds();\n return after.slice(before.length);\n}\n\n/**\n * The wrapper slice key on a composed Model — the single own enumerable field\n * whose name starts with `$`. Throws if zero or more than one is found, because\n * the wrapper-tier contract is exactly one named `$`-slice per wrapper.\n */\nfunction wrapperSliceKey(model: object): string {\n const dollarKeys = Object.keys(model).filter((k) => k.startsWith(\"$\"));\n if (dollarKeys.length !== 1) {\n throw new Error(\n `assertWrapperFaithful: expected exactly one \"$\"-prefixed wrapper slice ` +\n `on the composed Model, found ${dollarKeys.length} (${dollarKeys.join(\", \") || \"none\"}). ` +\n `Every withX wrapper owns exactly one named slice (e.g. \"$deadline\").`,\n );\n }\n // biome-ignore lint/style/noNonNullAssertion: length checked to be exactly 1 above\n return dollarKeys[0]!;\n}\n\n/**\n * Assert `needle` is an (order-preserving) subsequence of `haystack` by deep\n * equality — every base Cmd appears, in order, somewhere in the wrapped Cmd\n * stream (wrapper Cmds may be interleaved). This is the \"base Cmds pass through\n * UNCHANGED\" check that tolerates the wrapper's own appended Cmds without\n * requiring an exact-equal stream. When `step` is supplied the message names\n * the transition index, so a per-transition retiming failure points at the\n * exact step a base Cmd was deferred away from.\n *\n * `intercepting` (default `undefined` → the strict OBSERVE-ONLY check above)\n * relaxes the match for a base Cmd that an INTERCEPTING wrapper retags: when a\n * needle Cmd is NOT found raw in `haystack`, it is accepted IFF some `$x:*`\n * wrapper Cmd in `haystack` RECORDS it — as the carrier's `innerField` payload\n * (retag) or another `$x:*` Cmd's `recordsField` (recorded gate/defer). The\n * relaxation ONLY ever looks inside `$x:*` Cmds, so a base Cmd that vanished\n * with no `$x:*` record still fails. The order check is preserved: the carrier\n * / divergence Cmd must come at or after the cursor, exactly like a raw match.\n */\nfunction expectCmdSubsequence(\n needle: readonly Cmd[],\n haystack: readonly Cmd[],\n step?: number,\n intercepting?: InterceptingOpt,\n): void {\n let i = 0;\n for (const cmd of haystack) {\n if (i >= needle.length) break;\n if (__deepEqual(needle[i], cmd)) {\n i++;\n continue;\n }\n // Intercepting relaxation: the base Cmd at the cursor may legitimately be\n // absent raw because the wrapper RETAGGED it. Accept this haystack Cmd as\n // the matching slot IFF it is a `$x:*` wrapper Cmd that records `needle[i]`.\n if (\n intercepting !== undefined &&\n recordsBaseCmd(cmd, needle[i] as Cmd, intercepting)\n ) {\n i++;\n }\n }\n const where =\n step === undefined\n ? \"the wrapped Cmd stream\"\n : `the wrapped Cmd stream AT TRANSITION ${step} (a base Cmd deferred to a ` +\n `later transition is an intra-window retiming betrayal)`;\n const swallowHint =\n intercepting === undefined\n ? \"a missing/rewritten/retimed base Cmd is a swallow betrayal\"\n : `an intercepting wrapper must RETAG each target base Cmd into a ` +\n `\"${intercepting.carrierCmdType}\" carrier (inner field ` +\n `\"${intercepting.innerField}\") or record it on a \"$*:\" divergence Cmd ` +\n `— a base Cmd neither present raw NOR recorded by any \"$*:\" Cmd is a ` +\n `swallow betrayal`;\n expect(\n i,\n `expected every base Cmd to pass through unchanged (matched ${i} of ` +\n `${needle.length} base Cmds as an ordered subsequence of ${where}) — ` +\n `${swallowHint}`,\n ).toBe(needle.length);\n}\n\n/**\n * Does the wrapped Cmd `cmd` RECORD the base Cmd `baseCmd` under the\n * intercepting contract? True iff `cmd` is a `$`-prefixed wrapper Cmd AND\n * either:\n * - `cmd.type === carrierCmdType` and `cmd[innerField]` deep-equals\n * `baseCmd` (the retag carrier), OR\n * - `recordsField` is configured and `cmd[recordsField]` deep-equals\n * `baseCmd` (a recorded gate/defer divergence on any `$x:*` Cmd).\n *\n * The `$`-prefix guard is load-bearing: the relaxation must NEVER accept a base\n * Cmd hidden inside a NON-wrapper Cmd — that would let a wrapper launder a\n * swallowed base Cmd through an arbitrary re-emit. Only the wrapper's own\n * `$x:*` family may carry a retagged base Cmd.\n */\nfunction recordsBaseCmd(cmd: Cmd, baseCmd: Cmd, opt: InterceptingOpt): boolean {\n if (!cmd.type.startsWith(\"$\")) return false;\n const rec = cmd as unknown as Record<string, unknown>;\n if (\n cmd.type === opt.carrierCmdType &&\n __deepEqual(rec[opt.innerField], baseCmd)\n )\n return true;\n if (\n opt.recordsField !== undefined &&\n __deepEqual(rec[opt.recordsField], baseCmd)\n )\n return true;\n return false;\n}\n\n/**\n * Structural deep equality for plain Cmd data.\n *\n * NOT `JSON.stringify` equality: `JSON.stringify` DROPS undefined-valued fields,\n * so `{ type: \"x\" }` would falsely equal `{ type: \"x\", foo: undefined }` and the\n * gate could accept a wrapper that smuggles an extra (undefined) field into a\n * \"byte-identical\" base Cmd or a retag carrier. This walk distinguishes an\n * ABSENT key from an `undefined`-VALUED key by comparing the full own-enumerable\n * key SET (not just the defined values) in both directions, then recursing.\n *\n * Cmds are plain data — primitives, `null`, arrays, and plain objects — so this\n * intentionally does not model `Date`, `Map`, `Set`, cycles, or class instances.\n *\n * Exported under the `__` test-only convention so the conformance suite can\n * pin the absent-vs-undefined distinction directly. Not part of the public API.\n *\n * @internal test-only\n */\nexport function __deepEqual(a: unknown, b: unknown): boolean {\n if (Object.is(a, b)) return true;\n\n // Past the identity check, equality requires same kind on both sides. Anything\n // non-object (primitive, function, symbol) that wasn't `Object.is`-equal above\n // is unequal. `null` is `typeof \"object\"` but only equals `null` (caught by\n // `Object.is`), so screen it out explicitly.\n if (\n typeof a !== \"object\" ||\n typeof b !== \"object\" ||\n a === null ||\n b === null\n ) {\n return false;\n }\n\n const aIsArray = Array.isArray(a);\n if (aIsArray !== Array.isArray(b)) return false;\n\n if (aIsArray) {\n const bArr = b as unknown[];\n if (a.length !== bArr.length) return false;\n for (let i = 0; i < a.length; i++) {\n if (!__deepEqual(a[i], bArr[i])) return false;\n }\n return true;\n }\n\n // Plain objects: compare the own-enumerable key SET first so a key present on\n // one side with an `undefined` value (and absent on the other) is caught —\n // the betrayal `JSON.stringify` hid. Then recurse on every value.\n const aRec = a as Record<string, unknown>;\n const bRec = b as Record<string, unknown>;\n const aKeys = Object.keys(aRec);\n const bKeys = Object.keys(bRec);\n if (aKeys.length !== bKeys.length) return false;\n for (const key of aKeys) {\n if (!Object.hasOwn(bRec, key)) return false;\n if (!__deepEqual(aRec[key], bRec[key])) return false;\n }\n return true;\n}\n","// ---------------------------------------------------------------------------\n// Test-side assertions over `replay`. Each helper composes the replay call\n// with a single `expect(...)` so consumers stop hand-rolling the 5-line\n// \"destructure { state, cmds } → expect.toBe / toEqual / toContainEqual\"\n// boilerplate at every test site.\n//\n// Each helper is a thin wrapper that:\n// 1. Calls `replay(machine, opts)` once.\n// 2. Pipes the result into a single vitest `expect(...)` matcher.\n//\n// All helpers return `void` — assertions throw on failure (vitest contract).\n// No mutation of the machine or opts. Pure test ergonomics.\n//\n// Type-inference note: each helper anchors its generic parameters to the\n// `machine` argument. The `expected` (and `opts.msgs`) arguments are wrapped\n// in `NoInfer<...>` so they do NOT participate in inference — otherwise a\n// `[]`-shaped `expected` would force `C = never` and reject a machine whose\n// real Cmd union is non-empty. Anchoring inference to the machine is the\n// same discipline `replay` uses (it has nothing but the machine and opts).\n//\n// Strengthens invariant 9 (the testing surface is named, small, and forks\n// nothing of the substrate's purity guarantees).\n// ---------------------------------------------------------------------------\n\nimport { expect } from \"vitest\";\nimport { type Cmd, type Machine, replay, type Sub } from \"../index\";\n\n// `NoInfer<T>` is the built-in TypeScript 5.4+ intrinsic that blocks\n// inference from a generic parameter at a position. We use it on `expected`\n// and `opts` so inference flows purely FROM the machine — `[]`-shaped\n// `expected` no longer drags `C` down to `never` and rejects the machine.\n\n/**\n * Shared options shape for every test assertion below. Mirrors the\n * second argument of `replay(machine, opts)` — `msgs` is the sequence to\n * fold over (may be empty for init-only assertions), `ctx` is the\n * substrate-required ctx value, `loaded` is the optional pre-`init`\n * snapshot (omit / pass `null` for fresh boot).\n */\nexport interface ReplayOpts<S, M, Ctx> {\n readonly msgs: readonly M[];\n readonly ctx: Ctx;\n readonly loaded?: S | null;\n}\n\n/**\n * Assert the final state after replaying `opts.msgs` equals `expected`.\n * Replaces the boilerplate:\n *\n * const { state } = replay(machine, opts);\n * expect(state).toEqual(expected);\n *\n * Uses `toEqual` (deep structural). For type-narrowing assertions that\n * branch on `state.type` afterwards, fall back to plain `replay` —\n * `expectFinalState` is the \"exact match\" tool.\n */\nexport function expectFinalState<\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: NoInfer<ReplayOpts<S, M, Ctx>>,\n expected: NoInfer<S>,\n): void {\n const { state } = replay(machine, opts);\n expect(state).toEqual(expected);\n}\n\n/**\n * Assert that `cmd` appears at least once in the cmds array produced by\n * replaying `opts.msgs`. Uses `toContainEqual` (deep structural). Order\n * and surrounding cmds are not asserted — use `expectCmdSequence` for\n * exact ordered match.\n *\n * Replaces:\n *\n * const { cmds } = replay(machine, opts);\n * expect(cmds).toContainEqual(cmd);\n */\nexport function expectCmdEmitted<\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: NoInfer<ReplayOpts<S, M, Ctx>>,\n cmd: NoInfer<C>,\n): void {\n const { cmds } = replay(machine, opts);\n expect(cmds).toContainEqual(cmd);\n}\n\n/**\n * Assert the exact ordered sequence of cmds emitted by replaying\n * `opts.msgs`. Uses `toEqual` against the full cmds array — extra cmds\n * fail the assertion, missing cmds fail the assertion, wrong order\n * fails the assertion.\n *\n * Replaces:\n *\n * const { cmds } = replay(machine, opts);\n * expect(cmds).toEqual(expected);\n */\nexport function expectCmdSequence<\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: NoInfer<ReplayOpts<S, M, Ctx>>,\n expected: NoInfer<readonly C[]>,\n): void {\n const { cmds } = replay(machine, opts);\n expect(cmds).toEqual(expected);\n}\n\n/**\n * Assert the exact set of subs desired at the final state after\n * replaying `opts.msgs`. Uses `toEqual` against the full subs array.\n *\n * Replaces:\n *\n * const { subs } = replay(machine, opts);\n * expect(subs).toEqual(expected);\n */\nexport function expectActiveSubs<\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: NoInfer<ReplayOpts<S, M, Ctx>>,\n expected: NoInfer<readonly U[]>,\n): void {\n const { subs } = replay(machine, opts);\n expect(subs).toEqual(expected);\n}\n\n/**\n * Single-msg step helper — feeds `loaded → msg → next state + cmds emitted by\n * that msg`. Returns a readonly tuple in the shape consumers used before the\n * substrate (`[state, cmds]`), so existing tests that destructure with\n * `[next, cmds]` can swap `reduce(state, msg)` for `step(machine, state, msg,\n * ctx)` without changing the assertion code.\n *\n * Internally a `replay` call with `loaded: prevState` and a single-element\n * `msgs` array. The cmds returned are exactly the cmds emitted by THIS msg\n * (init emits no cmds when `loaded` is provided, so the slice is the entire\n * array).\n *\n * Use when consumers want to walk a machine one msg at a time and assert per\n * step. For one-shot \"final state after N msgs\" assertions, prefer\n * `expectFinalState`.\n */\nexport function step<\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 loaded: NoInfer<S>,\n msg: NoInfer<M>,\n ctx: NoInfer<Ctx>,\n): readonly [S, readonly C[]] {\n const { state, cmds } = replay(machine, { msgs: [msg], ctx, loaded });\n return [state, cmds] as const;\n}\n","// ---------------------------------------------------------------------------\n// `bindMachine(machine, ctx)` — bound test harness over the free-function\n// assertions in `./assertions.ts`. Closes over the `machine` and `ctx` once\n// so per-test callsites stop repeating both at every invocation.\n//\n// Why this exists: every consumer test file ends up hand-rolling a local\n// two-arg `step(state, msg)` wrapper around `step(machine, state, msg, ctx)`,\n// and the four `expect*` assertions repeat `machine` + `ctx` at every\n// callsite. The bound form pulls both into one place and gives every\n// per-test call its tightest possible shape (2-arg max).\n//\n// `bindMachine` is built ON TOP of the free helpers — it does not replace\n// them. Both forms coexist; pick the one that fits the call site:\n//\n// - Free form → one-off call inside a helper that isn't bound to one\n// machine (e.g. cross-machine integration test).\n// - Bound form → a `describe` block runs many assertions against one\n// machine + ctx. The bound form is the common case.\n//\n// Strengthens invariant 9 (the testing surface is named, small, and forks\n// nothing of the substrate's purity guarantees).\n// ---------------------------------------------------------------------------\n\nimport { expect } from \"vitest\";\nimport {\n type BuiltinSub,\n type Cmd,\n type Machine,\n replay,\n type Sub,\n} from \"../index\";\n\n/**\n * Replay options shape used by every bound method. `ctx` is captured by\n * `bindMachine`; the per-call opts only need `msgs` and an optional\n * `loaded` snapshot. (Compare `ReplayOpts` in `./assertions.ts`, which\n * still takes `ctx` because the free helpers cannot capture it.)\n */\ninterface BoundOpts<S, M> {\n readonly msgs: readonly M[];\n readonly loaded?: S | null;\n}\n\n/**\n * The bound testing surface. Every method is 2-arg max — `ctx` and\n * `machine` are captured by `bindMachine`.\n *\n * `NoInfer<...>` on `expected` / `cmd` arguments mirrors the discipline\n * the free helpers use (see `./assertions.ts`): inference flows purely\n * FROM the machine, so a `[]`-shaped expected does not drag `C` down to\n * `never` and reject the machine.\n */\nexport interface BoundMachine<\n S,\n M extends { type: string },\n C extends Cmd,\n U extends Sub,\n // `Ctx` is a phantom-style parameter — present for consumers that want to\n // spell `BoundMachine<S, M, C, U, Ctx>` explicitly, mirroring `Machine`.\n // biome-ignore lint/correctness/noUnusedVariables: phantom type param (see above)\n Ctx,\n> {\n /**\n * Single-msg step — feeds `loaded → msg → [next state, cmds emitted by\n * that msg]`. Mirrors the free `step(machine, loaded, msg, ctx)`.\n */\n step(loaded: S, msg: M): readonly [S, readonly C[]];\n /**\n * Assert the final state after replaying `opts.msgs` deep-equals\n * `expected`. Mirrors the free `expectFinalState(machine, opts, expected)`.\n */\n expectFinalState(opts: BoundOpts<S, M>, expected: NoInfer<S>): void;\n /**\n * Assert `cmd` appears at least once in the emitted cmd list. Order is\n * not asserted. Mirrors the free `expectCmdEmitted(machine, opts, cmd)`.\n */\n expectCmdEmitted(opts: BoundOpts<S, M>, cmd: NoInfer<C>): void;\n /**\n * Assert the exact ordered sequence of cmds emitted by replaying\n * `opts.msgs`. Mirrors the free `expectCmdSequence(machine, opts, expected)`.\n */\n expectCmdSequence(\n opts: BoundOpts<S, M>,\n expected: readonly NoInfer<C>[],\n ): void;\n /**\n * Assert the exact set of subs desired at the final state. Mirrors the\n * free `expectActiveSubs(machine, opts, expected)`.\n */\n expectActiveSubs(\n opts: BoundOpts<S, M>,\n expected: readonly NoInfer<U | BuiltinSub<M>>[],\n ): void;\n /**\n * Bound `replay` — returns `{ state, cmds, subs }` for the given opts.\n * Use for the \"narrow-then-assert\" pattern where the test inspects a\n * specific field after `state.type === \"...\"` discrimination.\n */\n replay(opts: BoundOpts<S, M>): {\n state: S;\n cmds: readonly C[];\n subs: readonly (U | BuiltinSub<M>)[];\n };\n}\n\n/**\n * Bind a machine + ctx into a small bag of 2-arg helpers. Each method\n * delegates to `replay(machine, { ...opts, ctx })` and pipes the result\n * through a single `expect(...)` matcher (or returns the raw tuple, for\n * `step` and `replay`).\n *\n * Use one bind per `describe` block (or per file) when many assertions\n * share the same machine + ctx. For one-off cross-machine calls, stick\n * with the free helpers from `./assertions.ts`.\n */\nexport function bindMachine<\n S,\n M extends { type: string },\n C extends Cmd,\n U extends Sub,\n Ctx,\n>(machine: Machine<S, M, C, U, Ctx>, ctx: Ctx): BoundMachine<S, M, C, U, Ctx> {\n return {\n step(loaded, msg) {\n const { state, cmds } = replay(machine, { msgs: [msg], ctx, loaded });\n return [state, cmds] as const;\n },\n expectFinalState(opts, expected) {\n const { state } = replay(machine, { ...opts, ctx });\n expect(state).toEqual(expected);\n },\n expectCmdEmitted(opts, cmd) {\n const { cmds } = replay(machine, { ...opts, ctx });\n expect(cmds).toContainEqual(cmd);\n },\n expectCmdSequence(opts, expected) {\n const { cmds } = replay(machine, { ...opts, ctx });\n expect(cmds).toEqual(expected);\n },\n expectActiveSubs(opts, expected) {\n const { subs } = replay(machine, { ...opts, ctx });\n expect(subs).toEqual(expected);\n },\n replay(opts) {\n return replay(machine, { ...opts, ctx });\n },\n };\n}\n","// ---------------------------------------------------------------------------\n// `drive(machine, initial, msg, handlers, opts)` — the runtime's own loop,\n// said once, for a test.\n//\n// `bindMachine` hands back the Cmds a fold emitted and stops there; performing\n// them is the caller's. So every consumer test that exercises a Cmd-emitting\n// machine hand-writes the same fixture: step the Msg, await the real interpret\n// handler over each emitted Cmd, feed the settle Msg back, repeat until quiet,\n// with a hand-picked guard bound in the loop header. The guard count, the\n// accumulate-then-swap order and the \"did I drain this round before starting\n// the next\" question are re-decided at every copy site, and one of those copies\n// ships in `docs/how-to/ask-jev-a-typed-question.md`.\n//\n// `drive` is that fixture as one call. It composes `bindMachine`'s synchronous\n// 2-arg `step` and adds NO second reducer path — there is no `Runtime` here, no\n// observation, no clock, and nothing borrowed from the internal flow helpers.\n// The only impure thing it does is `await` the handler the caller handed it.\n//\n// **It returns the history, not just the endpoint.** `{ state, trace }`, where\n// `trace` is every Msg folded and every Cmd dispatched in order, is what makes\n// this worth a stable export rather than a snippet: a test asserts on the\n// SEQUENCE as well as the settled state — which handler ran, in which round,\n// and what came back — and the same trace's Msgs replayed through `replay` from\n// the same initial state reproduce the returned state exactly.\n//\n// Prior art converged on the same answer: Temporal's `TestWorkflowEnvironment`\n// hands a test the event history rather than the final result, and Effect's\n// `TestClock` runs make the effect log inspectable rather than opaque.\n//\n// **Exhausting `maxRounds` THROWS.** A driver that quietly returns a\n// half-driven state lets a test assert green on a machine that never settled —\n// the exact failure a hand-rolled `guard < 10` already risks.\n//\n// Strengthens invariant 9 (the testing surface is named and small).\n// ---------------------------------------------------------------------------\n\nimport {\n type Cmd,\n type CtxArg,\n type Interpret,\n type Machine,\n Outcome,\n type PortEmitter,\n type Sub,\n} from \"../index\";\nimport { cmdEdge, cmdEdgeOver } from \"../pure/core\";\nimport { bindMachine } from \"./bind-machine\";\n\n/**\n * The default round bound when `opts.maxRounds` is omitted: **100**.\n *\n * A round is one drain of the pending Msgs plus one drain of the Cmds those\n * folds emitted, so a settling machine costs a handful; 100 is loose enough\n * that a legitimate retry ladder finishes inside it and tight enough that a\n * genuine cycle stops rather than hangs.\n */\nexport const DEFAULT_MAX_ROUNDS = 100;\n\n/**\n * One entry of a driven run's history, in dispatch order.\n *\n * - `msg` — a Msg folded through the machine's reducer. The seed Msg is the\n * first entry of every trace; every later one is a settle Msg a handler\n * returned (or fired through its injected `dispatch`).\n * - `cmd` — a Cmd handed to an interpret handler. It is recorded BEFORE the\n * handler is awaited, so a trace recovered from a rejected handler names the\n * Cmd that rejected as its last entry.\n */\nexport type DriveTraceEntry<M, C> =\n | { readonly kind: \"msg\"; readonly msg: M }\n | { readonly kind: \"cmd\"; readonly cmd: C };\n\n/** What a settled {@link drive} hands back. */\nexport interface DriveResult<S, M, C> {\n /** The state after the machine went quiet — no Msg pending, no Cmd unperformed. */\n readonly state: S;\n /**\n * Every Msg folded and every Cmd dispatched, in order. Filtering it to its\n * `msg` entries and replaying those through `replay` from the same initial\n * state reproduces {@link DriveResult.state}.\n */\n readonly trace: readonly DriveTraceEntry<M, C>[];\n}\n\n/**\n * {@link drive}'s `ctx` field. `CtxArg` widened by exactly one case: a machine\n * declaring `ctx: undefined` in its `types` block — the pure shape every\n * how-to on this package writes — may omit it too. `CtxArg` alone keeps `ctx`\n * REQUIRED there, because `{}` is not assignable to `undefined`, which would\n * make the common pure call site spell `{ ctx: undefined }` to say nothing.\n * A machine whose `Ctx` carries a field a handler reads still requires it.\n */\nexport type DriveCtxArg<Ctx> = [undefined] extends [Ctx]\n ? { readonly ctx?: Ctx }\n : CtxArg<Ctx>;\n\n/**\n * {@link drive}'s options. `ctx` is conditionally optional (see\n * {@link DriveCtxArg}).\n */\nexport type DriveOptions<Ctx> = DriveCtxArg<Ctx> & {\n /**\n * The round bound. Exceeding it throws {@link DriveRoundsExceededError};\n * `drive` never returns a half-driven state. Defaults to\n * {@link DEFAULT_MAX_ROUNDS} (100).\n */\n readonly maxRounds?: number;\n /**\n * The clock that stamps `at` on a `Cmd.define`d Cmd's minted `_ok` / `_err`\n * Msg — the one `run` takes. Defaults to `Date.now`; pin it for a test that\n * asserts on `at`.\n */\n readonly clock?: () => number;\n};\n\n/**\n * Raised when a driven machine is still emitting work after `maxRounds` rounds.\n * Follows the tea error dialect (`override readonly name`) and carries a `_tag`\n * discriminant, so a test branches on it by `instanceof` or on the tag.\n *\n * It carries the round count it stopped at and the PARTIAL trace up to that\n * point, which is what a test needs to see the cycle — the bound alone says\n * only that one exists.\n */\nexport class DriveRoundsExceededError<M, C> extends Error {\n override readonly name = \"DriveRoundsExceededError\";\n readonly _tag = \"DriveRoundsExceededError\" as const;\n constructor(\n /** The bound that was exceeded. */\n public readonly maxRounds: number,\n /** The round the driver stopped at — always `maxRounds + 1`. */\n public readonly rounds: number,\n /** Every Msg folded and Cmd dispatched before the driver gave up. */\n public readonly trace: readonly DriveTraceEntry<M, C>[],\n ) {\n super(\n `@demlik/tea: drive did not settle within ${maxRounds} round(s) — the ` +\n `machine was still emitting work at round ${rounds}. The partial ` +\n `trace (${trace.length} entr${trace.length === 1 ? \"y\" : \"ies\"}) is ` +\n `on the error's \\`trace\\` field.`,\n );\n }\n}\n\n/**\n * Raised when a Cmd reaches {@link drive} with no handler for its `type` in the\n * `handlers` record. `Interpret`'s mapped type makes that a compile error at a\n * well-typed call site; this is the runtime arm for a handler record assembled\n * dynamically or cast.\n */\nexport class DriveNoHandlerError<M, C> extends Error {\n override readonly name = \"DriveNoHandlerError\";\n readonly _tag = \"DriveNoHandlerError\" as const;\n constructor(\n /** The Cmd `type` nothing in the handler record answered. */\n public readonly cmdType: string,\n /** Every Msg folded and Cmd dispatched before the miss. */\n public readonly trace: readonly DriveTraceEntry<M, C>[],\n ) {\n super(\n `@demlik/tea: drive found no interpret handler for Cmd type ` +\n `\"${cmdType}\" — the handlers record must answer every Cmd the ` +\n `machine emits.`,\n );\n }\n}\n\n/** The key `drive` hangs a partial trace off a rejected handler's error under. */\nconst TRACE_KEY = \"driveTrace\";\n\n/**\n * Read back the partial trace `drive` attached to an error a handler rejected\n * with. Returns `undefined` for anything `drive` did not annotate.\n *\n * A rejecting handler's error propagates out of `drive` UNSWALLOWED — same\n * value, same `instanceof`, same `_tag` — so a test that already branches on\n * the handler's own error type keeps doing so. The trace rides along on a\n * non-enumerable property so it is recoverable without changing how the error\n * prints or serializes.\n */\nexport function driveTraceOf<M, C>(\n err: unknown,\n): readonly DriveTraceEntry<M, C>[] | undefined {\n if (typeof err !== \"object\" || err === null) return undefined;\n const carried = (err as Record<string, unknown>)[TRACE_KEY];\n return Array.isArray(carried)\n ? (carried as readonly DriveTraceEntry<M, C>[])\n : undefined;\n}\n\n/**\n * Drive `machine` from `initial` through `msg` against the REAL interpret\n * `handlers`, feeding every settle Msg back until the machine goes quiet, and\n * hand back the settled state together with the whole history.\n *\n * `handlers` is the same table a host hands `run` as its `interpret` (e.g.\n * a jev knob's `resilient_run` handler), so the test drives the real interpreter and\n * mocks only the port beneath it.\n *\n * One round is: fold every pending Msg, then await a handler for every Cmd\n * those folds emitted. A Msg a handler returns — or fires through its injected\n * `dispatch` — is pending for the next round. A machine that emits no Cmd for\n * its seed Msg therefore settles in ONE round and never awaits a handler at\n * all.\n *\n * The `ctx` handed to each handler is `opts.ctx` augmented with a NO-OP `emit`,\n * so a handler that emits to a `Port` runs without a live runtime; nothing here\n * observes ports. Supply your own `emit` on `ctx` to capture them.\n *\n * @throws {DriveRoundsExceededError} when the machine is still emitting work\n * after `opts.maxRounds` rounds. It never returns a half-driven state.\n * @throws whatever a handler rejects with, unchanged — annotated with the\n * partial trace, readable via {@link driveTraceOf}.\n */\nexport async function drive<\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 initial: S,\n msg: M,\n handlers: Interpret<M, C, Ctx>,\n ...[opts]: Record<never, never> extends DriveOptions<Ctx>\n ? [opts?: DriveOptions<Ctx>]\n : [opts: DriveOptions<Ctx>]\n): Promise<DriveResult<S, M, C>> {\n const options = (opts ?? {}) as {\n ctx?: Ctx;\n maxRounds?: number;\n clock?: () => number;\n };\n const maxRounds = options.maxRounds ?? DEFAULT_MAX_ROUNDS;\n const bound = bindMachine(machine, options.ctx as Ctx);\n\n // The `Cmd.define` edge `run` applies (ADR 0021): a defined Cmd's handler\n // returns an outcome, and the edge mints it into the def's `_ok` / `_err`\n // Msg. A hand-written Cmd's return passes through untouched.\n const settle = cmdEdgeOver(machine.cmds ?? [], options.clock ?? Date.now);\n\n // A handler's ctx is `Ctx & PortEmitter`, plus the `ok` / `err` builders and\n // the edge a defined Cmd's handler is handed. The Ctx half is the caller's;\n // the rest is the kernel's, and a driven test has no kernel — so a no-op\n // `emit` stands in, placed FIRST so a caller's own `emit` wins.\n const noopEmit: PortEmitter = { emit: () => {} };\n const handlerCtx = {\n ...noopEmit,\n ok: Outcome.ok,\n err: Outcome.err,\n [cmdEdge]: settle,\n ...(options.ctx as unknown as Record<string, unknown> | undefined),\n };\n\n // Indexed dynamically: `Interpret`'s mapped type already proved every Cmd\n // variant has a cell, but `cmd.type` is a union at the value level and TS\n // cannot correlate the two sides of that index.\n const cells = handlers as unknown as Record<\n string,\n | ((\n cmd: C,\n ctx: unknown,\n dispatch?: (msg: M) => void,\n // biome-ignore lint/suspicious/noConfusingVoidType: mirrors `Interpret`'s own cell return — a follow-up Msg, or nothing\n ) => Promise<M | void>)\n | undefined\n >;\n\n const trace: DriveTraceEntry<M, C>[] = [];\n let state = initial;\n let pending: M[] = [msg];\n let round = 0;\n\n while (pending.length > 0) {\n round += 1;\n if (round > maxRounds) {\n throw new DriveRoundsExceededError<M, C>(maxRounds, round, trace);\n }\n\n // Drain the round's Msgs first, THEN its Cmds. Swapping the buffer before\n // the fold is what keeps a settle Msg out of the round that produced it —\n // the ordering question every hand-rolled copy of this loop re-answers.\n const folding = pending;\n pending = [];\n const emitted: C[] = [];\n for (const next of folding) {\n trace.push({ kind: \"msg\", msg: next });\n const [advanced, cmds] = bound.step(state, next);\n state = advanced;\n emitted.push(...cmds);\n }\n\n for (const cmd of emitted) {\n trace.push({ kind: \"cmd\", cmd });\n const cell = cells[cmd.type];\n if (cell === undefined) {\n throw new DriveNoHandlerError<M, C>(cmd.type, trace);\n }\n // biome-ignore lint/suspicious/noConfusingVoidType: mirrors `Interpret`'s own cell return — a follow-up Msg, or nothing\n let settled: M | void;\n try {\n settled = settle(\n cmd,\n await cell(cmd, handlerCtx, (fired) => {\n pending.push(fired);\n }),\n ) as M | undefined;\n } catch (err) {\n // Unswallowed: the handler's own error is what leaves `drive`, so a\n // test's `instanceof` / `_tag` branch still lands. The trace rides on\n // a non-enumerable property (see `driveTraceOf`).\n if (typeof err === \"object\" && err !== null) {\n Object.defineProperty(err, TRACE_KEY, {\n value: [...trace],\n enumerable: false,\n configurable: true,\n writable: true,\n });\n }\n throw err;\n }\n if (settled !== undefined) pending.push(settled);\n }\n }\n\n return { state, trace };\n}\n","// ---------------------------------------------------------------------------\n// noopRuntime — a Runtime<S, M>-shaped value whose every method is inert.\n//\n// The motivating callsite: a machine's `ctx` requires a sibling Runtime<S,\n// M> reference (e.g. the queue runtime in extension/lib/queue-machine\n// reaches into an `auditRuntime: Runtime<...>` slot on its ctx so its\n// interpret handlers can dispatch into the audit machine). When the test\n// replays such a machine, `replay` never actually invokes `interpret`, so\n// the runtime reference is never dereferenced — but the type system\n// still requires a value of `Runtime<S, M>` shape at the ctx slot. Tests\n// today work around this with a hand-rolled 12-line NOOP_AUDIT_RUNTIME\n// const cast through `as unknown as Runtime<...>`.\n//\n// `noopRuntime<S, M>()` is that hand-roll, named once. It returns a real\n// Runtime<S, M> value whose every method is a structurally-correct no-op:\n//\n// - `dispatch`: resolves immediately, never advances state.\n// - `getState`: returns the optional `initialState` argument (or a\n// deliberate `undefined` cast as S — the function lies about its\n// return type when no initial state is provided; this is the trade-off\n// we accept for an ergonomic test substrate).\n// - `subscribe` / `observe` / `subscribePort`: register the listener,\n// return a no-op unsubscribe. The listener is never fired because the\n// state never changes.\n// - `emitPort`: no-op.\n// - `ready`: a Promise that resolves to the no-op runtime itself (the #45\n// `ready: Promise<Runtime<S, M>>` shape — already booted, nothing to wait\n// for).\n// - `stop`: resolved Promise<void>.\n//\n// Strengthens invariant 9 (the testing surface is named and small).\n// ---------------------------------------------------------------------------\n\nimport type { Port, Runtime } from \"../index\";\n\n/**\n * Construct an inert `Runtime<S, M>` value. Use at ctx sites that require\n * a Runtime reference but where the test never invokes `interpret` (so\n * the runtime is never dereferenced in practice).\n *\n * @param opts.initialState Optional value returned by `getState()`. Omit\n * when the test never calls `getState()` on the no-op runtime — most\n * tests only need the type-level slot filled.\n */\nexport function noopRuntime<S, M extends { type: string }>(opts?: {\n initialState?: S;\n}): Runtime<S, M> {\n const initialState = opts?.initialState;\n // Single source of truth for the \"do-nothing\" unsubscribe so multiple\n // subscribe call sites share the same function instance — purely cosmetic\n // (the function would be a no-op either way).\n const noopUnsubscribe = (): void => {};\n const runtime: Runtime<S, M> = {\n async dispatch(_msg: M): Promise<void> {\n // Resolves immediately. State never advances; listeners never fire.\n // Quiescent by default (#50), but the no-op has no follow-up chain to\n // drain, so single-step and run-to-quiescence collapse to the same no-op.\n },\n async dispatchOnce(_msg: M): Promise<void> {\n // Single-step sibling of `dispatch` (#50). Same no-op for the no-op\n // runtime — there is no tail to leave in flight.\n },\n async idle(): Promise<void> {\n // No tail to drain — the no-op runtime never enqueues a follow-up.\n },\n result(): S | undefined {\n // The no-op runtime never advances, so it is never terminal (#46).\n return undefined;\n },\n done(): Promise<S> {\n // Never terminal → the awaitable never settles, matching `run()` with no\n // `terminal` predicate. Returned as a never-resolving promise.\n return new Promise<S>(() => {});\n },\n getState(): S {\n // Lie if no initial state was provided. The caller's contract is\n // \"you accept the lie because you know replay never invokes\n // interpret and therefore never reads this.\" When the caller DOES\n // pass an initialState the lie collapses to truth.\n return initialState as S;\n },\n subscribe(_listener: () => void): () => void {\n return noopUnsubscribe;\n },\n observe(_observer: (msg: M, state: S) => void): () => void {\n return noopUnsubscribe;\n },\n onBoot(_handler: (state: S) => void): () => void {\n // Boot never fires on the inert runtime — it is \"already booted\" with no\n // initial fanout, so the handler is registered and never called (#47).\n return noopUnsubscribe;\n },\n on<K extends never>(\n _type: K,\n _handler: (event: never) => void,\n ): () => void {\n // The no-op runtime's event surface is `never` (no `events` projector),\n // so `on` is structurally present but uncallable — there is no `K` to\n // pass. The body is unreachable; it returns the shared no-op unsubscribe.\n return noopUnsubscribe;\n },\n subscribePort<T>(\n _port: Port<T>,\n _listener: (value: T) => void,\n ): () => void {\n return noopUnsubscribe;\n },\n emitPort<T>(_port: Port<T>, _value: T): void {\n // No-op. No subscribers to fan out to; nothing to do.\n },\n // Assigned just below — `ready` must resolve to `runtime` itself, which\n // can't be referenced inside its own object literal.\n ready: undefined as unknown as Promise<Runtime<S, M>>,\n async stop(): Promise<void> {\n // Resolves immediately. No in-flight tail to drain, no subs to clean.\n },\n };\n // Already \"booted\" — `ready` hands back the same runtime synchronously.\n runtime.ready = Promise.resolve(runtime);\n return runtime;\n}\n","// ---------------------------------------------------------------------------\n// stateFactory — typed phase-constructor API for a discriminated-union State.\n//\n// The motivating callsite: every reducer test today opens with ~60–80 lines\n// of hand-rolled factory functions, one per phase, each one's defaults\n// duplicated across files:\n//\n// function idleState() { return { type: \"idle\" }; }\n// function creatingWindowState(overrides?: Partial<...>) {\n// return { type: \"creating_window\", auditId: ..., wsUrl: ..., ...overrides };\n// }\n// ...\n//\n// `stateFactory<BackgroundState>({...})` collapses the whole block to one\n// declaration: pass each phase's REQUIRED defaults once (the type system\n// enforces every phase has an entry), and the helper builds an API of\n// `factory.idle()`, `factory.creating_window({...})`, etc.\n//\n// Two type-level guarantees:\n//\n// 1. Every phase has a defaults entry — `StateFactoryDefaults<S>` is a\n// mapped type keyed by every `S[\"type\"]`. Missing an entry is a\n// compile error (the @ts-expect-error in testing.spec.ts pins this).\n//\n// 2. Each phase's defaults match that phase's required shape minus the\n// `type` discriminator. Passing wrong fields fails to compile.\n//\n// The runtime is pure data:\n//\n// api[k] = (overrides) => ({\n// type: k,\n// ...defaults[k],\n// ...stripUndefined(overrides ?? {}),\n// })\n//\n// The `stripUndefined` pass is what preserves `exactOptionalPropertyTypes`\n// assignability — without it, calling `factory.creating_window({\n// queueItemId: undefined })` would land an explicit `queueItemId: undefined`\n// on the object, which is NOT assignable to `queueItemId?: string` under\n// `exactOptionalPropertyTypes`. Stripping undefineds before spread keeps\n// the boundary clean.\n//\n// `stripUndefined` is inlined (not imported from a shared stdlib) so this\n// package can stay dep-free of stdlib.\n// ---------------------------------------------------------------------------\n\n/** A factory-constructed phase: `S` narrowed to the arm whose discriminator equals `K`. */\ntype StateOf<S, K> = Extract<S, { type: K }>;\n\n/** A factory-constructed phase with the `type` discriminator removed — the \"fields the caller cares about\" half. */\ntype RequiredFields<T> = Omit<T, \"type\">;\n\n/**\n * Defaults shape passed to `stateFactory`. Mapped type over the discriminant\n * set: every phase MUST have an entry, and that entry MUST match the phase's\n * required fields minus the `type` discriminator.\n */\nexport type StateFactoryDefaults<S extends { type: string }> = {\n readonly [K in S[\"type\"]]: RequiredFields<StateOf<S, K>>;\n};\n\n/**\n * The API returned by `stateFactory`. One method per phase; calling it with\n * no args returns the default snapshot, calling it with a partial overrides\n * object merges those overrides in (with undefineds stripped — see\n * stripUndefined below).\n */\nexport type StateFactoryAPI<S extends { type: string }> = {\n readonly [K in S[\"type\"]]: (\n overrides?: Partial<RequiredFields<StateOf<S, K>>>,\n ) => StateOf<S, K>;\n};\n\n/**\n * Strip own-enumerable properties whose value is `undefined`. Used inside\n * the factory's spread chain so callers can pass `{ queueItemId: undefined }`\n * without the explicit-undefined landing on the result object (which would\n * fail to assign to a `queueItemId?: string` field under\n * `exactOptionalPropertyTypes`).\n *\n * Inlined (not imported from `a shared stdlib`) so `@demlik/tea/testing` can stay\n * dependency-free of stdlib. The 8-line cost of duplication is cheaper than\n * a package-graph edge.\n */\nfunction stripUndefined<T extends object>(obj: T): Partial<T> {\n const out: Partial<T> = {};\n for (const key of Object.keys(obj) as (keyof T)[]) {\n const value = obj[key];\n if (value !== undefined) {\n out[key] = value;\n }\n }\n return out;\n}\n\n/**\n * Build a typed phase-constructor API from per-phase defaults. The defaults\n * object MUST have one entry per `S[\"type\"]` discriminant; the returned API\n * has one method per phase. Each method merges the defaults with optional\n * overrides (undefineds stripped), then stamps the `type` discriminator.\n *\n * @example\n * type S = { type: \"a\"; n: number } | { type: \"b\"; s: string };\n * const f = stateFactory<S>({ a: { n: 0 }, b: { s: \"\" } });\n * f.a(); // { type: \"a\", n: 0 }\n * f.a({ n: 42 }); // { type: \"a\", n: 42 }\n * f.b({ s: \"hi\" }); // { type: \"b\", s: \"hi\" }\n */\nexport function stateFactory<S extends { type: string }>(\n defaults: StateFactoryDefaults<S>,\n): StateFactoryAPI<S> {\n // Build the API by walking the defaults' own keys. Each key corresponds\n // to one phase discriminator; the constructor closes over both the key\n // (for the `type` stamp) and that phase's defaults snapshot.\n const api = {} as { [k: string]: (overrides?: object) => unknown };\n for (const key of Object.keys(\n defaults,\n ) as (keyof StateFactoryDefaults<S>)[]) {\n const phaseDefaults = defaults[key];\n api[key as string] = (overrides?: object) => {\n // The strip-undefined pass lives here, not at the caller. See the\n // module header for the `exactOptionalPropertyTypes` rationale.\n const cleanedOverrides = overrides ? stripUndefined(overrides) : {};\n return { type: key, ...phaseDefaults, ...cleanedOverrides };\n };\n }\n return api as StateFactoryAPI<S>;\n}\n"]}