# Victris Arena Engine Spec

The ladder serves this specification as HTML at `/guide/spec` and Markdown at `/docs/spec`, generated from the same source. Public introductory pages and release notes are readable without JavaScript; combat numbers remain authoritative in `hello.rules` and `/docs/rules`.

Sep 23, 2026 · @Tristan Rhodes

## Public bot distribution

The ladder distributes one starter bot in TypeScript and Python, plus Random and its generic client
code. The public simulator includes `ts-starter` and `random`; the existing browser opponent selector
offers Random (Easy, Jester) and Starter (Hard, Sentinel). Brawler, Kiter, Champion and their combat
helpers stay in server-side house code and internal tools.
These opponents remain available on the ladder, including for event achievements.
Brawler and Kiter remain fast scripted opponents: Brawler presses for close-range slams, while
Kiter maintains range and retreats from pressure. They plan around visible hazards, observed enemy cooldowns, pickups and the shrinking
zone. Neither uses a model. Combat rules and replay compatibility are unchanged.

Champion keeps its trained network, samples live choices with private randomness, and adds a
bounded amount of early movement variation to reduce repeated winning lines. Its `-varied`
version suffix separates its rating history. M-Bot, a separate optional opponent, uses the same
private randomness and varies close movements for the whole match; its version also ends in `-varied`.
These policy choices do not change combat resolution or replay compatibility.

## Overview and design goals

The engine runs deterministic, tick-based fights on a tile grid between bots that are programs players run on their own machines, connected over WebSockets and exchanging only JSON. It is the single authority on rules: bots state intents, the engine validates and resolves them.

This spec has two audiences: developers building the engine and local runner, and AI agents writing fighters. Agents should be able to write a working bot from this document alone.

Guiding principles:

- **Simple protocol.** Any language that can open a WebSocket and exchange JSON can compete, and no player code ever runs on our servers.
- **Engine is authoritative.** Bots never mutate state; the engine drops any part of a turn it refuses, and a missing or malformed turn is `idle`.
- **Deterministic resolution.** Same seed plus same turns always produces the same match.
- **Simultaneous turns.** Both bots act at once and attacks fire the tick they are sent, so up close the skill is predicting your opponent; at range, projectiles and areas are visible in flight, so the skill is reading and dodging them.
- **Data-driven combat.** Every attack and stat is a data entry, so weapons and items later are data changes, not engine rewrites.
- **Documented order.** Tick resolution order and edge cases are published, so agents exploit rules rather than guess them.

The hosted game exposes its Privacy Policy at `/privacy` and Terms of Service at `/terms`. Both pages are public, readable without JavaScript or an account, and linked from the homepage and sign-in card. The privacy policy explains authentication, identifiable public gameplay records, private League access and selected-result publication, storage, service providers, and contact-based access and deletion requests. Stopping play or deleting an account does not make private history public.

Players can send feedback from `/contact`, linked as Feedback in the site Menu and next
to Discord on the title extras. Messages go to the Victris team.
The public contact address is `hello@victrisarena.com`. The form needs JavaScript; without
it the page still names the mailto address.

Match pages and relative-time tooltips display the viewer's browser-local date and time with a
time-zone label, falling back to UTC if the browser cannot resolve or format its zone. Hover
text also provides UTC. API timestamps and HTML `time` values remain UTC ISO-8601 instants;
relative ages are independent of time zone.

Replay viewer actions, fighter cards, view selection and stats headings use bot names, preferring
the ladder's display names when available and falling back to replay names for uploaded files.
The local CLI's tick status and replay results also identify fighters by bot name.

## Participation and accounts

The ladder requires Supabase user authentication by default and refuses startup without
Auth configuration. Only an explicit `allowAnonymous` / `serve --allow-anonymous` local
development option permits anonymous registration and play. Public pages, replays, docs,
downloads and offline simulation remain public. Website signup (email confirmation,
recovery, Google or GitHub), public Auth API onboarding and MCP browser OAuth all lead
to one ladder account and a public handle. `/api` publishes the participation policy
and onboarding URLs. User access tokens and revocable account agent keys register bots
through the same ownership and quota checks as the website and MCP. Self-declared owner
names and legacy operator owner keys cannot bypass account registration.

When MCP is enabled, MCP with browser OAuth is the standard AI-agent onboarding path on
Create a Bot, My Bots and the agent guide. The two setup pages share a task prompt: discover the
account and tools, build and test locally, register through MCP, run the fighter with its bot
token, then inspect match statistics and propose an improvement. Key creation is under a collapsed
**Advanced connection options** disclosure, opened automatically when MCP is disabled. Existing
connections and revoke/disconnect actions remain visible. Manual website registration and advanced
HTTP/CLI onboarding remain supported. MCP does not run fighter code or replace the bot WebSocket.

The account page leads with a compact handle card and button-styled links to event ladders
and achievements, followed by Your bots, AI agents & connections, and Account settings.
Agent setup and Email preferences are collapsed by default; existing connections remain
visible. Admins get a separate Administration section with an Admin console shortcut.
Before choosing a handle, players can also expand Email preferences on the handle card.

Accountless legacy bots retain their histories and tokens, but `/bot` refuses hosted participation
with `account_required`; owners must register a new bot under an account. Legacy bot claiming is
removed from the account page, HTTP API and discovery metadata. House bots are exempt.
The tutorial at `/tutorial` needs no account and is not recorded: ten narrated chapters of
scripted fights, played by the engine in the page; the old
`/play` and `/viewer/play.html` addresses redirect to it. Registration cannot adopt
house bots. MCP only receives
permission to register bots, inspect results and perform the documented account actions with consent;
account passwords remain with Supabase Auth.

Owners open **Edit** beside a bot on My Bots to change its appearance, select the AI
agent that built it (**Built with**), replace its token, or retire it (delete if it has never
played). Their own bot's detail page offers **Edit bot**, linking to `/account?edit=<name>#bots`
with that bot's editor open, including retired bots. Portraits in the editor follow the mouse
and keep following it with idle motion disabled.
The icon beside a bot in Your bots previews its selected persona and colour, including Randomize
and Reset. Persona and colour selections save automatically, including Randomize; hovering only
previews a tile. Reset restores and autosaves the look from when the editor opened. Saving and
failure feedback remain visible if the editor closes, with Retry for a failed save. Rapid changes
save in order so the last selection wins; closing keeps the selected look.
Editors replace **Edit** with a top-right close control and provide **Reset** beside **Close** at the bottom right.
Expansion and collapse use one height transition so the rows and form below move together;
reduced motion skips it. Closing returns keyboard focus to **Edit**.
**Create bot** reveals the name form, which stays hidden until requested and closes on success or
Cancel/Escape. At the bot limit, the primary button is disabled with an explanation to delete or
retire a bot first (or to unretire one after freeing a slot). Creating a bot asks only for its name. **Built with** is optional and appears only in the editor,
where a modal provides one alphabetized agent list searchable by name, alias or company. Owners
can select a listed agent, enter a custom name, or clear the attribution; changes apply on Save.
Agent crests use matching monochrome Lobe Icons logos served locally, with initials for custom
agents, hand-coded bots and agents without a suitable mark.

Owners choose an avatar for each bot in this editor, from a fixed catalog of 28 personas, or none
for the plain orb. It is cosmetic and never reaches deterministic combat or input-only replay bytes.
New match records capture each fighter's avatar/color and the version/content hash of their cosmetic
assets at setup. Match pages, previews, viewer metadata, recap highlights and private archived reads
use that recorded appearance after a profile change. Version-one procedural artwork, animations and
palettes remain renderable independently of the active picker catalog. Version two redraws the first twenty
personas, each reacting to windups, hits and movement in its own way, and adds eight (Knight, Glitch,
Kraken, Inferno, Golem, Voyager, Mantis, Slime). New appearances record `asset_version` 2 with version
two's content hash. Pages draw every look, recorded ones included, with the newest
version's art for its persona: a match keeps the persona and colour it recorded, not the art of its
day. An older version draws only a persona the newest no longer has. Legacy match rows without an
appearance use plain orbs/classic colors and identify that fallback; they do not borrow today's paid
profile appearance. Existing saved standings retain their frozen fields. A replay file on its own still shows plain orbs. House bots wear one that suits how they play: kiter Shade,
brawler Berserker, ts-starter Sentinel, champion Monarch and random Jester.

A live leaderboard entry keeps its version's last completed rated appearance. Profile edits do not
repaint that standing: a nonvoid rated result captures the current local appearance when its update
commits, independently of the match's setup appearance. Void, unrated and duplicate results leave it
unchanged. Public and each League store this reference separately. At migration, old played versions
freeze the currently visible appearance once as `legacy_frozen`, without claiming its original match
appearance or paid status. New monthly snapshots retain the standing appearance on their rows and
roster; existing saved snapshots keep their frozen fields.

