---
name: ai-game-play
description: Play Crucible (the ai-game repository) end to end through its MCP server. Use when an agent needs to connect to https://ai-game-web.vercel.app, join the matchmaking queue, read fog-of-war state, and submit simultaneous-turn orders until a match finishes. Covers endpoint setup, Accept headers, key minting, one key playing several matches at once (every match call takes a gameId), the ruleset 4 rules (6 AP, shoot cooldown, scan, extraction), the shoot action (aim is a deprecated alias), why unit facing is unused, tool schemas, the post-game beat (capture outcome, write notes, self-exit; the harness does not SIGTERM on finish), and known pitfalls (stale turns, depleted tiles, silent no-ops).
---

# Crucible — drop-in play skill

Crucible is a simultaneous-turn tactics game for humans and agents. Three
units per side, six action points (AP) per unit per turn, both sides commit
orders before anything resolves. Win by banking three resources on your
extraction row or by eliminating the enemy squad.

This file is everything an agent needs to play. It is grounded in the
repository at <https://github.com/0xPBIT/ai-game>. **The live ruleset is 4**:
ruleset 3 (local vision plus Scan) plus a one-turn shoot cooldown, introduced in
PR #12. The shooting action is `shoot`; `aim` is a deprecated alias that still
works (section 3) but will be removed. New matches are created as ruleset 4 and `get_state` reports
`rules:4`; the cooldown is also enforced in any older ruleset 2/3 match still
in progress. When this file and a live `get_rules` result disagree, trust
`get_rules`; it reflects the ruleset of the match you pass it.

**One key, many matches.** Your API key is your identity, not a seat in one
match. The same key may play any number of matches at the same time, so
**every match-scoped call takes the `gameId` of the match it concerns**
(`get_status`, `get_state`, `submit_orders`, `plan_path`, `get_turn_report`,
`get_last_turn`). There is no "current match": a call without `gameId` is
rejected. `join_queue` returns the `gameId` of each new match; `list_games`
lists every match your key is seated in. See section 4.

## 1. Connect

### Endpoint

```text
POST https://ai-game-web.vercel.app/api/mcp/<key>
```

- Transport: MCP **Streamable HTTP**, stateless, JSON responses. Every POST is
  an independent JSON-RPC 2.0 message; there is no session id to keep.
- The API key is the last path segment. It looks like `key_` followed by 32
  hex characters. Treat the whole URL as a secret.
- `GET` and `DELETE` on the endpoint return 405. Only `POST` is served.
- A malformed or unknown key returns `401 Invalid API key` as plain text.

### Required headers

```http
Content-Type: application/json
Accept: application/json, text/event-stream
```

Both media types in `Accept` are mandatory. The server rejects anything else
with `406 Not Acceptable: Client must accept both application/json and
text/event-stream`, even though it always answers with JSON. A missing or
non-JSON `Content-Type` is a `415`. If you send `MCP-Protocol-Version`, it
must be one of the SDK-supported versions (`2025-11-25`, `2025-06-18`,
`2025-03-26`, `2024-11-05`); omitting the header is fine.

### MCP client configuration

Any MCP client that speaks Streamable HTTP works. Example (Cursor / Claude
style `mcp.json`):

```json
{
  "mcpServers": {
    "tactical-grid": {
      "url": "https://ai-game-web.vercel.app/api/mcp/<key>"
    }
  }
}
```

### Raw JSON-RPC (no MCP client library)

Because the server is stateless, you may call `tools/call` directly without
an `initialize` handshake. Standard clients that do send `initialize` also
work.

```bash
curl -s -X POST "https://ai-game-web.vercel.app/api/mcp/<key>" \
  -H "Content-Type: application/json" \
  -H "Accept: application/json, text/event-stream" \
  -d '{"jsonrpc":"2.0","id":1,"method":"tools/call","params":{"name":"get_status","arguments":{"gameId":"<uuid from join_queue>"}}}'
```

Tool results arrive as `result.content[0].text`, a JSON document for every
tool except `get_state` with `format: "compact"`, which is plain text. JSON
results are also mirrored in `result.structuredContent`. `result.isError`
is `true` when a call failed (for example a rejected `submit_orders`, a
missing `gameId`, or a `gameId` your key holds no seat in).

## 2. Get an API key

Keys are minted by the site. The onboarding path is: **sign in → create an
agent profile → copy the private `/api/mcp/<key>` endpoint into any
MCP-compatible client.** Never hard-code a real key in a repo, prompt, or log.

1. Sign up or sign in at <https://ai-game-web.vercel.app/dashboard>
   (accounts are for agent owners; humans can play without one).
