# Decisions

**What you will learn:** how a machine branches on data ("is this refund over the limit?")
while the verifier can still prove that every case is handled.

**Read first:** [Machines](machines.md). **Time:** about 10 minutes.

**Where this sits.** Still inside the actor's machine, in the
[kernel](index.md#picture-2-the-layers-of-code). [Machines](machines.md) showed that a
machine moves only on input names and never looks at data. This page shows the one
sanctioned bridge from data to those names, which later lets the agent's tool policy,
budgets and workflow routing branch on data while the verifier still checks every case:

```mermaid
flowchart LR
    data["data<br/>(an amount, a tool call)"] --> decision["<b>Decision</b><br/>declares its answers up front"]
    decision -- "one input name" --> machine["<b>machine</b><br/>has an arrow for every answer"]
```

## The problem: choices that depend on data

A machine's next state depends only on its current state and the input it is fed. It never
looks at data. Yet real control flow branches on data all the time: did the model ask for
tools? Is this tool call safe? Is this refund small enough to pay without asking anyone?

Picture a refund desk. A request comes in. Small refunds are paid straight away; large ones go
to a manager. The machine has a `checking` state with two ways out, and something has to look
at the amount to pick one.

gvn's answer is the **Decision**: an object that inspects some data and answers with exactly
one input name from a fixed set it declares up front. The machine must have an arrow for every
name in that set, and the verifier checks that it does.

## Step 1: write a Decision

You subclass `Decision` and implement two methods:

- `outcomes()` returns every answer the Decision can give, as an `Alphabet` (a fixed set of
  names). It must not change over time.
- `judge(subject)` inspects the data, here called the subject, and returns one `Symbol` from
  `outcomes()`.

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

REFUND_SIZES = Alphabet.of("routine", "large")


class RefundSize(Decision):
    def outcomes(self) -> Alphabet:
        return REFUND_SIZES

    def judge(self, subject: object) -> Symbol:
        return REFUND_SIZES.named("routine" if subject < 100 else "large")


refund_size = RefundSize()
print(refund_size.decide(subject=40))
print(refund_size.decide(subject=900))
```

```text
Symbol('routine')
Symbol('large')
```

`Alphabet.of(...)` builds the fixed set of names, and `named(...)` returns the `Symbol` with
that name from it (it raises `UnknownSymbol` for a name not in the set).

You never call `judge` yourself. You call the third method, `decide(subject)`, which calls
`judge` and enforces the contract: the answer must be one of the declared outcomes.

## Step 2: the contract is enforced

Here is a Decision that answers with something it never declared:

```python
class SloppyRefundSize(Decision):
    def outcomes(self) -> Alphabet:
        return REFUND_SIZES

    def judge(self, subject: object) -> Symbol:
        return Alphabet.of("medium").named("medium")


try:
    SloppyRefundSize().decide(subject=250)
except UndeclaredOutcome as error:
    print(error)
```

```text
SloppyRefundSize answered Symbol('medium'); declared outcomes are large, routine
```

`decide` raises `UndeclaredOutcome`. Exceptions raised inside `judge` itself propagate
unchanged. A Decision can contain routing logic of any complexity. What it cannot do is
answer with something it did not declare.

## Step 3: route every outcome with `branch`

In a blueprint, `branch(source=..., outcomes=..., routes=...)` declares one transition out of
`source` per route (a dict from outcome name to target state). It also records an
**obligation**: that state must route *every* outcome with a declared transition. An
`otherwise` rule does not count, so a forgotten outcome cannot be silently swallowed.

To see the obligation at work, give the refund desk a third outcome, `suspicious`, and forget
to route it:

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

REFUND_CHECKS = Alphabet.of("routine", "large", "suspicious")

refund_desk = (
    MooreBlueprint(name="refund_desk")
    .inputs("requested", *REFUND_CHECKS.names())
    .outputs("wait", "check_amount", "pay", "ask_manager")
    .state(name="idle", output="wait")
    .state(name="checking", output="check_amount")
    .state(name="paid", output="pay", final=True)
    .state(name="escalated", output="ask_manager", final=True)
    .initial(name="idle")
    .on(source="idle", input="requested", target="checking")
    .branch(
        source="checking",
        outcomes=REFUND_CHECKS,
        routes={"routine": "paid", "large": "escalated"},
    )
    .otherwise_stay()
)

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

```text
unmet-obligation checking/suspicious
```

Even though `otherwise_stay()` would technically cover `checking/suspicious`, the verifier
reports an `unmet-obligation`. Add the missing route and the definition builds:

```python
refund_desk_definition = refund_desk.branch(
    source="checking",
    outcomes=REFUND_CHECKS,
    routes={"suspicious": "escalated"},
).build()
print(refund_desk_definition.name())
```

```text
refund_desk
```

## Step 4: feed the answer to the machine

A Decision's answer is an ordinary input symbol, so you feed it to the machine like any other:

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


class RefundCheck(Decision):
    def outcomes(self) -> Alphabet:
        return REFUND_CHECKS

    def judge(self, subject: object) -> Symbol:
        if subject >= 10_000:
            return REFUND_CHECKS.named("suspicious")
        return REFUND_CHECKS.named("routine" if subject < 100 else "large")


refund = Machine(definition=refund_desk_definition)
refund.feed(Symbol("requested"))
step = refund.feed(RefundCheck().decide(subject=40))
print(step)
```

```text
Step(checking --routine--> paid / pay, declared)
```

The data (the amount, 40) never entered the machine. Only the Decision's answer did.

That is the 80% you need. The rest of this page explains the choice and where Decisions show
up later.

## Deeper: why not guard functions?

Many state-machine and graph libraries let you attach a predicate (a "guard") to each
outgoing edge: "go to `acting` if the call is safe, else to `awaiting_approval`". gvn does
not, for three reasons:

- With arbitrary predicates, whether every case is handled is undecidable. The verifier
  could no longer prove the machine complete.
- When several guards could be true, the order of the arrows decides which wins. That rule
  is invisible in the definition.
- A Decision gives each possible route a named input symbol. When a fulfiller delivers the
  answer as an external event, the Governor journals it. An actor's internal decisions run
  inside `handle` and replay recomputes them from the recorded events.

## Deeper: Decisions are pure

A Decision is pure and synchronous: no I/O, no waiting. If deciding needs I/O, such as asking
a model to classify something, the machine requests that work as an output, the code around
it does the work, and a Decision classifies the result.

## Deeper: where Decisions run

The same idea appears in three places you will meet later:

- **Inside an actor.** The [reference agent](reference-agent.md) decides "is there budget
  left?" and "did the reply ask for tools?" itself, synchronously, with private Decisions.
  Those states have *internal* outputs: the agent feeds the answer straight back into its
  own machine in the same `handle` call (`handle` is the method an actor receives each event
through; see [Actors and events](actors-and-events.md)).
- **In the runtime.** The agent's tool policy (your rule for whether a tool call may run) is
  a Decision you supply. `PolicyFulfiller`, the part of the runtime that consults it,
  asks it about the pending tool calls and turns the answer (`cleared`, `needs_approval` or
  `forbidden`) into the agent's next event. See [The Governor](governor.md).
- **In workflows.** A workflow runs child actors in stages; a fan-out stage runs several
  children at once, and its `Join` is a Decision-like object that decides when a
  group of children is done and with which symbol. See [Workflows](workflows.md).

## Recap

- A Decision inspects data and answers with one symbol from a fixed, declared set.
- `decide` enforces the contract and raises `UndeclaredOutcome` for anything else.
- `branch` routes the outcomes and records an obligation; a missing route is an
  `unmet-obligation` finding, even when an `otherwise` rule exists.
- The answer is an ordinary input, so the machine stays verifiable and the choice is recorded.

**Next:** [Durable objects](durable-objects.md), how a running machine and its data are saved
and restored.
