# Rules: what the game does today

**Owns:** every shipped rule and its constant. Code must match this file; a PR that changes behaviour updates it. Why the rules are what they are: [whitepaper.md](whitepaper.md).

---

## Worlds

Today only the **Sandbox** (world id `10s`, **5 s** cooldown) is open to players (`/health` `publicModes: ["10s"]`, `rankedModesEnabled` false). Slower worlds (`1m` Standard, `24h` Daily) are defined in the code and use the same rules, but they are not open. Each world is fully separate (own board, players, chat, history), and only the cycle length differs between them. Sandbox vs Ranked, accounts, and the 100-player sandbox plan: [modes.md](modes.md).

| World | Cycle (cooldown) | Open today |
|---|---:|---|
| `10s` Sandbox (default; the id is kept for API and stored data, the cooldown is 5 s) | 5 s | yes |
| `1m` Standard | 1 min | no, defined only |
| `24h` Daily | 24 h | no, defined only |

**Every timing rule is in cycles** (1 cycle = the world's cooldown), so changing world speed rescales the whole meta. In the 5 s Sandbox that means, for example, a check answer window of 15 s (3 cycles), a mate rescue window of 5 s, quiet exit after 75 s (15 cycles) and a return lockout of 75 s. The cycle length is set in one place, `GAME_MODES` in `packages/protocol/src/modes.ts`.

| Constant | Value | Meaning |
|---|---:|---|
| `maxRange` | 4 | Max slide of Q / R / B |
| `spawnSpacing` | `maxRange` = 4 | Minimum Chebyshev distance from any other piece at spawn; spawn lattice pitch = footprint + spacing − 1 = **7 × 8** |
| `zoneMinRadius`, `zoneDensity` | 10, 4 | Target radius = `max(10, ⌈4·√n⌉)`, `n` = alive players |
| `chatRange` | 16 | Nearby chat reach (Chebyshev distance between Kings) |
| `quietExitCycles` | 15 | No own move + no lost piece → auto-hibernate; **under check → mate-path removal** instead ([#138](https://github.com/chessar-io/chessar.io/issues/138)) |
| `checkGraceCycles` | 3 | After you become ready under check, this many cycles to answer or die ([#127](https://github.com/chessar-io/chessar.io/issues/127)) |
| `returnLockoutCycles` | 15 | Wait after any hibernate before returning |
| `idleSafetyCapCycles` | 90 | Never-moved **and** never-touched army is removed |
| `captureRecruit` | `true` | Capture → recruit that type only if victim material ≥ yours (pre-capture) |
| `mateCredit` | `'last'` | The last hit is the credited killer (stats, `matedBy`); it does not decide who is rewarded |
| `mateReward` | `'raid'` | The mated army's non-King pieces become a shared pool every attacker takes from, first come first served (see Growth) |
| `exits` | `'earned'` | Hibernate only via earned exit (or quiet exit) |

---

## Board & spawn

- One infinite board, fully public (no fog). Pieces live and move only inside the **active zone**: `|x| ≤ R` and `|y| ≤ R`.
- `R` grows when a spawn needs room. Each tick it shrinks by 1 toward the target radius, but only while the outer ring holds no piece, so no piece is ever removed or pushed.
- **Warlord Stack**: every fresh army, 16 pieces, King at the centre:

```text
. P P .
P R B P
N Q K N
P B R P
. P P .
```

- **Placement (spawn, respawn, return):** armies are placed only on lattice slots `(7i, 8j)`. On an intact neighbour this puts the Kings 7 apart horizontally (like e1 to e8) with 3 empty cells between the armies.
- **A slot is valid only if all of these hold, with the board exactly as it is** (scattered and moved pieces included):
  1. the whole footprint is empty and inside the zone;
  2. no other piece is closer than `spawnSpacing`;
  3. **no first-move capture either way:** no new piece could capture anything, no existing piece could capture any new piece, and the new King is not in check. Pawn double steps count.
- **Among valid slots, pick by similar army size.** Army material = sum of on-board pieces with chess values **Q 9 · R 5 · B 3 · N 3 · P 1** (King 0; a fresh Warlord Stack is **39**). Pick the valid slot whose nearest alive neighbour (Chebyshev King-to-slot) has the closest army material to yours; ties use the existing tie-breaks (most occupied neighbouring slots, then nearest the centre of the alive Kings). If none is valid, grow `R` by one lattice step and retry. Same rule for every army (human or agent); no special cases.
- No spawn protection is needed: placement guarantees nobody can capture on the first move. Contact starts from the second cycle.

## Moving

- **Move whenever you like.** After each move your pieces rest for a moment (one cycle); everyone else keeps playing.
- One piece per move. If two moves target the same cell, the first valid command wins and the other gets `collision`.
- An available move never expires.

| Piece | Moves | Captures |
|---|---|---|
| King | 1 cell, any direction | same |
| Queen / Rook / Bishop | slide up to `maxRange`, stopped by the first piece | the first enemy piece on the line |
| Knight | classic L, jumps | same |
| Pawn | 1 cell orthogonally; 2 cells (both empty) as its first move as a member of the army: spawned, returned, recruited and raided pawns all start fresh | 1 cell diagonally, or en passant |

- A piece never moves onto its own side's piece; only knights jump.
- **En passant.** When a pawn makes its 2-cell first move, enemy pawns standing directly beside its landing cell (perpendicular to the step) may capture it by moving diagonally onto the cell it skipped. Only pawns may, only that pawn, and only until the double-stepping army can move again (its one-cycle cooldown) or moves, whichever comes first. The move command names the captured pawn in `capture` although the target cell is empty. Capture-recruit and check rules apply as for any capture; taking the checking pawn en passant answers a check.
- No castling or promotion. Kings are never captured.
- **Everything is in range.** A move is illegal only if afterwards your King is attacked by a piece that can actually reach it (within `maxRange`). A slider farther away never pins.

## Check, mate, stalemate

| Outcome | When |
|---|---|
| **Check** | At least one enemy piece attacks your King. Only moves that end it are legal. A **check clock** runs: deadline = `max(now, readyAt) + checkGraceCycles × cooldown`; miss it while still checked → same death as a held mate |
| **Checkmate** | In check with no legal move. A **rescue window** of one cycle opens: if anyone breaks the mate in time (captures a checker, blocks a line, frees a square), the King lives; if the mate still holds when the window ends, the army falls |
| **Stalemate** | Not in check and no legal move → you skip one cycle (not a death) |

- Check does **not** bypass the cooldown. The check clock counts from when you can move again (`readyAt`). Any legal answer (or a third-party rescue that ends the check) clears the deadline (`checkDeadline` on the army / snapshot for UI [#140](https://github.com/chessar-io/chessar.io/issues/140)).
- The check clock never extends the mate rescue window: a King with no legal move still has one cycle to be rescued.
- **During the rescue window** the mated side has no legal move and cannot surrender (`mate_pending`). Its pieces stay on the board and can be captured. A mate that breaks and is rebuilt starts a new window.
- **Last-hit credit:** the player whose command made the mate is credited (`matedBy`), but only if they still attack the King when the window ends. Else the check starter (`checkedBy`) if they still attack; else nobody. Every other current attacker is an **assist** (a public log row); all attackers, assists included, share the mate reward (see Growth). A mate that appears from a removal (no command) goes to the check starter by the same rule. Check-clock timeout, idle-under-check, and leave-under-attack reuse this credit path.

## Growth (capture-recruit, mate raid)

Material for growth gates uses the same chess values as spawn and the player list: **Q 9 · R 5 · B 3 · N 3 · P 1** (King 0). Count every piece on the board owned by that player **before** the capture resolves.

- **Capture-recruit (parity).** After you capture a non-King of type `T`, your **next** move may place `T` (your colour) on an empty cell Chebyshev-adjacent to your King, inside the zone, **only if** the victim’s army material **before** that capture is **≥** your army material before it. Equal material recruits; punching down does not. Placing **is** the move (cooldown + `movesThisLife`). Any other move clears the chance; only the latest capture counts. Placement must leave your King safe (it may block a check). Recruited pawns are fresh (they keep the 2-cell first step). No timers, no army-size caps, no extra fields: the pending place stays until you place or make another move.
- **Mate raid.** When a mate holds (or a check clock, idle or leave removal ends the army), the fallen army's non-King pieces become a **raid pool** (counts per type, no positions). **Every alive army with a piece attacking the King at that moment is a raider**; a bare check never opens one, and armies that join later get nothing. No material gate. Full reasoning and the owner decisions: [mate-raid.md](mate-raid.md).
  - **Taking.** A raider takes a piece with `place { type, to }` (the same command as a recruit): the piece appears on an empty cell next to the own King, inside the zone, and the King must be safe afterwards (it may block a check). A take **is a move**: it costs the cooldown, counts in `movesThisLife` and ends en passant, so at most one piece per cycle and at most as many as there are free cells next to the King. The raider **chooses the type** from what is left. Taking from the pool is not a capture and never recruits a second piece.
  - **Race.** Takes are applied in arrival order, first come, first served: a take removes that piece from the pool for everybody. A request for a type that is gone is rejected `pool_empty` and the raider may name another type. Several mates at once open several raids; a take comes from the oldest raid that still has that type. A pending capture-recruit of the same type is used before the pool.
  - **Rights.** There is no time limit. A raider keeps the right to take for as long as it has a free cell next to its King, one piece per move. The right **ends** when the raider (a) moves any other piece, makes a capture or a capture-recruit placement, (b) is put in check, (c) dies or hibernates, or (d) has no free cell left. A raider that is already in check when the raid opens may still take (a take can block the check) until the check is renewed.
  - **Closing.** The raid ends when its pool is empty or when no raider keeps the right. An open raid is part of the snapshot and survives a restart; it has no clock, so downtime changes nothing.
  - **Stats.** Every raider counts a mate (`mates`), even when the pool is empty (nothing opens then), and the first take opens the earned exit.
  - **Example.** B (King, Q, R, P) is mated by A, C and D. The pool is Q 1, R 1, P 1. D has a free cell and is ready first: it takes the Queen. A asks for the Queen a moment later and gets `pool_empty`, so it takes the Rook. C takes the Pawn when ready, and the raid closes. If C moves a Knight instead of taking, C gives up the right and the Pawn stays in the pool for whoever still has it.
- **Same rules for every army.** Humans and agents; no bot-only growth, spawn, or caps in these rules.
- **Worked examples** (material before the capture):
  - A = 39 captures from B = 39 → A gets a recruit (equal).
  - A = 42 vs B = 36: A captures from B → **no** recruit; B captures from A → B recruits (42 ≥ 36).
  - A = 20 captures a Queen from C = 70 → A gets a Queen recruit (70 ≥ 20).
- **Command:** `place { type, to }` (socket + REST). Reject: `no_pending_place` (nothing to place), `pool_empty` (a raider asked for a type that is gone), `bad_type`, `not_adjacent`, `occupied`, `out_of_zone`, `in_check` / `self_check`, `cooldown`, … (a capture that fails the parity gate never grants pending place).

## Leaving and dying

| Action | Effect |
|---|---|
| **Death** (held mate, check-clock timeout, or idle/leave under check) | Army removed via the shared mate-credit path. Respawn a fresh Warlord Stack at any time, ready to move at once |
| **Surrender / leave** | Starts a one-cycle leave window (`leaveUntil`). If still checked when it ends → mate credit for attackers; else voluntary death. Cannot leave during a mate rescue window (`mate_pending`) |
| **Earned exit (hibernate)** | After taking a piece from a mate raid, until your next move, you may hibernate even while cooling down (not in check). Reject `no_earned_exit` otherwise. Same `returnLockoutCycles` |
| **Quiet exit** | `quietExitCycles` with no own move and no lost piece → automatic hibernate when **not** in check. Under check, the same timer routes to mate-path removal instead (attackers keep credit). An own move or a lost piece (re)starts the quiet window; **check alone does not** |
| **Idle safety cap** | Removes only armies that never moved **and** were never touched (`idleSafetyCapCycles`) |
| **Return** | After the lockout: Warlord Stack with holes for missing types; every leftover piece (any type) goes on rings clockwise from east of the King (order Q, R, B, N, P) |
| **Abandon** | During the lockout, drop the stored army and respawn fresh |

## Identity

- **Guest:** a random token in `localStorage`. The server stores only its hash. Nicknames are unique per world (case-insensitive).
- **Account:** username + password. Registering claims the current guest's armies; logging in on another device gives the same armies.
- **Agents:** one API key = one agent identity owned by an account, shown by its plain name; its player card says **AI agent · by owner**. Agent armies per account are capped. Same rules, same validation. API: [api.md](api.md).
- Every player gets a colour no other player in the world has. It stays the same across deaths and respawns.
- Splash suggests a guest nickname (`alice69`-style).
- One live connection per army: a new tab or device takes over, and the old one is told (`kicked`).
- Disconnecting pauses nothing: your army stays on the board, and you just stop moving.
- A deploy or restart keeps every army (snapshots); cooldowns and timers are shifted by the downtime.

## Diplomacy

Chat is not game state: it never changes the board, `seq` or snapshots.

- **Nearby:** delivered to every alive player whose King is within `chatRange` of the sender's King at send time. Possibly nobody.
- **DM:** to one player in the same world, anywhere; kept for them if they are offline.
- **Block:** the blocker stops receiving that player's Nearby and DMs. The sender is never told.
- Only alive players can send. Text is 1 to 280 characters after trimming, single line. Rate: burst 3, then 1 message / 2 s per player across all transports.
- Messages are kept 30 days. Every reader sees exactly what was delivered to them at send time.
- **Public battle history** (kept `BATTLE_LOG_RETENTION_DAYS` days, default 30, [ops.md](ops.md); no auth): captures, mates (`checkmate` when the window opens, `rescued` if it breaks, `mated` for the credited player + `assist` rows when it holds, and a `raid` row with the pool and the raiders, target = the fallen army), placements (`placed`), spawns (`resumed`), hibernations (incl. `earned`), surrenders, despawns (`idle` | `revoked`).
- No alliance objects, no reputation, no team flags, by design ([whitepaper.md](whitepaper.md#5-diplomacy-and-the-social-dilemma)).

## Client

- Splash: nickname, world, play as guest or log in. End screens: checkmated / surrendered / hibernating, with survival time, captures and mates. Guests are nudged to save an account before hibernating. In game: "Save your army" creates an account.
- Board: pan, zoom, Space centres your King. One camera framing: whenever the camera moves to a King (join, respawn, Center in the bar or on a card, Space, a Players row, the first frame of Follow; mine or an enemy's) it ends at the same default zoom with that King at the centre of the visible board area (the board above the bottom bar). The default zoom shows at least about 14 x 26 cells on a desktop and 12 x 20 on a phone (never closer than one cell = 64 px, never smaller than 29 px), so part of the neighbouring armies is in view. Center after a manual zoom returns to that zoom; while Follow runs only the pan follows, so you can zoom. A tap on the board never moves the camera. The name label sits on the King's own cell, centred, with its top flush with the cell top. Move dots are rose while cooling down, green when ready. Names show on hover or select, in full (a nickname is at most 16 characters; only a longer name is cut), in neutral white with a strength icon to their left: a red chevron up when that army has more material than yours, a green chevron down when it has less, a blue diamond when equal (the same material as the player list; it is also what capture-recruit compares). Your own label has no icon.
- HUD: cooldown clock is a status (tabular time / "Ready", never a button); check/mate banner sits below the top bar (who checks you · when you can move · "only moves that end the check"; mate window is red with rescue countdown); placement is a compact one-line banner above the player bar (piece icon + short "this is your move" copy + Ready/countdown; ≤48px tall on ≤480px viewports); first visit shows a non-blocking bottom coach strip (Skip always; auto-dismiss after first move; full How-to stays in More + landing); one-shot coach tip sits above the banner on first recruit; board auto-frames King + place cells above the banner once when placement becomes pending; in a mate raid the placement banner ("Mate raid: take a piece next to your King") comes with a raid tray: the pieces still in the pool, strongest first, with live counts (a taken piece greys out); tap one to choose, then tap a glowing cell (the strongest left is chosen for you); a piece someone else just took is refused with "already taken"; the player bar is the same on desktop and mobile: identity, cooldown status, icon actions (Center, Chat, Players on mobile) and a More menu (Save army, Hibernate when earned, How to play, Invite, a Show coordinates toggle with its state, and Surrender last, set apart and confirmed); your own army card opens above the identity block; player status ≤2 lines (name + you · pieces/captures/mates as icon+number); player list ranked by material on the board (Q 9 · R 5 · B 3 · N 3 · P 1; ties by mates, then captures); **tap a player row to centre the camera on their King** (a camera flight: short hops glide ~320 ms; far ones zoom out first, slide, then zoom back in on the player, ≤1.3 s; instant when `prefers-reduced-motion`), pulse a ring ~1.2 s, open the player card above the bottom bar; **tapping an enemy piece on the board only opens the card and pulses their King, the camera never moves** (Center in the card does it), and on narrow viewports collapse the Players sheet so the King stays visible; **Follow** keeps recentering when they move; Message opens chat prefilled with `@name `; own row has Center only (no Message); if the camera moves while a placement is pending or a piece is selected, a toast offers **Center** back on your King; battle log (shows only your own battles). Placement cells highlight cyan while a recruit/reward is pending (stay visible but dimmed while a piece is selected; tapping a glowing cell places, unless the selected piece can legally move there, in which case it moves). A checkmated King in its rescue window has a red ring and ✕ next to its name. Rejected actions toast near the bottom bar (~3 s, `aria-live=polite`).
- **In check:** every checking piece and the cells between it and your King are highlighted, so you can see which line to block or which piece to capture. Your pieces that have no legal move are dimmed. A rejected non-answer says which piece still gives check.
- Chat dock (Nearby + DMs, unread badge); player card (rank, material, captures, mates, army size, world mode; Center / Follow / Message / Block; Esc or tap elsewhere dismisses). A faint ring shows `chatRange` while you type.
- Agents show their plain name; the player card says **AI agent**.

## Known gaps

Shipped-rule edge cases that can leave a game without a clean end. Severity = player impact if it happens often.

| Severity | Gap | Evidence | Proposed |
|---|---|---|---|
| **done** | Long live checks / unmatable Kings | Check clock (`checkGraceCycles`) + shared mate-removal path. | [#127](https://github.com/chessar-io/chessar.io/issues/127) shipped |
| **done** | Quiet exit while checked | Under check, quiet timer → mate credit (not hibernate). | [#138](https://github.com/chessar-io/chessar.io/issues/138) shipped |
| **med** | Unused recruit never expires (an open raid ends when no raider keeps the right) | `hasLegalMove` counts a legal place (`legality.ts`); growth tests assert place-only “has a move”. Mate waits; AFK still quiet-exits (above). | Check clock bounds live checks; place semantics unchanged unless a later job says otherwise |
| **med** | `maxRange` = 4 geometry stall | `packages/engine/test/geometry-stall.test.ts`: rook at range cap checks a King that still has flight → not mate. | Mostly moot once check clock kills unanswered check; keep range unless bots say otherwise |
| **low** | Idle safety cap ignores touched armies | Only never-moved **and** never-touched despawn. | Unchanged |
| **low** | Stalemate is a skip, not death | Not in check + no legal move → one cycle skip. | Unchanged |

### Findings (job `73c27159`, 2026-11-02)

Three brief suspects, all **confirmed in code/tests**, no product change in this docs PR:

1. **Pending place stalls mate detection**: true: `hasLegalMove` returns true when a safe recruit or raid cell exists. By design for stalemate; also means a smothered King with a pending place is not mated.
2. **AFK under check hibernates**: fixed: quiet under check → mate path (`quiet-exit-checked.test.ts`, [#138](https://github.com/chessar-io/chessar.io/issues/138)).
3. **Range-cap + cooldown make mate slow**: true for lone distant checkers (`geometry-stall.test.ts`); check clock bounds unanswered checks ([#127](https://github.com/chessar-io/chessar.io/issues/127)).

**Next:** re-measure mates per 100 checks and growth ([#125](https://github.com/chessar-io/chessar.io/issues/125)) now that the check clock, pawn double-step and shared rewards have shipped. Do not raise `maxRange` in those PRs. Client check-clock banner: [#140](https://github.com/chessar-io/chessar.io/issues/140) (reads `checkDeadline`).

Client note: below 900 px width the player list becomes a floating panel.
