# Diagrams and diffs

This guide draws a state machine three ways and compares two versions of it, so a change
can be reviewed as a sentence rather than as code. At the end you have a diagram you can
paste into a review and a list, in words, of everything a change to a machine changes.

- **You will be able to:** render a definition (the checked description of a machine) as Mermaid, Graphviz Dot or a plain table, and
  list what changed between two versions of a machine.
- **Read first:** [Machines](../concepts/machines.md), which explains states, inputs, outputs
  and the `otherwise` rule, and the tutorial [A first machine](../tutorials/first-machine.md), which builds a
  machine with a blueprint.
- **Time:** about 15 minutes.

## Where this fits

In the [big picture](../quickstart.md#the-big-picture), every **actor** is a verified state
machine. You describe it with a blueprint; the verifier checks it and returns a
[**definition**](../reference/glossary.md#definition): the checked, unchangeable description
of the machine (its states, inputs, outputs and transitions). This guide works on that
definition, outside any run: no Governor, fulfiller or journal is involved.

```mermaid
flowchart LR
    blueprint["Blueprint"] -- "build(): verifier" --> definition["<b>Definition</b>"]
    definition --> renderers["Mermaid · Dot · Table<br/>a picture or a listing"]
    old["Definition, old"] --> difference["<b>Difference</b>"]
    new["Definition, new"] --> difference
    difference --> changes["the changes,<br/>as sentences"]
```

Why you would want this: a proposed change to a machine, from a person or from an agent,
should be reviewed as "this transition now goes there", not as "the code differs". A
definition is data, so gvn can draw it and compare two versions of it:

- `gvn.kernel.diagram` renders a definition as **Mermaid** (the diagram language this site
  draws with), **Dot** (the language of the Graphviz layout tool) or a plain **Table**.
- `gvn.kernel.diff` compares two definitions and lists every **Change**.

Both are deterministic: the same definition always renders to the same text, whatever order
its parts were declared in, so renderings can be versioned, reviewed and compared in tests.
Both are in the kernel (gvn's lowest layer, the machines themselves), so they need nothing
but the standard library.

## Step 1: a machine to draw

The running example is a kettle: it is `cold` until switched on, `heating` until it boils, and
`done` when it has boiled. It is a [Moore machine](../reference/glossary.md#moore-machine),
one whose output depends only on its state:
each state says what the kettle does (`nothing`, `heat` or `whistle`). The function takes one
parameter, where switching off while heating goes, so that step 5 can build a changed version:

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


def kettle(off_goes_to: str = "cold") -> Definition:
    return (
        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=off_goes_to)
        .otherwise_stay()
        .build()
    )


KETTLE = kettle()
print(KETTLE.name())  # kettle
```

`otherwise_stay()` says what happens to every pair of state and input not declared: the
machine stays where it is. Building the blueprint runs the verifier, so `KETTLE` is a complete
machine.

## Step 2: Mermaid

`Mermaid().render(definition)` returns a `stateDiagram-v2` block:

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

print(Mermaid().render(KETTLE))
```

```text
stateDiagram-v2
    cold : emits nothing
    done : emits whistle
    heating : emits heat
    [*] --> cold
    cold --> heating : switched_on
    heating --> done : boiled
    heating --> cold : switched_off
    done --> [*]
    note right of cold
        otherwise: stay
    end note
```

Pasted into a Markdown page that renders Mermaid (this site does), it draws:

```mermaid
stateDiagram-v2
    cold : emits nothing
    done : emits whistle
    heating : emits heat
    [*] --> cold
    cold --> heating : switched_on
    heating --> done : boiled
    heating --> cold : switched_off
    done --> [*]
    note right of cold
        otherwise: stay
    end note
```

The initial state is entered from `[*]` and final states lead to `[*]`. In a Moore machine
each state shows its output; in a Mealy machine (one whose output belongs to each transition,
see [Machines](../concepts/machines.md)) each edge is labelled `input / output`.
Undeclared pairs are not drawn one by one: the `otherwise` rule appears once, as a note.
State names containing `.` or `-` get a safe identifier and keep their name as the label.

## Step 3: Dot

`Dot().render(definition)` returns a Graphviz `digraph`, for tools that lay out larger
machines better than Mermaid does. Final states are double circles:

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

print(Dot().render(KETTLE))
```

```text
digraph "kettle" {
  rankdir=LR;
  label="otherwise: stay";
  labelloc=b;
  "__start__" [shape=point, style=invis];
  "cold" [shape=circle, label="cold\n/ nothing"];
  "done" [shape=doublecircle, label="done\n/ whistle"];
  "heating" [shape=circle, label="heating\n/ heat"];
  "__start__" -> "cold";
  "cold" -> "heating" [label="switched_on"];
  "heating" -> "done" [label="boiled"];
  "heating" -> "cold" [label="switched_off"];
}
```

<a id="table"></a>

## Step 4: Table

`Table().render(definition)` is plain text: one row per state, sorted by name, with its
output (Moore) and its declared transitions sorted by input. `>` marks the initial state and
`*` the final states; the last line states the `otherwise` rule.

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

print(Table().render(KETTLE))
```

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

The table is the form to put in front of a model: it is compact, it states every declared
transition, and it needs no renderer. The [domain pages](../domains/index.md) show each
harness's plan this way, and a docs test re-renders those tables from the code so the pages
cannot drift from it.

Every actor class exposes its definition, so the same calls draw an agent or a workflow:
`Table().render(Agent.definition())` for the agent, or `Mermaid().render(Briefing.definition())`
for the `Briefing` [workflow](../concepts/workflows.md) class.

## Step 5: diffs

`Difference(old=..., new=...)` compares two definitions. Iterate it for the `Change`s, sorted
by kind and subject. Here the changed kettle goes to `done` when switched off while heating,
instead of back to `cold`:

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

safer = kettle(off_goes_to="done")
difference = Difference(old=KETTLE, new=safer)
for change in difference:
    print(change.kind(), change.subject(), change.before(), change.after())
# transition-retargeted heating/switched_off cold done
print(difference.summary())
# transition heating/switched_off now goes to done (was cold)
```

Each change has a **kind** (what sort of change), a **subject** (what it is about) and the
two sides, before and after; `summary()` gives every change as a sentence.

A larger change reads the same way. This kettle gains a state, `scaled`, that it enters
when switched off while heating and leaves once descaled:

```python
descaling = (
    MooreBlueprint(name="kettle")
    .inputs("switched_on", "boiled", "switched_off", "descaled")
    .outputs("nothing", "heat", "whistle", "descale")
    .state(name="cold", output="nothing")
    .state(name="heating", output="heat")
    .state(name="done", output="whistle", final=True)
    .state(name="scaled", output="descale")
    .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="scaled")
    .on(source="scaled", input="descaled", target="cold")
    .otherwise_stay()
    .build()
)
print(Difference(old=KETTLE, new=descaling).summary())
# input descaled was added
# output descale was added
# state scaled was added
# transition scaled/descaled was added, going to cold
# transition heating/switched_off now goes to scaled (was cold)
print(Difference(old=KETTLE, new=kettle()).summary())  # no changes
```

### What a difference and a change offer

| Method | Returns |
|---|---|
| `changes()` | the tuple of `Change`s, sorted by (kind, subject) |
| `kinds()` | the frozenset of kinds present |
| `empty()` | whether the two describe the same machine (equal [fingerprints](../reference/glossary.md#fingerprint)) |
| `summary()` | every change as a sentence, one per line; `"no changes"` when empty |

A `Change` has a `kind()`, a `subject()` (a state, a symbol, or `"state/symbol"` for a
transition), `before()` and `after()` (short descriptions of each side, or `None`), and
`sentence()`.

The kinds are stable, and code may depend on them:

| Kind | Subject |
|---|---|
| `renamed`, `style-changed` | `"name"`, `"style"` |
| `state-added`, `state-removed` | the state |
| `input-added`, `input-removed`, `output-added`, `output-removed` | the symbol |
| `initial-changed` | `"initial"` |
| `final-added`, `final-removed` | the state |
| `transition-added`, `transition-removed` | `"state/symbol"` |
| `transition-retargeted` | `"state/symbol"`: same pair, different target |
| `transition-output-changed` | `"state/symbol"`: Mealy, same pair, different output |
| `state-output-changed` | the state: Moore, its output changed |
| `otherwise-changed` | `"otherwise"` |
| `obligation-added`, `obligation-removed` | `"state/symbol"`: a Decision outcome the state must route |

A state added together with its output is one `state-added`. Transitions of an added or
removed state are still listed, because they are what a reviewer needs to see.

## How the pieces are used together

The diff gives a reviewer a change as a sentence, the table gives a model a compact picture of the machine it is asked to change,
and [replay](replay-and-evaluation.md) shows what the change would have done to recorded
runs. The [self-improvement](self-improvement.md) harness uses all three.

## Keeping a rendering current

A diagram or table copied into a page or a review is a snapshot; it does not follow the
code. Re-render it in a test, as the docs tests do for the domain pages.
`Difference.empty()` tells you whether two definitions differ, and `summary()` says how.

## Recap

- `Mermaid`, `Dot` and `Table` from `gvn.kernel.diagram` render any definition, the same way
  every time; the table is the form to show a model.
- `Difference(old=..., new=...)` lists every change with a stable kind, and `summary()` says
  it in sentences.

**Next:** to see what a changed machine would have done with runs you already recorded,
read [Replay and evaluation](replay-and-evaluation.md#step-4-replay-against-a-change); for a
harness that uses diagrams, diffs and replay to change another harness, read
[Self-improvement](self-improvement.md).
