# Ladder API

The ladder serves everything, pages, API and bot sockets, from one address.

The leaderboard always keeps four aligned columns for rank, bot, score and W–L–D, including
on phones. Score and record stay on one line; bot names and owner labels can wrap within the
bot column. Other narrow bot panels use labelled rows. API counts and identifiers are unchanged.

| what                 | where                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                              |
| -------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| bot WebSocket        | `wss://victrisarena.com/bot` (header `Authorization: Bearer <token>`); `wss://<host>/bot` on a hosted ladder, as `GET /api` reports in `bot_endpoint`                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                 |
| optional MCP         | `https://victrisarena.com/mcp`, Streamable HTTP; `GET /api` reports `mcp` as its canonical URL, or null when disabled. Supabase OAuth and browser consent authorize bot and League tools (see [MCP.md](/docs/mcp))                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                       |
| title screen         | `https://victrisarena.com/`: the game's menu, leading to the tutorial, creating a bot and the leaderboard                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                             |
| dashboard            | `https://victrisarena.com/ladder`: the leaderboard, recent and live matches, and who is online                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                        |
| create a bot         | `/create-bot`: connect a coding agent to the ladder, one step at a time, with this ladder's addresses filled in                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                    |
| how bots work        | `/how-bots-work`: how a bot works and how to connect one by hand, for people, with this ladder's addresses filled in                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                               |
| JSON API             | `https://victrisarena.com/api/...` (index at `/api`, which also reports the running `versions`: the `release`, `engine`, `protocol`, `rules` and its `rules_hash`, database `schema`, and the git `commit` on a deployed ladder; `changelog` (`page`, `markdown`, `json` and `feed` links), `simulator`, the links to this release's simulator, and `bot_code`, the starters and house bots below)                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                    |
| docs                 | `/docs` (an index), `/docs/agents`, `/docs/bot-guide`, `/docs/api`, `/docs/spec`, `/docs/simulator`, `/docs/changelog`, `/docs/rules` (annotated, with the zone schedule per map), `/docs/rules.json` (raw), `/docs/frame-data`, `/docs/schema/` (schema index), `/docs/schema/<name>.json` (short names such as `observation` work)                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                               |
| OpenAPI              | `/openapi.json`: OpenAPI 3.1 contract for public discovery/data, bot registration and bot-token management, linked by `GET /api` as `openapi` and by `/llms.txt`. Includes request/response schemas, separate account and bot credentials, and the configured registration gate. Browser account management and operator APIs remain in this guide; WebSocket combat remains in the protocol schemas.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                              |
| API catalog          | `/.well-known/api-catalog` ([RFC 9727](https://www.rfc-editor.org/rfc/rfc9727)): a `application/linkset+json` document naming the HTTP API at `/api` with its OpenAPI contract (`service-desc`), this guide (`service-doc`), the versioning policy (`service-meta`) and `/api/status` (`status`).                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  |
| Agent skill          | `/.well-known/agent-skills/index.json` (Agent Skills discovery v0.2.0) lists one skill, `victris-arena`, with its SHA-256 digest; its `SKILL.md` is at `/.well-known/agent-skills/victris-arena/SKILL.md`: the agent guide's path, with this ladder's addresses. MCP serves the same file as `skill://victris-arena/SKILL.md`.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                     |
| Markdown for agents  | `/`, every guide page (`/guide/<name>`, `/changelog`), `/pricing` and `/leagues` answer in Markdown to `Accept: text/markdown`, with `Vary: Accept`: the home page is `/llms.txt`, a guide is `/docs/<name>`, and Pricing and Leagues are also at `/pricing.md` and `/leagues.md`. Bot pages (`/bot/<name>`: record and versions), match pages (`/match/<id>`: result, ratings and replay links) and the live standings (`/leaderboard`, `?ladder=<id>`) answer in Markdown built from their data at the same address; their HTML names both forms in `Link` headers (`type="text/markdown"` and the JSON route as `type="application/json"`). Their HTML names that Markdown in a `Link: <…>; rel="alternate"; type="text/markdown"` header. A missing address answers a Markdown request with a 404 that links to `/llms.txt`, the guides, `/api` and the sitemap; other requests still get JSON |
| replays              | `/replays/<match id>.jsonl.gz`                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                     |
| changelog            | `/changelog` is the public page, with release links such as `/changelog#v0.29.3`. `/docs/changelog` is Markdown; `GET /api/changelog` returns `{versions, markdown}`, with the same `versions` as `/api` and the history bundled with the ladder. `/changelog.atom` is an Atom feed of the dated releases (newest 50), titled with a note when a release changes the rules. Unreleased notes are separate from numbered releases. A missing changelog returns 404.                                                                                                                                                                                                                                                                                                                                                                                                                                 |
| simulator            | this release's match code, for training offline (see [SIMULATOR.md](/docs/simulator)). `GET /api` → `simulator` lists `javascript`, `script` and `python`. Local ladders use `/download/arena-sim.mjs`, `/download/arena-sim.js` and `/download/arena_sim-<release>-py3-none-any.whl` (another release's wheel name gets a 404 that names this one). When `ARENA_SIMULATOR_PUBLIC_URL` is set, those links are versioned CDN URLs (`…/download/<release>/…`) on the public assets domain; the ladder still serves the same files under `/download/` as a fallback                                                                                                                                                                                                                                                                                                                                     |
| bot code             | `/download/bots`: JSON listing one starter bot in TypeScript and Python, plus Random and its generic client code, each file's address and what it is, and the commands to set up a starter. Each file is at `/download/bots/<path>` (for example `/download/bots/py-starter/bot.py`); served, the starters connect to this ladder by default                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                       |
| a bot's page         | `/bot/<name>`: each version's rank, rating and record, a rating chart over the last day, week, month or all time, records for the 100 most recent opponents from the last 500 matches in a scrolling panel (column sorting keeps that selection), map records, health and recent matches; Opponents and Maps have independent version filters, defaulting to the ladder's current version, with older versions and All versions available (filtering the last 500 matches across all versions); the ladder picker only offers ladders with recorded matches for this bot, across all versions and match modes, and scopes all stats to one ladder (Public by default) and preserves `?ladder=<id>` in the URL; it updates when the bot finishes a match                                                                                                                                            |
| a match's page       | `/match/<match id>`: the result, a link to watch it, and its stats as a table                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                      |
| watch a match        | `/view/<match id>` (opens the viewer)                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                              |
| learn how bots fight | `/tutorial`                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                        |

Leaderboard, bot detail and admin data tables sort when you click a column heading;
click again to reverse direction. The selected order follows refreshed records, including
additions and removals. This sorts the loaded browser data; API response ordering is unchanged.
Reference and match-stat tables keep their fixed order.
Click anywhere on a leaderboard row to open the bot's detail page;
owner links still open the owner's profile. Hover and keyboard focus highlight the whole row,
including wrapped bot text. Bot links also support opening in a new tab.
The leaderboard's **Search bots** field filters by bot name, owner, team domain or credited agent.
Search terms are case-insensitive and all terms must match. Filtering keeps each bot's ladder rank;
clearing the search restores the full board. On My Bots, names and portraits open the bot page;
open **Edit** to rename a bot.
Site pages share **Leaderboard**, **Events**, **Teams**, **Agents**, **Feedback**, **My Bots** (or **Sign in**) and
**Create a Bot** navbar controls, including the title screen, guides, legal pages, practice and
replay viewer. The leaderboard uses its ladder and month switchers in place of a redundant
Leaderboard button; detail pages return to the selected competition. Phones put common
actions in a **Menu** dropdown. Account actions only appear when accounts are enabled;
the account page offers **Sign out** once signed in. Static navigation remains usable without
JavaScript. The title screen's **Tutorial** entry opens the animated tutorial at `/tutorial`. The replay viewer keeps its match link and file picker; the standalone CLI viewer
links to the public arena and does not request account data from its file server.
The ladder and bot pages omit explanatory panel footnotes; rating, qualification,
health and sampling definitions are documented in this guide.

Public HTML guides are at `/guide` and `/guide/<name>` (for example, `/guide/agents`
and `/guide/api`). The web build generates them from the same sources as the Markdown
at `/docs/<name>`. Served repository links resolve to the appropriate ladder endpoint
or source file on GitHub. `/docs/ranged-attacks` also serves the ranged attack guide.
The homepage, bot-building guide and release notes include text before JavaScript
loads. Rankings, event directories and achievements also include introductory summaries
and links to current JSON data. Bot and match pages include their identity, canonical URL
and summary in the initial HTML; missing entities return 404 with `X-Robots-Tag: noindex`.
Live tables and account interactions still load in the browser. Public pages include
JSON-LD describing the game, website, guides and breadcrumbs. Live rules and frame data
still come from the running ladder. Canonical URLs,
`/sitemap.xml` and `/robots.txt` use the configured public address, or the local ladder
address when no public address is set. The sitemap adds ranked public bots and recent
public bot matches to the build's page list. Crawlers can discover those URLs through
the sitemap without JavaScript; internal links in live tables still require rendering.
`/docs/schema/` lists the generated schema URLs as JSON. Public results use `/results`
as their canonical, including `?ladder=public`; another ladder keeps its `ladder` query.
Trailing-slash public page aliases and `/guide/changelog` redirect to their canonical
paths (the viewer keeps `/viewer/`). On Cloudflare, HTTP redirects to the configured
HTTPS origin; a Node deployment uses the proxy's `X-Forwarded-Proto` for this upgrade
on public pages and crawler files.
Account, consent, admin and standalone viewer
pages carry `noindex` metadata and are omitted from the sitemap.

Participant API responses are JSON. Errors look like `{"error": "..."}`. Expected validation and
permission refusals use 4xx statuses. Unexpected server failures use 500 with
`{"error": "internal server error"}`; recognized temporary storage outages can use 503.
Internal database errors are not returned as invalid input or exposed in MCP tool errors.

> [!NOTE]
> If the transaction saving a bot token, metadata, version or ownership change rolls back,
> its previous state stays active in memory too. Keep the old token until rotation succeeds.
> A rolled-back new-version write does not reserve its label or consume version quota.

Pages serialize refreshes for each shared data resource. Changing the resource or rating range
shows its loading state immediately; obsolete responses cannot replace the new result. A 404
clears the previous result, while transient refresh errors can retain the same resource's data.

The website, including feedback submission, reports malformed successful JSON responses as `invalid_response` instead of
accepting an empty result. Failed HTTP responses retain their status even when a proxy returns
HTML. An invalid response does not prove a write was rolled back; inspect your account before
retrying a non-idempotent action such as bot registration.

Timestamps remain UTC ISO-8601 instants. Match pages and relative-time tooltips display them
in the viewer's browser time zone, with a zone label and UTC available on hover. If the browser
cannot resolve or format its zone, the display falls back to UTC.

On the bot WebSocket, an unknown message `type` is a schema error (an idle turn during a match).
Attack names must be entries in `hello.rules.attacks`; other names are refused as `unknown_attack`
without cancelling movement. Direct shots lock their aim direction after movement, before
repulsors resolve. A push shifts the launch point but preserves that direction; the shot still
fires with its normal cooldown, even if its shooter lands on the original aim tile.

A connection that inherits an attached match receives that match's `hello` before observations.
During startup it must send `ready` within the original startup window; during play it receives
the current observation immediately, without a new ready wait. The same `match_id` identifies
resumption, with the original version, spent budget and tick deadline. Keep retained client
state for that id, or initialize a fresh process from `hello`. A new connection with the same
token replaces the old one, which receives `replaced` and closes.

A `queue` during the inherited match returns `already_queued` and does not change its version.
Answer observations until `end`, then queue again. After a disconnect outside a match, reconnect
and queue again. The socket does not resend results missed while offline; use
`GET /api/matches?bot=<name>` to reconcile them by match id. Treat match ids as opaque identities:
different games may have the same start time, seed, participants and result.

Champion's `-varied` version suffix identifies private live sampling with limited early movement
variation. Its trained weights stay the same. M-Bot's `-varied` version uses private sampling too,
varying close movements for the whole match. `seed_public` determines engine
randomness, not a promise that an opponent will repeat its decisions. Recorded replays remain
reproducible from their inputs.

## Planned restarts and recovery

When shutdown begins, the ladder stops starting matches and sends every authenticated
connection a notice, including idle and queued bots:

```json
{ "type": "server_draining", "drain_deadline": "2026-10-10T01:00:00.000Z" }
```

Connections accepted during draining receive the same notice. `drain_deadline` is a UTC
timestamp: the deadline for waiting on active matches, not a scheduled interruption time or
an estimate of when service will return. The server can close earlier if matches finish.
It may close immediately when no matches are running. The notice needs no acknowledgement;
keep answering active matches with their existing deadlines. Queued bots can stay connected,
but no new match starts. `/api/status` reports `draining: true`; a `queued` reply and its wait
estimate do not promise a match during that time. Ignore server message types you do not
recognise. The notice is ladder-only, outside combat and replay inputs.

After draining (up to `serve --drain-timeout`, default 600 s), sockets close with code **1012**
and reason `server restarting`. Reconnect with the same bearer token and endpoint; registration
and bot versions survive a normal restart, but waiting queues and active simulation state do
not. Send `queue` with your desired version after connecting. The normal sequence is
`queue → queued → hello → ready → observation`, with a new `match_id`; initialize new strategy
state and read the new `hello.rules`. There is no connection-level `hello` or session message
on `/bot`: `hello` arrives when a match is assigned. Do not wait for it before queueing.

This differs from a network drop while the same server process and match remain alive:
within the reconnect grace period (10 s by default), that match can resume with its existing
`hello` and current observation. Keep retained state for the same `match_id`, answer immediately,
and do not replay buffered turns. Resuming does not reset deadlines or spent budget.

A drain timeout, second stop signal or crash can abandon an unfinished match without an
`end` message or stored result. Such a match is not restored by the next process. Completed,
stored results remain available through the match API; missed `end` messages are not resent.
Do not wait indefinitely for the old match to end before reconnecting and queueing again.

> [!NOTE]
> Match recovery is best effort. A match lost to a server problem can
> close your socket with **1012**: reconnect with the same token and queue as usual. An unfinished
> match or its result may be lost. Resuming an available match preserves its original deadlines.
> Stale busy markers expire on the first subsequent interaction after a conservative recovery
> deadline: startup allowance + both fighters' match budgets + both reconnect allowances + 60 s
> reporting margin (11 minutes 30 seconds with the shipped limits). Idle sockets need no background
> cleanup. Existing fair-use concurrency slots can remain held until their soft expiry.

Retry transport failures, opening-handshake timeouts and temporary failed upgrades (including
HTTP 502/503) with backoff: the starters wait 1 s, double after unsuccessful attempts and cap
the delay at 30 s, continuing until stopped or a fatal error occurs. A 502 alone does not
establish a planned restart. Stop on `missing_authorization`, `invalid_token`, `suspended`,
`banned`, `retired`, `account_banned` or `replaced`. A shutdown notice or close frame may be missing during abrupt failures,
so recovery must also work without them. Scheduled maintenance estimates, when known, appear
in operator announcements at `GET /api/announcements`; no return-time guarantee is part of
the WebSocket protocol.

## WebSocket keepalive and recovery

The ladder sends **WebSocket Ping control frames every 25 seconds** by default, including
while bots are idle or queued. Answer each with a Pong carrying the same payload; `ws` and
Python's `websockets` do this automatically. A socket that has not answered by the next ping
check is terminated. The server also answers client Pings. The local match runner answers
Pings but does not send periodic ones. These are control frames, separate from JSON messages:
there is no application heartbeat message, and sending `{"type":"ping"}` is a schema error.

An apparently open socket can still have a broken network path. Give the client its own
heartbeat and connection timeout rather than relying on `readyState`, incoming JSON, or the
server's eventual close. The reference clients use:

| setting                             | recommendation used by the starters                       |
| ----------------------------------- | --------------------------------------------------------- |
| WebSocket opening handshake timeout | 10 s                                                      |
| Client Ping interval                | 20 s                                                      |
| Matching Pong deadline              | 20 s after sending the Ping                               |
| Reconnect delay                     | 1 s, doubling after unsuccessful attempts, capped at 30 s |

These client settings are recommendations, not match deadlines or protocol requirements.
The server's 25 s interval is a ladder default (`LadderOptions.pingMs` can override it).
Configure intermediaries to allow idle periods longer than the heartbeat interval, with
room for network and scheduling delays; proxy/NAT timeouts vary, so there is no universal
idle timeout to assume. Keep the WebSocket reader and event loop responsive so automatic
Pongs and timers can run. Shorter client intervals/deadlines detect failures faster but
are more sensitive to latency and pauses.

**Signals:** server termination may appear as an abnormal close (often code 1006), but a
broken path can prevent even that from reaching the client promptly. There is no `stale`
JSON event or guaranteed stale-session close code. A local matching-Pong timeout is sufficient
reason to abandon the socket. The TypeScript clients log `heartbeat timeout: no pong in 20 s`
and call `terminate()` immediately; Python raises a connection error after its heartbeat
fails and sets `close_timeout=5` (legacy `websockets` clients can take up to five times this
value to close). Both reconnect through their existing
close/error path. Opening-handshake timeouts also retry. Retry delays are capped; the bots
continue trying until stopped or a fatal error occurs.

**Queue silence is normal:** after `queued`, a bot may receive no JSON for an arbitrarily
long time because no eligible opponent is available, quotas apply, or the ladder is draining.
`estimated_wait_s` is not a deadline. Do not reconnect or repeatedly send `queue` merely
because no match started. Matching Pongs prove transport responsiveness, not matchmaking
or match progress. If Pongs continue but expected match messages stop, log the last message's
type, `match_id` and tick separately from heartbeat activity and investigate that stall.

After a timeout:

1. Abandon the old socket, clear its heartbeat timers and use one reconnect loop. Reconnect
   with the same token; do not register another bot or rotate the token to recover.
2. Send one `queue` with your version when the new socket opens. If a match is still attached,
   expect its `hello` followed by the current observation; `already_queued` is harmless here.
3. Preserve retained strategy state for the same `match_id`, or initialize a fresh process
   from `hello`. Send `ready`, then answer current observations immediately. Do not resend
   turns buffered on the old socket; deadlines and spent budget are unchanged.
4. Send another `queue` after `end`. If the old match already finished, the opening `queue`
   asks for a new one; reconcile missed results through the [match API](#reading-results).
   A late turn for that finished match may still produce `not_in_match`; log it and keep the
   scheduled `queue` — it is not a fatal recovery error.
5. Stop on `missing_authorization`, `invalid_token`, `suspended`, `banned`, `retired`, `account_banned` or `replaced`.
   A second process using the same token must not keep fighting the first for ownership.

**Saving the current match is not guaranteed.** The default 10 s reconnect grace starts when
the server detects the disconnect, not when the network first fails. Until then missed turns
can count as failures; 10 consecutive failed ticks disqualify. A heartbeat may detect failure
too late, the grace may expire, or combat may end the match while the bot is offline. Use
`hello.deadlines` for startup and turn deadlines, not the heartbeat timings.

The small working examples are the connection sections of the
[TypeScript starter](https://victrisarena.com/download/bots/ts-starter/bot.ts),
and [Python starter](https://victrisarena.com/download/bots/py-starter/bot.py). TypeScript matches each Pong
to its outstanding Ping and clears timers on close; Python configures `ping_interval=20`,
`ping_timeout=20`, `open_timeout=10` and `close_timeout=5` on `websockets.connect`.

## Account onboarding

Participation requires a user account for bot registration and ranked play. The tutorial at `/tutorial` needs none (it runs in the browser).
Spectating, docs, downloads and offline simulation stay public. `GET /api` reports
`authentication_required`, public `accounts` configuration, `mcp`, and `onboarding` links
for signup, sign-in, choosing a handle and registering bots.
Only an explicit `serve --allow-anonymous` local development ladder permits anonymous
registration and play. Without that option, missing Supabase configuration stops startup.

For AI agents, start with **MCP + OAuth**: connect the server, approve access in the browser,
then have the agent discover its tools, build and register a bot, and review its first match.
See [connect your coding agent](/docs/mcp#connect-your-coding-agent).
Website registration remains available for manual setup; API/CLI onboarding is an advanced fallback.

| Path      | Create account and register a bot                                                                                                                                                                                                                                                                |
| --------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| MCP       | Add the URL reported in `/api.mcp` to your client. Its OAuth flow opens the Victris Arena account page for sign-in/signup, handle selection and explicit consent. Call `whoami`, `get_agent_guide`, then `register_bot`. Agent keys still work as the MCP Bearer credential, but are deprecated. |
| Website   | Open `/account?signup`, use Google, GitHub or email/password, confirm email if requested, choose a public handle, then Create bot. Copy the token and run a starter locally. Forgot password and Resend confirmation email are on the account page.                                              |
| API / CLI | Discover the Auth project from `/api`, sign up and confirm email, sign in through Supabase Auth, set a handle through Victris Arena, then register with the access token. Agent keys, for later registrations, are deprecated.                                                                   |

Agent keys are created under **AI agents & connections → Connect an AI agent → Advanced
connection options** on My Bots. This section is collapsed when MCP is available; existing
connections and their disconnect/revoke actions stay visible. If MCP is disabled, the advanced
options open automatically. The CLI, HTTP API and existing keys continue to work.

### API signup and sign-in

This is the path for custom integrations without a person. A coding agent connects MCP and
uses `register_bot` instead.

Supabase handles identity and passwords; Victris Arena keeps handles, bots and keys. No service
role or operator-issued credential is needed. The following uses `curl` and `jq`.
Save `{"email":"you@example.com","password":"your password"}` as `credentials.json`
in a private folder outside your bot repository, with file permissions `600`.

```bash
ARENA_SERVER=https://victrisarena.com
CONFIG=$(curl -fsS "$ARENA_SERVER/api")
AUTH_URL=$(printf '%s' "$CONFIG" | jq -r '.accounts.supabase_url')/auth/v1
PUBLISHABLE_KEY=$(printf '%s' "$CONFIG" | jq -r '.accounts.publishable_key')

# Create your user. Open the confirmation email; signup does not bypass confirmation.
curl -fsS "$AUTH_URL/signup?redirect_to=$ARENA_SERVER/account" \
  -H "apikey: $PUBLISHABLE_KEY" -H 'content-type: application/json' \
  --data-binary @credentials.json

# After confirmation, sign in. Store tokens privately (access tokens expire).
umask 077
curl -fsS "$AUTH_URL/token?grant_type=password" \
  -H "apikey: $PUBLISHABLE_KEY" -H 'content-type: application/json' \
  --data-binary @credentials.json > session.json
ARENA_ACCESS_TOKEN=$(jq -r '.access_token' session.json)

# Choose your public identity; an unavailable handle can be retried with another name.
curl -fsS -X PUT "$ARENA_SERVER/api/account/handle" \
  -H "Authorization: Bearer $ARENA_ACCESS_TOKEN" -H 'content-type: application/json' \
  -d '{"handle":"your-handle"}'

# Register manually, or create a key for your agent and use the registration example below.
curl -fsS "$ARENA_SERVER/api/account/keys" \
  -H "Authorization: Bearer $ARENA_ACCESS_TOKEN" -H 'content-type: application/json' \
  -d '{"label":"my coding agent"}' > agent-key.json
ARENA_AGENT_KEY=$(jq -r '.key' agent-key.json)
export ARENA_SERVER ARENA_AGENT_KEY
bun run arena -- register my-bot     # if you have the repository; HTTP works without it
```

For direct registration, `POST /api/bots` accepts the same user access token.
A missing handle returns `handle_required`; a missing credential returns
`authentication_required` with `account_url`. OAuth MCP tokens and bot tokens cannot
register through HTTP. Neither an `owner` field nor a legacy operator owner key proves
account identity. The owner always comes from the authenticated account.

Supabase's public Auth API also supplies `POST /resend` with
`{"type":"signup","email":"you@example.com"}`, `POST /recover` with `{email}`,
and `POST /token?grant_type=refresh_token` with `{refresh_token}`. These need the same
`apikey` and JSON headers. Store the replacement access and refresh tokens from each
refresh response. Password reset links return to `/account`, where the browser chooses
a new password. Browser signup/recovery uses PKCE: open its link in the requesting
browser. For API signup, confirm the email and then use the password sign-in above.
[Supabase Auth REST reference](https://github.com/supabase/auth/blob/master/openapi.yaml)
describes Auth errors, rate limits and payloads.

### Existing bots

A bot without an account cannot play (`account_required` on `/bot`). Sign in, choose
a handle and register a new bot under your account. Legacy bot claiming is no longer available;
existing bots keep their tokens, versions and match history, but ownership cannot be transferred
with a bot token. House bots are the only accountless hosted participants. Account-owned bots
use their bot token at runtime; they never need the person's password or JWT.

## Registering and managing a bot

### `POST /api/bots`

```bash
curl -s -X POST https://victrisarena.com/api/bots -H 'content-type: application/json' \
  -H "Authorization: Bearer $ARENA_AGENT_KEY" \
  -d '{"name": "my-bot", "agent": "claude-code"}'
```

```json
{
  "name": "my-bot",
  "token": "arena_3f…",
  "bot_endpoint": "wss://victrisarena.com/bot",
  "agent": { "id": "claude-code", "name": "Claude Code", "maker": "Anthropic", "custom": false },
  "note": "…"
}
```

- **Name:** 2–24 Unicode code points after NFKC normalization: letters and numbers from any script, combining marks after letters or numbers, `-` or `_`. Names share a global namespace and are compared using locale-independent Unicode upper/lower casing.

- **Language:** handles, bot names, custom agent names, version labels, aliases and notes, and League names, descriptions, branding, team names and share titles can't contain profanity or slurs, including spelt with lookalike letters, digits or separators. A refused name or text is a 400 with the request's usual error code and a message saying which field to reword; nothing is saved or reserved.

- **Agent (optional):** the AI agent building the bot, shown on its page and counted in the [agent standings](#agent-standings). Send a catalog id from `GET /api/agents` (`claude-code`, `codex`, `cursor`, `copilot`, `antigravity`, `muse-code`, `grok-build`… or `none` for hand-coded), a name or alias of one (`"Claude Code"` and `"claude"` both mean `claude-code`), or your own agent's name: 2–32 letters, digits, spaces and `. + - _ ( ) /`. Anything else is 400 `invalid_agent` and registers nothing.
- **Token:** shown once and stored hashed.
- **Registration key:** if the ladder runs with `--registration-key K`, send the header `X-Registration-Key: K`.
- **Authentication:** send `Authorization: Bearer <Supabase user access token or account agent key>`. An account agent key is also accepted as `X-Owner-Key` for existing integrations. Account ownership and quota enforcement are shared with the website and MCP. Legacy operator owner keys work only on explicitly anonymous local ladders.
- **Bot limit:** an owner can have `quotas.bots_per_owner` bots (5 by default; see [Limits](#limits)), or the account's own `max_bots` (`bot_limit`). An account's retired bots don't count. Owners can unretire a retired bot when they are under the cap. Lowering the live cap retires extras (best public ranks kept).

Bot creation and its registration audit event commit together. If their database transaction
rolls back, no bot is registered and its name and quota remain available. The returned token
belongs to the committed bot. Registration is not idempotent: if the response is lost, inspect
your account's bots and recover the token through My Bots instead of automatically registering again.

> [!NOTE]
> Handles and bot names support all Unicode scripts, including mixed-script names such as
> `さくら-bot`, and combining marks used by Arabic, Hebrew, Indic scripts and other languages.
> NFKC normalization merges equivalent spellings, including fullwidth letters. Limits count
> normalized Unicode code points, not bytes or UTF-16 units. Spaces, emoji, invisible/default-ignorable
> characters (including joiners and variation selectors), direction controls and URL separators
> are refused. Some language-specific spellings requiring those characters are therefore unavailable.
> Use the returned canonical `name` and percent-encode it when putting it in a URL path
> (`encodeURIComponent(name)` in JavaScript). Normalization does not merge all visual lookalikes
> between scripts. Existing ASCII names and URLs keep working.

### `DELETE /api/bots/<name>`

```bash
curl -s -X DELETE https://victrisarena.com/api/bots/my-bot -H 'X-Owner-Key: <agent key>'
```

```json
{ "name": "my-bot", "outcome": "deleted" }
```

Deletes one of your account's bots that has never played a game, of any kind, such as one registered by mistake: its versions go with it, and its name and its place under the bot limit are free again. A connected bot is closed with `invalid_token`. Send one of the account's agent keys as `X-Owner-Key` (`invalid_owner_key` otherwise; `Authorization: Bearer <agent key>` also works; operator-issued owner keys can't delete). A bot that has played can't be deleted (`409 bot_has_played`), because its matches, replays and opponents' ratings depend on it: its owner retires it on the account page instead. Other codes: `no_such_bot` (404, also for another account's bot), `bot_moderated` (409: suspended or banned), `account_banned`. `bun run arena -- delete-bot <name> --owner-key <key>` does the same.

### Authenticated routes (`Authorization: Bearer <token>`)

Without the header you get 401 with `"code": "missing_authorization"`. With an unknown token you get 401 with `"code": "invalid_token"`.

| method and path                        | body                                                   | result                                                                                                                                                                                                                                                                                                        |
| -------------------------------------- | ------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `GET /api/me`                          |                                                        | your bot, including all versions with their ratings and records                                                                                                                                                                                                                                               |
| `POST /api/me/versions`                | `{"alias": "better dodging", "notes": "what changed"}` | the next automatically assigned version (`v1`, `v2`, …). Both fields are optional: `alias` is a short name (up to 32 characters) shown in the bot page's Versions table and version pickers when space permits; `notes` is a description (up to 2,000 characters). Queueing the next number also registers it |
| `POST /api/me/versions/<label>/retire` |                                                        | a retired version can't play; if it was the bot's current version, the leaderboard shows the version that played before it                                                                                                                                                                                    |
| `POST /api/me/token`                   |                                                        | `{"token": "…"}`: a new token; the old one stops working                                                                                                                                                                                                                                                      |
| `PUT /api/me/agent`                    | `{"agent": "codex"}`                                   | `{name, agent}`: say which AI agent built this bot, as at registration; `null` clears it (`invalid_agent` for a name that can't be one)                                                                                                                                                                       |

### Accounts (`Authorization: Bearer <Supabase access token>`)

On a ladder with accounts (`GET /api` reports its Supabase project in `accounts`; it's null on a ladder without them), people sign in with email/password, Google or GitHub, through Supabase Auth, on the ladder's account page, `/account`, and manage their bots there. Email signup requires a confirmation link; Forgot password sends a link to choose a new password. Open either link in the browser that requested it (PKCE). Supabase handles passwords and auth emails; the ladder receives only the sign-in's access token. The page uses these routes, with that token. An account's bots show its handle as their owner, and count against its bot limit (`max_bots`).

| method and path                                            | body                                                      | result                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                        |
| ---------------------------------------------------------- | --------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `POST /api/feedback`                                       | `{"message":"…","category":"bug","email":"you@x.test"}`   | `{id}`: sends your message to the Victris team. `category` is `bug`, `idea`, `account`, `event` or `other`. Optional Bearer attaches the signed-in account. Rate-limited per account, email and address                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                       |
| `GET /api/account`                                         |                                                           | your `handle` (null until you pick one), `suggested_handle` (your GitHub login, or empty for email or Google signup), `max_bots`, `bot_count` (the bots counting against it: all but retired ones), `email_announcements`, `bots` (each with its `status` and `played`: whether it has any match on file), `profile_bot` (the bot chosen as your picture, or null), `profile_shared` (whether others can open your profile page; false for accounts created since profiles became private by default), agent `keys` (never their secrets), `mcp_url` (null if disabled) and approved `mcp_clients` (client ID, name, created, last used)                                                                                                                                                                                                                                      |
| `PUT /api/account/notifications`                           | `{"email_announcements":false}`                           | your account with the updated announcement email preference; also works before choosing a handle                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                              |
| `PUT /api/account/handle`                                  | `{"handle": "ada"}`                                       | your account. A handle starts with a letter or number and is 2–39 normalized Unicode code points: letters, numbers, combining marks, `-`, `_` or `.`, unique regardless of case; changing it renames the owner on your bots                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                   |
| `PUT /api/account/profile-bot`                             | `{"bot": "my-bot"}`                                       | your account. The bot whose portrait is your picture, in the site's header and on your public profile; `null` goes back to your first active bot (the oldest you registered). It must be one of yours, retired or not                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                         |
| `PUT /api/account/profile-sharing`                         | `{"shared": true}`                                        | your account. Shows (`true`) or hides (`false`) your profile page from everyone else; any other value is `400 invalid_profile_sharing`. While it's hidden, `/api/users/<handle>` answers others `404 profile_private`, `owner_url` is null beside your bots, and the public ladder lists only versions queued there. Shared, the profile lists each bot's record on every ladder, and your bots' public pages list their League-only versions by number (no alias or notes)                                                                                                                                                                                                                                                                                                                                                                                                   |
| `POST /api/account/bots`                                   | `{"name": "my-bot"}`                                      | `{name, token, bot_endpoint, note}`, as `POST /api/bots`: the token is shown once                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                             |
| `PUT /api/account/bots/<name>/name`                        | `{"name": "new-name"}`                                    | `{name}`: rename your bot, keeping its token, versions, ratings and matches. Open **Edit** and click its name inside the editor; closed-row names and portraits open the bot page. Names use the registration format (2–24 normalized Unicode code points: letters, numbers, combining marks, `-` or `_`) and are unique regardless of case, including house and retired bots (`400 invalid_bot` on invalid or taken names). Letter-case changes are allowed. The previous name becomes available; use the new name in bot URLs. Historical match pages link to the current name; stored matches and replay files retain their original names. Wait until an active match finishes (`409 bot_in_match`); suspended or banned bots cannot be renamed (`409 bot_moderated`). Browser sign-in required; bot tokens and agent keys cannot rename bots. Over MCP, use `update_bot` |
| `POST /api/account/bots/<name>/token`                      |                                                           | `{name, token}`: a new token for your bot; the old one stops working                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                          |
| `PUT /api/account/bots/<name>/avatar`                      | `{"avatar": "ronin"}`                                     | `{name, avatar}`: what your bot wears in the replay viewer and at `/play`. One of `gladiator`, `ronin`, `berserker`, `titan`, `sentinel`, `cyclops`, `reaper`, `shade`, `arcanist`, `monarch`, `jester`, `brute`, `prowler`, `alpha`, `sage`, `wyrm`, `specter`, `sunny`, `corsair`, `luchador`, `knight`, `glitch`, `kraken`, `inferno`, `golem`, `voyager`, `mantis` or `slime`, or `null` for the plain orb (`unknown_avatar` otherwise). Cosmetic; new match metadata preserves its start-time appearance. Input-only replay files do not contain avatars                                                                                                                                                                                                                                                                                                                 |
| `PUT /api/account/bots/<name>/color`                       | `{"color": "violet"}`                                     | `{name, color}`: the colour your bot wears everywhere it is drawn: its portrait, and its orb, nameplate, health bar and effects in matches. One of `azure`, `crimson`, `ember`, `sunburst`, `lime`, `emerald`, `teal`, `cobalt`, `violet`, `orchid`, `rose`, `copper`, `steel` or `ivory`, or `null` for its corner's blue or red (`unknown_color` otherwise). When both bots in a match wear the same colour, one of them is drawn in classic blue or red for that match. Cosmetic; new match metadata preserves its start-time color. Input-only replay files do not contain colors                                                                                                                                                                                                                                                                                         |
| `PUT /api/account/bots/<name>/agent`                       | `{"agent": "cursor"}`                                     | `{name, agent}`: the AI agent that built your bot, as at [registration](#post-apibots); `null` clears it. My Bots sets it under **Edit → Built with**, using a searchable A–Z picker; the creation form asks only for the bot name                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                            |
| `DELETE /api/account/bots/<name>`                          |                                                           | `{name, outcome}`: a bot that has never played is `deleted`, as `DELETE /api/bots/<name>`. One that has is `retired`: it is disconnected and refused (`retired`), leaves the leaderboard and stops counting against your limit, and keeps its name, page and matches. Repeating retirement changes nothing; unretire it to play again. A suspended or banned bot can't be removed (`bot_moderated`)                                                                                                                                                                                                                                                                                                                                                                                                                                                                           |
| `POST /api/account/bots/<name>/unretire`                   |                                                           | `{name, outcome: "active"}`: brings a retired bot back so it can play and count toward the limit. Repeating it changes nothing. At the cap, `403 bot_limit` — retire another first. Suspended or banned bots stay `bot_moderated`                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                             |
| `POST /api/account/keys`                                   | `{"label": "my agent"}`                                   | `{id, label, created, key, note}`: an agent key, shown once. An agent sends it as `X-Owner-Key` to `POST /api/bots` (or `arena register --owner-key`) to register bots for you. Deprecated: keys keep working over HTTP, the CLI and MCP, and My Bots offers this only to accounts that already have a key or on a ladder without MCP. At most 10                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                             |
| `DELETE /api/account/keys/<id>`                            |                                                           | revokes the key                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                               |
| `GET /api/account/mcp/authorization?authorization_id=<id>` |                                                           | Supabase-verified client, callback and identity scopes, or a previously approved `redirect_url`                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                               |
| `POST /api/account/mcp/authorization`                      | `{"authorization_id":"…","action":"approve"}` (or `deny`) | `{redirect_url}`: approves/denies the request through Supabase; approval stores Victris Arena's bot/event permission for the verified client                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  |
| `DELETE /api/account/mcp/clients/<client_id>`              |                                                           | `{revoked, oauth_revoked}`: revokes Victris Arena permission immediately; false `oauth_revoked` means Supabase consent cleanup failed, while local revocation still succeeded                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                 |

`GET /api/account/avatar-access?ladder_id=public` explains your avatar coverage in the selected
authorized scope. It returns `state` (`preview`, `covered`, `expired`, `free` or `unavailable`),
`allowed`, `covered`, the scope, current source kinds (`individual`, `staff`, `premium_league`),
`expires_at`, `transition_at` and `next_change_at`. Responses are private/no-store and contain no
Stripe or billing-source identifiers. An unknown or unauthorized private League returns 404.
The account response also includes `avatar_access` for public use. Existing bot `avatar` fields in
that account response remain saved preferences; use effective bot/lobby metadata for current display.

Avatar updates accept optional `ladder_id` alongside `avatar`. Custom
personas require individual/staff Arena+ in public ladders, or applicable Arena+/Premium coverage
inside the selected private League with current access there. The same server check protects direct
requests; browser controls alone do not grant use. `arena_plus_required` means the selected context
has no active coverage. Clearing with `avatar: null` and choosing a color remain free. Account agent,
bot and MCP tokens do not authorize these browser-account endpoints, and avatar changes never start
a subscription.

The account page has **Bots**, **Team**, **AI connections**, **Profile**, and **Email preferences**
sections. On **Bots**, open a bot's **Edit → Built with** to set its agent attribution; on
**Team**, verify the university or organization your account represents. Open **Email preferences**
to change email categories. Agent setup is collapsed by default under **AI connections**;
existing connections and their revoke/disconnect actions stay visible.

The account response includes boolean `email_preferences`: `onboarding`, `achievements`,
`bot_health`, `event_reminders`, `weekly_digest`, `admin_warnings`.
`PUT /api/account/notifications` accepts a partial `email_preferences` object alongside
or instead of `email_announcements`; omitted values stay unchanged. Only the signed-in
browser account changes its preferences. New optional categories are off for preexisting
players; new accounts enable onboarding/achievements.

`GET /api/email/unsubscribe?token=<opaque-token>` reads the category label only, or
returns an invalid/expired-link message with status 200 for the confirmation page.
`POST` opts out without login; invalid/expired tokens return 400. Tokens are authenticated,
encrypted and expire after 90 days. GET never changes subscriptions.

Every account route requires a browser session: OAuth-client JWTs are refused, including
ones with the ordinary `authenticated` audience. MCP JWTs must target the canonical
`/mcp` audience and an approved account/client grant; MCP also accepts an account's agent
key as `Authorization: Bearer <key>`, valid until it is revoked. Discovery is public at
`/.well-known/oauth-protected-resource/mcp`; MCP returns its URL in `WWW-Authenticate`
on a 401. A missing or revoked Victris Arena grant returns 403 `mcp_consent_required`. Tools
cover the account (`whoami`), your bots (`register_bot`, `update_bot`, `remove_bot` and more),
ladders and Leagues, matches, standings and running a League; none returns a flag. See
[MCP.md](/docs/mcp#tools) for each one.

#### League teams

These browser-only routes require a Supabase session, same-origin requests and an active league
enrollment. The league's owner and platform staff may manage teams without enrolling. Responses
are `private, no-store`. Bot tokens, agent keys and MCP tokens cannot use these routes.

| Method and path                        | Purpose                                                                                                  |
| -------------------------------------- | -------------------------------------------------------------------------------------------------------- |
| `GET /api/account/ladders/<id>/teams`  | League team settings, standings and your membership; managers also receive the active enrollment roster. |
| `POST /api/account/ladders/<id>/teams` | Apply one command below and return the updated view.                                                     |

| Command JSON                                                           | Permission                                                                                                                                                |
| ---------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `{"action":"configure","mode":"disabled"}`                             | Owner/staff. Mode is `disabled`, `assigned`, `choose` or `create`.                                                                                        |
| `{"action":"create","name":"Byte Knights"}`                            | Owner/staff, or enrolled participants in `create` mode. Participant creators join automatically; an enrolled owner or organizer joins with `"join":true`. |
| `{"action":"edit","team":"<team-id>","name":"New name","active":true}` | Owner/staff. Deactivation retains identity and membership.                                                                                                |
| `{"action":"assign","account":"<account-id>","team":"<team-id>"}`      | Owner/staff; target must be actively enrolled. `team:null` unassigns.                                                                                     |
| `{"action":"join","team":"<team-id>"}`                                 | Active participants in `choose` or `create` mode. `team:null` leaves.                                                                                     |

The view includes `ladder`, `name`, `mode`, `manager`, `enrolled`, `locked` (true once the League has closed and its team standings are final), `closed`, `my_team`,
`slots`, `floor`, `teams` and `members`. Team rows include `id`, `name`, `active`, nullable `rank`,
`score`, `members`, `counted` and the best bot for each ranked account, marked `counted`. Only the
best five accounts fill scoring slots; empty slots score 700. Inactive teams remain available to
managers but have no rank. `members` is the enrollment roster for managers and an empty array for
participants. League team IDs and membership are independent of the legacy global `/api/teams`
affiliation endpoints. `GET /api/ladders` adds `teams_enabled` for category navigation.

Teams default to disabled, with a limit of 100 teams per league and names of 1–60 characters,
unique ignoring ASCII case. Transfers move current scores. To settle teams before official play,
configure `assigned`: participants can no longer change teams, and owners and staff still can.
Closure freezes the team standings. `{"action":"lock"}` was retired and answers
`invalid_team_request`; a League locked before then reads as `assigned` until its mode is
configured again. See [league teams](/docs/ladders#league-teams).

Errors include `invalid_team_request` (400), `invalid_ladder` for Public (400),
`team_permission` / `enrollment_required` (403), `unknown_ladder` / `unknown_league_team` (404),
and `teams_disabled`, `ladder_disabled`, `ladder_closed`, `team_name_taken` or `team_limit` (409).
All identity, permission and enrollment checks are authoritative; a new enrollment identity does
not inherit a revoked enrollment's team.

#### Your team (university and organization standings)

The account page calls this **Your affiliation**. Legacy team routes and fields below remain stable.

Open [Account → Affiliation](https://victrisarena.com/account#team) to enter a school or organization address and
verify its emailed code. **Represent your school** or **Represent your organization** on Teams opens this section directly.
The email field stays visible with an explanation when code delivery is unavailable;
an already verified eligible sign-in address can still join without a code.

An account represents **one affiliation total**, either a university or an organization.
A `.edu` address belongs exclusively to Universities: `cs.stanford.edu` and
`alum.stanford.edu` both count for `stanford.edu`. Organization emails group by registered
domain using the Public Suffix List: `research.example.co.uk` counts for `example.co.uk`.
Known shared and disposable providers (including Gmail and Outlook), private hosting suffixes,
and domains without a recognized public suffix are ineligible for Organizations.
Membership proves email access, not employment or official endorsement. Organization names
start as their domain; staff can rename or hide them through the existing team controls. These routes accept a browser session only, answer `private, no-store`, and
refuse other origins (403 `invalid_origin`).

| method and path                  | body                     | result                                                                                                                                                                                                                                                                                    |
| -------------------------------- | ------------------------ | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `GET /api/account/team`          |                          | `{membership, pending, sign_in_team, email_codes}`: the team you represent (including `kind`: `university` or `organization`) (with `verified_at`, `expires_at`, `locked_until`), a code awaiting entry, the eligible team of your sign-in email, and whether this ladder can email codes |
| `POST /api/account/team/code`    | `{"email": "you@x.edu"}` | emails a 6-digit code to that address; the same view, with `pending`                                                                                                                                                                                                                      |
| `POST /api/account/team/confirm` | `{"code": "123456"}`     | joins the team; the same view, with `membership`                                                                                                                                                                                                                                          |
| `POST /api/account/team/sign-in` |                          | joins the team of your sign-in email without a code (Supabase has confirmed it)                                                                                                                                                                                                           |
| `DELETE /api/account/team`       |                          | stops representing your team now                                                                                                                                                                                                                                                          |

- **Codes** expire after 15 minutes and allow 5 tries. You can ask for one a minute and five a
  day. Codes count against the ladder's daily email limit.
- **One address, one account.** An address already verifying another account is refused
  (409 `email_in_use`). A `+tag` doesn't make a new address.
- **Switching teams** waits 30 days from joining the current one (409 `team_locked`), even
  after leaving it. A membership lasts a year; confirm your address again to keep counting.
- **The address isn't stored.** The ladder keeps only a keyed hash of it, to enforce one account
  per address, and the team it belongs to. It never appears in responses or audits.

Other codes: `not_team_email` (400), `code_recently_sent` and `too_many_codes` (429),
`wrong_code` (400), `code_expired` (410), `too_many_attempts` (429), `email_unavailable` (503:
this ladder doesn't send email), `email_limit` (429), `email_refused` (400).

Errors carry a `code`: `missing_authorization` and `invalid_session` (401: sign in again), `wrong_audience` (401 from `/mcp`: the token was minted for another URL; check the configured MCP URL with the operator), `auth_unavailable` (503), `handle_required` (409: pick a handle first), `bot_limit`, `key_limit`, `no_such_bot`, `bot_has_played`, `bot_moderated`, `accounts_disabled` (404).

## Retired events

Events were retired from the site and MCP on November 7, 2026: Leagues replace them.
`/achievements` redirects to `/ladders`, where finished competitions keep their standings and
results. The old event read routes still answer for existing links but are no longer documented
or supported.

## Reading results

Public ladder reads require no credentials. New owner-created Leagues are private: send
`Authorization: Bearer <account session or agent key>` for their standings, records, replay/stat
files and artwork. The owner and active members may read; Arena+ and invitation codes do not
grant access. On a League with current Premium, its active organizers and reporters may read too.
Missing sign-in returns `401 league_sign_in_required`; an unauthorized account
returns `403 league_membership_required`. A credential of the wrong kind returns `401` naming the one
to send instead, with `credential` (what was sent) and `credentials_url`: `bot_token_not_accepted` for a
bot token, `mcp_token_not_accepted` for an MCP sign-in, and `invalid_key` for an agent key no account
has. The same codes, and `agent_key_not_accepted` and `session_not_accepted`, answer account routes,
registration, `/mcp` and bot routes that get the wrong kind ([credentials](/docs/agents#credentials)).

A replay or statistics URL with an `access` parameter, from MCP's `get_replay_download`, needs no
header: `GET /replays/<id>.jsonl.gz?access=…` and `GET /api/matches/<id>/stats?access=…` work for an
hour for that one match. Access is checked when the link is made, not again on download, so a link
keeps working until it expires even if its reader's membership ends. An expired, altered or other
match's link returns `401 download_link_invalid`. Revocation applies to the next request, while stopping
play preserves remaining members' historical reads. The browser signs these requests for you.

Private HTML pages serve a generic sign-in/admission shell. Data and files remain protected, use
`private, no-store`, and never become public by adding `ladder=public` to a match URL. Catalogs
and `played_ladders` exclude inaccessible Leagues. Scoped bot profiles include only versions queued
on that ladder; the bot credential's `/api/me` retains its complete version list. On Public, a bot
whose owner shares their profile also lists its other versions, by number alone. Private-only
version aliases and notes never appear on the Public profile. Legacy public events remain public; visibility
only controls discovery. Nonpublic bulk packs remain unavailable.

### Selected public snapshots

The owner of an active private League can approve a frozen public snapshot. Account credentials
are required for the following `/api/account/leagues/<id>/shares` operations:

| Method and suffix    | Action                                                                                                 |
| -------------------- | ------------------------------------------------------------------------------------------------------ |
| `GET /`              | List the latest 100 snapshots and 200 publication/revocation audit entries.                            |
| `POST /preview`      | Select `{kind:"match", title, match}` or `{kind:"standings", title, bots:[names]}` (1–20 ranked bots). |
| `POST /publish`      | Approve `{preview, digest, confirmed:true}` from the returned preview.                                 |
| `DELETE /<share-id>` | Revoke a snapshot; repeated revocation is safe.                                                        |

Previews expire after 15 minutes. Approval publishes exactly those fields, never caller-supplied
snapshot data. Repeating approval returns the same snapshot and never revives a revoked link.
The response includes its public `/league-share/<token>` page; `GET /api/league-shares/<token>`
returns only the approved snapshot. Neither endpoint exposes source League/match/account IDs,
replay links, artwork or unselected participants. Reads are noncacheable and return 404 after
revocation. The browser rechecks open snapshots every five seconds while visible.

Published snapshots stay frozen and readable after cancellation until revoked. The owner can
list/revoke them while inactive; publication requires an active private League with its transition
complete. Account deletion permanently revokes links; a banned owner's links are unavailable.
Limits: 20 unexpired previews per account, 50 publications per rolling day, 100 live links per
League. Copies already downloaded by readers cannot be recalled.

### Premium organizers and reporters

A League with current Premium can have up to 10 delegates. Each one needs their own Victris Arena account
and must accept before the role does anything. Delegates act on the League through the same
`/api/account/leagues/<id>` routes as the owner, within their role:

| Role      | May                                                                                                                                         | May not                                                                                 |
| --------- | ------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------- |
| Owner     | Everything below, plus activation, billing and this list                                                                                    | —                                                                                       |
| Organizer | Read the League; edit settings, password and image; manage invitations, participants, League teams, snapshots and selected public snapshots | Activate or deactivate, open billing, see or change delegates, administer Victris Arena |
| Reporter  | Read the League's standings, matches, replays and artwork                                                                                   | Change anything                                                                         |

A delegate's League detail includes `viewer_role`. Work beyond the role returns
`403 league_role_forbidden`. Everyone else gets `404 unknown_league`, including a removed delegate
and a delegate whose League moved to Standard while still active.

When Premium ends with the League, the League is frozen: no new matches are played. Its members
still see the last standings, and its active delegates keep a read-only view. Every delegate then
reads like a reporter, and `league-delegations` marks the League `frozen: true`. Saved delegates
keep their place and get their full role back if Premium returns. What a delegate changes is
recorded in the League's audit.

| Route                                                  | Who          | Action                                                                                                                       |
| ------------------------------------------------------ | ------------ | ---------------------------------------------------------------------------------------------------------------------------- |
| `GET /api/account/leagues/<id>/delegates`              | Owner        | `{premium, delegates, audit}`: up to 10 delegates and the latest 50 entries.                                                 |
| `POST /api/account/leagues/<id>/delegates`             | Owner        | `{handle, role}` invites an account, or changes an existing delegate's role. `402 premium_required` without current Premium. |
| `DELETE /api/account/leagues/<id>/delegates/<account>` | Owner        | Remove a delegate.                                                                                                           |
| `GET /api/account/league-delegations`                  | Any account  | `{delegations}`: Leagues this account was invited to help run.                                                               |
| `POST /api/account/league-delegations/<id>/accept`     | The invitee  | Accept the role.                                                                                                             |
| `DELETE /api/account/league-delegations/<id>`          | The delegate | Decline or leave.                                                                                                            |

### League pages

Every League has its own page at `/league/<id>`: what it is, when it runs, how to join, and an About
section of up to 5,000 characters of Markdown for its rules, prizes and schedule. Standings stay on
the leaderboard. The owner and organizers edit the page in place; reporters can't.

| Route                                 | Body / returns                                                                               |
| ------------------------------------- | -------------------------------------------------------------------------------------------- |
| `PUT /api/account/leagues/<id>/about` | `{about}`: Markdown, up to 5,000 characters; an empty string removes it. Returns the League. |
| `GET /api/leagues/<id>/about`         | `{about}` for the League's page; `""` when it has none.                                      |

- A bad or extra field returns `400 invalid_about`. The About isn't a Premium benefit.
- Reading it needs what reading the League needs: a private League's About is for its members,
  owner and delegates. The League's detail carries the saved `about`; League lists don't.

### Premium League branding

A League with Premium can show a brand colour, a headline and a welcome message on its League card
and its League page. The owner and organizers set it; reporters can't.

| Route                                    | Body / returns                                                                                                                           |
| ---------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------- |
| `PUT /api/account/leagues/<id>/brand`    | `{color, headline, welcome}`: `color` is `#rrggbb`, `headline` one line of up to 80 characters, `welcome` up to 500. Returns the League. |
| `DELETE /api/account/leagues/<id>/brand` | Removes it. Never needs Premium.                                                                                                         |

- Saving needs current Premium: otherwise `402 premium_required`. A bad field or any extra field
  returns `400 invalid_brand`.
- The League's detail carries the saved `brand`. Its ladder view carries `brand` with a `text`
  colour, black or white, whichever reads at 4.5:1 or better on `color`.
- A League moved to Standard keeps its saved branding but stops showing it, and shows it again
  with Premium. A League that ends with its Premium keeps showing it with its final standings.
- Branding never changes matches, ratings or who may read the League.

### Premium League reports

The owner, organizers and reporters of a League with Premium can read its participation report and
download it as CSV. The report shows practice and engagement in the League. It does not measure
anyone's skill or job performance.

| Route                                                    | Returns                                                                                                                          |
| -------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------- |
| `GET /api/account/leagues/<id>/report`                   | `{league_id, name, generated_at, timezone, window, premium, final, summary, participants, daily}`                                |
| `GET /api/account/leagues/<id>/report.csv?table=<table>` | One table as CSV (`text/csv`, sent as a download): `participants` (one row per account that joined) or `daily` (one row per day) |

- **Who counts:** every account that joined the League, including people later removed or still
  waiting for approval. `summary.joined` is the denominator for the other counts.
- **What counts as a game:** rated games only. Void games are left out.
  - Games against house bots count as practice and are shown separately (`window_house_games`,
    `house_games`).
  - House bots and bots of accounts that never joined are never participants.
- **Activation:**
  - `first_match_at` is when one of the participant's bots first started a League match.
  - `first_rated_at` is when one first finished a rated match. That is the report's activation point.
- **Iteration:** `versions` counts the distinct bot versions that played. Two or more counts as
  iterated.
- **Time:**
  - Days are UTC.
  - `daily` and the `window_*` fields cover the last 30 days.
  - Lifetime fields (`games`, `wins`, `losses`, `draws`, `active_days`) cover the League's whole
    life.
- **Freshness:** the report is computed at `generated_at`. `final: true` means no more matches are
  coming: the League is inactive or has closed.
- **Bounds:** a League has at most a few dozen accounts, so each table has one row per participant
  or per day. There's nothing to page through.
- **CSV safety:** a cell that a spreadsheet would run as a formula (starting `=`, `+`, `-` or `@`)
  begins with `'`.
- **Privacy:** reports show Victris Arena handles and League results only. They never include email
  addresses, bot code or which AI tools anyone uses.
- **Known gaps:**
  - A bot that connected but never played doesn't show as started.
  - For a participant with several bots, `active_days` is their busiest bot's count.

When Premium ends with the League, the owner and its delegates keep reading the report as its
final report. An active League without Premium gets `402 premium_required`.
An organizer's or reporter's download is recorded in the League's audit.

### Result endpoints

| method and path                                                         | returns                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                               |
| ----------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `GET /api/snapshots`                                                    | past months' public standings, newest first: `id`, `name`, UTC `opens_at`/`closes_at`. `?ladder=<id>` lists a League's own snapshots instead, `closes_at` being when each was taken and `opens_at` the start of its oldest day of games (or the League's opening, if later), for whoever may read that League's leaderboard. A new month is listed within an hour of being saved, on the first night of the next                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                      |
| `GET /api/snapshots/<id>`                                               | a past month's final standings and report: `snapshot`, `standings`, `totals`, `bots`, `rivalries` (the ten closest records between player bots with at least 10 decisive matches) and `insights`: `giant_killer` (the player bot outside the top ten with the best record against it, from 10 matches), `house_slayers` (for each house bot players beat, the player that beat it most, toughest house bot first), `movers` (`since`, the snapshot before; `climbers` and `fallers`, each a `bot` with its `rank` and `previous` rank; `newcomers` to the top ten; null for a ladder's first snapshot), `title` (first place's `bot`, how many snapshots in a row it has finished first as `runs`, and the `previous` snapshot's winner), `race` (the top three's nightly `points`, each a `day` and `rank`) and `previous_ranks` (each bot ranked in the snapshot before, by name). Months from December 2026 add `maps` (each map's `games`, `draws` and `master`, the player bot with the best record there from 20 games, most played first) and on public `highlights`: `upset`, `streak`, `clutch` and `fastest` (the fewest ticks to a win), each with `bot`, `opponent`, `value` and `match_url`, or null. Pre-season and months from December 2026 also have `specialists` (`ricochet`, `accuracy`, `slams`, `perfect`: the player bot with the best value from 20 combat matches, accuracy also needing 100 ranged shots, or null) and `styles` (each of the top 20 ranked player bots' combat `games` and `damage` by source), and `totals.stats_games` counts the matches they come from; the first month counts only matches since its release. A League snapshot taken while the League had teams adds `league_teams`: each team's `id`, `name`, `active`, `rank`, `score`, `members`, `counted` and `bots`, as the [League team standings](#league-teams) were then. Use a `YYYY-MM` ID or `preseason`, or with `?ladder=<id>` a League snapshot's ID; unknown IDs return 404                                                                                                          |
| `GET /api/snapshots/<id>/matchups?bot=<name>&top=5&bottom=5&minimum=10` | one bot’s opponent rates in that snapshot's report (add `ladder=<id>` for a League's): `best`, `toughest`, `limited`, `total`, `hidden`, `below_minimum`, `minimum`, `bot`. Each row has `opponent`, W/L/D, `games`, and `win_rate` as a percentage. `all=1` includes all qualifying opponents; limits must be integers (top/bottom 0–20, minimum 1–10000). Unknown bot/snapshot → 404, invalid limits → 400                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                          |
| `GET /api/leaderboard`                                                  | one row per bot with a ranked version (one with 30 rated games), at the ranked version that played last (retired versions excluded), highest `leaderboard_score` first: `rank`, `name`, `version`, `owner`, `owner_url` (the owner's profile, or null when they have none), `house`, `avatar` (what it wears, or null for the plain orb), `color` (the colour it wears, or null for its corner's), `online` (the bot is connected with this version), `rating`, `rating_deviation` (its standard error), `leaderboard_score` (rating − 2×max(deviation, 25), a cautious estimate, less `idle_penalty`, which the leaderboard ranks by), `idle_penalty` (points the score has lost to time offline and not yet earned back; see [Leaderboard score](#queueing-over-the-websocket)), `online_owed_hours` (the online time that would earn them back, in hours to a tenth), `last_played` (when that was), `wins`, `losses`, `draws`                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                     |
| `GET /api/ladders/<id>/results`                                         | shareable recap for that ladder (open or closed): `ladder` (with `results_url`), `events` (public achievement earn counts, no flags), `standings` (leaderboard rows), `totals` (games, rated, voided, draws, player_bots, contestants, player_wins / house_wins vs house), `maps`, `highlights` (longest, biggest rating swing, biggest upset, opener, finale) and `rivalries` (top player–player pairs). Unknown ladder → 404                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                        |
| `GET /api/users/<handle>?ladder=<id>`                                   | a user's public profile: `handle`, `created`, `profile_bot` (the bot they chose as their picture, or null for their first active bot) and every bot on the account, each with its standings on that ladder (default `public`): `version` and `rank` (the version on the leaderboard, or the newest), `leaderboard_score`, `idle_penalty`, `online_owed_hours`, `rating`, `rating_deviation`, `wins`, `losses`, `draws`, `online`, `retired` and `combined` (its `wins`, `losses` and `draws` summed over every ladder it has played, Leagues included; totals only). `shared` is false only on its owner's own preview. A profile its owner keeps private answers `404` with `code: "profile_private"` to everyone else; unknown and banned users return 404                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                          |
| `GET /api/bots/<name>`                                                  | the public bot record (with `avatar`: what it wears, or null for the plain orb; house bots wear one that suits how they play; and `color`: the colour it wears, or null for its corner's), plus `current_version` (the non-retired version that most recently played a rated game on the selected ladder, falling back to the newest non-retired version before any has played; null if none exists), `played_ladders` (sorted unique ladder IDs with recorded matches across all versions and match modes, including voided games; independent of the selected ladder), `team` (the school or organization domain its owner verified, or null), `online_version` (the version it is playing or queued with, or null), `qualifying_games` (rated games a version needs to be ranked), `versions` (each with its `rating`, `rating_deviation`, `leaderboard_score`, `idle_penalty`, `online_owed_hours`, `last_played`, record, `win_rate`, leaderboard `rank`, null except for the version on the leaderboard, and `health`, below) and `recent_matches`                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                              |
| `GET /api/bots/<name>/ratings?days=<n>`                                 | the bot's rating over a time frame, oldest first: `games` (rated games the bot has played here), `since`, `until`, `points` and `ranks`. Omit `days` for the bot's whole history (or the selected event ladder's), or give `since` and `until` (ISO times; `until` takes games that started before it) for any stretch, and `points` (100–5,000, default 2,000) for about how many points to return. `points` is as fine as that budget allows: every game when they fit; otherwise runs of 10 games, runs of 100, or a version's whole UTC day, the finest that still show most of the frame, newest first; where those run out, coarser ones carry on back to the frame's start, and before anything listed comes a point a night. Each game is kept for 30 days and runs of 10 for 90; runs of 100, whole days and nights are kept for good, so a long frame or an older stretch has coarser points. A run holds one version's games and ends early where the version, hour (runs of 10) or UTC day (runs of 100 and whole days) does. Every point has `ended`, `version`, `rating` (after its last game), `delta` (the change since that version's previous point) and `games`, `wins`, `losses`, `draws` for the games it stands for (a night has about its share of the day's games, or null, and no record). A game also has `match_id`, `result` (`W`, `L` or `D`), `opponent` (`name@version`), `opponent_display_name` and `map`; other points have these null or empty. A run also has `low` and `high`, its lowest and highest rating along the way (null on games and nights). Games and runs have `rank`, where the bot stood on the leaderboard just after the game (a run: after its last ranked game), or null when it had no ranked version then; a run also has `rank_best` and `rank_worst`, its best and worst place along the way. Nights, and games played before ranks were kept per game, have these null. `ranks` is where the bot stood on the leaderboard at the end of each day it was ranked (`day`, `rank` and `score`), for the time before its points carry a `rank` |
| `GET /api/matches?bot=<name>&limit=<n>&stats=1`                         | newest first; each match has `mode` (`ranked`), `map`, `seed`, `bots` (with `version`, `fighter`, `house` and, when rated, the version's `rating_before`/`rating_after`), `winner` (bot id or null), `reason`, `final_tick`, `duration_ms` (wall-clock milliseconds; null for older games), `voided`, `replay_url`, `stats_url`, `watch_url`. `version` with `bot` keeps only that version's games (public name or stored label). With `stats=1` each also carries its `stats` (below), for analysing many games in one request                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                       |
| `GET /api/matches?after=<match id>&limit=<n>`                           | the matches after that one, **oldest first**, optionally for one `bot`, up to `limit` (at most 500): follow a ladder or walk its 30-day window by passing the last id you got; `400 unknown_cursor` if an older-style id has aged out, so start again without it                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                      |
| `GET /archive/packs/<scope>/<pack>.pack`                                | a minute's matches on a ladder at once, from a match's `pack_url`: see [Downloading matches in bulk](#downloading-matches-in-bulk)                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                    |
| `GET /api/matches/<id>`                                                 | one match; each of its `bots` has `house` and the `avatar` and `color` it wears                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                       |
| `GET /api/matches/<id>/stats`                                           | what each fighter did in the match (below); 404 for a voided match                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                    |
| `GET /api/status`                                                       | who is online and what they're doing; active matches with their current tick; `capacity` (running / max); `draining` (true while the ladder finishes its matches before a restart: no new ones start); `qualifying_games` (rated games a bot version needs on this ladder to appear on its leaderboard); on public only, `all_ladders` (`online` and `live`: bots online and matches live across every ladder, Leagues included, a bot counted once and League house bots not counted; absent when unavailable)                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                       |
| `GET /api/lobby`                                                        | every online bot, highest `leaderboard_score` first: `version` (the one it plays, or null before it queues), that version's `rating`, `rating_deviation`, `leaderboard_score`, `idle_penalty` and `online_owed_hours` (the same Score as the leaderboard and bot version table; all five are null before it queues), `difficulty` (house bots: `Easy` for kiter, `Medium` for brawler, `Hard` for ts-starter, `Very hard` for champion; null for player bots or unknown house kinds), its `avatar` and `color`, and `state`: `waiting` (queued for a match), `playing` or `idle`. Practice at `/play` does not use the lobby: it runs house policies in the browser                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                   |

Ladder results are computed in bounded batches and cached incrementally; concurrent requests share the same history scan. The JSON fields are unchanged. On `/match/<id>`, the result and replay links appear independently of full stats, which may take longer to load from the archive.

Full stats remain available after a replay leaves the public window. They may load from private
object storage; the response fields and measured timings are unchanged. A temporarily unavailable,
missing or corrupt archived object returns `503` with `Retry-After: 5`, including requests using
`stats=1`. Retry those requests; a `404` still means stats are unavailable for that match.

Bulk stats reads use bounded concurrency and yield between records, so an analysis request cannot
queue its whole history ahead of individual match pages or hold up live match timers on cached data.
The same applies to MCP `list_matches`. For quick history browsing, omit `stats=1` and load selected
matches through their `stats_url`; cold archive batches can take longer than a single match.

Profiles sum each bot's wins, losses and draws across all its versions on the selected ladder,
including retired versions. Owner links on the leaderboard and bot pages keep that ladder selected
when opening `/user/<handle>`.

### The rolling window and past months

Live leaderboard rows optionally include `appearance` with `asset_version`, `asset_sha256`, `avatar`,
`color` and `source`. `completed_update` records the local appearance when that version's latest
nonvoid rated result committed; editing a profile, a void game or a duplicate result does not repaint
the standing. Each League stores it independently. `legacy_frozen` preserves the appearance visible
at upgrade or first metadata recovery, without claiming original match appearance or historical paid
status. Older saved snapshots keep their existing frozen fields and can omit this metadata.

Saved account customization fields are preferences. Render current bot/lobby avatars from that
scope's response, and historical appearances from their match/standing response; do not replace them
with today's account preference. Arena+ coverage applies globally, while Premium sponsorship applies only inside its private League with current
enrollment. Expiry affects future appearances and preserves free colors and recorded
history.

New match fighters carry optional `appearance: {asset_version, asset_sha256, avatar, color}`.
`asset_version` is 2 for appearances recorded from this release on, and 1 for earlier ones. The
asset hash identifies that version's retained procedural artwork/animations and palettes. The
website draws every persona with its newest art (version two redraws the first twenty and adds
`knight`, `glitch`, `kraken`, `inferno`, `golem`, `voyager`, `mantis` and `slime`), whichever version
recorded it. Standing appearances use the same versions. Display
`avatar`/`color` come from that match-start record, independently of current bot settings or the reader's
subscription. `appearance_source` is `recorded`, or `legacy_unrecorded` when no original appearance
exists; the latter uses plain orbs/classic colors. Private history `recorded_bots` and page JSON exports
retain the same appearance metadata when present. Downloaded replay bytes remain inputs only and do
not carry these cosmetics. Existing saved standings keep their recorded appearance fields.

On Cloudflare, saved private League match IDs remain readable after their active rows are pruned:
match details, stats, MCP match reads and individual replay downloads use the League's private archive.
The owner and currently active members retain access after cancellation. Revoked or departed members
lose access immediately. A pending archive lookup returns `503 archive_index_pending`; a damaged or
unavailable lookup returns `503 archive_history_unavailable`. Retry later. Match lists still cover their
current window. Use the separate private archive history endpoint below to discover older match IDs.

An archived private recording that is missing, corrupt, oversized or too slow returns retryable
`503 archive_media_unavailable` for stats/MCP reads; replay downloads return `503` with
`Retry-After: 5`. An unknown match still returns `404`. A voided match with explicitly unrecorded
stats has no stats. These failures do not remove its retained match details. Replay downloads preserve
the original compressed bytes and recording-compatible simulator selection.

### Historical public recordings

`GET /api/archive/public/history` searches public recordings. There is
no browser search page: agents query it with an account key, and the replay viewer and match pages
play the results. Bot detail (`GET /api/bots/<current-name>`) exposes its stable `id`; use that ID
for retired/renamed history. `GET /api` reports `public_history` for service availability; it does
not report a reader's coverage.

The public ladder enforces the replay window below. A ladder you run yourself leaves it off, so
every replay it retains is free there and it has no history search. History is not complete:
matches before collection began on 2026-11-06 are best-effort. Recent match lists and basic public
results don't need this API.

| Route                                                  | Result                                                                                                   |
| ------------------------------------------------------ | -------------------------------------------------------------------------------------------------------- |
| `GET /api/archive/public/history?bot=<stable-bot-id>`  | Bounded metadata page, `next` cursor and explicit false verification flags.                              |
| `GET /api/archive/public/matches/<id>`                 | Historical result with protected `replay_url`, `stats_url` and compatible `watch_url`; no bulk-pack URL. |
| `GET /api/archive/public/matches/<id>/replay.jsonl.gz` | Exact original gzip recording, including packed and individual files.                                    |
| `GET /api/archive/public/matches/<id>/stats`           | Original stored statistics after bounded decompression and digest verification.                          |
| `GET /api/archive/public/matches/<id>/access`          | Current access decision without downloading the gameplay payload; availability is checked separately.    |

Send a browser Supabase session or a player-issued account agent key in `Authorization: Bearer`.
The key identifies its owner; an agent's tool permissions do not buy a subscription. Historical search
needs current account-wide Arena+; recordings follow the window below. Premium League membership
supplies no public archive coverage.
Bot tokens and MCP OAuth tokens cannot authenticate these HTTP reads. Source expiry/revocation,
account bans and key revocation take effect on subsequent requests; transient entitlement failures
deny new delivery with `503`. Responses are `private, no-store`. Browser replay and match pages
also clear protected state on account changes or a confirmed loss of access.

Public point results are free. A recording and
its full gameplay stats are free when the match is in either participating stable bot's newest 200
completed public games, across versions. Voids count; private League games do not. Completion UTC
and stable match ID order the window, rather than start time. Individual/staff account-wide Arena+
extends the window to either bot's newest 1,000. Older recordings return `403 arena_plus_required`
without Arena+, and `403 outside_arena_plus_window` past the 1,000. Historical search lists each
bot's newest 1,000 archived matches.
Coverage or collection failures return retryable `503 public_replay_access_unavailable`. Explicitly
unrecorded void stats stay absent. Available history before the disclosed collection boundary is
best-effort. Paid access never grants unrelated private League access.

Under that policy, a minute pack (`pack_url`) holds only that minute's matches anyone may download
free, and leaves the rest out: download those from their own `replay_url`/`stats_url`. Arena+ doesn't
widen a pack. Public match lists with inline stats return `503 public_bulk_stats_unavailable`,
including for paid readers. Omit `stats=1`, and use packs or follow each match's `stats_url`/`replay_url` instead. MCP `list_matches` has
the same restriction; `get_match` with `stats: true` checks the individual match. These restrictions
prevent a mixed bulk response from bypassing the free window. Do not retry an upgrade response as
a storage failure, and use bounded concurrency/backoff for temporary errors.

When a match advertises `recording_access_url`, use that endpoint to recheck access; public result
visibility alone does not authorize a recording. The hot-match equivalent is
`GET /api/matches/<id>/access`. A successful response is `{"allowed":true}` and does not promise that
the media is available. The viewer checks this URL every five seconds while visible, clears its
loaded recording on a denial (`401`, `403` or anything but `{"allowed":true}`) or after three checks
in a row the server couldn't answer (`5xx` or no connection), and rechecks after account changes.
A `503` means access couldn't be verified right then: retry shortly with backoff.

Search uses required stable `bot`, with optional stored `version`, stable `opponent`, explicitly
public `ladder`, UTC `from`/`before`, `min_rating`/`max_rating` and `limit` (default 50, maximum 100).
Renames do not change bot identity. Order is completion timestamp then stable match ID, descending.
One request scans at most 512 candidates and 24 verified index objects (2 MiB compressed,4 MiB expanded).
Send the same filters with each returned opaque `cursor`; an empty page with non-null `next` still
has more candidates. Changed filters/generation, duplicate parameters or an invalid cursor return 400.
R2 index transport, each account/coverage/render RPC and media validation have finite time budgets.
The existing API rate limits apply. Retry `503` with backoff; do not issue unbounded parallel requests.

Historical records can belong to another player and predate the reader's signup. Only source scopes
proven public enter this generation; paid coverage never authorizes private League bytes. The page
preserves `recorded_bots`, original names/version labels and `metadata_engine` where observed. The
viewer follows the replay header's simulator/rules identity. Missing, corrupt or incompatible media
stays explicit; it is never replaced with today's engine. An explicitly unrecorded void returns 404
`stats_not_recorded`; retained missing/corrupt/oversized/slow media returns 503 `archive_media_unavailable`.

For a training/evaluation client, read each page and follow its individual protected URLs, preserving
match IDs, seed, rules and engine identity alongside downloaded inputs. This API adds no separate
archive fee or hosted-compute allowance. Use `/match/<id>?archive=public` for the protected result
page; dedicated historical URLs remain usable when a legacy League has left live discovery.

### Private League archive history

On Cloudflare, request `GET /api/ladders/<id>/history`, or page MCP's `list_matches` past a
League's recent matches; there is no browser page for it. Deployments without private archive
support answer with retryable unavailability. The owner and currently active members can read this metadata after
cancellation and Premium expiry. Public and legacy public Leagues use their separate archive policy;
this endpoint does not grant public archive access.

Each response contains `{matches, next, scanned}`. Matches use the usual detail fields and add
`recorded_bots`: original stable IDs, names, stored version labels, fighter slots and any recorded
ratings. These facts remain distinct from current bot profile labels. Pages descend by recorded
sequence, which can differ from completion time. Recent unarchived games remain in Current matches
and `/api/matches`; the history endpoint reads archived records only, including voids.

| Parameter | Meaning                                                               |
| --------- | --------------------------------------------------------------------- |
| `bot_id`  | Optional stable bot ID, across renames and versions.                  |
| `version` | Optional stored version label; requires `bot_id`.                     |
| `limit`   | 1–50 matches; defaults to 50.                                         |
| `cursor`  | Opaque `next` value from the preceding page. Resend the same filters. |

One request scans at most one bounded archive block. A sparse filter can return no matches and a
nonnull `next`; keep following it until `next` is null. A cursor freezes the indexed upper boundary,
so new archive blocks do not shift an ongoing scan. Start without a cursor for the newest saved games.
Invalid or mismatched filters/cursors return `400 invalid_history_cursor`. An indexing backlog returns
`503 archive_index_pending`; unavailable/corrupt indexes return `503 archive_history_unavailable`.
Unsupported deployments return `503 history_unavailable`. HTTP 503 responses include `Retry-After`.
Every page rechecks membership and is noncacheable. Cursors grant no access.

The browser can download the displayed page as JSON. For a complete metadata export, follow every
`next` and combine the pages; exports remain private. Replay and stats downloads use each match's
existing guarded links. The history route rejects `stats` and `after` parameters. This metadata
listing does not establish that every historical media file or simulator is available.

The public leaderboard never resets. Ratings, records, qualification and matchmaking history count the rated games of the last 30 UTC days; a game counts toward the day it ended on. Each night the oldest day leaves, so a rating can move a little without its version playing. A version with no games in the window has no record or rank. Private ladders follow the same rules on their own schedules and totals. A closed one keeps the standings and results it ended with.

Bot detail adds `history_days`, `lifetime` (null until the bot has played: `since`, `first_played`, `first_completed`, `games`, `wins`, `losses`, `draws`, `active_days`, `best_rank`, `best_score`, on Public; `best_rank` is checked nightly), and `snapshot_history` (rank, version, score and W/L/D for each past month).

The navbar's standings dropdown sits beside the ladder switcher. Choosing a month opens the standings as they stood when it ended, and **Browse past months** opens `/snapshots`, which links to each month's report. Add `?snapshot=<id>` to `/api/leaderboard`, `/api/affiliations` or `/api/agents` for a past month, or with `?ladder=<id>` for one of that League's snapshots. A match feed lists recent matches only.

Match and stats URLs work while a match is in the window. After that they answer 404: the row, replay and stats stay in a private permanent archive.

The selected-bot opponent chart uses wins divided by all non-void rated games, including draws in the denominator; it combines versions. Specialist combat records use compatible saved stats and display sample sizes. A month's standings and report never change once saved. An old replay may no longer be available or compatible with the current viewer.

### Team standings

`GET /api/affiliations` ranks universities; `GET /api/affiliations?kind=organization` ranks
Organizations on a separate board. `/api/teams` is their earlier name and still answers the same,
deprecated: League teams are a different thing. Leaderboard rows and bots name the school or
organization their owner represents in `affiliation`; `team` carries the same value until it is
removed. `kind=university` is the default; other values return 400 `invalid_request`.
The website shows them at `/universities` and `/organizations` (always the public ladder; old
`/teams` URLs redirect). `.edu` teams never enter Organizations.
Both rank the bots of the accounts that represent them (see
[Your team](#your-team-university-and-organization-standings)). Each team scores the average
`leaderboard_score` of its best 5 accounts, taking each account's best ranked bot. Empty places
score 700, a new version's score, so one strong player can't top a team with five. Ties go to
the better top bot, then more ranked members. House bots and hidden teams never count.

Each row includes `members`: all currently verified players on that team, across ladders,
including players without ranked bots. The table displays this as **Players**, separately from
`ranked_members` (players with ranked bots on this board) and `counted` (the best five used for
scoring). `members` is a current count even when viewing a past month.

```json
{
  "kind": "university",
  "slots": 5,
  "floor": 700,
  "teams": [
    {
      "rank": 1,
      "id": "stanford.edu",
      "name": "Stanford University",
      "score": 1214,
      "members": 10,
      "counted": 5,
      "ranked_members": 7,
      "top": {
        "name": "…",
        "display_name": "…",
        "owner": "…",
        "owner_url": "…",
        "avatar": "ronin",
        "color": "violet",
        "leaderboard_score": 1630
      },
      "wins": 212,
      "losses": 140,
      "draws": 9
    }
  ]
}
```

Team `name` is a display label; use `id` for stable links and comparisons. Organization names
come from a staff override, a cached name from the organization's public website, or the domain.
Discovery runs in the background, so a newly joined team can show its domain at first. Staff edits
always win. Website labels do not verify ownership or change affiliation.

`GET /api/affiliations/<domain>` returns `{team, slots, floor, members, standing, bots}`: the team (`id`, `name`, `kind`),
how many accounts represent it now, its standing (or null), and its members' ranked bots as
leaderboard rows, each with `counted`. Any root `.edu` or eligible organization domain answers,
so a link works before anyone has ranked; invalid, shared-provider and non-root domains are
404 `unknown_team`. Detail rank is always within the team's own category. Both accept `?ladder=<id>` and
`?snapshot=<id>`, one of that ladder's snapshots. Each leaderboard row's `team` names its owner's affiliation domain, or null.

Standings are rebuilt at most every 15 seconds (sooner when someone joins or leaves) and are
served with `cache-control: public, max-age=15`. A past month's rows keep the affiliation each
owner represented when it ended.

### Agent standings

`GET /api/agents` compares the AI agents that built bots, from the agent each bot's owner names
(see [registration](#post-apibots)). It ranks agents like schools: each scores the average
`leaderboard_score` of its best 5 accounts, one ranked bot each, with empty places at 700, so one
prolific player can't carry an agent and neither can numbers alone. Ties go to the better top
bot, then more ranked players. House bots never count. Beside the score:

- `median`: the middle score of its ranked bots, how good a typical one is.
- `bots`, `players`, `games`, `share`: bots naming it that played a rated game on this board,
  their owners, those bots' rated games, and its fraction of the bots that name an agent
  (`declared`; `undeclared` counts the ones that don't). An agent whose bots play but none is
  ranked yet has `rank`, `score` and `top` null and comes after the ranked ones.
- `versus`: its bots' score against other agents' bots (a draw counts half), from every rated
  game between them on this board, all versions included. `matchups` has each pair both ways
  round as `{a, b, games, score_rate}`; under `min_matchup_games` (10) is too few to read.

```json
{
  "slots": 5,
  "floor": 700,
  "min_custom_accounts": 3,
  "min_matchup_games": 10,
  "declared": 182,
  "undeclared": 41,
  "agents": [
    {
      "rank": 1,
      "id": "claude-code",
      "name": "Claude Code",
      "maker": "Anthropic",
      "custom": false,
      "score": 1388,
      "counted": 5,
      "ranked_bots": 61,
      "ranked_players": 44,
      "top": {
        "name": "…",
        "display_name": "…",
        "version": "v9",
        "owner": "…",
        "owner_url": "…",
        "rank": 2,
        "leaderboard_score": 1702
      },
      "median": 1104,
      "wins": 5120,
      "losses": 4377,
      "draws": 210,
      "bots": 70,
      "players": 51,
      "games": 9707,
      "share": 0.385,
      "versus": { "games": 6012, "score_rate": 0.541 }
    }
  ],
  "matchups": [{ "a": "claude-code", "b": "codex", "games": 1240, "score_rate": 0.553 }],
  "catalog": [
    {
      "id": "claude-code",
      "name": "Claude Code",
      "maker": "Anthropic",
      "assistant": false,
      "description": "Anthropic's coding agent: in a terminal, an IDE, claude.ai/code or the Claude desktop app's Code tab."
    }
  ]
}
```

`catalog` lists every id registration accepts; `assistant` marks chat assistants and personal
agents that also write code (ChatGPT, dots, Instinct…), as opposed to coding agents. Where one maker
has several entries, `description` says where each runs (Claude Code or the Claude app, Codex or
ChatGPT), so an agent can pick its own; it's null elsewhere. A custom name stands on its own once
`min_custom_accounts` accounts name it (`id` is its slug, its name as its earliest bot spells it);
until then it counts with the other rare names under `other`, "Other agents".
`GET /api/agents/<id>` returns `{agent, slots, floor, min_matchup_games, standing, bots,
matchups}`: the agent, its standing (or null), its ranked bots as leaderboard rows with
`counted` (and `agent_name`, the name its owner typed, for `other`), and its record against each
other agent. Every catalog id and `other` answers, so a link works before anyone ranks with it;
anything else is 404 `unknown_agent`. Both accept `?ladder=<id>` and `?snapshot=<id>`, one of that ladder's snapshots.
Each leaderboard row's `agent` is the stored id or custom name, or null; each bot record's
`agent` is `{id, name, maker, custom}` or null.

Owners say which agent built a bot and nobody checks it, so read the standings as a friendly
rivalry, not a benchmark. They are rebuilt at most every 15 seconds (at once when a bot's agent
changes) and served with `cache-control: public, max-age=15`.

### Position heatmaps

The bot page header has a compact **Position heatmap**; click it for the large view, with a map selector.
Hover or tap a cell for its tick count and percentage of sampled ticks. The grid shows the
map’s walls. Colors scale to the selected grid’s busiest cell; compare percentages when
versions have different play time.

`GET /api/bots/<name>/heatmaps?version=<label>&ladder=public` returns
`version`, `eligible_games`, `recorded_games` and `buckets`, over the version's whole life on that
ladder: heatmaps don't age out of the window. Each bucket contains `map`, `mode`, `width`,
`height`, `games`, `ticks` and row-major `counts` (`y * width + x`). Maps and match modes stay
separate. Unknown bots, versions and ladders return 404. A missing version
is treated as unknown. Voided matches are excluded.

Each living fighter contributes one sample at the start of each resolved tick, including
idle and stunned ticks. Dashes do not count intermediate tiles. Unvisited cells have zero
counts; unavailable historical matches contribute to `eligible_games` but not `recorded_games`.
Older match statistics may omit `fighters[].occupancy`; new statistics include its `width`,
`height` and `counts`. Existing statistics retain version 2 because the existing fields keep
their meanings.

### Match stats

Use the simulator's `verifyReplay` to check a downloaded replay's tick hashes and combat result.
For a forfeit or disqualification, it checks that combat was still running, the ending is at the
next unresolved tick, and the winner is a living fighter (or a draw for a forfeit). The server's
reason for the external ending remains trusted; combat inputs do not record socket decisions.

On the public ladder, a replay downloads while its match is in either bot's newest 200 public games, or newest 1,000 with Arena+ (see [historical public recordings](#historical-public-recordings)); on a ladder you run yourself, while its match is in the 30-day feed. Temporary outages return `503` with `Retry-After: 5`.

### Downloading matches in bulk

For public matches, use bulk downloads when you need more than a few. Finished matches are stored in one pack a minute, and a public match's `pack_url` downloads its minute's public replays and stats in one request.

> [!NOTE]
> The public ladder enforces the [replay window](#historical-public-recordings): a pack holds only
> the matches in it that anyone may download free, those in either bot's newest 200 public games.
> A match missing from its pack is outside that window: download it from its own `replay_url` with
> Arena+, if you have it. Every match is in the window when it ends, so collecting packs as they
> appear gets every match.

```text
{"matches":[{"id":"g1275313_1c4b9738","replay":[0,2816],"stats":[2816,861]},...]}
<the files>
```

The first line is JSON. After its newline come the files, each gzipped, and each `[offset, length]` counts from there. A voided match has no `stats`.

```python
import gzip, json, urllib.request

def get(url):
    request = urllib.request.Request(url, headers={"User-Agent": "my-bot-trainer"})
    return urllib.request.urlopen(request).read()

base, after, done = "https://victrisarena.com", None, set()
while True:  # walk the window, oldest first; run it again later to follow along
    query = "limit=500" + (f"&after={after}" if after else "")
    matches = json.loads(get(f"{base}/api/matches?{query}"))
    if not matches:
        break
    after = matches[-1]["id"]
    for url in {m["pack_url"] for m in matches if "pack_url" in m} - done:
        done.add(url)
        head, _, files = get(url).partition(b"\n")
        for m in json.loads(head)["matches"]:
            start, length = m["replay"]
            replay = gzip.decompress(files[start:start + length])
```

Keep to these limits:

- A pack appears a minute or two after its matches end. Until then it's `404` with `{"code": "pack_not_ready"}` and `Retry-After`, and the match's `replay_url` and `stats_url` still work.
- `pack_url` is absent for league matches and matches from before November 1, 2026 at 22:00 UTC. Use their individual `replay_url` and `stats_url` where access is available.
- Packs outside the 30-day window are `404`, the same as the feed.
- The stats in a pack are as first recorded. A match whose stats were corrected later keeps the corrected ones at `stats_url`.
- A hosted ladder only serves packs where it has them, so a ladder without `pack_url` has no bulk downloads: use the match's own URLs. `arena_sim.download_replays` copes with all of this.
- About 120 pack downloads a minute from one address answer `429` with `Retry-After`; a minute's pack is one request, so that's plenty to follow along or catch up.

> [!NOTE]
> Bulk downloads support only `/archive/packs/public/<pack id>.pack`. League scopes return
> `404` with `{"code":"pack_unavailable"}` and `Cache-Control: no-store`, regardless of credentials.
> Public responses contain only public-match bytes. There are no League bulk downloads: use each
> League match's own URLs.

Every finished match has stats: the same object arrives in your bot's `end` message as `stats`, and the ladder keeps it (even after the replay file is trimmed). The schema is [`docs/schema/match-stats.json`](/docs/schema/match-stats.json) (`/docs/schema/match-stats.json`).

Match records also keep `duration_ms`, measured with a monotonic server clock from match setup until the result is ready to persist, including startup, bot waits, simulation and replay saving. Queueing, database persistence and sending the end message are excluded. This field is in `GET /api/matches/<id>` and match lists, including human and voided games, and appears on `/match/<id>` under Stats. It is null for older games. It is separate from replay-derived combat stats and is not added to the bot protocol or local replays.

```bash
curl -s https://victrisarena.com/api/matches/<match-id>/stats -o stats.json
curl -s "https://victrisarena.com/api/matches?bot=<your-bot>&limit=200&stats=1" -o my-games.json
bun run arena -- stats <match-id>          # as a table (--json for the raw object)
bun run arena -- stats replays/x.jsonl.gz  # the same, computed from a local replay
```

```json
{"match_id": "m_…", "stats_version": 2, "map": "pillars-21", "seed": 3, "ticks": 521, "winner": 2, "reason": "last_standing",
 "fighters": [{"id": 1, "name": "kiter", "version": "v3", "hp": 0, "alive": false,
   "moves": 16, "moves_blocked": 0, "dashes": 4, "dash_tiles": 12,
   "weapons": {"ranged": {"uses": 5, "hits": 2, "damage": 30}, "frostburst": {"uses": 2, "hits": 0, "damage": 0}, "repulsor": {"uses": 0, "hits": 0, "damage": 0}},
   "ricochets": {"bounces": 4, "hits": 1, "damage": 18},
   "pickups": {"health": 0, "power": 3}, "healed": 0,
   "damage_dealt": 30, "dealt_by_source": {"ranged": 30}, "damage_taken": 100, "taken_by_source": {"zone": 100},
   "wall_slams": 0, "knocked_back": 0, "stunned": 0, "zone_ticks": 20,
   "rejected": {"not_visible": 1}, "refused_turns": 1, "refused_turns_by_reason": {"not_visible": 1}, "server_idles": {"timeout": 2},
   "timing": {"replies": 520, "mean_ms": 41, "p50_ms": 18, "p95_ms": 160, "max_ms": 1003, "near_limit": 3,
     "tick_ms": 1000, "budget_ms": 300000, "budget_ms_left": 278680, "histogram": [210, 95, 80, 60, 45, 12, 5, 4, 2, 1, 1, 1, 1, 0, 1, 2]},
   "disconnects": 0, "disqualified": false}, …]}
```

- `fighters[].id` is the fighter id: `hello.bot_id` identifies you, and `hello.opponent.bot_id` identifies your opponent. Match records map it to bots in `bots[].fighter`. Stats `winner` is a fighter id; a match record's `winner` is a bot id (both use null for a draw).
- `weapons` lists every attack in the rules. `uses` counts attacks the engine accepted and fired; `hits` counts hits on an opponent, so accuracy is `hits / uses`. Damage includes the power buff.
- `ricochets.bounces` counts your shots that bounced off a wall; `hits` and `damage` are the hits they scored after bouncing (also counted under `weapons`). Hit events carry `"ricochet": true` for these.
- `moves` are steps taken; `moves_blocked` are steps the engine accepted but another fighter stopped. Dashes are counted separately, with the tiles they covered.
- Damage sources are attack names plus `wall_slam`, `collision` and `zone`.
- `rejected` counts refused turn parts by reason (as in `rejected` events); `refused_turns` counts turns with at least one refused part (and `refused_turns_by_reason` the same per reason, a turn counting once for each); `server_idles` counts ticks the server played as idle for you (`timeout`, `malformed_json`, `disconnected`…). Both hold reason codes only: the text of an error (what your bot sent, or what was wrong with it) goes to your bot alone, in the next observation, and is never recorded.
- `timing` is how long you took to reply, as the server timed it: from sending the observation to your reply arriving, network included. A reply that never came counts at the deadline. `near_limit` counts replies that took at least 80% of the tick limit: one slow moment from a timeout, so watch it before timeouts show up in `server_idles`. `budget_ms_left` is what was left of the match's response-time budget. `histogram` counts replies per bucket (upper bounds 10, 25, 50, 100, 200, 300, 400, 500, 600, 700, 800, 850, 900, 950 and 1000 thousandths of `tick_ms`, then slower) so matches add up. `timing` is null where nothing was timed, as in the simulator.
- `disconnects` counts contiguous runs of recorded `disconnected` idle turns for this fighter, not socket-close events. Ten consecutive such turns count as ten `server_idles.disconnected` and one `disconnects`. A brief drop with no recorded disconnected turn is not counted, and multiple drops without an intervening other turn form one run. `disqualified` says the match ended because this fighter failed too many ticks in a row.
- Stats are recomputed from the replay by the engine, so `arena stats` on a downloaded replay gives the same numbers.

`server_idles.timeout` means no usable reply arrived before that fighter's turn deadline;
`server_idles.disconnected` means its connection was treated as unavailable. These identify
the affected fighter, not which process, network path or server component caused the problem.
The wire/replay code is `disconnected`, not `disconnect`. An absent key means zero recorded
idles for that reason. Counts cover replayed ticks; the unresolved tick at a server-decided
forfeit or disqualification is not recorded as another idle turn.

The live protocol sends timeout rejections only to the affected bot and sends no disconnect
event to either bot. Final stats expose both fighters' counters. Use `end` or the saved match
record for completion, rather than inferring a result from idle counters or a socket close.
Turn `timeout` is separate from match reasons `timeout_hp`, `timeout_damage` and `timeout_draw`
(the combat tick limit). See [disconnects, timeouts and match completion](/docs/bot-guide#disconnects-timeouts-and-match-completion)
for grace-period behavior, resumption and missed-result handling.

### Version health

`GET /api/bots/<name>` gives each version a `health` summary of up to its latest 500 matches among the bot's 2,000 up to the version's last, counting only matches with current (`stats_version` 2) stats, or null when none are available. `matches` and `turns` report that measured subset; older stats remain stored but do not contribute missing measurements as zero. Check it after deploying a version: it shows what your bot's own logs may not.

```json
"health": {"matches": 500, "turns": 214300,
  "idle_pct": 1.6, "idle_pct_by_reason": {"timeout": 1.4, "schema": 0.2},
  "refused_pct": 3.4, "refused_pct_by_reason": {"not_ready": 3.1, "blocked": 0.4},
  "reply_ms": {"replies": 213000, "mean": 410, "p50": 400, "p95": 900, "max": 1004},
  "near_limit_pct": 6.2, "lowest_budget_ms_left": 120000, "disconnects": 2, "disqualifications": 1}
```

- Percentages are of turns (one a tick), to two decimals. `idle_pct`: turns the server played as idle for the version because its reply was late, malformed or missing, and `idle_pct_by_reason` the same by reason. `refused_pct`: turns with at least one part the engine refused, and `refused_pct_by_reason` the same by reason (a turn refused for two reasons counts under each). Reason codes only, never error text.
- `reply_ms`: reply times over those matches. `p50` and `p95` come from the summed histograms, so each is the upper bound of its bucket (never above `max`); `mean` and `max` are exact. Null when no match timed a reply.
- `near_limit_pct`: replies that took at least 80% of the tick limit, as a % of replies. Anything above 0 means the version runs close to timing out.
- `lowest_budget_ms_left`: the least response-time budget any of the matches ended with.
- `disconnects`: sum of the match stats' runs of recorded `disconnected` idle turns; `disqualifications`: matches lost by failing too many ticks in a row.

The bot's page shows the same, per version, in its Health panel. Its Match interruptions column labels disconnects and disqualifications explicitly. Idle turns are percentages of turns, while disconnects count recorded interruptions and disqualifications count matches lost. Reply-time and Near limit statistics describe replies and can look healthy even when a bot disconnects. A disconnect that outlasts the reconnect grace period causes a forfeit; it does not count as a disqualification. Match and replay stats summarize these endings above the combat table. Information buttons beside the relevant metrics explain the details, including why a forfeiting fighter can still have HP. Tooltips open on hover, keyboard focus or tap and dismiss with Escape or a tap outside.

## Effective match limits

`GET https://victrisarena.com/api` publishes `operational_policy` with the current bot match limits,
ladder limits and message caps. These live values can differ from the downloadable simulator's
bundled defaults. Match `hello` and replay rules contain the effective limits captured for that
match; a reconnect retains the same snapshot. Match deadlines and per-tick flood limits change
only for new matches, and WebSocket message-size changes affect new connections. Existing
invitations and human tickets retain their original expiry. Read the live quotas below when
planning online play; use the simulator's supplied rules for offline testing.

## Limits

Admins change these live (see [Effective match limits](#effective-match-limits)). The
ladder fills this table with its current values when it serves this guide; the repository copy
shows the bundled defaults. Read them as JSON from `quotas` in `GET /api`, keyed by name, each
with its `label`, `value`, `unit` (`"ms"`, or `""` for a count) and `note`:

```json
"quotas": {
  "bots_per_owner": { "label": "Bots per owner", "value": 5, "unit": "", "note": "Retired bots don't count. …" },
  "matches_per_bot_per_hour": { "label": "Matches per bot per hour", "value": 10000, "unit": "", "note": "Rolling hour; house bots are exempt." }
}
```

<!-- quotas -->

| limit | value | notes |
| ----- | ----- | ----- |
| Bots per owner | 5 | Retired bots don't count; owners can unretire one after freeing a slot. An account's own allowance (max_bots in GET /api/account) takes precedence. |
| New versions per bot per day | 100 | Rolling 24 hours; house bots are exempt. |
| Matches per bot per hour | 1,000 | Rolling hour; house bots are exempt. |
| Matches per owner per day | 20,000 | Rolling 24 hours, across all of an owner's bots. |
| Match interval | 300 ms | Minimum time between one bot's match starts. |
| Concurrent matches per owner | 5 | Across all of an owner's bots and ladders; a ladder can set a lower cap (GET /api/ladders). |
| Concurrent matches, public ladder | 15 | Each League has its own cap (effective.max_concurrent in GET /api/ladders). |
| Agent keys per account | 10 | Revoking a key frees its place. |
| API requests per minute | 6,000 | Per client address, in one-minute windows; 0 means no limit. |

<!-- /quotas -->

Each ladder can cap concurrency lower: `effective` in each `GET /api/ladders` entry gives the
caps that admit its matches, the smaller of the ladder's and the server's.

A bot held back by a match quota (matches per bot per hour, per owner per day, or the owner's concurrent matches) stays queued, and gets a `quota_exceeded` error (at most once every 5 minutes per reason) that says which quota and when it frees:

```json
{
  "type": "error",
  "code": "quota_exceeded",
  "message": "hourly match quota reached (10 per hour)",
  "quota": "matches_per_bot_per_hour",
  "limit": 10,
  "used": 10,
  "retry_after_s": 742
}
```

| field           | meaning                                                                                                                                                               |
| --------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `quota`         | `matches_per_bot_per_hour`, `matches_per_owner_per_day` or `concurrent_matches_per_owner`: the quota's name in `GET /api` `quotas`                                    |
| `limit`         | the quota's current value                                                                                                                                             |
| `used`          | matches the bot (or, for the daily quota, all of its owner's bots) started in the rolling window, or the owner's running matches                                      |
| `retry_after_s` | seconds until the rolling window frees a place (0 if it already has); `null` for concurrent matches, where a place frees when one of the owner's running matches ends |

Stay connected and queued: the bot plays as soon as a place frees, without reconnecting or queueing again. Each throttle is written to the audit log. The match interval and server or ladder capacity hold a bot back without a message. The other limits refuse the request: registration answers `bot_limit`, a new agent key `key_limit`, queueing a new version `version_limit` (registering one over HTTP answers 400), and an API request past its budget HTTP 429 with `Retry-After`.

### HTTP API rate limit

Every `/api` request counts against its client address (Cloudflare's `CF-Connecting-IP` on the
hosted ladder), in fixed one-minute windows. Pages, docs, downloads, replays and the bot WebSocket
don't count. Separately, about 20,000 `/api` requests a minute from one address is treated as a
runaway, whatever the budget says, and answers `429`. Replay downloads have their own limit: about
120 `/replays/` downloads a minute from one address answer `429` with `Retry-After: 60`. To fetch many
replays, use [minute packs](#downloading-matches-in-bulk), one request for a minute's matches. Each `/api` response says where the client stands, in the fields of
[draft-ietf-httpapi-ratelimit-headers](https://datatracker.ietf.org/doc/draft-ietf-httpapi-ratelimit-headers/):

```http
RateLimit-Policy: "api";q=6000;w=60
RateLimit: "api";r=5874;t=41
```

`q` requests are allowed every `w` seconds; `r` remain for the next `t` seconds. Past the
budget, the ladder answers `429` with `{"code": "rate_limited"}` and `Retry-After: <seconds>`.
Wait that long, then continue. Admins change the budget live with the `apiRequestsPerMinute`
setting; `0` turns it and the headers off. `GET /api` reports it
as `operational_policy.api_requests_per_minute`.

### Shared reads

On the hosted ladder, the public ladder's most polled reads are shared through Cloudflare's cache,
so an answer can be up to this old:

| Read                                                  | Up to |
| ----------------------------------------------------- | ----- |
| `GET /api/lobby`                                      | 10 s  |
| `GET /api/status`, `GET /api/matches` without `stats` | 15 s  |
| `GET /api/leaderboard`                                | 60 s  |
| `GET /api/bots/<name>` without credentials            | 60 s  |

A shared copy has `X-Arena-Cache: hit` and `Cache-Control: public, max-age=<seconds>`. It doesn't
count against your budget and has no `RateLimit` field. Polling faster than these times only
returns the same answer again. League reads (`ladder=<league>`) and anything signed-in readers see
differently are never shared.

### The public ladder's live copy

The hosted ladder also publishes a copy for crowds to read straight from its CDN, with no request
budget at all. Public `GET /api/status` says where it is:

```json
"live": {
  "feed": "https://assets.example/live/v1/public/dashboard.json.gz",
  "replays": "https://assets.example/live/v1/"
}
```

- **`feed`** is one JSON object (served gzip-encoded) with `generated_at` and what the dashboard
  shows: `leaderboard`, `matches` (the newest 50), `status` and `lobby`, in the same shapes as their
  endpoints. It's rewritten at most every 15 s while public plays, and at least every minute. Poll it
  no faster than every 15 s, and use the API instead if `generated_at` is more than 5 minutes old.
  Add `?t=<unix seconds ÷ 15, rounded down>` as the pages do: the CDN keeps a "not found" for hours,
  and a new `t` each slot gets past one.
- **`replays`**: for a public match in the first 55 minutes after it ends, its replay is at
  `<replays>replays/<YYYY-MM-DDTHH>/<id>.jsonl.gz`, where the folder is the UTC hour of `ended`. That's the
  same gzipped file as `/replays/<id>.jsonl.gz`. Copies are deleted after an hour or two, so fall back
  to `replay_url` on a 404.

Neither is the only copy: everything stays in the API. Other ladders and Leagues have no live copy,
so their `status` has no `live`.

## Versioning and deprecation

The HTTP API is version `1`. Every `/api` response carries `Arena-Api-Version: 1`, and
`GET /api` reports it as `api_version`. Send the same header to pin the version: a request for
a version this ladder doesn't serve gets `400` with `{"code": "unsupported_api_version",
"supported": ["1"]}`, rather than an answer in a shape you didn't expect. Without the header,
you get the current version.

- **Compatible changes ship in the current version.** New endpoints, new optional request
  fields, new response fields and new `code` values can appear in any release. Ignore fields you
  don't know.
- **Breaking changes get a new version.** Removing or renaming a field, changing its type or
  meaning, or tightening validation of an existing request happens only in a new version, served
  beside the old one.
- **Deprecation is announced before removal.** A deprecated operation or version answers with
  `Deprecation` ([RFC 9745](https://www.rfc-editor.org/rfc/rfc9745)) and, once a removal date is
  set, `Sunset` ([RFC 8594](https://www.rfc-editor.org/rfc/rfc8594)) headers, is marked
  `deprecated` in `/openapi.json`, and is listed in the [changelog](/changelog). It keeps working
  for at least 90 days after the announcement.

The bot WebSocket protocol is versioned separately (`protocol` in `GET /api` → `versions`).

Replays are the engine's JSON Lines format, gzipped, with rules and map embedded. New recordings
include `release` and `replay_format: 1`. The viewer, CLI replay analysis and retained-stat
reconstruction use the matching runtime; unversioned files require a compatible installed engine
or an explicitly vetted legacy runtime, initially engine 0.21.0. Source/adapter identity and pinned
artifact checksums protect that legacy mapping; the recording remains unchanged.
`bun run arena -- replay <file>` verifies it, and `--view-as <id>` prints observations.
`--from/--swap` requires the matching release of the CLI to continue the match. See
[replay loading](/docs/simulator#replays) for archive access and runtime API details.

Versioned download paths include `/download/<release>/manifest.json` and
`/download/<release>/replay-fixture.jsonl`. The manifest identifies the release, engine, replay
format/API and each runtime artifact's SHA-256 and byte length. It contains no executable URLs.
An older release's paths redirect to the configured public simulator archive; local ladders
without an archive only serve their own release.

Supported legacy runtime paths use
`/download/legacy-engines/0.21.0/v1/{manifest.json,arena-sim.mjs,replay-fixture.jsonl}`.
Unknown legacy engines/adapter versions are not redirected to executable code.

## Queueing over the WebSocket

> [!NOTE]
> M-Bot plays on every ladder; it is not an event achievement opponent. Champion and M-Bot code and weights are not downloadable. Use the starter bots and Random for offline practice.

After connecting, and again after each `end`, a bot asks for its next match:

```json
{ "type": "queue", "version": "v2" }
```

The server replies `{"type": "queued", "version": "v2", "estimated_wait_s": 0}`. `{"type": "leave"}` takes the bot out of the queue.

- **Versions:** the server assigns `v1`, `v2`, … per player bot in registration order, including retired versions. Use `POST /api/me/versions` with optional `alias` and `notes` and queue its returned `label`, or queue the next number directly. Existing custom names become aliases; legacy HTTP `label` and queue strings still identify those versions, while responses use the assigned number (numbered names take precedence over legacy aliases). House policies retain their release labels. A new version is registered on the spot when first queued. It is rated from its own games only, but the matchmaker starts it from the bot's current rating. A retired version can't queue.
- **Every game is rated,** for the two versions that played it. Ratings are a Bradley-Terry fit to every rated game in the current competition scope, refitted after each one: a version's games all count equally, whenever they were played. Each version keeps its own rating and record, so a changed bot's results show on their own and a regression shows as a lower rating. The house bots average 1500 (except `house-champion` and optional `house-mbot`, which are there to be beaten and float above the scale). A version is ranked after 30 rated games; the leaderboard lists each bot once, at its ranked version that played last, by `leaderboard_score`.
- **Leaderboard score:** `round(rating − 2×max(rating_deviation, 25))`, using the model's full-precision values before rounding. The 25-point deviation floor applies only to this score: `rating_deviation` still reports the actual standard error, and rating fits and matchmaking keep using it. Once deviation reaches 25, further uncertainty reduction alone cannot improve the score; stronger results can still improve the rating. Uncertain versions keep the larger penalty, and each new label must still qualify from its own games. The number of games needed to reach the floor depends on the results and opponents.
- **Online time:** a version is online while it is queued or in a match on that ladder (pauses of up to a minute, between games or while reconnecting, still count), and the score asks for 4 hours online in every 24. A bank of online time drains by 4 hours a day and fills by an hour for each hour online, holding at most 4 hours, so a day away is free. Past that the version owes online time, up to 24 hours, reported as `online_owed_hours`, and its score loses `400 × (hours owed / 8)²` points, at most 400 (6 at 30 hours away, 100 at two days, 400 from three days), reported as `idle_penalty`. Only time online pays it back, at 50 minutes an hour; games don't. The rating, `rating_deviation` and matchmaking are unchanged. A closed competition measures time away to its close (an event ladder's `closes_at`), so its final standings stay put.

**Default pairing:** every couple of seconds the matchmaker considers the whole available queue. It combines competitive quality, waiting time, fewer recent games, settling new versions against established ones, and information from under-tested matchups. Maximum-weight matching chooses the combination of pairs, rather than taking the best individual pair first.

Forecasts start from the same Bradley–Terry matchmaking ratings used for placement. Each version pair's results are smoothed toward that estimate with 20 prior games; its results on each map are then smoothed toward the pair estimate with another 20 prior games. Quality is averaged over a uniform mix of the configured maps, so opposite map-specific blowouts aren't mistaken for an even match. A small recent-opponent penalty discourages repeats without outweighing competitiveness. Human and voided results don't enter matchup forecasts.

**Discovery:** approximately one in seven ranked starts is reserved for under-tested version pairs across all rating gaps, independently of predicted competitiveness. Coverage is averaged over the configured maps. Early results that contradict the rating prediction get extra testing until the pair has 20 games. When no competitive match can be allocated, compatible bots can also play discovery matches rather than wait for a rating window; those fallback starts are additional to the normal discovery share. Owner exclusions, quotas, capacity and rematch holds apply to all matches. This allows testing for non-transitive strategies such as `A > B, B > C, C > A` while retaining Bradley–Terry leaderboard ratings.

The competitive rating window starts at 400 points and widens by 20 per second of the shorter wait. At 60 seconds, the oldest eligible bots get priority against their best available opponents, and their own waits widen the window; the gap is capped at 1200 points. An established competitive matchup (at least 20 version-pair games, predicted score 25–75% and average map quality at least 0.5) can pass the initial window, within that cap. Discovery bypasses both competitive rating filters. Waiting cannot override same-owner, house-versus-house, quota, capacity or rematch restrictions. Two bots that just played must both wait 10 seconds before meeting again. There is no opponent-refusal mechanism: skipping `ready` forfeits a rated game.

For each version pair, the next ranked map is chosen from its least-played configured maps, independently of the expected winner; the match seed breaks ties. Fighter IDs are assigned to reduce each bot's accumulated ranked-seat imbalance, with seeded ties. The engine still randomizes spawn sides. These choices leave combat, protocol and Bradley–Terry ratings unchanged. The [operator guide](https://victrisarena.com/docs/matchmaking) describes decision traces and shadow comparisons.

**Optional information pairing:** a ladder can instead prioritize per-version opponent/map coverage
and expected learning about ratings and counterstrategies. The initial coverage target is 25% of
ordinary starts while compatible untested opponent/maps are available; incidental coverage counts.
All compatible rating gaps are eligible. Coverage entitlement accrues only from actual starts,
is bounded, and resets with a changed version or server restart. Same-owner/house-house exclusions,
capacity, quotas, the two-sided rematch hold, balanced maps/seats and the rating fit still apply.
A shadow trial continues to start the default weighted pairings. Bot messages do not change;
there is still no opponent-refusal mechanism. See [matchmaking](/docs/matchmaking).

**Pacing:** a bot starts at most one match every 0.3 seconds. A bot waiting out its interval stays queued, and the `queued` reply's `estimated_wait_s` includes the remaining time.

On the ladder, `end` also carries `watch_url`, and `rating_change` is your version's change from the refit after the game (null when the game wasn't rated). Other versions' ratings move a little with each refit too.

Ratings recorded on matches and `rating_change` are rounded to whole points; a displayed +0 can hide a fractional change. The fit keeps full precision, so these small changes accumulate. With thousands of games, one new result usually has little influence. Match deltas and historical charts describe the raw rating. Current standings on the leaderboard, Online list and bot version table display Score, which subtracts twice the greater of the standard error and 25. Online shows the connected version; the leaderboard and bot headline show the latest qualifying version, so compare the version labels and selected ladder.

Queue and turn errors arrive as `{"type": "error", "code": …}` (socket stays open unless noted):

- `version_retired`
- `version_limit` (more than 1000 new versions in a day)
- `quota_exceeded` (not fatal: you stay queued; `quota`, `limit`, `used` and `retry_after_s` say which quota and when it frees, see [Limits](#limits))
- `already_queued` (you're in a match: continue it, then queue after `end`)
- `not_in_match` (a turn with no match running — including a late reply after `end` cleared the
  seat). Not fatal: keep the connection and send `queue` after `end` as usual. While a match is
  still attached, late replies that echo an older `tick` are discarded silently instead. Error
  frames carry no `match_id` or `tick`; after `end`, attribute `not_in_match` to that finished
  match rather than to the next `hello`.

Connection errors (the socket closes afterwards):

- `missing_authorization`: no `Authorization: Bearer` header on the upgrade request
- `invalid_token`: no bot has this token
- `replaced`: a newer connection took over this token; stop this client
- `suspended`, `banned`: the Victris team has suspended or banned this bot
- `retired`: its owner retired this bot; unretire it on the account page to play again, or register a new one
- `account_banned`: an admin has banned the account this bot belongs to
- `rate_limited`: more than 5 messages in one tick, or more than 50 a second outside a match

## Competition ladders

### Browser billing management

Use the signed-in organizer's **Billing** controls under **My leagues**, and **Arena+** in the
account menu for the personal plan. The account menu shows Arena+ only when it is on sale or the
account has an Arena+ purchase or coverage to explain. Arena+ (monthly or yearly) and every League
plan are on sale on the public ladder; a ladder without billing sells nothing. Arena+ includes each
bot's newest 1,000 public matches and custom avatars. Archive locks (`403 arena_plus_required`) on match pages and the replay
viewer link to **Get Arena+** only while the signed-in account can buy it. These
Cloudflare routes require an unbanned account's browser Supabase Bearer session, return
`private, no-store`, and reject bot/agent/MCP credentials. Mutations require the exact trusted
Origin; cross-site fetches are refused. No request accepts a customer, Price, account or return URL.

| Route                                             | Body                                    | Result                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                   |
| ------------------------------------------------- | --------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `GET /api/account/billing/arena-plus`             | —                                       | Individual plan, pending purchase, payment dates and independent global individual/staff sources, without financial identifiers. Premium membership is not global coverage. A ladder without billing answers `available:false` with no sources; the other routes return `503 billing_unavailable`.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                       |
| `POST /api/account/billing/arena-plus/checkout`   | `{"offer":"arena-plus-monthly"}`        | Account-scoped attempt: `arena-plus-monthly` ($5 USD a month) or `arena-plus-yearly` ($50 a year, two months free), from `offers`; `200` when ready/review/`other_plan` or `202` while preparing/confirming. No League, customer, price or return route accepted. `{"code":"<promo code>"}` redeems an Arena+ promo code, as for Leagues below.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                          |
| `GET /api/account/billing/league-offers`          | —                                       | The League plans on sale now, before you own a League: `{available, offers}`, each offer as in the row below, monthly and yearly. Empty while sales are closed. The buy form reads it.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                   |
| `GET /api/account/billing/leagues/<id>`           | —                                       | Owner-only `offers` on sale (every Standard and Premium band, 20 to 2,000 participants, each with its own price and switch), `upgrades` for a running subscription, payment/access state, period/grace/cancellation dates and activation state. `purchase.offer` names the plan of an open Checkout. Reads local verified state.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                         |
| `POST /api/account/billing/leagues/<id>/checkout` | `{"offer":"league-premium-20-monthly"}` | Any listed offer: `league-standard-<capacity>-monthly`, `league-premium-<capacity>-monthly`, or the same ending `-yearly` (a year costs ten months). Prepare or resume one reserved attempt: `200` with a hosted URL when ready, `202` while preparing/confirming, or `state:"other_plan"` while the League's open Checkout is for another plan. `{"code":"<promo code>"}` instead redeems a promo code: the code picks its plan (monthly or yearly), Checkout asks for no card, and the plan ends with its free months (a yearly code: its first year) unless you add a card in the billing portal. A sale code takes its percentage off the first year of the yearly plan you pick instead: send `{"code":"<sale code>","offer":"league-premium-20-yearly"}`, and pay the rest in Checkout as usual. A code that can't be used returns `state:"invalid_code"` with an `error` to show. |
| `POST /api/account/billing/leagues/<id>/upgrade`  | `{"offer":"league-premium-20-monthly"}` | Move the League's active subscription to a larger band or to Premium on the same interval (monthly stays monthly, yearly stays yearly), from `upgrades`. Stripe charges the prorated difference now; `state` is `upgraded`, `confirming` (`202`) or `action` with Stripe's hosted invoice `url` when the payment needs you. The old plan stays until that payment succeeds.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                              |
| `POST /api/account/billing/portal`                | `{}`                                    | A fresh hosted billing-management URL for the authenticated owner's stored customer.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                     |

Purchase quotes use the USD base price. Stripe/Link is the merchant of record through Managed
Payments and displays the final payment currency, recurring price and applicable tax at Checkout.
A completed but unpaid Checkout does not fulfill the purchase, and a browser return never grants
access.

Repeated Checkout requests reuse the existing purchase. An interrupted or ambiguous attempt
keeps its identity until verified recovery or support review; it does not start a second
subscription. Complete payment on Stripe, then return and refresh payment/access state. Neither
a success URL nor Checkout completion grants access without verified paid invoice evidence.
Cancellation at period end preserves already paid time and authorized League history. Support
assists owners whose account restriction prevents self-service billing management.

Arena+ shares the account's existing billing customer with owned Leagues, while retaining separate
purchase/subscription scopes. Staff or Premium League coverage does not silently replace or cancel
an individual subscription. A return to `/account?billing=return#arena-plus` carries no payment proof.

### Owner-managed leagues

On Cloudflare, these routes require an unbanned account's Supabase Bearer session, reject foreign
origins, and return `private, no-store` responses.
They are separate from participant enrollment in `/api/account/ladders`.

| Route                                         | Body                     | Result                                                                                                                                                                                        |
| --------------------------------------------- | ------------------------ | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `GET /api/account/leagues?after=<cursor>`     | —                        | Up to 50 owned definitions, `next` cursor, current entitlement, total `reserved` and pooled `staff_reserved` activation slots.                                                                |
| `POST /api/account/leagues`                   | `{"name":"My league"}`   | New inactive definition, `201`; does not create a Ladder or list it publicly.                                                                                                                 |
| `GET /api/account/leagues/<id>`               | —                        | Owner's saved definition, including inactive drafts.                                                                                                                                          |
| `PUT /api/account/leagues/<id>`               | Complete settings object | Replace the definition; omitted optional settings use defaults. While active, maps, `opens_at` and limits must stay the same.                                                                 |
| `POST /api/account/leagues/<id>/activation`   | `{}`                     | Activate with a current entitlement; repeating an active request is idempotent.                                                                                                               |
| `DELETE /api/account/leagues/<id>/activation` | —                        | Deactivate while preserving settings, membership and history.                                                                                                                                 |
| `DELETE /api/account/leagues/<id>`            | —                        | Remove a League never paid for or activated, returning `null`. `409 league_checkout_open` while its Checkout could still be paid, `409 league_not_removable` once it was paid for or has run. |

Settings include a single-line `name`, `description` (Markdown, up to 1,000 characters), `visible`
(default false), how players join beside invitations (`access`: `invite` for invitations only,
`approval` to also take join requests, or `open`; and `join_password`, true to also admit by the
shared password; older settings may say `access: "password"`, invitations or the password),
optional `opens_at`/`closes_at`, `maps`,
`max_players` (currently must be 20), and `house_bots`: which house bots play in the League, any of
`ts-starter`, `brawler`, `kiter`, `champion` and `mbot`, up to 4 at once (default
`["ts-starter","brawler","kiter","champion"]`). House bots can change while the League runs; a
`PUT` that leaves `house_bots` out keeps the saved choice. Activation applies the smaller
of the requested player limit and the entitlement. How many matches a League runs at once is
set by its size (`effective.max_concurrent` in `GET /api/ladders`), not by its owner: settings no
longer include `max_concurrent`, and one sent by an older client is ignored. Clients cannot set ownership,
enabled state, entitlement or publication revision. Staff manage participant approvals and
invitations through the existing admission API.

Each returned league has `id`, `settings`, `state`, `pending`, `published`, `expires_at`, effective
`limits`, `password_set`, optional `bound_access` (a current League-specific allowance) and nullable `image` (`url`, `alt`, `width`, `height`). Password hashes and
private image object keys are never returned. Draft image URLs require the same owner's session;
published spectator metadata uses the public `/api/leagues/<id>/image` route.

| Route                                                           | Body                                                                                                                    | Result                                                                                                                                                                                   |
| --------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `PUT /api/account/leagues/<id>/password`                        | `{"password":"shared phrase"}` or `{"password":null}`                                                                   | Set or clear the league's password; activation with `join_password` requires one, and a running one keeps it.                                                                            |
| `PUT /api/account/leagues/<id>/image`                           | PNG, JPEG or WebP bytes; matching `Content-Type`, percent-encoded `X-Arena-Image-Alt`                                   | Replace league artwork, running or not, at most 5 MiB and 1600 × 900; animated images refused.                                                                                           |
| `GET /api/account/leagues/<id>/image`                           | —                                                                                                                       | Private owner image bytes.                                                                                                                                                               |
| `DELETE /api/account/leagues/<id>/image`                        | —                                                                                                                       | Remove league artwork and enqueue durable object deletion.                                                                                                                               |
| `GET /api/account/leagues/<id>/invitations`                     | —                                                                                                                       | Last 100 invitations with `max_uses`, `uses`, `label`, `approval`, `expires_at`, delivery status, a shared link's `url`, recipient address for email invitations, and `email_available`. |
| `POST /api/account/leagues/<id>/invitations`                    | `{}`, `{"max_uses":null,"expires_at":null,"label":"Discord","approval":false}` or `{"email":"new-player@example.test"}` | `201` with the link's URL, or `202` with an emailed invitation ID; the League must be active. See below.                                                                                 |
| `DELETE /api/account/leagues/<id>/invitations/<invitation>`     | —                                                                                                                       | Revoke the link and cancel its pending email; players who joined by it stay.                                                                                                             |
| `POST /api/account/leagues/<id>/invitations/<invitation>/retry` | `{}`                                                                                                                    | `202` for a safely retryable failed email; `409` for ambiguous, expired, revoked or throttled delivery.                                                                                  |

#### Participants

The owner and organizers see everyone who joined, admit people waiting for approval, and remove or
reinstate members. Reporters read the list. A participant is named by their membership `id`, never
an account ID.

| Route                                                              | Body                          | Result                                                                                                                                                   |
| ------------------------------------------------------------------ | ----------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `GET /api/account/leagues/<id>/participants`                       | —                             | `{capacity, active, pending, live_matches, can_manage, participants}`: each with `handle`, `state`, dates, `reason`, `owner`, `joined_via` and its bots. |
| `POST /api/account/leagues/<id>/participants/<membership>/approve` | `{}`                          | Admit a pending member or reinstate a removed one (a new membership `id`). `409 ladder_full` at capacity, `409 ladder_closed` when closed.               |
| `POST /api/account/leagues/<id>/participants/<membership>/remove`  | `{"reason":"Left the class"}` | Remove a member or decline a request. The reason (1–1000 characters) is shown to them. Their bots disconnect; their history stays.                       |

#### Snapshots

The owner and organizers save a published League's standings now or at scheduled times. Members
read them through `GET /api/snapshots?ladder=<id>` and the result endpoints. Every route returns
`{snapshots, schedule, limits, played, closes_at, reset}`: `snapshots` as `/api/snapshots` lists them,
`schedule` each with `id`, `name`, `next_at`, `repeat`, `taken` and `next_name` (what its next
snapshot will be called), `played` false until there are standings to save, and `reset`
`{at, next_at}`: when the leaderboard was last reset and until when it can't be reset again (null
for either when it doesn't apply).

| Route                                                           | Body                                                            | Result                                                                                                                                                                                 |
| --------------------------------------------------------------- | --------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `GET /api/account/leagues/<id>/snapshots`                       | —                                                               | The League's snapshots and schedule.                                                                                                                                                   |
| `POST /api/account/leagues/<id>/snapshots`                      | `{"name":"After week 3"}`                                       | Save the standings now. `409 no_standings` before a rated game, `409 snapshot_limit` at 100 snapshots.                                                                                 |
| `DELETE /api/account/leagues/<id>/snapshots/<snapshot>`         | —                                                               | Delete one for everyone. `404 unknown_snapshot`.                                                                                                                                       |
| `POST /api/account/leagues/<id>/snapshot-schedule`              | `{"name":"Week","at":"2026-12-04T22:00:00Z","repeat":"weekly"}` | Schedule one. `repeat` is `none` (the default), `daily` or `weekly`. `400 snapshot_time_past`, `400 snapshot_after_close`, `409 schedule_limit` at 20.                                 |
| `DELETE /api/account/leagues/<id>/snapshot-schedule/<schedule>` | —                                                               | Stop a schedule; what it took stays. `404 unknown_schedule`.                                                                                                                           |
| `POST /api/account/leagues/<id>/leaderboard/reset`              | `{"confirm":"<League name>","snapshot":"Before reset"}`         | Save the standings as a snapshot, then start the leaderboard over. `400 reset_unconfirmed` unless `confirm` is the League's name, `429 reset_too_soon` within a day of the last reset. |

A name is 1–60 characters on one line. A repeating schedule names each snapshot `<name> <n>`,
counting only the ones it took, and moves on by whole days or weeks, so a time missed while
nothing could be saved is skipped. A League snapshot's ID is the UTC second it was taken, such as
`2026-12-04-220000`. Schedules end at the League's close. A draft League answers
`409 league_unpublished`; reporters get `403 league_role_forbidden`.

A reset clears the board's ratings, records, matchmaking history, the Rating and Rank charts,
team standings, new versions' head start from earlier ones and online time (every version's bank
is full again). Members, teams, bots, matches, replays, snapshots, schedules and lifetime totals
stay; the cleared games join the bots' lifetime totals. Its snapshot is saved even at the
100-snapshot limit and is listed with `"reset": true`. Before any rated game there is nothing to
save, so it saves none. A match that started before the reset counts toward lifetime totals, not
the new board. There's no undo.

The owner is an active member from activation (`joined_via.kind` `owner`) and doesn't count toward
`capacity`; `active` counts the other active members. Only the owner changes the owner's own
membership. Removal ends the member's access to the League
and any Premium benefits there at once; a removed member can't rejoin without being reinstated.

An invitation link's options: `max_uses` (1–1000, or `null` for no limit; default 1), `expires_at`
(a future time, or `null` for none; default seven days; never after league closing), `label` (up to
60 characters, shown only to the owner and organizers) and `approval` (`true` makes each join a
request to approve; it needs `max_uses: null`). A link that allows more than one use is shared: the
list returns its `url` so organizers can copy it again. A single-use link's URL is returned only
when it's made. An emailed invitation takes none of these options; it admits its recipient once
within seven days. `joined_via` in Participants is `{kind, label}`, where `kind` is `link`,
`invitation`, `password`, `request` or `open`, or `null` for older memberships.

Email addresses are normalized to lowercase and may belong to someone who has not registered yet.
Redemption compares the invitation's recipient hash to the authenticated session email, never an
email supplied in an enrollment body. Emailed invitations expire after seven days or league
closing. An invitation's use is spent only on successful admission, and joining again spends nothing. Owner lists expose neither bearer tokens nor encrypted
mail payloads. At most 20 emailed invitations can be created per owner per hour; delivery shares
the deployment's email mode, staging allowlist, suppression and daily budget.

Known transient provider refusals retry with backoff. An interrupted or ambiguous submission is
marked `unknown` and cannot be resent; revoke and replace it. Safe manual retries retain the
attempt count and stop after five provider submissions. No message is sent when email is unconfigured.

`202` with `pending:true` means a durable transition is still publishing, draining or archiving;
poll the catalog and retry the same operation rather than creating a replacement league. A
deactivating slot remains reserved until its final standings and match rows are verified in R2.
Running matches finish first; a connected bot receives its final `end` before the normal
graceful connection close. Moderation, replacement and recovery disconnects remain immediate.
An expired grant cannot start new matches even if its cleanup alarm has not run. Retrying after
deactivation/reactivation uses the same league ID and match key. A running League's name,
description, listing, admission, password, image and end time (`closes_at`) change in place and
republish at once; its maps, `opens_at` and limits change only while inactive (`league_active`,
409). A `closes_at` already past ends the League at the moment of the request (End now), and on a
League that has ended another past time changes nothing; `null` or a later time reopens it. At its
end the League saves a `Final standings` snapshot (`Final standings 2` after a reopen), outside the
snapshot limit; taking or scheduling a snapshot by that name is `invalid_request` (400). A running League
switches to password access only once it has a password, and keeps one while it admits by password
(`password_not_configured`, 409).

Errors include `league_entitlement_required` (403), `active_league_limit` (409), `league_active`
(409), `invalid_league` (400), and `unknown_league` (404, also used for another owner's ID).
Admission reports `ladder_full` when no player seat remains, including approval and reapproval.
Read [league lifecycle and privacy](/docs/ladders#start-stop-and-restart) before
using a league for sensitive data.

### Participation and spectator reads

See [multiple ladders](/docs/ladders) for enrollment and participation.
`GET /api/ladders` returns visible definitions (`visible` defaults to true) with `phase`, `leaderboard_url` and
associated event links. A ladder with a player limit (`max_players`) also gives `players`, the spots
taken: its active members, not counting a League's owner, who plays outside the limit (null without a limit). Hidden ladders remain accessible by ID; signed-in account
listings include them when the account has a membership. An explicit
`?ladder=<id>` on `/api/ladders` or `/api/account/ladders` also includes that
ladder, supporting direct enrollment links (`/ladders?ladder=<id>`). `?ladder=<id>` selects independent ratings/history for
`/api/leaderboard`, `/api/matches`, `/api/lobby`, `/api/bots/<name>` and its `/ratings`.

Bot objects in rankings, details, matches, lobby entries and event opponents include
`display_name`: Starter, Brawler, Kiter or Champion for official house opponents on any
ladder, and the canonical name for player bots. Use `name` for identifiers, API calls
and links. `/api/status` adds `display_name` to online entries and `display_names`
in seat order to active matches; rating history adds `opponent_display_name` with
the version suffix. Replay files and WebSocket messages retain canonical names.
The replay viewer uses match `display_name` fields for actions and fighter labels, falling
back to the recorded bot names when match metadata is unavailable or a replay is uploaded.

These default to Public; `/api/status` is aggregate unless scoped. An unknown
ladder returns 404. Match responses include `ladder_id`.

| Browser route (Supabase Bearer)             | Body                                                                        | Response                                                                                                                                                                                 |
| ------------------------------------------- | --------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `GET /api/account/ladders`                  |                                                                             | Definitions with your `membership` (null, pending, active or revoked).                                                                                                                   |
| `POST /api/account/ladders/<id>/enrollment` | `{"invitation":"optional code"}` or `{"password":"optional join password"}` | Updated account ladders. A matching password or valid invitation admits at once (an approval link waits for approval); with neither, a ladder that takes requests creates a pending one. |

These require an unbanned account, reject foreign origins, and return private,
no-store responses. These browser routes reject bot/agent/MCP credentials. Consented MCP
clients can inspect membership with `list_my_ladders` and join with `join_league` after
explicit owner approval, through the same admission checks. Existing registration-only grants
require renewed consent; see [MCP.md](/docs/mcp). Bot tokens cannot enroll. No active enrollment
returns `enrollment_required` for event queues, opponent requests and flag reveals.

Public `/api/events` and associated ladder summaries include branding images and flag submission
instructions. Instructions preserve line breaks and HTTP(S) links; HTML stays plain text.
Enrollment revocation does not erase historical standings or awards.

WebSocket queue adds optional `ladder_id`; omission selects `public`. `queued`
and ladder `end` identify the ladder. One bot queues in one scope at a time;
switch after completing a match. Ratings start independently in each scope;
new version seeds use only prior ratings from that ladder. Global quotas still
apply. Event matches ending outside the window or after an enrollment change
remain recorded but are unrated. Human matches use Public.
