# Controller

> The controller is one loop in convoyd that keeps a run's actual state matching its declared state. This page is the full state machine, covering every state, transition, trigger and action.

The controller makes decisions that can be computed from state: has an agent crashed, is it stuck, has it finished, has a limit or the budget been reached. Anything that needs judgment is delegated to the [overseer](/docs/concepts/overseer/) by publishing a message. The controller works on runs. A `convoy run` on a swarm with no active run creates a new run; a second one while a run is `pending` or `running` is rejected with 409, so the controller never changes a running swarm's declared agents.

## Design rules

1. **One goroutine.** Every decision is made in one loop, in order, against a consistent read of the store. Process exit watchers only post events.
2. **Every transition is a store transaction that also writes an event.** Either the state change and its event both exist, or neither does.
3. **Decisions are recomputable.** The loop holds nothing in memory it could not rebuild from the store.
4. **Mechanical facts only.** Judgment goes to the overseer.

## Triggers

A pass runs when any of these happens:

- A tick, every 5 seconds (`--tick`).
- The store commits an event. The store signals a buffered channel of size 1 after every event-writing transaction; coalescing is fine because a pass reads everything.
- A process exits. The backend's wait goroutine writes an `agent.exited` event, which is itself a commit.

A pass runs the run rules, then the agent rules, for every run whose status is `pending` or `running`. Passes never overlap.

## States

**Run:** `pending`, `running`, `done`, `stopped`, `failed`. The last three are terminal. Every terminal run has an `end_reason`: `done`, `budget`, `max_runtime`, `failed`, `stopped` or `server_restart`.

**Agent:** `pending`, `running`, `idle`, `stuck`, `done`, `stopped`, `failed`. The last three are terminal.

| State | Meaning |
| --- | --- |
| `pending` | Waiting for `inputs` and `depends_on` to be `done`, or for a free process slot |
| `running` | In a turn |
| `idle` | Between turns, waiting in `wake` |
| `stuck` | A `running` agent that has not reported progress for too long. Not terminal |
| `done` | `finish` was accepted |
| `stopped` | Stopped by a person, the overseer, a parent, a limit or the run ending |
| `failed` | The runner died, bad inputs, or the server restarted |

The controller keeps per agent: `created_at`, `started_at`, `last_turn_at`, `last_progress_at`, `ended_at`, and the counters `turns`, `depth` and `cost_usd`. It records `sdk_session_id`, `last_response_id` and `process_id` for [post-MVP recovery](/docs/runtime/durability/) and reads none of them. Per run it keeps `started_at`, `ended_at`, `end_reason` and `cost_usd`, the sum over every agent including the overseer.

## Run transitions

Rules are checked in table order. A pass that sees both the budget crossed and `done_when` true ends the run as `budget`, which keeps the budget a hard rule that a lucky finish cannot mask.

| From | Condition | To | Actions |
| --- | --- | --- | --- |
| `pending` | first pass | `running` | set `started_at`; emit `run.started`; publish `swarm started` to `system`, addressed to `overseer` |
| `running` | `max_cost_usd` set and run `cost_usd >= max_cost_usd` | `stopped` | `end_reason = budget`; stop every non-terminal agent; emit `run.ended` |
| `running` | `now - started_at >= max_runtime` | `stopped` | `end_reason = max_runtime`; cascade; emit `run.ended` |
| `running` | `done_when` evaluates true | `done` | `end_reason = done`; cascade; emit `run.ended` |
| `running` | `done_when` returns a diagnostic | `running` | emit `done_when.error`, once per distinct message |
| `running` | every agent terminal, `done_when` not true | `failed` | `end_reason = failed`; emit `run.ended` with detail `all agents ended without meeting done_when` |
| `running` | a dead end: every agent has ended except pending ones blocked on a dependency that ended without an output, and the overseer has ended or may not create agents | `failed` | `end_reason = failed`; detail `no agent can make progress: ...` |
| `running` | the provider refused an agent's key, or its account has no credit | `failed` | `end_reason = failed`; detail `agent X:` and the provider's words |
| `running` | `POST :stop` | `stopped` | `end_reason = stopped`; cascade; emit `run.ended` |

`done_when` is evaluated on every pass, not only after a `finish`, so a run never waits for a tick that did not come. The overseer is excluded from "every agent terminal": a run whose only live agent is the overseer counts as all agents terminal.

### Budget

Spend enters the store in one place: the `wake` handler. Each `wake` carries the previous turn's token usage. The handler prices it, adds it to the agent's and the run's `cost_usd` in one transaction, and emits `agent.turn_ended`. The commit triggers a pass, and the first rule of the pass compares the run's `cost_usd` with `max_cost_usd`. The overseer's turns are priced and counted the same way.

