Why Use State Machines?

Most of this is about State Machines in general. Some of this is specific to the StateAtlas Framework's implementation of the state machine engine and its multi-layer architecture.

Thinking About the Application Using State Machines

States: What the Application is Doing Now

Events: Cause a Transition to the Next State

Guards: Make Sure the Transition is Allowed

Actions: Do the Work

Actions are small functions in regular imperative code. Their code is not in the map. The map names them and decides when they execute.

In Code You See Instructions. In a Map You See Behavior.

What you see IS the application. Imperative code is temporal—it exists as lines of execution moving forward through time. A declarative map is spatial. It maps your entire application out like a physical territory. Because it is static data, you can look at the whole system at once. A human can trace paths with a finger and visually verify: "Yes, there is a track connecting the loading screen to the error screen, so that flow is covered."

What you see DOES the application. In an imperative application, there is always a gap between what the developer thinks the code does and what the computer actually executes. Hidden edge cases live in that gap. With a state map, the map is what the engine actually executes, so for the flow of the application there is no gap. If a state transition line isn't explicitly defined in the map, the engine cannot execute it. The gap that remains is inside each small action, where it is easy to find. You can confidently reason about the application visually because the visualization and the runtime logic are the exact same thing.

This is not true of application diagrams and design documents, which can become stale and no longer match reality (if they ever did) as code changes.

The map can be viewed and reasoned about visually. In practice I rarely need to: the AI writes and reads the maps, and the framework checks them. What matters is that the behavior is written down in one place where it can be checked mechanically.

Making the Application

Making the map

These applications are entirely made by the AI. I don't actually do much thinking about maps. So you may ask at this point, "Why bother with state machines if the AI is doing the work?"

Because the AI is doing the work. When I wrote code myself, I was the check on it. I can't read everything an AI writes, so something else has to be the check. A state map is a kind of program a machine can verify: the linter will not export a map with a missing action, two transitions that conflict, or a state that cannot be reached (among many other checks). The AI and I talk about what the application should do, and the map is where those decisions are written down in a form small enough for either of us, or the next AI, to take in, whole. The AI still writes ordinary code, but only inside small actions, and the map decides when each one runs.

This environment is a place where an AI consistently makes good code. The map makes it easy. The Linter enforces it. The things that simplify reasoning for a human also simplify reasoning (so called) for an AI.

There are other very good reasons.

Managing complexity

In imperative code, complexity multiplies silently. Every new true/false flag doubles the number of situations the program can be in: three flags make eight combinations, ten flags make more than a thousand, and nobody has thought about most of them. Worse, nothing tells you which of them are supposed to be possible.

A map does not abolish that multiplication, but it reduces it and moves what remains into the open. Conditions modeled as states are mutually exclusive by construction — ten states, not a thousand combinations — and what is left over lives in declared variables with declared lifetimes.

Because behavior is declared rather than implied, a tool can compute how branching a map has become, flag a state that has grown too many exits, and prove that an event has nowhere legal to go. A combination that is not on the map does not exist — the engine executes only declared transitions, and that is checkable before the program runs rather than discovered when it misbehaves.

Two things keep a large map readable.

States can contain other states. A transition declared on an outer state applies to every state inside it, so a rule such as "Cancel returns to the start" is written once instead of once per step. Nesting also scopes memory: a variable owned by a state is cleared automatically when control leaves it. This is what hierarchical means in Hierarchical State Machine.

An application can contain more than one map. Each covers one concern — in this framework the logger, the map viewer and the application's own workflows are separate maps that exchange events — which keeps each map scoped to one concern rather than to the whole application.

One map, several user interfaces

A single map serves three surfaces. Moving an application from desktop to phone or web leaves the state map untouched — the states, transitions, guards and actions are the same. What changes is the widget layer for the new host, and the declarations that describe the new surface: a desktop app declares panes and widgets, a web app declares pages, fragments and routes. The behavior is not restated. Neither, for the most part, is the bridge: it is framework-provided, and an application declares its surface rather than writing one.

The bridge translates in both directions. Inbound, a widget signal becomes an event, carrying a payload drawn from a widget property, from the signal's own emitted value, or from a constant stated in the map. Outbound, it carries four distinct things:

The per-profile shape of all this is generated when the contract is exported, which is why one map can drive a Qt desktop surface, a QML phone surface and an HTMX web app at once — three projections of the same behavior, with the map authored once.

The same method extends further than the same map does. A device too small for Python runs a separate engine written in C that implements the same semantics, fed by a contract exported from the same database by the same pipeline. The map is a different map — a watch has no forms or menus, and its budgets are measured in hundreds of bytes — but the schema, the authorities and the export machinery are the ones already in use. What ports is the approach, not the application.

The interface mirrors the machine's capabilities rather than re-deciding them. Each button or menu item is bound to an event; when that event is legal from the current state the control is enabled, and when it is not, it is disabled. No custom code makes that decision. Forms and dialogs are bound to states, with the mode declared alongside — the same form can serve Add from one state and Edit from another — and whether it clears or retains its contents on close is likewise declared rather than coded.

From the developer's side this is a few rows in a database instead of a tangle of enable/disable logic, visibility flags and dialog bookkeeping. That removes a large class of code from the application, and a larger class of bugs with it. It is a significant architectural advantage over the imperative model.

Because the bindings are declared, the seam can be checked mechanically. The map names a widget, a signal, a setter — and those names all live in one place, so a tool can confirm that everything the map depends on actually exists in the code for each surface, before the application runs. The framework does this today: declared widgets are matched against the widgets the code creates, and a signal's payload type is checked against the slot that receives it, so a mismatch becomes a build-time fault instead of a crash the first time someone opens that screen. Testing the map benefits every surface, and verifying that each surface honors the map is a mechanical check rather than a manual review. In imperative code the equivalent mistake is undiscoverable without executing the path that triggers it.

Explicit state instead of implicit state

In imperative code it is easy to reach a state nobody designed. Flags disagree, a dialog is open when the data behind it has gone, a retry path was never written. This is implicit state — a situation the program can occupy that no one described — and in my experience it is the single largest source of defects.

An explicit map trades that for control, and the control is checkable. Because the behavior is declared, things can be established before the program runs:

Seven layers, one direction

The map says what the application does. The code that carries it out is divided into a fixed set of layers, and that division is as declared as the map is.

There are seven: passive widgets that display state and emit signals; the transport that carries those signals to the engine, with one adapter per platform; the state machine engine itself; the actions and guards the engine calls; the data access layer; the infrastructure boundaries for files, logging, network and platform APIs; and the frozen typed shapes that cross between them. What I'm Building lists them by name.

Dependencies flow one way. An upper layer may call a lower one; a lower layer may never call upward. A widget cannot reach the database. An action cannot touch a widget. The engine knows nothing about Qt. A linter enforces this, so a violation fails the build instead of becoming a habit.

That rule is what the rest of this document leans on whenever it says a check is local. A boundary is a named place, so a check can live there: the typed shapes crossing it can be verified, the methods on the far side can be required to exist, and a defect can be attributed to one join rather than to the program as a whole. Without the layer rule there is no boundary for "verify at the boundary" to point at.

Code Review

A lot of headlines are out there these days saying things like "AI made writing code cheap, but verifying it is correct/safe is the new bottleneck". AIs make these state maps and applications extremely well.

In my experience using this framework with AIs to make applications, the verification process has changed.

This framework moves a huge amount of verification out of ad hoc code review and into architecture.

The AI is not being asked to invent arbitrary program flow in raw Python. It is being asked to fill in constrained slots:

That makes AI-generated work much easier to trust because the system constrains the shape of possible mistakes.

The verification burden does not disappear. It changes form:

That is a much better environment for AI because AI is weakest when it must maintain hidden global consistency across scattered imperative code. This framework gives it rails: the linter, database schema, state machine topology, typed context, and generated contracts all narrow the blast radius.

This system is designed so verification is structural, automatic, and local: structural because it checks code shape and boundaries; automatic because many checks run mechanically from the declared structure; and local because each behavior is checked at the map row, contract, type, or layer boundary that owns it, instead of by tracing the whole program.

Testing

Because the complete behavior of the application is declared as data rather than implied by code, verification is systematic instead of anecdotal. The payoff is not the one a complete map suggests. It is not that you can write a test that walks every path; it is that most of what such a test would tell you is settled before the application starts, and the effort that remains can be aimed at one place. Defects cluster where layers meet, and in a declared system the joins are named — so they can be aimed at deliberately instead of discovered.

