@demlik/tea 0.1.1 → 0.2.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 (150) hide show
  1. package/dist/agent/index.d.ts +2 -2
  2. package/dist/agent/index.js +8 -8
  3. package/dist/authed-call/index.d.ts +3 -3
  4. package/dist/authed-call/index.js +5 -5
  5. package/dist/await-terminal/index.d.ts +1 -1
  6. package/dist/await-terminal/index.js +2 -2
  7. package/dist/batch-window/index.d.ts +2 -2
  8. package/dist/batch-window/index.js +4 -4
  9. package/dist/cache/index.d.ts +2 -2
  10. package/dist/{chunk-EIZJTYKR.js → chunk-5KVHID6A.js} +4 -4
  11. package/dist/{chunk-EIZJTYKR.js.map → chunk-5KVHID6A.js.map} +1 -1
  12. package/dist/{chunk-RVJFGRGK.js → chunk-6GIGQT6C.js} +4 -4
  13. package/dist/chunk-6GIGQT6C.js.map +1 -0
  14. package/dist/{chunk-FH5RUIIL.js → chunk-6OUDPSSG.js} +3 -3
  15. package/dist/{chunk-FH5RUIIL.js.map → chunk-6OUDPSSG.js.map} +1 -1
  16. package/dist/{chunk-2WZHS4P2.js → chunk-6VDCTR7N.js} +25 -40
  17. package/dist/chunk-6VDCTR7N.js.map +1 -0
  18. package/dist/{chunk-BNJYE4AU.js → chunk-DYRKDCJI.js} +46 -16
  19. package/dist/chunk-DYRKDCJI.js.map +1 -0
  20. package/dist/{chunk-RGTPPF4U.js → chunk-EGWTT5XJ.js} +3 -3
  21. package/dist/{chunk-RGTPPF4U.js.map → chunk-EGWTT5XJ.js.map} +1 -1
  22. package/dist/{chunk-A56GNPI7.js → chunk-EMJTPHI7.js} +5 -23
  23. package/dist/chunk-EMJTPHI7.js.map +1 -0
  24. package/dist/{chunk-IFBQJYGI.js → chunk-FOGL3TC7.js} +3 -3
  25. package/dist/{chunk-IFBQJYGI.js.map → chunk-FOGL3TC7.js.map} +1 -1
  26. package/dist/{chunk-RVU3RBE6.js → chunk-G2U7DJHL.js} +6 -4
  27. package/dist/chunk-G2U7DJHL.js.map +1 -0
  28. package/dist/{chunk-WUV3PSCZ.js → chunk-HCEVHFJ7.js} +2 -2
  29. package/dist/chunk-HCEVHFJ7.js.map +1 -0
  30. package/dist/{chunk-EDGDR5XX.js → chunk-IK4S5DJN.js} +3 -3
  31. package/dist/{chunk-EDGDR5XX.js.map → chunk-IK4S5DJN.js.map} +1 -1
  32. package/dist/{chunk-EQRUAP2A.js → chunk-J6527VRQ.js} +2 -2
  33. package/dist/chunk-J6527VRQ.js.map +1 -0
  34. package/dist/{chunk-TAO4YOLO.js → chunk-M6UZT7HS.js} +3 -3
  35. package/dist/{chunk-TAO4YOLO.js.map → chunk-M6UZT7HS.js.map} +1 -1
  36. package/dist/{chunk-QGZW4W3E.js → chunk-SKAMZKTE.js} +3 -3
  37. package/dist/{chunk-QGZW4W3E.js.map → chunk-SKAMZKTE.js.map} +1 -1
  38. package/dist/{chunk-TC4HWABA.js → chunk-VFGKTGGC.js} +7 -7
  39. package/dist/{chunk-TC4HWABA.js.map → chunk-VFGKTGGC.js.map} +1 -1
  40. package/dist/{chunk-D5EQDLDV.js → chunk-ZDRN3YCE.js} +4 -4
  41. package/dist/{chunk-D5EQDLDV.js.map → chunk-ZDRN3YCE.js.map} +1 -1
  42. package/dist/{core-CymXZCeY.d.ts → core-BmlJOvxM.d.ts} +20 -1
  43. package/dist/deadline/index.d.ts +2 -2
  44. package/dist/deadline/index.js +3 -3
  45. package/dist/debounce/index.d.ts +6 -0
  46. package/dist/debounce/index.js +1 -1
  47. package/dist/do/index.d.ts +422 -315
  48. package/dist/do/index.js +173 -149
  49. package/dist/do/index.js.map +1 -1
  50. package/dist/{durable-effects-2MDxDs45.d.ts → durable-effects-9LxFpmh3.d.ts} +1 -1
  51. package/dist/extension/index.d.ts +1 -1
  52. package/dist/extension/index.js +3 -3
  53. package/dist/extension/react.js +3 -3
  54. package/dist/extension/subs/index.d.ts +2 -2
  55. package/dist/fan-out/index.d.ts +1 -1
  56. package/dist/idempotent-intake/index.d.ts +1 -1
  57. package/dist/index.d.ts +20 -3
  58. package/dist/index.js +2 -2
  59. package/dist/llm-call/index.d.ts +2 -2
  60. package/dist/llm-call/index.js +5 -5
  61. package/dist/machine-viz/index.d.ts +4 -4
  62. package/dist/machine-viz/index.js +4 -8
  63. package/dist/machine-viz/index.js.map +1 -1
  64. package/dist/mem/index.d.ts +1 -1
  65. package/dist/monitored-run/index.d.ts +2 -2
  66. package/dist/monitored-run/index.js +5 -5
  67. package/dist/node/index.d.ts +1 -1
  68. package/dist/paginated-walk/index.d.ts +2 -2
  69. package/dist/paginated-walk/index.js +5 -5
  70. package/dist/parity/index.d.ts +10 -4
  71. package/dist/parity/index.js +6 -5
  72. package/dist/parity/index.js.map +1 -1
  73. package/dist/pbt/arbitraries/index.d.ts +1 -1
  74. package/dist/pbt/index.d.ts +15 -8
  75. package/dist/pbt/index.js +5 -11
  76. package/dist/pbt/index.js.map +1 -1
  77. package/dist/pbt/runners/index.d.ts +1 -1
  78. package/dist/pbt/runners/index.js +3 -3
  79. package/dist/poller/index.d.ts +2 -2
  80. package/dist/poller/index.js +3 -3
  81. package/dist/prediction/index.d.ts +23 -2
  82. package/dist/prediction/index.js +2 -2
  83. package/dist/pure/index.d.ts +2 -2
  84. package/dist/pure/index.js +2 -2
  85. package/dist/react/index.d.ts +1 -1
  86. package/dist/react/index.js +8 -4
  87. package/dist/react/index.js.map +1 -1
  88. package/dist/reconciler/index.d.ts +2 -2
  89. package/dist/reconciler/index.js +5 -5
  90. package/dist/recorder/index.d.ts +1 -1
  91. package/dist/resilient-call/index.d.ts +45 -2
  92. package/dist/resilient-call/index.js +4 -4
  93. package/dist/retry-to-success/index.d.ts +109 -0
  94. package/dist/retry-to-success/index.js +35 -0
  95. package/dist/retry-to-success/index.js.map +1 -0
  96. package/dist/saga/index.d.ts +14 -1
  97. package/dist/saga/index.js.map +1 -1
  98. package/dist/snapshot/index.d.ts +1 -1
  99. package/dist/snapshot/index.js +3 -3
  100. package/dist/subs/index.d.ts +2 -2
  101. package/dist/testing/index.d.ts +1 -1
  102. package/dist/testing/index.js +2 -2
  103. package/dist/throttle/index.d.ts +9 -0
  104. package/dist/throttle/index.js +1 -1
  105. package/dist/throttled-input/index.d.ts +10 -2
  106. package/dist/throttled-input/index.js +6 -6
  107. package/dist/throttled-input/index.js.map +1 -1
  108. package/dist/token-refresh/index.d.ts +1 -1
  109. package/dist/token-refresh/index.js +3 -3
  110. package/dist/trace-replay/index.d.ts +1 -1
  111. package/dist/trace-replay/index.js +3 -3
  112. package/dist/{types-N9LZbdnr.d.ts → types-BoUWgwSm.d.ts} +1 -1
  113. package/dist/with-deadline/index.d.ts +1 -1
  114. package/dist/with-deadline/index.js +5 -24
  115. package/dist/with-deadline/index.js.map +1 -1
  116. package/dist/with-resilience/index.d.ts +2 -2
  117. package/dist/with-resilience/index.js +13 -36
  118. package/dist/with-resilience/index.js.map +1 -1
  119. package/dist/with-telemetry/index.d.ts +1 -1
  120. package/dist/with-telemetry/index.js +4 -29
  121. package/dist/with-telemetry/index.js.map +1 -1
  122. package/dist/work-queue/adapter.d.ts +1 -1
  123. package/dist/work-queue/index.d.ts +1 -1
  124. package/dist/work-queue/ops.d.ts +1 -1
  125. package/dist/workflow/index.d.ts +16 -10
  126. package/dist/workflow/index.js.map +1 -1
  127. package/package.json +8 -20
  128. package/dist/chunk-2WZHS4P2.js.map +0 -1
  129. package/dist/chunk-7VEG4KHB.js +0 -202
  130. package/dist/chunk-7VEG4KHB.js.map +0 -1
  131. package/dist/chunk-A56GNPI7.js.map +0 -1
  132. package/dist/chunk-BNJYE4AU.js.map +0 -1
  133. package/dist/chunk-EQRUAP2A.js.map +0 -1
  134. package/dist/chunk-RVJFGRGK.js.map +0 -1
  135. package/dist/chunk-RVU3RBE6.js.map +0 -1
  136. package/dist/chunk-WUV3PSCZ.js.map +0 -1
  137. package/dist/chunk-XRXKH7KA.js +0 -268
  138. package/dist/chunk-XRXKH7KA.js.map +0 -1
  139. package/dist/raft/demo.d.ts +0 -105
  140. package/dist/raft/demo.js +0 -172
  141. package/dist/raft/demo.js.map +0 -1
  142. package/dist/raft/index.d.ts +0 -548
  143. package/dist/raft/index.js +0 -7
  144. package/dist/raft/index.js.map +0 -1
  145. package/dist/raft/sim.d.ts +0 -222
  146. package/dist/raft/sim.js +0 -8
  147. package/dist/raft/sim.js.map +0 -1
  148. package/dist/raft/timeline.d.ts +0 -46
  149. package/dist/raft/timeline.js +0 -62
  150. package/dist/raft/timeline.js.map +0 -1
@@ -1,6 +1,6 @@
1
1
  import { QueueItem } from './index.js';
2
2
  import '../index.js';
3
- import '../core-CymXZCeY.js';
3
+ import '../core-BmlJOvxM.js';
4
4
 
