Finite state machines in Jennifer

Jennifer

From flags and nested ifs to explicit states and transitions: by hand with an enum and match, then with the @deckyard/fsm deck.

November 2026, by @mplx.
Based on Jennifer 0.27.0

Powered by Jennifer's Cantrip - Markdown into slide decks, https://github.com/jennifer-language/cantrip
1 / 22

The plan

StepTool
Why flags go wronga struct of bools
A machine by handdef enum, match
The same machine with the deckfsm.machine, fsm.fire
An order life cycleguards, hooks, fsm.events, fsm.can
Find flaws in the definitionfsm.check
The machine as data and as a picturefsm.load, fsm.mermaid, fsm.dot
Test it, and avoid the trapsjennifer test, testing.assertThrows
2 / 22

Flags and nested ifs

def struct Conn { connected as bool, loggedIn as bool, closing as bool };

func send(c as Conn, line as string) {
    if (not $c.connected) { return "error: not connected"; }
    if ($c.closing) { return "error: closing"; }
    if (not $c.loggedIn and $line != "LOGIN") { return "error: log in first"; }
    return "sent " + $line;
}
def c as Conn init Conn{connected: false, loggedIn: true, closing: true};

Prints error: not connected: eight combinations, four real states.

3 / 22

A state machine, in words

TermTurnstile
States: a finite set, one currentLocked, Unlocked
Initial stateLocked
Events: what happens to itCoin, Push
Transitions: (state, event) -> state(Locked, Coin) -> Unlocked
Final states: nothing followsnone: it runs forever
CoinPush
LockedUnlockedLocked
UnlockedUnlockedLocked
4 / 22

By hand: two enums and a match

def enum State { Locked, Unlocked };
def enum Event { Coin, Push };
func next(state as State, event as Event) {
    match ($state) {
        when Locked {
            match ($event) {
                when Coin { return State.Unlocked; }
                when Push { return State.Locked; }
            }
        }
        when Unlocked { ... the same for Unlocked ... }
    }
}
5 / 22

What the match does not tell you

QuestionBy hand@deckyard/fsm
Which events are allowed now?write a second matchfsm.events
Who may take a transition?ifs in each armguards
Run code on entering a statecalls in each armonEnter, onLeave
Can every state be reached?read the codefsm.check
A state stored as textparse it yourselffsm.isState
Change it without a releasenofsm.load from TOML, YAML, JSON
A diagram for the docsdraw it by handfsm.mermaid, fsm.dot
6 / 22

@deckyard/fsm: a machine is a value

$ jvc add @deckyard/fsm && jvc install
import "@deckyard/fsm/" as fsm;
7 / 22

The turnstile with the deck

def m as fsm.Machine init fsm.machine("turnstile", "locked");
$m = fsm.addStates($m, ["unlocked"]);
$m = fsm.addTransition($m, "coin", ["locked", "unlocked"], "unlocked");
$m = fsm.addTransition($m, "push", ["locked", "unlocked"], "locked");

def state as string init $m.initial;
for (def e in ["coin", "push", "push", "coin"]) {
    $state = fsm.fire($m, $state, $e, {}).target;
    io.printf("%s -> %s\n", $e, $state);
}
io.printf("from %s: %v\n", $state, fsm.events($m, $state, {}));
coin -> unlocked ... coin -> unlocked
from unlocked: ["coin", "push"]
8 / 22

Refused when built, refused when fired

fsm.fire($m, "locked", "kick", {});                          # no such transition
fsm.fire($m, "jammed", "push", {});                          # not a state
$m = fsm.addTransition($m, "kick", ["lockd"], "unlocked");   # typo
$m = fsm.addTransition($m, "coin", ["locked"], "locked");    # shadowed
fsm: turnstile: no "kick" transition from locked
fsm: turnstile: not a state: "jammed"
fsm: turnstile: not a state: "lockd"
fsm: turnstile: coin from locked already has an unguarded transition;
  this one could never be taken

Every failure is Error{kind: "fsm"}: match the kind, never the message.

9 / 22

A real one: the order life cycle

def m as fsm.Machine init fsm.machine("order", "draft");
$m = fsm.addStates($m,
    ["review", "approved", "rejected", "shipped", "cancelled"]);
$m = fsm.addFinals($m, ["rejected", "shipped", "cancelled"]);
$m = fsm.addTransition($m, "submit", ["draft"], "review");
$m = fsm.addTransition($m, "edit", ["review"], "draft");
$m = fsm.addGuarded($m, "approve", ["review"], "approved", isManager);
$m = fsm.addTransition($m, "reject", ["review"], "rejected");
$m = fsm.addGuarded($m, "ship", ["approved"], "shipped", isPaid);
$m = fsm.addTransition($m, "cancel",
    ["draft", "review", "approved"], "cancelled");
$m = fsm.onEnter($m, "approved", stamp);
10 / 22

Guards: may this transition happen?

export func isManager(s as fsm.Step) {
    return maps.has($s.ctx, "role") and $s.ctx["role"] == "manager";
}
11 / 22