When the budget rule fires, every agent is stopped by the normal stop sequence and outputs already passed to `finish` are kept. Two kinds of overshoot are expected:

- **Recorded overshoot.** Turns that end between the crossing and the stop still add to `cost_usd`. `convoy status` shows the recorded total, which may be above `max_cost_usd`.
- **Unrecorded spend.** A turn cut off by the stop sequence's `SIGTERM` never reaches `wake`, so its usage is not recorded. This is bounded by one partial turn per agent that was mid-turn.

When `max_cost_usd` is not set the rule never fires; spend is still recorded and shown.

## Agent transitions

Agents are processed in this order: the overseer, then declared agents in the dependency graph's start order, then runtime-created agents by `created_at`. Within one pass an agent moves at most one transition.

### Starting

| From | Condition | To | Actions |
| --- | --- | --- | --- |
| `pending` | gates satisfied and a process slot is free | `running` | start sequence; emit `agent.started` |

**Gates satisfied** means every instance in the agent's `inputs` and every `depends_on` target is `done`. A dependency that is `failed` or `stopped` can never satisfy the gate. The agent stays `pending` until the run ends, and the pass emits `agent.blocked` once with the names of the ended dependencies. The overseer gets the same message on `system`.

**A slot is free** means agents in `running`, `idle` or `stuck`, across every active run on this server and including overseers, number fewer than `--max-processes`. This is a limit on the machine, not on the swarm; the DSL has no attribute for it. Agents are admitted in rule order, so the overseer and then earlier declared agents win a scarce slot.

**Start sequence:**

