# Architecture

Read this before your first real change to Andon. Most of the code follows from one decision: **the database is the
message bus, and every machine dials out to it.** When a bug makes no sense, it is often a property of that shape.

## The database is the hub

Andon has no worker service, no queue, no broker and no app server that owns domain state. Work is coordinated through
rows, and live updates are row changes:

- a `runs` row is a job;
- a `commands` row is an instruction to a machine;
- a `run_events` row is a log line;
- an `attention_v` row is a request for a person.

The server's Server-Sent Events push those changes to whoever is watching.

| Because the database is the bus | this is true in the code |
|---|---|
| Claiming work is a job-queue query | `claim_next_run()` is a `security definer` RPC with `for update … skip locked`. Every dispatch rule is a SQL predicate in it |
| Tenancy is enforced where the data is | row-level security on every tenant table, and a tenancy registry whose test fails when a new table isn't covered |
| A machine needs no inbound port | the agent polls and streams out. Its only listeners are on loopback: the hook server, and tunnels opened on demand |
| The server stays thin | `apps/server` is a transport over the schema: the product logic is in Postgres and `packages/shared`, so any Postgres 15+ runs Andon |
| The board can't call a machine directly | board → row → agent → local process, in that order, and each step can refuse |

## Three planes and one backend

```
Clients        board (Vite/React PWA) · desktop (Tauri shell) · phone and iPad · andon CLI · MCP (inside a run)
Control plane  apps/server: Hono · better-auth · /api/db query compiler · SSE · storage · functions · jobs
               → Postgres 15+ (one schema, RLS, several hundred security definer functions)
Execution      apps/agent on each machine: daemon · hook server (127.0.0.1) · an MCP server per run
               → git worktree or Orca workspace → Claude Code, Codex or Gemini CLI in `tmux -L andon`
Sideways       GitHub (push, PR and merge from the machine) · model calls in the functions (Gemini, the Vercel AI Gateway or a machine)
```

## One server

Andon has one backend: `apps/server`, a single Hono app on the web Fetch API. There is no second backend to keep in
step, no Supabase stack and no Docker in development. The app is built once by `createServer()`
(`apps/server/src/server.ts`) and has two entry points:

| Entry point | Runs as | Scheduled work | Live updates |
|---|---|---|---|
| `src/node.ts` | one long-lived Node process (a container, a VPS, `andon up`, `pnpm dev`) | a timer every `ANDON_TICK_MS`, and a `LISTEN` for queued jobs | a stream lasts until the caller's token expires, then the client reconnects; the voice relay's WebSocket (`VOICE_TRANSPORT=relay`) runs only here |
| `src/vercel.ts` | one Node function on Vercel's Fluid compute, for `/api/*` | Vercel Cron calls `/api/cron/tick` with `CRON_SECRET` | each stream closes before the function's `maxDuration`, and the client reconnects |

On both, an agent's heartbeat also runs scheduled work that is due, and each server instance holds one `LISTEN` on
the direct connection while a stream is open. Both answer the same routes, listed in the header of `src/app.ts`:

| Route | What it is |
|---|---|
| `/api/health` | the server and its database answer |
| `/api/auth/*` | better-auth: sessions, codes, passkeys and OAuth |
| `/api/machine/token` | a machine's refresh token swapped for a new pair |
| `/api/db/query`, `/api/db/rpc/:fn` | the data API: a query or a call, checked against the generated allowlist, run as the caller so row-level security applies |
| `/api/realtime` | live updates as Server-Sent Events: row changes, broadcast and presence |
| `/api/storage/*` | files, on disk, S3 or Vercel Blob; the database decides who may read or write each one |
| `/api/fn/:name`, `/functions/v1/*` | the functions over HTTP |
| `/api/cron/tick` | the scheduled work, for Vercel Cron |
| `/api/setup` | a fresh instance's owner and first org |
| `/api/v1/*` | the public API and the instances API |

Outside `/api`, the Node entry point also serves the built board (`ANDON_BOARD_DIR`), so one process is the whole
deployment. The board's build carries `install.sh` and the agent's update bundle. On Vercel the CDN serves that build.