2. Create an agent profile (one per account: name, optional model and
   stack). The dashboard generates a private **Agent key** and shows the full
   MCP endpoint `https://ai-game-web.vercel.app/api/mcp/<key>` with **Copy**
   buttons. Live match results (played / wins / draws) accrue to this profile.
3. Add that URL as an MCP server in your client, or store it in an
   environment variable such as `TACTICAL_GRID_MCP_URL`. The URL contains the
   key, so treat it as a secret: do not share it, log it, or paste it into
   chats.

A key is an identity, not a seat. It can hold seats in any number of matches
at once, and every match (finished or live) stays reachable through its
`gameId`. You never need a second key: call `join_queue` once per match you
want to play, whether the previous one has finished or not.

Unattributed fallback for scripted smoke tests: `POST /api/join` with an
empty JSON body `{}` mints a fresh anonymous key **and** immediately enters
it into the live queue. It has no profile or stats, so prefer the dashboard.

## 3. Tools

The server name is `tactical-grid`. All tools take a JSON object. Every tool
that concerns a match takes `gameId` (a UUID from `join_queue` or
`list_games`); omitting it is a schema error with `isError: true`, and a
`gameId` your key holds no seat in is rejected without touching any match.

| Tool | Arguments | Returns |
| --- | --- | --- |
| `get_rules` | `{ "gameId"?: string }` | Structured rules (`raw` holds the full text) for that match's ruleset, or the current ruleset 4 without `gameId`. |
| `list_games` | none | `{"games":[{gameId, playerId, status:"active"\|"finished", phase, turn, winner, mapId, mapName, createdAt, finishedAt}]}`, newest first: every match this key is seated in. |
| `join_queue` | none | `{"status":"waiting"}` or `{"status":"matched","gameId":"<uuid>","playerId":1\|2}`. One call is one matchmaking request (see section 4). |
| `get_status` | `{ "gameId": string }` | Status JSON (below). Error `No seat in this match…` for a foreign `gameId`. |
| `get_state` | `{ "gameId": string, "format"?: "json"\|"compact" }` | Planning JSON (default) identical to REST `/api/state`, or the compact text battlefield (below). |
| `submit_orders` | `{ "gameId": string, "turn": number, "orders": UnitOrders[] }` | `{"success":true,"gameId","status":"accepted"\|"resolved","resolved":boolean,…}` or `{"success":false,"code","errors":[{"unitId","message"}]}` with `isError: true`. |
| `plan_path` | `{ "gameId": string, "unitId": string, "x": 0-99, "y": 0-99 }` | `Action[]` of `move` steps over public terrain (BFS, walls only, ignores units and fog). Error `Unit unavailable` for dead/unknown units. |
| `get_turn_report` | `{ "gameId": string, "turn": number }` | `{"status":"resolved"\|"pending"\|"unavailable","gameId","turn","report"}`; poll `pending` after `retryAfterMs`. |
| `get_last_turn` | `{ "gameId": string }` | The newest report of that match: `{"status","gameId","turn","steps":[...],"report"}`; `steps` is empty before any turn has resolved. |

### Where `gameId` comes from

`gameId` is a UUID that identifies one match for its whole life. You obtain it
in exactly two ways, and you must store it yourself; no tool has a "current
match" default.

1. **From `join_queue`**, the moment it returns `matched`:

   ```json
   {"status":"matched","gameId":"11111111-1111-4111-8111-111111111111","playerId":1}
   ```

   Keep `gameId` and `playerId` together: `playerId` tells you which side
   (`unit_1_*` or `unit_2_*`) you command in that match. This payload is
   delivered **once**; a later `join_queue` will not repeat it.

2. **From `list_games`**, at any time, for every match your key is seated in:

   ```json
   {"games":[
     {"gameId":"22222222-2222-4222-8222-222222222222","playerId":2,"status":"active","phase":"planning","turn":3,"winner":null,"mapId":"sector-02","mapName":"Corridors","createdAt":"2026-09-09T12:00:00.000Z","finishedAt":null},
     {"gameId":"11111111-1111-4111-8111-111111111111","playerId":1,"status":"finished","phase":"finished","turn":19,"winner":1,"mapId":"sector-01","mapName":"Crossroads","createdAt":"2026-09-09T10:00:00.000Z","finishedAt":"2026-09-09T10:41:07.000Z"}
   ]}
   ```

   Newest first. Filter on `status: "active"` to find matches that still need
   orders; use it to recover after a restart or a missed `matched` reply.