The map is checked as a whole, before anything runs. Every event a transition expects is raised by something. Every event something raises is handled somewhere. Every state is reachable. No two transitions out of a state conflict. No transition names an action that does not exist. These hold across the entire topology rather than over a sampled set of user journeys, and they fail the build rather than the user. In imperative code the equivalent question — can this situation still arise? — has no mechanical answer at all. You read the program and form an opinion.

The seam between the map and the code is checked by generated tests, not hand-written ones. The exported contract already names every state, widget, property, setter and action method the application depends on. That list is data, so the assertions that the code really provides them are generated from it, per user interface profile, and run on every build. Nobody writes them per feature, which is the only reason they stay complete. The failure this prevents is specific and ordinary: a form missing the method its map calls does not crash for the first person who opens that screen three weeks later, it fails the build the day the map changed.

You can state rules about your own application and have them checked over the map. This is the part with no imperative equivalent. From every state, a close request ends in quit. Every failure state offers the user something other than Cancel. In imperative code these are aspirations you re-audit by hand and hope about in between. Over a declared topology each one is a short query, written once, checked on every build, against every state — including the states someone adds next month without ever reading the rule. A handful of these finds more real defects than a large number of per-feature tests, because each is a statement about the whole application rather than about one path through it.

Where exhaustiveness genuinely pays, the same map compiles to a formal model and a model checker explores orderings and interleavings no hand-written test would think to construct.

What is left over is the seam, and that is where hand-written effort belongs: the code inside each action, the widgets each state drives, and the real dependencies behind the data layer — exercised against a real database with the real migrations applied, not against a stand-in built to agree with its caller. The map still earns its keep here, because it tells you exactly which states to exercise and what each is supposed to permit. Faults are injected rather than imagined: force each action to fail and assert the application lands somewhere usable, with a message, in a state the map allows.

The useful measurement is not how many tests exist, but how many of each kind. Counting by shape — how many assert source text, how many run against stand-ins, how many drive real behavior through the map — tells you something about coverage. A total does not. A suite can be large and still point entirely inward.

Two habits are worth more than any individual test. A test whose expected value was produced by the code under test cannot fail; it records what the code currently does, which is not the same as what it should do. Expectations are derived by hand, or by comparing two independent implementations. And a check reporting "nothing missing" reads identically whether it searched or not, so it is trusted only after being made to fail on purpose: break the input, watch it fire, put it back.

Debugging

In imperative code, the scattered state variables are not the worst of it. The harder problem is that the history of how you got there is hidden.

When an imperative application fails, the variables at the moment of failure tell you where you are. They do not tell you the path you took to get there. So we add logging, and because the flow is complex the logging has to be complex too — which means the detail you need is reliably the one somebody forgot to write.

The question you actually have is rarely about the current value. Did the Save button stay disabled because validation failed, because the record was already saving, because a stale async callback overwrote the form state, or because a previous error flag was never cleared? The variables might only say can_save = false. The code path that made it false is spread across event handlers, callbacks, timers and UI state updates, and nothing in the program records which of them ran.

With a map, the history is not something you remember to write down. Every advance through the application passes through the engine, so the engine records it. The trace is not a sample whose coverage you have to guess at — it covers every step by construction, because there is no other way for the application to move. For each advance it carries:

Two of those answer the Save button directly. Either the event never arrived, in which case nothing matched and the trace says so, or it arrived and a named guard refused it, in which case the trace names the guard and the transition it blocked. Those are the two questions an imperative log is least able to answer, because answering them means knowing what the application could have done at that moment, and only a declared topology knows that.

Context values are included under a declared per-variable policy, so application memory can appear in the trace without secrets appearing with it.

The trace speaks the same vocabulary as the map, which makes it more than a record. It can be replayed through the engine to reproduce a failure exactly. Two runs of the same scenario can be compared directly, so a regression appears as a divergence at a named transition instead of as a difference in symptoms. And a trace captured from a real failure is an expectation derived from reality rather than from the code — which, as above, is the only kind that can fail. With the map alongside it, a visual player follows naturally: highlight each state, animate each transition, show the guards and actions, display the context changes.

Debugging becomes following the declared rails instead of reconstructing branching history from scattered imperative code.