Hooks: run code on entering or leaving

export func stamp(s as fsm.Step) {
    def c as map of string to string init $s.ctx;
    $c["approvedBy"] = $c["user"];
    return $c;
}
fire does, in order
1. choose the transitionfirst candidate whose guard passes
2. leave hook of the sourcegets the caller's context
3. enter hook of the targetgets what the leave hook returned
4. return the Stepctx as the hooks left it
12 / 22

Walking an order

$state = fsm.fire($m, $state, "submit", $ctx).target;
io.printf("%s, can: %v\n", $state, fsm.events($m, $state, $ctx));
...                                    # approve as a clerk: refused
$ctx["role"] = "manager";
def s as fsm.Step init fsm.fire($m, $state, "approve", $ctx);
$state = $s.target;
io.printf("%s by %s\n", $state, $s.ctx["approvedBy"]);
io.printf("ship? %v\n", fsm.can($m, $state, "ship", $ctx));
review, can: ["edit", "reject", "cancel"]
fsm: order: "approve" from review refused by its guard
approved by ada
ship? false
13 / 22

check: flaws in the definition

$m = fsm.addStates($m, ["review", "approved", "rejected", "archived"]);
$m = fsm.addFinals($m, ["rejected"]);
...
$m = fsm.addTransition($m, "reopen", ["rejected"], "review");
for (def p in fsm.check($m)) { io.printf("%s: %s\n", $p.kind, $p.message); }
dead-end: order: approved is not final and has no transition out
final-exit: order: rejected is final but has transitions out (reopen)
unreachable: order: archived cannot be reached from draft
dead-end: order: archived is not final and has no transition out
14 / 22

The machine as data: fsm.load

initial = "draft"
states = ["draft", "review", "approved", "rejected", "shipped", "cancelled"]
[[transitions]]
event = "approve"
from = "review"
to = "approved"
guard = "isManager"
def m as fsm.Machine init
    fsm.load(fs.readString("order.toml"), "toml", orders.functions());
same as orders.build(): true
fsm: load: /transitions/0: unknown key "gaurd"
15 / 22

Drawing it

io.printf("%s", fsm.mermaid($m));      # fsm.dot($m) for Graphviz
stateDiagram-v2
    state "draft" as s0
    ...
    [*] --> s0
    s0 --> s1 : submit
    s1 --> s2 : approve [isManager]
    s2 --> s4 : ship [isPaid]
    s3 --> [*]
16 / 22

Stored states

if (not fsm.isState($m, $o.state)) {
    io.printf("%s: unknown state %s, migrate it\n", $o.id, $o.state);
} elseif (fsm.isFinal($m, $o.state)) {
    io.printf("%s: %s, closed\n", $o.id, $o.state);
} else {
    io.printf("%s: next %v\n", $o.id, fsm.events($m, $o.state, {}));
}
A1: next ["edit", "reject", "cancel"]
A2: shipped, closed
A3: unknown state pending, migrate it
17 / 22

Testing a machine: paths

def struct Path { events as list of string, want as string };
...
    def paths as list of Path init [
        Path{events: ["submit", "approve", "ship"], want: "shipped"},
        Path{events: ["submit", "edit", "submit", "reject"], want: "rejected"},
        Path{events: ["submit", "approve", "cancel"], want: "cancelled"}
    ];
    for (def p in $paths) {
        testing.assertEqual(walk($m, $p.events, $ctx), $p.want);
    }

walk fires each event in turn from $m.initial and returns the last state.

18 / 22

Testing a machine: definition and refusals

func testTheDefinitionIsClean() {
    testing.assertEqual(len(fsm.check(orders.build())), 0);
}
func clerkApproves() {
    walk(orders.build(), ["submit", "approve"], {"user": "bo", "role": "clerk"});
}
func testRefusedEventsThrow() {
    testing.assertThrows("clerkApproves", "fsm");
    ...
$ jennifer test lifecycle_test.j
4 passed, 0 failed, 4 total
19 / 22

Pitfalls

MistakeWhat happensInstead
fsm.fire(...) without using .targetthe state never moves$state = fsm.fire(...).target
fsm.addStates($m, ...) alonethe copy is dropped$m = fsm.addStates($m, ...)
a guard that writes or logsruns in can, events, fireguards only read the Step
a hook reads a missing context keya runtime error, passed throughmaps.has first
a passing check taken as proofguards are ignoredtest paths with contexts
a state read back from storagefire throws "not a state"fsm.isState, then migrate
a guard returns a stringan fsm error naming the guardreturn bool
20 / 22

By hand or with the deck?

By hand: enum + match@deckyard/fsm
Missing (state, event) pairload-time errorfire throws fsm
A typo in a stateload-time errorerror when built
Cost per eventone matchabout 0.2 ms for 50 transitions
Guards, hooks, eventswrite them yourselfbuilt in
Check, load, diagramnobuilt in
Fitslexers, protocol parsers, gamesorders, tickets, workflows
21 / 22

Read more

Based on Jennifer 0.27.0, November 2026.

22 / 22