ADR-0325:
Explicit State Machines (fsm,
derive StateMachine, and fsm_test)
- Status: Accepted
- Date: 2026-11-28
- Related: ADR-0290 (Bundled First-Party Plugin Catalog),
ADR-0291 (Freeze Rust CLI Surface, Grow in Tenon), ADR-0293
(
app_actions_gen), ADR-0299 (derive StateView), ADR-0309 (app_testFuzz Explorer), ADR-0318 (Implicit Cache-BackedderiveMaterialization)
Context
Interactive workflows, TUI screens, agent loops, and background
job runners in Tenon rely on finite state machines (FSMs).
Hand-written enum + match tables suffer
from recurring correctness bugs:
- Illegal target transitions: a handler for
(Running, Retry)can accidentally return any state variant (such asQueuedorCancelled) and still typecheck. - Forgotten transition handlers or silent wildcard
swallowing: adding a new state or event behind a
_catch-all silently drops transitions instead of failing at compile time. - Graph-level structural defects: unreachable
states, accidental non-terminal dead-end sinks, transitions
exiting
@terminalstates, duplicate(state, event)edges, and inconsistent event payload types across states go undetected until runtime. - Combinatorial runtime bugs: subtle invariant violations, non-deterministic handlers, or corrupted state on rejected events are rarely caught by hand-written unit tests.
Adding core-language typestate, linear/affine ownership, or
dedicated machine/state keywords to
Tenon would:
- bloat
docs/spec/LANGUAGE.mdand degrade LLM zero-shot transfer, - add complexity to
tenon-frontendandtenon-compileragainst ADR-0291, and - conflict with Tenon's immutable value semantics that power effortless state snapshots, undo/rollback, dry-run previews, and deterministic trace replay.
Tenon already has closed nominal enums with
exhaustive match, immutable structs,
static-dispatch nominal interfaces
(<H: I>), repeatable struct field attributes,
GEN_ABI 2 pure .tn generators, and
ADR-0318 implicit derive materialization. Together these deliver
~90% of compiler-enforced explicit state machine safety with
zero changes to LANGUAGE.md, ~1
compact syntax, or Tenon's type system.
Decision
We introduce three pure, zero-capability
(capabilities = [], edition = "2026")
first-party plugins:
1.
plugins/fsm/ — Pure Core Runtime, Parser, Validator
& Mermaid Exporter
- Runtime & Graph Types
(
fsm.lib):InvalidTransition { from_state: str, event: str }andinvalid_transition_messageStateMeta { name: str, variant: str, is_initial: bool, is_terminal: bool, allow_sink: bool, doc: str }EdgeMeta { from_state: str, event: str, event_payload: str, targets: vec<str> }FsmGraph { name: str, states: vec<StateMeta>, edges: vec<EdgeMeta> }GraphDiagnostic { code: str, message: str }- Query helpers:
initial_state,find_state,is_terminal,allowed_events,can_transition, andedge_keys(locked to"from_state::event->target").
- Transition DSL Parser
(
fsm.parse):- Parses
@on("<spec>")strings of the form<event>[(<PayloadType>)] -> <target1>[, <target2>...]intoParsedEdge, validating ASCII identifiers, optional non-empty type names, and target uniqueness.
- Parses
- Static Graph Validator
(
fsm.validate):validate_graph(g: FsmGraph) -> result<unit, vec<GraphDiagnostic>>enforces deterministic fail-closed diagnosticsFSM001–FSM010:FSM001: empty state list or duplicate state namesFSM002: missing@initialstate (count == 0)FSM003: multiple@initialstates (count > 1)FSM004: unknownfrom_stateor unknowntargetstate in an edgeFSM005: outgoing edge declared on a@terminalstateFSM006: duplicate(from_state, event)edgeFSM007: duplicate target inside a single edgeFSM008: unreachable state (BFS from@initial)FSM009: non-terminal dead-end state (0 outgoing edges and!allow_sink)FSM010: conflictingevent_payloadfor the sameeventname across states
- Mermaid Exporter (
fsm.mermaid):to_mermaid(g: FsmGraph) -> stremits deterministicstateDiagram-v2diagrams with[*] --> <initial>,<from> --> <target> : <event>[(<payload>)], and<terminal> --> [*].
2.
plugins/fsm_gen/ — GEN_ABI 2
derive StateMachine
- Targets a catalog
structwhose fields declare states (unitfor payload-less states or a payload type) using existing repeatable field attributes:@initial(required on exactly 1 state)@terminal(forbids outgoing@on)@allow_sink(explicit opt-in for non-terminal states with 0 outgoing edges)@on("<event>[(<PayloadType>)] -> <t1>[, <t2>...]")(repeatable)@doc("...")(optional state description)
- Emits closed
<Name>Stateand<Name>Eventenums, narrowed target return types (direct target payload for single-target edges;pub enum <Name><State>On<Event> { To<T1>(...), To<T2>, ... }for branching edges so illegal target states cannot typecheck), a required<Name>Handlersinterface (missing handlers fail to compile), a zero-wildcard<name>_step<H: <Name>Handlers>dispatcher using qualified interface calls returningresult<<Name>State, InvalidTransition>, and introspection helpers (<name>_initial,<name>_state_name,<name>_event_name,<name>_is_terminal,<name>_allowed_events,<name>_can_handle,<name>_graph,<name>_mermaid). - Fails closed with
E0966on anyFSM001–FSM010violation, non-struct target, invalid@on(...)syntax,@initial+@terminalon multi-state machines, or generated identifier collisions.
3.
plugins/fsm_test/ — Pure Deterministic Explorer &
Shrinker
- Works on both
derive StateMachinemachines and hand-writtenenum+matchFSMs using an overflow-free Park-Miller PRNG and delta-debugging trace shrinker (capabilities = [], C/interpparity). - Enforces 5 universal FSM oracles
(
InitInvariantViolated,NonDeterministic,TerminalEscaped,StateCorruptedOnReject,InvariantViolated), tracks visited states and"from_state::event->target"edges againstFsmGraph, and formats minimized counterexamples as copy-pasteable.tnregression tests.
Consequences
- Positive: Compile-time illegal-transition
prevention, exhaustive handler coverage, static graph validation,
Mermaid export,
app_actionsaffordance gating (<name>_allowed_events), and automated property exploration with shrinking — all with 0 bytes added todocs/spec/LANGUAGE.md, zero new Rust CLI commands, and seamless ADR-0318 implicit derive materialization. - Trade-off: Custom event payload structs
referenced in
@on("ev(MyPayload) -> ...")must be declared or imported in the deriving module's scope. Hierarchical/parallel Harel statecharts are intentionally out of scope for v1 (compose multiple small FSMs in a parentstructinstead). - Edition Wiring:
fsm,fsm_gen, andfsm_testship offline inedition = "2026"viacrates/tenon-assets/build.rsandcrates/tenon-compiler/src/editions.rs.