# 1. A first machine, and what "verified" buys you

**At the end you can:** write a state machine of your own, read every finding the verifier
gives about it, and run and draw it.

**What you will learn:** what a state machine is in gvn, how to write one down, how to read
what the verifier says about it, and how to run it step by step.

**Before this:** the [quickstart](../quickstart.md) is helpful but not required. You need gvn
[installed](../install.md).

**Time:** about 10 minutes.

!!! note "Coming from the quickstart?"
    Steps 1 to 4 repeat what you did there, on a new example: declare a machine, read the
    `incomplete` findings, close them with `otherwise_stay()`, and feed inputs. Skim them, but
    type the code, because the later pages build on this ticket. New to you: the table in
    step 2 that separates blueprint, Definition and Machine; step 5, where the verifier
    refuses a state nothing reaches and an input nothing uses; and step 6, which draws the
    machine.

## Where this sits in the big picture

In the quickstart's [big picture](../quickstart.md#the-big-picture), the run is a loop
between the Governor and an **actor**, and at the centre of every actor is a verified state
machine. This page opens that centre box and nothing else: no model, no Governor, no
journal. Everything later in the tutorials is built on what you write here.

## Why start with a machine

Every agent harness has control flow: "call the model, run the tools it asked for, ask a
person, try again, give up". In most frameworks that flow is ordinary code, and you find the
case nobody handled when it happens in production: an approval that arrives after the run
was cancelled, a tool result that arrives twice.

In gvn, every control flow is a **state machine**: a fixed list of states, a fixed list of
inputs, and a table that says, for each state and each input, which state comes next. Before a
machine can be used, a **verifier** reads that table and refuses it if any combination is
missing. Every agent in gvn, and every workflow (several agents run in an order fixed by
code), is built this way, so this first tutorial uses no agent at all: just one machine.

The running example of the tutorials is the help desk of a small online shop. This page
builds the life of a support ticket. Later tutorials add an agent that answers tickets, tools
it can use, and a person who approves refunds.

Put each block below in one file, in order, or paste them into one Python 3.12 session.

## Step 1: sketch the ticket

A ticket starts `new`. When the customer files it, it is `open`. When someone answers it, it
is `resolved`, and that is the end.

| State | What is happening | What the system should do (the output) |
|---|---|---|
| `new` | nothing yet | `wait` |
| `open` | waiting for an answer | `work` |
| `resolved` (final) | done | `close` |

Two words in that table matter:

- An **input** is something that happens to the machine: here `filed` and `answered`.
- An **output** is what the system should do while the machine is in a state. A machine whose
  outputs belong to states, as here, is called a **Moore machine**. (gvn also has Mealy
  machines, whose outputs belong to transitions; you will not need them in the tutorials.)

## Step 2: write it down and let the verifier read it

A `MooreBlueprint` collects the declarations: the inputs, the outputs, the states, which state
is the first one, and the transitions. `on(source=..., input=..., target=...)` declares one
transition: in state `source`, the input `input` leads to state `target`.

Read the declarations as a description of the ticket, rather than as instructions to run:

| Declaration | What you are deciding |
|---|---|
| `name="ticket"` | The identity of this machine definition; each running ticket will have its own position on it. |
| `inputs(...)` | Which kinds of event the ticket understands. An input is something that happened. |
| `outputs(...)` | Which kinds of work the ticket may ask for. Declaring `work` does not implement that work. |
| `state(name, output, final=False)` | A situation the ticket can be in, and the work associated with it. A final state ends the machine. |
| `initial(name)` | Where a fresh ticket begins. |
| `on(source, input, target)` | One explicit answer to “what happens in this situation when this event arrives?” |

The blueprint is the editable description. A **Definition** is the checked, immutable result
of building it. A **Machine**, introduced in step 4, is one running instance on a Definition.
Keeping those three roles separate lets many tickets share one verified definition without
sharing their current state.

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

draft = (
    MooreBlueprint(name="ticket")
    .inputs("filed", "answered")
    .outputs("wait", "work", "close")
    .state(name="new", output="wait")
    .state(name="open", output="work")
    .state(name="resolved", output="close", final=True)
    .initial(name="new")
    .on(source="new", input="filed", target="open")
    .on(source="open", input="answered", target="resolved")
)

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

A blueprint accepts anything you declare. `examine()` asks the verifier for its opinion
without raising, and lists every finding at once:

```text
incomplete new/answered
incomplete open/filed
```

The verifier is asking two questions you had not answered:

- What should `answered` do to a ticket that is still `new`?
- What should `filed` do to a ticket that is already `open`? (A customer double-clicks.)

This is the core rule of gvn: **every state must say what every input does there**. The
verifier will not guess, because a guess is exactly the unhandled case you would otherwise
meet in production.

## Step 3: say what the other cases mean

