# Workflows in depth

**What you will learn:** how a stage can decide on what a child said, how to loop safely,
every join gvn ships and how to write your own, deadlines, a fan-out over items with retries,
a stage of children of different kinds, compensation the verifier checks, workflows inside
workflows, and what a workflow guarantees and stores.

**Read first:** [Workflows](workflows.md); this page continues its report example. The
sections on deadlines and on children of different kinds also lean on [Time](time.md),
[Errands](errands.md) and [Asking a person](asking-a-person.md).
**Time:** 5 to 10 minutes per topic. This is a topic collection, rather than a single
lesson to read in one sitting. For one continuous example, use the
[workflow tutorial](../tutorials/workflow.md).

## Where this sits

In the [big picture](index.md#picture-1-the-loop-that-runs), a workflow is one more
**actor**: the Governor feeds it events and fulfils its requests like any other. What makes
it different is inside: it owns child actors (agents, errands, inquiries, even other
workflows), passes each event to the child it is addressed to, and turns the way each child
ended into an input to its own verified machine. Everything on this page is a refinement of
that one arrangement, in the harness layer of
[picture 2](index.md#picture-2-the-layers-of-code).

## The shape of it

```mermaid
flowchart LR
    governor["Governor"]
    subgraph workflow ["Workflow (one actor)"]
        direction TB
        machine["parent machine<br/>(verified)"]
        stage["stage<br/>Host · FanOut · ForEach · Parallel"]
        children["child actors"]
        decide["judge or join<br/>(a Decision)"]
        memo[("memo<br/>input + finished visits")]
        machine -- "current state names a stage" --> stage
        stage -- "creates" --> children
        children -- "ending" --> decide
        memo -.-> stage
        memo -.-> decide
        decide -- "one declared symbol" --> machine
    end
    governor -- "events" --> workflow
    workflow -- "children's requests" --> governor
```

Read it from the parent machine down, as [Workflows](workflows.md) built it:

- The parent's **machine** is an ordinary verified machine. Each of its working states names
  a **stage**: a recipe that creates the children for that state.
- When children end, something turns their endings into **one symbol** the parent's machine
  must route: `routes` (a fixed mapping of the child's final state), a **judge** (a
  [Decision](decisions.md) that reads one child's ending, data included), or a **join** (a
  Decision that reads a group of children and says when the group is over).
- The **memo** is the parent's read-only view of its starting input and of every finished
  visit of every stage. Stage functions, judges and joins read it; nothing writes it but the
  workflow.

These are different responsibilities, even when one stage uses all of them. The topics
below each refine one part of the picture: what decides (judges, joins), how often a stage
runs (loops, deadlines), which children a stage makes (`ForEach`, `Parallel`), what a failed
run must undo (compensation), and what a workflow promises and stores (nesting, internal
symbols, atomicity, the outcome, the durable form).

## Choose the question you need to answer

| Question | Start here | Parameters to understand first |
|---|---|---|
| Does the next step depend on result data? | [Judges](#judges-deciding-on-what-a-child-said) | `judge` receives an `Ending`: the child's outcome, the parent's memo and the stage's name, in one object. |
| Can a stage repeat, and when must it stop? | [Loops](#loops), [Memo](#the-memo-in-full) | Visit counts and finite decision outcomes express the stopping rule. |
| When is a concurrent group finished? | [Joins](#joins-when-is-a-fan-out-over) | `success`/verdicts describe child endings; `reached` and `missed` are parent inputs. |
| Do I need a deadline or less retained history? | [Deadlines and long loops](#deadlines-and-long-loops) | `deadline` requests a time; `expired` routes timeout; `retain` trims old payloads. |
| One child per input item? | [ForEach](#fan-out-over-items-foreach) | `items` selects work, `window` limits active children, `retry` governs fresh attempts. |
| Different kinds of child in one group? | [Parallel](#different-kinds-at-once-parallel) | Each `Branch` maps an actor's ending to a common verdict vocabulary. |
| Must earlier effects be undone on failure? | [Compensation](#compensation-the-verifier-checks) | `Compensate` declares effect/undo pairs; `undone` identifies the constrained final states. |
| Can a child be a whole workflow? | [Nesting](#nesting) | The child still has the `Actor` contract; only its internals grow. |
| Which models and tools may the children use? | [Model roles](#model-roles), [Tools](#declared-tools) | `Plan(model_roles=..., tools=...)` declares them, so the runtime is checked before the run. |
| What must persist, or remain atomic? | [Internal symbols](#internal-symbols), [atomicity](#atomicity), [stored state](#what-the-durable-form-holds) | Separate stage code from the instance state saved in a [Dto](durable-objects.md) (the plain-data form an object is saved as). |

The sections share the report example below. Read each section's explanation before its
code; expand the setup when you want to run the blocks. For application boundaries across
several such workflows, see [Designing a large harness](../guides/large-harnesses.md).

## The example so far

This block repeats the report workflow from [Workflows](workflows.md) in one piece, so the
examples below can run. Skim it if you just read that page: two researcher agents run side
by side (`researching`), then one writer agent writes their notes up (`writing`).

??? example "Runnable setup: the report workflow and its fake Governor"

    ```python
    import asyncio
    from collections.abc import Callable

    from gvn.harness.agent import Agent
    from gvn.harness.events import Event
    from gvn.harness.workflow import AllOf, FanOut, Host, Memo, Plan, Report, Workflow
    from gvn.kernel.blueprint import MooreBlueprint
    from gvn.kernel.symbols import Alphabet

    REPORT_MACHINE = (
        MooreBlueprint(name="report")
        .inputs("started", "researched", "research_failed", "written", "write_failed")
        .outputs("idle", "research", "write", "done", "failed")
        .state(name="idle", output="idle")
        .state(name="researching", output="research")
        .state(name="writing", output="write")
        .state(name="done", output="done", final=True)
        .state(name="failed", output="failed", final=True)
        .initial(name="idle")
        .on(source="idle", input="started", target="researching")
        .branch(
            source="researching",
            outcomes=Alphabet.of("researched", "research_failed"),
            routes={"researched": "writing", "research_failed": "failed"},
        )
        .branch(
            source="writing",
            outcomes=Alphabet.of("written", "write_failed"),
            routes={"written": "done", "write_failed": "failed"},
        )
        .otherwise_stay()
        .build()
    )

    researching = FanOut(
        actor_class=Agent,
        count=lambda memo: memo.input()["angles"],
        make=lambda name, index, memo: Agent(
            name=name, instructions="Research one angle in one line.", turns=3
        ),
        start=lambda index, memo: Event(
            "started", payload={"prompt": f"{memo.input()['topic']}, angle {index}"}
        ),
        join=AllOf(success="completed", reached="researched", missed="research_failed"),
    )

    writing = Host(
        actor_class=Agent,
        make=lambda name, memo: Agent(name=name, instructions="Write the notes up.", turns=3),
        start=lambda memo: Event(
            "started",
            payload={"prompt": " | ".join(r.payload()["text"] for r in memo.results("researching"))},
        ),
        routes={"completed": "written", "failed": "write_failed", "overflowed": "write_failed"},
    )

    REPORT = Plan(
        definition=REPORT_MACHINE,
        stages={"researching": researching, "writing": writing},
        relay=["interrupted", "resumed"],
    )


    class Briefing(Workflow):
        @classmethod
        def plan(cls) -> Plan:
            return REPORT
    ```

    And the offline Governor, whose model wraps each prompt in `note<...>`:

    ```python
    from gvn.harness.messages import Message
    from gvn.harness.ports import Exchange, Journal, Reply
    from gvn.harness.tools import Toolbox
    from gvn.runtime.fulfillers import ModelFulfiller
    from gvn.runtime.governor import Governor
    from gvn.testing.fakes import FunctionModel, ManualClock, MemoryJournal, RecordingOutput


    def note(exchange: Exchange) -> Reply:
        return Reply(message=Message.assistant(text=f"note<{exchange.messages()[0].text()}>"))


    def governor_with(respond: Callable[[Exchange], Reply], journal: Journal) -> Governor:
        return Governor(
            fulfillers={
                "invoke_model": ModelFulfiller(model=FunctionModel(respond=respond), toolbox=Toolbox())
            },
            journal=journal,
            output=RecordingOutput(),
            clock=ManualClock(),
        )


    result = asyncio.run(
        governor_with(respond=note, journal=MemoryJournal()).deliver(
            actor=Briefing(name="report"),
            event=Event("started", payload={"topic": "Moore machines", "angles": 2}),
        )
    )
    reading = Report(outcome=result.outcome())
    print(reading.state())
    ```

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

## Judges: deciding on what a child said

A `Host` ends its stage in one of two ways, and takes exactly one of them:

- **`routes`** map each final state of the child's machine to a workflow input (as in
  [Workflows](workflows.md)). Use them when the way on depends only on how the child ended.
- **`judge`** is a kernel [Decision](decisions.md) whose outcomes are the symbols the stage
  can end with. Use it when the way on depends on data: what the agent said, which tools it
  used, how many times the stage has run.

Why would you need that? An agent that ends in `completed` may still have said "this draft
is not good enough". Routes cannot see that; a judge can. A judge that reads which tools the
child used picks them from the outcome's `"tools"` or `"attempts"` by tool, with
`calls_to(entries, tool)` or `is_call_to(entry, tool)` from `gvn.harness.tools`, which compare
[identities](tools.md#two-names-the-short-name-and-the-identity), never the short name.

When the child finishes, the judge decides on an **`Ending`**: `outcome()` is the child's
`Outcome` (its final state and payload), `memo()` is the workflow's `Memo` at that moment,
and `stage()` is the stage's name. This judge approves a draft the reviewer called good, asks
for another round otherwise, and gives up after three reviews:

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


class Verdict(Decision):
    """Approve, ask for another round, or give up after three reviews."""

    def outcomes(self) -> Alphabet:
        return Alphabet.of("approved", "revise", "give_up")

    def judge(self, ending: object) -> Symbol:
        if "LGTM" in ending.outcome().payload().get("text", ""):
            return Symbol("approved")
        if ending.memo().visits(ending.stage()) >= 3:
            return Symbol("give_up")
        return Symbol("revise")


reviewing = Host(
    actor_class=Agent,
    make=lambda name, memo: Agent(name=name, instructions="Review the draft.", turns=3),
    start=lambda memo: Event("started", payload={"prompt": "Review it."}),
    judge=Verdict(),
)
```

A judge's outcomes are checked against the machine like routes are. A judge that raises, or
answers a symbol it did not declare, is a mistake in the plan: the event that triggered it
raises, and the workflow is unchanged.

## Loops

A workflow's machine may have cycles. A cycle is an ordinary pair of transitions, so the
verifier checks it like any other: every state on it must still be able to reach a final
state. What stops a loop from running for ever is a judge that counts visits, like `Verdict`
above.

This workflow drafts, has the draft reviewed, and goes back to drafting until the reviewer
approves. First the machine: `reviewing` routes all three of `Verdict`'s outcomes, and
`revise` leads back to `drafting`.

```python
DRAFTING_MACHINE = (
    MooreBlueprint(name="drafting")
    .inputs("started", "drafted", "draft_failed", "approved", "revise", "give_up")
    .outputs("idle", "draft", "review", "done", "gave_up", "failed")
    .state(name="idle", output="idle")
    .state(name="drafting", output="draft")
    .state(name="reviewing", output="review")
    .state(name="done", output="done", final=True)
    .state(name="gave_up", output="gave_up", final=True)
    .state(name="failed", output="failed", final=True)
    .initial(name="idle")
    .on(source="idle", input="started", target="drafting")
    .branch(
        source="drafting",
        outcomes=Alphabet.of("drafted", "draft_failed"),
        routes={"drafted": "reviewing", "draft_failed": "failed"},
    )
    .branch(
        source="reviewing",
        outcomes=Verdict().outcomes(),
        routes={"approved": "done", "revise": "drafting", "give_up": "gave_up"},
    )
    .otherwise_stay()
    .build()
)
```

Then the plan. The drafter is shown every earlier review through `memo.history`, which holds
one tuple of results per finished visit of a stage:

```python
def start_drafter(memo: Memo) -> Event:
    reviews = [visit[0].payload()["text"] for visit in memo.history("reviewing")]
    return Event(
        "started", payload={"prompt": f"Draft: {memo.input()['topic']}. Reviews: {reviews}"}
    )


DRAFTING = Plan(
    definition=DRAFTING_MACHINE,
    stages={
        "drafting": Host(
            actor_class=Agent,
            make=lambda name, memo: Agent(name=name, instructions="Draft it.", turns=3),
            start=start_drafter,
            routes={"completed": "drafted", "failed": "draft_failed", "overflowed": "draft_failed"},
        ),
        "reviewing": reviewing,
    },
)


class Drafting(Workflow):
    @classmethod
    def plan(cls) -> Plan:
        return DRAFTING
```

Now run it with a reviewer that is never satisfied:

```python
def picky(exchange: Exchange) -> Reply:
    return Reply(message=Message.assistant(text="Needs work."))


essay = Drafting(name="essay")
result = asyncio.run(
    governor_with(respond=picky, journal=MemoryJournal()).deliver(
        actor=essay, event=Event("started", payload={"topic": "Moore"})
    )
)
history = result.outcome().payload()["history"]
print(result.outcome().state())
print([[review["name"] for review in visit] for visit in history["reviewing"]])
```

```text
State('gave_up')
[['essay/reviewing.1'], ['essay/reviewing.2'], ['essay/reviewing.3']]
```

The reviewer never approved, so on its third visit the judge answered `give_up`. The bound
lives in a Decision the machine must route, not in a loop counter hidden in code, so it is
recorded in the journal and visible to replay.

Every finished visit is kept, in the outcome and in the workflow's Dto. A loop bounded by a
judge stays small; a loop with no bound makes the Dto grow with every round.

## The Memo in full

Every stage function, judge and join receives a `Memo`: a read-only view of the workflow's
data. Most of its methods return `Result`s; a `Result` is the record of one finished child,
described just after the table.

| Method | Returns |
|---|---|
| `input()` | the payload of the event that started the workflow (a fresh copy) |
| `results(stage)` | the `Result`s of the stage's latest *finished* visit, in child order; `()` if none |
| `history(stage)` | one tuple of `Result`s per finished visit, in order |
| `visits(stage)` | how many times the stage has been entered, the visit in progress included |
| `expired(stage)`, `abandoned(stage)`, `trimmed(stage)` | see [Deadlines and long loops](#deadlines-and-long-loops) |

A `Result` is one finished child: its `index()` in the fan-out (0 for a hosted child), its
`name()`, its `outcome()` and its `attempt()` (1, unless a
[ForEach](#fan-out-over-items-foreach) tried its item again). It also reads like an `Outcome`
through `state()` and `payload()`. Children dropped before they finished are absent, so their
indexes are missing.

While a stage is running, `results(stage)` still shows its previous visit. A stage that is
entered again can see what it produced last time.

## Joins: when is a fan-out over?

A **join** answers with one symbol from a declared set, or `None` to keep waiting. Four ship
with gvn. Three of them are counting joins: they take what counts as success and two workflow
input symbols, `reached` (the count of successes was reached) and `missed` (it was not, and
can no longer be):

| Join | Answers `reached` | Answers `missed` |
|---|---|---|
| `AllOf(success, reached, missed)` | when every child ended in `success` | when all have ended and at least one did not |
| `AnyOf(success, reached, missed)` | as soon as one child ends in `success` | when all have ended and none did |
| `Quorum(count, success, reached, missed)` | as soon as `count` children end in `success` (see below for `wait`) | once that can no longer happen |

When a join ends a stage early, the remaining children are dropped. Their requests disappear,
and the Governor cancels their work.

### Classifying children

By default a child succeeds when its final state is named `success`. That is often too
coarse: an agent that `completed` may still have said "no". Give the join `classify=`, a
kernel `Decision` over the child's `Outcome`, and a child succeeds when the decision's answer
is named `success`. The join then counts verdicts rather than final states.

This decision reads a reviewer as in favour when it completed and its answer starts with
"yes":

```python
from gvn.harness.actor import Outcome
from gvn.kernel.symbols import State


class ReadVerdict(Decision):
    """A reviewer is in favour when it completed and its answer starts with 'yes'."""

    def outcomes(self) -> Alphabet:
        return Alphabet.of("in_favour", "against")

    def judge(self, outcome: object) -> Symbol:
        text = outcome.payload().get("text", "") if outcome.state().name() == "completed" else ""
        return Symbol("in_favour" if text.lower().startswith("yes") else "against")


print(ReadVerdict().decide(Outcome(state=State("completed"), payload={"text": "Yes, ship it."})))
```

```text
Symbol('in_favour')
```

A `Quorum` that uses it:

```python
from gvn.harness.workflow import Quorum

panel = Quorum(
    count=2, success="in_favour", reached="approved", missed="rejected", classify=ReadVerdict()
)
print(sorted(panel.outcomes().names()))
```

```text
['approved', 'rejected']
```

`panel` approves as soon as two reviewers' outcomes are classified `in_favour`, and rejects
once two can no longer be reached.

### Quorum options

`Quorum` counts in three ways, and takes two keyword options:

- `count`: an int, `Majority()` (more than half of the stage's children) or
  `AtLeast(fraction)` (at least that fraction, rounded up: `AtLeast(0.5)` is "at least
  half"). The last two are worked out from the number of children each visit, so a fan-out
  whose size comes from data still has a sensible quorum.
- `wait=True`: reaching the count does not end the stage; the join waits for every child, so
  every result is collected, and then answers `reached`. It still answers `missed` as soon as
  the count becomes unreachable.
- `veto={verdict: symbol}`: as soon as a finished child's verdict is a veto verdict, the stage
  ends with that symbol and the rest are dropped.

The join ends only once its answer is **settled**: it never answers what a child still
running could change. With a veto whose symbol is not `missed`, an unreachable count
therefore waits for every child before answering `missed`, because a later veto would
change the answer.

```python
from gvn.harness.workflow import AtLeast

review = Quorum(
    count=AtLeast(0.5),
    success="in_favour",
    reached="approved",
    missed="rejected",
    classify=ReadVerdict(),
    wait=True,
    veto={"against": "vetoed"},
)
print(sorted(review.outcomes().names()))
```

```text
['approved', 'rejected', 'vetoed']
```

Here half the reviewers must be in favour, everyone is heard, and any one against vetoes.

### Worst: the worst verdict wins

The fourth join, `Worst(order, classify=None, early=())`, lets the worst verdict win. `order`
lists `(verdict, symbol)` pairs, worst first; a child's verdict is its final state's name or,
with `classify=`, the name of the decision's answer. The join waits for every child and
answers the symbol of the worst verdict present, unless a child's verdict is in `early`: then
the stage ends at once with that verdict's symbol. A veto is one line:

```python
from gvn.harness.workflow import Worst

worst = Worst(
    order=[("veto", "vetoed"), ("against", "rejected"), ("in_favour", "approved")],
    early=["veto"],
)
print(sorted(worst.outcomes().names()))
```

```text
['approved', 'rejected', 'vetoed']
```

Every symbol in `order` must be routed by the plan, and the plan checks that the verdicts
cover every final state of the stage's children (or every outcome of `classify`).

### Your own join

To write your own join, subclass `Join` and implement `outcomes()` and
`judge(finished, total, memo)`: `finished` is the tuple of finished children's `Outcome`s in
child order, `total` the number of children, and `memo` the workflow's `Memo`. Return a
symbol to end the stage, or `None` to keep waiting. Once every child has finished, you must
return a symbol; `Join.decide` raises `UndeclaredOutcome` if you do not.

## Deadlines and long loops

`Host`, `FanOut`, `ForEach`, and `Parallel` accept a `deadline=` function returning `At(t)`
or `After(seconds)`. Set `expired=` to the symbol that ends the stage at the deadline.
The runtime drops children still running and cancels their pending work.
`memo.expired(stage)` and `memo.abandoned(stage)` record which visits expired and what
each dropped child was waiting for. [Time](time.md) explains deadlines in full.

A loop keeps every finished visit. `Host(..., retain=N)` keeps full outcomes for only the
last N visits of the stage; earlier ones keep each child's index, name and final state, and
`memo.trimmed(stage)` says how many were trimmed. That shrinks a long loop's stored state; a
trimmed visit still keeps its index, name and final state, about 90 bytes.

## Fan-out over items: `ForEach`

A `FanOut` counts its children; `count` returns a number and your `make` maps each index back
to the thing it works on. When the work is "one child per item of this list", `ForEach` takes
the list itself, and adds two things a list of real work needs: a **window** (at most so many
children at once) and **retries** (a failed item is tried again, a bounded number of times).

Here the researchers work on named angles from the input, two at a time, and an angle whose
agent failed gets one more attempt:

```python
from gvn.harness.workflow import ForEach, Retry

researching_each = ForEach(
    actor_class=Agent,
    items=lambda memo: memo.input()["angles"],
    make=lambda name, angle, memo: Agent(
        name=name, instructions="Research one angle in one line.", turns=3
    ),
    start=lambda angle, memo: Event(
        "started", payload={"prompt": f"{memo.input()['topic']}, {angle}"}
    ),
    join=AllOf(success="completed", reached="researched", missed="research_failed"),
    retry=Retry(attempts=2, on=["failed"]),
    window=2,
)

EACH_REPORT = Plan(
    definition=REPORT_MACHINE,
    stages={"researching": researching_each, "writing": writing},
    relay=["interrupted", "resumed"],
)


class AngleBriefing(Workflow):
    @classmethod
    def plan(cls) -> Plan:
        return EACH_REPORT


result = asyncio.run(
    governor_with(respond=note, journal=MemoryJournal()).deliver(
        actor=AngleBriefing(name="angles"),
        event=Event("started", payload={"topic": "Moore machines", "angles": ["history", "uses"]}),
    )
)
print([child.name() for child in Report(outcome=result.outcome()).results("researching")])
```

```text
['angles/researching.1.0.1', 'angles/researching.1.1.1']
```

The rules, one by one:

- **Items come from trusted data.** `items(memo)` reads the input or an earlier stage's
  results, never text a model or a person wrote. It is called on entering the stage, and
  again when a stored run is revived during the stage; the list must then have the same
  fingerprint (a short code computed from the list's content), or the run refuses to load. So it must depend only on the memo.
- **Names say item and attempt.** A child is `<workflow>/<stage>.<visit>.<index>.<attempt>`:
  `index` is the item's place in the list, `attempt` counts from 1.
- **A retry is a new child.** `Retry(attempts=..., on=[...], classify=None)`: when a child
  ends with a verdict in `on` (its final state's name, or `classify`'s answer) and the item
  has attempts left, a new child starts at once in its place. Its requests have new ids, so
  its tool calls have new [idempotency keys](run-context.md#idempotency-keys) (the stable
  key a tool uses to recognise a repeated call): a retry is visibly a new attempt. A request
  re-issued after a crash keeps its child's name and so its key.
- **The join sees final results only**, one per item, in item order, with `total` the number
  of items. Every join on this page works unchanged.
- **The window.** With `window=N`, items start in list order and the next one starts when an
  item is final. When the join ends the stage early, items not started never start.
- **Item count.** `limit` (default 1,000) caps the items; more is a plan error. No items is a
  plan error unless `empty=` names the symbol the stage then ends with.
- **What is stored**: each finished item's `Result` (with its `attempt`), the running
  children, and a 64-character fingerprint of the list, never the items. Measured with a
  payload-free child, about 115 bytes per finished item besides the child's own outcome.
- **Deadlines and `retain`** work as for the other stages. At the deadline the attempts still
  running are cut and recorded as abandoned (their names say which attempt), items not started
  are in neither the results nor the abandoned list, and finished items keep their results.
  `retain` trims old visits to names, states and attempts.

The plan checks a `ForEach` as it checks a `FanOut` (every join answer, `empty` and `expired`
routed; `Worst` and `Quorum` verdicts possible), and also that every `Retry` verdict is one the
children can have. The guide [Fan-out over items, with retries](../guides/items-and-retries.md)
runs one end to end, with a payment service that fails once.

## Different kinds at once: `Parallel`

A `FanOut` and a `ForEach` make children of one class. When one step needs an agent, an
errand and a question to a person at the same time, `Parallel` runs a fixed list of
**branches**, each with its own class. A `Branch` turns its child's ending into a
**verdict**, through `verdicts` (a mapping of final state to verdict) or `classify` (a Decision
over the outcome), and one join decides on the verdicts.

Here a reviewer agent (classified by `ReadVerdict` from [above](#classifying-children)) runs
alongside a whole `Briefing` workflow, a different kind of child:

```python
from gvn.harness.workflow import Branch, Parallel

second_opinion = Parallel(
    branches=[
        Branch(
            actor_class=Agent,
            make=lambda name, memo: Agent(name=name, instructions="Say yes or no.", turns=3),
            start=lambda memo: Event("started", payload={"prompt": "Yes, ship it?"}),
            classify=ReadVerdict(),
        ),
        Branch(
            actor_class=Briefing,
            make=lambda name, memo: Briefing(name=name),
            start=lambda memo: Event("started", payload=memo.input()),
            verdicts={"done": "in_favour", "failed": "against"},
        ),
    ],
    join=AllOf(success="in_favour", reached="researched", missed="research_failed"),
)
summing_up = Host(
    actor_class=Agent,
    make=lambda name, memo: Agent(name=name, instructions="Sum up.", turns=3),
    start=lambda memo: Event("started", payload={"prompt": "Sum up both opinions."}),
    routes={"completed": "written", "failed": "write_failed", "overflowed": "write_failed"},
)
OPINION = Plan(
    definition=REPORT_MACHINE, stages={"researching": second_opinion, "writing": summing_up}
)


class Opinion(Workflow):
    @classmethod
    def plan(cls) -> Plan:
        return OPINION


def says_yes(exchange: Exchange) -> Reply:
    return Reply(message=Message.assistant(text=f"yes: {exchange.messages()[0].text()}"))


result = asyncio.run(
    governor_with(respond=says_yes, journal=MemoryJournal()).deliver(
        actor=Opinion(name="opinion"),
        event=Event("started", payload={"topic": "Moore machines", "angles": 1}),
    )
)
opinions = Report(outcome=result.outcome())
print(opinions.state(), [child.state().name() for child in opinions.results("researching")])
```

```text
State('done') ['completed', 'done']
```

The join saw two `in_favour` verdicts; the results keep each child's real outcome. Children are
named by branch index, as in a `FanOut` (`opinion/researching.1.0`, `opinion/researching.1.1`).
Because the join reads verdicts, it must not `classify` itself: the plan refuses that, and it
checks a `Worst` order or a `Quorum` veto against every verdict the branches can give.
`deadline`/`expired` work as for a `FanOut`. The guide
[Different kinds of child in one stage](../guides/mixed-stages.md) runs an agent, an errand
and an inquiry together.

For kinds chosen by data, a stage that needs one child per item, each of the class its item
names (the [fleet campaign](../domains/software.md)'s builds, one per repository, each on its
own stack), wraps them in one class of its own.

## Compensation the verifier checks

A **saga** is a sequence of steps with effects in which each effect has a **compensation**, a
later step that undoes it, and a run that cannot finish undoes what it did, latest first. A
plan declares the pairs with `Compensate` and names the final states that mean "undone"; the
plan is then refused unless every way to those states passes through the compensations, in
reverse order.

Here publishing a report is undone by retracting it, and `withdrawn` means "undone":

```python
from gvn.harness.workflow import Compensate, PlanRejected
from gvn.kernel.definition import Definition


def publishing_machine(when_rejected: str) -> Definition:
    return (
        MooreBlueprint(name="publishing")
        .inputs("started", "posted", "post_failed", "approved", "rejected")
        .inputs("retracted", "retract_failed")
        .outputs("idle", "post", "review", "retract", "live", "withdrawn", "needs_person")
        .state(name="idle", output="idle")
        .state(name="posting", output="post")
        .state(name="reviewing", output="review")
        .state(name="retracting", output="retract")
        .state(name="live", output="live", final=True)
        .state(name="withdrawn", output="withdrawn", final=True)
        .state(name="needs_person", output="needs_person", final=True)
        .initial(name="idle")
        .on(source="idle", input="started", target="posting")
        .on(source="posting", input="posted", target="reviewing")
        .on(source="posting", input="post_failed", target="retracting")
        .on(source="reviewing", input="approved", target="live")
        .on(source="reviewing", input="rejected", target=when_rejected)
        .on(source="retracting", input="retracted", target="withdrawn")
        .on(source="retracting", input="retract_failed", target="needs_person")
        .otherwise_stay()
        .build()
    )


def agent_stage(done: str, failed: str) -> Host:
    return Host(
        actor_class=Agent,
        make=lambda name, memo: Agent(name=name, instructions="Do your step.", turns=3),
        start=lambda memo: Event("started", payload={"prompt": "Go."}),
        routes={"completed": done, "failed": failed, "overflowed": failed},
    )


PUBLISHING_STAGES = {
    "posting": agent_stage("posted", "post_failed"),
    "reviewing": agent_stage("approved", "rejected"),
    "retracting": agent_stage("retracted", "retract_failed"),
}
RETRACT = Compensate(stage="posting", by="retracting", done=["retracted"])

try:
    Plan(
        definition=publishing_machine(when_rejected="withdrawn"),
        stages=PUBLISHING_STAGES,
        compensations=[RETRACT],
        undone=["withdrawn"],
    )
except PlanRejected as rejected:
    print(rejected.problems()[0])
```

```text
compensation: uncompensated-path posting/withdrawn: 'posting' is not compensated on this way to the undone final state 'withdrawn': idle --started--> posting --posted--> reviewing --rejected--> withdrawn. After 'posting', the way must leave 'retracting' on 'retracted'.
```

A rejected report would be marked withdrawn while still posted. Route `rejected` to
`retracting` and the plan builds:

```python
PUBLISHING = Plan(
    definition=publishing_machine(when_rejected="retracting"),
    stages=PUBLISHING_STAGES,
    compensations=[RETRACT],
    undone=["withdrawn"],
)
print(PUBLISHING.compensations())
```

```text
(Compensate('posting', by='retracting', done=['retracted']),)
```

The parts:

- `Compensate(stage, by, done, untouched=())`: `stage` has effects; `by` undoes them, and has
  done so when it ends with a `done` symbol. `untouched` names the symbols `stage` ends with
  only when it changed nothing (a call that never ran), so that visit needs no undo. Neither
  may be a stage's `expired` symbol: work cut at a deadline may have done anything.
- `undone`: the final states that mean "this run was undone". Ends that are not undone
  (`needs_person` here, when the retraction itself fails) are not constrained.
- With several pairs, the latest effect must be undone first; a walk that undoes an earlier
  one while a later one is outstanding, or enters an earlier effect stage again meanwhile, is
  refused (`unordered-compensation`).

How it is proved. The kernel verifier's `examine_compensations` walks the definition's graph,
keeping the effects still to undo, in order, along every walk from the initial state. Every
run is such a walk, so what holds for all walks holds for all runs, and a walk that no run
could take, because a judge never gives that answer there, is checked too. You supply which
stages have effects, and that the compensating stage really undoes them: the verifier takes
`done` and `untouched` as given, as it takes routes. The guide
[Undo that the verifier checks](../guides/compensation.md) has the full list and runs a saga.

## Nesting

A `Workflow` is an `Actor`, so a stage can host a workflow as easily as an agent. Its routes
name the hosted workflow's final states. Here `Publish` hosts the whole `Briefing` as one
stage:

```python
PUBLISH_MACHINE = (
    MooreBlueprint(name="publish")
    .inputs("started", "reported", "report_failed")
    .outputs("idle", "report", "published", "failed")
    .state(name="idle", output="idle")
    .state(name="reporting", output="report")
    .state(name="published", output="published", final=True)
    .state(name="failed", output="failed", final=True)
    .initial(name="idle")
    .on(source="idle", input="started", target="reporting")
    .branch(
        source="reporting",
        outcomes=Alphabet.of("reported", "report_failed"),
        routes={"reported": "published", "report_failed": "failed"},
    )
    .otherwise_stay()
    .build()
)

PUBLISH = Plan(
    definition=PUBLISH_MACHINE,
    stages={
        "reporting": Host(
            actor_class=Briefing,
            make=lambda name, memo: Briefing(name=name),
            start=lambda memo: Event("started", payload=memo.input()),
            routes={"done": "reported", "failed": "report_failed"},
        )
    },
    relay=["interrupted", "resumed"],
)


class Publish(Workflow):
    @classmethod
    def plan(cls) -> Plan:
        return PUBLISH
```

Start it by hand, without a Governor, and look at what it wants done:

```python
weekly = Publish(name="weekly")
weekly.handle(Event("started", payload={"topic": "Mealy machines", "angles": 2}))
print([request.request_id() for request in weekly.pending()])
```

```text
['weekly/reporting.1/researching.1.0/3', 'weekly/reporting.1/researching.1.1/3']
```

Names compose: the inner researchers live at `weekly/reporting.1/researching.1.0`, and their
request ids start with that path. The whole tree is still one actor with one journal and one
Dto. Because `Publish` relays `interrupted` and `Briefing` relays it too, one
`Event("interrupted")` reaches every agent in the tree.

## Model roles {#model-roles}

An agent can name a **model role**, such as `"summariser"`, that the runtime wiring maps to
a model ([A model per role](../guides/vendors.md#a-model-per-role)). Before the Governor
drives any actor, it asks the actor which roles it may need (`model_roles()`) and refuses
the call when the wiring lacks one, so a missing model shows up before the run starts, not
in the middle of it. A workflow builds its children only as it reaches their stages, so it
answers from its plan: `Plan(..., model_roles=[...])` declares the roles its children, and
anything beneath them, may ask for, and `Workflow.model_roles()` returns them.

The declaration is enforced where children are made. A stage that builds a child naming a
role the plan does not declare raises `ValueError` naming the workflow, the stage, the child
and the roles. It is code, not data, so it happens the same way every time the stage is
reached, and a test that reaches the stage finds it. Here a researching agent names a
`"summariser"` role; the first plan does not declare it and the second does:

```python
summarising = Host(
    actor_class=Agent,
    make=lambda name, memo: Agent(name=name, instructions="Summarise.", model_role="summariser"),
    start=lambda memo: Event("started", payload={"prompt": memo.input()["topic"]}),
    routes={"completed": "researched", "failed": "research_failed", "overflowed": "research_failed"},
)
UNDECLARED = Plan(definition=REPORT_MACHINE, stages={"researching": summarising, "writing": writing})
DECLARED = Plan(
    definition=REPORT_MACHINE,
    stages={"researching": summarising, "writing": writing},
    model_roles=["summariser"],
)


class Undeclared(Workflow):
    @classmethod
    def plan(cls) -> Plan:
        return UNDECLARED


class Declared(Workflow):
    @classmethod
    def plan(cls) -> Plan:
        return DECLARED


try:
    Undeclared(name="draft").handle(Event("started", payload={"topic": "Moore machines"}))
except ValueError as error:
    print(error)
declared = Declared(name="final")
declared.handle(Event("started", payload={"topic": "Moore machines"}))
print(sorted(declared.model_roles()), declared.state())
```

```text
workflow 'draft', stage 'researching': child 'draft/researching.1' names model roles ['summariser'] that plan 'report' does not declare (Plan(model_roles=...) declares [])
['summariser'] State('researching')
```

A workflow that hosts another workflow declares the inner workflow's roles too, since the
inner one is a child whose `model_roles()` are its own plan's. The declaration lives in the
plan, which is code, so it never reaches the durable form.

## Tools {#declared-tools}

Tools are checked before the run in the same way. Every actor answers `tool_identities()`:
the [identities](tools.md#two-names-the-short-name-and-the-identity) of every tool it may
offer a model or ask to run. Before the Governor drives an actor, its tool and model
fulfillers check that their toolbox holds each of them, and the Governor refuses the call
with `Unfulfillable` when one is missing
([checked before the run starts](tools.md#checked-before-the-run-starts)). A workflow's
children do not exist yet when the run starts, so, as for roles, the plan declares their
tools: `Plan(..., tools=[...])` lists every tool its children, and anything beneath them, may
be offered or call, as Tool objects (or a `Toolbox`). `Workflow.tool_identities()` returns
their identities, and those are what the Governor checks against its toolbox. Declare only
the tools the children use: every declared tool must be in the runtime's toolbox.

The declaration is enforced where children are made, as for roles: a stage that builds a
child offered a tool the plan does not declare raises `ValueError` naming the workflow, the
stage, the child and the identities. Here the researching agent is offered a web `search`;
the first plan declares nothing, the second declares the web search and a library search
that another stage could use. Both have the short name `search`: children of one plan may use
same-named tools from different places, since only their identities are kept, and each child
is still offered one tool per short name. The two `StubTool`s take a `namespace=` to stand
for two such tools:

```python
from gvn.kernel.schema import Record, Text
from gvn.testing.fakes import StubTool

web_search = StubTool("search", Record({"query": Text()}), namespace="web")
library_search = StubTool("search", Record({"query": Text()}), namespace="library")

searching = Host(
    actor_class=Agent,
    make=lambda name, memo: Agent(name=name, instructions="Search.", tools=[web_search]),
    start=lambda memo: Event("started", payload={"prompt": memo.input()["topic"]}),
    routes={"completed": "researched", "failed": "research_failed", "overflowed": "research_failed"},
)
TOOLS_UNDECLARED = Plan(
    definition=REPORT_MACHINE, stages={"researching": searching, "writing": writing}
)
TOOLS_DECLARED = Plan(
    definition=REPORT_MACHINE,
    stages={"researching": searching, "writing": writing},
    tools=[web_search, library_search],
)


class ToolsUndeclared(Workflow):
    @classmethod
    def plan(cls) -> Plan:
        return TOOLS_UNDECLARED


class ToolsDeclared(Workflow):
    @classmethod
    def plan(cls) -> Plan:
        return TOOLS_DECLARED


try:
    ToolsUndeclared(name="draft").handle(Event("started", payload={"topic": "Moore machines"}))
except ValueError as error:
    print(error)
searched = ToolsDeclared(name="final")
searched.handle(Event("started", payload={"topic": "Moore machines"}))
print(sorted(searched.tool_identities()), searched.state())
```

```text
workflow 'draft', stage 'researching': child 'draft/researching.1' names tools ['web.search'] that plan 'report' does not declare (Plan(tools=...) declares [])
['library.search', 'web.search'] State('researching')
```

A workflow that hosts another workflow declares the inner workflow's tools too, since the
inner one is a child whose `tool_identities()` are its own plan's. Like the roles, the
declaration is code and never reaches the durable form.

## Internal symbols

The symbols a workflow's stages produce (every route value, every judge outcome, every join
outcome and every `empty` and `expired` symbol) are **internal**. Only the workflow itself
decides them, from its children's outcomes. Delivering one from outside, where it would take
a declared step, raises `ValueError` and changes nothing:

```python
draft = Briefing(name="draft")
draft.handle(Event("started", payload={"topic": "Moore machines", "angles": 1}))
try:
    draft.handle(Event("researched"))
except ValueError as error:
    print(error)
```

```text
'researched' is produced by stage 'researching', it cannot be delivered from outside
```

Where the symbol would not take a declared step it is simply rejected, like any other
unexpected input. This is the same rule the [reference agent](reference-agent.md) applies to
its own decisions (`within_budget`, `answered` and so on): nobody outside can claim that
research succeeded.

## Atomicity

As for every actor, an event that raises or is rejected changes nothing, the children
included. In a workflow, that covers plan code too:

- A judge, a join, a `classify` Decision or a stage function that raises while an event is
  handled is a mistake in the plan. The error propagates and the workflow is exactly as it
  was before the event.
- A child that rejects its opening event, or raises on it, is also a mistake in the plan:
  `handle` raises `ValueError` naming the stage, and changes nothing.

The workflow keeps this cheap. Before a child handles an event, its Dto is saved only when
plan code could run if the child finishes. Routes and the built-in joins without `classify`
cannot fail, so for them nothing needs saving.

## The outcome

When the workflow reaches a final state, its outcome payload is:

```text
{"input":   <the starting payload>,
 "history": {<stage>: [[{"index": i, "name": <child name>, "outcome": <Outcome.Dto plain>}, ...], ...]}}
```

`history` holds every finished visit of every stage, in order, each as the `Result`s of its
children in child order. Fan-out children that were dropped before finishing are absent;
`index` says which are present. The outcome is built once, when first asked for, and then
shared.

If visits expired, the payload also includes `expired` (visit numbers by stage) and
`abandoned` (dropped children and their pending request kinds, grouped by expired visit).
If earlier visits were trimmed, `trimmed` holds the number trimmed per stage.

Read it with `Report`, which `gvn.harness.workflow` provides for exactly this: `state()`,
`input()`, `stages()`, `results(stage)` for the latest finished visit, `history(stage)` for
all of them, and `report(stage, index=0)` for the `Report` of a child that was itself a
workflow. `expired(stage)`, `abandoned(stage)`, and `trimmed(stage)` read the optional
visit metadata. Using `reading` from the top of this page:

```python
print(reading.stages(), [child.name() for child in reading.results("researching")])
print([[child.name() for child in visit] for visit in reading.history("writing")])
```

```text
('researching', 'writing') ['report/researching.1.0', 'report/researching.1.1']
[['report/writing.1']]
```

A parent workflow that hosts this one sees that payload in its own `Result`, and
`Report(...).report(stage)` opens it. `Outcome.view()` (and `Result.view()`) give a read-only
form of a payload without copying it, for code that only reads.

## What it costs

A workflow keeps what it needs to undo an event only when the event can finish the child it
is for and plan code could run because of that. It asks the child with
`Actor.settles(event)` ("could handling this event leave you finished?"): an `Agent` answers
from its definition, a workflow by asking its own child and checking where that child's
ending could lead. So an event deep in a tree costs about what it costs at the top, and each
level keeps its children's wanted requests from their last reaction instead of walking the
tree again.

## What the durable form holds

One `Workflow.Dto` class serves every workflow. It holds:

| Field | What it is |
|---|---|
| `name` | the workflow's name |
| `plan` | the plan's name, checked on revival |
| `machine` | the machine's [position](machines.md#positions): definition fingerprint, state, step count |
| `input` | the starting payload (`None` until the workflow leaves its initial state) |
| `history` | every finished visit of every stage, as `Result` Dtos |
| `children` | the active children of the current stage: stage, index, child total, each child's own plain Dto, and its `attempt` when a ForEach retried it |
| `finished` | the `Result`s already recorded in the current visit |
| `items` | only while a ForEach visit runs: the fingerprint of its item list |
| `deadline` | the current visit's deadline state, absolute time when known, and requested delay for `After` |
| `expired`, `abandoned` | visit numbers that expired and the active children dropped at each deadline |
| `trimmed` | count by stage of earlier visits that keep only child identity and final state |
| `settings` | only when the plan, or a workflow beneath it, declares [settings](#settings): the plan's settings fingerprint |

The plan itself is not in the Dto: it is code, and the class supplies it. `from_dto` raises
`TypeError` for a Dto of another class and `ValueError` for a Dto made by a different plan
(another plan name, or a machine position on a different definition), and `SettingsMismatch`
for a Dto stored under other settings, so a run never resumes silently on a changed plan.

### Settings: what the plan's code was built from {#settings}

A stored run is continued by rebuilding the workflow from its Dto and the plan the class
supplies. Two things must then be the same as when the run began: the machine and the code
around it. The machine is covered already: the Dto holds the machine definition's
**fingerprint**, a short code computed from its content, and a different definition is
refused. The code around it, which is the stage functions (`make`, `start`), the judges,
the joins and the deadlines, is ordinary Python and cannot be fingerprinted. So the plan
declares, as `settings=`, the plain data that code was built from: the instructions a
stage gives its agent, the conventions, limits and model choices it puts into the run, or
just a version string for code that holds such things itself. Settings are any plain JSON
data.

A workflow stores the plan's **settings fingerprint**, `plan.settings_fingerprint()`: a
fingerprint of the plan's settings together with the settings fingerprint of every workflow
class beneath it (hosted, fanned out, or in a branch of a `Parallel`). A change of settings
deep in a stage the run has not reached yet therefore changes the fingerprint of every plan
above it. A stored workflow revives only under the same fingerprint; any other raises
`SettingsMismatch`, a `ValueError`, before anything of the stored run is rebuilt. Equal
settings give equal fingerprints whatever the order of their keys. A plan with no settings,
and none beneath it, has no fingerprint and stores nothing extra.

You are responsible for the link between settings and code: pass, as settings, the data your
stage functions read, and read it from the same value. gvn compares the settings, not the
code, so code changed without its settings changing is not seen.

Here a plan's stage reads its instructions from the conventions it was built with, and
declares the same conventions as settings. A stored run revives under the plan it began on,
and is refused under a plan built with other conventions:

```python
import json
import typing

from gvn.harness.agent import Agent
from gvn.harness.events import Event
from gvn.harness.workflow import Host, SettingsMismatch


def drafting_class(conventions: dict[str, typing.Any]) -> type[Workflow]:
    machine = (
        MooreBlueprint("drafting")
        .inputs("started", "done", "failed")
        .outputs("idle", "draft", "finished", "broken")
        .state("idle", output="idle")
        .state("drafting", output="draft")
        .state("finished", output="finished", final=True)
        .state("broken", output="broken", final=True)
        .initial("idle")
        .on("idle", "started", "drafting")
        .branch("drafting", Alphabet.of("done", "failed"), {"done": "finished", "failed": "broken"})
        .otherwise_stay()
        .build()
    )
    stage = Host(
        Agent,
        make=lambda name, memo: Agent(name, conventions["instructions"], turns=2),
        start=lambda memo: Event("started", {"prompt": "go"}),
        routes={"completed": "done", "failed": "failed", "overflowed": "failed"},
    )
    plan = Plan(machine, {"drafting": stage}, settings=conventions)

    class Drafting(Workflow):
        @classmethod
        def plan(cls) -> Plan:
            return plan

    return Drafting


Gentle = drafting_class({"instructions": "Polish it gently."})
Blunt = drafting_class({"instructions": "Rewrite it from scratch."})

stored = json.dumps(Gentle("memo-1").to_dto().to_plain())
print(Gentle.from_dto(Gentle.Dto.from_plain(json.loads(stored))).name())
try:
    Blunt.from_dto(Blunt.Dto.from_plain(json.loads(stored)))
except SettingsMismatch as refused:
    print("refused:", type(refused).__name__)
```

```text
memo-1
refused: SettingsMismatch
```

Here the `weekly` workflow from [Nesting](#nesting) goes through JSON and back:

```python
import json

stored = json.dumps(weekly.to_dto().to_plain())
again = Publish.from_dto(Publish.Dto.from_plain(json.loads(stored)))
print(again.active(), again.pending() == weekly.pending())
```

```text
('weekly/reporting.1',) True
```

The revived workflow is at the same stage and wants exactly the same work.

## Recap

- A `judge` ends a `Host` stage on what the child said; its outcomes are routed like any
  others, and a judge that counts visits bounds a loop where replay can see it.
- The `Memo` gives every stage function the starting input, every finished visit and how
  many visits there have been.
- Joins: `AllOf`, `AnyOf`, `Quorum` (with `Majority`, `AtLeast`, `wait` and `veto`), `Worst`,
  or your own `Join`. A join answers only once its answer is settled.
- Deadlines end a stage with an `expired` symbol; `retain` trims old visits of a long loop.
- `ForEach` runs one child per item, with a window and bounded retries (each a new child with
  new keys); `Parallel` runs children of different kinds and joins their verdicts.
- `Compensate` and `undone` let the verifier prove every way to an undone end compensates,
  latest first.
- Workflows nest; names and relayed events compose through the tree.
- A plan declares the model roles and the tools its children may use
  (`Plan(model_roles=..., tools=...)`), so the runtime is checked before the run starts.
- Stage symbols are internal, events are atomic, and the Dto refuses a changed plan.

**Next:** [Harnesses](harnesses.md), how a whole job is packaged and run by name.