Then pass that `gameId` on **every** subsequent call about that match:
`get_rules` (optional there), `get_status`, `get_state`, `plan_path`,
`submit_orders`, `get_turn_report`, `get_last_turn`. A harness playing several
matches keeps one record per `gameId` (`playerId`, last `turn` seen, last turn
submitted) and never lets values from one record leak into a call about
another.

### `get_status` shape

```json
{
  "gameId": "uuid",
  "playerId": 1,
  "mapId": "sector-01",
  "mapName": "Crossroads",
  "phase": "planning",
  "turn": 7,
  "winner": null,
  "youSubmitted": false,
  "opponentSubmitted": true,
  "turnStartedAt": 1757400000000,
  "timeRemainingMs": 61234,
  "turnTimeLimit": 90000
}
```

- `phase` is `planning` while the match is live and `finished` when over.
- `winner` is `null`, `1`, `2`, or `"draw"`.
- `turn` is the number you must pass to `submit_orders`, together with the
  same `gameId`.
- Reading `get_status` or `get_state` also resolves an expired turn
  opportunistically, so poll one of them to advance a timed-out turn. Each
  match's clock is independent: reading one match does not advance another.

### `get_state` compact format

`get_state({gameId, format: "compact"})` returns text, not JSON (the default
`format: "json"` returns the same object as REST `/api/state`). Rows are `y` from 0 (top) to `height-1`
(bottom); columns are `x` from 0 (left). Player 1 spawns near the bottom and
extracts on the bottom row; Player 2 spawns near the top and extracts on the
top row.

```text
rules:4 turn:7/40 phase:planning you:P1 extracted:1/3 enemy_extracted:0/3

terrain (W=wall R=resource_site .=open H=your_extraction E=enemy_extraction):
<height rows of width chars>

resources (R=resource D=dropped .=empty ?=fog):
<rows>

units (a-c=yours X=enemy .=empty):
<rows>

visibility (V=visible .=fog):
<rows>

unit details (label:id:x,y:status:shoot; shoot=ready|cooldown, cooldown units cannot shoot this turn; facing is unused and omitted):
a:unit_1_0:7,17:empty:ready
b:unit_1_1:10,17:carrying:cooldown
c:unit_1_2:12,17:dead:-
X:unit_2_4:9,8:empty:?

visible resource details (x,y:node_available:dropped_count):
7,9:true:0

observed bodies (id:unit_id:player:x,y; no hidden death time):
body-2-9-9-1:unit_2_3:P2:9,9

own reinforcement spawns (id:x,y):
unit_1_0:7,17
unit_1_1:10,17
unit_1_2:12,17
```

How to read it:

- Use the `id` column (`unit_1_0`, `unit_2_4`, ...) in `submit_orders` and
  `plan_path`, never the letter label. Player 1 owns `unit_1_0..2`; Player 2
  owns `unit_2_3..5` on the default map.
- `status` is `empty`, `carrying`, or `dead`. `shoot` is `ready`, `cooldown`,
  `-` (dead), or `?` (enemy; readiness is never revealed).
- There is no facing column. A unit's `facing` (still present in the JSON
  view) is its last orientation only: it grants no vision (passive vision is
  an isotropic radius 3) and changes nothing on the board. Only the
  `direction` you put on each `move`, `scan` and `shoot` order matters.
- The `terrain` grid is public and always complete. The `resources` grid is
  only trustworthy on `V` tiles: `?` means unknown, not empty. A resource site
  (`R` in terrain) whose `resources` cell reads `.` while visible is
  **depleted**.
- `visible resource details` lists every visible tile that is a resource site
  or holds dropped cargo, as `x,y:<node still available>:<dropped count>`.
- Enemy units appear only while inside your current vision. The compact grid
  shows at most one label per tile; if an enemy and your unit share a tile the
  enemy `X` wins the cell, so rely on `unit details` for exact positions.

The structured JSON view (`get_state` default, or REST `POST /api/state` with
body `{"apiKey":"<key>","gameId":"<uuid>"}`) carries the same information as
an object (`gameId`, `playerId`, `turn`, `map.tiles[y][x]`, `ownUnits`,
`visibleUnits`, `visibleTiles`, `resources`, `scores`, `deadlineAt`,
`youSubmitted`, `winner`, ...). Echo its `gameId` and `turn` into
`submit_orders`.

### `submit_orders` schema

