# Machines

**What you will learn:** what a state machine is, how you write one down in gvn, how you run
it, and what the verifier proves before it lets you run it. By the end you can read any
diagram or table on this site.

**Read first:** [the overview](index.md) of how gvn fits together. Otherwise this page
assumes only Python. **Time:** about 20 minutes.

**Where this sits.** In the [loop that runs](index.md#picture-1-the-loop-that-runs), every
**actor** (an agent, a workflow, a conversation) decides what happens next with a state
machine. This page is about that machine on its own, with no model, no tools and no
Governor: the innermost layer of gvn, the [kernel](index.md#picture-2-the-layers-of-code).
Everything later in this section is built on it.

## The problem: control flow you cannot see

An agent loop usually starts as a `while` loop with a few `if`s: call the model, run the
tools it asked for, maybe wait for a person to approve something, repeat. It works until
someone asks a question the code does not answer on its face. What happens if the person
cancels while a tool is running? What if the model replies while you are still waiting for an
approval? Is there a path where the loop can never finish?

gvn answers those questions by writing the control flow down as a **state machine** and
checking it before it ever runs. Every control flow in gvn, from a kettle to a coding agent,
is one.

## A state machine in one picture

A **state machine** is a small set of named situations, called **states**, and rules that say
which state comes next when something happens. The things that happen are **inputs**. While
in a state, or when moving between states, the machine can name some work it wants done: an
**output**.

Take a kettle. It is `cold`, `heating`, or `done`. Switching it on moves it from `cold` to
`heating`; boiling moves it to `done`.

```mermaid
stateDiagram-v2
    [*] --> cold
    cold --> heating : switched_on
    heating --> done : boiled
    heating --> cold : switched_off
    done --> [*]
```

Each state also names the work the kettle wants while it is there: nothing while `cold`, heat
while `heating`, a whistle once `done`. One state is where the machine starts (the
**initial** state, `cold`). Some states are where it ends (the **final** states, `done`).

Notice what the machine does *not* do: it never heats anything. It only says "now I want
heat". Something outside it does the heating and tells it what happened next. In gvn, that
split is the whole design: machines decide, other code does the work.

## Step 1: declare the kettle

You write a machine down with a **blueprint**. A blueprint collects your declarations and
never complains while you write them; all checking happens at the end. Start with the
vocabulary: the inputs the kettle understands and the outputs it can name.

```python
from gvn.kernel.blueprint import MooreBlueprint

kettle_blueprint = (
    MooreBlueprint(name="kettle")
    .inputs("switched_on", "boiled", "switched_off")
    .outputs("nothing", "heat", "whistle")
)
```

Each name is a plain string. Names must match `[A-Za-z][A-Za-z0-9_.-]*`.

Next, the states. Each one names its output, and one is final:

```python
kettle_blueprint = (
    kettle_blueprint
    .state(name="cold", output="nothing")
    .state(name="heating", output="heat")
    .state(name="done", output="whistle", final=True)
    .initial(name="cold")
)
```

Then the **transitions**, the arrows of the picture. Each says: in state `source`, on input
`input`, go to state `target`.

```python
kettle_blueprint = (
    kettle_blueprint
    .on(source="cold", input="switched_on", target="heating")
    .on(source="heating", input="boiled", target="done")
    .on(source="heating", input="switched_off", target="cold")
)
```

You have now declared everything in the picture. One question is still open, and it is the
one that matters most.

## Step 2: say what happens otherwise

What happens if someone presses `switched_on` while the kettle is already `heating`? Or
`boiled` while it is `cold`? You did not say. In a hand-written loop that gap is where bugs
live. gvn refuses to guess: for every pair of state and input, the machine must say where it
goes.

Most of those pairs mean "this does not apply here, ignore it". So instead of spelling each
one out, you declare one rule that covers every pair you did not declare:

```python
kettle_blueprint = kettle_blueprint.otherwise_stay()
kettle = kettle_blueprint.build()
print(kettle.name(), kettle.style(), kettle.initial())
```

```text
kettle moore State('cold')
```

`otherwise_stay()` means "any input I did not mention leaves the state as it is".
`build()` checks the whole blueprint and returns a **definition**: the finished, checked
description of the machine. A definition is a description, not a running thing; you can run
as many machines from it as you like.

## Step 3: run it

A `Machine` holds one current state and changes it only when you `feed` it an input. An
input is passed as a `Symbol`: a name wrapped in a small object, so an input can never be
mixed up with a plain string. Each `feed` returns the `Step` it took. States print as
`State('...')` for the same reason.

```python
from gvn.kernel.machine import Machine
from gvn.kernel.symbols import Symbol

kettle_machine = Machine(definition=kettle)
step = kettle_machine.feed(Symbol("switched_on"))
print(step)
print(step.declared())
```

```text
Step(cold --switched_on--> heating / heat, declared)
True
```

The step reads as: from `cold`, on `switched_on`, to `heating`, and the output is now `heat`.
It was **declared**: you wrote that arrow yourself.

Now feed the same input again, while the kettle is already heating:

```python
step = kettle_machine.feed(Symbol("switched_on"))
print(step)
print(step.declared())
```

```text
Step(heating --switched_on--> heating / heat, undeclared)
False
```

The `otherwise` rule handled it: the kettle stayed in `heating`, and the step says it was
**undeclared**. That flag is how the code around the machine tells requested work from an
input that did not apply. The output is still `heat`, but because the step was not declared,
the code that does the work (in gvn, the [runtime](index.md#picture-2-the-layers-of-code))
knows not to start heating a second time.

Finish the run:

```python
kettle_machine.feed(Symbol("boiled"))
print(kettle_machine.state(), kettle_machine.finished(), kettle_machine.steps())
```

```text
State('done') True 3
```

`steps()` counts every input fed, including the undeclared one. Two more queries are handy:
`expected()` is the set of inputs with a declared transition from the current state, and
`definition()` returns the definition.

A final state is **absorbing**: once there, every input keeps the machine there. Final states
need no transitions and may not have any.

## What "verified" means

When `build()` succeeded above, the **verifier** proved some facts about the kettle before
letting you run it. A definition that passes is **verified**; gvn also calls it **formally
complete**, meaning the rules leave no gap. The verifier proves that:

- every pair of a non-final state and an input has exactly one next state (no gaps, and no
  two arrows for the same pair);
- every state can be reached from the initial state;
- from every state, some final state can still be reached, so the machine can always finish;
- every state (or transition) names its output.

An uncovered pair in a non-final state needs an `otherwise` rule. A final state is
absorbing even when there is no declared transition for the input.

To see what the verifier says about a broken blueprint without raising an error, call
`examine()`. Here is a door with a few mistakes left in on purpose:

```python
broken_door = (
    MooreBlueprint(name="door")
    .inputs("open", "close", "lock")
    .outputs("shut", "ajar", "secured")
    .state(name="closed", output="shut")
    .state(name="opened", output="ajar")
    .state(name="locked", output="secured", final=True)
    .initial(name="closed")
    .on(source="closed", input="open", target="opened")
    .on(source="opened", input="close", target="closed")
)

report = broken_door.examine()
print(report.clean())
for finding in report:
    print(finding.code(), finding.subject())
```

```text
False
dead-end-state closed
dead-end-state opened
incomplete closed/close
incomplete closed/lock
incomplete opened/lock
incomplete opened/open
unreachable-state locked
unused-input lock
```

Read the findings as a to-do list. Nothing ever goes to `locked`, so it is unreachable, and
`closed` and `opened` can never finish (dead ends). Four pairs are uncovered, because there is
no `otherwise` rule. And `lock` is declared but never used.

Each finding has a stable `code()`, a `subject()` (a state name, or `"state/symbol"`), and a
`message()` written so that a person or an agent can act on it. The verifier reports every
finding at once, and it avoids cascades: a piece already reported as broken is skipped by the
checks that depend on it.

`build()` runs the same checks and raises `DefinitionRejected`, which carries the same report:

```python
from gvn.kernel.definition import DefinitionRejected

try:
    broken_door.build()
except DefinitionRejected as rejected:
    print(len(rejected.report()), "findings")
```

```text
8 findings
```

So a definition that exists is always a verified one. You cannot run a machine with a gap in
it.

## Choosing what happens otherwise

Every pair of a non-final state and an input needs an answer. So far the kettle ignored
anything unexpected. That is one of three choices, and the right one depends on what an
unexpected input means in your system.

| You write | An input you did not declare | Choose it when |
|---|---|---|
| `otherwise_stay()` | leaves the state as it is | an unexpected input is harmless and can be ignored |
| `otherwise_go(target=...)` | moves to the one state you name | an unexpected input is a fault that must be handled, for example by failing or escalating |
| neither | has no answer, so `build()` refuses the blueprint | every pair deserves its own decision, written as its own `on(...)` |

Here is a stricter kettle. It treats anything unexpected as a fault and ends in a `faulted`
state that sounds an alarm. Leave the rule out first and ask the verifier what is open:

```python
def strict_blueprint():
    return (
        MooreBlueprint(name="strict_kettle")
        .inputs("switched_on", "boiled", "switched_off")
        .outputs("nothing", "heat", "whistle", "alarm")
        .state(name="cold", output="nothing")
        .state(name="heating", output="heat")
        .state(name="done", output="whistle", final=True)
        .state(name="faulted", output="alarm", final=True)
        .initial(name="cold")
        .on(source="cold", input="switched_on", target="heating")
        .on(source="heating", input="boiled", target="done")
        .on(source="heating", input="switched_off", target="cold")
    )


for finding in strict_blueprint().examine():
    print(finding.code(), finding.subject())
```

```text
incomplete cold/boiled
incomplete cold/switched_off
incomplete heating/switched_on
unreachable-state faulted
```

Three pairs have no answer, and nothing leads to `faulted` yet. With neither rule, you
would close each gap with its own `on(...)`. One `otherwise_go` closes all three and makes
`faulted` reachable:

```python
strict = strict_blueprint().otherwise_go(target="faulted").build()
strict_machine = Machine(definition=strict)
print(strict_machine.feed(Symbol("switched_on")))
print(strict_machine.feed(Symbol("switched_on")))
print(strict_machine.feed(Symbol("boiled")))
```

```text
Step(cold --switched_on--> heating / heat, declared)
Step(heating --switched_on--> faulted / alarm, undeclared)
Step(faulted --boiled--> faulted / alarm, undeclared)
```

The three steps show how the rule behaves:

- **A declared transition always wins.** `switched_on` in `cold` went to `heating` because
  you wrote that arrow. The rule only answers pairs you left open.
- **The rule answers the rest.** `switched_on` while `heating` went to `faulted`, marked
  `undeclared`.
- **A final state stays put.** `faulted` is final, so the last input changed nothing. The
  rule applies to non-final states only.

Two more things to know:

- A machine has one `otherwise` rule. Calling `otherwise_stay()` and then `otherwise_go(...)`
  keeps the last one.
- The rule does not make an input used. Every input still needs at least one declared
  transition somewhere, or the verifier reports `unused-input`.

## Two styles: Moore and Mealy

The kettle names its output per *state*: while `heating`, it wants `heat`. That style is
called a **Moore machine** (after Edward Moore). A step's output is the output of the state
it lands in. The state says what the system is doing, and its output is the work it wants:
in the [quickstart](../quickstart.md)'s agent, the state `thinking` emits `invoke_model`
("call the model"). This is the default for harness machines,
because it is easy to read, draw and verify.

The other style names the output per *transition*: a **Mealy machine** (after George Mealy).
A step's output is the output of the arrow it took. Use it where one state must answer
differently depending on the input, such as accepting some inputs and refusing others.

A turnstile is the classic case. While `locked`, a coin unlocks it, but a push must be
refused. The answer depends on the input, not just on the state:

```python
from gvn.kernel.blueprint import MealyBlueprint

turnstile = (
    MealyBlueprint(name="turnstile")
    .inputs("coin", "push", "retire")
    .outputs("unlock", "lock", "refuse", "shut_down")
    .state(name="locked")
    .state(name="open")
    .state(name="retired", final=True)
    .initial(name="locked")
    .on(source="locked", input="coin", target="open", output="unlock")
    .on(source="open", input="push", target="locked", output="lock")
    .on(source="locked", input="retire", target="retired", output="shut_down")
    .otherwise_stay(output="refuse")
    .build()
)
step = Machine(definition=turnstile).feed(Symbol("push"))
print(step.output(), step.declared())
```

```text
Symbol('refuse') False
```

States carry no output here. Every transition names one, and so does the `otherwise` rule.

Both styles produce the same `Definition` class, and both are driven through the same
`Machine` interface. The style is just a property of the definition.

In the Mealy style the `otherwise` rule names the output it emits as well:
`otherwise_stay(output=...)` and `otherwise_go(target=..., output=...)`. The
[three choices](#choosing-what-happens-otherwise) are the same in both styles.

## Control state and data

You may wonder how a machine with three states can run an agent whose conversation grows
without limit. The answer is that gvn splits what it tracks in two:

- **Control state** is the machine's current state, such as `thinking` or
  `awaiting_approval`. There are finitely many, and the current state, together with the
  input, is the only thing that decides the next state.
- **Data** (the transcript, a budget, tool results) lives in ordinary objects owned by
  whoever holds the machine. The machine never reads it.

The machine is *purely symbolic*: its inputs and outputs are names with no payload. A
`Symbol` is never equal to a `State` or to a plain `str`, even with the same name. Data
travels beside the machine, in the objects that own it. That is what keeps the machine small
enough to verify. When a choice has to depend on data ("is this refund over the limit?"), a
[Decision](decisions.md) turns the data into one of a fixed set of inputs; that is the next
page.

That is the 80% you need. The rest of this page is detail you can come back to.

## Deeper: the formal parts

If you have met state machines in a textbook, a definition is the textbook tuple. An
**alphabet** in that tuple is just the fixed set of names a machine accepts as inputs, or
emits as outputs.

| Part | In gvn |
|---|---|
| States Q | `State` objects, named |
| Input alphabet Σ | an `Alphabet` of input `Symbol`s |
| Output alphabet Λ | an `Alphabet` of output `Symbol`s |
| Transition function δ | declared transitions, plus one `otherwise` rule |
| Output function ω | per state (Moore) or per transition (Mealy) |
| Initial state q0 | one state |
| Final states F | at least one state |

## Deeper: every verifier finding

The codes are stable. Tests and self-improving agents depend on them. Two rows mention an
**obligation**: a state's duty to route every outcome of a [Decision](decisions.md)
explicitly, which the next page introduces.

| Code | Meaning |
|---|---|
| `invalid-name` | a state, symbol or definition name is not a valid name |
| `duplicate-name` | a name appears twice in states, inputs or outputs |
| `unknown-state` | a reference (initial, final, transition end, otherwise target, ...) names no state |
| `unknown-symbol` | a transition or obligation uses an undeclared input, or an undeclared output |
| `no-final-state` | there are no final states |
| `empty-alphabet` | the inputs or the outputs are empty |
| `nondeterministic` | two transitions share a source and an input |
| `incomplete` | a (non-final state, input) pair is uncovered and there is no `otherwise` rule |
| `final-not-absorbing` | a declared transition leaves a final state |
| `unreachable-state` | the initial state cannot reach this state |
| `dead-end-state` | this state cannot reach any final state |
| `missing-output` | Moore: a state has no output. Mealy: a transition or the `otherwise` rule has none |
| `misplaced-output` | an output in the place the other style uses |
| `unused-input` | an input has no declared transition anywhere |
| `unused-output` | an output is never emitted |
| `unmet-obligation` | a state must route a Decision outcome explicitly and does not (see [Decisions](decisions.md)) |

## Deeper: definitions are data

A built `Definition` is immutable. Its `to_dto()` returns a plain record of every state,
symbol, transition and rule (a **Dto**, short for data transfer object), and
`Definition.from_dto(dto)` builds one back. A Dto is treated as untrusted input, because an
agent may have edited it, so `from_dto` always runs the verifier again.

Every definition has a `fingerprint()`: a SHA-256 of its content that ignores declaration
order. Two definitions that describe the same machine have the same fingerprint and compare
equal.

### Positions

A running machine can be reduced to a `Machine.Position`: the definition's fingerprint, the
current state and the step count. An owner that already holds the definition in code (the
agent, a workflow) stores a position instead of the whole definition and rebuilds with
`Machine.at`, which refuses a position recorded on a different definition.

```python
position = kettle_machine.position()
print(position.state, position.steps)
again = Machine.at(definition=kettle, position=position)
print(again.state())
```

```text
done 3
State('done')
```

`Machine.to_dto()` instead embeds the whole definition, so a machine can be revived anywhere
on the exact version it started with (`Machine.from_dto`, or `Machine.resume` to skip
re-verification when you hold a definition with the same fingerprint).

## Deeper: drawing and comparing

`gvn.kernel.diagram` renders a definition three ways: `Mermaid`, `Dot` (Graphviz) and
`Table`. Rendering is deterministic, so renderings can be compared and versioned.

```python
from gvn.kernel.diagram import Table

print(Table().render(definition=kettle))
```

```text
   state    output   transitions
>  cold     nothing  switched_on -> heating
*  done     whistle  -
   heating  heat     boiled -> done, switched_off -> cold
otherwise: stay
```

`>` marks the initial state and `*` the final states.

`gvn.kernel.diff.Difference` says exactly what changed between two versions of a machine, as
a list of `Change` objects with stable kinds such as `state-added` or
`transition-retargeted`. Here a stricter kettle goes to `done` when switched off, instead of
back to `cold`:

```python
from gvn.kernel.diff import Difference

stricter_kettle = (
    MooreBlueprint(name="kettle")
    .inputs("switched_on", "boiled", "switched_off")
    .outputs("nothing", "heat", "whistle")
    .state(name="cold", output="nothing")
    .state(name="heating", output="heat")
    .state(name="done", output="whistle", final=True)
    .initial(name="cold")
    .on(source="cold", input="switched_on", target="heating")
    .on(source="heating", input="boiled", target="done")
    .on(source="heating", input="switched_off", target="done")
    .otherwise_stay()
    .build()
)
for change in Difference(old=kettle, new=stricter_kettle):
    print(change.kind(), change.subject())
```

```text
transition-retargeted heating/switched_off
```

That is what lets a proposed change to a machine be reviewed as "this transition now goes
there" instead of "the hash differs".

## Recap

- A state machine is a finite set of states, the inputs it understands, the outputs it names,
  and the transitions between states.
- You declare it with a `MooreBlueprint` or `MealyBlueprint` and `build()` it into a verified
  `Definition`. An `otherwise` rule covers every pair you did not declare.
- The verifier rejects gaps, unreachable states and dead ends, and tells you each problem by a
  stable code.
- A `Machine` runs a definition. `feed` returns a `Step`; `declared()` tells requested work
  from an input that did not apply.
- Moore names outputs per state; Mealy names them per transition.
- Machines hold only control state. Data lives beside them.

**Next:** [Decisions](decisions.md), how a machine branches on data without losing
completeness.
