@demlik/tea 0.5.0 → 0.6.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +1 -1
- package/dist/agent/index.d.ts +5 -5
- package/dist/agent/index.js +10 -10
- package/dist/authed-call/index.d.ts +3 -3
- package/dist/authed-call/index.js +7 -7
- package/dist/await-terminal/index.d.ts +2 -2
- package/dist/await-terminal/index.js +3 -2
- package/dist/await-terminal/index.js.map +1 -1
- package/dist/batch-window/index.d.ts +4 -4
- package/dist/batch-window/index.js +3 -3
- package/dist/cache/index.d.ts +2 -2
- package/dist/cache/index.js +4 -4
- package/dist/{chunk-PUTHY7LR.js → chunk-2KBEIGYP.js} +3 -3
- package/dist/{chunk-PUTHY7LR.js.map → chunk-2KBEIGYP.js.map} +1 -1
- package/dist/{chunk-QKUWDC4P.js → chunk-2UGTDYOK.js} +3 -3
- package/dist/{chunk-QKUWDC4P.js.map → chunk-2UGTDYOK.js.map} +1 -1
- package/dist/{chunk-ZILCH3WS.js → chunk-66S2KEQQ.js} +4 -4
- package/dist/{chunk-ZILCH3WS.js.map → chunk-66S2KEQQ.js.map} +1 -1
- package/dist/{chunk-362SZ6CS.js → chunk-A7USKARI.js} +3 -3
- package/dist/{chunk-362SZ6CS.js.map → chunk-A7USKARI.js.map} +1 -1
- package/dist/{chunk-ZT3MGQB7.js → chunk-ASX7PL2K.js} +3 -3
- package/dist/{chunk-ZT3MGQB7.js.map → chunk-ASX7PL2K.js.map} +1 -1
- package/dist/{chunk-62QBHM3T.js → chunk-AZ3NHUPD.js} +3 -3
- package/dist/{chunk-62QBHM3T.js.map → chunk-AZ3NHUPD.js.map} +1 -1
- package/dist/{chunk-7FYQGDMF.js → chunk-AZZLE7XR.js} +3 -3
- package/dist/{chunk-7FYQGDMF.js.map → chunk-AZZLE7XR.js.map} +1 -1
- package/dist/{chunk-W2S4HK7J.js → chunk-EC6FO42Q.js} +6 -6
- package/dist/{chunk-W2S4HK7J.js.map → chunk-EC6FO42Q.js.map} +1 -1
- package/dist/{chunk-T6HDAPMR.js → chunk-ERYY5P6W.js} +3 -3
- package/dist/{chunk-T6HDAPMR.js.map → chunk-ERYY5P6W.js.map} +1 -1
- package/dist/{chunk-CIDS43FH.js → chunk-IVHQCVFX.js} +3 -3
- package/dist/{chunk-CIDS43FH.js.map → chunk-IVHQCVFX.js.map} +1 -1
- package/dist/{chunk-DBOJ2UC6.js → chunk-O7ED34JH.js} +4 -2
- package/dist/chunk-O7ED34JH.js.map +1 -0
- package/dist/{chunk-LFW66IIV.js → chunk-S6Y3RNX4.js} +4 -4
- package/dist/{chunk-LFW66IIV.js.map → chunk-S6Y3RNX4.js.map} +1 -1
- package/dist/{chunk-KEFMI24G.js → chunk-UV7VCTNC.js} +7 -7
- package/dist/{chunk-KEFMI24G.js.map → chunk-UV7VCTNC.js.map} +1 -1
- package/dist/{chunk-7UU5P2CX.js → chunk-WF46FABO.js} +3 -3
- package/dist/{chunk-7UU5P2CX.js.map → chunk-WF46FABO.js.map} +1 -1
- package/dist/{chunk-KWPB6BM6.js → chunk-XMHZ44QC.js} +4 -4
- package/dist/{chunk-KWPB6BM6.js.map → chunk-XMHZ44QC.js.map} +1 -1
- package/dist/{chunk-7A74NSG4.js → chunk-XOAP3LOT.js} +3 -3
- package/dist/{chunk-7A74NSG4.js.map → chunk-XOAP3LOT.js.map} +1 -1
- package/dist/{chunk-PBAYOJJO.js → chunk-ZH454CR5.js} +9 -3
- package/dist/chunk-ZH454CR5.js.map +1 -0
- package/dist/{core-DPYOyOJv.d.ts → core-CUN5HDKL.d.ts} +16 -1
- package/dist/deadline/index.d.ts +2 -2
- package/dist/deadline/index.js +3 -3
- package/dist/do/index.d.ts +9 -9
- package/dist/do/index.js +10 -10
- package/dist/do/index.js.map +1 -1
- package/dist/{durable-effects-B0YpoCHg.d.ts → durable-effects-CXMOi-sp.d.ts} +2 -2
- package/dist/extension/index.d.ts +2 -2
- package/dist/extension/index.js +3 -3
- package/dist/extension/react.js +3 -3
- package/dist/extension/subs/index.d.ts +2 -2
- package/dist/extension/test-utils.d.ts +1 -1
- package/dist/extension/test-utils.js.map +1 -1
- package/dist/fan-out/index.d.ts +2 -2
- package/dist/idempotent-intake/index.d.ts +2 -2
- package/dist/index.d.ts +4 -4
- package/dist/index.js +2 -2
- package/dist/llm-call/index.d.ts +3 -3
- package/dist/llm-call/index.js +7 -7
- package/dist/{machine-Q_Bsm7Vu.d.ts → machine-CoWpvp8x.d.ts} +3 -3
- package/dist/machine-viz/index.d.ts +1 -1
- package/dist/machine-viz/index.js +2 -2
- package/dist/mem/index.d.ts +2 -2
- package/dist/monitored-run/index.d.ts +4 -4
- package/dist/monitored-run/index.js +5 -5
- package/dist/node/index.d.ts +2 -2
- package/dist/paginated-walk/index.d.ts +3 -3
- package/dist/paginated-walk/index.js +7 -7
- package/dist/parity/index.d.ts +30 -2
- package/dist/parity/index.js +3 -3
- package/dist/parity/index.js.map +1 -1
- package/dist/pbt/arbitraries/index.d.ts +3 -3
- package/dist/pbt/arbitraries/index.js +1 -1
- package/dist/pbt/index.d.ts +1 -1
- package/dist/pbt/index.js +4 -4
- package/dist/pbt/runners/index.d.ts +1 -1
- package/dist/pbt/runners/index.js +3 -3
- package/dist/poller/index.d.ts +3 -3
- package/dist/poller/index.js +3 -3
- package/dist/prediction/index.d.ts +1 -1
- package/dist/prediction/index.js +2 -2
- package/dist/pure/index.d.ts +1 -1
- package/dist/pure/index.js +2 -2
- package/dist/react/index.d.ts +2 -2
- package/dist/react/index.js +2 -2
- package/dist/reconciler/index.d.ts +3 -3
- package/dist/reconciler/index.js +7 -7
- package/dist/recorder/index.d.ts +2 -2
- package/dist/resilient-call/index.d.ts +2 -2
- package/dist/resilient-call/index.js +6 -6
- package/dist/retry-to-success/index.js +2 -0
- package/dist/retry-to-success/index.js.map +1 -1
- package/dist/{runtime-types-uBuVvZqa.d.ts → runtime-types-BD3ZFfdw.d.ts} +2 -2
- package/dist/saga/index.d.ts +2 -2
- package/dist/snapshot/index.d.ts +1 -1
- package/dist/snapshot/index.js +3 -3
- package/dist/subs/index.d.ts +3 -3
- package/dist/subs/index.js +3 -3
- package/dist/testing/index.d.ts +2 -2
- package/dist/testing/index.js +2 -2
- package/dist/throttled-input/index.d.ts +2 -2
- package/dist/throttled-input/index.js +6 -6
- package/dist/token-refresh/index.d.ts +1 -1
- package/dist/token-refresh/index.js +3 -3
- package/dist/trace-replay/index.d.ts +2 -2
- package/dist/trace-replay/index.js +3 -3
- package/dist/{types-C6mXL9wA.d.ts → types-CjAkI83U.d.ts} +1 -1
- package/dist/with-deadline/index.d.ts +1 -1
- package/dist/with-deadline/index.js +2 -2
- package/dist/with-resilience/index.d.ts +2 -2
- package/dist/with-resilience/index.js +6 -6
- package/dist/with-telemetry/index.d.ts +1 -1
- package/dist/with-telemetry/index.js +2 -2
- package/dist/work-queue/adapter.d.ts +2 -2
- package/dist/work-queue/index.d.ts +3 -3
- package/dist/work-queue/index.js.map +1 -1
- package/dist/work-queue/ops.d.ts +2 -2
- package/dist/workflow/index.d.ts +6 -4
- package/dist/workflow/index.js +1 -1
- package/dist/workflow/index.js.map +1 -1
- package/package.json +12 -4
- package/dist/chunk-DBOJ2UC6.js.map +0 -1
- package/dist/chunk-PBAYOJJO.js.map +0 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/workflow/route.ts","../../src/workflow/index.ts"],"names":["id"],"mappings":";;;;AAqBO,SAAS,gBAAA,CACd,EAAA,EACA,KAAA,EACA,GAAA,EAC8B;AAC9B,EAAA,QAAQ,IAAI,IAAA;AAAM,IAChB,KAAK,aAAA;AACH,MAAA,OAAO,EAAA,CAAG,YAAA,CAAa,KAAA,EAAO,GAAG,CAAA;AAAA,IACnC,KAAK,cAAA;AACH,MAAA,OAAO,EAAA,CAAG,aAAA,CAAc,KAAA,EAAO,GAAG,CAAA;AAAA,IACpC,KAAK,iBAAA;AACH,MAAA,OAAO,EAAA,CAAG,gBAAA,CAA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EAAA,KAAA,MAAW,OAAO,IAAA,EAAM;AAOtB,IAAA,KAAA,GAAQ,gBAAA,CAAiB,EAAA,EAAI,KAAA,EAAO,GAAG,CAAA,CAAE,KAAA;AAAA,EAC3C;AACA,EAAA,OAAO,KAAA;AACT","file":"index.js","sourcesContent":["// ---------------------------------------------------------------------------\n// routeWorkflowMsg — the ONE WorkflowMsg → verb routing table.\n//\n// Two call sites fold a `WorkflowMsg` into a workflow's next step: the pure\n// replay `foldWorkflow` (a `switch`) and the durable grain's `defineMachine`\n// update map in `do.ts` (one cell per Msg tag). Both encode the SAME mapping\n// (`activity_ok` → `onActivityOk`, `activity_err` → `onActivityErr`,\n// `compensation_ok` → `onCompensationOk`, `compensation_err` →\n// `onCompensationErr`). Left duplicated, adding a fifth Msg variant meant\n// editing the routing decision in two places. This dispatcher owns the table\n// once; each call site delegates. The `switch` is exhaustive over the\n// `WorkflowMsg` union, so a new variant is a compile error here until routed.\n// ---------------------------------------------------------------------------\n\nimport type {\n Workflow,\n WorkflowMsg,\n WorkflowReducerStep,\n WorkflowState,\n} from \"./index\";\n\nexport function routeWorkflowMsg<A, R, F>(\n wf: Workflow<A, R, F>,\n state: WorkflowState<A, R, F>,\n msg: WorkflowMsg<R, F>,\n): WorkflowReducerStep<A, R, F> {\n switch (msg.type) {\n case \"activity_ok\":\n return wf.onActivityOk(state, msg);\n case \"activity_err\":\n return wf.onActivityErr(state, msg);\n case \"compensation_ok\":\n return wf.onCompensationOk(state, msg);\n case \"compensation_err\":\n return wf.onCompensationErr(state, msg);\n }\n}\n","/**\n * @packageDocumentation\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\";\nimport { routeWorkflowMsg } from \"./route\";\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 workflow's step sequence at construction — a NON-EMPTY tuple. A workflow\n * with nothing to do reaches `completed` only by carrying a final result, and an\n * empty sequence produces none, so \"≥ 1 step\" is a precondition. Encoding it as\n * `readonly [WorkflowStep<A>, ...WorkflowStep<A>[]]` makes the empty case a\n * COMPILE error at every construction boundary (`init`, `foldWorkflow`,\n * `workflowGrain`) — parse-don't-validate, so the reducer never needs a runtime\n * throw to reject a resultless workflow.\n */\nexport type WorkflowSteps<A> = readonly [WorkflowStep<A>, ...WorkflowStep<A>[]];\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/** Every `status` discriminant of the {@link WorkflowState} union. */\nexport type WorkflowStatus = WorkflowState<unknown, unknown, unknown>[\"status\"];\n\n/**\n * The runtime accept-set of every {@link WorkflowStatus} — the single source of\n * truth the boundary snapshot parse keys off (see `do.ts`). Built from an\n * exhaustive `Record<WorkflowStatus, true>`, so adding a variant to the union\n * above without listing it here is a COMPILE error: the set can never silently\n * drift from the union again (the #312 regression, where the #125 compensation\n * statuses were missing and evicted-mid-rollback grains re-seeded fresh).\n */\nexport const WORKFLOW_STATUSES: ReadonlySet<string> = new Set(\n Object.keys({\n running: true,\n completed: true,\n failed: true,\n compensating: true,\n failed_compensated: true,\n compensation_failed: true,\n } satisfies Record<WorkflowStatus, true>),\n);\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 WorkflowReducerStep}/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 WorkflowReducerStep} 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/** Every `type` discriminant tag of the {@link WorkflowMsg} union. */\nexport type WorkflowMsgType = WorkflowMsg<unknown, unknown>[\"type\"];\n\n/**\n * The runtime accept-set of every {@link WorkflowMsgType} — the single source of\n * truth the boundary replay parse keys off (see `do.ts`). Built from an\n * exhaustive `Record<WorkflowMsgType, true>`, so adding a Msg variant to the\n * union above without listing it here is a COMPILE error: the set can never\n * silently drift from the union again (the #312 regression, where the #125\n * compensation result tags were missing and dropped from replay).\n */\nexport const WORKFLOW_MSG_TYPES: ReadonlySet<string> = new Set(\n Object.keys({\n activity_ok: true,\n activity_err: true,\n compensation_ok: true,\n compensation_err: true,\n } satisfies Record<WorkflowMsgType, true>),\n);\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 WorkflowReducerStep<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` (a NON-EMPTY {@link WorkflowSteps}) and\n * dispatch its first activity → `running` with `current` = step 0, owed on the\n * ledger. The \"≥ 1 step\" precondition is carried by the tuple type: an empty\n * sequence is a compile error at the call site, not a runtime throw here — a\n * workflow with nothing to do could never reach `completed` (no final result\n * to carry), so it is unrepresentable by construction.\n */\n init(steps: WorkflowSteps<A>): WorkflowReducerStep<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 ): WorkflowReducerStep<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 ): WorkflowReducerStep<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 ): WorkflowReducerStep<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 ): WorkflowReducerStep<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 /**\n * Assemble the next `compensating` step from a `base` (everything but the\n * in-flight compensation — carried identically from the failure pivot OR from\n * the prior compensating state) and the `next` compensation to owe. Both the\n * failure pivot ({@link Workflow.onActivityErr}) and each `compensation_ok`\n * advance ({@link Workflow.onCompensationOk}) continue the unwind the same way,\n * so the confirm-then-owe ledger discipline (`[confirmed, next.owed]`, dispatch\n * `[next.cmd]`) lives here once instead of mirrored at both call sites.\n */\n function continueCompensating(\n base: Omit<CompensatingWorkflow<A, R, F>, \"current\">,\n next: {\n readonly current: InFlightCompensation<A>;\n readonly owed: EffectOwed<WorkflowCmd<A>>;\n readonly cmd: CompensationCmd<A>;\n },\n confirmed: EffectConfirmed,\n ): WorkflowReducerStep<A, R, F> {\n const compensating: CompensatingWorkflow<A, R, F> = {\n ...base,\n current: next.current,\n };\n return {\n state: compensating,\n ledger: [confirmed, next.owed],\n cmds: [next.cmd],\n };\n }\n\n return {\n init(steps) {\n // `steps` is a non-empty `WorkflowSteps` (the empty case is a compile\n // error at the call site), so step 0 always exists — no runtime guard.\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). The\n // `base` here is FRESH from the failing activity (failedStep/failure from\n // `state.current`/`msg`, empty `compensated`).\n return continueCompensating(\n {\n status: \"compensating\",\n steps: state.steps,\n completed: state.completed,\n failedStep: state.current.step,\n failure: msg.failure,\n compensated: [],\n },\n next,\n confirmed,\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 // Continue the unwind. The `base` here CARRIES failedStep/failure from the\n // prior compensating `state` and the accumulated `compensated` list.\n return continueCompensating(\n {\n status: \"compensating\",\n steps: state.steps,\n completed: state.completed,\n failedStep: state.failedStep,\n failure: state.failure,\n compensated,\n },\n next,\n confirmed,\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: WorkflowSteps<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 via the shared dispatcher. The forward\n // results (`activity_*`) and the reverse compensation results\n // (`compensation_*`, #125) are folded by the same fresh recorder, so a\n // replay across a failure+compensation sequence re-issues every delivery id\n // in identical order — byte-identity holds end to end (acceptance\n // criterion 4).\n state = routeWorkflowMsg(wf, state, msg).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/route.ts","../../src/workflow/index.ts"],"names":["id"],"mappings":";;;;AAqBO,SAAS,gBAAA,CACd,EAAA,EACA,KAAA,EACA,GAAA,EAC8B;AAC9B,EAAA,QAAQ,IAAI,IAAA;AAAM,IAChB,KAAK,aAAA;AACH,MAAA,OAAO,EAAA,CAAG,YAAA,CAAa,KAAA,EAAO,GAAG,CAAA;AAAA,IACnC,KAAK,cAA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ACA,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;AAOtB,IAAA,KAAA,GAAQ,gBAAA,CAAiB,EAAA,EAAI,KAAA,EAAO,GAAG,CAAA,CAAE,KAAA;AAAA,EAC3C;AACA,EAAA,OAAO,KAAA;AACT","file":"index.js","sourcesContent":["// ---------------------------------------------------------------------------\n// routeWorkflowMsg — the ONE WorkflowMsg → verb routing table.\n//\n// Two call sites fold a `WorkflowMsg` into a workflow's next step: the pure\n// replay `foldWorkflow` (a `switch`) and the durable grain's `defineMachine`\n// update map in `do.ts` (one cell per Msg tag). Both encode the SAME mapping\n// (`activity_ok` → `onActivityOk`, `activity_err` → `onActivityErr`,\n// `compensation_ok` → `onCompensationOk`, `compensation_err` →\n// `onCompensationErr`). Left duplicated, adding a fifth Msg variant meant\n// editing the routing decision in two places. This dispatcher owns the table\n// once; each call site delegates. The `switch` is exhaustive over the\n// `WorkflowMsg` union, so a new variant is a compile error here until routed.\n// ---------------------------------------------------------------------------\n\nimport type {\n Workflow,\n WorkflowMsg,\n WorkflowReducerStep,\n WorkflowState,\n} from \"./index\";\n\nexport function routeWorkflowMsg<A, R, F>(\n wf: Workflow<A, R, F>,\n state: WorkflowState<A, R, F>,\n msg: WorkflowMsg<R, F>,\n): WorkflowReducerStep<A, R, F> {\n switch (msg.type) {\n case \"activity_ok\":\n return wf.onActivityOk(state, msg);\n case \"activity_err\":\n return wf.onActivityErr(state, msg);\n case \"compensation_ok\":\n return wf.onCompensationOk(state, msg);\n case \"compensation_err\":\n return wf.onCompensationErr(state, msg);\n }\n}\n","/**\n * @packageDocumentation\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\";\nimport { routeWorkflowMsg } from \"./route\";\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 workflow's step sequence at construction — a NON-EMPTY tuple. A workflow\n * with nothing to do reaches `completed` only by carrying a final result, and an\n * empty sequence produces none, so \"≥ 1 step\" is a precondition. Encoding it as\n * `readonly [WorkflowStep<A>, ...WorkflowStep<A>[]]` makes the empty case a\n * COMPILE error at every construction boundary (`init`, `foldWorkflow`,\n * `workflowGrain`) — parse-don't-validate, so the reducer never needs a runtime\n * throw to reject a resultless workflow.\n */\nexport type WorkflowSteps<A> = readonly [WorkflowStep<A>, ...WorkflowStep<A>[]];\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/** Every `status` discriminant of the {@link WorkflowState} union. */\nexport type WorkflowStatus = WorkflowState<unknown, unknown, unknown>[\"status\"];\n\n/**\n * The runtime accept-set of every {@link WorkflowStatus} — the single source of\n * truth the boundary snapshot parse keys off (see `do.ts`). Built from an\n * exhaustive `Record<WorkflowStatus, true>`, so adding a variant to the union\n * above without listing it here is a COMPILE error: the set can never silently\n * drift from the union again (the #312 regression, where the #125 compensation\n * statuses were missing and evicted-mid-rollback grains re-seeded fresh).\n */\nexport const WORKFLOW_STATUSES: ReadonlySet<string> = new Set(\n Object.keys({\n running: true,\n completed: true,\n failed: true,\n compensating: true,\n failed_compensated: true,\n compensation_failed: true,\n } satisfies Record<WorkflowStatus, true>),\n);\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 WorkflowReducerStep}/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 WorkflowReducerStep} 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/** Every `type` discriminant tag of the {@link WorkflowMsg} union. */\nexport type WorkflowMsgType = WorkflowMsg<unknown, unknown>[\"type\"];\n\n/**\n * The runtime accept-set of every {@link WorkflowMsgType} — the single source of\n * truth the boundary replay parse keys off (see `do.ts`). Built from an\n * exhaustive `Record<WorkflowMsgType, true>`, so adding a Msg variant to the\n * union above without listing it here is a COMPILE error: the set can never\n * silently drift from the union again (the #312 regression, where the #125\n * compensation result tags were missing and dropped from replay).\n */\nexport const WORKFLOW_MSG_TYPES: ReadonlySet<string> = new Set(\n Object.keys({\n activity_ok: true,\n activity_err: true,\n compensation_ok: true,\n compensation_err: true,\n } satisfies Record<WorkflowMsgType, true>),\n);\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 WorkflowReducerStep<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` (a NON-EMPTY {@link WorkflowSteps}) and\n * dispatch its first activity → `running` with `current` = step 0, owed on the\n * ledger. The \"≥ 1 step\" precondition is carried by the tuple type: an empty\n * sequence is a compile error at the call site, not a runtime throw here — a\n * workflow with nothing to do could never reach `completed` (no final result\n * to carry), so it is unrepresentable by construction.\n */\n init(steps: WorkflowSteps<A>): WorkflowReducerStep<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 ): WorkflowReducerStep<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 ): WorkflowReducerStep<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 ): WorkflowReducerStep<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 ): WorkflowReducerStep<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 /**\n * Assemble the next `compensating` step from a `base` (everything but the\n * in-flight compensation — carried identically from the failure pivot OR from\n * the prior compensating state) and the `next` compensation to owe. Both the\n * failure pivot ({@link Workflow.onActivityErr}) and each `compensation_ok`\n * advance ({@link Workflow.onCompensationOk}) continue the unwind the same way,\n * so the confirm-then-owe ledger discipline (`[confirmed, next.owed]`, dispatch\n * `[next.cmd]`) lives here once instead of mirrored at both call sites.\n */\n function continueCompensating(\n base: Omit<CompensatingWorkflow<A, R, F>, \"current\">,\n next: {\n readonly current: InFlightCompensation<A>;\n readonly owed: EffectOwed<WorkflowCmd<A>>;\n readonly cmd: CompensationCmd<A>;\n },\n confirmed: EffectConfirmed,\n ): WorkflowReducerStep<A, R, F> {\n const compensating: CompensatingWorkflow<A, R, F> = {\n ...base,\n current: next.current,\n };\n return {\n state: compensating,\n ledger: [confirmed, next.owed],\n cmds: [next.cmd],\n };\n }\n\n return {\n init(steps) {\n // `steps` is a non-empty `WorkflowSteps` (the empty case is a compile\n // error at the call site), so step 0 always exists — no runtime guard.\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). The\n // `base` here is FRESH from the failing activity (failedStep/failure from\n // `state.current`/`msg`, empty `compensated`).\n return continueCompensating(\n {\n status: \"compensating\",\n steps: state.steps,\n completed: state.completed,\n failedStep: state.current.step,\n failure: msg.failure,\n compensated: [],\n },\n next,\n confirmed,\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 // Continue the unwind. The `base` here CARRIES failedStep/failure from the\n // prior compensating `state` and the accumulated `compensated` list.\n return continueCompensating(\n {\n status: \"compensating\",\n steps: state.steps,\n completed: state.completed,\n failedStep: state.failedStep,\n failure: state.failure,\n compensated,\n },\n next,\n confirmed,\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: WorkflowSteps<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 via the shared dispatcher. The forward\n // results (`activity_*`) and the reverse compensation results\n // (`compensation_*`, #125) are folded by the same fresh recorder, so a\n // replay across a failure+compensation sequence re-issues every delivery id\n // in identical order — byte-identity holds end to end (acceptance\n // criterion 4).\n state = routeWorkflowMsg(wf, state, msg).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// The ONE WorkflowMsg → verb routing table, exported because a consumer driving\n// a workflow from its own host — rather than through `./do`'s grain — otherwise\n// has to re-derive the same four-way mapping by hand, and a fifth Msg variant\n// would then break it silently instead of at compile time.\nexport { routeWorkflowMsg } from \"./route\";\n"]}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@demlik/tea",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.6.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",
|
|
@@ -15,8 +15,7 @@
|
|
|
15
15
|
"homepage": "https://demlik.run",
|
|
16
16
|
"repository": {
|
|
17
17
|
"type": "git",
|
|
18
|
-
"url": "git+https://github.com/
|
|
19
|
-
"directory": "packages/tea"
|
|
18
|
+
"url": "git+https://github.com/kamp-us/demlik.git"
|
|
20
19
|
},
|
|
21
20
|
"license": "MIT",
|
|
22
21
|
"author": "Can Sirin",
|
|
@@ -279,6 +278,8 @@
|
|
|
279
278
|
}
|
|
280
279
|
},
|
|
281
280
|
"devDependencies": {
|
|
281
|
+
"@biomejs/biome": "2.3.14",
|
|
282
|
+
"@changesets/cli": "^2.27.11",
|
|
282
283
|
"@cloudflare/workers-types": "4.20260312.1",
|
|
283
284
|
"@types/chrome": "^0.1.42",
|
|
284
285
|
"@types/node": "^22",
|
|
@@ -298,6 +299,12 @@
|
|
|
298
299
|
"publishConfig": {
|
|
299
300
|
"access": "public"
|
|
300
301
|
},
|
|
302
|
+
"bugs": {
|
|
303
|
+
"url": "https://github.com/kamp-us/demlik/issues"
|
|
304
|
+
},
|
|
305
|
+
"volta": {
|
|
306
|
+
"node": "23.7.0"
|
|
307
|
+
},
|
|
301
308
|
"scripts": {
|
|
302
309
|
"build": "NODE_OPTIONS=--max-old-space-size=8192 tsup",
|
|
303
310
|
"lint": "biome check src package.json",
|
|
@@ -307,6 +314,7 @@
|
|
|
307
314
|
"typecheck:examples": "tsc -p examples/tsconfig.json",
|
|
308
315
|
"docs:reference": "TEA_DOCS_WRITE=1 vitest run src/docs/reference/generate-reference.test.ts",
|
|
309
316
|
"docs:reference:check": "pnpm run docs:reference && git diff --exit-code -- docs/reference",
|
|
310
|
-
"verify-exports": "node scripts/verify-exports.mjs"
|
|
317
|
+
"verify-exports": "node scripts/verify-exports.mjs",
|
|
318
|
+
"release": "changeset"
|
|
311
319
|
}
|
|
312
320
|
}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/pure/core.ts"],"names":["cell"],"mappings":";AA4BO,IAAM,WAAoB,MAAM;AACrC,EAAA,IAAI;AACF,IAAA,MAAM,IAAA,GAAO,MAAA,CAAA,IAAA;AACb,IAAA,IAAI,IAAA,CAAK,GAAA,EAAK,GAAA,KAAQ,KAAA,CAAA,EAAW;AAC/B,MAAA,OAAO,KAAK,GAAA,CAAI,GAAA;AAAA,IAClB;AAAA,EACF,CAAA,CAAA,MAAQ;AAAA,EAER;AACA,EAAA,IAAI;AACF,IAAA,OACE,OAAO,OAAA,KAAY,WAAA,IAAe,OAAA,CAAQ,KAAK,QAAA,KAAa,YAAA;AAAA,EAEhE,CAAA,CAAA,MAAQ;AACN,IAAA,OAAO,KAAA;AAAA,EACT;AACF,CAAA,GAAG;AAEI,SAAS,UAAA,CAAc,KAAQ,IAAA,EAA2B;AAC/D,EAAA,IAAI,GAAA,KAAQ,IAAA,IAAQ,OAAO,GAAA,KAAQ,UAAU,OAAO,GAAA;AACpD,EAAA,MAAM,KAAA,GAAQ,MAAA,CAAO,cAAA,CAAe,GAAG,CAAA;AACvC,EAAA,IAAI,UAAU,MAAA,CAAO,SAAA,IAAa,KAAA,KAAU,KAAA,CAAM,aAAa,KAAA,KAAU,IAAA;AACvE,IAAA,OAAO,GAAA;AACT,EAAA,MAAM,OAAA,GAAU,IAAA,oBAAQ,IAAI,OAAA,EAAQ;AACpC,EAAA,IAAI,OAAA,CAAQ,GAAA,CAAI,GAAa,CAAA,EAAG,OAAO,GAAA;AACvC,EAAA,OAAA,CAAQ,IAAI,GAAa,CAAA;AACzB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,IAAA,OAAO,CAAA,CAAA,EAAI,KAAK,GAAA,CAAI,CAAC,MAAM,CAAA,EAAG,IAAA,CAAK,UAAU,CAAC,CAAC,IAAI,eAAA,CAAgB,GAAA,CAAI,CAAC,CAAC,CAAC,EAAE,CAAA,CAAE,IAAA,CAAK,GAAG,CAAC,CAAA,CAAA,CAAA;AAAA,EACzF;AAEA,EAAA,MAAM,IAAI,KAAA;AAAA,IACR,+EAA+E,CAAC,CAAA,iEAAA;AAAA,GAElF;AACF;AAyaO,SAAS,WAAA,CACd,OAAA,EACA,YAAA,EACA,IAAA,EACyB;AACzB,EAAA,IAAI,KAAA,GAAW,YAAA;AACf,EAAA,MAAM,OAAY,EAAC;AAEnB,EAAA,KAAA,MAAW,OAAO,IAAA,EAAM;AACtB,IAAA,MAAM,CAAC,IAAA,EAAM,OAAO,IAAI,gBAAA,CAA0B,OAAA,EAAS,OAAO,GAAG,CAAA;AACrE,IAAA,KAAA,GAAQ,IAAA;AACR,IAAA,IAAA,CAAK,IAAA,CAAK,GAAG,OAAO,CAAA;AAAA,EACtB;AAEA,EAAA,OAAO,EAAE,OAAO,IAAA,EAAK;AACvB;AA8BO,SAAS,QAAA,CAMd,OAAA,EAAmC,IAAA,EAAS,IAAA,EAAuB;AACnE,EAAA,OAAO,WAAA,CAAqB,OAAA,EAAS,IAAA,EAAM,IAAI,CAAA,CAAE,KAAA;AACnD","file":"chunk-DBOJ2UC6.js","sourcesContent":["/**\n * @demlik/tea — pure-core leaf (ADR 0006).\n *\n * This is the runtime-free pure core of the substrate. It holds the\n * client-prediction fold seam (`foldMsgs`), the form reader\n * (`formOf`/`detectUpdateForm`), and the pure type vocabulary (`Machine`,\n * `Reducer`, `Transitions`, `Cmd`, `Sub`, `Port`, …).\n *\n * **Dependency direction (the actual decoupling):** this module imports\n * NOTHING from the runtime — no `better-result`, no `run`/host/`Store`. The\n * runtime (`run`, the host, interpret, `Store`, subscribe — all in\n * `../index.ts`) imports *from* here; never the reverse. The\n * `@demlik/tea/pure` subpath re-exports this surface, and\n * `pure/import-graph.test.ts` is the regression fence asserting the pure\n * entrypoint's import graph never reaches `run`.\n */\n\n// === Dev-mode invariant enforcement ===\n//\n// Three runtime guards that catch TEA invariant violations during development.\n// Dead-code-eliminated in production by any bundler that replaces\n// `import.meta.env.DEV` (Vite) or `process.env.NODE_ENV` (webpack/esbuild).\n//\n// 1. deepFreeze(state) before passing to update — catches mutation\n// 2. Thenable check on return value — catches async update\n// 3. Walk cmd fields for function types — catches closures-as-data\n//\n// These enforce invariants 1 and 2 at runtime where the type system cannot.\nexport const __DEV__: boolean = (() => {\n try {\n const meta = import.meta as unknown as { env?: { DEV?: boolean } };\n if (meta.env?.DEV !== undefined) {\n return meta.env.DEV;\n }\n } catch {\n // import.meta not available (Node CJS, service workers)\n }\n try {\n return (\n typeof process !== \"undefined\" && process.env?.NODE_ENV !== \"production\"\n );\n } catch {\n return false;\n }\n})();\n\nexport function deepFreeze<T>(obj: T, seen?: WeakSet<object>): T {\n if (obj === null || typeof obj !== \"object\") return obj;\n const proto = Object.getPrototypeOf(obj);\n if (proto !== Object.prototype && proto !== Array.prototype && proto !== null)\n return obj;\n const visited = seen ?? new WeakSet();\n if (visited.has(obj as object)) return obj;\n visited.add(obj as object);\n Object.freeze(obj);\n for (const v of Object.values(obj as Record<string, unknown>))\n deepFreeze(v, visited);\n return obj;\n}\n\nexport function hasFunctionValues(obj: unknown): string | null {\n if (obj === null || typeof obj !== \"object\") return null;\n for (const [key, value] of Object.entries(obj as Record<string, unknown>)) {\n if (typeof value === \"function\") return key;\n }\n return null;\n}\n\nexport function assertPureResult(result: unknown, msgType: string): void {\n if (result && typeof (result as { then?: unknown }).then === \"function\") {\n throw new Error(\n `@demlik/tea: update cell \"${msgType}\" returned a Promise. ` +\n `update must be synchronous. Move async work to interpret.`,\n );\n }\n if (\n !Array.isArray(result) ||\n result.length < 2 ||\n !Array.isArray(result[1])\n ) {\n throw new Error(\n `@demlik/tea: update cell \"${msgType}\" returned a non-tuple. ` +\n `Expected [State, Cmd[]], got ${typeof result}.`,\n );\n }\n const cmds = result[1] as readonly { type: string }[];\n for (const cmd of cmds) {\n const fnField = hasFunctionValues(cmd);\n if (fnField !== null) {\n throw new Error(\n `@demlik/tea: Cmd \"${cmd.type}\" has function field \"${fnField}\". ` +\n `Cmds must be plain data, not closures.`,\n );\n }\n }\n}\n\n/**\n * Drop one `key` from a `Record` immutably — returns a new record with `key`\n * omitted, leaving the input untouched. The immutable-record-key-drop the L2\n * resilience bricks reach for whenever a settled/restarted call must forget its\n * per-key bookkeeping (a retry counter, a parked input). A plain\n * object-rest spread, lifted here so `resilient-call` and `authed-call` share\n * one definition instead of open-coding `const { [key]: _drop, ...rest } = rec`\n * at each site.\n */\nexport function without<V>(\n rec: Readonly<Record<string, V>>,\n key: string,\n): Readonly<Record<string, V>> {\n const { [key]: _dropped, ...rest } = rec;\n return rest;\n}\n\n// === Cmd: tagged-union, one-shot effect ===\nexport type Cmd<T extends string = string> = { readonly type: T };\n\n// === SyncReturn<S, C>: the compile-time reentrancy guard (ADR 0003 #5) ===\n//\n// The canon rule (`.patterns/tea-do/reentrancy.md`,\n// `.patterns/tea-do/reentrancy-deadlock.md`): a reducer must never\n// inline-`await` a re-entrant result. \"Non-reentrant by default\" ≡ \"the reducer\n// is pure AND synchronous\": a reducer that returns a `Promise` (because it is\n// `async`, or inline-`await`s) is the suspended-but-still-blocking turn Orleans\n// serializes against — it occupies the single-writer slot across a suspension\n// point and can be re-entered mid-flight → deadlock.\n//\n// So the guard is purely type-level: every reducer/transition cell returns\n// `SyncReturn<S, C>` — the synchronous result tuple, intersected with `{ then?:\n// never }` to make it *non-thenable*. A `Promise<readonly [S, readonly C[]]>`\n// is an object with a `then` method, so it fails to satisfy `then?: never`; an\n// `async (s, m) => [...]` (or one that inline-`await`s) is therefore\n// unrepresentable at compile time — `tsc` rejects it *at the cell*, not at a\n// runtime hang. A plain synchronous tuple `[next, cmds]` has no `then` property,\n// so the optional-absent `then?: never` is satisfied and existing pure reducers\n// compile unchanged. `SyncReturn<S, C>` is also assignable *to* `readonly [S,\n// readonly C[]]` (the intersection is narrower), so the runtime dispatch in\n// `run`/`replay` consumes a cell result exactly as before.\n//\n// This mirrors `retry-backoff`'s `Rng` brand (#63): the obligation lives in the\n// type at the construction boundary (\"parse, don't validate\"), not in a comment.\nexport type SyncReturn<S, C extends Cmd> = readonly [S, readonly C[]] & {\n // A thenable carries a callable `then`; forbidding it rejects every Promise.\n // Optional + `never` means \"absent on a sync tuple, impossible on a Promise\".\n readonly then?: never;\n};\n\n// === update form: Reducer vs Transitions, tagged once ===\n//\n// The substrate accepts two `update` shapes (see the `Machine.update` union and\n// the `defineMachine` overloads):\n//\n// - \"reducer\" — flat record keyed by Msg.type, every cell a function.\n// - \"transitions\" — 2D table keyed by State.type then Msg.type, every cell a\n// record of functions.\n//\n// Which one a given machine is must be known at runtime by `run`, `replay`, and\n// the `withX` wrappers (their dispatch / key-enumeration / reserved-namespace\n// scans differ per form). Rather than re-derive it structurally at every reader\n// — a `typeof update[firstKey] === \"function\"` heuristic that breaks the day a\n// reducer cell is itself an object-with-a-call — `defineMachine` computes the\n// form ONCE at construction and stamps it on the machine as a non-enumerable\n// `__form` (so it never serializes, never collides with a Msg.type key, never\n// shows up in `Object.keys(machine)`). Every reader calls `formOf(machine)`.\nexport type UpdateForm = \"reducer\" | \"transitions\";\n\n// The single structural heuristic, defined ONCE. Used only by `defineMachine`\n// (and `formOf`'s fallback for machines built without it, e.g. a plain object\n// literal annotated as `Machine`). A Reducer's first own value is a function; a\n// Transitions table's first own value is a record (of functions). An empty\n// record (`M` is `never`) can never dispatch a Msg, so the form is irrelevant —\n// \"reducer\" is returned arbitrarily.\nexport function detectUpdateForm(update: object): UpdateForm {\n const firstKey = Object.keys(update)[0];\n if (firstKey === undefined) return \"reducer\";\n const firstValue = (update as Record<string, unknown>)[firstKey];\n return typeof firstValue === \"function\" ? \"reducer\" : \"transitions\";\n}\n\n// The single reader every form-sensitive site goes through. Prefers the\n// `__form` tag stamped by `defineMachine` (authoritative — computed once at the\n// typed construction boundary); falls back to `detectUpdateForm` only for a\n// machine that never passed through `defineMachine`. No reader re-implements the\n// heuristic.\nexport function formOf(machine: {\n update: object;\n __form?: UpdateForm;\n}): UpdateForm {\n return machine.__form ?? detectUpdateForm(machine.update);\n}\n\n// === NoCellError: the named cell-lookup failure (#276) ===\n//\n// An unknown `msg.type` (wire data reaching dispatch) or a type-bypassed\n// missing cell used to surface as a bare `TypeError: ... is not a function`\n// deep inside dispatch — no msg.type, no state name, nothing actionable. The\n// guard lives in `applyCell` because it is the single dispatch primitive\n// every stepping site goes through (#275), so one guard covers `run`,\n// replay/foldMsgs, the PBT fold runner, and the withX wrappers.\nexport class NoCellError extends Error {\n override readonly name = \"NoCellError\";\n readonly _tag = \"NoCellError\" as const;\n constructor(\n public readonly msgType: string,\n public readonly stateName: string,\n ) {\n super(\n `@demlik/tea: no update cell for msg.type \"${msgType}\" in state ` +\n `\"${stateName}\" — the machine's update does not handle this Msg ` +\n `(an unknown wire msg.type, or a missing cell reached by bypassing ` +\n `the mapped types).`,\n );\n }\n}\n\n// Reducer-form State carries no mandatory discriminant; best-effort read of a\n// string `state.type` for the error, else a placeholder.\nfunction stateNameOf(state: unknown): string {\n if (typeof state === \"object\" && state !== null && \"type\" in state) {\n const t = (state as { type: unknown }).type;\n if (typeof t === \"string\") return t;\n }\n return \"(untagged state)\";\n}\n\n// === applyCell: THE single reducer-vs-transitions dispatch primitive ===\n//\n// Applies the one update cell selected by `(formOf(machine), state, msg)` and\n// returns its `[nextState, cmds]` verbatim. Every site that steps a machine —\n// `run`'s applyUpdate, `foldUpdates` (replay/foldMsgs), the PBT fold runner,\n// and the withX wrappers — dispatches through THIS function, so production and\n// the verification tools agree on the update form by construction (#275).\n// Pure and dev-check-free: `deepFreeze`/`assertPureResult` stay at the call\n// sites that want them. A missing cell throws `NoCellError` (#276), never a\n// bare TypeError.\nexport function applyCell<S, M extends { type: string }, C extends Cmd>(\n machine: { update: object; __form?: UpdateForm },\n state: S,\n msg: M,\n): readonly [S, readonly C[]] {\n type CellFn = (state: S, msg: M) => readonly [S, readonly C[]];\n if (formOf(machine) === \"reducer\") {\n const record = machine.update as Record<string, CellFn | undefined>;\n const cell = record[msg.type];\n if (typeof cell !== \"function\") {\n throw new NoCellError(msg.type, stateNameOf(state));\n }\n return cell(state, msg);\n }\n const table = machine.update as Record<\n string,\n Record<string, CellFn | undefined> | undefined\n >;\n // The ONE sanctioned `state as unknown as { type }` read: the Transitions\n // overload constrains S to `{ type: string }` at the `defineMachine`\n // boundary, but that constraint is erased on the runtime-facing `object`\n // here — every former per-site copy of this double-cast collapsed into\n // this line (#275).\n const stateKey = (state as unknown as { type: string }).type;\n const cell = table[stateKey]?.[msg.type];\n if (typeof cell !== \"function\") {\n throw new NoCellError(msg.type, String(stateKey));\n }\n return cell(state, msg);\n}\n\n// === applyCellChecked: `applyCell` wrapped in the DEV pre/post invariant pair ===\n//\n// The dev-mode discipline every fold site shares: `deepFreeze` the input `state`\n// so a reducer that mutates it in place trips synchronously, then\n// `assertPureResult` the returned `[state, cmds]` shape. Both guards compile out\n// of production (`__DEV__`). `run`'s dispatch loop and `foldUpdates` both step\n// through THIS wrapper so the invariant enforcement lives in exactly one place\n// and cannot drift between the runtime and the pure fold.\nexport function applyCellChecked<S, M extends { type: string }, C extends Cmd>(\n machine: { update: object; __form?: UpdateForm },\n state: S,\n msg: M,\n): readonly [S, readonly C[]] {\n if (__DEV__) deepFreeze(state);\n const result = applyCell<S, M, C>(machine, state, msg);\n if (__DEV__) assertPureResult(result, msg.type);\n return result;\n}\n\n// === msgKeysOf: recover the Msg.type set from either update form ===\n//\n// A Reducer's own keys ARE the Msg.type set. A Transitions table's keys are\n// state.type; its INNER keys are the Msg.type set (uniform across phases by\n// the mapped-type contract), so the first phase's inner keys are read. An\n// empty update (`M` is `never`) yields `[]`. Keyed on `formOf` — the withX\n// wrappers and the PBT `msgTypeKeys` all read through this one helper (#275).\nexport function msgKeysOf(machine: {\n update: object;\n __form?: UpdateForm;\n}): readonly string[] {\n const keys = Object.keys(machine.update);\n const firstKey = keys[0];\n if (firstKey === undefined) return [];\n if (formOf(machine) === \"reducer\") return keys;\n const firstValue = (machine.update as Record<string, unknown>)[firstKey];\n return Object.keys(firstValue as object);\n}\n\n// === Reducer<S, M, C>: record-of-handlers form of `update` ===\n//\n// Flat dispatch table keyed by `Msg.type`. Each cell is a pure transition for\n// a single Msg variant, narrowed via `Extract<M, { type: K }>`. The mapped type\n// is *load-bearing*: adding a Msg variant without a matching key in the\n// Reducer record is a compile error — no `absurd()` helper at call sites, no\n// silent fall-through, no default branch hiding impurity.\n//\n// Strengthens invariant 2 (pure transitions — the record form has no\n// fall-through default to hide impurity behind) and invariant 7 (identity is\n// explicit — the Msg variant set is load-bearing at the type level).\n//\n// `defineMachine` accepts the Reducer record form via overload. The runtime\n// dispatches via `update[msg.type](state, msg)`.\nexport type Reducer<S, M extends { type: string }, C extends Cmd> = {\n [K in M[\"type\"]]: (\n state: S,\n msg: Extract<M, { type: K }>,\n // `SyncReturn<S, C>` (not `readonly [S, readonly C[]]`) is the reentrancy\n // guard: a non-thenable return type, so an `async`/inline-`await`ing cell —\n // which returns `Promise<...>` — fails to compile at the cell. See the\n // `SyncReturn` doc above.\n ) => SyncReturn<S, C>;\n};\n\n// === Transitions<S, M, C>: table form of `update` for state-machine-shaped machines ===\n//\n// When `State` is itself a discriminated union (`State.type` is the active\n// phase), the table form makes every (state.type × msg.type) cell explicit at\n// the type level. Missing a cell — e.g. forgetting how `phase: \"settling\"`\n// handles `msg.type: \"tab_stepped\"` — fails to compile. No nested switch, no\n// fall-through, no `_ -> (state, [])` default branch hiding regressions.\n//\n// Each cell receives the narrowed `State` for its phase and the narrowed\n// `Msg` for its variant via two `Extract` lookups. Phantom-narrow at the\n// type level; pure data at runtime.\n//\n// `defineMachine` accepts a third `update` form for `Transitions<S, M, C>` —\n// the runtime dispatches via `update[state.type][msg.type](state, msg)`.\n//\n// Strengthens invariant 2 (table form has no fall-through default),\n// invariant 6 (runtime walks the table predictably, no hidden dispatch\n// fallback), and invariant 7 (both state.type and msg.type are load-bearing\n// at the type level).\nexport type Transitions<\n S extends { type: string },\n M extends { type: string },\n C extends Cmd,\n> = {\n [P in S[\"type\"]]: {\n [K in M[\"type\"]]: (\n state: Extract<S, { type: P }>,\n msg: Extract<M, { type: K }>,\n // Same reentrancy guard as `Reducer`: a transition cell that returns a\n // Promise (async / inline-await) is the suspended-blocking turn the canon\n // forbids, so its return is the non-thenable `SyncReturn<S, C>`.\n ) => SyncReturn<S, C>;\n };\n};\n\n// === Cmd: namespace for conditional Cmd emission ===\n//\n// Two recurring frictions in reducer cells:\n//\n// 1. \"Emit cmd X only when condition Y holds.\"\n// Hand-rolled: `cond ? [{ type: \"x\", ... }] : []`\n// With Cmd: `Cmd.when(cond, { type: \"x\", ... })`\n//\n// 2. \"Emit cmd X carrying a value that may be undefined; if undefined,\n// emit nothing.\"\n// Hand-rolled: `value !== undefined ? [{ type: \"x\", value }] : []`\n// With Cmd: `Cmd.whenDefined(value, (v) => ({ type: \"x\", value: v }))`\n//\n// Both forms return `readonly C[]` so they spread cleanly into the cmds\n// array returned by a Transitions cell:\n//\n// return [next, [\n// ...Cmd.when(state.tabId !== undefined, { type: \"detach_debugger\", tabId: state.tabId }),\n// ...Cmd.whenDefined(state.queueItemId, (id) => ({\n// type: \"queue:complete\", queueItemId: id, status: \"done\",\n// })),\n// ]];\n//\n// `Cmd` as a value namespace coexists with `Cmd<T>` as a type — TypeScript's\n// declaration merging puts them in different name spaces (type vs. value).\n// The reader sees `Cmd<...>` in type position and `Cmd.when(...)` in\n// expression position; no ambiguity at use sites.\n//\n// Why a namespace and not top-level `when` / `whenDefined`: `when` at module\n// scope reads as a generic conditional, but these helpers are specifically\n// for *Cmd emission* (return `readonly C[]`, the cmds-array contract of\n// every Transitions cell). The namespace pins that intent at the call site.\nexport const Cmd = {\n /**\n * The empty Cmd array. Typed `readonly never[]` so it's assignable to any\n * `readonly C[]` for any `C extends Cmd`. Use in `init` returns and\n * Transitions cells that emit zero effects:\n *\n * init: (loaded) => [loaded ?? initial, Cmd.none],\n * tick: (state) => [state, Cmd.none],\n *\n * Elm's `Cmd.none` analogue. Cultural signal alongside the runtime help:\n * `[state, Cmd.none]` reads as intent (\"this transition emits nothing\"),\n * `[state, []]` reads as \"empty array of what\".\n *\n * Frozen at runtime so a downstream consumer can't `.push()` into the\n * shared reference.\n */\n none: Object.freeze([]) as readonly never[],\n\n /**\n * Flat concat of cmd arrays. Use when a cell composes effects from\n * multiple conditional sources:\n *\n * return [next, Cmd.batch(\n * Cmd.whenDefined(state.queueItemId, (id) => ({ type: \"complete\", id })),\n * Cmd.when(state.windowId !== undefined, { type: \"close_window\", windowId }),\n * [{ type: \"detach_debugger\", tabId: state.tabId }],\n * )];\n *\n * `<const C>` keeps inline cmd literals' discriminants narrow (same\n * rationale as `when` / `whenDefined` above).\n */\n batch: <const C extends Cmd>(\n ...arrs: readonly (readonly C[])[]\n ): readonly C[] => {\n const out: C[] = [];\n for (const arr of arrs) out.push(...arr);\n return out;\n },\n\n /**\n * Emit `cmd` wrapped in a single-element array iff `cond` is true.\n * Otherwise return the empty array. Spreads cleanly into the cmds array\n * returned by a Transitions cell.\n *\n * `const C` (TypeScript 5.0+) keeps the inferred `type:` discriminator\n * literal narrow when called with an object literal — so `Cmd.when(b,\n * { type: \"x\", ... })` infers as `{ type: \"x\", ... }`, not `{ type:\n * string, ... }`, and stays assignable to a discriminated-union arm\n * without `as const` at the call site.\n */\n when: <const C extends Cmd>(cond: boolean, cmd: C): readonly C[] =>\n cond ? [cmd] : [],\n\n /**\n * If `value` is defined, call `build(value)` and emit the resulting cmd\n * wrapped in a single-element array. If `value` is `undefined`, return\n * the empty array. `value` is narrowed to `T` inside `build`.\n *\n * `const C` on the return type keeps the callback's object-literal\n * `type:` field narrow (see `when` above for the full rationale).\n */\n whenDefined: <T, const C extends Cmd>(\n value: T | undefined,\n build: (value: T) => C,\n ): readonly C[] => (value !== undefined ? [build(value)] : []),\n} as const;\n\n// === SubId: branded string for Sub identity ===\n//\n// Subs are reconciled by id on every transition (canon §2.5, invariant 7).\n// Before branding, `Sub.id` was a raw `string` — a typo at one call site and a\n// different typo at another would silently produce two distinct subs that\n// looked identical to a human reader. The brand makes id construction explicit\n// (`subId(\"...\")`) and catches accidental string-where-SubId at the type\n// level.\n//\n// The brand is structural: `string & { __brand: \"SubId\" }`. The `subId(s)`\n// constructor is the ONE permitted cast in the substrate — every other call\n// site must go through it.\nexport type SubId = string & { readonly __brand: \"SubId\" };\n\n/**\n * Construct a `SubId` from a string. Use this everywhere a Sub literal is\n * built — including ids derived from runtime data (`subId(\\`ws:${auditId}\\`)`).\n * The brand is structural, not nominal, so dynamic ids are permitted; the\n * constructor's job is to make the identity decision explicit at every call\n * site so the type system can catch accidental raw-string drift.\n *\n * Strengthens invariant 7 (identity is explicit).\n */\nexport function subId(s: string): SubId {\n return s as SubId;\n}\n\n// === Sub: tagged-union, continuous source of msgs; stable id used for diff/reconcile ===\nexport type Sub<T extends string = string> = {\n readonly id: SubId;\n readonly type: T;\n};\n\n// === Dispose: the cleanup a dep-keyed Sub's source returns ===\n//\n// A `source` opens a resource and returns the function that closes it. The\n// substrate's reconcile calls it when the Sub's `deps` go null (torn down) or\n// change (re-armed: old `Dispose` then a fresh `source`). Same contract as the\n// `() => void` cleanup every `subscribe[type]` handler returns — named so a\n// dep-keyed Sub's `source` reads as \"open → returns close\".\nexport type Dispose = () => void | Promise<void>;\n\n// === depsInactive: the dep-keyed gate, defined ONCE ===\n//\n// \"This Sub has no slice in this state\" is one fact read by two places — the\n// runtime's `reconcileDepSubs` and `replay`'s desired-set projection — so it\n// gets one definition rather than a `deps === null` written twice.\n//\n// It reads NULLISH, not `null`. `(s) => s.runId` over an optional field is the\n// natural projection an author writes, and it yields `undefined` on the states\n// that mean \"inactive\"; a `=== null` gate armed the Sub there and hashed the\n// slice to the string `\"undefined\"` — one shared key under which a resource\n// was acquired for a state that had none. The typed alternative (`deps: (s) =>\n// {} | null`) would reject that projection at compile time, but it also rejects\n// every battery's `(state) => TKey | null` for an unconstrained `TKey`, so the\n// gate is widened instead of the type narrowed.\nexport function depsInactive(deps: unknown): boolean {\n return deps === null || deps === undefined;\n}\n\n// === structuralHash: deterministic, order-independent id from a deps value ===\n//\n// The id of a dep-keyed Sub (invariant 7 — identity is explicit) is DERIVED\n// from the slice of state the Sub depends on, never hand-authored. So adding a\n// field to `deps` changes the id exactly when that field changes, and a\n// churning id — the named #1 Sub bug (a Sub that remounts every tick, so its\n// timer never fires) — becomes impossible by construction: the author cannot\n// build the id wrong because the author does not build it.\n//\n// Determinism is load-bearing (invariant 2 — the reconcile pass runs inside\n// the pure-transition path's reconcile step; the same `deps` must always hash\n// to the same id). So: NO `Date`, NO random, NO insertion-order dependence.\n// Object keys are sorted so `{ runId, phase }` and `{ phase, runId }` hash\n// identically — the canonical \"name the slice → stable key\" adaptation FoldKit\n// makes for TS (its `modelToDependencies`), which Elm gets free from its\n// structural compare.\n//\n// The supported `deps` shape is plain JSON-compatible data (string / number /\n// boolean / null / array / plain object). A function, class instance, symbol,\n// or bigint in `deps` is a programming error — `deps` names a state SLICE, and\n// state is a value (invariant 1); such a value would also break the\n// determinism this hash promises. The walk throws on all of them to surface\n// that loudly rather than silently producing an unstable — or, worse, a\n// COLLIDING — id.\n//\n// The non-plain OBJECT case is the one that bites: `Object.keys` reports no own\n// enumerable property on a `Date`, `Map`, `Set`, `Error`, or a typical class\n// instance, so a walk that trusts it renders every one of them — and `{}` —\n// as `\"{}\"`. That is not an unstable id, it is ONE id for every value, which\n// defeats the identity filter (a foreign run's message compares equal), pins a\n// dep-keyed Sub to its first slice forever, and makes a battery's handle table\n// return the previous key's handle. The guard is therefore on the PROTOTYPE\n// (`Object.prototype` or `null`), not on a list of known classes: a\n// user-defined `RunKey` is refused by the same rule as `Date`, and no future\n// exotic builtin slips through.\n//\n// Rendering `Date`/`Map`/`Set` structurally was the alternative. It was\n// rejected: it buys a second rule to remember for a value the author can\n// project in one call (`startedAt.toISOString()`), and `Map`/`Set` iteration is\n// INSERTION-ordered, so any faithful rendering is order-sensitive — exactly the\n// churn this hash exists to prevent. One rule, stated once: plain data only.\n//\n// It is also the ONE \"turn this key value into a stable string\" primitive the\n// `@demlik/tea/subs` batteries address their interpret-local handle tables\n// with, so a battery's key rendering and the kernel's Sub identity can never\n// drift into two hashes for one fact.\nexport function structuralHash(deps: unknown): string {\n return stableStringify(deps);\n}\n\nfunction stableStringify(value: unknown): string {\n if (value === null) return \"null\";\n const t = typeof value;\n if (t === \"string\") return JSON.stringify(value);\n if (t === \"number\" || t === \"boolean\") return String(value);\n if (t === \"undefined\") return \"undefined\";\n if (t === \"function\") {\n throw new Error(\n \"@demlik/tea: structuralHash received a function in `deps`. \" +\n \"A dep-keyed Sub's `deps` must be a plain state slice (string / number / \" +\n \"boolean / null / array / object), not a closure — see invariant 1.\",\n );\n }\n if (Array.isArray(value)) {\n return `[${value.map(stableStringify).join(\",\")}]`;\n }\n if (t === \"object\") {\n // Plain-object gate. `Object.keys` is only a faithful reading of a value\n // whose prototype is `Object.prototype` (or `null` — a bag built with\n // `Object.create(null)` is plain by every measure that matters here).\n // Anything else keeps its data somewhere `Object.keys` cannot see, and\n // would render as `\"{}\"` — one id for every such value.\n const proto = Object.getPrototypeOf(value) as object | null;\n if (proto !== Object.prototype && proto !== null) {\n const ctor = (value as { constructor?: { name?: string } }).constructor;\n const label = ctor?.name ?? \"object\";\n throw new Error(\n `@demlik/tea: structuralHash received a non-plain object (${label}) in \\`deps\\`. ` +\n \"A `Date`, `Map`, `Set`, `Error` or class instance carries no own enumerable \" +\n \"properties, so every one of them would hash to the same id as `{}` — a silent \" +\n \"collision, not a wrong-looking key. Project it to plain data first \" +\n \"(e.g. `startedAt.toISOString()`, `[...set].sort()`) — see invariant 1.\",\n );\n }\n const obj = value as Record<string, unknown>;\n const keys = Object.keys(obj).sort();\n return `{${keys.map((k) => `${JSON.stringify(k)}:${stableStringify(obj[k])}`).join(\",\")}}`;\n }\n // bigint / symbol — not JSON-representable; same class of error as function.\n throw new Error(\n `@demlik/tea: structuralHash received an unsupported \\`deps\\` value of type \"${t}\". ` +\n \"Use plain JSON-compatible data for a dep-keyed Sub's `deps`.\",\n );\n}\n\n// === DepKeyedSub<S, M, Ctx>: a Sub whose identity AND gate fall out of `deps` ===\n//\n// The author declares the slice of state the Sub depends on (`deps`) and how\n// to open the resource for that slice (`source`). The substrate derives BOTH:\n//\n// - the **id** = `structuralHash(deps(state))` — changes exactly when the\n// slice changes (re-arm), stable otherwise (no churn). The author never\n// writes `subId(...)` — the hand-written subId was the drift away from\n// Elm's structural identity, which this restores.\n// - the **gate** = `deps(state)` returning `null` ⇒ inactive in this state\n// (dispose if running); non-null ⇒ active. The substrate folds every\n// `DepKeyedSub` into its own active set, so the author deletes the central\n// `subscriptions(state)` aggregate — there is no list to forget to edit\n// when a new phase is added (a per-Sub gate travels with the Sub).\n//\n// This is the FoldKit `modelToDependencies` shape: a Sub names the state slice\n// it depends on, the kernel keys on that slice. The manual `subscriptions?:`\n// field stays as the documented escape hatch (see `Machine`).\n//\n// `source` returns a `Dispose`. On a `deps` change the substrate runs the old\n// `Dispose` then re-runs `source` with the new deps (re-arm); on `deps` going\n// null it runs `Dispose` (teardown). The same reconcile machinery the manual\n// `Sub` path uses (`reconcileSubs` in `../run.ts`) — no second loop.\n//\n// Strengthens invariant 4 (external lifecycle owned by the substrate — the\n// dep-keyed Sub is reconciled, never hand-driven) and invariant 7 (identity is\n// explicit — derived deterministically from `deps`, never an ad-hoc string).\nexport interface DepKeyedSub<S, M, Ctx = unknown> {\n /**\n * The slice of state this Sub depends on. `null` OR `undefined` ⇒ the Sub is\n * inactive in this state (the substrate disposes it if it was running) — see\n * `depsInactive`, so `(s) => s.optionalRunId` gates correctly. Otherwise the\n * Sub is active, keyed on `structuralHash(deps)`.\n *\n * Pure (invariant 2). Plain JSON-compatible data only (invariant 1) — the\n * structural hash walks it deterministically and THROWS on a `Date`, `Map`,\n * `Set`, `Error` or class instance rather than collapsing them all onto one\n * id. Project such a value first (`startedAt.toISOString()`).\n */\n readonly deps: (state: S) => unknown;\n /**\n * Open the resource for the current `state` (whose `deps` the kernel just\n * found non-null). Receives `dispatch` to fire follow-up Msgs (a timer's\n * fire, an inbound frame) and the machine's `ctx` (the host's transport\n * factory, storage handles). Returns the `Dispose` the substrate runs on\n * teardown / re-arm. Same role as a `subscribe[type]` handler's returned\n * cleanup.\n *\n * `source` takes `state` (not the deps slice) so the slice type `D` never\n * escapes the entry — each battery's `.depKeyed` closes over its own typed\n * deps internally (cast-free existential: the entry that produced the deps\n * is the entry that consumes them).\n */\n readonly source: (state: S, dispatch: (msg: M) => void, ctx: Ctx) => Dispose;\n}\n\n// === Identity<S, M>: declare the instance's identity once; the kernel drops\n// mis-addressed messages before they reach `update` ===\n//\n// Without this: the substrate dispatches EVERY message to `update`, so an\n// author who needs \"this message is for THIS run\" must repeat\n// `if (msg.runId !== state.runId) return [state, []]` in every reducer cell.\n// Forget one cell and a stale or foreign run's message is applied → silent\n// corruption. That per-cell check is a rung-4 runtime stand-in for invariant 7\n// (identity is explicit): the identity invariant the host already holds (one\n// instance per run — `idFromName(runId)`) is re-asserted, cell by cell, where\n// it can be forgotten.\n//\n// `Identity<S, M>` lifts that to ONE declaration the kernel enforces. The\n// machine names two projections:\n//\n// - `ofState(state)` → the identity THIS instance owns, derived from state.\n// - `ofMsg(msg)` → the identity a message is ADDRESSED to, or\n// `undefined` when the message carries no identity\n// (lifecycle messages like `boot`, or `start_audit`\n// before the run exists — those are never dropped).\n//\n// Per transition the kernel compares `ofMsg(msg)` to `ofState(state)` by\n// `structuralHash` (so the identity can be any plain value, same machinery the\n// dep-keyed Sub id uses). A message addressed to a DIFFERENT identity is\n// dropped BEFORE `update` runs — the reducer never sees it, so no cell needs a\n// guard. A message with `ofMsg === undefined` is identity-agnostic and always\n// reaches `update`.\n//\n// Two projections rather than a single `(state) => state.runId`: the kernel\n// needs BOTH the state's identity AND the message's to compare, and splitting\n// them keeps the comparison `K`-to-`K` with no `as` cast (a message union\n// carries its identity field on only SOME arms — `ofMsg` narrows per arm in\n// author-land, returning `undefined` on the arms that have none, instead of\n// the substrate reaching into `msg.runId` it cannot type).\n//\n// Opt-in (escape hatch): a machine that declares no `identity` skips the filter\n// entirely — every message reaches `update`, exactly as before.\n//\n// Strengthens invariant 7 (identity is explicit — declared once, derived\n// deterministically, kernel-enforced rather than re-checked per cell) and\n// invariant 6 (the runtime is small and inspectable — a mis-addressed message\n// is dropped at ONE observable point, not silently mishandled in N cells).\nexport interface Identity<S, M> {\n /** The identity THIS instance owns. Pure (invariant 2); plain value. */\n readonly ofState: (state: S) => unknown;\n /**\n * The identity a message is addressed to, or `undefined` when the message\n * carries no identity (lifecycle / pre-identity messages — never dropped).\n * Pure (invariant 2); plain value when defined.\n */\n readonly ofMsg: (msg: M) => unknown;\n}\n\n// === Port<T>: typed escape hatch for \"data leaving the runtime\" ===\n//\n// A Port is a named, typed channel that Cmd handlers can `emit` to via the\n// augmented `ctx.emit(port, value)`. Subscribers attach via\n// `runtime.subscribePort(port, listener)` and receive every emitted value\n// synchronously (same fanout discipline as `runtime.observe`).\n//\n// Why Ports are a substrate primitive, distinct from State and Observe:\n// - **State** is \"the world as the program sees it.\" Folding outgoing\n// announcements into State turns ephemeral signals into persisted facts —\n// the classic anti-pattern that motivated this primitive.\n// - **Observe** sees every transition `(msg, state)`. That's the right channel\n// for devtools and logging, but it forces every consumer to filter the\n// entire firehose for a single signal.\n// - **Ports** are typed and selective: one channel per concept, subscribers\n// only see what the handler chose to emit. Mirrors Elm's outgoing-port\n// semantics — a typed declaration with `port` keyword whose values flow\n// out of the program to the host.\n//\n// Port identity is **by reference** — the returned object IS the identity.\n// Name is metadata for debugging. To prevent the \"two modules definePort the\n// same name expecting to share a channel, silently get distinct ports\" class\n// of bug, `definePort` asserts the name has not been seen in this process —\n// the symmetric runtime check to `SubId` (canon §2.12, invariant 7). Each\n// definePort call must use a unique name; if two modules need the same port,\n// one module exports it and the other imports it.\nexport interface Port<T> {\n readonly __brand: \"port\";\n readonly name: string;\n // Phantom field — never assigned, never read at runtime. Carries `T` for\n // inference at `ctx.emit` and `subscribePort` call sites. Using `?` so\n // `definePort` can produce a Port without constructing a value of `T`.\n readonly __t?: T;\n}\n\n/**\n * Augmentation injected onto `ctx` inside Cmd handlers. Handlers receive\n * `ctx & PortEmitter` so they can call `ctx.emit(port, value)` synchronously.\n * Subscribers registered via `runtime.subscribePort(port, listener)` receive\n * the value immediately.\n *\n * Emitting to a port with no subscribers is a no-op (does not throw).\n */\nexport interface PortEmitter {\n emit<T>(port: Port<T>, value: T): void;\n}\n\n// === NoCtx: the context-free marker ===\n//\n// A handler, Sub, or machine that reads NOTHING from `ctx` says so by using\n// `NoCtx` for its Ctx slot. This is the DELIBERATE absence of context — not\n// the accidental `unknown` looseness that erodes a boundary (see issue #64).\n//\n// `unknown` at a Ctx seam is ambiguous: it can mean \"I intentionally need no\n// context\" OR \"I gave up tightening this type.\" `NoCtx` resolves that\n// ambiguity at the type level. A reader (and the next agent) sees `NoCtx` and\n// knows the context-free-ness is a choice the author made, not a hole.\n//\n// Shape: an empty readonly record. A `Ctx & PortEmitter` is-a `NoCtx`, so a\n// context-free handler still composes at a richer call site. It carries no\n// own fields, so the name's claim (\"reads nothing from ctx\") is what callers\n// read at the seam.\n//\n// Strengthens invariant 6 (no silent looseness — a context-free seam is named,\n// not inferred) and invariant 8 (the boundary is legible; `unknown` stays\n// reserved for genuine wire-edge erasure, not for \"didn't bother\").\nexport type NoCtx = Readonly<Record<never, never>>;\n\n/**\n * Spelled-out alias for `NoCtx`.\n *\n * @deprecated Use {@link NoCtx}. One Way to Do Each Thing — `NoCtx` is the\n * single non-deprecated name for the context-free-ctx marker (this alias has\n * no in-tree uses). Kept as a re-export for one minor per the deprecate-don't-\n * delete policy in `MAINTAINING.md`, then removed.\n */\nexport type ContextFree = NoCtx;\n\n// === Interpret<M, C, Ctx>: record-of-handlers form of `interpret` ===\n//\n// Flat dispatch table keyed by `Cmd.type`. Each cell receives the narrowed Cmd\n// and the runtime-augmented Ctx (`Ctx & PortEmitter`) and resolves to a\n// follow-up Msg or `void` (fire-and-forget). The mapped type makes a missing\n// handler a compile error — `defineMachine` cannot accept the dictionary until\n// every Cmd variant has one.\n//\n// **The injected `dispatch` — the typed Cmd→Msg edge.** A leaf handler that\n// resolves on its own returns its follow-up Msg (`Promise<M | void>`) and\n// IGNORES the third argument. A DETACHED handler (one that hands long-running\n// work to `ctx.waitUntil` and CANNOT return its terminal Msg inline — awaiting\n// it would deadlock the serial dispatch tail) fires its terminal Msg through\n// this injected `dispatch` instead. Today such a handler reaches for a\n// host-wired `ctx.dispatch` typed to the FULL Msg union — so a typo'd or wrong\n// terminal Msg from a detached site compiles silently (rung 5: the allowed set\n// lives only in a comment). `wrapDetached<C, Allowed>` (in `../runtime-types`)\n// narrows THIS injected `dispatch` to the Cmd's declared result-Msg set, so a\n// wrong terminal Msg fails to compile (rung 2).\n//\n// Additive: the third arg is OPTIONAL (`dispatch?: (msg: M) => void`), so a\n// handler declaring only `(cmd, ctx)` stays assignable, and a unit test that\n// invokes a handler directly with two args still typechecks. The kernel ALWAYS\n// passes the dispatch (see `runInterpret` in `../run.ts`); the optionality is\n// purely a backward-compatibility affordance on the TYPE, not a runtime \"maybe\n// absent\". A handler authored via `wrapDetached` receives a NARROWER view of\n// this dispatch (only its declared result-Msg set).\n//\n// Hoisted out of `Machine.interpret` so consumers can type a free-standing\n// handler dictionary with `Interpret<MyMsg, MyCmd, MyCtx>` instead of\n// re-declaring the mapped type at every effects module.\n//\n// Strengthens invariant 2 (the record form has no fall-through default to\n// hide impurity behind) and invariant 7 (identity is explicit — the Cmd\n// variant set is load-bearing at the type level).\nexport type Interpret<M extends { type: string }, C extends Cmd, Ctx> = {\n [K in C[\"type\"]]: (\n cmd: Extract<C, { type: K }>,\n ctx: Ctx & PortEmitter,\n dispatch?: (msg: M) => void,\n // biome-ignore lint/suspicious/noConfusingVoidType: an interpret handler returns a follow-up Msg or nothing; `void` permits no-return bodies that `M | undefined` would reject\n ) => Promise<M | void>;\n};\n\n// === InterpretDetached<C, Allowed, Ctx>: a detached interpret handler ===\n//\n// A handler that detaches long-running work (`ctx.waitUntil(...)`) and therefore\n// CANNOT return its terminal Msg inline (awaiting it would deadlock the serial\n// dispatch tail). It returns `Promise<void>` and fires its terminal Msg through\n// the kernel-injected `dispatch`, which is NARROWED to `Allowed` — the subset\n// of the Msg union this Cmd is permitted to produce. A wrong / typo'd terminal\n// Msg then fails to compile.\n//\n// `Allowed extends { type: string }` is the declared result-Msg set (e.g.\n// `GraphFinished | GraphFailed`). `dispatch: (msg: Allowed) => void` is the\n// narrowed edge. The handler still receives `ctx` (carrying `waitUntil`).\n//\n// Authored via `wrapDetached` (in `../runtime-types`), which adapts this shape\n// back into a plain `Interpret` cell so it drops into the existing `interpret`\n// dictionary with no kernel change at the call site.\nexport type InterpretDetached<\n C extends Cmd,\n Allowed extends { type: string },\n Ctx,\n> = (\n cmd: C,\n ctx: Ctx & PortEmitter,\n dispatch: (msg: Allowed) => void,\n) => Promise<void>;\n\n// === Subscribe<M, U, Ctx>: record-of-handlers form of `subscribe` ===\n//\n// Flat dispatch table keyed by `Sub.type`. Each cell receives the narrowed\n// Sub, the Ctx, and a `dispatch` to fire follow-up Msgs. Returns a cleanup\n// function the substrate calls when the Sub is reconciled out (state\n// transitioned away). The mapped type guarantees every Sub variant has a\n// handler at the type level; runtime dispatch is a single property lookup.\n//\n// The cleanup shares `Dispose`'s shape: a returned Promise is AWAITED by\n// `stop()` (bounded), so an async teardown a host relies on before evicting the\n// isolate actually completes. Mid-run reconcile does not await it — the\n// reconcile pass is synchronous by construction (invariant 2) — but the promise\n// is tracked from the moment it exists, so `stop()` catches it either way.\n//\n// Hoisted out of `Machine.subscribe` so consumers can type a free-standing\n// handler dictionary with `Subscribe<MyMsg, MySub, MyCtx>` instead of\n// re-declaring the mapped type at every subs module.\n//\n// Strengthens invariant 7 (identity is explicit — the Sub variant set is\n// load-bearing at the type level).\nexport type Subscribe<M extends { type: string }, U extends Sub, Ctx> = {\n [K in U[\"type\"]]: (\n sub: Extract<U, { type: K }>,\n ctx: Ctx,\n dispatch: (msg: M) => void,\n ) => Dispose;\n};\n\n// === Machine: pure data, host-agnostic ===\n//\n// `update` is stored as a union of the two record forms — the runtime branches\n// on shape at dispatch time. The public `defineMachine` overloads enforce one\n// shape per call so consumers never see the union themselves.\n//\n// - Reducer form: `Reducer<S, M, C>` — flat record keyed by Msg.type;\n// exhaustiveness enforced by the mapped type.\n// - Transitions form: `Transitions<S, M, C>` — 2D table keyed by\n// `state.type` then `msg.type`; only available when `S extends { type:\n// string }`. Conditional in the union so machines without a discriminated\n// State don't widen to include this branch.\n//\n// `M` is constrained to `{ type: string }` because both record forms require\n// a string discriminant.\n//\n// `interpret` is conditionally optional: when `C` is `Cmd<never>` the\n// interpret map is keyed by `never`, so the only valid value is `{}`. Forcing\n// every cmdless machine to write `interpret: {} as never` is ceremony for a\n// shape the type already pins. The tuple-wrap (`[C] extends [Cmd<never>]`)\n// disables distributive conditional so a real cmd union (e.g.\n// `Cmd<\"a\"> | Cmd<\"b\">`) doesn't degrade to optional just because one arm\n// happens to be `Cmd<never>`. Same trick the `update` field uses.\nexport type Machine<\n S,\n M extends { type: string },\n C extends Cmd,\n U extends Sub,\n Ctx,\n> = {\n /**\n * Boot the runtime. Called once by `run(...)` with whatever `Store.load()`\n * returned: `null` on fresh boot, the persisted state on rehydrate.\n *\n * **Contract:** when `loaded !== null`, init MUST return `[loaded, []]` —\n * no Cmds. Init's rehydrate branch is the migration / parse boundary, not\n * the boot-effect hook. See Invariant 2 in `.patterns/tea/tea-invariants.md`.\n *\n * Boot effects routes:\n * - Stateless infrastructure → host module top, outside TEA.\n * - State-conditional resume → a `boot` Msg the host dispatches once\n * after `run(...)` returns.\n *\n * Violations are caught at runtime by `replay` (which throws with a\n * pointer to the alternatives).\n */\n init: (loaded: S | null, ctx: Ctx) => readonly [S, readonly C[]];\n update:\n | Reducer<S, M, C>\n // Wrap in tuple to disable distributive conditional behavior. Without\n // `[S]`, TS distributes the conditional across `S`'s union members,\n // producing `Transitions<A,...> | Transitions<B,...>` instead of the\n // desired `Transitions<A|B,...>` — the table form needs a single\n // mapping over the full union of state types, not separate tables per\n // member.\n | ([S] extends [{ type: string }] ? Transitions<S, M, C> : never);\n /**\n * Dep-keyed Subs. Each declares the state slice it depends on; the substrate\n * derives the id (`structuralHash(deps)`) and the gate (`deps` non-null) and\n * folds them into the SAME reconcile loop `subscriptions` feeds. The author\n * never writes `subId(...)` and never lists Subs in a central\n * `subscriptions(state)` aggregate — a per-Sub gate travels with the Sub, so\n * a new phase can't silently forget to arm it.\n *\n * The deps slice type is erased to `unknown` per entry — each Sub's slice\n * differs, but the slice type never crosses this field (the kernel only needs\n * to hash it and pass `state` back to that same entry's `source`).\n *\n * Optional and independent of `subscriptions` / `subscribe`: a machine that\n * omits `subs` reconciles exactly as before.\n *\n * Strengthens invariant 4 (lifecycle owned by the substrate) and invariant 7\n * (identity derived, not hand-authored).\n */\n subs?: ReadonlyArray<DepKeyedSub<S, M, Ctx>>;\n /**\n * Instance-identity filter. Declares THIS instance's identity once; the\n * substrate drops any message addressed to a DIFFERENT identity before it\n * reaches `update`. Replaces the per-cell `if (msg.runId !== state.runId)`\n * guard entirely — the reducer never sees a foreign-instance message, so no\n * cell needs to check.\n *\n * Opt-in: a machine that omits `identity` skips the filter (every message\n * reaches `update`, exactly as before). A message whose `ofMsg` returns\n * `undefined` is identity-agnostic and always reaches `update` (lifecycle /\n * pre-identity messages).\n *\n * Strengthens invariant 7 (identity is explicit — declared once, enforced by\n * the substrate) and invariant 6 (mis-addressed messages dropped at one\n * observable point, not per cell).\n */\n identity?: Identity<S, M>;\n /**\n * Manual Sub aggregate — the documented escape hatch, KEPT alongside `subs`.\n * The machine that needs cross-Sub logic the per-Sub `deps` fold can't\n * express lists Subs here; the substrate reconciles them via `subscribe`.\n * Both paths feed ONE reconcile pass.\n */\n subscriptions?: (state: S) => readonly U[];\n subscribe?: Subscribe<M, U, Ctx>;\n /**\n * The update form (\"reducer\" | \"transitions\"), stamped non-enumerably by\n * `defineMachine` at construction (see `UpdateForm` / `formOf`). Optional in\n * the type so the structural `Machine` annotation form keeps accepting plain\n * object literals; readers go through `formOf`, which falls back to\n * `detectUpdateForm` when the tag is absent. Never written by hand.\n */\n readonly __form?: UpdateForm;\n} & ([C] extends [Cmd<never>]\n ? { interpret?: Interpret<M, C, Ctx> }\n : { interpret: Interpret<M, C, Ctx> }) &\n // `subscribe`/`subscriptions` are conditionally REQUIRED the same way\n // `interpret` is (#276): a machine declaring a real Sub union without a\n // subscribe map compiled and silently wired no subs (`reconcileSubs` skips\n // undefined handlers) — the exact silent-failure class the `interpret`\n // conditional prevents. The optional declarations above stay as U's\n // inference sites (a conditional type is not an inference site); this\n // intersection only adds requiredness when U is a real union. Same\n // tuple-wrap trick as `interpret` to disable distribution.\n ([U] extends [Sub<never>]\n ? unknown\n : {\n subscriptions: (state: S) => readonly U[];\n subscribe: Subscribe<M, U, Ctx>;\n });\n\n// === foldUpdates: the single internal fold `replay` and `foldMsgs` share ===\n//\n// Folds `machine.update` over `msgs` from `initialState`, dispatching each\n// Msg through `applyCell` — the same primitive `run` uses — so every fold site\n// agrees on the reducer-vs-transitions form by construction (no second copy of\n// the dispatch to drift). Returns the final state plus the Cmds the cells emitted\n// along the way; the caller keeps them (`replay`) or discards them (`foldMsgs`).\n//\n// Touches no `Store`, no `interpret` handler, and starts no subscription — it\n// only calls `update` cells. The two public folds differ only in how they\n// enter and what they return: `replay` enters via `init` and returns\n// `{ state, cmds, subs }`; `foldMsgs` enters from a base state and returns `S`.\nexport function foldUpdates<S, M extends { type: string }, C extends Cmd>(\n machine: { update: object; __form?: UpdateForm },\n initialState: S,\n msgs: readonly M[],\n): { state: S; cmds: C[] } {\n let state: S = initialState;\n const cmds: C[] = [];\n\n for (const msg of msgs) {\n const [next, emitted] = applyCellChecked<S, M, C>(machine, state, msg);\n state = next;\n cmds.push(...emitted);\n }\n\n return { state, cmds };\n}\n\n// === foldMsgs: runtime-free client-prediction fold seam (ADR 0006, #211) ===\n//\n// Folds `machine.update` over an ordered `Msg[]` starting from a caller-supplied\n// `base` state and returns the resulting state ONLY. This is the client-side\n// replay primitive a prediction loop needs (the Gambetta/Valve\n// authoritative-server reconcile step): re-simulate a queue of un-acked inputs\n// on top of an authoritative snapshot —\n// `foldMsgs(machine, snapshot, pendingInputs)`.\n//\n// Distinct from `replay` (the test idiom), by design (ADR 0006):\n// - Enters from a direct `base` parameter, NOT via `init`/`loaded` — so\n// reconciliation correctness never depends on the machine author's `init`\n// rehydrate discipline. Takes no `ctx` (the fold calls `update` only).\n// - Returns just the final `S` — not `{ state, cmds, subs }`. During prediction\n// the inputs' effects were already sent to the server; re-emitting their Cmds\n// on the client would double-fire, and `subs` are a runtime concern. Returning\n// only `S` makes \"replay fires no effects\" structural, not caller discipline.\n// A caller that wants the emitted Cmds for assertions uses `replay`.\n//\n// Invokes no `Store`, no `interpret` handler, and starts no subscription — it\n// shares `replay`'s `foldUpdates` fold, which only calls `update` cells, and\n// reads the reducer-vs-transitions form via the same `formOf(machine)` reader\n// `run`/`replay` use, so it agrees with them by construction.\n//\n// Per ADR 0006 the runtime-free *guarantee* lives on a dedicated\n// `@demlik/tea/pure` subpath whose module graph never reaches `run`; that\n// subpath export + import-graph guard are #213's scope. Here `foldMsgs` ships\n// as a reachable public API from root; #213 formalizes the boundary.\nexport function foldMsgs<\n S,\n M extends { type: string },\n C extends Cmd,\n U extends Sub,\n Ctx,\n>(machine: Machine<S, M, C, U, Ctx>, base: S, msgs: readonly M[]): S {\n return foldUpdates<S, M, C>(machine, base, msgs).state;\n}\n"]}
|