5
5
  /**
6
6
  * @demlik/tea/work-queue/adapter — the verb seam over the pure queue ops.
@@ -1,5 +1,5 @@
1
1
  import { Store } from '../index.js';
2
- import '../core-CymXZCeY.js';
2
+ import '../core-BmlJOvxM.js';
3
3
 
4
4
  /**
5
5
  * @demlik/tea/work-queue — substrate-agnostic work-queue lifecycle on `Store<S>`.
@@ -1,6 +1,6 @@
1
1
  import { QueueItem } from './index.js';
2
2
  import '../index.js';
3
- import '../core-CymXZCeY.js';
3
+ import '../core-BmlJOvxM.js';
4
4
 
5
5
  /**
6
6
  * Pure queue-lifecycle ops over `QueueItem<I>[]` — the BLESSED delegation
@@ -1,6 +1,6 @@
1
- import { D as DeliveryId, E as EffectLedgerEvent } from '../durable-effects-2MDxDs45.js';
2
- export { a as EffectConfirmed, b as EffectOwed, e as emptyLedger } from '../durable-effects-2MDxDs45.js';
3
- import { C as Cmd } from '../core-CymXZCeY.js';
1
+ import { D as DeliveryId, E as EffectLedgerEvent } from '../durable-effects-9LxFpmh3.js';
2
+ export { a as EffectConfirmed, b as EffectOwed, e as emptyLedger } from '../durable-effects-9LxFpmh3.js';
3
+ import { C as Cmd } from '../core-BmlJOvxM.js';
4
4
 
5
5
  /**
6
6
  * @demlik/tea/workflow — the durable-workflow runtime core (#124, the first
@@ -45,14 +45,20 @@ import { C as Cmd } from '../core-CymXZCeY.js';
45
45
  * activity exists only while running" is a type-level guarantee, not a runtime
46
46
  * convention (acceptance criterion 1).
47
47
  *
48
- * **Forward-only (#124 scope).** This core advances FORWARD on success. A step
49
- * failure transitions to `failed` — a deliberate placeholder. Compensation /
50
- * Saga rollback (the reverse-ordered sequence of compensating activities) is
51
- * #125; the `// #125:` seam in {@link Workflow.onActivityErr} marks exactly
52
- * where that slice hooks in. DO-grain host wrapping is #126; the Saga demo is
53
- * #127.
48
+ * **Boundary with `@demlik/tea/saga` — the compensation test.** Both drive an
49
+ * ordered multi-step transaction with reverse-order compensation (#125 here);
50
+ * the line between them is whether every step carries a true inverse. Here
51
+ * {@link WorkflowStep.compensation} is OPTIONAL — an irreversible step (a sent
52
+ * email) is simply SKIPPED during the unwind, and the run still reaches a
53
+ * terminal state. Saga's `SagaStep<D, U>` REQUIRES both `do` and `undo` — a
54
+ * step without its inverse is unrepresentable, so full reversibility is a
55
+ * type-level guarantee. Pick by the test: **every step must be reversible →
56
+ * saga; some steps are irreversible but the run must finish → workflow.**
57
+ * Cross to saga when you want the type system to enforce that every step can
58
+ * be undone; stay here when the transaction includes steps that can't be.
59
+ *
54
60
  * This module is the pure reducer only — like `../raft/index.ts` is the pure
55
- * Raft reducer with the DO grain deferred to its `./do` sibling.
61
+ * Raft reducer with the DO grain deferred to its `./do` sibling (here #126).
56
62
  *
57
63
  * Generic over three opaque payloads, like raft's command generic: the activity
58
64
  * descriptor `A` (what a step asks to do — the consumer's interpret cell knows
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/workflow/index.ts"],"names":["id"],"mappings":";;;;AAojBO,SAAS,eAAwB,OAAA,EAGlB;AAKpB,EAAA,MAAM,QAAA,GAAW,qBAAqC,OAAO,CAAA;AAc7D,EAAA,SAAS,MAAA,CACP,OACA,KAAA,EACiB;AACjB,IAAA,MAAM,IAAA,GAAO,MAAM,KAAK,CAAA;AACxB,IAAA,IAAI,SAAS,MA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CAAA,EAAG,IAAA,EAAM,EAAC,EAAE;AAAA,IACxD,CAAA;AAAA,IAEA,oBAAoB,YAAA,EAAc;AAKhC,MAAA,MAAM,MAAA,GACJ,WAAW,YAAY,CAAA;AACzB,MAAA,OAAO,iBAAiB,MAAM,CAAA,CAAE,IAAI,CAAC,IAAA,KAAS,KAAK,MAAM,CAAA;AAAA,IAC3D;AAAA,GACF;AAMA,EAAA,SAAS,QAAQ,EAAA,EAAiC;AAChD,IAAA,OAAO,QAAA,CAAS,OAAA,CAAQ,EAAE,CAAA,CAAE,KAAA;AAAA,EAC9B;AACF;AA8BO,SAAS,YAAA,CACd,OACA,IAAA,EACwB;AACxB,EAAA,MAAM,KAAK,cAAA,EAAwB;AACnC,EAAA,IAAI,EAAE,KAAA,EAAM,GAAI,EAAA,CAAG,KAAK,KAAK,CAAA;AAC7B,EAAA,KAAA,MAAW,OAAO,IAAA,EAAM;AAMtB,IAAA,IAAI,IAAA;AACJ,IAAA,QAAQ,IAAI,IAAA;AAAM,MAChB,KAAK,aAAA;AACH,QAAA,IAAA,GAAO,EAAA,CAAG,YAAA,CAAa,KAAA,EAAO,GAAG,CAAA;AACjC,QAAA;AAAA,MACF,KAAK,cAAA;AACH,QAAA,IAAA,GAAO,EAAA,CAAG,aAAA,CAAc,KAAA,EAAO,GAAG,CAAA;AAClC,QAAA;AAAA,MACF,KAAK,iBAAA;AACH,QAAA,IAAA,GAAO,EAAA,CAAG,gBAAA,CAAiB,KAAA,EAAO,GAAG,CAAA;AACrC,QAAA;AAAA,MACF,KAAK,kBAAA;AACH,QAAA,IAAA,GAAO,EAAA,CAAG,iBAAA,CAAkB,KAAA,EAAO,GAAG,CAAA;AACtC,QAAA;AAAA;AAEJ,IAAA,KAAA,GAAQ,IAAA,CAAK,KAAA;AAAA,EACf;AACA,EAAA,OAAO,KAAA;AACT","file":"index.js","sourcesContent":["/**\n * @demlik/tea/workflow — the durable-workflow runtime core (#124, the first\n * Phase-1 slice of the Temporal-style durable-workflow engine, epic #118).\n *\n * A workflow is a long-running, multi-step transaction whose every step (an\n * **activity**) is a side effect that may evict the actor mid-flight. The\n * substrate already solves \"a state survives eviction\" (the event-sourced\n * store) and \"an owed effect survives eviction\" (the `do/` pending-effects\n * ledger, #67). This module composes those two into the third primitive: a\n * **pure TEA reducer over a workflow's progress**, where each step is dispatched\n * as a durable owed effect and the next step is decided only after the previous\n * one's result is folded back in. That is exactly Temporal's contract — a\n * deterministic workflow function whose activities are the only impurity, so a\n * replay of the event log re-decides every step identically.\n *\n * The mapping onto TEA, mirroring `../raft`:\n *\n * - **Reducer** — {@link createWorkflow}'s verbs (`init`, `onActivityOk`,\n * `onActivityErr`) are the transition function over {@link WorkflowState}.\n * PURE: they read no clock and no RNG. Wall time, randomness, retries — all\n * impurity lives in the consumer's injected *interpret cell* (the thing that\n * actually performs the activity `Cmd` and dispatches its result `Msg`).\n * A workflow driven by a recorded result schedule re-decides bit-for-bit —\n * the headline replay-determinism payoff (acceptance criterion 4).\n * - **Cmd** — the activity dispatch is an {@link ActivityCmd}, recorded on the\n * #67 ledger as an `effect_owed` BEFORE it is performed and `effect_confirmed`\n * on its result. This module emits the Cmd literals; it performs NO side\n * effects. The owed/confirmed events are persisted into the same log the\n * reducer folds, so the ledger (and thus \"which activity is still owed\")\n * rebuilds for free on cold wake — re-emit-on-wake is idempotent by the\n * ledger's monotonic delivery id (acceptance criterion 3).\n * - **Msg** — an activity result (`activity_ok` / `activity_err`) is a `Msg`\n * the consumer routes back into a verb. The verb folds the result, records\n * the completed step, and advances to the next activity (or to `completed`\n * when the sequence is exhausted).\n *\n * **Invalid states unrepresentable.** The in-flight activity (`current`, with\n * its delivery id) lives ONLY on the `running` variant of {@link WorkflowState}.\n * A `completed` workflow carries its final output and no current activity; a\n * `failed` one carries its failure and no current activity. So \"the current\n * activity exists only while running\" is a type-level guarantee, not a runtime\n * convention (acceptance criterion 1).\n *\n * **Forward-only (#124 scope).** This core advances FORWARD on success. A step\n * failure transitions to `failed` — a deliberate placeholder. Compensation /\n * Saga rollback (the reverse-ordered sequence of compensating activities) is\n * #125; the `// #125:` seam in {@link Workflow.onActivityErr} marks exactly\n * where that slice hooks in. DO-grain host wrapping is #126; the Saga demo is\n * #127.\n * This module is the pure reducer only — like `../raft/index.ts` is the pure\n * Raft reducer with the DO grain deferred to its `./do` sibling.\n *\n * Generic over three opaque payloads, like raft's command generic: the activity\n * descriptor `A` (what a step asks to do — the consumer's interpret cell knows\n * how to perform it), the activity result `R`, and the failure `F`. The reducer\n * never inspects them; it only sequences them.\n *\n * NOT a substrate primitive: it depends only on the core `Cmd` type and the\n * sibling `../do` durable-effects ledger. Consumers reach it via the\n * `@demlik/tea/workflow` subpath.\n */\n\nimport {\n type DeliveryId,\n type EffectConfirmed,\n type EffectLedgerEvent,\n type EffectOwed,\n emptyLedger,\n foldLedger,\n type PendingEffectsLedger,\n pendingEffectsLedger,\n survivingEffects,\n} from \"../do/durable-effects\";\nimport type { Cmd } from \"../index\";\n\n// ─────────────────────────────────────────────────────────────────────────────\n// Steps — the static definition of a workflow.\n//\n// A workflow is defined by an ordered sequence of steps. A step is an activity\n// descriptor: a stable `name` (for readability + correlation in the event log)\n// plus the opaque `activity` payload the consumer's interpret cell performs.\n// Steps are inert data; the reducer walks them in order.\n// ─────────────────────────────────────────────────────────────────────────────\n\n/**\n * One step of a workflow: a named activity descriptor. `A` is the opaque\n * payload the consumer's interpret cell knows how to perform (an HTTP call, a\n * sibling-grain message, a tool round-trip). The reducer never inspects\n * `activity` — it only sequences the steps and correlates results.\n *\n * A step may declare a **compensation** — the inverse activity that undoes the\n * forward one (cancel the reservation, refund the charge). Compensation is the\n * `{ do, undo }` pair of `@demlik/tea/saga` mapped onto the workflow: the step's\n * `activity` is the `do`, its `compensation` is the `undo`. The pair is the unit\n * of reversibility — a step that completed (its forward activity succeeded) is\n * exactly a step whose `compensation` must run, in reverse order, if a LATER\n * step fails (#125). A step WITHOUT a compensation contributes nothing to the\n * unwind: it is skipped during the reverse walk (an irreversible step — a sent\n * email — that the saga model treats as a no-op `undo`).\n */\nexport interface WorkflowStep<A> {\n /** Stable, human-readable step name — appears in the completed-step record. */\n readonly name: string;\n /** The opaque activity this step performs. Interpreted by the consumer. */\n readonly activity: A;\n /**\n * The opaque compensating (inverse) activity, performed in reverse order on a\n * downstream failure (#125). Optional: a step with no compensation is skipped\n * during the unwind. Interpreted by the consumer's interpret cell, exactly\n * like {@link activity}.\n */\n readonly compensation?: A;\n}\n\n/**\n * A completed step: the step that ran plus the result its activity produced.\n * The `running` state accumulates these in execution order, so the full\n * forward history is available to the consumer (and to #125's compensation,\n * which will walk it in reverse).\n */\nexport interface CompletedStep<A, R> {\n readonly step: WorkflowStep<A>;\n readonly result: R;\n}\n\n// ─────────────────────────────────────────────────────────────────────────────\n// The in-flight activity — the bridge between the reducer and the #67 ledger.\n//\n// While `running`, exactly one activity is in flight. It carries the step it is\n// performing AND the monotonic `deliveryId` the #67 ledger issued for it. The\n// delivery id is the single correlation key: an `activity_ok`/`activity_err`\n// Msg names the id it answers, the reducer matches it against `current.id`, and\n// the ledger confirms that same id. Re-emit-on-wake re-fires the SAME id, so a\n// duplicate result is a no-op (idempotent by delivery id, acceptance crit. 3).\n// ─────────────────────────────────────────────────────────────────────────────\n\n/** The activity currently in flight on a `running` workflow. */\nexport interface InFlightActivity<A> {\n /** The 0-based index of this step in the workflow's step sequence. */\n readonly index: number;\n /** The step whose activity is in flight. */\n readonly step: WorkflowStep<A>;\n /** The #67 ledger delivery id this activity was owed under (the dedup key). */\n readonly id: DeliveryId;\n}\n\n/**\n * The compensation currently in flight on a `compensating` workflow (#125). The\n * mirror of {@link InFlightActivity} for the reverse walk: exactly one\n * compensation is owed at a time, on the SAME #67 ledger, with its own monotonic\n * delivery id. `index` is the index (into `completed`/`steps`) of the step being\n * undone — the unwind walks these from high to low (strict reverse order).\n */\nexport interface InFlightCompensation<A> {\n /** The 0-based index (into the step sequence) of the step being compensated. */\n readonly index: number;\n /** The step whose compensation is in flight. */\n readonly step: WorkflowStep<A>;\n /** The #67 ledger delivery id this compensation was owed under (the dedup key). */\n readonly id: DeliveryId;\n}\n\n// ─────────────────────────────────────────────────────────────────────────────\n// WorkflowState — the discriminated union. Invalid states unrepresentable.\n//\n// `status` is the discriminant. The in-flight `current` activity exists ONLY on\n// `running` and `compensating`; `completed` carries the final `output`;\n// `failed` / `failed_compensated` / `compensation_failed` carry the failure.\n// There is no representable state with a current activity that is neither\n// running nor compensating, nor a terminal state still holding one\n// (acceptance crit. 1).\n//\n// The failure path (#125), mirroring `@demlik/tea/saga`'s phases:\n//\n// running ──activity_err with completed steps──▶ compensating\n// running ──activity_err with NO completed steps──▶ failed (empty rollback)\n// compensating ──all compensations confirmed──▶ failed_compensated\n// compensating ──a compensation itself fails──▶ compensation_failed\n//\n// `compensating` is the analogue of saga's `compensating`; `failed_compensated`\n// of saga's `aborted` (fully unwound); `compensation_failed` of saga's\n// `compensation_failed` (an `undo` bounced, partially unwound — visible state,\n// never a workflow wedged in `compensating` forever).\n// ─────────────────────────────────────────────────────────────────────────────\n\n/**\n * A workflow in progress. Carries the ordered `completed` steps (forward\n * history), the `steps` it is sequencing, and the `current` in-flight activity\n * (with its ledger delivery id). `completed.length === current.index` always\n * holds — the current activity is the next step after the last completed one.\n */\nexport interface RunningWorkflow<A, R> {\n readonly status: \"running\";\n /** The full, static step sequence this workflow runs. */\n readonly steps: readonly WorkflowStep<A>[];\n /** Steps that have produced a result, in execution order. */\n readonly completed: readonly CompletedStep<A, R>[];\n /** The single activity in flight right now. */\n readonly current: InFlightActivity<A>;\n}\n\n/**\n * A workflow that ran every step to completion. `output` is the result of the\n * final step — the workflow's overall output. No activity is in flight.\n */\nexport interface CompletedWorkflow<A, R> {\n readonly status: \"completed\";\n readonly steps: readonly WorkflowStep<A>[];\n /** Every step, in execution order, with its result. */\n readonly completed: readonly CompletedStep<A, R>[];\n /** The final step's result — the workflow's output. */\n readonly output: R;\n}\n\n/**\n * A workflow that failed on an activity with NOTHING to compensate — the\n * forward failure happened with zero completed steps (the first activity\n * failed). `failedStep` is the step whose activity reported the failure;\n * `failure` is the opaque failure payload. `completed` is empty by construction:\n * a failure WITH completed steps pivots into {@link CompensatingWorkflow}\n * instead, so `failed` is precisely the empty-rollback terminal (the analogue\n * of saga's `aborted` reached straight from the first step). No activity is in\n * flight; this is terminal (#125 acceptance criterion 3).\n */\nexport interface FailedWorkflow<A, R, F> {\n readonly status: \"failed\";\n readonly steps: readonly WorkflowStep<A>[];\n /** Empty by construction — a failure with completed steps compensates instead. */\n readonly completed: readonly CompletedStep<A, R>[];\n /** The step whose activity failed. */\n readonly failedStep: WorkflowStep<A>;\n /** The opaque failure the activity reported. */\n readonly failure: F;\n}\n\n/**\n * A workflow unwinding after a forward failure (#125): the compensations of the\n * `completed` steps are being emitted in STRICT REVERSE order, one at a time, on\n * the same #67 ledger. The analogue of saga's `compensating` phase.\n *\n * `current` is the single compensation in flight (the mirror of `running`'s\n * in-flight activity). `compensated` records, in unwind order, the completed\n * steps whose compensation has confirmed — the reverse-walk's progress log, so\n * a cold wake resumes mid-rollback exactly. `failedStep`/`failure` carry the\n * forward failure that triggered the unwind (verbatim, never interpreted),\n * preserved for the consumer to read and to fold onto the terminal state.\n *\n * Invariant: the unwind walks `completed` from its tail toward index 0, skipping\n * steps with no compensation, so `current.index` is strictly below the index of\n * every entry in `compensated`.\n */\nexport interface CompensatingWorkflow<A, R, F> {\n readonly status: \"compensating\";\n readonly steps: readonly WorkflowStep<A>[];\n /** The completed forward steps, in execution order — the history being unwound. */\n readonly completed: readonly CompletedStep<A, R>[];\n /** The step whose forward activity failed, triggering the unwind. */\n readonly failedStep: WorkflowStep<A>;\n /** The opaque forward failure that triggered the unwind. Carried, never interpreted. */\n readonly failure: F;\n /** The single compensation in flight right now. */\n readonly current: InFlightCompensation<A>;\n /** Completed steps whose compensation has confirmed, in unwind (reverse) order. */\n readonly compensated: readonly CompletedStep<A, R>[];\n}\n\n/**\n * A workflow that failed forward and then fully unwound: every completed step's\n * compensation confirmed, in reverse order. Terminal. The analogue of saga's\n * `aborted` (fully unwound) — named `failed_compensated` to align with #125's\n * vocabulary. No activity or compensation is in flight.\n */\nexport interface FailedCompensatedWorkflow<A, R, F> {\n readonly status: \"failed_compensated\";\n readonly steps: readonly WorkflowStep<A>[];\n /** The forward steps that completed (and were each compensated), in execution order. */\n readonly completed: readonly CompletedStep<A, R>[];\n /** The step whose forward activity failed, triggering the (now-finished) unwind. */\n readonly failedStep: WorkflowStep<A>;\n /** The opaque forward failure that triggered compensation. Carried, never interpreted. */\n readonly failure: F;\n}\n\n/**\n * A workflow whose ROLLBACK itself failed: a compensation activity reported a\n * failure mid-unwind. Terminal, PARTIALLY unwound — the analogue of saga's\n * `compensation_failed`. A failed compensation is a real-world fact (a refund\n * that bounced, a hold that won't release) that must become visible terminal\n * state, never a workflow wedged in `compensating` forever.\n *\n * `compensated` is left intact (the steps already rolled back); `uncompensated`\n * is the step whose compensation bounced PLUS the steps still owed a\n * compensation behind it — exactly what the consumer must reconcile by hand.\n * `compensationFailure` is the rollback failure (distinct from `failure`, the\n * forward failure that started the unwind), carried verbatim.\n */\nexport interface CompensationFailedWorkflow<A, R, F> {\n readonly status: \"compensation_failed\";\n readonly steps: readonly WorkflowStep<A>[];\n /** The full completed-forward history, in execution order. */\n readonly completed: readonly CompletedStep<A, R>[];\n /** The step whose forward activity failed, triggering the unwind. */\n readonly failedStep: WorkflowStep<A>;\n /** The opaque forward failure that triggered compensation. Carried, never interpreted. */\n readonly failure: F;\n /** Completed steps successfully compensated before the rollback broke, in unwind order. */\n readonly compensated: readonly CompletedStep<A, R>[];\n /** The step whose compensation bounced. Its forward effect stands un-reversed. */\n readonly failedCompensationStep: WorkflowStep<A>;\n /** The opaque rollback failure (distinct from {@link failure}). Carried, never interpreted. */\n readonly compensationFailure: F;\n}\n\n/**\n * The workflow's state — a discriminated union on `status`. The current\n * in-flight activity is reachable ONLY through `running`, and the in-flight\n * compensation ONLY through `compensating`, making \"an in-flight effect exists\n * only while the workflow is actively driving one\" unrepresentable to violate.\n */\nexport type WorkflowState<A, R, F> =\n | RunningWorkflow<A, R>\n | CompletedWorkflow<A, R>\n | FailedWorkflow<A, R, F>\n | CompensatingWorkflow<A, R, F>\n | FailedCompensatedWorkflow<A, R, F>\n | CompensationFailedWorkflow<A, R, F>;\n\n// ─────────────────────────────────────────────────────────────────────────────\n// Cmds — the activity dispatch. Recorded on the #67 ledger as an owed effect.\n//\n// `ActivityCmd` is the single Cmd this module emits: \"perform the activity for\n// step `index`, and the result you dispatch back must carry delivery id `id`\".\n// The consumer's interpret cell performs `activity` and dispatches an\n// `ActivityOk`/`ActivityErr` Msg carrying the SAME id. The owed/confirmed\n// ledger events ride alongside (see {@link WorkflowStep0}/the step tuple).\n// ─────────────────────────────────────────────────────────────────────────────\n\n/**\n * Dispatch the in-flight activity. Routed through the consumer's `interpret`\n * over an injected activity port. The reducer emits this literal; it performs\n * no side effect. The result MUST be dispatched back as a Msg carrying `id`.\n */\nexport interface ActivityCmd<A> extends Cmd<\"workflow_activity\"> {\n /** The 0-based step index this activity belongs to. */\n readonly index: number;\n /** The #67 delivery id the result Msg must echo (the dedup key). */\n readonly id: DeliveryId;\n /** The opaque activity to perform. */\n readonly activity: A;\n}\n\n/**\n * Dispatch a compensation (#125). Same shape + ledger discipline as\n * {@link ActivityCmd} — a compensation is just another durable owed effect on\n * the same #67 ledger, with its own delivery id — but the consumer's interpret\n * cell performs the inverse `compensation` payload, and the result is dispatched\n * back as a {@link CompensationOk}/{@link CompensationErr} carrying the SAME id.\n * Distinguished by `type` so the consumer routes forward vs. inverse work to the\n * right port, and the re-emit-on-wake stays type-correct.\n */\nexport interface CompensationCmd<A> extends Cmd<\"workflow_compensation\"> {\n /** The 0-based step index whose compensation this is. */\n readonly index: number;\n /** The #67 delivery id the result Msg must echo (the dedup key). */\n readonly id: DeliveryId;\n /** The opaque compensating (inverse) activity to perform. */\n readonly compensation: A;\n}\n\n/** The Cmd union this module emits: forward activity dispatches AND (#125)\n * reverse compensation dispatches. The owed/confirmed ledger events are not\n * `WorkflowCmd`s — they are Msg variants persisted into the event log (see\n * {@link EffectLedgerEvent}); the {@link WorkflowStep0} tuple carries them out\n * alongside the dispatch Cmd so the host persists owed-before-dispatch. Both\n * Cmd kinds are owed effects on the same ledger, so `survivingActivities`\n * re-emits either kind on cold wake. */\nexport type WorkflowCmd<A> = ActivityCmd<A> | CompensationCmd<A>;\n\n// ─────────────────────────────────────────────────────────────────────────────\n// Msgs — activity results the consumer routes back into the reducer.\n// ─────────────────────────────────────────────────────────────────────────────\n\n/** An activity succeeded: `id` echoes the {@link ActivityCmd} it answers; the\n * reducer matches it against `current.id`, records the completed step, and\n * advances. */\nexport interface ActivityOk<R> {\n readonly type: \"activity_ok\";\n readonly id: DeliveryId;\n readonly result: R;\n}\n\n/** An activity failed (retries already exhausted by the consumer's interpret\n * cell — this module does not retry). `id` echoes the {@link ActivityCmd};\n * the reducer begins compensation (or settles `failed` when nothing has\n * completed). */\nexport interface ActivityErr<F> {\n readonly type: \"activity_err\";\n readonly id: DeliveryId;\n readonly failure: F;\n}\n\n/** A compensation succeeded (#125): the inverse activity took. `id` echoes the\n * {@link CompensationCmd} it answers; the reducer matches it against the\n * in-flight compensation's id, records the step as compensated, and either\n * emits the next compensation (continuing in reverse) or settles\n * `failed_compensated` when the unwind is complete. A compensation produces no\n * result the workflow carries — its only signal is \"the undo took\". */\nexport interface CompensationOk {\n readonly type: \"compensation_ok\";\n readonly id: DeliveryId;\n}\n\n/** A compensation itself failed (#125): the inverse activity bounced (a refund\n * that won't go through). `id` echoes the {@link CompensationCmd}; the reducer\n * halts the rollback at the terminal `compensation_failed` state — never wedged\n * in `compensating` forever. */\nexport interface CompensationErr<F> {\n readonly type: \"compensation_err\";\n readonly id: DeliveryId;\n readonly failure: F;\n}\n\n/** The Msg union the reducer folds: forward activity results AND (#125) reverse\n * compensation results. */\nexport type WorkflowMsg<R, F> =\n | ActivityOk<R>\n | ActivityErr<F>\n | CompensationOk\n | CompensationErr<F>;\n\n// ─────────────────────────────────────────────────────────────────────────────\n// The step tuple — the reducer's output shape.\n//\n// A verb returns the next `WorkflowState` PLUS the side-effect intents the host\n// must enact, in the ORDER they must be enacted (owed-before-dispatch):\n//\n// - `ledger` — the `effect_owed` / `effect_confirmed` events to PERSIST into\n// the same event log the reducer folds. A `running`-emitting verb owes the\n// new activity (and a verb that folded a prior result confirms it). Persist\n// these BEFORE the dispatch Cmd (the #67 \"persist the intent before deliver\"\n// rule) so an eviction between persist and dispatch re-fires on wake.\n// - `cmds` — the activity dispatch Cmd(s). Empty on a terminal transition.\n//\n// This is the same `readonly [state, cmds]` discipline as raft's `RaftStep`,\n// extended with the ledger-events channel because activities ARE owed effects.\n// ─────────────────────────────────────────────────────────────────────────────\n\n/** A workflow reducer step: the next state, the ledger events to persist\n * (owed-before-dispatch), and the activity Cmds to dispatch. */\nexport interface WorkflowStep0<A, R, F> {\n readonly state: WorkflowState<A, R, F>;\n /** Ledger events to persist into the event log, in order, BEFORE `cmds`. */\n readonly ledger: readonly EffectLedgerEvent<WorkflowCmd<A>>[];\n /** Activity dispatch Cmds, after the ledger events are durable. */\n readonly cmds: readonly WorkflowCmd<A>[];\n}\n\n// ─────────────────────────────────────────────────────────────────────────────\n// createWorkflow — the factory. Returns the hook bag (init/verbs), mirroring\n// how `createRaftNode` / `createAgent` shape their knobs. The factory owns the\n// #67 monotonic-id recorder so every dispatched activity gets a gap-free\n// delivery id; the recorder is rehydrated from the persisted ledger events on\n// cold wake (see `restore`) so ids resume without gaps.\n// ─────────────────────────────────────────────────────────────────────────────\n\n/** The hook bag returned by {@link createWorkflow}. Spread its verbs into a\n * machine; `init(steps)` seeds a fresh workflow and emits the first activity,\n * the verbs fold results and advance, and `survivingActivities` re-emits the\n * owed-but-unconfirmed dispatch on cold wake (idempotent by delivery id). */\nexport interface Workflow<A, R, F> {\n /**\n * Seed a fresh workflow over `steps` and dispatch its first activity.\n *\n * - Empty `steps` ⇒ a workflow with nothing to do completes only when it has\n * an output; with no steps there is no output, so an empty sequence is\n * rejected as a misuse (a workflow must have at least one step). The reducer\n * never reaches `completed` without a final result to carry.\n * - Otherwise → `running` with `current` = step 0, owed on the ledger.\n */\n init(steps: readonly WorkflowStep<A>[]): WorkflowStep0<A, R, F>;\n\n /**\n * Fold an activity success. If `msg.id` does not match the in-flight\n * activity's id (a stale/duplicate result from re-emit-on-wake, or a result\n * for an already-advanced step), the state is returned UNCHANGED with no\n * effects — idempotent by delivery id (acceptance criterion 3). Otherwise:\n * record the completed step, confirm the owed activity on the ledger, and\n * either advance to the next step (owing its activity) or transition to\n * `completed` carrying the final result.\n *\n * Only meaningful on `running`; a result arriving for a terminal workflow is\n * a no-op (the workflow is done — at-least-once tolerates the late echo).\n */\n onActivityOk(\n state: WorkflowState<A, R, F>,\n msg: ActivityOk<R>,\n ): WorkflowStep0<A, R, F>;\n\n /**\n * Fold an activity failure (#125). Same id-match idempotency guard as\n * {@link onActivityOk}. On a match: confirm the owed activity on the ledger,\n * then PIVOT into compensation — walk the completed-step history in strict\n * reverse and owe the first declared compensation as a durable effect on the\n * same ledger, transitioning to `compensating`. If NO completed step declares\n * a compensation (the empty-rollback edge — the first activity failed, or\n * every completed step is irreversible), settle `failed` directly with\n * nothing to unwind.\n */\n onActivityErr(\n state: WorkflowState<A, R, F>,\n msg: ActivityErr<F>,\n ): WorkflowStep0<A, R, F>;\n\n /**\n * Fold a compensation success (#125). Same id-match idempotency guard against\n * the in-flight compensation. On a match: confirm the owed compensation,\n * record the step as compensated, and continue the reverse walk — owe the\n * next declared compensation strictly below the step just undone, or settle\n * `failed_compensated` when the unwind is complete. Only meaningful on\n * `compensating`; a result for a terminal/forward workflow is a no-op.\n */\n onCompensationOk(\n state: WorkflowState<A, R, F>,\n msg: CompensationOk,\n ): WorkflowStep0<A, R, F>;\n\n /**\n * Fold a compensation failure (#125). Same id-match idempotency guard. On a\n * match: confirm the owed compensation and HALT the rollback at the terminal\n * `compensation_failed` state — a bounced compensation is visible terminal\n * state to reconcile by hand, never a workflow wedged in `compensating`\n * forever. Mirrors `@demlik/tea/saga`'s `undoErr`.\n */\n onCompensationErr(\n state: WorkflowState<A, R, F>,\n msg: CompensationErr<F>,\n ): WorkflowStep0<A, R, F>;\n\n /**\n * The owed-but-unconfirmed dispatch(es) to re-emit on activation — a forward\n * activity OR (#125) a compensation, rebuilt by folding the persisted ledger\n * events. On a fresh / fully-settled workflow this is empty. The re-fired Cmd\n * carries the SAME delivery id, so a duplicate result is a no-op at the\n * reducer (the id-match guard). This is the cold-wake re-emit that makes both\n * activities AND compensations exactly-once-observable despite the\n * at-least-once transport (acceptance criterion 2 & 3) — including a\n * compensation owed mid-rollback when the actor was evicted.\n */\n survivingActivities(\n ledgerEvents: Iterable<EffectLedgerEvent<WorkflowCmd<A>>>,\n ): readonly WorkflowCmd<A>[];\n}\n\n/**\n * Build a workflow hook bag. The factory captures NO clock and NO RNG — pure\n * bookkeeping over the injected #67 recorder, exactly like\n * `pendingEffectsLedger`. `restore` rehydrates the monotonic delivery-id\n * counter from the persisted ledger events on cold wake, so re-dispatched\n * activities resume their ids without gaps.\n *\n * @param restore - the persisted ledger events (read back from the log) and/or\n * the last issued delivery id, so the id counter resumes gap-free. Omit for a\n * fresh workflow.\n */\nexport function createWorkflow<A, R, F>(restore?: {\n readonly events?: Iterable<EffectLedgerEvent<WorkflowCmd<A>>>;\n readonly lastId?: DeliveryId;\n}): Workflow<A, R, F> {\n // The #67 monotonic-id recorder. It owns the gap-free `deliveryId` and folds\n // an in-memory mirror of the ledger from the same owed/confirmed events the\n // host persists. Reused verbatim — activities AND compensations ARE owed\n // effects on this one ledger (do NOT reinvent the ledger).\n const recorder = pendingEffectsLedger<WorkflowCmd<A>>(restore);\n\n /**\n * Owe + dispatch the activity for `step` at `index`: allocate its delivery\n * id, build the dispatch Cmd, and emit BOTH the `effect_owed` ledger event\n * (to persist first) and the dispatch Cmd. The owed effect IS the dispatch\n * Cmd, so a cold wake re-emits the identical dispatch by folding the ledger.\n *\n * Returns the running state's `current` plus the owed event + dispatch Cmd.\n */\n /** Index into a step sequence with a bounds-check narrowing away `undefined`\n * (`noUncheckedIndexedAccess`). Every call site has already proven the index\n * in range — this converts that proof into the non-optional type, throwing\n * only on a logic error that should be unreachable. */\n function stepAt(\n steps: readonly WorkflowStep<A>[],\n index: number,\n ): WorkflowStep<A> {\n const step = steps[index];\n if (step === undefined) {\n throw new Error(\n `createWorkflow: step index ${index} out of range (length ` +\n `${steps.length}) — a reducer bounds proof was violated.`,\n );\n }\n return step;\n }\n\n /**\n * Predict the next delivery id, build the FINAL dispatch Cmd with it via\n * `build`, owe that exact Cmd on the #67 ledger, and assert the issued id\n * equals the prediction.\n *\n * The dispatch Cmd needs the delivery id, and the ledger event carries that\n * Cmd as its `effect` payload — so the id and the Cmd are mutually dependent.\n * Resolve the cycle by predicting the next id (`lastId() + 1`, the recorder's\n * gap-free monotonic rule), building the final Cmd, then handing that exact\n * Cmd to `recorder.owe`. The recorder issues the predicted id and folds the\n * final Cmd into its mirror — so the mirror, the persisted `effect_owed`\n * event, and the dispatch Cmd all carry one identical id and payload (no\n * placeholder, no rebuild). Shared by the forward owe ({@link oweActivity})\n * and the reverse owe ({@link oweCompensation}) so both halves of the\n * transaction allocate ids on the SAME monotonic ledger.\n */\n function oweOnLedger<C extends WorkflowCmd<A>>(\n build: (id: DeliveryId) => C,\n ): {\n readonly id: DeliveryId;\n readonly owed: EffectOwed<WorkflowCmd<A>>;\n readonly cmd: C;\n } {\n const id = (recorder.lastId() + 1) as DeliveryId;\n const cmd = build(id);\n const { id: issued, event } = recorder.owe(cmd);\n // Defensive: the prediction must equal the issued id, or the ledger mirror\n // and the dispatch Cmd would diverge. This holds by the recorder's gap-free\n // monotonic contract; assert it rather than silently carry a mismatch.\n if (issued !== id) {\n throw new Error(\n `createWorkflow: delivery-id prediction (${id}) diverged from the ` +\n `recorder's issued id (${issued}). The #67 recorder's monotonic ` +\n \"counter is not gap-free as assumed — this is a substrate invariant \" +\n \"violation, not a recoverable condition.\",\n );\n }\n return { id, owed: event, cmd };\n }\n\n function oweActivity(\n step: WorkflowStep<A>,\n index: number,\n ): {\n readonly current: InFlightActivity<A>;\n readonly owed: EffectOwed<WorkflowCmd<A>>;\n readonly cmd: ActivityCmd<A>;\n } {\n const { id, owed, cmd } = oweOnLedger<ActivityCmd<A>>((id) => ({\n type: \"workflow_activity\",\n index,\n id,\n activity: step.activity,\n }));\n const current: InFlightActivity<A> = { index, step, id };\n return { current, owed, cmd };\n }\n\n /**\n * Owe + dispatch the COMPENSATION for the completed step at `index` (#125):\n * the reverse-walk mirror of {@link oweActivity}. The compensation is a\n * durable owed effect on the SAME #67 ledger, so a cold wake mid-rollback\n * re-emits the identical compensation dispatch by folding the ledger\n * (acceptance criterion 2). `step.compensation` is required to be present —\n * the caller (the reverse walk) only owes compensations for steps that\n * declared one, skipping the rest.\n */\n function oweCompensation(\n step: WorkflowStep<A>,\n compensation: A,\n index: number,\n ): {\n readonly current: InFlightCompensation<A>;\n readonly owed: EffectOwed<WorkflowCmd<A>>;\n readonly cmd: CompensationCmd<A>;\n } {\n const { id, owed, cmd } = oweOnLedger<CompensationCmd<A>>((id) => ({\n type: \"workflow_compensation\",\n index,\n id,\n compensation,\n }));\n const current: InFlightCompensation<A> = { index, step, id };\n return { current, owed, cmd };\n }\n\n /**\n * Begin (or continue) the reverse walk from `completed`, owing the next\n * compensation strictly BELOW `belowIndex` (exclusive) that declares one. The\n * single source of truth for \"what to undo next\", shared by the failure pivot\n * ({@link Workflow.onActivityErr}) and each `compensation_ok` step\n * ({@link Workflow.onCompensationOk}). Steps with no compensation are SKIPPED\n * (they contribute nothing to the unwind — saga's no-op `undo`).\n *\n * Returns the next compensation to owe (its in-flight record + ledger event +\n * dispatch Cmd), or `null` when no compensable step remains below `belowIndex`\n * — the unwind is complete and the caller settles `failed_compensated`.\n */\n function oweNextCompensation(\n completed: readonly CompletedStep<A, R>[],\n belowIndex: number,\n ): {\n readonly current: InFlightCompensation<A>;\n readonly owed: EffectOwed<WorkflowCmd<A>>;\n readonly cmd: CompensationCmd<A>;\n } | null {\n // Walk the completed history from just below `belowIndex` toward 0 (strict\n // reverse order), stopping at the first step that declares a compensation.\n for (let i = belowIndex - 1; i >= 0; i--) {\n const entry = completed[i];\n // `completed[i]` is the i-th completed step; `i` is also its step index\n // (completed is in execution order, contiguous from 0 up to the failure).\n if (entry !== undefined && entry.step.compensation !== undefined) {\n return oweCompensation(entry.step, entry.step.compensation, i);\n }\n }\n return null;\n }\n\n return {\n init(steps) {\n if (steps.length === 0) {\n throw new Error(\n \"createWorkflow.init: a workflow must have at least one step. An \" +\n \"empty step sequence has no final result to carry into `completed`, \" +\n \"so it is unrepresentable as a completed workflow — reject it at the \" +\n \"boundary rather than admit a resultless terminal state.\",\n );\n }\n const { current, owed, cmd } = oweActivity(stepAt(steps, 0), 0);\n const state: RunningWorkflow<A, R> = {\n status: \"running\",\n steps,\n completed: [],\n current,\n };\n return { state, ledger: [owed], cmds: [cmd] };\n },\n\n onActivityOk(state, msg) {\n // A result for a terminal workflow, or one whose id does not match the\n // in-flight activity, is a no-op — idempotent by delivery id. This is the\n // guard that makes re-emit-on-wake safe: a re-fired (already-folded)\n // activity's result arrives with an id that is no longer `current.id`.\n if (state.status !== \"running\" || msg.id !== state.current.id) {\n return { state, ledger: [], cmds: [] };\n }\n\n // Record the completed step and confirm the owed activity on the ledger.\n const confirmed: EffectConfirmed = confirm(state.current.id);\n const completedStep: CompletedStep<A, R> = {\n step: state.current.step,\n result: msg.result,\n };\n const completed = [...state.completed, completedStep];\n\n const nextIndex = state.current.index + 1;\n if (nextIndex >= state.steps.length) {\n // The final step's result is the workflow's output → `completed`.\n const done: CompletedWorkflow<A, R> = {\n status: \"completed\",\n steps: state.steps,\n completed,\n output: msg.result,\n };\n return { state: done, ledger: [confirmed], cmds: [] };\n }\n\n // Advance: owe + dispatch the next activity.\n const { current, owed, cmd } = oweActivity(\n stepAt(state.steps, nextIndex),\n nextIndex,\n );\n const running: RunningWorkflow<A, R> = {\n status: \"running\",\n steps: state.steps,\n completed,\n current,\n };\n // Persist the confirm of the prior activity AND the owe of the next, in\n // that order, before dispatching the next. (Confirm-then-owe keeps the\n // ledger holding at most one in-flight activity per workflow.)\n return { state: running, ledger: [confirmed, owed], cmds: [cmd] };\n },\n\n onActivityErr(state, msg) {\n if (state.status !== \"running\" || msg.id !== state.current.id) {\n return { state, ledger: [], cmds: [] };\n }\n const confirmed: EffectConfirmed = confirm(state.current.id);\n\n // #125: the forward failure PIVOTS into compensation. Mirroring saga's\n // `stepErr`: walk the completed history in strict reverse, owing the\n // first declared compensation as a durable effect on this SAME ledger.\n // `state.completed` is preserved precisely so this reverse walk has its\n // history.\n const next = oweNextCompensation(state.completed, state.completed.length);\n\n if (next === null) {\n // Empty rollback: no completed step declares a compensation (the first\n // activity failed, OR every completed step is irreversible). The\n // analogue of saga aborting straight from the first step — settle\n // `failed` directly, nothing to unwind (acceptance criterion 3).\n const failed: FailedWorkflow<A, R, F> = {\n status: \"failed\",\n steps: state.steps,\n completed: state.completed,\n failedStep: state.current.step,\n failure: msg.failure,\n };\n return { state: failed, ledger: [confirmed], cmds: [] };\n }\n\n // Pivot to `compensating`, emitting the first compensation. Confirm the\n // failed forward activity AND owe the first compensation, in that order,\n // before dispatching it (the same confirm-then-owe ledger discipline as\n // the forward advance — at most one in-flight effect per workflow).\n const compensating: CompensatingWorkflow<A, R, F> = {\n status: \"compensating\",\n steps: state.steps,\n completed: state.completed,\n failedStep: state.current.step,\n failure: msg.failure,\n current: next.current,\n compensated: [],\n };\n return {\n state: compensating,\n ledger: [confirmed, next.owed],\n cmds: [next.cmd],\n };\n },\n\n onCompensationOk(state, msg) {\n // A compensation result for a non-compensating workflow, or one whose id\n // does not match the in-flight compensation, is a no-op — idempotent by\n // delivery id, the same re-emit-on-wake guard as the forward verbs.\n if (state.status !== \"compensating\" || msg.id !== state.current.id) {\n return { state, ledger: [], cmds: [] };\n }\n\n // Confirm the owed compensation and record the step as compensated.\n const confirmed: EffectConfirmed = confirm(state.current.id);\n const undoneStep = state.completed[state.current.index];\n if (undoneStep === undefined) {\n throw new Error(\n `createWorkflow.onCompensationOk: compensation index ` +\n `${state.current.index} has no completed step — a reverse-walk ` +\n \"bounds proof was violated.\",\n );\n }\n const compensated = [...state.compensated, undoneStep];\n\n // Continue the reverse walk strictly below the step just undone, skipping\n // steps with no compensation.\n const next = oweNextCompensation(state.completed, state.current.index);\n\n if (next === null) {\n // Fully unwound → `failed_compensated` (saga's `aborted`).\n const settled: FailedCompensatedWorkflow<A, R, F> = {\n status: \"failed_compensated\",\n steps: state.steps,\n completed: state.completed,\n failedStep: state.failedStep,\n failure: state.failure,\n };\n return { state: settled, ledger: [confirmed], cmds: [] };\n }\n\n const compensating: CompensatingWorkflow<A, R, F> = {\n status: \"compensating\",\n steps: state.steps,\n completed: state.completed,\n failedStep: state.failedStep,\n failure: state.failure,\n current: next.current,\n compensated,\n };\n return {\n state: compensating,\n ledger: [confirmed, next.owed],\n cmds: [next.cmd],\n };\n },\n\n onCompensationErr(state, msg) {\n // Same id-match idempotency guard as the other verbs.\n if (state.status !== \"compensating\" || msg.id !== state.current.id) {\n return { state, ledger: [], cmds: [] };\n }\n // Confirm the owed compensation (the dispatch is no longer owed — it was\n // delivered and answered, just with a failure), then HALT the rollback at\n // the terminal `compensation_failed` state. Mirroring saga's `undoErr`: a\n // bounced compensation is a real-world fact the consumer must reconcile by\n // hand, never a workflow wedged in `compensating` forever. `compensated`\n // (already rolled back) is left intact for the consumer to read.\n const confirmed: EffectConfirmed = confirm(state.current.id);\n const halted: CompensationFailedWorkflow<A, R, F> = {\n status: \"compensation_failed\",\n steps: state.steps,\n completed: state.completed,\n failedStep: state.failedStep,\n failure: state.failure,\n compensated: state.compensated,\n failedCompensationStep: state.current.step,\n compensationFailure: msg.failure,\n };\n return { state: halted, ledger: [confirmed], cmds: [] };\n },\n\n survivingActivities(ledgerEvents) {\n // Rebuild the ledger by folding the persisted events (NOT a side table),\n // then the surviving owed effects ARE the dispatch Cmds to re-fire — each\n // owed effect's payload is its dispatch Cmd (a forward activity OR a\n // compensation), carrying the same id.\n const ledger: PendingEffectsLedger<WorkflowCmd<A>> =\n foldLedger(ledgerEvents);\n return survivingEffects(ledger).map((owed) => owed.effect);\n },\n };\n\n /** Confirm an owed activity (or compensation) on the recorder's ledger,\n * returning the `effect_confirmed` event to persist. The boolean (was-owed)\n * is not needed by the reducer — the id-match guard above already gates on\n * the in-flight effect — so it is discarded here. */\n function confirm(id: DeliveryId): EffectConfirmed {\n return recorder.confirm(id).event;\n }\n}\n\n// ─────────────────────────────────────────────────────────────────────────────\n// foldWorkflow — the pure replay fold. The determinism contract (acceptance\n// criterion 4) in one function: fold a workflow's full event log — its `init`\n// steps plus the ordered activity-result Msgs — back into a `WorkflowState`,\n// reading no clock and no RNG. Two folds of the same log produce byte-identical\n// state, because every decision is a pure function of (state, msg) and the\n// delivery ids are reissued in the same order from the same fresh recorder.\n//\n// This is the workflow-level twin of `foldLedger`: the host's `replay()` over\n// the event-sourced store re-runs exactly this fold to rebuild a workflow on\n// cold wake. Kept here (not only in the host, #126) so the determinism contract\n// is provable against the pure core alone.\n// ─────────────────────────────────────────────────────────────────────────────\n\n/**\n * Replay a workflow from its event log: seed over `steps`, then fold each\n * activity-result `Msg` in order. Returns the final {@link WorkflowState}.\n *\n * Determinism: a freshly-constructed {@link createWorkflow} reissues delivery\n * ids monotonically from 0, and the reducer reads no ambient state — so two\n * calls with the same `steps` + `msgs` return deeply-equal states (and equal\n * `JSON.stringify`). This is the byte-identity property #124 pins.\n *\n * Note this folds ONLY the result Msgs; the `init` dispatch + per-step\n * owe/confirm ledger events are an internal effect channel reconstructed by the\n * fresh recorder, not part of the replayed Msg log — exactly as the activity\n * results are the only thing the consumer records and replays.\n */\nexport function foldWorkflow<A, R, F>(\n steps: readonly WorkflowStep<A>[],\n msgs: Iterable<WorkflowMsg<R, F>>,\n): WorkflowState<A, R, F> {\n const wf = createWorkflow<A, R, F>();\n let { state } = wf.init(steps);\n for (const msg of msgs) {\n // Route each result Msg to its verb. The forward results (`activity_*`) and\n // the reverse compensation results (`compensation_*`, #125) are folded by\n // the same fresh recorder, so a replay across a failure+compensation\n // sequence re-issues every delivery id in identical order — byte-identity\n // holds end to end (acceptance criterion 4).\n let step: WorkflowStep0<A, R, F>;\n switch (msg.type) {\n case \"activity_ok\":\n step = wf.onActivityOk(state, msg);\n break;\n case \"activity_err\":\n step = wf.onActivityErr(state, msg);\n break;\n case \"compensation_ok\":\n step = wf.onCompensationOk(state, msg);\n break;\n case \"compensation_err\":\n step = wf.onCompensationErr(state, msg);\n break;\n }\n state = step.state;\n }\n return state;\n}\n\n// Re-export the durable-effects types a consumer needs to persist + replay a\n// workflow's ledger (the owed/confirmed events, the delivery id, the empty\n// seed) without reaching into the `../do` subpath directly.\nexport {\n type DeliveryId,\n type EffectConfirmed,\n type EffectLedgerEvent,\n type EffectOwed,\n emptyLedger,\n};\n"]}
1
+ {"version":3,"sources":["../../src/workflow/index.ts"],"names":["id"],"mappings":";;;;AA0jBO,SAAS,eAAwB,OAAA,EAGlB;AAKpB,EAAA,MAAM,QAAA,GAAW,qBAAqC,OAAO,CAAA;AAc7D,EAAA,SAAS,MAAA,CACP,OACA,KAAA,EACiB;AACjB,IAAA,MAAM,IAAA,GAAO,MAAM,KAAK,CAAA;AACxB,IAAA,IAAI,SAAS,MAAA,EAAW;AACtB,MAAA,MAAM,IAAI,KAAA;AAAA,QACR,CAAA,2BAAA,EAA8B,KAAK,CAAA,sBAAA,EAC9B,KAAA,CAAM,MAAM,CAAA,6CAAA;AAAA,OACnB;AAAA,IACF;AACA,IAAA,OAAO,IAAA;AAAA,EACT;AAkBA,EAAA,SAAS,YACP,KAAA,EAKA;AACA,IAAA,MAAM,EAAA,GAAM,QAAA,CAAS,MAAA,EAAO,GAAI,CAAA;AAChC,IAAA,MAAM,GAAA,GAAM,MAAM,EAAE,CAAA;AACpB,IAAA,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KAAA;AAAA,EAC9B;AACF;AA8BO,SAAS,YAAA,CACd,OACA,IAAA,EACwB;AACxB,EAAA,MAAM,KAAK,cAAA,EAAwB;AACnC,EAAA,IAAI,EAAE,KAAA,EAAM,GAAI,EAAA,CAAG,KAAK,KAAK,CAAA;AAC7B,EAAA,KAAA,MAAW,OAAO,IAAA,EAAM;AAMtB,IAAA,IAAI,IAAA;AACJ,IAAA,QAAQ,IAAI,IAAA;AAAM,MAChB,KAAK,aAAA;AACH,QAAA,IAAA,GAAO,EAAA,CAAG,YAAA,CAAa,KAAA,EAAO,GAAG,CAAA;AACjC,QAAA;AAAA,MACF,KAAK,cAAA;AACH,QAAA,IAAA,GAAO,EAAA,CAAG,aAAA,CAAc,KAAA,EAAO,GAAG,CAAA;AAClC,QAAA;AAAA,MACF,KAAK,iBAAA;AACH,QAAA,IAAA,GAAO,EAAA,CAAG,gBAAA,CAAiB,KAAA,EAAO,GAAG,CAAA;AACrC,QAAA;AAAA,MACF,KAAK,kBAAA;AACH,QAAA,IAAA,GAAO,EAAA,CAAG,iBAAA,CAAkB,KAAA,EAAO,GAAG,CAAA;AACtC,QAAA;AAAA;AAEJ,IAAA,KAAA,GAAQ,IAAA,CAAK,KAAA;AAAA,EACf;AACA,EAAA,OAAO,KAAA;AACT","file":"index.js","sourcesContent":["/**\n * @demlik/tea/workflow — the durable-workflow runtime core (#124, the first\n * Phase-1 slice of the Temporal-style durable-workflow engine, epic #118).\n *\n * A workflow is a long-running, multi-step transaction whose every step (an\n * **activity**) is a side effect that may evict the actor mid-flight. The\n * substrate already solves \"a state survives eviction\" (the event-sourced\n * store) and \"an owed effect survives eviction\" (the `do/` pending-effects\n * ledger, #67). This module composes those two into the third primitive: a\n * **pure TEA reducer over a workflow's progress**, where each step is dispatched\n * as a durable owed effect and the next step is decided only after the previous\n * one's result is folded back in. That is exactly Temporal's contract — a\n * deterministic workflow function whose activities are the only impurity, so a\n * replay of the event log re-decides every step identically.\n *\n * The mapping onto TEA, mirroring `../raft`:\n *\n * - **Reducer** — {@link createWorkflow}'s verbs (`init`, `onActivityOk`,\n * `onActivityErr`) are the transition function over {@link WorkflowState}.\n * PURE: they read no clock and no RNG. Wall time, randomness, retries — all\n * impurity lives in the consumer's injected *interpret cell* (the thing that\n * actually performs the activity `Cmd` and dispatches its result `Msg`).\n * A workflow driven by a recorded result schedule re-decides bit-for-bit —\n * the headline replay-determinism payoff (acceptance criterion 4).\n * - **Cmd** — the activity dispatch is an {@link ActivityCmd}, recorded on the\n * #67 ledger as an `effect_owed` BEFORE it is performed and `effect_confirmed`\n * on its result. This module emits the Cmd literals; it performs NO side\n * effects. The owed/confirmed events are persisted into the same log the\n * reducer folds, so the ledger (and thus \"which activity is still owed\")\n * rebuilds for free on cold wake — re-emit-on-wake is idempotent by the\n * ledger's monotonic delivery id (acceptance criterion 3).\n * - **Msg** — an activity result (`activity_ok` / `activity_err`) is a `Msg`\n * the consumer routes back into a verb. The verb folds the result, records\n * the completed step, and advances to the next activity (or to `completed`\n * when the sequence is exhausted).\n *\n * **Invalid states unrepresentable.** The in-flight activity (`current`, with\n * its delivery id) lives ONLY on the `running` variant of {@link WorkflowState}.\n * A `completed` workflow carries its final output and no current activity; a\n * `failed` one carries its failure and no current activity. So \"the current\n * activity exists only while running\" is a type-level guarantee, not a runtime\n * convention (acceptance criterion 1).\n *\n * **Boundary with `@demlik/tea/saga` — the compensation test.** Both drive an\n * ordered multi-step transaction with reverse-order compensation (#125 here);\n * the line between them is whether every step carries a true inverse. Here\n * {@link WorkflowStep.compensation} is OPTIONAL — an irreversible step (a sent\n * email) is simply SKIPPED during the unwind, and the run still reaches a\n * terminal state. Saga's `SagaStep<D, U>` REQUIRES both `do` and `undo` — a\n * step without its inverse is unrepresentable, so full reversibility is a\n * type-level guarantee. Pick by the test: **every step must be reversible →\n * saga; some steps are irreversible but the run must finish → workflow.**\n * Cross to saga when you want the type system to enforce that every step can\n * be undone; stay here when the transaction includes steps that can't be.\n *\n * This module is the pure reducer only — like `../raft/index.ts` is the pure\n * Raft reducer with the DO grain deferred to its `./do` sibling (here #126).\n *\n * Generic over three opaque payloads, like raft's command generic: the activity\n * descriptor `A` (what a step asks to do — the consumer's interpret cell knows\n * how to perform it), the activity result `R`, and the failure `F`. The reducer\n * never inspects them; it only sequences them.\n *\n * NOT a substrate primitive: it depends only on the core `Cmd` type and the\n * sibling `../do` durable-effects ledger. Consumers reach it via the\n * `@demlik/tea/workflow` subpath.\n */\n\nimport {\n type DeliveryId,\n type EffectConfirmed,\n type EffectLedgerEvent,\n type EffectOwed,\n emptyLedger,\n foldLedger,\n type PendingEffectsLedger,\n pendingEffectsLedger,\n survivingEffects,\n} from \"../do/durable-effects\";\nimport type { Cmd } from \"../index\";\n\n// ─────────────────────────────────────────────────────────────────────────────\n// Steps — the static definition of a workflow.\n//\n// A workflow is defined by an ordered sequence of steps. A step is an activity\n// descriptor: a stable `name` (for readability + correlation in the event log)\n// plus the opaque `activity` payload the consumer's interpret cell performs.\n// Steps are inert data; the reducer walks them in order.\n// ─────────────────────────────────────────────────────────────────────────────\n\n/**\n * One step of a workflow: a named activity descriptor. `A` is the opaque\n * payload the consumer's interpret cell knows how to perform (an HTTP call, a\n * sibling-grain message, a tool round-trip). The reducer never inspects\n * `activity` — it only sequences the steps and correlates results.\n *\n * A step may declare a **compensation** — the inverse activity that undoes the\n * forward one (cancel the reservation, refund the charge). Compensation is the\n * `{ do, undo }` pair of `@demlik/tea/saga` mapped onto the workflow: the step's\n * `activity` is the `do`, its `compensation` is the `undo`. The pair is the unit\n * of reversibility — a step that completed (its forward activity succeeded) is\n * exactly a step whose `compensation` must run, in reverse order, if a LATER\n * step fails (#125). A step WITHOUT a compensation contributes nothing to the\n * unwind: it is skipped during the reverse walk (an irreversible step — a sent\n * email — that the saga model treats as a no-op `undo`).\n */\nexport interface WorkflowStep<A> {\n /** Stable, human-readable step name — appears in the completed-step record. */\n readonly name: string;\n /** The opaque activity this step performs. Interpreted by the consumer. */\n readonly activity: A;\n /**\n * The opaque compensating (inverse) activity, performed in reverse order on a\n * downstream failure (#125). Optional: a step with no compensation is skipped\n * during the unwind. Interpreted by the consumer's interpret cell, exactly\n * like {@link activity}.\n */\n readonly compensation?: A;\n}\n\n/**\n * A completed step: the step that ran plus the result its activity produced.\n * The `running` state accumulates these in execution order, so the full\n * forward history is available to the consumer (and to #125's compensation,\n * which will walk it in reverse).\n */\nexport interface CompletedStep<A, R> {\n readonly step: WorkflowStep<A>;\n readonly result: R;\n}\n\n// ─────────────────────────────────────────────────────────────────────────────\n// The in-flight activity — the bridge between the reducer and the #67 ledger.\n//\n// While `running`, exactly one activity is in flight. It carries the step it is\n// performing AND the monotonic `deliveryId` the #67 ledger issued for it. The\n// delivery id is the single correlation key: an `activity_ok`/`activity_err`\n// Msg names the id it answers, the reducer matches it against `current.id`, and\n// the ledger confirms that same id. Re-emit-on-wake re-fires the SAME id, so a\n// duplicate result is a no-op (idempotent by delivery id, acceptance crit. 3).\n// ─────────────────────────────────────────────────────────────────────────────\n\n/** The activity currently in flight on a `running` workflow. */\nexport interface InFlightActivity<A> {\n /** The 0-based index of this step in the workflow's step sequence. */\n readonly index: number;\n /** The step whose activity is in flight. */\n readonly step: WorkflowStep<A>;\n /** The #67 ledger delivery id this activity was owed under (the dedup key). */\n readonly id: DeliveryId;\n}\n\n/**\n * The compensation currently in flight on a `compensating` workflow (#125). The\n * mirror of {@link InFlightActivity} for the reverse walk: exactly one\n * compensation is owed at a time, on the SAME #67 ledger, with its own monotonic\n * delivery id. `index` is the index (into `completed`/`steps`) of the step being\n * undone — the unwind walks these from high to low (strict reverse order).\n */\nexport interface InFlightCompensation<A> {\n /** The 0-based index (into the step sequence) of the step being compensated. */\n readonly index: number;\n /** The step whose compensation is in flight. */\n readonly step: WorkflowStep<A>;\n /** The #67 ledger delivery id this compensation was owed under (the dedup key). */\n readonly id: DeliveryId;\n}\n\n// ─────────────────────────────────────────────────────────────────────────────\n// WorkflowState — the discriminated union. Invalid states unrepresentable.\n//\n// `status` is the discriminant. The in-flight `current` activity exists ONLY on\n// `running` and `compensating`; `completed` carries the final `output`;\n// `failed` / `failed_compensated` / `compensation_failed` carry the failure.\n// There is no representable state with a current activity that is neither\n// running nor compensating, nor a terminal state still holding one\n// (acceptance crit. 1).\n//\n// The failure path (#125), mirroring `@demlik/tea/saga`'s phases:\n//\n// running ──activity_err with completed steps──▶ compensating\n// running ──activity_err with NO completed steps──▶ failed (empty rollback)\n// compensating ──all compensations confirmed──▶ failed_compensated\n// compensating ──a compensation itself fails──▶ compensation_failed\n//\n// `compensating` is the analogue of saga's `compensating`; `failed_compensated`\n// of saga's `aborted` (fully unwound); `compensation_failed` of saga's\n// `compensation_failed` (an `undo` bounced, partially unwound — visible state,\n// never a workflow wedged in `compensating` forever).\n// ─────────────────────────────────────────────────────────────────────────────\n\n/**\n * A workflow in progress. Carries the ordered `completed` steps (forward\n * history), the `steps` it is sequencing, and the `current` in-flight activity\n * (with its ledger delivery id). `completed.length === current.index` always\n * holds — the current activity is the next step after the last completed one.\n */\nexport interface RunningWorkflow<A, R> {\n readonly status: \"running\";\n /** The full, static step sequence this workflow runs. */\n readonly steps: readonly WorkflowStep<A>[];\n /** Steps that have produced a result, in execution order. */\n readonly completed: readonly CompletedStep<A, R>[];\n /** The single activity in flight right now. */\n readonly current: InFlightActivity<A>;\n}\n\n/**\n * A workflow that ran every step to completion. `output` is the result of the\n * final step — the workflow's overall output. No activity is in flight.\n */\nexport interface CompletedWorkflow<A, R> {\n readonly status: \"completed\";\n readonly steps: readonly WorkflowStep<A>[];\n /** Every step, in execution order, with its result. */\n readonly completed: readonly CompletedStep<A, R>[];\n /** The final step's result — the workflow's output. */\n readonly output: R;\n}\n\n/**\n * A workflow that failed on an activity with NOTHING to compensate — the\n * forward failure happened with zero completed steps (the first activity\n * failed). `failedStep` is the step whose activity reported the failure;\n * `failure` is the opaque failure payload. `completed` is empty by construction:\n * a failure WITH completed steps pivots into {@link CompensatingWorkflow}\n * instead, so `failed` is precisely the empty-rollback terminal (the analogue\n * of saga's `aborted` reached straight from the first step). No activity is in\n * flight; this is terminal (#125 acceptance criterion 3).\n */\nexport interface FailedWorkflow<A, R, F> {\n readonly status: \"failed\";\n readonly steps: readonly WorkflowStep<A>[];\n /** Empty by construction — a failure with completed steps compensates instead. */\n readonly completed: readonly CompletedStep<A, R>[];\n /** The step whose activity failed. */\n readonly failedStep: WorkflowStep<A>;\n /** The opaque failure the activity reported. */\n readonly failure: F;\n}\n\n/**\n * A workflow unwinding after a forward failure (#125): the compensations of the\n * `completed` steps are being emitted in STRICT REVERSE order, one at a time, on\n * the same #67 ledger. The analogue of saga's `compensating` phase.\n *\n * `current` is the single compensation in flight (the mirror of `running`'s\n * in-flight activity). `compensated` records, in unwind order, the completed\n * steps whose compensation has confirmed — the reverse-walk's progress log, so\n * a cold wake resumes mid-rollback exactly. `failedStep`/`failure` carry the\n * forward failure that triggered the unwind (verbatim, never interpreted),\n * preserved for the consumer to read and to fold onto the terminal state.\n *\n * Invariant: the unwind walks `completed` from its tail toward index 0, skipping\n * steps with no compensation, so `current.index` is strictly below the index of\n * every entry in `compensated`.\n */\nexport interface CompensatingWorkflow<A, R, F> {\n readonly status: \"compensating\";\n readonly steps: readonly WorkflowStep<A>[];\n /** The completed forward steps, in execution order — the history being unwound. */\n readonly completed: readonly CompletedStep<A, R>[];\n /** The step whose forward activity failed, triggering the unwind. */\n readonly failedStep: WorkflowStep<A>;\n /** The opaque forward failure that triggered the unwind. Carried, never interpreted. */\n readonly failure: F;\n /** The single compensation in flight right now. */\n readonly current: InFlightCompensation<A>;\n /** Completed steps whose compensation has confirmed, in unwind (reverse) order. */\n readonly compensated: readonly CompletedStep<A, R>[];\n}\n\n/**\n * A workflow that failed forward and then fully unwound: every completed step's\n * compensation confirmed, in reverse order. Terminal. The analogue of saga's\n * `aborted` (fully unwound) — named `failed_compensated` to align with #125's\n * vocabulary. No activity or compensation is in flight.\n */\nexport interface FailedCompensatedWorkflow<A, R, F> {\n readonly status: \"failed_compensated\";\n readonly steps: readonly WorkflowStep<A>[];\n /** The forward steps that completed (and were each compensated), in execution order. */\n readonly completed: readonly CompletedStep<A, R>[];\n /** The step whose forward activity failed, triggering the (now-finished) unwind. */\n readonly failedStep: WorkflowStep<A>;\n /** The opaque forward failure that triggered compensation. Carried, never interpreted. */\n readonly failure: F;\n}\n\n/**\n * A workflow whose ROLLBACK itself failed: a compensation activity reported a\n * failure mid-unwind. Terminal, PARTIALLY unwound — the analogue of saga's\n * `compensation_failed`. A failed compensation is a real-world fact (a refund\n * that bounced, a hold that won't release) that must become visible terminal\n * state, never a workflow wedged in `compensating` forever.\n *\n * `compensated` is left intact (the steps already rolled back); `uncompensated`\n * is the step whose compensation bounced PLUS the steps still owed a\n * compensation behind it — exactly what the consumer must reconcile by hand.\n * `compensationFailure` is the rollback failure (distinct from `failure`, the\n * forward failure that started the unwind), carried verbatim.\n */\nexport interface CompensationFailedWorkflow<A, R, F> {\n readonly status: \"compensation_failed\";\n readonly steps: readonly WorkflowStep<A>[];\n /** The full completed-forward history, in execution order. */\n readonly completed: readonly CompletedStep<A, R>[];\n /** The step whose forward activity failed, triggering the unwind. */\n readonly failedStep: WorkflowStep<A>;\n /** The opaque forward failure that triggered compensation. Carried, never interpreted. */\n readonly failure: F;\n /** Completed steps successfully compensated before the rollback broke, in unwind order. */\n readonly compensated: readonly CompletedStep<A, R>[];\n /** The step whose compensation bounced. Its forward effect stands un-reversed. */\n readonly failedCompensationStep: WorkflowStep<A>;\n /** The opaque rollback failure (distinct from {@link failure}). Carried, never interpreted. */\n readonly compensationFailure: F;\n}\n\n/**\n * The workflow's state — a discriminated union on `status`. The current\n * in-flight activity is reachable ONLY through `running`, and the in-flight\n * compensation ONLY through `compensating`, making \"an in-flight effect exists\n * only while the workflow is actively driving one\" unrepresentable to violate.\n */\nexport type WorkflowState<A, R, F> =\n | RunningWorkflow<A, R>\n | CompletedWorkflow<A, R>\n | FailedWorkflow<A, R, F>\n | CompensatingWorkflow<A, R, F>\n | FailedCompensatedWorkflow<A, R, F>\n | CompensationFailedWorkflow<A, R, F>;\n\n// ─────────────────────────────────────────────────────────────────────────────\n// Cmds — the activity dispatch. Recorded on the #67 ledger as an owed effect.\n//\n// `ActivityCmd` is the single Cmd this module emits: \"perform the activity for\n// step `index`, and the result you dispatch back must carry delivery id `id`\".\n// The consumer's interpret cell performs `activity` and dispatches an\n// `ActivityOk`/`ActivityErr` Msg carrying the SAME id. The owed/confirmed\n// ledger events ride alongside (see {@link WorkflowStep0}/the step tuple).\n// ─────────────────────────────────────────────────────────────────────────────\n\n/**\n * Dispatch the in-flight activity. Routed through the consumer's `interpret`\n * over an injected activity port. The reducer emits this literal; it performs\n * no side effect. The result MUST be dispatched back as a Msg carrying `id`.\n */\nexport interface ActivityCmd<A> extends Cmd<\"workflow_activity\"> {\n /** The 0-based step index this activity belongs to. */\n readonly index: number;\n /** The #67 delivery id the result Msg must echo (the dedup key). */\n readonly id: DeliveryId;\n /** The opaque activity to perform. */\n readonly activity: A;\n}\n\n/**\n * Dispatch a compensation (#125). Same shape + ledger discipline as\n * {@link ActivityCmd} — a compensation is just another durable owed effect on\n * the same #67 ledger, with its own delivery id — but the consumer's interpret\n * cell performs the inverse `compensation` payload, and the result is dispatched\n * back as a {@link CompensationOk}/{@link CompensationErr} carrying the SAME id.\n * Distinguished by `type` so the consumer routes forward vs. inverse work to the\n * right port, and the re-emit-on-wake stays type-correct.\n */\nexport interface CompensationCmd<A> extends Cmd<\"workflow_compensation\"> {\n /** The 0-based step index whose compensation this is. */\n readonly index: number;\n /** The #67 delivery id the result Msg must echo (the dedup key). */\n readonly id: DeliveryId;\n /** The opaque compensating (inverse) activity to perform. */\n readonly compensation: A;\n}\n\n/** The Cmd union this module emits: forward activity dispatches AND (#125)\n * reverse compensation dispatches. The owed/confirmed ledger events are not\n * `WorkflowCmd`s — they are Msg variants persisted into the event log (see\n * {@link EffectLedgerEvent}); the {@link WorkflowStep0} tuple carries them out\n * alongside the dispatch Cmd so the host persists owed-before-dispatch. Both\n * Cmd kinds are owed effects on the same ledger, so `survivingActivities`\n * re-emits either kind on cold wake. */\nexport type WorkflowCmd<A> = ActivityCmd<A> | CompensationCmd<A>;\n\n// ─────────────────────────────────────────────────────────────────────────────\n// Msgs — activity results the consumer routes back into the reducer.\n// ─────────────────────────────────────────────────────────────────────────────\n\n/** An activity succeeded: `id` echoes the {@link ActivityCmd} it answers; the\n * reducer matches it against `current.id`, records the completed step, and\n * advances. */\nexport interface ActivityOk<R> {\n readonly type: \"activity_ok\";\n readonly id: DeliveryId;\n readonly result: R;\n}\n\n/** An activity failed (retries already exhausted by the consumer's interpret\n * cell — this module does not retry). `id` echoes the {@link ActivityCmd};\n * the reducer begins compensation (or settles `failed` when nothing has\n * completed). */\nexport interface ActivityErr<F> {\n readonly type: \"activity_err\";\n readonly id: DeliveryId;\n readonly failure: F;\n}\n\n/** A compensation succeeded (#125): the inverse activity took. `id` echoes the\n * {@link CompensationCmd} it answers; the reducer matches it against the\n * in-flight compensation's id, records the step as compensated, and either\n * emits the next compensation (continuing in reverse) or settles\n * `failed_compensated` when the unwind is complete. A compensation produces no\n * result the workflow carries — its only signal is \"the undo took\". */\nexport interface CompensationOk {\n readonly type: \"compensation_ok\";\n readonly id: DeliveryId;\n}\n\n/** A compensation itself failed (#125): the inverse activity bounced (a refund\n * that won't go through). `id` echoes the {@link CompensationCmd}; the reducer\n * halts the rollback at the terminal `compensation_failed` state — never wedged\n * in `compensating` forever. */\nexport interface CompensationErr<F> {\n readonly type: \"compensation_err\";\n readonly id: DeliveryId;\n readonly failure: F;\n}\n\n/** The Msg union the reducer folds: forward activity results AND (#125) reverse\n * compensation results. */\nexport type WorkflowMsg<R, F> =\n | ActivityOk<R>\n | ActivityErr<F>\n | CompensationOk\n | CompensationErr<F>;\n\n// ─────────────────────────────────────────────────────────────────────────────\n// The step tuple — the reducer's output shape.\n//\n// A verb returns the next `WorkflowState` PLUS the side-effect intents the host\n// must enact, in the ORDER they must be enacted (owed-before-dispatch):\n//\n// - `ledger` — the `effect_owed` / `effect_confirmed` events to PERSIST into\n// the same event log the reducer folds. A `running`-emitting verb owes the\n// new activity (and a verb that folded a prior result confirms it). Persist\n// these BEFORE the dispatch Cmd (the #67 \"persist the intent before deliver\"\n// rule) so an eviction between persist and dispatch re-fires on wake.\n// - `cmds` — the activity dispatch Cmd(s). Empty on a terminal transition.\n//\n// This is the same `readonly [state, cmds]` discipline as raft's `RaftStep`,\n// extended with the ledger-events channel because activities ARE owed effects.\n// ─────────────────────────────────────────────────────────────────────────────\n\n/** A workflow reducer step: the next state, the ledger events to persist\n * (owed-before-dispatch), and the activity Cmds to dispatch. */\nexport interface WorkflowStep0<A, R, F> {\n readonly state: WorkflowState<A, R, F>;\n /** Ledger events to persist into the event log, in order, BEFORE `cmds`. */\n readonly ledger: readonly EffectLedgerEvent<WorkflowCmd<A>>[];\n /** Activity dispatch Cmds, after the ledger events are durable. */\n readonly cmds: readonly WorkflowCmd<A>[];\n}\n\n// ─────────────────────────────────────────────────────────────────────────────\n// createWorkflow — the factory. Returns the hook bag (init/verbs), mirroring\n// how `createRaftNode` / `createAgent` shape their knobs. The factory owns the\n// #67 monotonic-id recorder so every dispatched activity gets a gap-free\n// delivery id; the recorder is rehydrated from the persisted ledger events on\n// cold wake (see `restore`) so ids resume without gaps.\n// ─────────────────────────────────────────────────────────────────────────────\n\n/** The hook bag returned by {@link createWorkflow}. Spread its verbs into a\n * machine; `init(steps)` seeds a fresh workflow and emits the first activity,\n * the verbs fold results and advance, and `survivingActivities` re-emits the\n * owed-but-unconfirmed dispatch on cold wake (idempotent by delivery id). */\nexport interface Workflow<A, R, F> {\n /**\n * Seed a fresh workflow over `steps` and dispatch its first activity.\n *\n * - Empty `steps` ⇒ a workflow with nothing to do completes only when it has\n * an output; with no steps there is no output, so an empty sequence is\n * rejected as a misuse (a workflow must have at least one step). The reducer\n * never reaches `completed` without a final result to carry.\n * - Otherwise → `running` with `current` = step 0, owed on the ledger.\n */\n init(steps: readonly WorkflowStep<A>[]): WorkflowStep0<A, R, F>;\n\n /**\n * Fold an activity success. If `msg.id` does not match the in-flight\n * activity's id (a stale/duplicate result from re-emit-on-wake, or a result\n * for an already-advanced step), the state is returned UNCHANGED with no\n * effects — idempotent by delivery id (acceptance criterion 3). Otherwise:\n * record the completed step, confirm the owed activity on the ledger, and\n * either advance to the next step (owing its activity) or transition to\n * `completed` carrying the final result.\n *\n * Only meaningful on `running`; a result arriving for a terminal workflow is\n * a no-op (the workflow is done — at-least-once tolerates the late echo).\n */\n onActivityOk(\n state: WorkflowState<A, R, F>,\n msg: ActivityOk<R>,\n ): WorkflowStep0<A, R, F>;\n\n /**\n * Fold an activity failure (#125). Same id-match idempotency guard as\n * {@link onActivityOk}. On a match: confirm the owed activity on the ledger,\n * then PIVOT into compensation — walk the completed-step history in strict\n * reverse and owe the first declared compensation as a durable effect on the\n * same ledger, transitioning to `compensating`. If NO completed step declares\n * a compensation (the empty-rollback edge — the first activity failed, or\n * every completed step is irreversible), settle `failed` directly with\n * nothing to unwind.\n */\n onActivityErr(\n state: WorkflowState<A, R, F>,\n msg: ActivityErr<F>,\n ): WorkflowStep0<A, R, F>;\n\n /**\n * Fold a compensation success (#125). Same id-match idempotency guard against\n * the in-flight compensation. On a match: confirm the owed compensation,\n * record the step as compensated, and continue the reverse walk — owe the\n * next declared compensation strictly below the step just undone, or settle\n * `failed_compensated` when the unwind is complete. Only meaningful on\n * `compensating`; a result for a terminal/forward workflow is a no-op.\n */\n onCompensationOk(\n state: WorkflowState<A, R, F>,\n msg: CompensationOk,\n ): WorkflowStep0<A, R, F>;\n\n /**\n * Fold a compensation failure (#125). Same id-match idempotency guard. On a\n * match: confirm the owed compensation and HALT the rollback at the terminal\n * `compensation_failed` state — a bounced compensation is visible terminal\n * state to reconcile by hand, never a workflow wedged in `compensating`\n * forever. Mirrors `@demlik/tea/saga`'s `undoErr`.\n */\n onCompensationErr(\n state: WorkflowState<A, R, F>,\n msg: CompensationErr<F>,\n ): WorkflowStep0<A, R, F>;\n\n /**\n * The owed-but-unconfirmed dispatch(es) to re-emit on activation — a forward\n * activity OR (#125) a compensation, rebuilt by folding the persisted ledger\n * events. On a fresh / fully-settled workflow this is empty. The re-fired Cmd\n * carries the SAME delivery id, so a duplicate result is a no-op at the\n * reducer (the id-match guard). This is the cold-wake re-emit that makes both\n * activities AND compensations exactly-once-observable despite the\n * at-least-once transport (acceptance criterion 2 & 3) — including a\n * compensation owed mid-rollback when the actor was evicted.\n */\n survivingActivities(\n ledgerEvents: Iterable<EffectLedgerEvent<WorkflowCmd<A>>>,\n ): readonly WorkflowCmd<A>[];\n}\n\n/**\n * Build a workflow hook bag. The factory captures NO clock and NO RNG — pure\n * bookkeeping over the injected #67 recorder, exactly like\n * `pendingEffectsLedger`. `restore` rehydrates the monotonic delivery-id\n * counter from the persisted ledger events on cold wake, so re-dispatched\n * activities resume their ids without gaps.\n *\n * @param restore - the persisted ledger events (read back from the log) and/or\n * the last issued delivery id, so the id counter resumes gap-free. Omit for a\n * fresh workflow.\n */\nexport function createWorkflow<A, R, F>(restore?: {\n readonly events?: Iterable<EffectLedgerEvent<WorkflowCmd<A>>>;\n readonly lastId?: DeliveryId;\n}): Workflow<A, R, F> {\n // The #67 monotonic-id recorder. It owns the gap-free `deliveryId` and folds\n // an in-memory mirror of the ledger from the same owed/confirmed events the\n // host persists. Reused verbatim — activities AND compensations ARE owed\n // effects on this one ledger (do NOT reinvent the ledger).\n const recorder = pendingEffectsLedger<WorkflowCmd<A>>(restore);\n\n /**\n * Owe + dispatch the activity for `step` at `index`: allocate its delivery\n * id, build the dispatch Cmd, and emit BOTH the `effect_owed` ledger event\n * (to persist first) and the dispatch Cmd. The owed effect IS the dispatch\n * Cmd, so a cold wake re-emits the identical dispatch by folding the ledger.\n *\n * Returns the running state's `current` plus the owed event + dispatch Cmd.\n */\n /** Index into a step sequence with a bounds-check narrowing away `undefined`\n * (`noUncheckedIndexedAccess`). Every call site has already proven the index\n * in range — this converts that proof into the non-optional type, throwing\n * only on a logic error that should be unreachable. */\n function stepAt(\n steps: readonly WorkflowStep<A>[],\n index: number,\n ): WorkflowStep<A> {\n const step = steps[index];\n if (step === undefined) {\n throw new Error(\n `createWorkflow: step index ${index} out of range (length ` +\n `${steps.length}) — a reducer bounds proof was violated.`,\n );\n }\n return step;\n }\n\n /**\n * Predict the next delivery id, build the FINAL dispatch Cmd with it via\n * `build`, owe that exact Cmd on the #67 ledger, and assert the issued id\n * equals the prediction.\n *\n * The dispatch Cmd needs the delivery id, and the ledger event carries that\n * Cmd as its `effect` payload — so the id and the Cmd are mutually dependent.\n * Resolve the cycle by predicting the next id (`lastId() + 1`, the recorder's\n * gap-free monotonic rule), building the final Cmd, then handing that exact\n * Cmd to `recorder.owe`. The recorder issues the predicted id and folds the\n * final Cmd into its mirror — so the mirror, the persisted `effect_owed`\n * event, and the dispatch Cmd all carry one identical id and payload (no\n * placeholder, no rebuild). Shared by the forward owe ({@link oweActivity})\n * and the reverse owe ({@link oweCompensation}) so both halves of the\n * transaction allocate ids on the SAME monotonic ledger.\n */\n function oweOnLedger<C extends WorkflowCmd<A>>(\n build: (id: DeliveryId) => C,\n ): {\n readonly id: DeliveryId;\n readonly owed: EffectOwed<WorkflowCmd<A>>;\n readonly cmd: C;\n } {\n const id = (recorder.lastId() + 1) as DeliveryId;\n const cmd = build(id);\n const { id: issued, event } = recorder.owe(cmd);\n // Defensive: the prediction must equal the issued id, or the ledger mirror\n // and the dispatch Cmd would diverge. This holds by the recorder's gap-free\n // monotonic contract; assert it rather than silently carry a mismatch.\n if (issued !== id) {\n throw new Error(\n `createWorkflow: delivery-id prediction (${id}) diverged from the ` +\n `recorder's issued id (${issued}). The #67 recorder's monotonic ` +\n \"counter is not gap-free as assumed — this is a substrate invariant \" +\n \"violation, not a recoverable condition.\",\n );\n }\n return { id, owed: event, cmd };\n }\n\n function oweActivity(\n step: WorkflowStep<A>,\n index: number,\n ): {\n readonly current: InFlightActivity<A>;\n readonly owed: EffectOwed<WorkflowCmd<A>>;\n readonly cmd: ActivityCmd<A>;\n } {\n const { id, owed, cmd } = oweOnLedger<ActivityCmd<A>>((id) => ({\n type: \"workflow_activity\",\n index,\n id,\n activity: step.activity,\n }));\n const current: InFlightActivity<A> = { index, step, id };\n return { current, owed, cmd };\n }\n\n /**\n * Owe + dispatch the COMPENSATION for the completed step at `index` (#125):\n * the reverse-walk mirror of {@link oweActivity}. The compensation is a\n * durable owed effect on the SAME #67 ledger, so a cold wake mid-rollback\n * re-emits the identical compensation dispatch by folding the ledger\n * (acceptance criterion 2). `step.compensation` is required to be present —\n * the caller (the reverse walk) only owes compensations for steps that\n * declared one, skipping the rest.\n */\n function oweCompensation(\n step: WorkflowStep<A>,\n compensation: A,\n index: number,\n ): {\n readonly current: InFlightCompensation<A>;\n readonly owed: EffectOwed<WorkflowCmd<A>>;\n readonly cmd: CompensationCmd<A>;\n } {\n const { id, owed, cmd } = oweOnLedger<CompensationCmd<A>>((id) => ({\n type: \"workflow_compensation\",\n index,\n id,\n compensation,\n }));\n const current: InFlightCompensation<A> = { index, step, id };\n return { current, owed, cmd };\n }\n\n /**\n * Begin (or continue) the reverse walk from `completed`, owing the next\n * compensation strictly BELOW `belowIndex` (exclusive) that declares one. The\n * single source of truth for \"what to undo next\", shared by the failure pivot\n * ({@link Workflow.onActivityErr}) and each `compensation_ok` step\n * ({@link Workflow.onCompensationOk}). Steps with no compensation are SKIPPED\n * (they contribute nothing to the unwind — saga's no-op `undo`).\n *\n * Returns the next compensation to owe (its in-flight record + ledger event +\n * dispatch Cmd), or `null` when no compensable step remains below `belowIndex`\n * — the unwind is complete and the caller settles `failed_compensated`.\n */\n function oweNextCompensation(\n completed: readonly CompletedStep<A, R>[],\n belowIndex: number,\n ): {\n readonly current: InFlightCompensation<A>;\n readonly owed: EffectOwed<WorkflowCmd<A>>;\n readonly cmd: CompensationCmd<A>;\n } | null {\n // Walk the completed history from just below `belowIndex` toward 0 (strict\n // reverse order), stopping at the first step that declares a compensation.\n for (let i = belowIndex - 1; i >= 0; i--) {\n const entry = completed[i];\n // `completed[i]` is the i-th completed step; `i` is also its step index\n // (completed is in execution order, contiguous from 0 up to the failure).\n if (entry !== undefined && entry.step.compensation !== undefined) {\n return oweCompensation(entry.step, entry.step.compensation, i);\n }\n }\n return null;\n }\n\n return {\n init(steps) {\n if (steps.length === 0) {\n throw new Error(\n \"createWorkflow.init: a workflow must have at least one step. An \" +\n \"empty step sequence has no final result to carry into `completed`, \" +\n \"so it is unrepresentable as a completed workflow — reject it at the \" +\n \"boundary rather than admit a resultless terminal state.\",\n );\n }\n const { current, owed, cmd } = oweActivity(stepAt(steps, 0), 0);\n const state: RunningWorkflow<A, R> = {\n status: \"running\",\n steps,\n completed: [],\n current,\n };\n return { state, ledger: [owed], cmds: [cmd] };\n },\n\n onActivityOk(state, msg) {\n // A result for a terminal workflow, or one whose id does not match the\n // in-flight activity, is a no-op — idempotent by delivery id. This is the\n // guard that makes re-emit-on-wake safe: a re-fired (already-folded)\n // activity's result arrives with an id that is no longer `current.id`.\n if (state.status !== \"running\" || msg.id !== state.current.id) {\n return { state, ledger: [], cmds: [] };\n }\n\n // Record the completed step and confirm the owed activity on the ledger.\n const confirmed: EffectConfirmed = confirm(state.current.id);\n const completedStep: CompletedStep<A, R> = {\n step: state.current.step,\n result: msg.result,\n };\n const completed = [...state.completed, completedStep];\n\n const nextIndex = state.current.index + 1;\n if (nextIndex >= state.steps.length) {\n // The final step's result is the workflow's output → `completed`.\n const done: CompletedWorkflow<A, R> = {\n status: \"completed\",\n steps: state.steps,\n completed,\n output: msg.result,\n };\n return { state: done, ledger: [confirmed], cmds: [] };\n }\n\n // Advance: owe + dispatch the next activity.\n const { current, owed, cmd } = oweActivity(\n stepAt(state.steps, nextIndex),\n nextIndex,\n );\n const running: RunningWorkflow<A, R> = {\n status: \"running\",\n steps: state.steps,\n completed,\n current,\n };\n // Persist the confirm of the prior activity AND the owe of the next, in\n // that order, before dispatching the next. (Confirm-then-owe keeps the\n // ledger holding at most one in-flight activity per workflow.)\n return { state: running, ledger: [confirmed, owed], cmds: [cmd] };\n },\n\n onActivityErr(state, msg) {\n if (state.status !== \"running\" || msg.id !== state.current.id) {\n return { state, ledger: [], cmds: [] };\n }\n const confirmed: EffectConfirmed = confirm(state.current.id);\n\n // #125: the forward failure PIVOTS into compensation. Mirroring saga's\n // `stepErr`: walk the completed history in strict reverse, owing the\n // first declared compensation as a durable effect on this SAME ledger.\n // `state.completed` is preserved precisely so this reverse walk has its\n // history.\n const next = oweNextCompensation(state.completed, state.completed.length);\n\n if (next === null) {\n // Empty rollback: no completed step declares a compensation (the first\n // activity failed, OR every completed step is irreversible). The\n // analogue of saga aborting straight from the first step — settle\n // `failed` directly, nothing to unwind (acceptance criterion 3).\n const failed: FailedWorkflow<A, R, F> = {\n status: \"failed\",\n steps: state.steps,\n completed: state.completed,\n failedStep: state.current.step,\n failure: msg.failure,\n };\n return { state: failed, ledger: [confirmed], cmds: [] };\n }\n\n // Pivot to `compensating`, emitting the first compensation. Confirm the\n // failed forward activity AND owe the first compensation, in that order,\n // before dispatching it (the same confirm-then-owe ledger discipline as\n // the forward advance — at most one in-flight effect per workflow).\n const compensating: CompensatingWorkflow<A, R, F> = {\n status: \"compensating\",\n steps: state.steps,\n completed: state.completed,\n failedStep: state.current.step,\n failure: msg.failure,\n current: next.current,\n compensated: [],\n };\n return {\n state: compensating,\n ledger: [confirmed, next.owed],\n cmds: [next.cmd],\n };\n },\n\n onCompensationOk(state, msg) {\n // A compensation result for a non-compensating workflow, or one whose id\n // does not match the in-flight compensation, is a no-op — idempotent by\n // delivery id, the same re-emit-on-wake guard as the forward verbs.\n if (state.status !== \"compensating\" || msg.id !== state.current.id) {\n return { state, ledger: [], cmds: [] };\n }\n\n // Confirm the owed compensation and record the step as compensated.\n const confirmed: EffectConfirmed = confirm(state.current.id);\n const undoneStep = state.completed[state.current.index];\n if (undoneStep === undefined) {\n throw new Error(\n `createWorkflow.onCompensationOk: compensation index ` +\n `${state.current.index} has no completed step — a reverse-walk ` +\n \"bounds proof was violated.\",\n );\n }\n const compensated = [...state.compensated, undoneStep];\n\n // Continue the reverse walk strictly below the step just undone, skipping\n // steps with no compensation.\n const next = oweNextCompensation(state.completed, state.current.index);\n\n if (next === null) {\n // Fully unwound → `failed_compensated` (saga's `aborted`).\n const settled: FailedCompensatedWorkflow<A, R, F> = {\n status: \"failed_compensated\",\n steps: state.steps,\n completed: state.completed,\n failedStep: state.failedStep,\n failure: state.failure,\n };\n return { state: settled, ledger: [confirmed], cmds: [] };\n }\n\n const compensating: CompensatingWorkflow<A, R, F> = {\n status: \"compensating\",\n steps: state.steps,\n completed: state.completed,\n failedStep: state.failedStep,\n failure: state.failure,\n current: next.current,\n compensated,\n };\n return {\n state: compensating,\n ledger: [confirmed, next.owed],\n cmds: [next.cmd],\n };\n },\n\n onCompensationErr(state, msg) {\n // Same id-match idempotency guard as the other verbs.\n if (state.status !== \"compensating\" || msg.id !== state.current.id) {\n return { state, ledger: [], cmds: [] };\n }\n // Confirm the owed compensation (the dispatch is no longer owed — it was\n // delivered and answered, just with a failure), then HALT the rollback at\n // the terminal `compensation_failed` state. Mirroring saga's `undoErr`: a\n // bounced compensation is a real-world fact the consumer must reconcile by\n // hand, never a workflow wedged in `compensating` forever. `compensated`\n // (already rolled back) is left intact for the consumer to read.\n const confirmed: EffectConfirmed = confirm(state.current.id);\n const halted: CompensationFailedWorkflow<A, R, F> = {\n status: \"compensation_failed\",\n steps: state.steps,\n completed: state.completed,\n failedStep: state.failedStep,\n failure: state.failure,\n compensated: state.compensated,\n failedCompensationStep: state.current.step,\n compensationFailure: msg.failure,\n };\n return { state: halted, ledger: [confirmed], cmds: [] };\n },\n\n survivingActivities(ledgerEvents) {\n // Rebuild the ledger by folding the persisted events (NOT a side table),\n // then the surviving owed effects ARE the dispatch Cmds to re-fire — each\n // owed effect's payload is its dispatch Cmd (a forward activity OR a\n // compensation), carrying the same id.\n const ledger: PendingEffectsLedger<WorkflowCmd<A>> =\n foldLedger(ledgerEvents);\n return survivingEffects(ledger).map((owed) => owed.effect);\n },\n };\n\n /** Confirm an owed activity (or compensation) on the recorder's ledger,\n * returning the `effect_confirmed` event to persist. The boolean (was-owed)\n * is not needed by the reducer — the id-match guard above already gates on\n * the in-flight effect — so it is discarded here. */\n function confirm(id: DeliveryId): EffectConfirmed {\n return recorder.confirm(id).event;\n }\n}\n\n// ─────────────────────────────────────────────────────────────────────────────\n// foldWorkflow — the pure replay fold. The determinism contract (acceptance\n// criterion 4) in one function: fold a workflow's full event log — its `init`\n// steps plus the ordered activity-result Msgs — back into a `WorkflowState`,\n// reading no clock and no RNG. Two folds of the same log produce byte-identical\n// state, because every decision is a pure function of (state, msg) and the\n// delivery ids are reissued in the same order from the same fresh recorder.\n//\n// This is the workflow-level twin of `foldLedger`: the host's `replay()` over\n// the event-sourced store re-runs exactly this fold to rebuild a workflow on\n// cold wake. Kept here (not only in the host, #126) so the determinism contract\n// is provable against the pure core alone.\n// ─────────────────────────────────────────────────────────────────────────────\n\n/**\n * Replay a workflow from its event log: seed over `steps`, then fold each\n * activity-result `Msg` in order. Returns the final {@link WorkflowState}.\n *\n * Determinism: a freshly-constructed {@link createWorkflow} reissues delivery\n * ids monotonically from 0, and the reducer reads no ambient state — so two\n * calls with the same `steps` + `msgs` return deeply-equal states (and equal\n * `JSON.stringify`). This is the byte-identity property #124 pins.\n *\n * Note this folds ONLY the result Msgs; the `init` dispatch + per-step\n * owe/confirm ledger events are an internal effect channel reconstructed by the\n * fresh recorder, not part of the replayed Msg log — exactly as the activity\n * results are the only thing the consumer records and replays.\n */\nexport function foldWorkflow<A, R, F>(\n steps: readonly WorkflowStep<A>[],\n msgs: Iterable<WorkflowMsg<R, F>>,\n): WorkflowState<A, R, F> {\n const wf = createWorkflow<A, R, F>();\n let { state } = wf.init(steps);\n for (const msg of msgs) {\n // Route each result Msg to its verb. The forward results (`activity_*`) and\n // the reverse compensation results (`compensation_*`, #125) are folded by\n // the same fresh recorder, so a replay across a failure+compensation\n // sequence re-issues every delivery id in identical order — byte-identity\n // holds end to end (acceptance criterion 4).\n let step: WorkflowStep0<A, R, F>;\n switch (msg.type) {\n case \"activity_ok\":\n step = wf.onActivityOk(state, msg);\n break;\n case \"activity_err\":\n step = wf.onActivityErr(state, msg);\n break;\n case \"compensation_ok\":\n step = wf.onCompensationOk(state, msg);\n break;\n case \"compensation_err\":\n step = wf.onCompensationErr(state, msg);\n break;\n }\n state = step.state;\n }\n return state;\n}\n\n// Re-export the durable-effects types a consumer needs to persist + replay a\n// workflow's ledger (the owed/confirmed events, the delivery id, the empty\n// seed) without reaching into the `../do` subpath directly.\nexport {\n type DeliveryId,\n type EffectConfirmed,\n type EffectLedgerEvent,\n type EffectOwed,\n emptyLedger,\n};\n"]}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@demlik/tea",
3
- "version": "0.1.1",
3
+ "version": "0.2.0",
4
4
  "description": "TEA-faithful state machine substrate — one package, every host adapter. Core + subs + testing, plus React, Durable Object, Chrome extension, Node, in-memory, work-queue, devtools, and property-testing modules as subpaths.",