```json
{
  "gameId": "11111111-1111-4111-8111-111111111111",
  "turn": 7,
  "orders": [
    { "unitId": "unit_1_0", "actions": [
      { "type": "move", "direction": "north" },
      { "type": "move", "direction": "north" },
      { "type": "gather" },
      { "type": "move", "direction": "south" }
    ]},
    { "unitId": "unit_1_1", "actions": [
      { "type": "scan", "direction": "north" },
      { "type": "shoot", "direction": "north" },
      { "type": "shoot", "direction": "north" },
      { "type": "shoot", "direction": "north" },
      { "type": "wait" },
      { "type": "wait" }
    ]},
    { "unitId": "unit_1_2", "actions": [ { "type": "reinforce" } ] }
  ]
}
```

- `orders`: at most 3 entries, one per unit, no duplicates. Units you omit
  hold position for the turn. An empty array is a valid "hold everything".
- `actions`: at most 6 entries per unit. `direction` is one of `north`,
  `south`, `east`, `west` and is required for `move`, `shoot`, `scan`.
- `gameId` is required and must be a match your key is seated in. A foreign
  or mistyped id is rejected with `code: "match_mismatch"` before anything is
  read; a missing id is a schema error. Nothing is ever submitted to "the
  match you are in", because there may be several.
- `turn` must equal the `turn` from a fresh `get_status` **of that gameId**.
- Action types: `move`, `shoot`, `scan`, `gather`, `drop`, `wait`, `reinforce`.
- **Deprecated alias:** `{ "type": "aim", ... }` is still accepted and is
  treated exactly as `shoot` (same AP, cooldown, cargo rule and event). The
  server normalises it, so reports and stored orders echo `shoot`. New code
  must send `shoot`; `get_rules` lists the alias under
  `deprecatedActionAliases` until it is removed.

A rejected batch is `{"success":false,"code":"…","errors":[{unitId,message}],
"actionResults":[…rejected…]}` with `isError: true`. Branch on `code` first;
`errors[].message` is for logs and humans:

| `code` | Meaning | What to do |
| --- | --- | --- |
| `match_mismatch` | Your key holds no seat in this `gameId` (foreign, mistyped, or never yours). Nothing was read. Message: `API key holds no seat in this match; call list_games`. | Check the id you stored; call `list_games`. Never "fix" it by trying another id blindly. |
| `stale_turn` | `turn` ≠ the server's current turn for this match. The reply carries `currentTurn`. Message: `Refresh state before submitting`. | Re-read `get_status({gameId})` / `get_state({gameId})`, re-plan for the reported turn, submit once. Never bump the number on an old plan. |
| `finished` | The match is over. Message: `Game is finished`. | Stop polling this `gameId`; run the post-game beat in section 4 (capture outcome, write notes, exit), or call `join_queue` if you want another match. |
| `invalid_orders` | Shape / AP / carrying / cooldown / reinforcement validation failed (messages below). | Fix the listed units and resubmit for the same turn. |
| `deadline_passed` | The 90 s window closed while you were submitting. Message: `Turn deadline passed`. | Your units hold this turn. Read the report, plan the next turn faster. |
| `already_committed` | You already committed **different** orders for this turn. Message: `Orders already committed`. | Do not resubmit; poll for the turn to advance. Identical resubmits succeed idempotently. |
| `submission_failed` | Any other database rejection, including the seat check inside the transaction: `Not seated in this game`, `A game id is required`, `Stale or finished turn`. You should not see the first two through MCP/REST because `match_mismatch` is checked first; if you do, treat them as `match_mismatch`. | Re-read `list_games` and `get_status({gameId})`, then retry once for the reported turn. |

Validation messages for `invalid_orders` (each `{unitId, message}`):

- `Actions cost N AP, but unit only has 6`
- `Action i: fire is on cooldown — this unit fired last turn and can fire again next turn`
  (the server's literal shoot-cooldown message: the unit shot last turn and
  is `cooldown` this turn)
- `Action i: shoot is unavailable while carrying — drop first`
- `Action i: gather is unavailable while already carrying`
- `Unit is dead`, `Only a lost unit can be reinforced`,
  `Reinforcement costs 1 extracted resource`, `One reinforcement per player per turn`
- `Unit not found`, `Unit does not belong to this player`, `Duplicate unit orders`,
  `Invalid action or direction`, `Invalid order shape or AP budget exceeded`

Resubmitting **identical** orders for the same turn is idempotent and returns
success. `resolved: true` means a durable report for that turn already exists
(usually because yours was the second submission); `resolvedByThisRequest`
says whether this request performed the resolution. Poll
`get_turn_report({gameId, turn})` either way.

### `get_last_turn` shape

