# Workflows

**What you will learn:** how to make several agents work together as one run: research a
topic with a few agents at once, then hand their notes to a writer. You will build a small
workflow step by step, run it, and read what it recorded.

**Read first:** [Machines](machines.md), [Decisions](decisions.md),
[Actors and events](actors-and-events.md), [The reference agent](reference-agent.md) and
[The Governor](governor.md). **Time:** about 25 minutes for this page;
[Workflows in depth](workflows-in-depth.md) covers the rest.

## Where this sits

So far every run had one actor: an agent or an errand, driven by the Governor
([the big picture](index.md#picture-1-the-loop-that-runs)). A **workflow** is still one
actor in that loop, in the harness layer, but it is an actor made of other actors. The
Governor hands every event to the workflow; the workflow passes it to the right child and
collects the children's requests as its own. The Governor never needs to know there is a
tree:

```mermaid
flowchart LR
    governor["Governor"]
    subgraph wf ["Workflow: one actor"]
        direction TB
        control["its own verified machine:<br/>which stage now"]
        child1["child actor<br/>(an agent)"]
        child2["child actor<br/>(an agent, an errand…)"]
        control --> child1
        control --> child2
    end
    governor -- "events" --> wf
    wf -- "requests from its children" --> governor
```

The rest of this page goes one level down at a time: the problem a workflow solves, who owns
what, then a small workflow built in six steps.

## The problem: many agents, one run

One agent answers one question. Real jobs are often several: three researchers look at a
topic from different angles at the same time, then a writer turns their notes into a report.
You could glue that together with `asyncio.gather` and a few `if`s, but then the glue is the
part nobody verified. What if one researcher fails? What if the process dies after two of
the three have answered? Can you replay the run later and get the same report?

A **workflow** is gvn's answer. It is an [actor](actors-and-events.md) made of other actors.
Its own control machine moves between **stages**: a stage runs one child actor, or several at
once. When the children finish, the workflow's machine moves on.

```mermaid
stateDiagram-v2
    [*] --> idle
    idle --> researching : started
    researching --> writing : researched
    researching --> failed : research_failed
    writing --> done : written
    writing --> failed : write_failed
    done --> [*]
    failed --> [*]
```

In `researching`, two researcher agents run side by side. In `writing`, one writer agent
reads their notes. The children live *inside* the workflow: the whole tree is one
[durable object](durable-objects.md) with one journal (the record of every event, which the
[Governor](governor.md) keeps). So a waiting workflow costs nothing, and a recorded run
replays the same way every time, even though its children ran at the same time.

This page builds that report workflow from `gvn.harness.workflow` in six steps.

## Who owns what

Four objects take part, and it helps to know which one owns what before meeting them in
code:

- The **definition** is the workflow's own verified machine (a [definition](machines.md), as
  on every earlier page): which stages exist and where each way of ending one leads.
- A **stage recipe** says how to create and start the children of one stage: `Host` for one
  child (step 2), `FanOut` for several of one class (step 3). A recipe is not itself a
  running child.
- The **plan** (step 4) pairs states of the definition with stage recipes.
- A **workflow instance** owns one run: its machine's current state, the input it was
  started with, its active children and the results of finished stages.

```mermaid
flowchart LR
    P["Plan: shared code and stage recipes"] -.->|"supplies behavior"| W["Workflow instance: one run"]
    W -->|"owns"| M["Current machine position"]
    W -->|"owns while researching"| C["Researcher actors"]
    W -->|"keeps"| H["Starting input and stage results"]
    W -->|"to_dto()"| D["One saved tree"]
```

Only the workflow instance's state goes into the saved tree. Parent code should use a
child's agreed starting input and result, rather than depending on its private state or
internal stage names. The examples here use the **`Memo`** (the workflow's read-only record of
its starting input and earlier stage results, step 2) to connect nearby stages; the
[large-harness guide](../guides/large-harnesses.md) explains where to place a stronger
application boundary as those stages grow.

## Step 1: the control machine

A workflow's machine is an ordinary Moore definition, one where each state names its output
(see [Machines](machines.md#two-styles-moore-and-mealy)). Each
stage is a state. The ways a stage can end are input symbols, declared with `branch` so the
verifier holds you to every one of them: `branch` records that the state must route each
listed outcome, and a missing route becomes an `unmet-obligation` finding. `Alphabet.of`
makes the fixed set of outcomes (both are explained in [Decisions](decisions.md)).

```python
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()
)
print(REPORT_MACHINE.name(), sorted(state.name() for state in REPORT_MACHINE.finals()))
```

```text
report ['done', 'failed']
```

Notice that the machine knows nothing about agents. It only says that `researching` ends in
one of two ways and where each leads. What runs *inside* each state comes next.

## Step 2: a stage with one child (`Host`)

A **`Host`** stage runs one child actor. You give it four things:

- `actor_class`: the child's class, here the [reference `Agent`](reference-agent.md) (its
  `turns` argument caps how many model calls it may make);
- `make(name, memo)`: a function that makes the child. It must return an instance of
  `actor_class` with exactly the name it was given;
- `start(memo)`: a function that makes the child's opening event;
- `routes`: how each way the child can end becomes a workflow input.

Both functions receive the workflow's **`Memo`**, a read-only view of the workflow's data:
what the workflow was started with, and what earlier stages produced. Here the writer reads
the researchers' notes from it:

```python
from gvn.harness.agent import Agent
from gvn.harness.events import Event
from gvn.harness.workflow import Host, Memo


def make_writer(name: str, memo: Memo) -> Agent:
    return Agent(name=name, instructions="Write the notes up in one line.", turns=3)


def start_writer(memo: Memo) -> Event:
    notes = " | ".join(result.payload()["text"] for result in memo.results("researching"))
    return Event("started", payload={"prompt": notes})


writing = Host(
    actor_class=Agent,
    make=make_writer,
    start=start_writer,
    routes={"completed": "written", "failed": "write_failed", "overflowed": "write_failed"},
)
```

`routes` maps each final state of the child's machine to a workflow input: an agent that ends
in `completed` makes the stage end with `written`. An agent has three final states:
`completed`, `failed` and `overflowed` (its conversation no longer fits the share of its
model's context window it may use; see [Context management](context-management.md)). Here that counts as a failed write. `Host`
checks, when you construct it, that `routes` names exactly the final states of
`Agent.definition()`. Leave one out and it raises
`ValueError`, so a way for the child to end can never go unhandled.

Routes are right when the way on depends only on *how* the child ended. When it depends on
*what* the child said, you give the `Host` a `judge` instead; see
[Judges](workflows-in-depth.md#judges-deciding-on-what-a-child-said).

## Step 3: a stage with several children (`FanOut`)

A **`FanOut`** stage runs several children of one class at once. It takes:

- `count(memo)`: how many children;
- `make(name, index, memo)`: makes child number `index` (counting from 0);
- `start(index, memo)`: makes that child's opening event;
- `join`: decides when the stage is over, and how it ended.

```python
from gvn.harness.workflow import AllOf, FanOut


def make_researcher(name: str, index: int, memo: Memo) -> Agent:
    return Agent(name=name, instructions="Research one angle in one line.", turns=3)


def start_researcher(index: int, memo: Memo) -> Event:
    return Event("started", payload={"prompt": f"{memo.input()['topic']}, angle {index}"})


researching = FanOut(
    actor_class=Agent,
    count=lambda memo: memo.input()["angles"],
    make=make_researcher,
    start=start_researcher,
    join=AllOf(success="completed", reached="researched", missed="research_failed"),
)
```

The number of researchers comes from the data the workflow was started with
(`memo.input()["angles"]`), so one plan serves two angles or ten.

The **join** here is `AllOf`: once every child has ended in `completed`, the stage ends with
`researched`; if all have ended and at least one did not, it ends with `research_failed`.
gvn ships three more joins (`AnyOf`, `Quorum` and `Worst`), described in
[Joins](workflows-in-depth.md#joins-when-is-a-fan-out-over).

If `count` can be 0, give the `FanOut` an `empty` symbol: a zero count then ends the stage
at once with it. `empty` needs a declared transition, like any join outcome. Without `empty`,
a zero count is a `ValueError`.

## Step 4: tie machine and stages together (`Plan` and `Workflow`)

A **`Plan`** says which stage runs in which state. It is checked as a whole when you build
it, the same way a blueprint is checked: every way a stage can end must have a declared
transition out of its state.

A workflow is a class: subclass `Workflow` and return the plan from `plan()`. A plan holds
code (classes and functions), so it cannot live in the workflow's saved data; the class is
what knows how to rebuild the children when a run is revived.

The functions in a stage are code too, and a stored run must be continued by the code it
started on. A plan can declare, as `settings=`, the plain data that code was built from; a
stored workflow revives only under the same settings.
[Workflows in depth](workflows-in-depth.md#settings) explains how.

The parameters describe relationships: `definition` supplies the control machine; `stages`
maps a state name to its recipe; `relay` names events to send to active children rather than
feed into the parent's own machine. Here `interrupted` and `resumed` are relayed, so one
event can pause or resume the active tree. These names must not be inputs of the parent's
machine.

```python
from gvn.harness.workflow import Plan, Workflow

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


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

`relay` lists symbols that are not the workflow's own inputs but are handed to every active
child, re-addressed to each. Relaying `interrupted` and `resumed` lets one call
[interrupt](human-in-the-loop.md) a whole tree of agents. A relayed event is rejected only if
every child rejected it, or there are no children. A workflow run under an allowance (a limit
on what the whole run may spend on model calls) lists `interrupted` in `relay`, since
reaching the allowance is delivered as `interrupted`; the Governor refuses to drive one that
takes it neither in its own machine nor by relay
([Spending and rate limits](../guides/spending-and-rate-limits.md)).

## Step 5: run it

A workflow is an actor, so the [Governor](governor.md) drives it like any other. To keep the
example offline, the model is `FunctionModel` from `gvn.testing.fakes`: its reply is a function of
the question, so the same question always gets the same answer. This one wraps the prompt in
`note<...>`, which makes it easy to see who read what.

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

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(),
    )
```

`governor_with` builds a Governor whose model answers with the function you pass. The journal,
output and clock are the in-memory fakes from [The Governor](governor.md); this workflow
calls no tools, so the toolbox is empty and only the model fulfiller is needed. Now start
a `Briefing` on a topic with two angles:

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

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

The workflow went `idle`, `researching`, `writing`, `done`. To see what the writer wrote, read
the outcome with **`Report`**, a reader for a finished workflow's outcome:

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

reading = Report(outcome=result.outcome())
print(reading.results("writing")[0].payload()["text"])
```

```text
note<note<Moore machines, angle 0> | note<Moore machines, angle 1>>
```

Read it from the inside out: each researcher wrapped its own prompt in `note<...>`, and the
writer wrapped the two notes joined by `|`. The two researchers ran concurrently: their
requests were fulfilled at the same time, and their results came back addressed to them.

## Step 6: names and addresses

How did each result find its way back to the right researcher? Children are named after the
workflow, the stage, and the visit:

- a hosted child: `"<workflow>/<stage>.<visit>"`, such as `report/writing.1`;
- a fan-out child: `"<workflow>/<stage>.<visit>.<index>"`, such as `report/researching.1.0`.

`visit` counts entries into the stage from 1, and `index` counts children from 0. Request
ids start with the child's name, so every result finds its way back. The journal shows it:

```python
async def show_journal() -> None:
    for record in await journal.read("report"):
        print(record["event"]["name"], record["event"]["to"])


asyncio.run(show_journal())
```

```text
started None
model_replied report/researching.1.0
model_replied report/researching.1.1
model_replied report/writing.1
```

The order of the two research results can differ from run to run, because they ran
concurrently. The journal records the order in which they actually arrived, and that is the
order replay uses.

You address an event to a child the same way, for example to approve a tool call one
researcher asked for: `Event("approved", to="report/researching.1.0")`. An event addressed
to a child that is no longer active (a result that arrives after a join dropped its child) is
ignored, not an error.

That is the 80% you need. The rest of this page covers what a plan checks; the second page
covers everything else.

## Deeper: what a plan checks

`Plan` checks, when you construct it:

- the definition must be a Moore definition;
- every stage must sit on a non-final, non-initial state;
- every route of a `Host`, every outcome of its judge, every outcome of a `FanOut`'s join and
  its `empty` symbol must have a declared transition out of that state;
- for a stage with a deadline (a time limit on the stage, explained in
  [Time](time.md#stage-deadlines)), its `expired` symbol must have a declared transition out of
  that state;
- every `relay` name must be a valid symbol that is not an input of the machine.

Every problem is reported together in `PlanRejected`. Here the stages are put on the wrong
states on purpose:

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

try:
    Plan(definition=REPORT_MACHINE, stages={"idle": writing, "writing": researching})
except PlanRejected as rejected:
    for problem in rejected.problems():
        print(problem)
```

```text
state 'idle' is the initial state and cannot have a stage
state 'writing': join outcome 'research_failed' has no declared transition
state 'writing': join outcome 'researched' has no declared transition
```

The initial state cannot have a stage (nothing has started yet), and the research join's
outcomes have nowhere to go from `writing`.

## What else workflows do

[Workflows in depth](workflows-in-depth.md) continues with the same report workflow:

- **[Judges](workflows-in-depth.md#judges-deciding-on-what-a-child-said)**: end a stage
  based on what a child said, not only how it ended.
- **[Loops](workflows-in-depth.md#loops)**: draft, review, draft again, with a bound the
  verifier can see.
- **[The Memo in full](workflows-in-depth.md#the-memo-in-full)**: every visit of every stage.
- **[Joins](workflows-in-depth.md#joins-when-is-a-fan-out-over)**: any of, a quorum, a
  veto, the worst verdict, or your own.
- **[Deadlines and long loops](workflows-in-depth.md#deadlines-and-long-loops)**.
- **[Fan-out over items](workflows-in-depth.md#fan-out-over-items-foreach)**: one child per
  item of a list, a window, and bounded retries.
- **[Different kinds at once](workflows-in-depth.md#different-kinds-at-once-parallel)**: an
  agent, an [errand](errands.md) and an [inquiry](asking-a-person.md) in one stage.
- **[Compensation the verifier checks](workflows-in-depth.md#compensation-the-verifier-checks)**:
  undo that is proved, not hoped for.
- **[Nesting](workflows-in-depth.md#nesting)**: a workflow that hosts another workflow.
- **[Internal symbols, atomicity, the outcome, cost and the durable form](workflows-in-depth.md#internal-symbols)**.

## Recap

- A workflow is an actor made of other actors. Its Moore machine moves between stages, and
  the verifier checks that every way a stage can end is routed.
- A `Host` stage runs one child; `routes` map the child's final states to workflow inputs.
- A `FanOut` stage runs several children at once; a join such as `AllOf` decides when the
  stage is over.
- A `Plan` ties machine and stages together and is checked as a whole; a `Workflow` subclass
  returns it from `plan()`.
- The Governor runs a workflow like any actor. Children are named
  `<workflow>/<stage>.<visit>[.<index>]`, and results find their way back by that name.
- The whole tree is one durable object with one journal, so concurrent runs still replay
  deterministically.

**Next:** [Conversations](conversations.md), an actor that talks with a person over many
turns, and that a workflow can host as a stage.
**Going further:** [Workflows in depth](workflows-in-depth.md), after [Time](time.md).