5
5
  "keywords": [
6
6
  "tea",
@@ -133,6 +133,10 @@
133
133
  "types": "./dist/await-terminal/index.d.ts",
134
134
  "import": "./dist/await-terminal/index.js"
135
135
  },
136
+ "./retry-to-success": {
137
+ "types": "./dist/retry-to-success/index.d.ts",
138
+ "import": "./dist/retry-to-success/index.js"
139
+ },
136
140
  "./machine-viz": {
137
141
  "types": "./dist/machine-viz/index.d.ts",
138
142
  "import": "./dist/machine-viz/index.js"
@@ -185,22 +189,6 @@
185
189
  "types": "./dist/poller/index.d.ts",
186
190
  "import": "./dist/poller/index.js"
187
191
  },
188
- "./raft": {
189
- "types": "./dist/raft/index.d.ts",
190
- "import": "./dist/raft/index.js"
191
- },
192
- "./raft/sim": {
193
- "types": "./dist/raft/sim.d.ts",
194
- "import": "./dist/raft/sim.js"
195
- },
196
- "./raft/demo": {
197
- "types": "./dist/raft/demo.d.ts",
198
- "import": "./dist/raft/demo.js"
199
- },
200
- "./raft/timeline": {
201
- "types": "./dist/raft/timeline.d.ts",
202
- "import": "./dist/raft/timeline.js"
203
- },
204
192
  "./workflow": {
205
193
  "types": "./dist/workflow/index.d.ts",
206
194
  "import": "./dist/workflow/index.js"
@@ -298,6 +286,7 @@
298
286
  "@types/react-dom": "19.0.3",
299
287
  "@types/ws": "8.5.14",
300
288
  "fast-check": "^3.23.0",
289
+ "happy-dom": "^20.9.0",
301
290
  "react": "19.0.0",
302
291
  "react-dom": "19.0.0",
303
292
  "tsup": "^8.3.5",
@@ -312,10 +301,9 @@
312
301
  "build": "NODE_OPTIONS=--max-old-space-size=8192 tsup",
313
302
  "lint": "biome check src package.json",
314
303
  "test": "vitest run",
315
- "demo:raft": "vitest run src/raft/demo.test.ts",
316
- "demo:raft:viz": "vitest run src/raft/timeline.test.ts",
317
304
  "demo:saga": "vitest run src/workflow/demo.test.ts",
318
305
  "typecheck": "tsc --noEmit",
319
- "typecheck:examples": "tsc -p examples/tsconfig.json"
306
+ "typecheck:examples": "tsc -p examples/tsconfig.json",
307
+ "verify-exports": "node scripts/verify-exports.mjs"
320
308
  }
321
309
  }