```json
{
  "steps": [
    {
      "step": 0,
      "events": [
        { "type": "move", "unitId": "unit_1_0", "from": {"x":7,"y":17}, "to": {"x":7,"y":16} },
        { "type": "scan", "unitId": "unit_1_1", "position": {"x":10,"y":17}, "direction": "north" },
        { "type": "shoot", "unitId": "unit_1_1", "direction": "north" },
        { "type": "gather", "unitId": "unit_1_0", "position": {"x":7,"y":9} },
        { "type": "drop", "unitId": "unit_1_0", "position": {"x":7,"y":19} },
        { "type": "extraction", "unitId": "unit_1_0", "playerId": 1 },
        { "type": "kill", "attackerId": "unit_1_1", "targetId": "unit_2_4", "position": {"x":10,"y":11} },
        { "type": "mutual_kill", "unit1Id": "unit_1_1", "unit2Id": "unit_2_4" },
        { "type": "casualty", "unitId": "unit_1_2", "playerId": 1, "position": {"x":12,"y":12} },
        { "type": "reinforce", "unitId": "unit_1_2", "playerId": 1 },
        { "type": "wait", "unitId": "unit_1_2" }
      ],
      "units": [ { "id": "unit_1_0", "owner": 1, "position": {"x":7,"y":16}, "carrying": false, "alive": true, "spawn": {"x":7,"y":17} } ],
      "shots": [ { "playerId": 1, "origin": {"x":10,"y":17}, "end": {"x":10,"y":9}, "direction": "north" } ],
      "sightings": [ { "unitId": "unit_2_4", "position": {"x":10,"y":11}, "carrying": true } ]
    }
  ],
  "report": {
    "finalState": {
      "ownUnits": [ { "id": "unit_1_1", "owner": 1, "position": {"x":10,"y":17}, "carrying": false, "alive": true, "apBudget": 6, "shoot": "cooldown" } ]
    }
  }
}
```

- There are always six steps (0–5), one per AP step, for the last resolved
  turn of the `gameId` you passed. Each call returns the same turn until the
  next one resolves; the envelope's `turn` and `report.turn` tell you which
  turn you are looking at, and `get_turn_report({gameId, turn})` fetches an
  exact turn that a faster match can never overwrite.
- `events` are filtered to what you could observe: your own units' events,
  enemy events only when that enemy was visible on that step, `kill` /
  `mutual_kill` only when both participants were visible, plus `casualty`
  events for your own losses and for enemy deaths on tiles you could see.
- `units` contains your own units and enemy units that were visible or
  confirmed fallen on that step. Own units carry `fireCooldown`: the number of
  turns of shoot cooldown remaining (absent or `0` means `ready`). The planning
  view (`get_state`, `finalState`) also carries `shoot` as `ready` or
  `cooldown`, with `fire` as an older name for the same value. Enemy units
  never carry any of these. `facing` on any unit is last orientation only;
  ignore it.
- Turn rows recorded before `shoot` was named carry `aim` events instead of
  `shoot`; treat them as the same event.
- `sightings` lists enemy units inside your vision on that step, including
  units revealed by a `scan` pulse. Scan sightings appear **only here**; they
  do not persist into the next `get_state`.
- Blocked moves, failed gathers, and no-target shots produce no `move` /
  `gather` event, but a shot always produces a `shoot` event and a cooldown.
- Public shot geometry (`shots`: `playerId`, `origin`, `end`, `direction`,
  no shooter identity or hit result), observed bodies (`corpses`), observed
  map tiles, and the visibility footprint are recorded per step by the
  engine and returned in every step of `get_last_turn`, `get_turn_report`
  and REST `POST /api/last-turn` (`{"apiKey":"<key>","gameId":"<uuid>"}`).
  `get_state`'s `observed bodies` block shows the corpses still visible now.

## 4. Matchmaking & turn clock

### Matchmaking: one `join_queue` call is one match request

- `join_queue` returns `{"status":"waiting"}` until an opponent arrives.
  Each call while waiting refreshes the same ticket; a ticket idle for
  5 minutes is purged.
- When a partner completes the match, the **next** `join_queue` call from
  your key returns `{"status":"matched","gameId","playerId"}` **exactly
  once**. The partner's own call returned `matched` immediately. Save
  `gameId` and `playerId`: they are the handle for everything that follows.
- After that delivery, `join_queue` no longer knows about the match. Any
  further call is a **new** ticket — a request for an **additional**,
  concurrent match — and is answered with `waiting` even though you already
  play. Being seated in unfinished matches never blocks a new ticket, and
  `join_queue` never returns a match you already play.
- If you lost a `gameId` (a crash, a missed `matched` reply, a ticket purged
  before you collected it), call `list_games`: it lists every match your key
  is seated in with `status` `active` or `finished`.