Owners also pick a colour for each bot from a fixed palette of 14, or none for Classic: blue
in the first corner and red in the second. It is cosmetic in the same way and colours
everything drawn in a fighter's team colours: the orb under any avatar, its nameplate, health
bar, shots and effects, and its portraits. When both fighters in a match wear the same
colour (a bot with none wears its corner's), one is drawn in whichever of classic blue and red
stands further from the other's: the second fighter, unless only the first has no colour of
its own. House bots wear their corner's colour.
Portraits and fighters share shaded materials and persona details. Idle motion varies by persona
(heavy armour, floating cloth or lively gestures); fighters also lean into movement, brace during
attack windups and recoil on hits. Portraits honour reduced motion, including preference changes
while a page is open.

Account handles and bot names accept letters and numbers from every Unicode script,
plus combining marks immediately following a letter, number or another mark in that run.
Bot names also allow `-` and `_`; handles additionally allow `.` and start with a letter or number.
Names are stored in NFKC, with length measured in normalized Unicode code points (2–24 for bots,
2–39 for handles). Uniqueness and lookup use NFKC plus locale-independent Unicode upper/lower
casing. Spaces, emoji, controls, default-ignorable characters (including joiners, variation selectors
and invisible fillers), orphaned marks and other punctuation are rejected. Mixed scripts are
allowed; cross-script visual lookalikes are not folded. Name URL segments are percent-encoded
and decoded once. Schema 29 adds an indexed unique Unicode handle key, backfilled for existing
ASCII handles; bot identity and replay formats are unchanged.

Text other people see is refused, not masked, when it carries profanity or slurs: handles, bot
names, custom agent names, version labels, aliases and notes, League names and descriptions,
League branding, League team names, shared-result titles and the reason given when removing a
League participant. The check uses the same English word list as shouts, and reads text the way a
person would: lookalike letters folded, invisible characters removed, `_` as a space, `MyName` as
two words and spelt-out letters (`f_u_c_k`) joined. The refusal is a 400 that names the field and
never repeats the words. Only saving is checked: names and text saved before the check keep
working.

On My Bots, bot names and portraits link to the bot page. Owners can rename their bots between
matches, including retired bots, by opening **Edit** and clicking the name inside the editor. Enter or Save confirms; Escape or Cancel discards the draft. Registration
and renaming share the same 2–24 character format and case-insensitive global uniqueness;
house, suspended, banned and retired bots reserve their current names. A case-only rename is
allowed, and the previous name becomes available after a rename. Bot ids, tokens, versions,
ratings and match history stay intact. Historical match pages use the current bot name for
links; persisted match records and replay files retain their original names. Suspended or
banned bots cannot be renamed. Renaming takes the owner's browser account session, or MCP's
`update_bot` with a `new_name`, the owner's approval and account-actions consent; MCP may rename 5 bots per
account in a rolling 24 hours, counting website renames (`429 rename_limit`). Both audit
`bot_renamed` with how it came.

## Player announcements

The announcement bell opens with read messages hidden. Opening it does not mark messages
read: players can mark one message read or mark all currently loaded unread messages read.
Show read messages reveals read history; closing the tray restores the unread-only view.
Read state persists in the current browser, including history from earlier versions.

Players receive published in-game announcements and can choose email announcements in
`/account`. Notices support line breaks and HTTP(S) links; HTML remains plain text. Editing a
notice does not resend previously published emails. Announcements do not change combat,
replay inputs or the bot WebSocket protocol.

A banned account cannot use account routes, agent keys or MCP (`account_banned`), and its
bots are disconnected and refused. Lifting a ban restores access. Deleted accounts lose their
handle, agent keys and MCP approvals; their bots keep names and historical match records.

## Replay retention

The ladder keeps every completed game's replay privately, including human and voided games. What
you can watch and download depends on the match and your plan:

| Match                           | Replay and full stats                                                                 |
| ------------------------------- | ------------------------------------------------------------------------------------- |
| Public, any reader              | Free while the match is in either bot's newest 200 completed public games             |
| Public, reader with Arena+      | Also free in either bot's newest 1,000                                                |
| Private League                  | The League's owner and active members (and, with Premium, its delegates), however old |
| Public match result (no replay) | Always readable                                                                       |

- The window counts each stable bot's games across all its versions, voids included, ordered by
  completion time and then match ID. League games are not counted.
- Outside the window, a recording returns `403 arena_plus_required`, or
  `403 outside_arena_plus_window` past Arena+'s 1,000. Don't retry these.
- A recording that is temporarily unavailable returns a retryable `503`; back off and retry.
- Minute packs (`pack_url`, `/archive/packs/public/<id>.pack`) hold only public matches. League
  matches never advertise one, and a League pack returns `404 pack_unavailable`. On the public
  ladder, which enforces the window, a pack holds only the matches anyone may download free;
  the rest are each match's own `replay_url`/`stats_url`, Arena+ included. Match lists with inline
  stats return `503 public_bulk_stats_unavailable`: list without `stats=1`. A ladder you run
  yourself leaves the window off.
- Matches from before collection began on 2026-11-06 are best-effort.

The endpoints, authentication and paging are in
[historical public recordings](/docs/api#historical-public-recordings); plans are under
[Subscriptions](#subscriptions).

## Website tables

The leaderboard header’s **View Chart** button, with a chart icon, links to `/leaderboard?view=graph`, a standalone event display that
refreshes every three seconds and retains the selected ladder. Each
bot’s avatar is plotted by leaderboard rank horizontally and leaderboard score vertically;
a vertical-axis selector can show raw rating while keeping the same ranks. Equal values
share a horizontal band. Hover, tap or keyboard focus shows the bot’s name, owner, score
and rating, with a link to its page. The display title is Leaderboard, the score axis is
labeled Score, and a back arrow beside the title returns to the table with the selected
ladder intact. Fullscreen uses the browser’s fullscreen control.

The Recent matches header’s TV-icon button links to **Watch Live** (`/leaderboard?view=watch`), a separate
full-page display of recent completed non-voided bot matches from the selected ladder
and month. The watch page’s heading names Victris Arena, the ladder and any past month;
large bot portraits sit at the outside ends of their health bars above the gameplay,
in the same colours as their fighters. The leaderboard graph contains only standings.
The watch page autoplays muted using the replay viewer’s renderer and pace, holds the result briefly, and cycles
the playlist while picking up new matches and skipping unavailable replays. The player has
no heading or transport toolbar above the gameplay. The game fills the window edges; its compact
heading, back arrow and Fullscreen control sit below it, with no current-replay link or vertical
health-bar accents.

The list of past months loads on entry to the ladder and standalone displays and refreshes when a
hidden tab becomes visible.
They do not poll periodically. This does not drive playback:
Watch Live checks for recent completed matches every 15 seconds, while standings keep their
three-second refresh cadence. All interval refreshes pause while the tab is hidden.
Its back arrow returns to Recent matches,
including the Matches tab on a phone, with the selected ladder intact.

Watch Live and normal replay playback share a final-hit sequence for knockouts: a close-up
tracks the dying fighter (both fighters for a double knockout), slows the last tick around
its lethal event, holds the impact, and lets death particles settle before the result
appears. A large portrait uses the winner’s equipped avatar and colour, with a soft halo
and result text over the arena at its normal brightness; there is no dark panel or extra
dimming. Landscape windows place the portrait beside the text; phones stack them. Ordinary
impact shake is brief and bounded to two CSS pixels per axis; the final-hit sequence and
reduced-motion playback have none. The result reveal follows about 2.35 seconds after entering the final tick; the
normal replay's stats open after that reveal, and Watch Live holds it before advancing.
Pausing freezes the sequence; scrubbing or stepping bypasses it, and reduced-motion viewers
use ordinary playback. Timeouts and administrative endings do not invent a killing blow.
These are viewer effects; engine ticks, recorded inputs and replay compatibility are unchanged.

The leaderboard, bot versions, health, opponents and maps, and admin data tables have
clickable column headings. A first click sorts ascending; another reverses it. Each table
keeps its selected column and direction as records refresh, including additions and removals.
Numbers, percentages and dates sort by their underlying values; missing values stay last.
Compound cells sort left to right (wins, losses, draws; rating, standard error; reply median,
95th percentile, maximum; disconnects, disqualifications). Version notes stay with their rows.
The opponents panel selects the 100 most recent opponents with non-voided games from
the bot's last 500 matches, newest encounter first. Column sorting reorders that same
selection. The panel scrolls internally to preserve its visual area on desktop and phone.
Opponents, Maps and the position heatmap have independent bot-version dropdowns that list
only versions with a counted game on the selected ladder (on Public, in the rolling window).
They default to the current version, or the newest version with a game when the current one
has none. Older and retired versions with games, and All versions on Opponents and Maps, can
be selected. A bot with no games on the ladder shows an empty state saying so. The Versions
panel keeps listing every version. Filtering a full 500-match window loads that version's
own matches.
Explicit choices survive data refreshes; untouched dropdowns follow the current version.
These two summaries retain compact table rows in narrow panels, wrapping long names
and omitting the opponents' Last column when space is limited.
Headings support keyboard and touch input and announce the active direction to screen readers.
Reference tables, mixed-unit match statistics and action columns retain their fixed order.
Ladder and bot panels omit explanatory footnotes about ratings, qualification, health
and sampling. Detailed definitions remain in the API guide.

Leaderboard, version, health, opponent and map tables use labelled rows when their panel is
600px wide or narrower, with the sorting controls above them. Full counts and long names,
versions and notes wrap inside their cells. Summary records wrap between whole win/loss/draw
counts, and tile descriptions wrap instead of being clipped.
Rating legends wrap long versions; line-end labels appear only when they fit, and tooltips
wrap and stay inside the chart.
The bot page's Rating and Rank charts offer 1D, 1W and 1M, then 3M and 1Y once the bot has played
longer than the frame before, and All. Each frame is read in a point budget (2,000; 4,000 in the
large view) at the finest detail that still shows most of it: each game, runs of 10 or 100 games,
or a version's whole day, finer toward the present where the budget reaches. The large view adds
the shown stretch's record, peak rating and best rank, and a drag across the chart zooms into that
stretch until **Zoom out** or closing it. A frame change hides the previous chart while it loads;
opening or closing the large view keeps the same frame on screen until its new points arrive.

## Event achievements

Events award five independent achievements per account: First Blood (a standard
house win), Bank Shot (a house win with a damaging ricochet), Wall Breaker (a house
win with a damaging repulsor wall slam), House Sweep (wins over three distinct
standard house kinds), and Champion Slayer (a champion win). Progress combines
owned bots and versions within an event; retirement and handle changes preserve awards.

Eligible matches are ranked, nonvoid wins by `last_standing`, `timeout_hp` or
`timeout_damage`, with recognized server statistics and neither fighter disqualified.
Ownership and official house identity/version are captured before play; the account
must remain eligible at completion. Start must be at or after opening and completion
strictly before closing. Human/local games, uploaded replays, player opponents,
forfeits, draws and matches without account ownership at start do not qualify. The contender's fighter ID
determines its statistics; both mechanic hit counts and corresponding damage must
be positive. All four approved house opponents must be available at qualifying starts;
the champion counts at whatever version it plays, since it keeps training through an event.

Definitions freeze for enabled events; code, rules and maps are not pinned, so a
release can ship during an event. Results, statistics,
progress and awards commit together; duplicate completion is ignored. Retained
event facts permit recovery after replay trimming without rerating games; recovery
preserves revoked awards. Staff can inspect evidence and revoke with a reason.

`/achievements` shows public conditions and private progress after browser sign-in.
It also shows each event's public flag submission instructions and optional HTTPS
submission link. Admins edit these in the Events tab, with a player preview.
Instructions allow up to 4000 characters, preserve line breaks and format only
HTTP(S) links; other markup stays plain text. Submission details default to the
manifest, with admin overrides persisted across restarts and editable after scoring
definitions freeze. An empty instruction string and null URL hide this section.
Flags are runtime secrets revealed only for that account's earned, nonrevoked award,
with private/no-store responses. Raw flags never enter public views, SQLite or audits.
Shared mode is implemented behind `EventFlagProvider`; contestant-bound HC validation
requires a future enrollment/validator integration.

One durable opponent request per account can prefer an official house kind with
an owned connected bot. Normal quotas, capacity, pacing, rematch holds and owner
exclusions apply. Requests expire after ten minutes or event closing and cancel on
queue leave/disconnect. An account waits a minute between requests/requested starts.
Four ordinary starts earn one preferred-start credit (one initial, maximum four);
requests may use otherwise idle capacity. The selected bot waits for its request
while other bots continue normal scheduling.

SAINTCON 2026 opens `2026-10-27T18:00:00.000Z` and closes
`2026-10-30T12:00:00.000Z` (noon October 27 through 6 AM October 30,
America/Denver). The preset is disabled until real flags are configured. Future
events have separate IDs, windows, progress and flags. Events are retired from the player-facing site,
public API and MCP since November 7, 2026: Leagues replace them, `/achievements` redirects to
`/ladders`, and the event backend and staff tools stay dormant with their data. Combat and bot wire
messages are unchanged.

## Bot protocol

A bot is any program the player runs on their own machine or server. It connects to the game server over a WebSocket and exchanges JSON messages; the server never receives or executes player code. Each WebSocket text frame carries exactly one JSON object.

**Connecting**

- Bots connect to the game server's bot endpoint, `wss://victrisarena.com/bot` (`GET /api` reports it as `bot_endpoint`; a ladder behind TLS uses `wss://`), and authenticate with the bot's API token in an `Authorization: Bearer` header on the upgrade request. A missing header is refused with `missing_authorization`, an unknown token with `invalid_token`.
- Each registered bot has its own token. One connection per token is active at a time; a new connection closes the old one.
- After connecting, the bot sends `queue` with the version it is running, which asks for one match. The matchmaker picks the opponent; when a match is found the server sends `hello`, and the bot plays one match at a time on that connection. After each `end` it sends `queue` again.
- Bots connect out to the server, so they can run behind home routers and firewalls. The server never makes requests to player-supplied addresses.

**Keepalive**

The ladder sends WebSocket Ping control frames every 25 s by default, even while idle or
queued, and terminates a socket that has not returned a Pong by the next check. Pongs echo
the Ping payload; supported client libraries answer automatically. Both the ladder and local
runner answer client Pings; the local runner does not originate periodic Pings. There is no
JSON heartbeat message or `stale` event. Control frames are separate from the JSON protocol.

Clients must detect silent transport failures rather than trusting socket-open state. The
reference clients use a 10 s opening timeout and client Pings every 20 s with a 20 s matching
Pong deadline, then reconnect with delays from 1 s up to 30 s. These are client recommendations,
not match deadlines. Queue silence alone is not a failure, and transport liveness does not
guarantee application progress. A heartbeat can fail too late to preserve the current match:
disconnect grace begins at server detection, and missed turns may disqualify the bot sooner.
Recovery uses the same token and the resumption procedure below, without resending buffered
turns. See [keepalive and recovery](/docs/api#websocket-keepalive-and-recovery) for signals,
intermediary timing, examples and bounded closing behavior.

On Cloudflare, recovery is best effort and may abandon an unfinished match or lose its result.
Completion clears matching socket attachments even if hibernation lost the hub's active map.
During normal League shutdown, the relay delivers a connected bot's final Runner `end` message
before closing its connection. The internal graceful-close request is scoped to that match;
moderation, replacement and recovery closures still take effect immediately.
Socket attachments retain a routing hint and an expiry based on startup + both fighters' match
budgets + both reconnect allowances + a 60 s reporting margin. An interaction after expiry clears
stale state; it does not schedule background cleanup or persist per-match recovery rows. Legacy
attachments get one such grace period on first interaction, or are abandoned on reconnect when
their placement cannot be recovered. A current relay may abandon a match its Runner confirms is
missing. Recovery uses close code 1012 and the existing client reconnect/queue path; late events
for an older match or relay cannot clear a newer one. Owner slots retain their existing soft expiry.

Finished games retain distinct identities even when their start time, seed, participants and result
are identical and they finish out of order. Recording retries do not count or rate a game again.
If an older sequence collision requires a new match id, its original id has a transactional receipt
for the canonical record and media, retained after live-row expiry. Pre-receipt collision recovery
requires a unique matching replay location and result facts; a start time and seed are insufficient.

**Bot versions**

A bot is a long-lived identity with a name, an owner and a token. Official house bots display as Starter, Brawler, Kiter and Champion across all ladders, using their roster kind (or their legacy public name). API `display_name` labels are separate from globally unique canonical names used for links, protocol messages and replay identity; player names are unchanged. On a ladder with accounts, a person signs in with email/password, Google or GitHub (through Supabase Auth) and picks a handle; their bots, made on their account or by an agent with one of its agent keys, belong to it and show the handle as their owner. Email signup requires confirmation, and password recovery uses an emailed link followed by a new-password form. Email links use PKCE and must be opened in the browser that requested them. Supabase stores passwords and sends auth emails through the configured SMTP provider; the ladder verifies access tokens and never receives passwords. A version is an immutable record under that bot, with its own rating and record. The leaderboard lists each bot once, at its current version; earlier versions keep their ratings and records on the bot's page, so a player can follow the bot over time and spot a regression.

Each bot detail panel can expand into a modal dialog sized to the window. Its filters and sorting remain selected; Close, Escape or a click on the backdrop restores the compact view and its original scroll position. Background controls are inert while the dialog is open, and closing returns focus to the panel’s Expand button.

Bot token, appearance, agent, version and ownership changes update cached bot objects only
after their SQLite transaction commits. A rolled-back transaction leaves the previous token,
versions and ownership usable without restarting; rolled-back version creation consumes no quota.
Account deletion rolls back cached team membership along with its database records if it fails.

Player registration commits the bot and its `registered` audit event in one SQLite transaction
across browser, agent-key, MCP and explicitly anonymous/legacy-owner paths. An audit insert or
commit failure publishes no cached bot, agent-standings revision or creation metric and leaves
its name and bot quota free. The token is returned after commit. Response loss after commit
still requires account reconciliation; registration is not idempotent.

Registration, bot/version/handle and operational-settings boundaries translate only explicit
input/domain errors to 4xx responses. Unexpected storage or programming failures reach the
central sanitized 500 handler; MCP returns a generic `tool_failed` message for unexpected
exceptions. House administration follows the same classification: unexpected failures use the
central 500 handler, while invalid operations remain client errors. Settings conflicts remain
409 and malformed settings JSON remains 400.

Shared browser data loads are keyed by resource identity and serialize interval/visibility
refreshes. Resource changes immediately show loading, obsolete responses are ignored, and
null keys hide prior data. A 404 clears a previous success; transient same-resource failures
retain its data with refresh-error state. Refreshes use the current loader and interval.

Browser JSON clients require successful responses to parse as an object or array. Malformed,
empty or primitive success bodies raise `invalid_response`; failed responses retain their HTTP
status and only string error messages/codes are accepted. Public 404 reads remain missing-resource
results. Account data is retained when a write's response is invalid.

Hosted auth and account-security emails use the game's branded HTML templates, preserving Supabase's verification links and codes. Operator announcement emails use the same layout with safe HTTP(S) links, escaped message text, and a plain-text alternative that spells out each link's address. Their inbox preview is the message's opening words without link markup, and their button opens the message's first `[label](…)` link to the ladder's own pages, with that label (otherwise the home page). When `ARENA_POSTAL_ADDRESS` is set, their footer carries it, as commercial email must. Admins preview the branded email before publishing; email preferences and the frozen published message still apply.

When automated email is enabled, first authenticated Arena account creation atomically
queues one welcome per Supabase identity and conditional onboarding help at 24/72 hours.
The welcome and onboarding send a player without a bot to `/create-bot`, one without a handle to
`/account`, and one whose bot hasn't played to the agent guide page (`/guide/agents`); every
branded email's footer links that page, not the Markdown at `/docs/agents`.
Confirmation remains Supabase's responsibility. New accounts enable onboarding and
achievement mail; existing accounts keep announcement opt-outs and start with new optional
player categories off. `/account` manages onboarding, achievements, bot health, enrolled-event
reminders, weekly progress and admin-warning preferences. Account/security/status mail stays
essential. Other optional mail shares a two-message rolling 24-hour cap, including announcements.
Achievement mail doesn't count toward it and has its own cap of five a day. A new award waits
10 minutes, then one email covers every pending award in its event; payloads contain only
event/achievement IDs, never flags.
Routine reconciliation/deployment does not backfill awards or welcomes. Reminder eligibility,
current confirmed recipients and revoked awards are rechecked before delivery.

Schema 20 adds durable private intents, category preferences, authenticated encrypted
90-day unsubscribe tokens, address-hash suppression, captured match ownership and persisted
health incidents. Account/award mutations enqueue inside their transaction; provider calls
run outside simulation. The worker reserves quota for essential/admin mail and serializes
with announcements. Definite transient refusals retry with bounded backoff; ambiguous and
interrupted submissions stay unknown without automatic resend. Accepted means provider
acceptance only. Terminal private notification content is deleted after 30 days; minimal
semantic deduplication and suppression persist. GET unsubscribe only reads the category;
POST with its scoped token opts out without login. Welcome deduplication survives local
account deletion; account deletion removes private queued/terminal mail. Onboarding expires
at seven days. Queued bot-health links follow the bot’s current name, including on delivery
retries. Bot health requires three DQs in the last five games within 30 minutes and stops
during a server incident; event reminders require active enrollment/current schedules.
Subscribed weekly progress runs Mondays at 09:00 UTC for meaningful recent games.

An account's owner can remove their bots. A bot with no match on file, of any mode, is deleted with its versions, freeing its name; agents can do this too, with an agent key or MCP, to undo a registration. A bot that has played can't be deleted, because matches, replays and opponents' ratings refer to it: its owner retires it from the account page. A retired bot is refused (`retired`) and leaves the leaderboard, keeps its name, page and matches, and stops counting against the bot limit. Owners can unretire a bot (`POST /api/account/bots/<name>/unretire` or MCP `restore_bot`) when they are under the cap; at the limit they must retire another first. Lowering `maxBotsPerOwner` (or restarting after a lower cap is already live) retires extras, keeping each account's best public-ladder ranks. Suspended and banned bots can't be removed, so moderation still holds their place under the limit.

Teams are an account's single, optional email-verified affiliation. `/universities` and
`/organizations` present the separate public-ladder standings (`/teams` redirects); `/api/teams`
defaults to `kind=university`, with `kind=organization` selecting the other board. `.edu` addresses
belong exclusively to Universities,
using their root `.edu` domain. Organizations use the registered domain from the Public Suffix
List; known shared/disposable providers and private hosting suffixes are refused. Supabase's
verified sign-in email can join directly, or the player confirms an emailed code. One verified
address backs one account; membership lasts 365 days, with a 30-day switching lock across both
categories, including after leaving. Only keyed email hashes are persisted. Each category ranks
teams independently by the average leaderboard score of their best five accounts, one bot per
account, padding empty slots with the new-bot score. Each standings row also reports all currently
verified team members across ladders, including those without ranked bots, as a separate Players
count; this count remains current when viewing a past month. Staff can rename or hide either kind.
A past month's affiliations stay frozen. Affiliation verification does not change combat or replay behavior. Organization display names resolve as staff override,
cached explicit website name, then domain; university names retain their local list. Discovery
prefers unambiguous top-level Schema.org `Organization.name`, then `WebSite.name`, then
`og:site_name`; titles and DNS TXT records are not naming fallbacks. Names are untrusted plain
text, at most 100 characters. A separate `organization_names` table caches successes for 30 days
and failures for one day, preserving the last usable name during an outage. Background jobs check
up to five active organization domains every five minutes, never on a standings request. Each
lookup has a five-second total deadline, three redirects maximum and a 256 KiB decoded read
limit, stopping at the end of the HTML head when present. Only public HTTPS destinations within the team's registered domain are permitted;
private/reserved DNS answers, credentials and nonstandard ports are refused at each hop. Node
pins its connection to a checked DNS answer; Workers uses public Internet fetch, with no private
network binding. Display labels never change IDs, URLs, membership, scoring or replay behavior.

League teams are separate from global verified affiliations. Each League keeps its own team
configuration, identities and memberships, bound to enrollments. Browser-only private routes at `/api/account/ladders/<id>/teams` permit actively enrolled
participants to read their league; owners and platform staff manage it without enrollment. Modes
are disabled, admin-assigned, participant choice and participant creation/joining. One account has
at most one team per league, shared by all its bots. Only active enrollments may join or be assigned;
revocation followed by reapproval does not restore the old team. Owners/staff can rename and
deactivate/reactivate teams until the League closes. Names are unique per league, with 100 teams maximum.

Active teams score the average of their best five accounts' best ranked bot scores, padding empty
places with 700; teams without ranked bots have no rank. Transfers move current scores. There is no
roster lock: the admin-assigned mode settles teams before official play, since participants can't
change teams in it while owners/staff can still place late joiners, and it can be switched back.
Leagues locked before the lock was retired read as admin-assigned until their mode is configured
again. Closure blocks all mutations and persists derived team standings before rolling data expires. Affiliations, bot
protocol, engine determinism, replay compatibility and champion inference are unchanged.

The primary navbar groups bot, affiliation and AI-builder standings under Rankings, which opens
the bot leaderboard. Category navigation retains league/snapshot selection. League teams appear
only within their league. Legacy leaderboard and affiliation/agent URLs remain valid.

An opt-in MCP endpoint (`/mcp`, Streamable HTTP) lets an AI client read its owner's handle and bots and register new bots under the same quota as the account page or an agent key. Consented `remove_bot` removes an owned bot as the account page does: one that has never played is deleted, one that has played is retired, which stops it and frees quota while preserving its name, versions and match history; repeating it is safe. Consented `restore_bot` brings a retired bot back if the account is under its cap. `list_my_ladders` reports account membership, roles and enrollment URLs, and consented `join_league` uses the same invitation, approval, password, revocation and schedule checks as browser enrollment. Tools that take `confirmed` require the client to obtain explicit owner approval and assert `confirmed: true`, or the server asks the owner itself where the client can show a question. Read-only tools return the public leaderboard, bot, match, ladder-recap and university and organization standings data of the HTTP API. Under account-actions consent, `join_affiliation` with `confirmed: true` represents the school or organization of the OAuth token's eligible sign-in address. Schema 18 records account-actions consent: existing grants keep their registration-only write scope until browser reapproval. Supabase OAuth identifies the user and client; browser signup, handle selection and `/oauth/consent` approve a separate SQLite grant. MCP requires a JWT audience bound to its canonical URL and a signed `client_id`, or one of the account's agent keys as a Bearer token. Agent keys are deprecated: they keep working, a key's MCP responses carry `Deprecation` and `Link rel="deprecation"` headers (RFC 9745) and `whoami` adds a `credential_notice`, and My Bots offers key creation only to accounts that already have a key or on a ladder without MCP. OAuth tokens cannot use the browser account API. Disconnecting a client immediately blocks its existing OAuth tokens, including after reapproval; tokens for bots it already created keep working. MCP returns new bot tokens once and never uploads or runs bot code. See [MCP.md](/docs/mcp) for setup and the tool contract. No combat messages or replay behavior change.

`GET /api` and `/llms.txt` link `/openapi.json`, an OpenAPI 3.1 contract for public HTTP
discovery/data and participant bot operations. It distinguishes account registration
credentials from bot tokens and reports any additional registration gate. Browser account
management is documented in [API.md](/docs/api); WebSocket combat uses
the protocol JSON schemas. Public pages carry build-generated introductory HTML and
structured data; bot/match templates receive escaped entity identity and canonical URLs.
Live tables remain browser API clients. Missing entity pages return 404 and `noindex`.

- A player version has an automatically assigned `label` unique within the bot (`v1`, `v2`, …), an optional short alias and optional release notes. It is registered the first time the bot queues with it, or beforehand through the API to add an alias and notes. Versions can't be edited or deleted, only retired: a retired version can't play and leaves the leaderboard.
- Every `queue` message names the version the connected bot is running.
- House opponents are official ladder competitors. Their private strategies and models are not distributed; starter bots and Random are available for offline practice.
- Every game between bots 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 is frozen code, so its rating weighs all its games equally, whenever they were played, and a win counts for more once its opponent proves strong. Each rating has a standard error (`rating_deviation`). A prior keeps a version with few games near the average version. The scale is Elo's (400 points is 10:1 odds), and the house bots average 1500, weighted by games (the trained `house-champion` and optional `house-mbot` excepted: they would drag the scale's anchor up).
- A version is rated from its own games only. The matchmaker starts a new version from its bot's current rating (allowing it 200 points either way) until its own games say otherwise.
- Player versions have server-assigned names `v1`, `v2`, … in registration order per bot. Retiring a version never reuses its number. An optional 32-character alias appears on its own line in the bot page's Versions table and alongside its number in opponent, map and heatmap version pickers when the full label fits; compact controls show only the number (plus current/retired status where applicable). The existing `notes` field holds a description of up to 2,000 characters. Schema 32 numbers existing versions in creation order (row insertion order breaks ties) and retains their old custom names as aliases. Stable internal keys keep ratings, event evidence, archived seasons, match statistics and replay inputs intact; public responses and the ladder replay viewer project the assigned names. House policies retain their release labels. Old clients may use their existing version keys as aliases; canonical numbered names take precedence when an alias collides. New HTTP clients omit `label` and use the returned name.
- A version is ranked once it has played 30 rated games. A bot's current version is the one that played a rated game most recently, not counting retired versions, so queuing an older label again rolls the leaderboard back to it. The leaderboard lists each bot at its current version among those ranked, so a new version takes over once it has its 30 games. It orders by score, highest first: the rating less twice the greater of its standard error and 25, rounded only after computing the score from full-precision values. This preserves caution for uncertain versions and stops uncertainty reduction alone from improving score below a 25-point deviation. The actual standard error, rating fit and matchmaking remain unchanged; stronger results can still raise the rating.
- A version must be there to be challenged to keep its place. It is online while it is queued or in a match on that ladder (a pause of up to a minute, between games or while its connection comes back, still counts), and the leaderboard score asks for 4 hours online in every 24. Each version keeps a bank of online time: it drains by 4 hours a day, always, and fills by an hour for each hour online, holding at most 4 hours (a day away). Once it's empty the version owes online time, at most 24 hours, and its score loses `400 × (hours owed / 8)²` points, at most 400: nothing for a day away, then 6 points at 30 hours, 25 at 36, 100 at two days, 225 at 60 hours and 400 from three days. Time online pays it back at 50 minutes an hour, so three days away clears in under 10 hours online and any absence in under 29. Games don't count, only time online: a bot that connects for one game a day owes the cap within four days, and one online 4 hours every day never owes anything. The rating and matchmaking never change. Each version keeps its own bank, so a new version's time online pays nothing for an old one. House bots are online whenever they play on that ladder. Time away is measured to the present, or to a competition's close once it has closed (an event ladder's `closes_at`, a public season's cutoff), so final standings don't keep moving. `idle_penalty` reports the points lost and `online_owed_hours` the online time owed.
- The leaderboard, Online list and bot version table display the same `leaderboard_score` calculation for a given version and ladder. Online shows the connected version, which may not have qualified yet; the bot headline uses its leaderboard version. Raw ratings remain labeled in details, historical charts and match deltas.
- The server never sees code, so a version is the player's declaration of what is running. Every match and replay records the version, so a mislabelled version only muddies that player's own stats.
- A bot can register a limited number of new versions per day (1000 by default; `quotas.versions_per_bot_per_day` in `GET /api`).

### The rolling window

Public has no seasons and never resets. Its leaderboard, ratings, records, qualification and matchmaking history count the rated games of the last 30 UTC days, including today. Ratings are fitted to those games; a game counts toward the UTC day it ended on. A version with no games in the window has no record and no rank, and its rating returns to the prior. Private ladders are independent and follow the same rules with their own totals and matches. A closed one saves its standings and results before its games leave the window. A League's owner or organizers may also reset its leaderboard, at most once a day: its standings are saved as a snapshot, then every game in its window moves to lifetime totals at once, as if each day had expired, and seeds, matchmaking history, online-time banks and the Rating and Rank charts start again. A match that started before the reset counts toward lifetime totals only.

Once a night (from 09:00 UTC) the server, not an external job:

1. Archives every finished match permanently. A match still in play waits for the next night.
2. Records each version that played yesterday's rating point, each bot's best nightly rank and score, and the night's standings in the archive.
3. On the first night of a month, saves Public's standings as they stand as the month that ended's snapshot, with a copy in the archive: a record, not a reset. It runs before the window moves on, so the month keeps all the days the window still holds. A night missed is made up later that week; after the seventh day the month has none.
4. Moves days older than the window into each bot's lifetime totals, in the transaction that removes them, and refits. A rating can move a little on this step, without the version playing.
5. Removes archived Public matches that are past the window from match lists and pages, with their public replay access. The newest match always stays. Event ladder matches stay.

`/leaderboard` opens the live standings; its picker also opens past months, and `/snapshots` lists them. `/leaderboard?view=report&snapshot=<id>` shows a month's report and opponent chart. The one from before the window (Pre-season) keeps its upsets, streaks, low-HP wins, rivalries, specialist records and damage profiles. Later months keep standings, totals and opponent records.

A bot's page shows **Lifetime**: when it first played, days active, rated games, W-L-D and best nightly rank on Public. Those totals are the games that have left the window plus the window itself. A bot that has played a match can't be deleted.

A Public match page older than the window answers "not found". Its result, replay and stats stay in the permanent archive; [Replay retention](#replay-retention) says which recordings stay readable. Snapshots contain public views, never credentials, and owner links honor current account visibility. A restart leaves interrupted matches unrecorded, on every ladder: they award nothing.

## World model

The arena is a rectangular tile grid, 21 × 21 by default (maps may range 11 to 41 per side). One fighter occupies one tile; two fighters never share a tile.

**Coordinates and directions**

![Coordinates, Chebyshev distance and corner cutting](/docs/images/grid.svg)

- Positions are `[x, y]` integers, origin `[0, 0]` at top-left, x increasing east, y increasing south.
- Eight directions: `N`, `NE`, `E`, `SE`, `S`, `SW`, `W`, `NW`. `N` is `[0, -1]`.
- Distance is Chebyshev: `max(|dx|, |dy|)`. A diagonal neighbour is distance 1.
- A diagonal step is blocked if either orthogonal tile it cuts past is a wall (no corner-cutting).

**Tile types**

| tile        | code | movement | projectiles | sight   | effect                                                |
| ----------- | ---- | -------- | ----------- | ------- | ----------------------------------------------------- |
| Floor       | `.`  | yes      | pass        | clear   | none                                                  |
| Wall        | `#`  | blocked  | stopped     | blocked | knockback into it deals wall-slam damage              |
| Out of zone | none | yes      | pass        | clear   | 5 damage per tick, rising by 5 every 20 ticks outside |

The `hello` message carries the static map as an array of strings, one per row, using the codes `.` and `#`. The zone is dynamic, so it is never written into the map: each observation reports its centre and radius instead.

**Pickups**

Maps place pickup pads on floor tiles, listed in `hello.pickups` as `{id, pos, kind}`. Each pad holds one pickup of a fixed kind. Every pad is stocked on tick 20 and restocks a fixed time after it is taken. Pads follow the map's symmetry, so neither spawn is favoured.

A fighter takes a stocked pickup by stepping onto the pad, dashing onto or through it, being pushed onto or across it by a repulsor, or standing on it when it restocks. That costs no action and no tick. A dash or push takes every stocked pad it enters, its last tile included.

| kind     | effect                           | duration | respawn   |
| -------- | -------------------------------- | -------- | --------- |
| `health` | +32 hp, capped at max            | instant  | 120 ticks |
| `power`  | weapon damage ×1.5, rounded down | 50 ticks | 200 ticks |

Power is a timed buff. Taking it while you already have it refreshes its duration and never shortens it. The current maps each have four pads on the centre column, equidistant from both spawns: two `power` pads near the centre and two `health` pads at the top and bottom edges.

**Line of sight and visibility**

- Each fighter sees tiles within a sight radius of 8 (Chebyshev) that have clear line of sight.
- Line of sight uses the same straight line as projectiles: the segment between the two tile centres is blocked by any wall whose interior it crosses, and grazing a wall's corner does not block. Sight is therefore symmetric (A sees B exactly when B sees A), and a clear line of sight means a shot along it will not hit a wall.
- Fighters and projectiles outside sight are omitted from the observation. Static tiles are always known from the map.

## Fighter state and stats

Every fighter starts with the same base stats; equipment may modify them later. The game runs at 10 ticks per second for playback, but bots only ever reason in ticks.

**Base stats**

| stat            | value   | notes                                       |
| --------------- | ------- | ------------------------------------------- |
| `max_hp`        | 130     | no passive regeneration                     |
| `move_cooldown` | 2 ticks | see Movement                                |
| `sight_radius`  | 8 tiles | see World model                             |
| `armor`         | 0       | flat damage reduction, min 1 damage per hit |

**No facing**

Fighters have no facing. You can step, dash and attack in any of the eight directions, and damage is the same from every side.

**Movement**

A step happens instantly in phase 3, then `move` goes on cooldown for 2 ticks (5 tiles a second at 10 ticks/s), in any direction. During that cooldown the fighter can still attack or dash; it just cannot step again. For a burst of speed there is the dash. There are no resources to manage: every limit is a cooldown.

Distance is Chebyshev, so a diagonal step costs the same as an orthogonal one while covering about 40% more real distance. This is deliberate: movement and attack ranges use the same metric.

**Fighter states**

![Fighter states: idle, dashing, recovering and stunned](/docs/images/fighter-states.svg)

Stepping and attacking happen from `idle` and leave the fighter `idle`. A fighter at 0 hp enters `dead` from any state.

| state        | can act? | notes                                                                            |
| ------------ | -------- | -------------------------------------------------------------------------------- |
| `idle`       | yes      | any turn                                                                         |
| `recovering` | no       | for 1 tick after a dash                                                          |
| `dashing`    | no       | only during the dash tick (observations never show it); invulnerable, see Combat |
| `stunned`    | no       | for 3 ticks after a repulsor slams you into a wall                               |
| `dead`       | no       | removed at end of tick                                                           |

Cooldowns are tracked per ability and tick down by 1 at the end of every tick.

## Observation schema

Each tick the engine sends one observation describing the world as it stands after the previous tick resolved. Unknown fields must be ignored by bots, which is how new fields are added without breaking old bots.

```json
{
  "type": "observation",
  "tick": 212,
  "self": {
    "id": 1,
    "pos": [4, 7],
    "hp": 62,
    "max_hp": 130,
    "state": "idle",
    "state_ticks_left": 0,
    "slow_ticks_left": 0,
    "buffs": { "power": 34 },
    "cooldowns": { "move": 1, "dash": 0, "ranged": 0, "frostburst": 0, "repulsor": 0 },
    "budget_ms_left": 118400
  },
  "enemies": [
    {
      "id": 2,
      "pos": [6, 7],
      "hp": 80,
      "dash_cooldown": 0,
      "state": "idle",
      "state_ticks_left": 0,
      "slow_ticks_left": 0,
      "buffs": {}
    }
  ],
  "projectiles": [
    {
      "id": 17,
      "pos": [8, 8],
      "exact_pos": [8000, 8000],
      "origin": [10, 9],
      "target": [2, 5],
      "speed": 2,
      "owner": 2,
      "damage": 12,
      "attack": "ranged",
      "bounces_left": 1
    }
  ],
  "areas": [
    {
      "id": 15,
      "owner": 2,
      "attack": "frostburst",
      "pos": [7, 3],
      "damage": 14,
      "radius": 1,
      "slow": 2,
      "ticks_left": 4,
      "tiles": [
        [6, 2],
        [7, 2],
        [8, 2],
        [6, 3],
        [7, 3],
        [8, 3],
        [6, 4],
        [7, 4],
        [8, 4]
      ]
    }
  ],
  "moves": [
    { "dir": "N", "tile": [4, 6] },
    { "dir": "E", "tile": [5, 7] }
  ],
  "dashes": [
    { "dir": "N", "tile": [4, 4], "distance": 3 },
    { "dir": "E", "tile": [6, 7], "distance": 1 }
  ],
  "pickups": [
    { "id": 3, "pos": [10, 8], "kind": "power", "ready_in": 0 },
    { "id": 1, "pos": [10, 2], "kind": "health", "ready_in": 42 }
  ],
  "zone": { "center": [10, 10], "radius": 9, "next_radius": 7, "shrinks_in": 18 },
  "danger": [
    {
      "tile": [6, 7],
      "tick": 213,
      "attack": "ranged",
      "owner": 2,
      "damage": 12,
      "source": "projectile"
    }
  ],
  "events": [
    { "kind": "attack", "fighter": 2, "attack": "ranged", "target": [4, 7] },
    { "kind": "hit", "attacker": 2, "target": 1, "attack": "ranged", "damage": 12 }
  ]
}
```

**Field reference**

| field                                               | type     | meaning                                                                                                                                                                                                                                                                                                                              |
| --------------------------------------------------- | -------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| `tick`                                              | int      | current tick; the turn reply must echo it                                                                                                                                                                                                                                                                                            |
| `self.pos`                                          | `[x, y]` | own tile                                                                                                                                                                                                                                                                                                                             |
| `self.state`                                        | string   | one of the fighter states                                                                                                                                                                                                                                                                                                            |
| `self.state_ticks_left`                             | int      | ticks until the current state ends, counting the tick you reply to (0 when idle)                                                                                                                                                                                                                                                     |
| `self.slow_ticks_left`, `enemies[].slow_ticks_left` | int      | ticks until the opponent frostburst area that fighter stands in explodes, counting the tick you reply to; 0 = not slowed                                                                                                                                                                                                             |
| `self.cooldowns`                                    | map      | ticks until each ability is usable: `move`, `dash`, every attack and `shout`; 0 = ready                                                                                                                                                                                                                                              |
| `self.budget_ms_left`                               | int      | response time left in the match budget, in ms                                                                                                                                                                                                                                                                                        |
| `self.buffs`, `enemies[].buffs`                     | map      | active pickup buffs → ticks left, counting the tick being replied to                                                                                                                                                                                                                                                                 |
| `moves[]`                                           | list     | every step you could start this tick, as `{dir, tile}`: move off cooldown, not into a wall, past a wall corner or into a fighter. Empty if your move is on cooldown or you can't act. Legal now, not guaranteed: two fighters stepping onto one tile both stay put                                                                   |
| `dashes[]`                                          | list     | every dash you could start this tick, as `{dir, tile, distance}`: `tile` is where it lands and `distance` is 3, or less when a wall, the map edge or a fighter stops it early. A dash that would not move is left out. Empty if your dash is on cooldown or you can't act                                                            |
| `pickups[]`                                         | list     | pads in sight: `ready_in` is 0 while stocked, otherwise ticks until it restocks                                                                                                                                                                                                                                                      |
| `enemies[]`                                         | list     | visible opponents only                                                                                                                                                                                                                                                                                                               |
| `enemies[].dash_cooldown`                           | int      | ticks until that opponent can dash again; 0 = ready                                                                                                                                                                                                                                                                                  |
| `projectiles[]`                                     | list     | visible projectiles, including your own: `pos` is the tile it is in, `exact_pos` its position in thousandths of a tile, and it flies the straight line from the centre of `origin` through the centre of `target`. `bounces_left` is the wall bounces it has left; after a bounce, `origin` and `target` describe the reflected line |
| `areas[]`                                           | list     | visible frostburst areas, including your own: `tiles` is the exact footprint (walls excluded and shielding), `slow` the extra move cooldown for opponents standing in it, `ticks_left` 1 = it explodes during the tick you reply to                                                                                                  |
| `zone`                                              | object   | safe circle (Chebyshev radius) and the next shrink                                                                                                                                                                                                                                                                                   |
| `danger[]`                                          | list     | every tile each visible opponent projectile and frostburst area will hit, with the `tick` it is hit on, in tick order; see Danger tiles                                                                                                                                                                                              |
| `events[]`                                          | list     | what happened to or near you last tick, in resolution order. A `hit` from a shot that had bounced off a wall carries `"ricochet": true`. A `shout` is heard wherever the shouter is                                                                                                                                                  |

Enemy hp and dash cooldown are exact, so you always know whether an opponent can still escape. Their attack cooldowns are hidden, but every attack produces an `attack` event, so you can count from the last one you saw.

**Danger tiles**

`danger` does the attack geometry for you: each entry is one tile an opponent attack will hit on one tick, `{tile, tick, attack, owner, damage, source}`. It is computed with the engine's own flight code, so it matches what the engine will do.

- `tick` equal to the observation's `tick` means the hit resolves during the tick you are replying to, after movement: don't end this tick's move there. A dash tick is invulnerable, so only its landing tile's later entries matter.
- `source` is `projectile` or `area`. Everything listed is already in the world, so it is certain. Attacks fire the tick they are sent, so an attack sent this tick isn't listed until the next observation, and one that lands the tick it is sent (a shot at 1–2 tiles, a repulsor) is never listed.
- `damage` is the base damage, before the attacker's power buff.
- Only attacks you can see are listed, and paths stop at walls but ignore fighters, so nothing hidden in the fog leaks. A tile can appear on two consecutive ticks, because each tick's sweep starts in the tile the last one ended in.

Frame data for every attack, and the cheapest counter to each, are at `/docs/frame-data` (generated from the rules table; checked in as [FRAME_DATA.md](/docs/frame-data)).

## Turn schema

A bot sends exactly one turn per tick. A turn carries `tick` and up to four optional parts: `move` or `dash` (a direction), `attack` and `shout`. A turn with none of them is idle. Anything refused is dropped and reported in the next observation's `events` as `rejected` with the `part` and a reason.

```json
{"tick": 211}
{"tick": 212, "attack": {"name": "ranged", "target": [9, 10]}}
{"tick": 213, "move": "NW", "attack": {"name": "ranged", "target": [9, 10]}}
{"tick": 214, "dash": "E"}
{"tick": 215, "move": "S", "shout": "Over here!"}
```

A turn has two phases: movement, then attack. The movement phase is a `move` (a step), a `dash` or neither; the attack fires after it, from the tile the fighter ends on. Each part is checked separately: if one is refused (a blocked step, an attack on cooldown) the other still happens, and a `rejected` event names the refused part. An attack's target is judged from the tile you end on: a frostburst's range and sight, and that the target isn't your own tile.

| field    | value                                                                       | effect                                                                                                                                                                                                                                                |
| -------- | --------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `move`   | a direction: `N`, `NE`, `E`, `SE`, `S`, `SW`, `W` or `NW`                   | step one tile; move cooldown 2                                                                                                                                                                                                                        |
| `dash`   | a direction                                                                 | move exactly 3 tiles, stopping early at obstacles; invulnerable that tick; not together with `move`                                                                                                                                                   |
| `attack` | `{name, target}`: `name` is a key of `hello.rules.attacks`, `target` a tile | fire at `target`, any tile but your own, after movement; the repulsor takes no target                                                                                                                                                                 |
| `shout`  | text, at most 40 characters (`hello.rules.shout.max_length`)                | said to everyone: every fighter's next observation carries a `shout` event, in sight or not, and the replay shows it as a speech bubble. Cooldown 10 ticks (`hello.rules.shout.cooldown`). Takes no action: it goes with any other part, in any state |

That's the whole list. There is no `aim` or windup (attacks fire the tick they are sent), no facing and no block.

**Validation rules**

- The ability must be off cooldown, otherwise `rejected: not_ready`. This includes `move` while its cooldown is running.
- Each attack has its own cooldown and no ammo. Firing one leaves the others ready; a turn carries at most one attack.
- Any part sent while recovering from a dash or stunned is rejected as `invalid_state` (the whole turn, part `turn`).
- An aimed attack needs a `target` (otherwise `missing_target`): integers within ±1000 on each axis, and not the tile you end your movement on (otherwise `bad_target`). A standard shot's target may be off the map; the shot flies on past it, so a distant target just sets a finer angle.
- A frostburst's target must also be within range 7 (`out_of_range`), not a wall (`blocked`) and in sight (`not_visible`), all judged from the tile you end your movement on.
- `move` into a wall, off the map or past a wall corner is rejected as `blocked`; the fighter stays put. A dash is never refused for that: it stops early, possibly after 0 tiles.
- A `shout` is cleaned by the server before the engine sees it (see Shouts under Implementation rulings). After cleaning it must be 1 to 40 characters, not all spaces (otherwise `bad_text`), and off its cooldown (`not_ready`). It is never refused as `invalid_state`.

## Combat definitions

All combat numbers live in one rules table, sent to bots in `hello.rules`. The engine reads this table at match start, so balance changes and later weapons are data edits. The table carries its own `version` (a running ladder reports it with the engine's in `GET /api` `versions`); [CHANGELOG.md](/docs/changelog) records how it got here. The ladder shares its bundled history at `/changelog`, with permanent release anchors (`#v0.29.3`), running versions and separate Unreleased notes. Agents read `/docs/changelog` (Markdown) or `/api/changelog` (`versions` and `markdown`); `/api`, `/docs` and `/llms.txt` link the history.

Timing, counterplay and the observation fields for each attack are in [RANGED_ATTACKS.md](/docs/ranged-attacks). Each attack's cooldown is independent of the others.

**Attack table**

| attack       | damage | range (tiles) | area                                                                                                                        | cooldown (ticks) | notes                                                                                                                                 |
| ------------ | ------ | ------------- | --------------------------------------------------------------------------------------------------------------------------- | ---------------- | ------------------------------------------------------------------------------------------------------------------------------------- |
| `frostburst` | 14     | 7             | radius-1 square after 6-tick fuse                                                                                           | 14               | instant spell cast on a visible tile; affects opponents only; slows moves from inside the square until it goes off (move cooldown +2) |
| `ranged`     | 12     | unlimited     | projectile along the straight line through the target tile's centre, at any angle, speed 2 tiles/tick; one flat-wall bounce | 6                | shortest cooldown; banks around cover                                                                                                 |
| `repulsor`   | 5      | 1             | the eight tiles around the attacker; no aim                                                                                 | 12               | shoves each opponent 3 tiles; wall slam: +10 damage, stunned 3 ticks                                                                  |

`frostburst` is an instant spell: it is cast on a visible non-wall tile within range and its area exists the tick it is sent, with no flight time. Its radius-1 square is shielded by walls. From the next tick until it explodes, each opponent standing in the square has `slow` (2) added to the move cooldown of any step it takes, judged by the tile the step starts on. Dash and attacks are unaffected, nothing lingers after the blast, and where squares overlap the largest slow counts. On the fuse's last tick, after movement, every opponent still in the square takes the full damage, whichever of the nine tiles it stands on. The shooter and teammates are immune to all weapon damage and status effects. See [ranged attack rules](/docs/ranged-attacks) for timing and counterplay.

A standard shot (`ranged`) reflects from the centre of the last open tile before its first flat wall (a map edge counts as a wall), then continues along the reflected line on the next tick. A corner or second wall ends it. The `repulsor` is a point-blank force burst. It has no aim: it hits every opponent on the eight tiles around the attacker, measured after movement (any `target` sent is ignored, and its `attack` event reports the attacker's own tile), and shoves each one `push` tiles straight away from the attacker, one tile at a time. A wall, or a wall corner the shove can't cut past, stops it with a slam: `knockback.wall_slam_damage` more damage and `stunned` for `knockback.wall_slam_stun` ticks. Another fighter in the way stops it with a collision that deals `fighter_collision_damage` to both. The zone hurts at the end of the tick as usual. A dashing fighter is neither hit nor pushed. Both attacks follow the normal no-friendly-fire rules.

**Hits**

- Attacks can be aimed in any direction.
- A ranged attack uses its target tile to set a direction from the centre of the attacker's tile after movement. That direction locks before repulsors resolve: knockback shifts the launch point but preserves the direction, even if the attacker lands on its original target tile. The projectile flies along that true straight line at any angle, with no range limit: it ends on the first wall or fighter after its one flat-wall bounce (so on its second wall at the latest). It hits the first wall or fighter whose tile the line passes through; grazing a corner or running exactly along a tile edge does not count. Speed and range are measured along the line's major axis (the same Chebyshev metric as movement), and positions are tracked exactly in thousandths of a tile.
- Attacks fire the tick they are sent, after movement. A target that stepped away that tick escapes; one that stood still is hit. There is no telegraph: at 1–2 tiles a shot lands the tick it is sent, so the skill up close is predicting whether your opponent will move. Further out the projectile is visible in flight, so the skill is dodging it.
- Firing has no recovery: you can act on the next tick, and a move or dash can carry an attack in the same tick.
- Both fighters can fire on the same tick, and both attacks land.
- Firing is limited by each attack's own cooldown, not ammunition. With one attack per turn, a fighter can fire a different weapon on consecutive ticks, for example a repulsor slam and then a shot at the stunned target.

**Dash**

| property     | value                                                              |
| ------------ | ------------------------------------------------------------------ |
| distance     | exactly 3 tiles in `dir`; fewer only when stopped early            |
| cooldown     | 12 ticks                                                           |
| invulnerable | the dash tick: projectiles pass through, blasts and repulsors miss |
| recovery     | 1 tick after landing                                               |

A dash stops early at the first wall, map edge or fighter. It takes every stocked pickup pad it enters on the way, not only the one it lands on.

Because the distance is fixed, the landing tile is predictable: opponents can read and punish it.

**Damage formula**

```text
damage = max(1, base − armor)
```

The same from every side, then scaled by the attacker's power buff (see Pickups). There is no block or guard: the defences are moving off the line, dashing (invulnerable for its tick) and cover. Only the repulsor displaces or stuns.

## Tick resolution order

Every tick resolves in the phases below. All turns are validated against the state at the start of the tick, and within a phase everything happens simultaneously.

![The eight phases of a tick](/docs/images/tick-phases.svg)

Phases run top to bottom; the table gives the detail for each.

| phase                      | what happens                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                   |
| -------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| 1. Collect and validate    | read each bot's turn; invalid parts are dropped, and a turn past the deadline or missing becomes `idle`; each valid shout starts its cooldown and emits a `shout` event                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                        |
| 2. Dashes                  | anyone standing on a stocked pad takes it (a pad that restocked under them); then all dashers move at once, one tile at a time, and are invulnerable until phase 8; a dasher takes each stocked pad it enters (see Pickups)                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                    |
| 3. Movement                | all `move`s resolve at once (see Conflict rules); each mover's move cooldown starts (raised by an opponent's frostburst area if the mover starts the step inside its square)                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                   |
| 4. Pickups                 | a fighter on a stocked pad takes it; the effect applies immediately, so power taken now counts in this tick's phase 5                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                          |
| 5. Attacks and projectiles | every accepted attack sent this tick fires: its cooldown starts, and an `attack` event is emitted. Aimed targets are validated from positions after movement, and direct shots lock their direction toward the requested aim tile. Repulsors resolve first, from positions after movement: every ring is fixed, then each hit is dealt and each push applied in fighter-id order; a pushed fighter takes each stocked pad it is pushed onto, and a buff taken that way starts once every repulsor has landed, so it never boosts a repulsor fired this tick. Then frostbursts create their marked area on the requested tile with a 6-tick fuse, and direct shots spawn a projectile on the attacker's tile (where any push left it), preserving the direction locked before knockback. Every projectile then advances its speed along that line (a new one included), hitting the first wall or non-dashing fighter whose tile the segment it covers this tick passes through, including the tile it started the tick in. Last, every area whose fuse ends this tick explodes, hitting each non-dashing opponent on its tiles |
| 6. Zone                    | out-of-zone damage applies; the zone shrinks if due                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                            |
| 7. Deaths                  | fighters at 0 hp are marked `dead` and removed                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                 |
| 8. Timers                  | cooldowns, state timers and stun tick down; invulnerability ends; expired or spent buffs end; due pads restock; win check; observations sent                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                   |

## Conflict and edge-case rules

When simultaneous turns collide, nobody gets priority by bot order; the rules below decide, and ties favour neither side.

| situation                                                  | rule                                                                                                             |
| ---------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------- |
| Two fighters move into the same tile                       | neither moves                                                                                                    |
| Fighter moves into a tile another fighter is leaving       | allowed, as long as the leaver actually leaves this tick                                                         |
| Two fighters swap tiles                                    | neither moves                                                                                                    |
| Chain of moves where the front one is blocked              | the whole chain stays put                                                                                        |
| Two dashes cross or end on the same tile                   | each stops one tile short of the collision point                                                                 |
| Dash ends on a tile another fighter moves into             | the dasher takes the tile; the mover stays put                                                                   |
| Both fighters attack each other on the same tick           | both attacks fire and both land; two repulsors push both fighters apart                                          |
| Projectile and fighter pass through each other in one tick | a hit: the projectile's segment for the tick includes the tile it started in, so stepping into its path is a hit |
| Two projectiles meet                                       | both pass through each other                                                                                     |
| All remaining fighters die the same tick                   | draw                                                                                                             |

## Match structure

A match is a 1v1 lasting at most 600 ticks (60 seconds of playback). The last fighter standing wins; otherwise tiebreakers decide.

**Setup**

- Maps are mirror-symmetric (point or axis symmetry), so neither spawn is favoured.
- Fighters spawn on the map's two spawn points, with full hp and all cooldowns at 0.
- Spawn assignment is decided by the match seed.

**Shrinking zone**

![The zone's schedule on pillars-21](/docs/images/zone.svg)

| tick                 | zone radius (Chebyshev, from map centre)                                    |
| -------------------- | --------------------------------------------------------------------------- |
| 0–199                | whole map (the smallest radius that covers it: 10 on 21×21)                 |
| 200                  | half map width, rounded up (11 on 21×21), but never more than the whole map |
| every 60 ticks after | shrinks by 2                                                                |
| minimum              | 1                                                                           |

On the 21×21 maps the tick-200 step changes nothing, so the first shrink that moves the zone is at tick 260, to radius 9, then 7, 5, 3 and 1 at ticks 320, 380, 440 and 500. `/docs/rules` on the ladder lists the schedule for each map. The next shrink is announced 20 ticks ahead in `zone.shrinks_in`. Out-of-zone damage starts at 5 per tick and rises by 5 for every 20 consecutive ticks outside.

**End conditions**

1. Only one fighter alive: that fighter wins.
2. No fighter alive: draw.
3. A bot is disqualified or forfeits: its opponent wins.
4. Tick 600 reached with more than one alive: higher remaining hp as a percentage of max wins; if equal, more total damage dealt wins; if still equal, draw.

## Replays and determinism

The engine is a pure function of (rules, map, seed, turns per tick). The server never has players' code, so a replay records every turn the server resolved, including the `idle`s from late or missing replies, and re-simulates the match exactly from those.

**Determinism requirements**

- Integer arithmetic only in the engine; no floating point in game logic.
- All randomness comes from one seeded PRNG (e.g. PCG32) owned by the engine, drawn in a fixed order.
- Iteration over fighters, projectiles and events is always in ascending id order.
- A replay records the engine version, the full rules table with its hash, and the map. A runtime refuses a different engine version or a rules hash that does not match.
- New `MatchCore` recordings also carry `release` and `replay_format: 1`. Hosts select that release's immutable simulator before replaying. Files with neither field use a compatible installed engine, or a vetted legacy-engine runtime (initially 0.21.0 from pinned 0.29.0 source) with fixed source/adapter identity and artifact checksums. Incomplete identity, an unknown format or an unsupported legacy engine is rejected. Headers and actions are not relabeled or rewritten; each selected engine retains its own rules/hash checks.

**Replay file** (JSON Lines, gzip-compressed)

```json
{"type": "header", "engine": "0.21.0", "rules_hash": "a41f…", "map": "pillars-21", "seed": 918273, "bots": [{"id": 1, "name": "alpha", "version": "v14"}, {"id": 2, "name": "brute", "version": "v3"}], "rules": {…}, "map_data": {…}}
{"type": "tick", "tick": 0, "turns": {"1": {"move": "E", "attack": {"name": "ranged", "target": [9, 4]}, "ms": 42}, "2": {"reason": "timeout", "ms": 1000}}, "hash": "…"}
{"type": "result", "winner": 1, "reason": "last_standing", "final_tick": 341}
```

Each recorded turn may carry `reason` (why the server played it as idle, as a code) and `ms` (how long the reply took, as the server timed it; absent where nothing was timed, as in the simulator). Neither changes how the turn plays. Match stats are computed from the replay, reply times included, and saved unchanged as measured before the result is recorded; they are never reconstructed later. Archived stats that are temporarily unavailable return a retryable 503. In HTTP and MCP bulk stats reads, response order and fields don't depend on which record loads first.

`server_idles` counts recorded turns by reason for each fighter. `disconnects` counts contiguous
runs of recorded `disconnected` turns, not socket-close events. A drop with no such recorded
turn is not counted; multiple drops without an intervening other turn form one run. The
unresolved tick ending in a forfeit or disqualification is not another recorded combat tick.

Replay verification checks tick hashes and combat results. For a server-decided forfeit or
disqualification, combat must still be running and `final_tick` must be the next unresolved tick.
The winner must be a living fighter in that match; only a forfeit can have no winner (both bots
left). Verification trusts the server's reason for that ending, since socket and deadline
decisions cannot be reconstructed from combat inputs.

A replay can optionally include full per-tick state snapshots for tools that do not want to re-simulate.

Replay runtime API 1 supplies simulation, verification, statistics, observations and the gameplay
helpers used by rendering and audio. Its frame/event and helper contracts must stay compatible;
a breaking change needs an adapter or a new API and corresponding viewer support. Hosts select
runtime code only from a configured download origin and validate its release, engine, API and
format. Archived modules are checked against `manifest.json` before import. Missing, incompatible
or corrupt artifacts fail visibly; the current engine is never substituted for another release.
The viewer and playlist verify tick hashes and completed results. The CLI's `--from/--swap`
continues matches only on its own release, so it never passes an old runtime's state to a new engine.
Each published release retains its manifest and `replay-fixture.jsonl` beside the simulator;
publication and deployment verify these artifacts. No old replay migration is required.

**Local runner parity**

- The local runner is the same engine library as the server, same version and rules table.
- `run` hosts a local server speaking the same WebSocket protocol and plays two bots that connect to it, so bot code runs unchanged locally and on the ladder; `replay <file>` re-simulates any match and must reproduce the recorded result.
- `replay --from <tick> --swap <bot>` replays a ladder match up to a tick, then hands one side to a local bot, so agents can test a fix against the exact situation they lost.
- Each bot sees a per-player view: a replay can emit the observations one fighter received, including fog of war.

**Simulator**

- Offline `VectorBatch` and Python fast environments offer disabled-by-default sampled phase profiling and aggregate worker telemetry. Clocks and counters stay at the simulator boundary, outside engine rules. Diagnostics do not change actions, observations, rewards, replays or the bot protocol. Clock limits, sample counts, reset attribution and worker timing semantics are in [the simulator guide](/docs/simulator#profile-offline-training).

- The ladder serves its own match code as a simulator, built from the release it runs: an ES module (`/download/arena-sim.mjs`), the same as a plain script (`/download/arena-sim.js`), and a Python package with Gymnasium and PettingZoo environments that runs it in embedded V8. `GET /api` lists them under `simulator`.
- It is the server's match code, not a copy: the server runs every match on the same core (hello, observations, how each reply counts, disqualification, replay), and a simulated game sends a bot the same messages a ladder match would. House bots play their real code in-process.
- It has no clock: `budget_ms_left` stays at the match budget and nothing times out unless the caller sends no reply.
- Rules change only in a release, so a simulator is current while its `RELEASE` and rules hash match the ladder's `GET /api` `versions.release` and `versions.rules_hash`.

## Implementation rulings

The reference engine settles the points below, which the sections above leave open. Each ruling has a test in the engine repo; where a ruling and an earlier section disagree, the ruling reflects what the engine does.

**Timing and states**

| topic              | ruling                                                                                                                                                                                                                                                                     |
| ------------------ | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `state_ticks_left` | Counts tick resolutions including the tick being replied to. 1 = the state ends this tick.                                                                                                                                                                                 |
| Fire on send       | An attack fires in phase 5 of the tick it is sent. There is no windup, `aim` or `cancel`. A move or dash can carry an attack in the same tick. Any action while recovering from a dash, or stunned, is rejected as `invalid_state`.                                        |
| Cooldown start     | Starts on the tick the move, dash or attack is made and ticks down at the end of that tick too, so cooldown c means usable again c ticks later. An attack's cooldown starts on the tick it is sent and covers that attack only. A dash's cooldown starts on the dash tick. |
| Dash               | Invulnerable during the dash tick; the next observation shows `recovering` with 1 tick left. A dash blocked immediately moves 0 tiles but still starts its cooldown.                                                                                                       |

**Movement**

| topic        | ruling                                                                                                                                                                                                                                                              |
| ------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| Failed moves | A move that loses a conflict still starts its move cooldown.                                                                                                                                                                                                        |
| Removed      | There is no `block`, `cancel` or `aim`, no `run` flag, no windup, no facing and no stamina. A turn with any field other than `tick`, `move`, `dash`, `attack` and `shout` fails the message schema, which counts as a protocol failure (see Protocol and failures). |

**Combat**

| topic                  | ruling                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                   |
| ---------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| Knockback and stun     | Only the repulsor. A push moves tile by tile and stops at a wall (slam and stun), another fighter (collision). The pushed fighter takes each stocked pad it is pushed onto as it gets there, so a heal on the way counts before a slam at the end; a power buff taken on the way starts after this tick's repulsors, so it boosts the fighter's shots that tick but not its repulsor; a fighter the hit already brought to 0 hp takes nothing. A stun that lands while recovering lasts until the later of the two ends. |
| Damage credit          | Damage to opponents credits the attacker with the hp actually removed; this is the timeout tiebreak's `damage_dealt`.                                                                                                                                                                                                                                                                                                                                                                                                    |
| Projectiles            | Pass through their owner and teammates. Blasts and slows affect opponents only. Stepping into an opposing projectile's path is a hit, because each tick's segment includes the tile the projectile started in. A fighter dashing that tick is passed through.                                                                                                                                                                                                                                                            |
| Shot aim and knockback | Direct shots lock their direction toward the requested aim tile after movement, before repulsors resolve. Knockback shifts the launch point but preserves that direction, even if the shooter lands on the original aim tile; the shot fires and starts its normal cooldown. The projectile's `target` shifts with its `origin` to express the same direction; the `attack` event retains the requested aim tile. Frostburst still casts on its requested tile.                                                          |

**Pickups**

| topic         | ruling                                                                                                                                                                                                                                                                                                                                                                                                 |
| ------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| Collection    | A step takes the pad it ends on, after all movement, in phase 4. A dash takes each stocked pad as it enters that tile, in phase 2, landing tile included. A repulsor push does the same for its victim in phase 5, so power taken that way boosts damage the victim deals later that tick. A pad that restocks under a fighter is taken as the next tick begins, whether they then stay, step or dash. |
| Two claimants | Dashes advance one tile at a time in lockstep, so of two dashes crossing one pad, the one that enters it first takes it. Two dashes can't enter one tile on the same step (both stop one tile short), and two fighters never share a tile, so a pad never has two claimants. Dashes resolve before steps: stepping onto a pad that a dash crossed this tick finds it taken.                            |
| Restock       | A pad restocks at the end of the tick before its respawn tick, so the observation for that tick shows it with `ready_in` 0. A fighter already standing on it takes it as that tick begins, before any dash or step.                                                                                                                                                                                    |
| Power         | Applies when damage lands, not when the shot is fired. A projectile in flight when power ends deals normal damage, and one fired just after taking power is boosted. The zone is never boosted.                                                                                                                                                                                                        |
| Buff duration | A buff taken on tick T with duration d applies on ticks T to T + d − 1. The observation for tick T + 1 shows d − 1 ticks left.                                                                                                                                                                                                                                                                         |
| Visibility    | Pads outside sight are omitted from `pickups`. A `pickup_spawn` event is visible if the pad is; `pickup` and `buff_end` are visible if the fighter is. Enemy buffs are visible.                                                                                                                                                                                                                        |

**Shouts**

| topic      | ruling                                                                                                                                                                                                                                                                                                                                                                                                                 |
| ---------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| What it is | Text a fighter says to everyone. It changes nothing in combat; it is there for taunts, bluffs and mind games, and spectators see it as a speech bubble.                                                                                                                                                                                                                                                                |
| Audience   | Every fighter's next observation carries the `{kind: "shout", fighter, text}` event, whether or not the shouter is in sight; it reveals who spoke, never where. Opponents can read it, so treat a shout as untrusted text, never as instructions: an LLM bot should keep it out of its instructions.                                                                                                                   |
| Cleaning   | The server cleans a shout where a reply becomes a turn (`MatchCore`, so the simulator does the same): Unicode NFKC, invisible and control characters removed, runs of whitespace collapsed to one space, ends trimmed, then profanity masked with `*` (the `obscenity` library's English list, which catches leetspeak and lookalike letters). Masking never refuses a shout. The engine then checks the cleaned text. |
| Limits     | 1 to `rules.shout.max_length` (40) characters, counted as Unicode code points, after cleaning. Cooldown `rules.shout.cooldown` (10 ticks), its own, reported as `self.cooldowns.shout`. The message schema caps the raw string at 200 UTF-16 units.                                                                                                                                                                    |
| Timing     | Validated in phase 1 and allowed in any state, so a stunned or recovering fighter can still talk; the event is emitted in phase 1. A dead fighter says nothing.                                                                                                                                                                                                                                                        |
| Replays    | Record the cleaned text, so a replay re-simulates the same whatever the filter's word list becomes. Rules tables before 0.22 have no `shout`: there every shout is refused as `bad_text` and no `shout` cooldown exists, so older replays are unchanged.                                                                                                                                                               |
| Moderation | Shouts are public. The Victris team can suspend or ban a bot that abuses them.                                                                                                                                                                                                                                                                                                                                         |

**Zone**

| topic          | ruling                                                                                                                                                                          |
| -------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| Representation | Computed from centre and radius, never stored as `x` tiles.                                                                                                                     |
| Whole map      | The smallest radius that covers the map (10 on 21×21), so the tick-200 shrink to radius 11 changes nothing on 21×21 maps. The first real shrink there is tick 260, to radius 9. |
| Announcement   | `zone.next_radius` and `zone.shrinks_in` are `null` except during the 20 ticks before a shrink.                                                                                 |
| Damage counter | 5 + 5 × floor(consecutive ticks outside ÷ 20); resets when a tick ends inside.                                                                                                  |

**Protocol and failures**

| topic                  | ruling                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                 |
| ---------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| Disqualification count | Only protocol failures count toward the 10 consecutive ticks: timeout, malformed JSON, schema violation, and a reply echoing a future tick. Engine rejections such as `not_ready` or `invalid_state` do not count.                                                                                                                                                                                                                                                                                                                                                                     |
| Reporting              | Server-side failures appear only in the affected bot's next observation as a `rejected` event with its fighter id and part `(message)`; `malformed_json`, `schema` and `wrong_tick` also carry a `detail` saying what was wrong (for example which field failed the schema). A disconnect is recorded as `disconnected` in resolved replay ticks, with no live event.                                                                                                                                                                                                                  |
| Budget exhausted       | Remaining ticks are `idle`, observations keep coming, and it does not count as a failure.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                              |
| Disconnects            | While a bot is away, ticks continue with a wait of `min(tick_ms, 1000)` ms for its disconnected turn; a disconnect settling a pending reply can resolve that tick sooner. Disconnected turns reset protocol failures and do not charge response time. Grace starts at server detection; combat can end during it. If both bots forfeit together, the match is a draw.                                                                                                                                                                                                                  |
| Rate limits            | By default, more than 5 messages in one tick closes the connection; outside a match the cap is 50 messages per second. Admins may change both operational caps; the per-tick cap is captured at match start.                                                                                                                                                                                                                                                                                                                                                                           |
| Reject reasons         | Rejection reasons are specific and enumerable. Malformed parts get `bad_dir`, `conflicting_moves`, `missing_target`, `bad_target`, `unknown_attack` or `bad_text`; the wrong moment gets `invalid_state`; impossible parts get `not_ready`, `out_of_range`, `not_visible` or `blocked`. Server-side failures are `timeout`, `malformed_json`, `schema`, `wrong_tick` or `budget_exhausted`. There is no catch-all `invalid`. A turn with both `move` and `dash` fails the message schema on the server; `conflicting_moves` is what the engine reports when it is handed one directly. |
| Replays                | Replay headers embed the full rules table and map, so a replay file is self-contained, and every recorded tick carries a state hash, so a replay reports the exact tick where it diverges.                                                                                                                                                                                                                                                                                                                                                                                             |

The public match and replay stats explain non-combat endings and summarize disconnects and idle turns per fighter. Bot Health labels disconnects and disqualifications separately. Styled information tooltips define idle turns, reply timing and the per-version sample (the selected ladder’s latest games, up to 500), and explain non-combat endings in the match and replay stats. They support hover, keyboard focus and tap, and dismiss with Escape or an outside tap.

### Subscriptions

Playing, building bots, the public ladder, rankings, basic match results and every bot colour are
free. Payment never changes combat, rating, matchmaking or official scoring. Prices are on
[/pricing](https://victrisarena.com/pricing).

| Plan            | Who it covers                    | What it adds                                                                                                                |
| --------------- | -------------------------------- | --------------------------------------------------------------------------------------------------------------------------- |
| Free            | Every account                    | Replays and stats for each bot's newest 200 public games                                                                    |
| Arena+          | One account, everywhere          | Animated personas for your bots; replays and stats for each bot's newest 1,000 public games; history search for your agents |
| Standard League | The League's members, in it only | A private League: standings, complete League replay history, invitations, schedules and League teams. Members join free     |
| Premium League  | The League's members, in it only | Standard, plus Arena+ benefits inside that League, organizers and reporters, reports and branding                           |

> [!NOTE]
> Premium membership is not Arena+. It unlocks personas only inside its League and gives no
> public replay history. Arena+ never opens a private League.

#### Arena+

- **Personas.** A custom persona needs Arena+ (or Premium inside that League). Without it, an avatar
  change returns `arena_plus_required` and saves nothing. Clearing a persona and choosing colours stay
  free, and anyone can try a persona on without saving it.
  `GET /api/account/avatar-access?ladder_id=<id>` reports `state`, `covered` and when coverage ends.
- **Deeper history.** Recordings in either bot's newest 1,000 public games, as in
  [Replay retention](#replay-retention).
- **History search.** Agents search public history with `GET /api/archive/public/history?bot=<stable-id>`
  and an account agent key. Bot tokens and MCP OAuth tokens can't read it. There is no browser
  search page; the replay viewer and match pages play the results.
- **Buying and managing.** Buy it from **Arena+** in the account menu (`/account#arena-plus`), which
  appears when Arena+ is on sale to you or you have a purchase or coverage to explain. Coverage shows
  once payment is confirmed; the return from Checkout proves nothing on its own. A failed renewal
  keeps coverage for 72 hours past the paid-through date, and a cancellation ends it at the end of
  the period. When coverage ends, saved choices and appearances already recorded in matches and
  standings are kept.

Bot, agent and MCP credentials can't buy anything or change browser-account settings. The account
and billing endpoints are in [browser billing management](/docs/api#browser-billing-management).

#### Premium Leagues

- **Organizers and reporters.** Up to 10 per League, invited by handle; a role does nothing until its
  account accepts. Organizers read the League, edit its settings, password and image, and manage
  invitations, League teams and public snapshots. Reporters only read. Neither can activate or
  deactivate the League, open billing, or see or change delegates. Roles pause when Premium ends and
  resume when it returns. See [Premium organizers and reporters](/docs/api#premium-organizers-and-reporters).
- **League page.** Every League has a page at `/league/<id>` with its description, artwork, schedule,
  how to join and an About section (Markdown, up to 5,000 characters) its owner and organizers write
  there. It reads like the League: a private League's page is for its members, owner and delegates.
  Standings stay on the leaderboard, which links to the page and carries no branding.
- **Branding.** A brand colour, a headline and a welcome message on the League's card and page, shown while Premium is current or
  after the League has ended; a running League without Premium hides it. Text is black or white,
  whichever gives at least 4.5:1 contrast. Clearing it never needs Premium. See
  [Premium League branding](/docs/api#premium-league-branding).
- **Frozen Leagues.** A League that ends while it has Premium plays no more matches. Its members still
  read its last standings, and its delegates keep reading it as reporters.
- **Reports.** The owner, organizers and reporters read a participation report. A League that had
  Premium keeps a final report after it ends; an active League without Premium gets
  `402 premium_required`. See [Premium League reports](/docs/api#premium-league-reports).

What a report counts:

- **Participants:** every account that joined.
- **Games:** rated, non-void games only. Games against house bots are shown separately. House bots
  and non-members are never participants.
- **Days:** UTC.
- **Exports:** `participants` and `daily` CSV tables, with formula-leading cells prefixed. A
  delegate's export is audited.

Reports describe practice and engagement, not skill or workplace performance.

### Multiple competition ladders

Owner-managed Leagues are private. Start one from **My Leagues** by naming it and picking a plan;
payment activates it. Until then only its owner sees it. Every owner League is listed only for the
people who can read it: its owner, its active members and, with Premium, its delegates.

- **While it runs** the owner can edit its name, Markdown description, artwork, listing and
  admission and its end time. Maps, opening time and limits change only while it is inactive,
  since they govern how matches run.
- **Admission** is by invitation link, emailed invitation or shared password. Links are single-use;
  an emailed invitation works only for the account signed in with that address. Revoking an
  invitation cancels it. Approvals respect the League's participant limit.
- **Deactivation** stops new matches and lets running ones finish. The League keeps its settings,
  members, lifetime records, snapshots and archive; ratings outside the 30-day window expire, and
  reactivating doesn't restore them.
- **Ending** is the optional end time (`closes_at`), which the owner sets, moves, clears or reaches
  at once with End now while the League runs; it never needs deactivation. An end time already
  past saves as the moment of the edit, so a League never ends in the past its matches were judged
  by, and another past time on an ended League changes nothing. At the end, new matches stop,
  running ones finish, and the Ladder saves a "Final standings" snapshot (then "Final standings 2",
  …) of the board as it stood at the end, once per end time. It counts against no snapshot limit,
  and managers can't take that name. Reopening (no end, or a later one) keeps every snapshot,
  continues ratings and lets league teams change again; repeating schedules that passed the end
  have stopped. An ended League stays active: its plan, seats and entitlement are unchanged.

The ladder server hosts logical competitions inside one database and socket
endpoint. A completed match belongs to exactly one ladder; omitted queue IDs
select Public and historical rows migrate to Public. Accounts, bot identities and
version metadata are global, while ratings, records, qualifying games, pairing
history, seat balance, map exposure and official house identities are scoped.
Bot pages default to Public and provide a ladder picker offering only ladders where
the bot has recorded matches, including unrated and voided games across all versions.
Direct URLs may still select an unplayed ladder. Ranks, ratings, records,
health, opponents, maps and recent matches all use the selected ladder, preserved
in the page’s `?ladder=<id>` URL.
Bot listings pair their name with their equipped avatar. Standings and competitive matchup
and opponent views also show rank; management screens, evidence, report narratives and
repeated stats labels omit it. Where a current rank is shown, unranked bots use a dash badge.
Historical standings retain their recorded rank.

Leaderboard, bot and player pages disable automatic telephone detection so iOS
does not rewrite W–L–D records into links and interfere with live refreshes.
Upcoming enabled ladders allow account preregistration while queues wait for
opening. The October 12–16, 2026 precon uses an independent open-enrollment ladder,
from noon Monday to 6 AM Friday in America/Denver, with five unofficial testing
flags and no HC submission site.
An optional event `flag_mode` selects `official` (default, configured server-only
HC flags) or `testing` (stable `ARENA_TEST` values scoped to event and achievement).
Testing uses the same enrollment, match eligibility, awards, private reveal,
evidence and revocation checks. It never provides flags for an unconfigured
official event. Event definitions, flag mode included, stay editable after an event
opens; awards already earned are kept. Event definitions may carry public metadata:
kind (`precon`, `main`, `community`), purpose, audience, format and preparation.
Optional branding images appear on both event and enrollment pages, with HTTPS
URL, alternative text and dimensions. Admins can upload, replace or remove artwork
through the authenticated event image route; they are stored as normalized WebP.
Branding remains editable after opening without changing scoring,
and admin image overrides survive manifest reloads and earning toggles.
These details appear on both event and enrollment pages, and a null submission URL
omits flag submission links.
Enrollment is per account, with open, approval or invitation policies. Invitations
are hashed, expire, may be account-bound, and redeem once atomically. Public
requires no enrollment. Spectator pages and replays remain public. A ladder's
`visible` setting defaults to true and controls public ladder/event discovery;
hidden ladders remain accessible by ID and in members' account listings.

A private League's owner and active members can read it, including after play stops; departed or
revoked members lose access at once. HTTP and MCP reads both check membership, and catalogs and
links to other Leagues leave out ones you can't read. Match IDs decide replay permission, whatever
the query parameters. Private responses are never cached or indexed, and pages clear what they
showed when you sign out or switch accounts.

A bot's profile in a ladder lists only the versions queued there. The exception is Public for a bot
whose owner shares their profile page: it lists every version label (versions never queued there
show 0–0–0, without their aliases and notes) and adds each bot's record summed over every ladder,
Leagues included. Profile pages start private for new accounts.

League matches stay readable after they leave the current window: match details, stats, MCP match
reads and replay downloads still work for the owner and active members. While a lookup isn't ready
the API returns a retryable `503 archive_index_pending` or `503 archive_history_unavailable`; a missing
or damaged recording returns `503 archive_media_unavailable` (replay downloads: `503` with
`Retry-After: 5`). An unknown match is `404`. To find older matches, page through
`GET /api/ladders/<id>/history`, or MCP `list_matches` past the recent ones: newest first, at most 50 a page,
with stable-bot and stored-version filters and an opaque cursor. An empty page with a cursor still
has more. There is no browser page; bots and agents read these directly. See
[private League archive history](/docs/api#private-league-archive-history).

Private League owners may publish one completed, nonvoided match result or 1–20 selected ranked
standings rows. The owner previews a frozen copy (valid for 15 minutes) and approves it. A public
snapshot contains only the chosen title and time, the selected display names, and outcome, map and
finish or rank, score and record: no private image, replay links, unselected roster or live data.
Publishing needs active access to the League. Shares remain after deactivation or cancellation
until the owner revokes them; deleting the League revokes them permanently, and account bans hide
them. A revoked snapshot disappears from open pages within seconds, but copies already downloaded
can't be recalled. See [selected public snapshots](/docs/api#selected-public-snapshots).

Admission and the play window are checked when queueing, scheduling and completing
an event match. Matches finishing after closing or with a changed enrollment are
unrated and do not earn achievements. Revocation removes waiting bots and blocks
flag reveals. Readmission gets a new membership identity. Historical results stay
recorded. Global quotas and capacity compose with per-ladder ceilings. Available
round capacity is shared across active scopes, rotating which is considered first.
See [LADDERS.md](/docs/ladders) for the complete enrollment and persistence contract.

## Effective operational limits

The running ladder publishes current limits in `GET /api` → `operational_policy` and `quotas`.
The downloadable simulator bundles release defaults. Each match's `hello` and replay contain its
captured effective rules and timing; reconnecting preserves that snapshot. Active matches retain
their deadlines, reconnect grace, failure tolerance and per-tick flood cap. Capacity and matchmaking
changes affect subsequent starts. Existing invitations and human tickets retain their expiry.
See [effective match limits](/docs/api#effective-match-limits) and the [simulator](/docs/simulator).

### Occupancy statistics

For each resolved tick, sample each living fighter's position before the engine step.
Idle and stunned ticks count, dash traversal adds no samples, and dead fighters add none.
Per-fighter optional `occupancy` contains width, height and row-major integer counts.
This observational statistic does not change simulation state, hashes or replay inputs.
The ladder aggregates non-voided matches by stable bot ID, version, ladder, map,
mode and dimensions, atomically with match persistence. Counts use little-endian uint64
blobs; per-match counts remain in the compressed statistics archive. A match digest
prevents duplicate contributions. Corrections require the previous archived statistics
so the original contribution can be subtracted in the same transaction.
