# State machines

::: info What you'll learn
Give a collection states (draft → pending → approved → paid) and the transitions between them: who
may make each one, what must be ready first, what it locks, and what runs after. Editors get one
button per transition; nothing else can change the state.

**Before this page:** [Actions](./actions), [Access control](./access-control).
:::

Approvals, claims and orders go wrong when a status skips a step, or someone changes it at the
wrong moment. With `stateMachine` the rules live in the config:

```ts
export default defineConfig({
  // …
  collections: [
    {
      slug: 'expenses',
      fields: [
        { name: 'title', type: 'text' },
        { name: 'amount', type: 'number' },
        { name: 'approvedBy', type: 'text' },
        { name: 'reason', type: 'text' },
      ],
      stateMachine: {
        initial: 'draft',
        states: {
          draft: {},
          pending: { label: 'Pending approval', lock: ['amount'] },
          approved: { lock: true },
          paid: { lock: true },
          refunded: { lock: true, final: true },
        },
        transitions: {
          submit: { from: 'draft', to: 'pending', label: 'Submit for approval', requires: ['amount'] },
          'send-back': { from: 'pending', to: 'draft' },
          approve: {
            from: 'pending',
            to: 'approved',
            access: ({ user }) => user?.role === 'admin',
            guard: ({ doc }) => doc.amount < 50000 || 'Over 50,000 needs the CFO',
            before: ({ user }) => ({ approvedBy: user?.email }),
          },
          pay: {
            from: 'approved',
            to: 'paid',
            effect: async ({ doc, cms }) => {
              await cms.sendEmail({ to: 'finance@example.com', subject: `Pay ${doc.title}` })
            },
          },
          refund: {
            from: 'paid',
            to: 'refunded',
            fields: [{ name: 'why', type: 'text', required: true }],
            confirm: { danger: true },
            before: ({ input }) => ({ reason: input.why }),
          },
        },
      },
    },
  ],
})
```

Easy CMS adds the state field (`state`, or the name in `field`): a select of the states, indexed,
read-only in the admin's side panel. New documents start in `initial`.

## States

| Option | |
|---|---|
| `label` | Shown in the admin. Default: the name, humanized. |
| `lock` | Fields that can't change while a document is in this state: `true` for all of them, or their names. The admin shows them read-only; the server refuses a change with a 400. |
| `final` | No transition leaves it. |

## Transitions

| Option | |
|---|---|
| `from`, `to` | The state (or states) it starts from, and the state it moves to. |
| `label` | Its button's label. |
| `access({ doc, user })` | Who may make it; `false` hides its button. Default: whoever may update the document. |
| `guard({ doc, user })` | Whether the document is ready: `true`, or the reason it isn't. The button shows greyed out with the reason. |
| `requires` | Fields that must have a value first; the reason names the empty ones. |
| `fields`, `confirm` | A small form asked before it runs (its values are `input`), and a confirmation, as for [actions](./actions). |
| `before({ doc, user, input })` | Runs in the transition's transaction: return values to save with the new state, or throw to stop. |
| `effect({ doc, user, input, previousState, state })` | Runs after the transition commits, e.g. an email or a [job](./jobs). Retried after 1m, 5m, 30m, 2h and 12h until it succeeds, so make it safe to run twice. |

The config refuses, when it loads, a state or field that doesn't exist, a transition out of a final
state, and transition names that aren't lowercase letters, digits and `-` (they are action names).

## The only way to change the state

`cms.transition()`, the buttons in the admin, REST, GraphQL and the MCP tool all make the same
checks, in order: the document's state is one the transition starts from (else 409), `access`,
`requires`, `guard`, then `before`. The new state is written only if the stored state is still the
one it started from, so of two people pressing **Approve** at once one wins and the other gets a
409. Its history row is written in the same transaction.

```ts
await cms.transition('expenses', id, 'approve', { user })
await cms.transition('expenses', id, 'refund', { input: { why: 'Broken' } }) // trusted code
const history = await cms.transitionHistory('expenses', id) // newest first
```

Without `user` (or with `overrideAccess: true`) it is trusted server code: `access` is skipped,
`requires` and `guard` are not. Transition names are typed from the config, so a misspelled one
doesn't compile.

Writes that set the state field directly, or change a locked field, are refused with a 400 for
users (the admin, REST, GraphQL). Trusted code (`overrideAccess`) may, e.g. for imports. Raw SQL
(`cms.sql`) is outside these rules, as everywhere.

With [drafts](./drafts), the state belongs to the live document: drafts don't hold it, and
publishing a draft doesn't change it.

## In the admin

Each transition is an [action](./actions) on the edit page (and for selected documents in the list,
in bulk), shown only in the states it starts from and to those it allows. A transition whose
`guard` or `requires` isn't met shows greyed out with the reason. Locked fields are read-only, and
the side panel shows the machine as a small diagram (the document's state, the transitions you
may make from it, and those not ready yet, dashed, with the reason) and the state history: each
transition, who made it and when.

With `admin: { board: { groupBy: 'state' } }` the list gets a [board](./admin#board): a column per
state, and dragging a card makes the transition to that column.

To check a machine before you run it, paste the config into [Studio](./studio#state-machine): it
draws the states and transitions, and warns about a state nothing leads to or nothing leaves.

## Effects

`effect` runs once the transition has committed, never for one that rolled back. It is recorded
with the transition and retried by `runJobs` (the scheduler, or the cron endpoint) until it
succeeds, then marked failed after five retries. Keep long or multi-step work (charge a card, wait
for a webhook) in a job or workflow started from it.

## Over REST

| | |
|---|---|
| `POST /api/cms/<collection>/<id>/transitions/<name>` `{ input? }` | Makes the transition; returns the document. |
| `GET /api/cms/<collection>/<id>/transitions` | `{ docs }`: its history, newest first. |
| `POST /api/cms/<collection>/<id>/actions/<name>` | The same transition, as an action (what the admin calls). |

GraphQL has `transition<Type>(id, name, input)`, and the [MCP](./mcp) server a
`transition_<collection>` tool; neither lets `update` set the state.
