# 2. Decisions and branching

**At the end you can:** make a machine choose its way from data, with the verifier checking
that every possible answer leads somewhere.

**What you will learn:** how a machine branches on data through a **Decision**, how the
verifier makes sure every answer of a decision is handled, and how to save, revive and compare
machines.

**Before this:** [1. A first machine](first-machine.md).

**Time:** about 10 minutes for the main idea (steps 1 to 3), and 5 more for "Going further".

## Where this sits in the big picture

You are still inside the **actor** box of the quickstart's
[big picture](../quickstart.md#the-big-picture): the verified state machine. Tutorial 1
showed how a machine moves on inputs. This page shows how it chooses between two ways
forward when the choice depends on data. The same mechanism is used later by every actor
gvn ships: the agent's [tool policy](../reference/glossary.md#policy), for one, is a Decision like the one you write here.

## Where you are

At the end of tutorial 1 the ticket machine could be filed, answered and withdrawn.

**Start a new file for this page, and begin it with the block below.** The block holds
everything from the earlier page that this page uses, imports included. That is the same
first step whether you have just finished tutorial 1 or are starting here. Then add each
block of the page below it, in order.

??? example "The ticket machine from tutorial 1"

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

    ticket = (
        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")
        .on(source="new", input="withdrawn", target="withdrawn")
        .on(source="open", input="withdrawn", target="withdrawn")
        .otherwise_stay()
        .build()
    )
    print(ticket)  # Definition('ticket', moore, ...)
    ```

## The problem: branching on data

The help desk wants to treat tickets differently: a routine question goes to the normal queue,
and an urgent one ("the site is down", "I was charged twice") pages a senior agent. Which way
a ticket goes depends on what it says.

In many frameworks you would write a function on the transition that returns the next node.
The trouble is that the set of things that function can return is hidden in its code, so
nothing can check that every answer leads somewhere. gvn makes the set of answers explicit.

## Step 1: write a Decision

A **Decision** is a small class that looks at some data and answers with one symbol from a
set it declares up front. You implement two methods: `outcomes()` returns the set (an
`Alphabet`, gvn's name for a fixed set of symbols), and `judge(subject)` picks one.

`Alphabet.of("routine", "urgent")` declares the possible answers;
`URGENCY.named("urgent")` retrieves the symbol for one answer. The subject here is the
ticket's text. Callers use `decide(subject)`, which calls your `judge` and checks that its
answer belongs to the declared alphabet. An undeclared answer raises `UndeclaredOutcome`.

```python
from gvn.kernel.decision import Decision
from gvn.kernel.symbols import Alphabet, Symbol

URGENCY = Alphabet.of("routine", "urgent")


class Triage(Decision):
    """Urgent when the ticket mentions an outage or a double charge."""

    def outcomes(self) -> Alphabet:
        return URGENCY

    def judge(self, ticket_text: object) -> Symbol:
        text = ticket_text.lower()
        urgent = any(phrase in text for phrase in ("outage", "down", "charged twice"))
        return URGENCY.named("urgent" if urgent else "routine")


triage = Triage()
print(triage.decide("The site is down"))  # Symbol('urgent')
print(triage.decide("How do I change my address?"))  # Symbol('routine')
```

A Decision has no side effects and reads no clock or network. It only looks at what it is
given. That keeps it easy to test and makes a run repeatable. The
[Decisions](../concepts/decisions.md) page explains why in more depth.

## Step 2: route the decision, and forget one answer

The ticket now needs a `triaging` state and two places to go from it: `queued` and
`escalated`. Instead of two separate `on(...)` calls, route the decision with
`branch(source=..., outcomes=..., routes=...)`. `branch` records an **obligation**: the
source state must route every outcome of the decision with a declared transition.

`source` names the state waiting for the decision; `outcomes` is the decision's complete
alphabet; `routes` maps answer names to target state names. The machine's input alphabet
must contain those answers too: `*URGENCY.names()` expands to `"routine", "urgent"`,
because the decision's answer becomes the next machine input.

To try several routings without repeating the whole machine, wrap it in a function that takes
the routes:

```python
def ticket_blueprint(urgency_routes: dict[str, str]) -> MooreBlueprint:
    return (
        MooreBlueprint(name="ticket")
        .inputs("filed", *URGENCY.names(), "answered", "withdrawn")
        .outputs("wait", "triage", "work", "page_senior", "close")
        .state(name="new", output="wait")
        .state(name="triaging", output="triage")
        .state(name="queued", output="work")
        .state(name="escalated", output="page_senior")
        .state(name="resolved", output="close", final=True)
        .state(name="withdrawn", output="close", final=True)
        .initial(name="new")
        .on(source="new", input="filed", target="triaging")
        .branch(source="triaging", outcomes=URGENCY, routes=urgency_routes)
        .on(source="queued", input="answered", target="resolved")
        .on(source="escalated", input="answered", target="resolved")
        .on(source="new", input="withdrawn", target="withdrawn")
        .on(source="triaging", input="withdrawn", target="withdrawn")
        .on(source="queued", input="withdrawn", target="withdrawn")
        .on(source="escalated", input="withdrawn", target="withdrawn")
        .otherwise_stay()
    )
```

Now route only the routine answer:

```python
forgetful = ticket_blueprint({"routine": "queued"})
for finding in forgetful.examine():
    print(finding.code(), finding.subject())
```

```text
unmet-obligation triaging/urgent
unreachable-state escalated
```

Look at what would have happened without the obligation. `otherwise_stay()` is still in
place, so an `urgent` answer in `triaging` would have quietly meant "stay", and every urgent
ticket would have sat in triage for ever. The obligation says an `otherwise` rule does not
count for a decision's outcomes: each one needs a declared transition.

The verifier has one more check you have not met yet, **`dead-end-state`**: a state from
which no path leads to a final state, so a run that enters it could never finish. Had you
forgotten that an escalated ticket can be answered or withdrawn, you would see it here.

## Step 3: route both answers and run it

```python
ticket = ticket_blueprint({"routine": "queued", "urgent": "escalated"}).build()

machine = Machine(definition=ticket)
machine.feed(Symbol("filed"))
step = machine.feed(triage.decide("I was charged twice for order A-17"))
print(step.target(), step.output())  # State('escalated') Symbol('page_senior')
```

This is the pattern every gvn harness uses, from the smallest to the agent you will meet in
the next tutorial:

1. the machine names what is happening (`triaging`);
2. a Decision turns data into one of a known set of symbols (`urgent`);
3. the machine routes each of those symbols, and the verifier checks that it does.

## You have the main idea

You can now write a Decision, route its answers with `branch`, and rely on the verifier to
refuse a machine that leaves one answer unrouted. That is all the next tutorial needs.

## Going further

Two more things a machine can do, because it is data:

- **Step 4, save and revive.** You need it when a machine must outlive the process that runs
  it.
- **Step 5, diff.** You need it when you change a machine and want to review exactly what
  changed.

### Step 4: save the machine and bring it back

A running machine can be turned into plain JSON at any step and rebuilt anywhere. Its
serialisable form is called its **Dto** ("data transfer object": a small, immutable record
checked against a [schema](../reference/glossary.md#schema), an object that says what a value
must look like). Every stateful object in gvn has one; [Durable
objects](../concepts/durable-objects.md) explains the pattern.

```python
import json

saved_text = json.dumps(machine.to_dto().to_plain())
revived = Machine.from_dto(Machine.Dto.from_plain(json.loads(saved_text)))
print(revived.state(), revived.steps())  # State('escalated') 2
print(revived.definition().fingerprint() == ticket.fingerprint())  # True
```

The saved text carries the definition the machine runs on, so the revived machine runs on
exactly that version. `Machine.from_dto` verifies the stored definition again, because stored
text is untrusted: someone, or some agent, may have edited it.

### Step 5: change the machine and see exactly what changed

Suppose escalated tickets should go back to the normal queue once a senior agent has reviewed
them. Build the new version and compare the two with `Difference(old=..., new=...)`:

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

revised = (
    ticket_blueprint({"routine": "queued", "urgent": "escalated"})
    .inputs("reviewed")
    .on(source="escalated", input="reviewed", target="queued")
    .build()
)

for change in Difference(old=ticket, new=revised):
    print(change.sentence())
```

```text
input reviewed was added
transition escalated/reviewed was added, going to queued
```

Notice what is *not* in the list: `escalated --answered--> resolved` is still there. You
added a way back to the queue but did not take away the shortcut to `resolved`. A diff that
names each change makes that kind of slip visible in review. Blueprints only add
declarations, so to remove a transition you declare the definition again without it. Each
change also has a stable `kind()` (here `input-added` and `transition-added`) and a
`subject()`, for code that reviews changes automatically.

## Change it and run again

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

**1. A ticket you did not think of.** `Triage` looks for the phrases `outage`, `down` and
`charged twice`. Which way does this ticket go?

```python
print(triage.decide("My parcel is down the street at a neighbour's"))
```

??? note "What happens"

    ```text
    Symbol('urgent')
    ```

    The text contains `down`, so the ticket is urgent. The machine guarantees that `urgent`
    is routed; what counts as urgent is your `judge`, and it is plain code you can test
    with one call, as here.

**2. Route both answers to the same state.** Every outcome of the decision is routed, so the
obligation is met. Does the verifier accept the machine?

```python
same_queue = ticket_blueprint({"routine": "queued", "urgent": "queued"})
for finding in same_queue.examine():
    print(finding.code(), finding.subject())
```

??? note "What happens"

    ```text
    unreachable-state escalated
    ```

    The obligation is met, but nothing leads into `escalated` any more, and the verifier
    refuses a state that can never be entered. Remove the state (and its transitions), or
    route an answer to it.

## Recap

- A **Decision** answers with one symbol from a set it declares (`outcomes()`); `decide`
  refuses any other answer.
- `branch(source=..., outcomes=..., routes=...)` routes a decision and obliges the source
  state to route every outcome. `otherwise_stay()` does not satisfy that obligation.
- The verifier reports incomplete pairs, unmet obligations, unreachable states, unused inputs
  and dead ends.
- Machines and definitions are data: you can save, revive, fingerprint, draw and diff them.

**Next:** [3. An agent with a scripted model](first-agent.md). The reference agent, the
ready-made agent gvn ships, is a machine like this one, with decisions inside it. You will run one, and see that it never calls
a model itself.