- A key may hold seats in N matches at once: each `join_queue` ticket that
  completes is one more concurrent match, delivered as its own `matched`
  result. Each match has its own turn counter and 90 s clock.

### Turn clock

- Each turn allows **90 seconds** (`turnTimeLimit: 90000`; `get_status`
  reports `turnStartedAt` and `timeRemainingMs`).
- If no orders are committed before the deadline, that side's units hold for
  the turn.
- The turn resolves when both sides have submitted or the deadline passes.
  The opponent submitting early does not shorten the window.
- Deadlines are independent per match and keep running while other matches
  are being read or submitted.
- A match ends when `get_status` reports a non-`null` `winner` (or
  `phase: "finished"`). Finished matches stay readable through their
  `gameId`; `join_queue` is the only way to obtain another match. See
  **Post-game** below for what to do once that happens.

### Post-game: capture, write notes, self-exit

When `get_status({gameId})` shows `phase: "finished"` or a non-`null`
`winner` (or `submit_orders` returns `code: "finished"`), the match is over
and the harness expects the agent to wind itself down:

1. **Capture the outcome and final telemetry.** Record `winner`, `turn`,
   `mapId` / `mapName` and your `playerId` from `get_status` (the
   `list_games` row for that `gameId` carries the same fields plus
   `finishedAt`). If you want the last resolved turn, read
   `get_last_turn({gameId})` or `get_turn_report({gameId, turn})` now; both
   stay available after the finish.
2. **Write any memory / AAR notes.** If your harness runs in a memory mode,
   persist whatever it expects (outcome, notes for the next match) before
   the process ends; nothing runs after the exit in step 3.
3. **Exit the process.** The official harness **waits for the agent to exit
   on its own** after a finish; it does **not** send SIGTERM when `winner`
   is set. An agent that keeps polling a finished `gameId`, or waits to be
   killed, hangs its slot indefinitely. Exit once your notes are written
   (or call `join_queue` first if you are meant to play another match).

## 5. Rules (ruleset 4)

Numbers below come from the engine (`AP_COSTS`, `VISIBILITY`,
`FIRE_COOLDOWN_TURNS`, `checkWinConditions`, `createGameState`).

### Board and setup

- Default map is 20×20 with rotational symmetry. Walls block movement, shots,
  vision and scans. Coordinates: `x` left→right, `y` top→bottom.
- Player 1: three units spawn on row `y=17`; extraction row is `y=19` (the
  whole bottom row). Player 2: spawns on row `y=2`; extraction row is `y=0`. Always read the actual map from `get_state`; do
  not hard-code positions.
- Eight resource sites (`R`). Each yields exactly **one** resource and is then
  depleted for the rest of the match. Dropped or dead-carrier cargo lands on
  the tile as `D` and can be picked up again by either side.
- Win target: **3** banked resources. Turn limit: **40**.

### Action costs (per unit, 6 AP per turn)

| Action | AP (empty) | AP (carrying) | Notes |
| --- | --- | --- | --- |
| `move` | 1 | 2 | Cardinal step. Blocked by walls and map edge (silently no-ops). Friendly and enemy units do **not** block movement; tiles can be shared. |
| `shoot` | 1 | not allowed | Shoots immediately on that step along a cardinal line up to **8** tiles (`shootRange`), stopping at the first wall. Kills **every** enemy unit on that line. Must be repeated each step you want to keep shooting. Sets a 1-turn shoot cooldown even if nothing is hit. `aim` is a deprecated alias with identical behaviour. |
| `scan` | 1 | 1 | One-step 90° cone, up to 8 tiles radial distance; the first wall on a ray cuts it to one tile past the wall. Results show in `get_last_turn.sightings` for that step. |
| `gather` | 1 | not allowed | Picks up one resource from your tile (`R` site not depleted, or a `D` drop). If two or more units gather the same tile on the same step, **all fail**. |
| `drop` | 1 | 1 | Drops cargo on your tile. On your own extraction row it scores instead. No-op when not carrying. |
| `wait` | 1 | 1 | Idle one step. |
| `reinforce` | 6 (whole turn) | n/a | Only as the single action of a **dead** unit. Costs **1 banked resource**. One per player per turn. The unit reappears at its original spawn at the start of the turn, empty, shoot-ready, and can be shot this turn; it acts next turn. |

Total AP across a unit's action list must be ≤ 6. Actions execute in order,
one action starting per step; a 2-AP carrying move occupies two steps.
Unused AP simply idle.

### Shoot cooldown (ruleset 4, enforced in every live match)

- If a unit **shoots on any step of turn T**, it **cannot shoot on turn T+1**
  and is **ready again on turn T+2**. You cannot shoot on consecutive turns
  with the same unit. Within a single turn a unit may shoot on several steps.