Here the right answer for both cases is "nothing: stay where you are". You could declare that
pair by pair, but `otherwise_stay()` says it once, explicitly, for every pair you did not
declare. When an unexpected input should count as a fault instead, `otherwise_go` sends it to
a state you name;
[Machines](../concepts/machines.md#choosing-what-happens-otherwise) compares the choices.

```python
ticket = draft.otherwise_stay().build()
print(ticket)  # Definition('ticket', moore, 45dcef85b1c5)
```

`build()` runs the verifier again. This time it finds nothing, and returns a **Definition**:
the verified, immutable form of the machine. The last part of its name is a fingerprint, a
short hash of everything in it, so two definitions with the same fingerprint are the same
machine. Had the verifier found anything, `build()` would have raised `DefinitionRejected`
with every finding in it.

## Step 4: run it

A `Machine` holds a current state on a definition. `feed` hands it one input and returns the
`Step` it took:

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

machine = Machine(definition=ticket)
for name in ["filed", "filed", "answered"]:
    step = machine.feed(Symbol(name))
    print(step)
print(machine.state(), machine.finished())
```

```text
Step(new --filed--> open / work, declared)
Step(open --filed--> open / work, undeclared)
Step(open --answered--> resolved / close, declared)
State('resolved') True
```

`Symbol("filed")` is the input named `filed`; gvn uses small `Symbol` and `State` objects
rather than bare strings so that names cannot be confused with text.

Notice the second step: the duplicate `filed` was handled by "otherwise stay", and the step
says so (`undeclared`). Later, when a machine drives real work, gvn uses that flag to avoid
starting the same work twice.

## Step 5: add a way out, and forget half of it

A customer can withdraw a ticket before it is answered. Add the input and a second final
state, but declare no transition into it yet, to see what the verifier says:

```python
withdrawable = (
    MooreBlueprint(name="ticket")
    .inputs("filed", "answered", "withdrawn")
    .outputs("wait", "work", "close")
    .state(name="new", output="wait")
    .state(name="open", output="work")
    .state(name="resolved", output="close", final=True)
    .state(name="withdrawn", output="close", final=True)
    .initial(name="new")
    .on(source="new", input="filed", target="open")
    .on(source="open", input="answered", target="resolved")
    .otherwise_stay()
)

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

```text
unreachable-state withdrawn
unused-input withdrawn
```

`otherwise_stay()` covered the missing pairs, so nothing is incomplete. But the verifier
checks more than completeness:

- **`unreachable-state`**: no path from `new` leads into `withdrawn`. A state you can never
  enter is a mistake, so it is refused.
- **`unused-input`**: the input `withdrawn` is declared but never routed anywhere, so every
  `withdrawn` would be silently ignored.

Each finding also carries a sentence for people, through `finding.message()`. Route the input
from both non-final states, and the machine builds:

```python
ticket = (
    withdrawable.on(source="new", input="withdrawn", target="withdrawn")
    .on(source="open", input="withdrawn", target="withdrawn")
    .build()
)
print(sorted(state.name() for state in ticket.states()))
# ['new', 'open', 'resolved', 'withdrawn']
```

A blueprint only ever adds declarations, so calling `on` on `withdrawable` extends it with the
two missing transitions.

## Step 6: draw it

A definition is data, so gvn can draw it. `Mermaid` renders the diagram syntax that this site
(and GitHub, and many editors) displays as a picture:

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

print(Mermaid().render(ticket))
```

Rendered, that output looks like this:

```mermaid
stateDiagram-v2
    new : emits wait
    open : emits work
    resolved : emits close
    withdrawn : emits close
    [*] --> new
    new --> open : filed
    new --> withdrawn : withdrawn
    open --> resolved : answered
    open --> withdrawn : withdrawn
    resolved --> [*]
    withdrawn --> [*]
    note right of new
        otherwise: stay
    end note
```

The drawing comes from the definition, not from a separate document, so it cannot drift from
the code. [Diagrams and diffs](../guides/diagrams-and-diffs.md) shows the other renderings.

## Change it and run again

Predict the answer first, then run the code and open the block.

**1. Remove one `on`.** This is the finished ticket without the transition from `open` on
`answered`. What will the verifier say?

```python
without_answer = (
    MooreBlueprint(name="ticket")
    .inputs("filed", "answered", "withdrawn")
    .outputs("wait", "work", "close")
    .state(name="new", output="wait")
    .state(name="open", output="work")
    .state(name="resolved", output="close", final=True)
    .state(name="withdrawn", output="close", final=True)
    .initial(name="new")
    .on(source="new", input="filed", target="open")
    .on(source="new", input="withdrawn", target="withdrawn")
    .on(source="open", input="withdrawn", target="withdrawn")
    .otherwise_stay()
)

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

??? note "What happens"

    ```text
    unreachable-state resolved
    unused-input answered
    ```

    That `on` was the only way into `resolved` and the only use of `answered`, so the
    verifier reports both. `otherwise_stay()` does not hide it: an input counts as used
    only when some `on` declares a transition for it.

**2. Forget that a state is final.** Put the `on` back, and remove `final=True` from
`resolved`. What does the verifier find now?

??? note "What happens"

    ```text
    dead-end-state resolved
    ```

    A ticket that enters `resolved` could never finish: the state is not final, and no
    transition leaves it. `finding.message()` says so in a sentence: "No path leads from
    'resolved' to a final state: a run that enters it can never finish. Add a transition
    towards a final state."

## Recap

- A gvn machine is a list of states, inputs and outputs, and a table of transitions.
- A blueprint accepts anything; the verifier judges it and reports every finding at once.
  `build()` returns a verified `Definition` or raises.
- Every (state, input) pair must mean something. `otherwise_stay()` says "nothing", explicitly.
- The verifier also refuses states you can never enter, inputs you never route, and (you will
  see it next) states from which a run can never finish.

What "verified" buys you: a run of this machine cannot reach a situation its author did not
decide about.

**Next:** [2. Decisions and branching](decisions-and-branching.md) adds triage. A ticket is
routine or urgent depending on what it says, and the verifier makes sure both answers are
handled.