The server runs Andon's 31 functions: 22 over HTTP at `/api/fn/<name>` (seven of them also at the old
`/functions/v1/<name>` paths) and 11 as database-driven jobs. [The server](https://andon-docs.pages.dev/contributing/server.md) lists them, and covers auth,
the data API, live updates and storage in depth.

Migrations come from `db/migrations` only. The Node server applies them when it starts, and a Vercel production build
applies them before it builds the board. Each runs once, in order, under an advisory lock.

### Where it runs

The code is the same everywhere; only the entry point and the platform's limits differ.

- **One box.** A container or a VPS runs `node.ts` with the board inside, next to Postgres. The `single` Docker target
  puts PostgreSQL 17 in the same container, on one volume. Scheduled work runs on the server's own timer and live
  updates have no platform time limit.
- **Vercel and a hosted Postgres.** The board is on Vercel's CDN, `/api/*` is one function, the database comes from the
  Marketplace (Neon or Supabase, used only as Postgres) and files go to Vercel Blob. Scheduled work runs when Vercel
  Cron calls (daily by default, the most Hobby allows) and whenever an agent's heartbeat finds work due.

[Deploy Andon](https://andon-docs.pages.dev/machines/deploy.md#choose-a-host) is the guide for picking between them.

`packages/shared` is the seam between the board, the agent and the server: types, zod schemas, enums, prompt templates, verdict
logic and the realtime wire format. It stays pure (no network, no filesystem), so the board can bundle it and the agent
can test it alone. The board talks to the server only, through `@andon/client`, which keeps supabase-js' shapes: its `db`
object is typed as the slice of `SupabaseClient` it uses (`apps/board/src/lib/db.ts`). supabase-js is a type there and
never in the bundle; lint refuses a runtime import of it under `apps/board/src`. `VITE_ANDON_URL` says where the server
answers (unset: the board's own origin).

## Where a change goes

| Change | Home | Start reading |
|---|---|---|
| Card or list UI, drag and drop, a page, a hook | `apps/board/src` | `lib/board-store.tsx`, `lib/db.ts`, `App.tsx`, `SignedIn.tsx` |
| A type, enum, schema or rule the board **and** the agent need | `packages/shared/src` | `index.ts`, `enums.ts` |
| A table, policy, RPC, view or trigger | a new file in `db/migrations` | [Schema changes](https://andon-docs.pages.dev/contributing/schema-changes.md) |
| What the agent does with a run | `apps/agent/src` | `agent.ts` (`start`, `launch`, `handleHook`), `policy.ts` |
| The API, auth, live updates, storage, jobs | `apps/server/src` | `app.ts`, whose header is the route map |
| The supabase-js-shaped client for the server | `packages/client/src` | `index.ts` |
| A function (an HTTP call or a job) | `apps/server/src/functions` | `http-fns.ts`, `jobs-fns.ts`, `shared/` |
| The desktop shell, tray and deep links | `apps/desktop` | its [README](https://github.com/psci-labs/andon/blob/main/apps/desktop/README.md), `src-tauri/src/` |
| A dev or CI helper | `scripts/` and a `package.json` script | the scripts beside it |

Two rules of thumb:

- If the board and the agent both need a rule, it belongs in `packages/shared`.
- If correctness depends on concurrency, it belongs in SQL. A TypeScript limiter next to `claim_next_run` is a second
  source of truth that will drift.

## A run, end to end

```
person drags a card → create_run RPC (a runs row: queued)
agent → claim_next_run (launching) → workspace + prompt.md + run contract + hooks + MCP config
      → tmux session → running on the first hook
session → hooks (lifecycle, permission requests) and MCP tools (report, ask, publish_output…)
      → runs.report, run_outputs, attention rows
session → git push, gh pr create (the run contract), then the machine's pipeline:
          review rounds → CI checks → merge gates → gh pr merge --match-head-commit
merge → migrations apply, the board deploys, every agent updates itself
```

What this flow makes true:

- **A card has many runs.** `runs.resumed_from` chains a Continue. A card's status is derived from its runs and its
  pipeline, never stored on the card.
- **A workspace outlives a run.** That is why `claim_next_run` enforces one session per checkout.
- **The machine does the GitHub work.** The server never holds a merge token. Merging needs the machine's own `gh`
  login and its local policy.
- **The run contract outranks the repository's docs.** `apps/agent/src/run-contract.ts` is put above a repository's own
  `CLAUDE.md`, so the delivery rules (push, open the pull request, never merge) win.

## State machines

`runs.status` is one of `queued`, `launching`, `running`, `needs_input`, `waiting`, `review`, `done`, `ended`, `failed`
or `cancelled`. The agent groups them into `ACTIVE` (the five that count against a machine's concurrency) and
`TERMINAL` in `apps/agent/src/run-status.ts`. A new status touches claiming, concurrency, the board's status colours and
that file: search for the existing list rather than writing a second one.

Cards move between column **roles** (`COLUMN_ROLES` in `packages/shared/src/enums.ts`), not column names. Each org can
rename and reorder its columns while automation still knows which one is Ready. Code finds a column with
`column_for_role(org, role)`, never by its name.

A pull request's pipeline lives in `pipelines` and `review_rounds` and moves through review, CI and merge, with
`blocked` and `ready` as resting states a person resolves. The verdicts are pure functions in
`packages/shared/src/pipeline.ts`.

## Trust boundaries

| Boundary | Authenticated by | What it reaches |
|---|---|---|
| browser → control plane | session cookie or JWT | what row-level security allows that person, **and** what their teams' visibility allows |
| agent → control plane | the machine's access token (its own auth user) | claiming, heartbeats, its org's rows |
| run → agent (loopback) | the run's own hook token, bound to its run id (`apps/agent/src/run-tokens.ts`) | that run's report, ask, outputs and permission requests; never another run's, never `/cli/*` |
| orchestrator thread → agent (loopback) | the thread's own hook token, bound to its thread id | that thread's `orch_*` tools |
| CLI → agent (loopback) | the machine's hook token (`hookToken` in the config file), which never enters a run's files | `/cli/*`: the machine's own queries, its backend token, starting cards |
| board → a run's terminal | the viewer's own JWT: `open_terminal` registers each viewer, and only that person joins its topic | its output to anyone who sees the run; keystrokes into a PTY only from the machine's or the card's owner |
| board → a machine's direct terminal (its tunnel) | a ticket from `terminal_ticket`: random, good once, for a minute, by the run's machine, for one run and viewer. The machine redeems it with its own token and asks `terminal_ticket_access` again every minute; the member's session token never goes to a machine | the same as above, closed when its person can no longer see the run, or no longer types in a viewer that types |
| outside → capture | a capture token | new cards in the org (the handler re-checks team visibility) |
| GitHub, Linear, Asana → control plane | an HMAC webhook secret | imports and pull request state |
| board hosting → every machine | a sha256 from the same origin | the agent's self-update bundle |

A run's folder (`<stateDir>/runs/<id>/`) holds its token, its MCP config and its runner script (a provider's key)
only while the run lasts: the agent deletes them when the session ends.

The last row is the weak point. Self-update checks the bundle's integrity, not who made it, so anything that makes the
board's origin more powerful makes every machine more exposed. Say so in the pull request when a change does that.

The machine's local policy (`apps/agent/src/policy.ts`) is the final word on what runs on it. The board may ask; it
can't widen what the policy allows.

## The rules a change keeps

1. **Org scope everywhere.** Every tenant table has `org_id uuid not null`, every query filters on it, every Realtime
   topic is `org:<orgId>:<area>` and every Storage path starts `<org_id>/`. Row-level security is the only tenancy
   control: no service in front of the database checks again.
2. **Visibility as well as membership.** An org member can't necessarily see a card, because teams can be private.
   Check with `can_see_card` or `can_see_team`, not `is_org_member` alone. Neither checks the org: they say yes to any
   open team in any org, so a `security definer` function, which skips row-level security, checks `can_read_org` on the
   row's org too. A write through the service role skips row-level security, so it must check visibility itself.
3. **Never address a column by its name.** Use its role.
4. **The machine's policy is the last word.** Anything that reaches a machine goes through `policy.ts`.
5. **No shell.** `execFile` or `spawn` with an argument array. Prompts and diffs go through files, never argv. ESLint
   blocks `exec`, `execSync` and `shell: true`.
6. **Dispatch rules live in `claim_next_run`.** A new rule is a migration, and the RPC is what you test.
7. **One home per fact.** The schema is `db/migrations`; the data API's allowlist is the generated
   `catalog.gen.ts`; shared rules and labels are in `packages/shared`.
8. **Functions live only on the server** (`apps/server/src/functions`, their pure cores in `shared/`). The
   public `/functions/v1/<name>` paths are routes of that server. The instances API (`/api/v1`) is the server's too.
9. **Load and subscribe the way the app already does.** Skip work while the page is hidden, coalesce bursts, batch by
   id. `card_board_v` and `attention_v` are heavy views: reading one per card is how a refetch storm starts.
10. **Fail closed.** An unknown state is not a pass.
11. **Parse real payloads.** `fixtures/` holds captured `orca`, `claude`, `codex`, `gh` and hook output. If a field
    isn't there, capture it before you write a parser.
12. **No personal values or secrets.** No real emails, hostnames, home paths or keys in code, tests, seeds or
    fixtures. The board ships no keys: it signs in to the server.
13. **Colours come from Tailwind tokens**, and red only ever means failed ([Design system](https://andon-docs.pages.dev/contributing/design-system.md)).

## Where the complexity is

| Hotspot | Why it is hard | Start at |
|---|---|---|
| `apps/agent/src/agent.ts` (about 6,000 lines) | one class owns claiming, launching, hooks, commands, outputs, clean-up, pipelines and usage | the `Agent` fields, then `start`, `launch`, `handleHook` |
| `claim_next_run` | dispatch policy as SQL predicates: the hardest concurrency in the codebase | its newest definition in `db/migrations` |
| `db/migrations/20261021160000_baseline.sql` | about 17,000 lines, frozen, never edited | read it; change the schema with a new migration |
| `apps/board/src/lib/board-store.tsx` | optimistic writes, reloads without gaps, coalescing | its header comment, then the reducer |
| `apps/desktop` | Rust and TypeScript, built by its own workflow | its README |

The board changes most often, then the server, then the agent. Look for a regression in that order.

## Reading order for a new area

1. [PRODUCT.md](https://github.com/psci-labs/andon/blob/main/PRODUCT.md) for the vocabulary.
2. The schema around `cards`, `runs` and `claim_next_run`.
3. `agent.ts`: `start`, `launch` and `handleHook`. Most of what Andon does happens here.
4. `db.ts`, `board-store.tsx` and `runs.ts` in `apps/board/src/lib`: how the UI follows a run.
5. `packages/shared/src/pipeline.ts`: how a pull request gets merged.
6. Then `apps/server`, which serves what you just read from any Postgres ([The server](https://andon-docs.pages.dev/contributing/server.md)).