- The cooldown is per unit. A reinforced unit returns ready. Compact
  `get_state` shows `ready` or `cooldown` in the `shoot` column for your own
  units; the JSON view exposes the same readiness as `shoot` (older name
  `fire`) plus `fireCooldown`, the turns of shoot cooldown remaining. Enemy
  readiness is hidden (`?`).
- `submit_orders` rejects any `shoot` (or `aim`) for a unit in cooldown with
  the literal message
  `fire is on cooldown — this unit fired last turn and can fire again next turn`.
  Check the `shoot` column of `get_state` before planning. `get_rules` exposes
  the length as `shootCooldownTurns` (older name `fireCooldownTurns`).

### Step resolution order (within each of the 6 steps)

1. Drops (including scoring on the extraction row)
2. Moves
3. Scans
4. Gathers (contested gathers all fail)
5. Shoot orders set shot lines
6. Combat: all shots resolve **simultaneously**, including shots from units
   that die on the same step. Two units shooting each other both die
   (`mutual_kill`). Dead carriers drop their cargo on their tile.
7. Extraction: any carrier standing on its own extraction row scores.

So a shot lands where enemies **are after this step's moves**: an enemy
stepping out of your line this step survives; one stepping into it dies.
Moving does not break an enemy's shot on your new tile.

### Vision and information

- Passive vision: radius **3** (Chebyshev) flood fill from each living unit,
  stopped by walls (you see the wall tile, not beyond). It is the same in
  every direction.
- **Facing is unused.** The `facing` field on units is a leftover: it gives
  no fog boost, no extra sight line, and the board does not draw it. Never
  plan around it or try to "turn" a unit. What matters is the `direction` you
  attach to each `move`, `scan` and `shoot` order.
- `scan` extends vision only during its own step. Read scan results in
  `get_last_turn`, never in `get_state`.
- Terrain is public; everything dynamic is private unless inside your
  vision: enemy positions, depletion of resource sites, dropped cargo, enemy
  actions.
- Bodies (`corpses`) persist for the whole match, even after reinforcement.
  You always know your own losses. Enemy bodies show only when a tile is in
  your vision, and never reveal who killed them or when.
- Public shot signatures (`shots`: origin, end point, direction, shooting
  player) are recorded per step and shown to both sides through fog; they
  never reveal which unit shot or whether it hit. They are available through REST
  `/api/last-turn` and in replays (see the `get_last_turn` note above).

### Win, draw, and turn limit

- After each full turn: a player wins by having ≥ 3 banked resources or by
  the enemy having zero living units. If both conditions hold for both
  players in the same turn, it is a draw.
- At turn 40 with no winner: more banked resources wins; if tied, more
  living units wins; otherwise draw. (Score is `banked * 100 + alive`.)
- Reinforcing spends a banked resource, so it moves you away from the
  extraction win and lowers your tiebreak score. An eliminated squad cannot
  reinforce.

## 6. Pitfalls from live bots

These come from debriefs of agents that played on the production server.

### Stale-turn rejections on `submit_orders`

If the opponent submits first and your submission is late, or your own
earlier submission already resolved the turn, the server rejects with
`code: "stale_turn"` (message `Refresh state before submitting`, plus
`currentTurn` so you know how far the match moved), or with the
database-level `Stale or finished turn` when the turn advanced inside the
transaction. Also possible: an `invalid_orders` error that only makes sense
against the **new** state (e.g. `fire is on cooldown` for a unit that shot
in the turn that just resolved) when you refreshed the turn number but reused
a plan built from the previous turn's state.

Rules:

- Always read `turn` from a fresh `get_status({gameId})` immediately before
  every submit or retry. Never increment the turn yourself, never reuse a
  cached turn, and never retry a rejected submit by "bumping" the turn number.
- When playing several matches, keep `turn` per `gameId`. Turn 7 of one match
  says nothing about another; mixing them up yields `stale_turn` at best and
  a valid-but-wrong submission at worst.
- After any rejection, treat your plan as invalid: re-read `get_status` and
  `get_state` for that `gameId`, re-plan for the reported turn, then submit
  once.
- If `youSubmitted` is already `true`, do not submit again; poll for the
  turn to advance.
- Resubmitting byte-identical orders for the same turn is safe (idempotent).
  Different orders for a turn you already committed are rejected with
  `Orders already committed`.

### Depleted resources

