# plusthree design Status: accepted (2026-11-17). This file is the canonical design; change it in the same commit as any change that departs from it. plusthree is a high-performance Rust port of XState v6. A statechart can be defined in typed Rust (a builder or a proc macro) or loaded from XState MachineJSON at runtime. Both paths compile into the same flat table form (the IR) and run on the same kernel. The kernel is sans-I/O and `no_std + alloc`: it never sleeps or spawns anything itself, and returns effects as data for the host to carry out. ## 1. Goals and non-goals **Goals** 1. **Correct XState v6 semantics.** The reference is `xstate@6.0.0-beta.3` (commit [`8e53990`](https://github.com/statelyai/xstate/commit/8e53990c2f9318d2d649b8af1a3c96af970d9bf2)), checked with differential tests against real XState (§9). Correctness wins over parity: where XState has a bug or an accidental quirk, plusthree does the correct thing and records the difference (§2). 2. **One IR and one kernel** shared by typed and JSON-loaded machines. Any semantic difference between the two paths is a bug. 3. **Typed by default.** User-defined context, event, effect, emitted-event, input and output types. No `serde_json::Value` unless the user chooses it. 4. **Fast.** No allocation per event in steady state. Bitset configurations. Transition plans precomputed when the machine is built. Targets are in §10. 5. **Pure, deterministic core.** `step(machine, &mut snapshot, event) -> effects`, with logical timers stored in the snapshot. The host owns the clock and I/O. The same core runs under tokio, embassy, WASM, or a test with simulated time. 6. **Compatible with the XState ecosystem:** MachineJSON import, the persisted snapshot format, and inspection events. That makes Stately tooling and existing definitions usable. **Non-goals for v1** - Running JavaScript or other code embedded in JSON (`@code`, `@expr`). JSON machines bind named implementations from a Rust registry. An evaluator trait can come later. - SCXML semantics. plusthree is an XState port, not an SCXML engine; an SCXML profile is not planned (§11). - Durable execution (`createAsyncLogic` with journaled `enq.step`), and observable, listener and subscription actors. - `no_std` without `alloc`. - Generating Rust code per machine. v1 interprets the tables. Codegen is a post-0.1 option (§10). ## 2. Semantics contract **The reference is XState v6 native semantics.** The highlights, all confirmed in the v6 source: - **State kinds:** `atomic | compound | parallel | final | history(shallow|deep) | choice`. - A compound state must declare `initial`. - Final states are inert: they take no transitions and start no invokes. - A `choice` state is rewritten into its `always` transitions. - **Transitions:** either an object `{target, context patch, input, reenter, meta}` or a transition function returning `Option`. - A function that returns `None` and enqueued nothing is not enabled. Selection then falls through to the ancestors. - There are no arrays of guarded transitions. Only JSON import accepts them, as consecutive guarded transitions (§7). - **Transition domain** (port `getTransitionDomain` + `narrowParallelDomain` from `packages/core/src/stateUtils.ts` verbatim): - `reenter` defaults to false. - Targets inside the source: the domain is the source with `reenter: true`. Otherwise the domain is narrowed through parallel nodes. - Otherwise: the LCA of source and targets, narrowed through parallel nodes unless `reenter: true`. Narrowing means a transition only exits the parallel region that contains its targets. - Special case: a history target that restores the source itself must exit and re-enter the source. - **Priority:** - Conflicting transitions (their exit sets intersect): the one whose source is a descendant wins, otherwise document order. - Event matching: exact name first, then wildcard descriptors longest first. - **Order inside a microstep** (§6.3 has the full list): 1. Record history. 2. Exit states deepest first. For each: its exit function, then stop its invokes. 3. Merge transition context patches in document order. 4. Enter states in document order. For each: spawn invokes, entry function, initial/history default content, `xstate.done.state` events. - **Macrostep:** the external event, then loop: eventless transitions first, otherwise the next internal event. Starting spawned or invoked children is deferred to the end of the macrostep. - **Errors abort the whole macrostep.** - If some active state handles `xstate.error.execution` (`onError`), the macrostep reruns from the pre-event snapshot with that event. - Otherwise the status becomes `error` and all children are stopped. - **Rewritten sugar:** `after`, `timeout`, `onTimeout`, `onDone` and `onError` become category events plus payload matchers. The delayed ones become logical timers scheduled on entry and cancelled on exit. **Correctness over parity.** XState is the oracle wherever it behaves as intended. We do not reproduce its bugs, JavaScript artifacts or accidental behaviour. When we judge XState wrong, we: - write down the correct behaviour and why, as an entry in `DEVIATIONS.md` (citing XState docs, SCXML, or an invariant such as "the configuration is always valid"); - add a Rust test that asserts the correct behaviour; - add the affected steps to the replay allow-list with the deviation ID and the fields or effects it changes, so every other step, and the rest of those steps, is still compared. Where XState's intent is unclear, prefer its documentation, then SCXML, then the simplest rule that keeps the invariants. Intended v6 design choices that differ from SCXML (§2 above, such as domain narrowing and `reenter: false`) are not bugs; we keep them. So is the asymmetry where an unhandled child error fails the parent while an unhandled child done event is ignored: errors escalate, completion is informational (conformance NOTES #9). **Deviations from v6.** | # | Deviation | Why | | --- | --- | --- | | D1 | `max_microsteps` defaults to 10,000 (v6: unbounded unless `maxIterations`). Hitting it raises an execution error. | Infinite eventless loops must not hang a `no_std` target. | | D2 | A transition function runs **exactly once** per selection (v6 can run it twice; #5910). | Determinism and speed. Visible only if a user function has side effects outside `enq`. | | D3 | Panics are not caught by the kernel. Only `Err` returned from user code becomes `xstate.error.execution`. | `no_std`, and Rust convention. The std runtime can opt in to `catch_unwind`. | | D4 | A transition into a history state always yields a valid configuration. v6 computes the domain from pre-microstep history but enters the newly recorded value, which can enter an invalid configuration. The kernel picks one consistent rule and documents it in `DEVIATIONS.md`. | Valid configurations are an invariant. | | D5 | Final states schedule no `after`/`timeout` timers. v6 schedules them and later fires an empty microstep. | Final states are inert. | | D6 | Document order is the order written in the source, including JSON keys that look like integers. v6 inherits JS `Object.keys` order (integer-like keys first). | JavaScript artifact. | | D7 | A timer consumed in a macrostep that errors and recovers is gone from the recovered snapshot. v6 leaves it listed, and it never fires. | A dangling timer that can never fire is a bug. | | D8 | An invoke with a `timeout` keeps the `context` patch on its `onDone`/`onError` transitions. v6 wraps them in a function and drops the patch. | Bug. | | D9 | A JSON action list that assigns produces a patch of only the keys it assigns. v6's `machineFromJSON` returns the whole `{...pre, ...patch}` context, so a later transition in the same microstep (for example in another parallel region) undoes an earlier one's patch. | Bug; seen in random traces 0031, 0059, 0074, 0098. | | D10 | JSON `matches` compares values by JSON equality. v6 uses `Object.is`, so object and array values never match. | JavaScript artifact. | | D11 | JSON `after` keys must be plain decimal milliseconds. v6 runs them through `Number()`, so `""`, `" 20 "`, `"0x14"`, `"1e3"` and `"-5"` are accepted. | JavaScript artifact. | | D12 | An unparsable delay string is a load error at its JSON path. v6 silently uses `parseFloat(s) \|\| 0`. | Silent misconfiguration. | | D13 | All JSON transition and choice-branch targets are resolved at load. v6 checks targets of transitions with actions, and of choice branches, only when first taken. | Errors belong at load time. | | D14 | A root's own `on["xstate.route"]` is kept alongside generated routes. v6 silently replaces it when routes exist. | Silent data loss. | | D15 | Selection visits parallel regions (event selection) and active atomic states (eventless selection) in document order, and history values are listed in document order. v6 uses JS `Set` insertion order, where a re-entered state moves to the end. | JavaScript artifact; SCXML and this section use document order. | | D16 | An unrecovered execution error cancels every pending timer (`Cancel` effects, empty timer list) and stops every child, removing it from the snapshot. v6 keeps the timers listed though they never fire, and keeps the stopped children listed. | The snapshot lists only timers that can fire (as D7) and children that run. | | D17 | No `Start` effect is emitted for a child that was stopped earlier in the same macrostep, and no second `Stop` for a child already stopped. v6 still emits `@xstate.start` for it, and `@xstate.stop` again. | Starting a stopped actor is a bug (conformance NOTES #10). | | D18 | Messages between actors go through one FIFO system queue, and each actor's macrostep completes and is published before the next message is delivered, as in v6's `systemTransition`. v6's `createActor` runtime delivers synchronously and depth-first, so a child's macrostep can finish before the sender's is published. `plusthree-system` and `plusthree-runtime` both use the FIFO order. Replay compares each actor's own macrostep sequence and the causal order of messages, not the global interleaving. Events still queued for an actor when it stops are dead letters (reason `stopped`); `systemTransition` drops them silently. | XState's two runtimes disagree; run-to-completion per actor and one deterministic order (NOTES #12). | | D19 | Restored timers keep their remaining delay under any clock: the persisted snapshot carries each timer's deadline relative to the system's `now`. v6 restarts the full delay unless the clock is wall-clock. | Restoring must not change when a timer fires (NOTES #14). | | D20 | An error in the initial macrostep is never recovered: there is no pre-event snapshot to return to. The machine ends with status `error`, its initial context, an empty configuration, and a published transition event. v6 recovers only through a root `onError`, skips the root's entry, publishes no transition, and leaves a snapshot with no value or context. | Consistent with the error model; no half-built snapshots (NOTES #18). | | D21 | An inspection event's `sent` lists each delayed send or raise with its own event. When a later send replaces one under the same id in the macrostep, v6 shows the replacing event in both entries. | Inspection describes what was scheduled. | ## 3. Architecture ``` plusthree facade crate: re-exports, prelude, feature flags ├─ plusthree-ir no_std+alloc. Builder, validation, flattening, desugaring, interning -> MachineDef ├─ plusthree-core no_std+alloc. Kernel: Snapshot, step/initial, selection, microstep, effects buffer, rollback journal ├─ plusthree-derive proc macros: #[derive(Context, Event, Children)], machine! DSL (emits builder calls + typed handles) ├─ plusthree-json std. MachineJSON import/export (machine.schema.json), Registry of named impls, persisted snapshot serde ├─ plusthree-system no_std+alloc. Pure actor-system reducer (port of systemTransition / advanceSystemTime) ├─ plusthree-runtime std. Mailbox actors, clock adapters: tokio, std thread, simulated; embassy behind a feature ├─ plusthree-inspect std. @xstate.actor / @xstate.transition events, Stately inspector bridge └─ (dev) conformance/ differential harness vs XState (Node), ported v6 tests, SCION corpus (later) (dev) plusthree-bench criterion + gungraun instruction counts, cross-library scenarios ``` - **Edition and MSRV:** Rust 2024 edition, MSRV = the stable release 2 versions back. - **Unsafe:** `core` and `ir` are `#![forbid(unsafe_code)]` until a benchmark justifies an exception. ## 4. The IR (`MachineDef`) The builder, the macro and JSON import all produce a `MachineDef`. It is validated, flattened and immutable once built. Building happens once (`OnceLock`, or `LazyLock` for statics). After that, everything is index-based. ### 4.1 States States are numbered in **pre-order**, so `StateId(u32)` is the document order (v6 `order`). The tables use struct-of-arrays layout: | Field | Meaning | | --- | --- | | `parent: [StateId]` | parent (the root points to itself) | | `depth: [u8]` | depth in the tree | | `kind: [Kind]` | atomic, compound, parallel, final, history(shallow\|deep), choice | | `subtree_end: [StateId]` | descendants of `s` are exactly `s+1 .. subtree_end[s]` | | `initial: [Option]` | compound states: a transition with `Trigger::Initial`, static targets or a function, plus input and meta | | `children: [Range]` | into a `child_ids` array (sorted, contiguous; history states excluded, as v6 `getChildren`) | | `entry` / `exit: [Option]` | at most one entry and one exit function per state (v6) | | `transitions: [Range]` | the state's own transitions, contiguous in `TransitionId` order; `always: [Range]` and the candidate index (§4.3) point into them | | `history_default: [Option]` | history states only (`Trigger::HistoryDefault`) | | `invokes: [Range]`, `timers: [Range]` | into the invoke table and the timer table (desugared `after`/`timeout`/invoke `timeout`, in v6 scheduling order) | | `tags`, `meta`, `key`, `id` | metadata; `id` is interned and used for `#id` targets and StateValue | **Consequences:** - `is_descendant(a, b)` is `b < a && a < subtree_end[b]`, which is O(1). - "Active descendants of d" is `config & range(d+1, subtree_end[d])`, computed with word masks. No per-state mask is stored. - Entry order is ascending bit order and exit order is descending bit order, so nothing is ever sorted. ### 4.2 Transitions ```rust struct TransitionDef { source: StateId, trigger: Trigger, // Event(TriggerKey) | Wildcard(WildcardId) | Always | Initial | HistoryDefault guard: Option, // matches pattern or guard, checked before the body body: Body, // Static { targets, reenter, patch } | Function(FnId) input: Option, meta: Option, cancel_timer: Option,// invoke completion transitions of a timed invoke (v6 cancels the timeout) plan: Option, // precomputed when the whole entry set is static } struct StaticPlan { domain: Option, exit: Range, enter: StateSet, default_entry: StateSet } ``` - **Static transitions** get their domain, exit scope and entry set precomputed at build time. At runtime, the exit set is just `config & exit`. `exit` is `range(domain+1, subtree_end[domain])`, widened to include the domain when a reentering transition's domain is its own source, everything when the domain is `None`, and empty when there are no targets. `default_entry` is v6's `statesForDefaultEntry`: entered compound states in it run their initial transition's content (input or function). - A plan is built only when the entry set is fully static: no history target, and default-entry completion reaches no history state and no function initial. - **Function transitions, and transitions targeting history,** compute their domain at runtime (`resolve`, then `enter_set` after history is recorded). That costs O(depth) with the parent/depth arrays. The states entered, ancestors included, use the history value recorded by this microstep's exits (D4); the domain is computed from the value before the microstep, which gives the same domain because a history value only changes when its parent is exited. Results for a given (source, targets, reenter) can be cached in a small LRU per machine. Benchmarks will decide whether that cache is worth having. - **Default-entry completion:** `default_entry[s]` is a precomputed `StateSet`: s plus its initial chain, plus every region of each parallel state, applied recursively, together with its `statesForDefaultEntry`. When the expansion reaches a history state or a function initial it depends on runtime data, so no entry is stored and the runtime walk expands it. Entering a state by default is then one OR. This costs n² bits. Above 2,048 states the table is not built and default entry is computed by walking the tree instead. ### 4.3 Events and candidate lookup - **Event names are interned** into an `EventId(u32)` at build time. - Typed machines have a closed alphabet: `#[derive(Event)]` gives each variant a name (`Event::NAMES`, and the `const fn` `EvKind::Inc.name()` on the generated fieldless `EvKind`) and `Event::index(&self)`, the declaration index, which is a `match` on the discriminant. The machine maps indices to `EventId`s with a table built once from `NAMES`. - JSON machines with untyped events intern unknown names on demand. A name the machine never mentions can only match wildcards. - **Built-in events never use strings.** Each v6 built-in event (`xstate.done.state`, `xstate.after`, `xstate.timeout.state`, `xstate.done.actor`, `xstate.error.actor`, `xstate.snapshot.actor`, `xstate.timeout.actor`, `xstate.error.execution`) has a reserved `EventId`, and triggers are keyed by `TriggerKey { event, arg }`: the arg is the `StateId` for done.state, the `TimerId` for after and timeout.state, and the `InvokeId` for actor events. v6's `matches: {stateId}` payload check therefore becomes a direct lookup. The names stay interned so user wildcards such as `*` or `xstate.done.*` match built-in events, as in v6. State `onError` is the v6 wildcard `xstate.error.*`. - **Per-state candidate index:** a sorted slice of `(TriggerKey, Range)` into a shared list of `TransitionId`s. A lookup with a specific arg falls back to the arg-less key. - It is precomputed with v6's `getCandidates` order: exact matches first, then wildcards longest first. - Lookup is a linear scan for 8 entries or fewer, otherwise a binary search. When states × events ≤ 2^18 (and states ≤ 2,048), a direct `(state, event) -> Range` table answers arg-less lookups in one load. - Per event, a `StateSet` of the states with candidates for it (the *listeners*), plus one for wildcard groups, is built under the same state limit. Selection visits only `config ∩ listeners(event)`, replaying v6's recursion over those states in pre-order with a stack of states waiting for their descendants; an event no active state listens to is unhandled without touching the tree. - The wildcard matches are folded into every interned event key at build time, so a lookup never has to fall back to wildcards. Names interned later (open alphabets) use `wildcard_candidates(state, name)`. - Final states have no candidates (v6: they take no event transitions); their eventless transitions remain. - User `matches` patterns (shallow payload equality) become a predicate `FnId` checked before the transition body runs. ### 4.4 Semantics profile `MachineDef` carries `Semantics { domain: V6 | Scxml, default_reenter: bool, matching: Exact | Prefix, errors: AbortMacrostep | QueueErrorEvent }`. Only `default_reenter` exists; the other fields would arrive only with an SCXML profile, which is not planned (§11). ## 5. Typed API ### 5.1 Types ```rust pub trait Types: 'static { type Context: Context; // #[derive(Context)] or serde_json::Map for JSON machines type Event: Event; // #[derive(Event)] enum type Effect; // user action enum, executed by the host type Emitted; // enq.emit payloads type Input; type Output; type Error; type Children: Children; // #[derive(Children)] enum, `()` when the machine has no children } pub trait Context: Clone { type Patch: Default; /// Apply a shallow patch; return the inverse patch (old values) for rollback. fn apply(&mut self, patch: Self::Patch) -> Self::Patch; } ``` **Why patches instead of mutable context.** In v6, transition functions run during selection against the context as it was before the microstep. Their patches are merged later, in document order, after the exit functions have run. A patch reproduces that exactly. It is also data, which makes it serializable, comparable in differential tests, and invertible for rollback. `#[derive(Context)]` on `struct Ctx { count: u32, name: String }` generates `CtxPatch { count: Option, name: Option }` with setter methods. For a JSON machine whose context is a `serde_json::Map`, the patch is a map and gets v6's `{...ctx, ...patch}` behavior unchanged. **Escape hatch:** a user can implement `Context` by hand with `type Patch = Self`, which replaces the whole context. **What inspection may show.** `Context::show_fields` passes inspection the fields it may show as `FieldValue`s (flags, numbers, text, durations in milliseconds); its default passes none. `#[derive(Context)]` overrides it only when fields are marked `#[context(show)]` (through `ShowField`) or `#[context(show_with = path)]`, so nothing shows unless marked and unmarked contexts generate no extra code. `VariantName` (`#[derive(VariantName)]`) names an enum value by its variant, never its data; a shown field of such a type shows its variant name, and inspection names effects with it. Both live in core so the derives work without the `inspect` feature; the kernel never calls them. ### 5.2 Implementations ```rust pub struct Args<'a, T: Types> { pub context: &'a T::Context, pub event: &'a Envelope, pub state: StateView<'a, T>, inputs: &'a [(StateId, StateInput)] } // a.input() pub struct Transition { target: Targets, patch: Option<::Patch>, reenter: Option, input: Option, meta: Option } type TransitionFn = dyn Fn(&Args, &mut Enq) -> Result>, T::Error> + Send + Sync; type ActionFn = dyn Fn(&Args, &mut Enq) -> Result>, T::Error> + Send + Sync; // entry/exit ``` - **Storage:** implementations live in `Arc`, created once at build time. A call costs one indirect call, the same as a `fn` pointer, and closures can capture data (JSON registries need this). - **Ergonomics:** helper traits let users return `Option`, `Transition`, or `()` instead of the full `Result` type. - **State input** (v6 `input`, `_stateInputs`): a transition's input is computed once, against the snapshot before the microstep, by an input function (`TransitionDef::input`) or set by a transition function with `Transition::input(v)`. After the exits, the inputs of states no longer active are dropped, then each target the transition entered gets the input; a compound state entered by default gives its initial's input to the initial targets after its entry function. `a.input()` reads the source's input: guards and transitions see it as of before the microstep, exit functions the old input, entry functions, delays and outputs the new one. A `StateInput` is an `AnyData` (any `Debug + Send + Sync` value; JSON machines use `serde_json::Value`), so `Types` gets no input type; persisting needs a JSON object held as a `serde_json::Value`. `Args` stores the snapshot's input slice and looks the input up on demand, so building `Args` for a guard costs no lookup. `Enq` writes into the caller's effects buffer, which is reused across events: `enq.action(T::Effect)`, `enq.raise(ev)`, `enq.raise_after(ev, delay, id)`, `enq.cancel(id)`, `enq.emit(T::Emitted)`, `enq.send_to(addr, ev)`, `enq.spawn(src, opts)`, `enq.stop(addr)`, `enq.log(..)`. User actions are a **data enum** (`T::Effect`) that the host interprets. That is what makes them allocation-free, serializable and assertable in tests. A user who really wants callbacks can make `type Effect = Box`. ### 5.3 Definition surfaces **Builder:** the foundation, used by tests and by JSON import. ```rust let m = Machine::::builder("counter") .initial("active") .state("active", |s| s .on_fn(EvKind::Inc, |a, _| Transition::::stay().patch(|p| p.count(a.context.count + 1))) .after(Duration::from_secs(5), "idle")) .state("idle", |s| s.on(EvKind::Inc, "active")) .build()?; // validation errors carry the state path ``` - **One method per transition form.** `on(kind, targets)` is a static transition, `on_fn(kind, |a, enq| ..)` a transition function, and `on_with(kind, |t| t.to(..).guard(..).action(..))` a static transition with a guard, content or `reenter`; `always`, `after`, `on_done` and `on_error` follow the same pattern. One generic `on` that accepted both targets and closures would lose closure signature inference, so every handler would need annotated arguments. - **One annotation remains:** Rust types `Transition::stay().patch(|p| ..)` before it learns the closure returns `Transition`, so the builder needs `Transition::::stay()` (or `with_patch`). `machine!` handlers do not: the macro declares `Transition` as the machine's transition type around each handler. - **Wildcards:** `on_wildcard("user.*", ..)` (with `_fn` and `_with` forms) adds a transition for a v6 wildcard descriptor: `*`, or a prefix ending in `.*`, which also matches the prefix itself (`user`). A descriptor with an infix `*`, which v6 never matches, is a build error. The handler signature is the same as for `on`, because `Args::event` is already an `Envelope`: a handler that can see any event reads it from there (`a.event.event()` for the user event, or a `match` on the built-in variants). - **Delay functions** are named, as in v6's `delays`: `delay("backoff", |a| ..)` declares one on a state for it and its descendants (a nearer declaration shadows), and `after` takes a `Duration` or a delay name. Entries with the same delay, fixed or named, share one timer and are tried in order. A name nobody declares is a build error. - **Function initials:** `initial_fn(|a, enq| ..)` computes a compound state's initial child. - **State input:** `TransitionBuilder::input(|a| value)` on any transition, and `initial_with(|t| t.to("child").input(|a| ..))` for an initial with an input. `a.source` is the state, so `a.resolve(".child")` names a child; `machine!` handlers use the typed handles. - **Invoke:** `invoke(|a| Kids::Fetch(..), |i| i.id("f").on_done(..).on_error(..).on_snapshot(..).timeout(delay, ..))` adds a v6 invoke. The source closure builds the whole `T::Children` value, input included, when the state is entered. `InvokeBuilder` has the three transition forms for `on_done`, `on_error` and `on_snapshot`; `timeout` takes a `Duration` or a named delay. Handlers read the child's typed data with `a.actor_output()`, `a.actor_error()` and `a.actor_snapshot()`, which return `None` for other events. - **Spawned children:** actions use `enq.spawn`, `enq.stop` and `enq.send_to`. `on_actor(ActorEvent::Done | Error | Snapshot, "id", ..)` handles one child's events by id, like v6 `on: { "xstate.done.actor.id": .. }`: a transition on the built-in actor event, with a guard on the actor id that runs before the transition's own guard. It also sees an invoked child's events, before the invoke's own transitions, which is v6's order. - The builder numbers the `FnId`s itself and builds the IR tree, so its errors are the IR's `BuildError`s with their state paths. **Macro:** sugar over the builder. It checks references at compile time and generates typed state handles. ```rust #[derive(Context, Clone, Default)] struct Ctx { count: u32 } #[derive(Event)] enum Ev { Inc, Add { n: u32 }, Reset } #[derive(Debug)] enum Fx { Beep(u32) } plusthree::machine! { Counter { context: Ctx, events: Ev, effects: Fx } id: "counter", initial: active, states: { active: { on: { Ev::Inc => |a, _| Transition::stay().patch(|p| p.count(a.context.count + 1)), Ev::Add { n } => |a, enq| { enq.action(Fx::Beep(*n)); Transition::stay().patch(|p| p.count(a.context.count + n)) }, Ev::Reset => idle, }, after: { 5s => idle }, }, idle: { on: { Ev::Inc => active } }, } } // generated: Counter::machine() -> &'static Machine, mod counter::states { ACTIVE, IDLE } // snapshot.matches(counter::states::ACTIVE) ``` - **Event patterns as keys:** a key like `Ev::Add { n }` is a pattern. The macro generates the destructuring, so the handler receives typed fields. - **Named implementations:** handlers can also be paths to functions. - **Error locations:** the macro emits one builder call per state, so validation errors point at the right source span. It also resolves every target, `initial` and history default itself (v6 `resolveTarget` rules), so a bad reference is a compile error on the offending token. - **Targets and handlers:** an identifier or dotted path (`idle`, `a.b`, `.child`, `#id`) is a state; a closure, or a path with `::` (`self::handler`), is a transition function; `{ target, guard, actions, reenter }` is a static transition; `[..]` lists candidates. Inside handlers the macro declares `type Transition = Transition`, so `Transition::stay().patch(|p| ..)` needs no annotation, and `type Patch` as the context's patch type, so an entry, exit or `actions` handler returns `Some(Patch::default().count(n))` without naming the generated `CtxPatch`. - **Wildcards:** a string key in `on` is a wildcard descriptor (`"*" => ..`, `"user.*" => ..`), checked at compile time. Its handlers see `a.event` as an `Envelope`. A binding, `ev @ "user.*" => |a, enq| match ev { .. }`, gives the handler the typed user event `&Ev`; built-in events skip such a transition, so it never has to handle them. - **Delay functions:** `delays: { backoff: |a| .. }` on a state declares named delay functions for it and its descendants; an `after` key that is an identifier (`after: { backoff => idle }`) names one, and the macro checks it is in scope. - **Function initials:** `initial:` takes a closure or a path with `::` as well as a child key; the function returns `Transition::to(handle)`. - **State input:** a transition object takes `input: |a| value` (the event pattern's bindings are in scope), and `initial: { target: child, input: |a| value }` gives the initial target an input. - **Invoke:** `invoke: { src: |a| Kids::Fetch(..), id: "f", registry_key: "k", on_done: .., on_error: .., on_snapshot: .., timeout: { 5s => slow } }`, or a list of such objects. `src` is required. `on_done`, `on_error` and `on_snapshot` take a transition, or arms keyed by patterns over the child's typed output, error or snapshot, tried in order: `on_done: { KidsOutput::Fetch(10) => big, KidsOutput::Fetch(n) => { target: small, actions: |_, enq| .. n .. }, _ => none }`. A refutable arm on a static transition becomes a guard, its bindings are in scope in its handlers, and `_` also takes a completion without output. Targets and named delays are checked at compile time. - **Child events in `on`:** `"xstate.done.actor."`, `"xstate.error.actor."` and `"xstate.snapshot.actor."` keys handle one child's events, spawned or invoked; `out @ "xstate.done.actor.w"` binds the typed data. They map to the builder's `on_actor`. Children are spawned from actions with `enq.spawn`. `machine!` does not generate the `Children` enum; declare it with `#[derive(Children)]` and pass it as `children: Kids`. - **Handles:** `StateRef` constants whose `StateId` is the state's pre-order index, computed by the macro; `build()` asserts them against the definition once. Handles are match patterns: `Snapshot::leaf`, `leaf_in(region)` and `active_child(parent)` return `Option>`, so `match snap.leaf(def) { Some(counter::states::IDLE) => .. }` replaces a chain of `matches` calls; `leaves` lists one active leaf per region. Children of a state live in a module named after it (`player::states::on::modes::audio::MUTED`). ## 6. Kernel ### 6.1 Snapshot ```rust pub struct Snapshot { status: Status, // Active | Done | Error | Stopped config: StateSet, // active states incl. ancestors context: T::Context, history: SmallMap, // only history states that have a value timers: TimerTable, // logical timers (v6 LogicalTimer) children: Children, // invoked + spawned; M4 state_inputs: SmallMap, output: Option, error: Option, counters: Counters, // next timer seq, next actor id } ``` - **Plain data.** The snapshot holds no reference to the machine; you pass `&Machine` into `step`. It is `Send` whenever its contents are, and cloning it never touches the machine. - `StateSet` is a bitset that holds two `u64` words inline (up to 128 states) and moves to a heap `Box<[u64]>` above that. A const-generic `[u64; N]` variant is an optimization to try later. - **Derived on demand, never stored:** `value()` (StateValue), `tags()`, `matches()`, `has_tag()`, `can(event)`. `can` runs selection only and discards the scratch effects. ### 6.2 Entry points ```rust impl Machine { fn initial(&self, input: T::Input, fx: &mut Effects) -> Result, StepError>; fn step(&self, snap: &mut Snapshot, ev: Envelope, fx: &mut Effects) -> Outcome; // Handled | Unhandled | Errored fn transition(&self, snap: &Snapshot, ev: Envelope) -> (Snapshot, Vec>); // pure wrapper: clone + step } ``` - `step` works in place. It is the fast path. - `transition` matches v6's pure API. - Observer and environment: each entry point has a `_with` form (`initial_with`, `step_with`, `fire_with`, `stop_with`) that takes the actor environment (`&()` outside a system) and an `obs: &mut impl Observer`, which gets a callback for each microstep (transitions, exit/entry sets, effects). `step_with` takes an `Envelope`, so a system can deliver child events. The simple forms use the no-op `()` observer, which compiles away. `Option` observes when `Some`, so a host with optional inspection keeps one call. Tests and inspection use this hook. - `Outcome::Unhandled` corresponds to v6's `isUnhandled`: no transition was enabled and no effects were produced, so the snapshot is unchanged. ### 6.3 Microstep, in bitset terms ``` select(ev): for atom in (config & atomic_mask) ascending: for s in atom, parent(atom), ...: # walk ancestors for t in candidates(s, key(ev)): r = eval(t) # static: check matcher; function: call once, effects -> scratch range if enabled(r): push (t, r) unless t already selected; next atom resolve conflicts: exit(t) = config & range(domain(t)); a pair conflicts if exits intersect; the descendant source wins, otherwise the earlier one; losers' scratch effect ranges are dropped (counters rolled back) microstep(T): X = OR exit(t) # exit set for h in history states whose parent ∈ X: history[h] = deep ? config&atomic&range(parent) : active children of parent for s in X descending: exit fn -> patch+effects; Stop effects for s.invokes; config.clear(s); cancel s's timers for t in T (selection order): apply patch (journal inverse); push its effects E = OR enter(t) (static plan, or computed: targets + ancestors up to domain + default_entry/history expansion) for s in E ascending: config.set(s); Spawn effects for invokes; schedule after/timeout timers; entry fn; initial/history-default content; final -> push done.state internal macrostep(ev): journal.begin(); fx.mark() T = select(ev); if T: microstep(T) loop { T = select_eventless() (only if the last microstep changed anything); else pop internal queue; ... } emit deferred Start effects; on error -> journal.rollback(); fx.truncate(mark); rerun with xstate.error.execution or set Error ``` - **Work masks.** `Machine` precomputes `exit_work` (exit function or timers), `entry_work` (entry function, timers, function initial, final) and the parents of history states. Exits and entries outside these masks are a single bit operation on `config`; the per-state loops run only when a mask intersects the exit or entry set. The *plain microstep* is the special case of one static transition with a plan (or a targetless one) touching none of the masks: `config = (config − config∩exit) ∪ enter` around the transition content, exactly what the general microstep does in that case. The entry set is computed before the exits run, so function initials see the pre-microstep snapshot. - The internal queue is a `VecDeque` owned by a reusable scratch area, together with the scratch effects and the selection list. Snapshots don't carry it. - The rollback journal records inverse context patches, the previous `config`/`history`/`timers` words, and counter values. It is cleared when the macrostep succeeds. Its buffers are reused, so the happy path never allocates. ### 6.4 Effects ```rust pub enum Effect { Action(T::Effect), Emit(T::Emitted), Log(LogRecord), Schedule { key: TimerKey, delay: Duration, timer: LogicalTimer }, Cancel(TimerKey), SendTo { to: Address, event: OutboundEvent }, Spawn { slot: ChildSlot, src: T::Children, input: ChildInput }, Start(ChildSlot), Stop(ChildSlot), DeadLetter { reason: DeadLetterReason, event: OutboundEvent }, } ``` - **Log:** `enq.log(value)` and JSON `@xstate.log` produce `Effect::Log(LogRecord)` in order with the other effects. A `LogRecord` (and a `StateInput`) is an `AnyData`: any `Debug + Send + Sync` value behind an `Arc`, read back with `get::()`; JSON logs the `args` array as a `serde_json::Value`. - **Order:** effects come out in v6 order: exit side effects, then transition, then entry, with deferred starts last. - **Timers:** the kernel records the logical timer in the snapshot *and* emits `Schedule`, so a host can either drive time itself or persist the timer and resume later. A fired timer comes back as `SysEvent::Timer(key)`. The kernel then consumes it, raising the delayed event internally or emitting `SendTo`, exactly as v6 handles `xstate.timer`. Simulated time is a host concern (`plusthree-runtime::SimClock`). `plusthree_core::host::Timers` is an optional host-side helper outside the kernel: it keeps the host's timer handle per `TimerKey` and nets one step's `Schedule`/`Cancel` effects into arm and disarm operations (a re-entered state yields `Cancel(k)` then `Schedule(k)`; a state left by `always` in the same macrostep yields `Schedule(k)` then `Cancel(k)`). - **`host::Driven`** removes the loop every host that steps a machine itself repeated around `Timers`. `Driven<'m, T, H, O = ()>` owns `&'m Machine`, the snapshot, the effects buffer, the `Timers` and its op buffer, and an observer `O`. `start(machine, input, scheduler)` runs `initial`; `new(machine, snap)` wraps a snapshot, and `restore(timers, scheduler)` starts a restored snapshot's timers. `step(event, scheduler) -> Outcome`, `fire(token, scheduler) -> Option` and `stop(scheduler) -> Outcome` run a macrostep and apply `Timers`, calling the scheduler for each arm (attaching the handle, and cancelling one `armed` hands back) and each disarm. `stop` is `stop_with` and then cancels every timer still pending, for teardown. - **`host::Scheduler`** is the host's side: `schedule(&mut self, delay, token) -> H` and `cancel(&mut self, H)`. It is a trait on one value, not two closures, because starting and stopping a timer usually need the same `&mut` context (a GUI toolkit's, Parcel's transaction), which two closures cannot both borrow. Calls take `impl Scheduler` by value and `&mut S` is a scheduler, so a host passes `&mut ctx` and keeps it, or a temporary. `schedule_with(schedule, cancel)` builds one from two closures; inference goes through its signature (`H` comes from `schedule`'s return, so `cancel` can call methods on it), which a tuple of closures would not give. The calls are monomorphized, so a scheduler costs what its methods do. `NoTimers` (panics if a timer starts) serves machines without timers and a start before the host's scheduler exists; `Recorder` is the shared test scheduler. - The caller's own effects stay in the buffer, timers removed and in order, readable with `effects()` or drained with `effects_mut()`; the next call clears them as the kernel does, and a stale `fire` (`None`) clears them too, so effects read after each call are never seen twice. Because `schedule` returns the handle synchronously, a timer cancelled before it has a handle can only be one scheduled and cancelled in the same macrostep, which `Timers` nets away; hosts that start timers later than they step use `Timers` directly, whose `armed` hands a stale handle back. Steady state allocates nothing (the S7 allocation gate runs through `Driven`), and the kernel is unchanged, so hosts that don't use it pay nothing. - **`host::Watch: Observer`** is how an observer sees a `Driven`'s macrosteps whole: `before(Macrostep)` (`Event(&T::Event)`, `Timer(&TimerKey)` or `Stop`) and `after(&Snapshot)`, both defaulting to nothing, called only by `Driven`, never by the kernel, so `step_with` users and `Report` keep their exact behaviour. `()` and `Option` implement it. `plusthree-inspect`'s `ActorHandle` implements it by taking the event's name (or what its `show_events` closure makes of it, the per-actor form of `Report::step_showing`, since `Driven::step` takes no per-call closure) before the step and calling `stepped` after it, with `xstate.timer` for a fire and `xstate.stop` for a stop; as the observer it already collects the transitions to highlight. A host keeps `Driven<.., Option>` and one code path whether inspection is on or off. The alternative, a `Report` method that takes a `Driven`, would have kept two call forms per host and put the inspector in the timer path; making the kernel call the hooks would have reported twice for hosts that call `step_with` then `stepped`. ## 7. JSON (`plusthree-json`) - **Import:** `Machine::from_json(json, &Registry)` parses v6 `machine.schema.json` into the builder. It returns a `JsonMachine`, which derefs to `Machine` and keeps the lowering's tables: v6 event objects for built-in events, and the persisted-snapshot format. JSON machines use `T: JsonTypes` (context, events, emitted events, output and errors are `serde_json` values; effects, input and children are the host's). - `Registry` maps names to the implementations a machine refers to: actions, guards, actors, delays. - **Input.** As in v6, the initial macrostep processes `xstate.init` with the machine input: `Envelope::Init` carries it (typed code reads it with `a.event.input()`), and JSON code sees `{"type":"xstate.init","input":..}` through `JsonArgs::event()`. A JSON machine's input type must serialize; `Json` takes `Option`, where `None` is v6's `undefined`. - Built-in serialized actions (`@xstate.raise`, `@xstate.assign`, `@xstate.emit`, `@xstate.log`, `@xstate.cancel`) and guards (`@xstate.not`, `@xstate.stateIn`) are implemented natively. `@xstate.log` is a no-op until the kernel has a log effect. A name the registry lacks is a load error at its JSON path. - Lowering (`MachineJson::lower`) produces the `MachineDef` plus descriptor tables saying what each `FnId`/`DataId` is (guards, action lists, choice functions, literals, registry names), each with its JSON path, and the v6 identity of every transition and timer. - Each JSON transition object stays a static IR transition: `matches` and `guard` become its guard, `context` and `actions` its patch function, so static plans survive. Arrays of guarded transitions (allowed only in JSON) become consecutive transitions for the same trigger, which the kernel tries in order: the first enabled one wins, as in v6, which keeps them as separate definitions. - Departures from `machineFromJSON` (JavaScript artifacts, §2): document order is the written order (D6); an action list's patch is only what it assigns, not v6's whole `{...context, ...patch}`, which lets a later parallel transition undo an earlier one's patch; `matches` compares JSON values, not `Object.is`; `after` keys are milliseconds only when they are plain decimals, not anything `Number()` accepts; an unparsable delay string is an error, not `parseFloat(s) || 0`; targets of transitions with actions and of choice branches are resolved and checked when loading, not when first taken; a root's own `on["xstate.route"]` is kept alongside `route` transitions instead of being replaced. - `@code` and `@expr` are rejected with a clear error (non-goal). - **Export:** `ToJson::to_json()` exports any built machine (builder, `machine!` or JSON) as MachineJSON for Stately Studio, the visualizers and the Stately Inspector. It reads the `MachineDef` and turns the IR's desugared forms back into v6 sugar: `after` timers become `after` keys, timeouts `timeout`/`onTimeout`, invoke completions the invoke's `onDone`/`onError`/`onSnapshot` (dropping the transition v6 adds to cancel an invoke timeout), `xstate.error.*` on a state that declares it `onError`, and a state's own done event `on["xstate.done.state"]` with `matches: {stateId}`, the form v6 JSON writes it in. Targets are written relative to the source (`.child`, a sibling path) or as `#id`. A state gets an explicit `id` only when its id is not the default path, so the exported tree has the ids `MachineDef::id_of` gives (the Inspector relies on that). - **What a handle stands for.** For a JSON machine, the lowering's descriptors: the JSON exported is the JSON loaded, normalized as below. For a built machine, each `FnId` has a `Label`: `Named` for a path handler in `machine!` (`self::is_positive` → `is_positive`; the macro passes the name, since it wraps every handler in a closure) and for a function item given to the builder (its last path segment, from `core::any::type_name`); `Anonymous` for a closure; `Actor { actor, guard }` for an `on_actor` guard, exported as `matches: {actorId}` plus the inner guard. Named delays are named by their declaration. - **Names of closures.** An anonymous implementation is named after where the machine uses it, in JSON path terms rooted at its state's id: `{id}.entry`, `{id}.exit`, `{id}.output`, `{id}.initial.input`, `{id}.choice`, `{id}.invoke[k]` (the source), and for the transition at index `i` of a list, `{id}.on.{event}[i]`, `{id}.always[i]`, `{id}.after.{key}[i]`, `{id}.onError[i]`, `{id}.onTimeout[i]` or `{id}.invoke[k].onDone[i]` (and `onError`, `onSnapshot`, `onTimeout`), with `.guard`, `.actions` or `.input` appended for its parts. The name depends only on the machine's structure, so it is stable across builds and unique in the machine. - **Where MachineJSON has no slot for a function.** Guards and transition content are `{"type": name}`. A transition function is a targetless transition whose one action names it (`{"actions": [{"type": name}]}`, keeping its guard): its targets are decided at run time, and a diagram shows the name on the edge. A choice function, an input or an output function is a code reference, `{"@code": name, "@lang": "plusthree"}`; XState loads it with an evaluator for `plusthree`. A function initial has no MachineJSON form: `initial` names the first child. A built machine exports no root `context`, and typed states have no `meta`. - **Normalization** (what a JSON round trip changes; `plusthree-json/tests/export.rs` checks every loadable fixture and trace machine against it): one-element lists are written without the array; defaults are dropped (`reenter: false`, `type` atomic or compound, `history: "shallow"`, a state `id` or invoke `id` equal to the default); named actions and guards declared in the machine are inlined and their maps dropped, as loading does; custom actions keep only `type` and `params`; `@xstate.stateIn` ids get their `#`; `timeout` values become milliseconds; `delays` keeps only literal delays an `after` key names, in milliseconds; `route` is expanded into the root's `on["xstate.route"]` (D14 keeps both kinds there, so the meaning is the same); `on` keys may move (a state's own `xstate.done.state` entry comes last) while `states` and `after` keep document order; and what loading ignores is dropped: `description`, `schemas`, `key`, `@exprLang`, the `actors` map, state `input`, and `context`, `version` and `internalEvents` below the root. Definitions with `@expr`/`@code` do not load, so they have no export. - **Persistence:** v6's persisted snapshot format (`persistedSnapshot.schema.json`), through `SnapshotFormat` and the kernel's `SnapshotParts` / `Snapshot::from_parts`, which checks that the parts form a reachable state. `config` is written as a StateValue, history as `{id}` arrays, timers with `scheduledAt`, children recursively through the `ChildCodec` hook. Restoring checks the machine `id` and `version`. Typed machines go through serde when their context, events, output and errors are `Serialize + DeserializeOwned`. - D19: the kernel keeps only each timer's delay, so persisting asks the host for each timer's deadline on its clock and writes `scheduledAt` = deadline − delay. Restoring takes `now` on the same clock and returns each timer's remaining delay (`scheduledAt + delay − now`, at least 0) for the host to schedule. A timer without `scheduledAt` (v6 under a simulated clock) restarts its full delay, as in v6. For an actor system the clock is the system's `now`. - **Systems.** `System::persist` persists the root actor: each actor persists itself (`Logic::persist`; a machine through its `Bridge`), and a machine's children are embedded by address through the `ChildCodec` (`SystemChildren` for JSON machines): `address`, `src`, `registryKey`, `syncSnapshot` and the child's own persisted snapshot, or `remote: true` (with v6's `incarnation` token) for a child that lives with another runtime. `syncSnapshot` is written for invoked children, and for spawned ones only when true: v6 omits it when the spawn did not set it, and the kernel does not keep the difference between unset and `false`. `System::restore_from` takes a tree of restored actors built from the same JSON: machines keep their state and timers (D19, in system time), async and callback logic start over with the input their snapshot records (NOTES #15), and remote children become stand-ins whose events go to the host (`Notice::Remote`). Delayed sends persist as `@xstate.sendTo` timers targeting `"self"`, a child id or `{"type":"parent"}`; a send to a registry key is persisted as the child registered under it, and any other target is not addressable from the snapshot, as in v6. Restoring folds child ids shaped like generated ones (`prefix:n`) into `nextActorIds`, as v6 does. Actor references in a JSON context (`{"@actor": address}`) are data and round-trip as written. ## 8. Actors and system **M4 scope:** children that are machines (invoke and spawn, with `onDone`, `onError`, `onSnapshot` and invoke `timeout`); async children (a `Future` producing output or an error); callback children; a `registryKey` registry and `send_to` by address; dead letters for missing targets. **Pure reducer:** `plusthree-system` ports v6's experimental `systemTransition` / `advanceSystemTime`. A `SystemSnapshot { now, actors, registry, messages, timers, counters }` is a deterministic reducer over the whole tree of actors. It is the substrate for tests, replay and persistence. **Live runtime:** `plusthree-runtime` provides a mailbox per actor, runs the effects after each macrostep, sends one snapshot notification per macrostep, and plugs in a clock (tokio, std, embassy, simulated). **Inspection in the Stately Inspector:** `plusthree-inspect` (std) turns the system's `Inspection` notices into the messages of `@statelyai/sdk`'s inspection protocol 2, the protocol of Stately's current, v6-aware inspector (`sky.stately.ai/inspect`). It is a local relay: a WebSocket server the hosted viewer connects to, so it needs no TLS, account or cloud relay. `@xstate.actor` becomes `actorRegistered` (address as `sessionId`, the machine's MachineJSON wrapped as `@statelyai.inspection.machine`, profile `xstate-v6-alpha`); `@xstate.transition` becomes `actorEvent` plus `actorSnapshot` with the transitions named by `MachineDef::id_of`, and `actorStopped` once the status is final. A host that steps machines itself, with no system, registers each with `Inspector::actor` and reports every macrostep to the returned `ActorHandle`, which is also an `Observer`: stepped through `step_with`/`fire_with` it records the transitions taken and the actions (built-in effects by the action types a system reports, the machine's own as `effect`), so the existing hook supplies them and plain `step` pays nothing. The `Report` trait's `step`/`fire`, on a handle or an `Option` of one, do both in one call. What could leak is opt-in: the viewer gets event names, snapshots with only the context fields marked `#[context(show)]` (`Context::show_fields`, §5.1) and unnamed effects unless the host names effects by variant (`name_effects`, which takes the machine so `T::Effect: VariantName` is checked at compile time) or supplies JSON per call (`step_showing`) or per actor (`show_context`, `show_effects`, stored type-erased so the handle stays untyped; the handle records its machine's effect type at registration and `show_effects` panics on a closure for another type instead of showing every effect as `effect`). `Inspector::group` registers an actor without a machine (no `logicType`, snapshot `{status: active}`, which the viewer shows as a running actor; without a snapshot it shows "Awaiting snapshot") to parent machines with no common root. Actors nest by session id (`parent/child`, made unique when taken), and a handle's registration number keeps a dropped handle from stopping an actor registered again under its id. Registering an id again under the same parent replaces that actor, reusing its session id, only once it has stopped: replacing a running actor would silently cut its live handle off, and a host that registers machines before it knows their parent, such as several sessions at the top level, would lose all but the last. `ActorHandle::move_to` re-parents an actor in place: it keeps its session id and re-sends `actorRegistered` with `replaces: true` and the new `parentSessionId`, then its last `actorSnapshot` (the viewer rebuilds a re-registered actor from its snapshot alone, losing the last event and actions), which the hosted viewer's reducer takes as the same actor under a new parent (its tree is built from `parentSessionId`, so order does not matter); late viewers get the new parent in `system.init`. A new session id with the old one stopped would leave a stopped copy in the viewer, which has no message to remove an actor. The legacy `@statelyai/inspect` package speaks XState v5's `@xstate.event`/`@xstate.snapshot`, drops v6's `@xstate.transition`, and its viewer draws diagrams only for signed-in users, so it is not targeted. **Children of different types.** `T::Children` is a user-declared `#[derive(Children)]` enum of the actor kinds a machine can spawn. `machine!` can generate it. The derive also generates output and error enums, so `onDone` handlers receive the child's typed output rather than a `dyn Any`. ## 9. Conformance and testing 1. **Differential tests against XState (primary oracle).** A Node harness runs XState beta.3 on MachineJSON plus a JS registry that mirrors the Rust one. It records traces: for each event, the StateValue, context, effect list, and microsteps (from `@xstate.transition` inspection). Rust replays the traces through `from_json` and requires an exact match, except for steps covered by a deviation (§2). Recorded traces are committed as fixtures, so CI does not need Node. 2. **Random differential fuzzing.** A generator builds random charts (depth up to 5, parallel regions, shallow and deep history, `always`, `after`, transitions between regions, `reenter`, final states inside parallel states) and random event and time sequences. Both engines run the same input and any divergence is minimized. This targets domain narrowing, conflict resolution, history-target domains, and done events across parallel states. 3. **Ported v6 semantic tests:** `microstep.v6`, `parallelConformance`, `history`, `transient`, `after`, `final`, `order`, `deterministic`, plus the `interpreterLaws` reference model as a proptest, hand-translated into Rust tests against the typed API. 4. **Persistence and inspection conformance:** golden files from `persistenceConformance.v6`, `serialization.conformance.v6`, `inspection.conformance.v6`. 5. **Allow-list.** Each entry needs a deviation ID from `DEVIATIONS.md` (or `msg` for error wording) and names, as masks, what the deviation changes in its steps: a field path, an array whose order differs, or the extra items one side has, matched by a pattern (`plusthree_conformance::Mask`). Everything else in those steps is compared. An entry whose step matches without its masks, or that has a mask the step does not need, fails CI. Every deviation also has a Rust test asserting the correct behaviour. XState v6 is still in beta. Re-pinning means regenerating traces, reviewing the diff, and updating the allow-list. ## 10. Performance The budgets are the measured numbers after the hot-path work (commit `3a745c0`), and they are a floor that must not regress. Instruction counts are the primary metric because they do not depend on the host; nanoseconds are scaled to the original baseline host through the xstate-statemachine-rs engine measured in the same run. `crates/plusthree-bench/BASELINES.md` has the method, every library's numbers and the caveats. | Scenario | Budget (instr/event) | plusthree (scaled ns) | xstate-statemachine-rs engine | XState v6 `transition()` | | --- | --- | --- | --- | --- | | Flat toggle (S1) | 628 | 33 ns | 785 instr, 41.7 ns | 2.3 µs | | Guard + context patch (S2) | 796 | 49 ns | 1,028 instr, 60.1 ns | 5.2 µs | | 3-level nested, cross-tree (S3) | 628 | 38 ns | 867 instr, 49.8 ns | 9.9 µs | | 2 parallel regions (S4) | 1,137 | 55 ns | 3,498 instr, 203 ns | 11.1 µs | | `after` timer fire, incl. schedule/cancel effects (S7) | 1,626 | 102 ns | 1,460 instr, 94.7 ns | 37 µs | | Build a 50-state machine from JSON (S5) | 3.34 M per build | 291 µs | 128 µs | 354 µs | | Allocations per steady-state event | 0 | 0 | 0 | — | - A counting-allocator test enforces 0 allocations per steady-state event for S1–S4 and S7, and for S7 run through `host::Driven` (`s7_plusthree_driven` in the instruction counts, about 2,020 instr/event: the S7 fire plus netting its timer effects and the host's callbacks). - `just bench-instr` runs the gungraun instruction counts and fails on a regression above 5% against the saved baseline. Run it before pushing changes to the kernel hot path or the IR. - The criterion suite also runs equivalent statig and smlang machines. Compiled dispatch costs them about 5 instructions per event, which is the floor for what codegen could reach. - The original targets (S1 ≤ 15 ns, S2 ≤ 25 ns, S3 ≤ 40 ns, S4 ≤ 60 ns, S7 ≤ 80 ns, S5 ≤ 50 µs) were set before any measurement. S3 and S4 met them. The rest would need per-machine specialization (S1, S2, S7) or a single-pass JSON loader (S5); both are deferred below. **After 0.1 (deferred, only on a real bottleneck):** - **Codegen:** an opt-in `machine!` backend that generates per-machine dispatch. It is a second execution path, so it ships only with an equivalence test that runs generated code against the interpreter on random machines and the conformance corpus where expressible. The interpreter stays the reference. - **Single-pass JSON loader:** MachineJSON values straight to the IR builder, interned names, JSON paths built only on error. Loading happens once per machine, so this waits until a user loads machines on a hot path. - **Const-generic inline `StateSet`:** rejected for now as too invasive while several crates changed at once; revisit if profiles point at set operations again. ## 11. SCXML: not planned Decided after 0.1.1: plusthree is complete as an XState v6 port, and an SCXML profile is not planned. XState departs from SCXML on purpose (re-entry by default, prefix event matching, partial transitions on error, inline scripts, narrow invoke), and plusthree follows XState. If SCXML documents ever need to run, the profile would differ from v6 in the places below, without forking the kernel. The kernel would branch on `Semantics` in four places: the domain (v6 narrowing vs SCXML LCCA with internal/external transitions); the default for `reenter`; event matching (exact plus specificity-ranked wildcards vs SCXML token prefixes in document order); errors (abort and replay vs `error.execution` on the internal queue, aborting only the current block). Delayed events on the external queue, invoke finalize and autoforward come with the profile. ## 12. Milestones - **M0, IR:** workspace, `plusthree-ir` builder, validation, flattening, desugaring, interning; `StateSet`; property tests for flattening invariants. - **M1, Kernel:** atomic, compound, parallel, final, choice; object and function transitions; entry/exit; patches; raise; `always`; done.state; history; selection and conflicts; `can`; StateValue; Observer hook. Differential harness up and running. - **M2, Time and errors:** logical timers (`after`, `timeout`, delayed raise, cancel), the error model with journal rollback, `max_microsteps`, benchmarks plus the allocation gate. - **M3, Surfaces:** `#[derive(Context, Event, Children)]`, `machine!`, MachineJSON import/export, persisted snapshots. - **M4, Actors:** children, the system reducer, the tokio runtime, inspection, public `microsteps()` / `next_transitions()`. - **M5:** embassy adapter. (An SCXML profile was dropped; see §11.) - **After 0.1:** codegen and the single-pass JSON loader, only on a real bottleneck (§10). ## 13. Decisions 1. **Event names.** By default the name is the variant name verbatim (`Inc` → `"Inc"`). Serde-style `#[event(rename = "user.login")]` and `#[event(rename_all = "SCREAMING_SNAKE_CASE")]` override it. A later `#[event(flatten)]` on a variant wrapping a nested enum may build dotted names: `User(UserEv::Login)` → `"user.login"`. 2. **Context updates.** Patches only in v1, with generated setters: `.patch(|p| p.count(n))`. Revisit an `update(|ctx| …)` form, backed by a per-macrostep arena, after writing real examples in M3. 3. **Child typing.** Users declare an explicit `#[derive(Children)]` enum, which generates output and error enums. `machine!` can generate it from `invoke`/`spawn` declarations. 4. **State ids.** `StateId(u32)`. 5. **License.** MIT. 6. **Microstep-level API.** M1 adds the compile-away `Observer` hook; public `microsteps()`, `next_transitions()` and inspection APIs come in M4.