1. Resolve `inputs` from the producers' outputs. A diagnostic here fails the agent with `end_reason = bad_inputs`.
2. Mint a token.
3. Build `start.json` (see [Seams and contracts](/docs/architecture/contracts/#startjson)).
4. `Create` the work folder (idempotent), then `Exec` the runner with `start.json` in the files. Store `process_id`; set `started_at` and `last_turn_at` to now.
5. Start a wait goroutine that writes `agent.exited` with the exit code and signal.

### Turns

| From | Condition | To | Actions |
| --- | --- | --- | --- |
| `running`, `stuck` | runner calls `wake` | `idle` | `turns += 1`; `last_turn_at = now`; price and record usage; record session ids; emit `agent.turn_ended` |
| `idle` | `wake` returns news | `running` | `last_turn_at = now`; emit `agent.turn_started` |

The `wake` handler performs both inside the board's transaction, because they must happen at the moment of the call. The first `wake` of a process ends the first turn, which began at start.

### Progress

| From | Condition | To | Actions |
| --- | --- | --- | --- |
| `running`, `stuck` | `report_progress(summary)` | `running` | store the summary; `last_progress_at = now`; emit `agent.progress` (and `agent.unstuck` when leaving `stuck`) |

### Limits

| From | Condition | To | Actions |
| --- | --- | --- | --- |
| `running`, `idle`, `stuck` | `turns >= max_turns` | `stopped` | `end_reason = max_turns`; stop sequence |

The runner also exits with code 4 on its own count. Whichever comes first wins and the other is a no-op.

### Stuck

| From | Condition | To | Actions |
| --- | --- | --- | --- |
| `running` | `now - max(started_at, last_turn_at, last_progress_at) >= stuck_after` | `stuck` | emit `agent.stuck`; publish to `system`, addressed to `overseer`: `agent researcher[groq] stuck: no progress for 20m; last progress: ...` |

Only `running` agents become stuck. An `idle` agent is waiting by design. `stuck_after` defaults to 20 minutes. Being stuck changes nothing about the process: the controller does not kill or restart it. What to do is the overseer's decision. A stuck agent is still bounded by `max_turns`, `max_runtime` and `max_cost_usd`. A stuck agent returns to `running` on its next `report_progress` and to `idle` when its turn ends.

### Exits

| From | Condition | To | Actions |
| --- | --- | --- | --- |
| `running`, `idle`, `stuck` | process exited, status already `done` | `done` | none; `agent.finished` already exists |
| same | exited, a stop was requested | `stopped` | finish the stop sequence |
| same | exited with code 4 | `stopped` | `end_reason = max_turns` |
| same | exited 0, not `done`, no stop requested | `failed` | `end_reason = runner_error`, detail `exited 0 without finish` (a runner bug, logged) |
| same | exited 1 or by signal | `failed` | `end_reason = runner_error`, detail with the code or signal |
| same | exited 2 | `failed` | `end_reason = bad_invocation` |

Exit code 3 is reserved and treated like code 1. Every transition to `failed` also revokes the token, stops the agent's children, emits `agent.failed`, and publishes `agent X failed: <end_reason>` to `system` for the overseer.

There are no restarts in the MVP. A runner that dies takes its agent with it and the run continues with the agents it has left. Exits are processed exactly once: `agents.last_processed_event_seq` records the last `agent.exited` event handled, and the same transaction that updates state advances it.

### Finish

| From | Condition | To | Actions |
| --- | --- | --- | --- |
| `running`, `stuck` | `POST :finish` accepted | `done` | store output; `ended_at = now`; emit `agent.finished`; the next `wake` returns `{stop, reason: finished}`; the token is revoked after the process exits |

The finish handler performs this. The loop then evaluates gates for dependents and `done_when` on the triggered pass.

### Stop

The stop sequence is used by `POST :stop`, the run-level cascade, limits, failures and parent stops:

1. Mark the agent stopping in memory (not a stored status) and emit `agent.stop_requested` with the reason.
2. Stop children first, depth-first, each through this same sequence.
3. Signal the board so a blocked `wake` returns at once with `{stop: true, reason}`.
4. Wait up to `--stop-grace` (5 seconds) for `agent.exited`.
5. If the process is still alive, destroy it: `SIGTERM` to the process group, then `SIGKILL` after `--kill-grace` (3 seconds).
6. Set status `stopped` (unless it became `done` meanwhile; `done` wins), set `ended_at` and `end_reason`, revoke the token, emit `agent.stopped`.

Steps 4 and 5 are not blocking waits. The loop records the request time in memory and checks it on later passes, so a run-level cascade completes over one or two passes. `run.ended` is emitted with the run's status change, so `convoy watch` ends as soon as the run does; the cascade's `agent.stop_requested` and `agent.stopped` events follow it.

### Token lifetime

An agent's token is revoked when its runner process exits, in the same transaction as `agent.exited`, whatever the agent's status and whatever the run's. When a run's cascade finishes, the tokens of agents with no live process are revoked too; agents whose runner is still shutting down keep theirs until it exits. So the agent whose `finish` ended the run still reports that last turn's usage on its next `wake`, and the turn is counted in the run's spend, and a finished or stopped agent's runner can store the end of its transcript for the [Web UI](/docs/runtime/web-ui/).

## The overseer's schedule

The overseer is an agent row that watches `system`, so the board wakes it like any other agent. The controller's part is publishing to `system` as sender `convoyd`, addressed to `overseer`:

| When | Message |
| --- | --- |
| Run started | `swarm started; N agents pending` |
| Every `--overseer-interval` (5 min) while running | `tick: elapsed 00:41 of 4h; spend $3.12 of $20.00; running 2, idle 4, stuck 0, done 1, pending 0` |
| `agent.stuck` | `agent X stuck: no progress for 20m; last progress: ...` |
| `agent.failed` | `agent X failed: <end_reason>` |
| `agent.finished` | `agent X finished`, plus the first 500 characters of the output |
| `agent.blocked` | `agent X cannot start: dependency Y is <status>` |

Messages another agent addresses to `overseer` go through the board directly. Several events within the debounce window become one overseer turn. With no `max_cost_usd` the tick shows `spend $3.12 (no cap)`.

## Recovery on restart

The MVP does not resume work after convoyd restarts. On start, before serving requests:

1. For every run that is `pending` or `running`, in one transaction per run: set every non-terminal agent to `failed` with `end_reason = server_restart`, revoke its tokens, emit `agent.failed`; then set the run to `failed` with `end_reason = server_restart` and emit `run.ended`.
2. For every affected agent with a stored `process_id`, kill it. Usually the process is already gone; this catches survivors.
3. Run one pass, which finds no active runs.

A new `convoy run` on the same swarm starts a fresh run. The failed run stays readable with `convoy status --run N`. The local backend accepts that a pid reused by an unrelated process since the crash would be signalled too.

Resuming the real SDK session from the stored session id, cursors and process handle is designed but not built. See [Durability](/docs/runtime/durability/).

## Timing parameters

| Flag | Default | Used by |
| --- | --- | --- |
| `--tick` | `5s` | Pass interval |
| `--stuck-after` | `20m` | Stuck rule |
| `--stop-grace` | `5s` | Stop sequence step 4 |
| `--kill-grace` | `3s` | `SIGTERM` to `SIGKILL` |
| `--overseer-interval` | `5m` | Heartbeat to `system` |
| `--wake-timeout` | `30s` | Board `Wake` |
| `--max-processes` | `50` | Admission |

## Concurrency

The loop and the HTTP handlers both write to the store. Handlers perform only the transitions marked above as theirs: turn start and end, progress, finish, agent creation and stop requests. Each is one transaction guarded by a status check in SQL (for example, `UPDATE agents SET status='done' ... AND status IN ('running','stuck')`), so a handler racing the loop cannot move an agent out of a terminal state. The loop re-reads state at the start of every rule.