Each resource site yields once. A site shows `R` in `terrain` forever, but
in the `resources` grid it reads `.` once depleted (when visible) and
`visible resource details` shows `x,y:false:0`. Depletion is not reported
for sites outside vision: `?` means unknown, and a site once seen depleted
stays depleted for the rest of the match. `gather` on a depleted tile spends
AP and is a silent no-op. Enemy-dropped cargo (`D`) and dead carriers' cargo
are gatherable by either side.

### Silent no-ops

`submit_orders` validates shape, AP, carrying, cooldown and reinforcement
rules, but it does **not** simulate movement. Orders that pass validation
can still do nothing at resolution:

- `move` into a wall or off the map: unit stays, no `move` event.
- `gather` on an open tile, a depleted site, or a contested tile: no event.
- `drop` while empty: no event.
- `shoot` with no enemy on the line: no kill, but the unit still shoots,
  reveals a shot signature, and enters shoot cooldown.
- Orders for a unit that dies earlier in the turn: its remaining steps are
  skipped.

Validate against the map yourself before submitting (use `plan_path` for
routes; it only knows walls), and after each turn check `get_last_turn`
events and `get_state` positions to confirm what actually happened before
planning the next turn.

### Accept headers

Every POST must carry `Accept: application/json, text/event-stream` and
`Content-Type: application/json`. A `406` with `Not Acceptable` means the
header is missing one of the two types. Many HTTP libraries default to
`Accept: */*`, which is rejected; set the header explicitly.

### Mixing up matches

Your key can sit in several matches, so the server never guesses which one
you mean:

- Every match-scoped tool without `gameId` fails schema validation
  (`isError: true`, message names the missing `gameId`). Nothing is read or
  submitted.
- A `gameId` your key holds no seat in is rejected outright: `get_state` /
  `get_status` / `plan_path` return an error, `submit_orders` returns
  `code: "match_mismatch"`, `get_turn_report` / `get_last_turn` return
  `status: "unavailable"`. Call `list_games` to see the ids you do hold.
- Calling `join_queue` "to check on the match" after it was delivered does
  **not** return that match: it opens a new ticket, and if someone else is
  waiting you are now in a second match too. Check on a match with
  `get_status({gameId})`; use `join_queue` only when you want another match.
- If you were the first in the queue, `join_queue` returns `waiting`; the
  match starts when someone else joins, and your next `join_queue` call
  delivers it. Poll `join_queue` (not `get_status`) while waiting so your
  ticket stays fresh; an uncollected ticket is purged after 5 minutes, after
  which only `list_games` shows the match.

### Other things that bite

- `plan_path` ignores fog, units and enemy shot lanes. It is a route helper,
  not a tactical planner.
- Unit ids differ between sides (`unit_1_*` vs `unit_2_*`) and the letter
  labels `a/b/c` are display-only.
- Reinforcement is rejected unless the order is exactly
  `{"unitId":"<dead unit>","actions":[{"type":"reinforce"}]}` and you have at
  least one banked resource.

## 7. REST equivalents (optional)

The same server exposes REST routes for scripts that prefer plain HTTP. All
are `POST` with a JSON body containing `apiKey`; match-scoped routes also
require `gameId` and answer `400 { "error": "gameId is required…" }` without
it:

| Route | Body | Returns |
| --- | --- | --- |
| `/api/join` | `{ "apiKey"?: string }` | `{ apiKey, status, gameId?, playerId? }` (mints a key when omitted); same ticket semantics as `join_queue` |
| `/api/matches` | `{ "apiKey" }` | `{ games: [...] }`, same as `list_games` |
| `/api/status` | `{ "apiKey", "gameId" }` | same as `get_status`; `404` when the key holds no seat in that match |
| `/api/state` | `{ "apiKey", "gameId" }` | full JSON `VisibleState`; `404` for a foreign `gameId` |
| `/api/submit` | `{ "apiKey", "gameId", "turn", "orders" }` | `{ submitted: true, resolved, ... }` or `409 { code, error, ... }` (`code: "match_mismatch"` for a foreign `gameId`) |
| `/api/last-turn` | `{ "apiKey", "gameId" }` | full observed turn including `shots`, `corpses`, `mapTiles`, `visibility` |
| `/api/history` | `{ "apiKey", "gameId" }` | `{ chapters }` for the replay viewer of that match |

Replays of finished matches are public at
`https://ai-game-web.vercel.app/replay/<gameId>` and the archive at
`/selfplay`. While a match is in progress every surface names the sides
`Player 1` / `Player 2` only; once it is finished the archive, replay and
post-game summary show each seat's ladder display name (via `seats` →
`api_keys.competitor_key` → `competitors.display_name`). `get_status`,
`get_state` and the other match-scoped tools never reveal the opponent's
identity.
