Skip to content

Architecture

For the adjudication algorithm itself see adjudication.md; for the wire/DB shapes see data_spec.md.

Processes

Telegram Bot ──┐
React SPA ─────┼──► FastAPI (port 8000) ──► GameService ──► GameRepo ──► Postgres
DAIDE clients ─┘         │                        │
                         │                        └─ (state_json / pending_orders /
                         │                            last_resolution / order_history)
                         └── engine.Game (pure logic, no I/O) ──► src/rendering (PNG maps)

Five things talk to one Postgres database: the FastAPI HTTP server, the Telegram bot (a thin HTTP client, never touches the engine or DB directly), the React SPA, DAIDE TCP clients (a real asyncio listener, src/server/daide/, started alongside the API process — see "DAIDE protocol support" below), and the deadline scheduler background task inside the API process. The scheduler's loop sleeps on the event loop but does each 30-second tick's work (processing due turns, reminders, proposal expiry, housekeeping) on a worker thread (asyncio.to_thread), so processing a turn never stalls the API or DAIDE clients. A tick reads every active game once and then works through them, each taking seconds, so before processing a due game it re-reads it and skips it unless it is still in the phase it saw with a deadline still due; it passes that phase to GameService.process_turn as expected_phase_code, which raises StaleGameError if the stored phase has moved on. A game another path processed meanwhile is never adjudicated again with no orders. The creator's POST /games/{id}/process_turn pins the same way: it passes the phase it read as expected_phase_code, and a client may send the phase it saw in the body ({"expected_phase_code": "S1901M"}; the web and the bot's confirm button do). A phase that has moved on is a 409 with X-Error-Code: phase_moved ("Phase S1901M has already been processed: the game is now in F1901M. …"), and nothing is processed.

Package boundaries

src/engine/          # PURE rules core — stdlib only, no I/O, no DB, no rendering
  types.py            # frozen dataclasses: Location, Unit, Order variants, GameState,
                       #   Resolution, DislodgedUnit; enums (UnitKind, Season, PhaseType,
                       #   OrderType, ResultCode, GameStatus)
  map_loader.py        # .map file -> MapData; coasts first-class; topology only
  orders/parser.py     # order grammar: coasts, VIA convoy, aliases; parse + format
  orders/validation.py # the one validation path: validate(order, state, map)
  adjudicator/movement.py    # Kruijswijk fixed-point resolver — see adjudication.md
  adjudicator/retreats.py    # retreat legality + phase
  adjudicator/adjustments.py # builds/disbands/civil disorder
  game.py               # phase machine over immutable GameState snapshots
  serialization.py      # canonical GameState/Order/Resolution <-> JSON (one place)
  simple_ai.py           # dumb heuristic order generator for demo/AI-filled games

src/persistence/       # SQLAlchemy models + DAL
  database.py            # ORM models (GameModel, UserModel, PlayerModel, ...)
  database_service.py     # DatabaseService — CRUD for players/users/messages/channels/
                          #   etc.; game *state* itself is delegated to...
  game_repo.py             # ...GameRepo: state_json/pending_orders/last_resolution/
                            #   order and resolution histories

src/rendering/          # SVG -> PNG map rendering
  board.py, overlays.py,   # the board and units, order/outcome symbols, footer key,
  arrows.py, tokens.py ... #   cache; map.py is the Map namespace over them
  view_adapter.py          # GameService.view dict -> renderer inputs
  order_overlay.py         # adapts engine Order/Resolution into the overlay's order dicts
  visualization_config.py   # colors/sizes/layout config

src/server/             # FastAPI app, CLI Server, DAIDE, Telegram bot
  game_service.py          # THE single entry point from server code into the engine —
                            # wraps engine.Game + serialization + parser/validation over
                            # GameRepo. Routes/CLI/DAIDE never touch engine internals directly.
  api/routes/               # games, orders, users, auth, messages, maps, channels, admin,
                             # waiting_list, bot_outbox, archive, feedback, sandbox
  legal_orders.py           # pure: every legal order for a power this phase
  order_notes.py            # pure: why an order is impossible / what it depends on,
                            #   from the board and the power's own orders only
  telegram_bot/              # thin HTTP client over the API — see below
  daide/                      # the DAIDE TCP protocol — see below
  server.py                    # text-command CLI surface (CREATE_GAME, ADD_PLAYER, ...),
                                # used by tests; independent of the HTTP API

Key discipline: src/engine/ imports nothing but stdlib. Nothing in it knows about SQLAlchemy, FastAPI, Pillow, or JSON serialization frameworks — tests/engine/test_purity.py checks every import statement. Everything else (persistence, rendering, the HTTP/bot/DAIDE surfaces) is an adapter around GameService, which is the only thing that constructs engine.game.Game instances, calls adjudicate(), or reaches into orders/parser.py and orders/validation.py.

Two pure server-side modules sit beside GameService and take MapData + GameState directly: legal_orders.py (what a power may order) and order_notes.py (the order helper: why an order is impossible, or what it depends on; data_spec.md §Order helper notes). Both answer from the board and one power's own orders, so every client -- the web game page, the bot, the sandbox -- shows the same thing. order_notes never receives another power's pending orders: those are secret until the turn is processed.

Engine design decisions (see adjudication.md for the algorithm)

  • Immutability. Every engine type is a frozen dataclass, hashable except GameState (its ownership is a dict). Adjudication is a pure function (map, state, orders) -> (Resolution, new_state). Game wraps the current state plus a tuple of past snapshots (history); nothing mutates in place.
  • Location = (province, coast|None) everywhere. A fleet in Spain is at Location("SPA", "SC"). Armies never carry a coast. There are no hardcoded adjacency/coast tables anywhere in the engine — map_loader.py is the only reader of maps/standard.map, which is the sole topology source.
  • Kruijswijk fixed-point resolver. Per-order state UNRESOLVED/GUESSING/RESOLVED; recursive resolve with dependency-cycle detection; circular movement succeeds, convoy-entangled cycles apply the Szykman rule. Full writeup: adjudication.md.
  • Phases: S{y}M -> [S{y}R] -> F{y}M -> [F{y}R] -> [W{y}A] -> S{y+1}M -> ...; a retreat phase is inserted only when the preceding movement dislodged a unit; an adjustment phase only when some power's unit count differs from its supply-center count; SC ownership updates once, after the Fall turn settles; victory at 18 centers.

State persistence

A game row (games table) stores the whole GameState as state_json (engine.serialization.state_to_dict), not a normalized relational breakdown of units and orders. Alongside it: pending_orders ({power: [order_str]}, submitted but not yet adjudicated), last_resolution (the most recent Resolution, kept only so the resolution-map renderer has something to draw arrows from), and order_history ({turn: {power: [order_str]}}, appended on every process_turn, powering the Telegram bot's order-history view). Player-to-power assignments live in the separate players table (never engine-coupled). See data_spec.md for the exact column list.

GameService (src/server/game_service.py) is the funnel: create_game / submit_orders / process_turn / view / last_resolution / order_history. process_turn loads state_json, parses pending_orders, calls Game.adjudicate(), and persists the next state_json + last_resolution + appended order_history, then clears pending_orders. view builds the GameState-native API response shape consumed by the frontend, the bot, and DAIDE (see data_spec.md §API view shape).

Rendering

src/rendering/ renders PNGs from a GameState-derived unit/ownership view (not from engine internals) plus, optionally, order or resolution arrows adapted by order_overlay.py from Order/Resolution objects. Results are cached in-memory and on disk at /tmp/diplomacy_map_cache. This package has no engine-internal coupling beyond map_loader topology and the plain-dict view GameService.view already produces.

DAIDE protocol support

src/server/daide/ is a real implementation of the DAIDE wire protocol — interoperability with the external DAIDE bot ecosystem (DumbBot, Albert, and other standalone Diplomacy AIs). It is started as an asyncio.start_server listener alongside the deadline scheduler in _api_module.py's lifespan, on port 8432 (DIPLOMACY_DAIDE_PORT).

src/server/daide/
  tokens.py    # Token: the DAIDE byte-level vocabulary (powers, provinces+coasts, unit
               #   types, order types, commands, THX/ORD/HLO tokens) as a bidirectional
               #   registry; province coverage is asserted against
               #   engine.map_loader.load_standard_map(), never a second hardcoded list
  wire.py      # DCSP framing: IM/RM/DM/FM/EM message types over asyncio Stream{Reader,
               #   Writer}; async read_message/write_message
  clauses.py   # the encode/decode bridge between DAIDE token clauses and engine.types
               #   (Location, Unit, Order variants); decode reuses
               #   engine.orders.parser.parse_order rather than a second grammar
  session.py   # DaideSession: per-connection protocol state machine — the IM/RM
               #   handshake, then NME/IAM/HLO/MAP/MDF/SCO/NOW/SUB/NOT/GOF/MIS/TME/HST/DRW/
               #   ADM/SND dispatch (THX is outbound only: the reply to SUB), all routed through GameService (never engine
               #   internals directly)
  server.py    # DaideServer: owns the listening socket, the game a connection's NME
               #   resolves against (created lazily on first successful NME, not at
               #   listener startup — see its docstring), the power/passcode registry,
               #   and the notify_game_processed broadcast (NOW/ORD/OUT/SLO) that fires
               #   whenever GameService.process_turn runs for a game with live sessions,
               #   and the on_draw_vote hook (_api_module passes api.shared.after_draw_vote,
               #   so a DRW notifies Telegram without daide/ importing server.api;
               #   after_draw_vote in turn sends DRW to the sessions for an HTTP draw),
               #   and the on_orders_changed hook (SUB / NOT (SUB) invalidate the cached
               #   games/{id} reads, as the HTTP order routes do)

The handshake follows the DAIDE client-server sequence. After IM/RM, a client's NME ('name') ('version') seats the next free power (or gets REJ (NME ...) when all seven are taken) and is answered YES (NME ...) followed by MAP ('STANDARD'). The client may ask MAP and MDF (both served before NME too), then accepts the map with YES (MAP ('STANDARD')), which the server answers with HLO (power) (passcode) (LVL 0), SCO and NOW (a repeated YES (MAP ...) gets nothing). REJ (MAP ...) releases the power, gets OFF, and ends the session. A reconnecting client sends IAM (power) (passcode), gets YES (IAM ...), and asks for what it needs; a client HLO re-sends its HLO at any time. HLO comes only after YES (MAP ...) (or a client HLO), never straight after NME. OBS gets REJ: observers are out of scope. Every other command before a power is held gets REJ.

Retreat and adjustment replies follow the DAIDE message syntax. In a retreat phase NOW lists each dislodged unit after the units on the board as (power type province MRT (retreats)), coasts bracketed ((BUL ECS)), and MRT () when it has nowhere to go; MIS lists the dislodged units of the power that have no order yet in the same form. In an adjustment phase MIS (n) counts what is still owed after the orders already submitted: positive is disbands, negative is builds (a WVE counts as a build, since every unused build must be waived). The build count is capped at the vacant owned home centres (adjustments_owed), the same number SUB accepts before answering NMB, so a power with more centres than build sites reaches zero after its last possible build. When nothing is owed, in any phase, the reply is a bare MIS. An ORD for a unit that was dislodged carries RET: (BNC RET) for a bounced move, (RET) alone for a hold. A SUB for a unit of another power gets THX (order) (NYU) and stores nothing.

No client input escapes its session. DaideSession.run answers every framing violation with the DCSP ErrorMessage for it and then closes the connection, logging a warning, never a traceback: a token outside the DAIDE vocabulary gets 0x0E, an unknown frame type 0x08, a DM before the IM 0x02 (IM_NOT_FIRST_MESSAGE), a second IM 0x06, an RM from the client 0x0D. A client's own ErrorMessage, whatever its code, is logged and the connection closed without a reply (DCSP: its sender closes). A connection that sends no IM within IM_TIMEOUT_SECONDS (30 s) gets 0x01 and is closed; a frame whose first byte arrived but whose remainder did not within FRAME_TIMEOUT_SECONDS (30 s) gets 0x09 and is closed; an idle connection between frames is left open. A connection holds at most one power: a second NME, or an IAM on a connection that already holds a power, gets REJ, and a session that ends for any reason releases its power. Every accepted socket has TCP keepalive on (SO_KEEPALIVE, plus TCP_KEEPIDLE 60 s, TCP_KEEPINTVL 20 s and TCP_KEEPCNT 6 where the platform has them), so a seated client whose network vanishes without a FIN or RST is dropped within about three minutes and its power can be reclaimed by IAM. An OSError while a command is handled ends the session with a logged warning naming it. Writes to other sessions (broadcast_admin, relay_press, the notify_game_processed NOW/ORD fan-out) go through DaideSession.deliver, which treats a closed or closing transport (including uvloop's RuntimeError) as a dead peer: it is unregistered and closed, and delivery continues to the rest. DaideServer.stop() sends OFF to every seated session, then closes every open connection (Server.close_clients), seated or not, so shutdown never waits on a peer that does not hang up. tests/test_daide_robustness.py covers each case over a real socket.

Known, permanent limitation: press content is relayed opaquely, not parsed. DAIDE's press negotiation grammar (PRP/ALY/XDO/... nested inside SND/FRM) is the deepest part of the spec and the least essential for interoperability. This codebase syntax-checks press messages only (balanced parens, a valid recipient-power list) and forwards the token payload opaquely between clients — negotiation content is the bots' concern, not the server's. Full press-grammar parsing is out of scope by design, not a temporary gap to be closed later.

End-to-end proof this composes correctly over a real socket (not just each layer's own unit tests) lives in tests/test_daide_server.py's TestEndToEndOneFullTurnOverOneSocket — one continuous asyncio TCP connection drives IM→RM→NME→YES/MAP→MDF→YES(MAP)→HLO/SCO/NOW→SCO→NOW→SUB→THX against a real GameService/Postgres-backed game, then GameService.process_turn + DaideServer.notify_game_processed (the same calls the HTTP route/deadline scheduler make) push a real NOW/ORD notification back over that same socket.

Notifications: who gets told what, when

There are three delivery surfaces, and they are not interchangeable:

  • Telegram DM — notify_user(telegram_id, message) and notify_players(numeric_game_id, message, exclude_telegram_id=None) in api/shared.py. These write a row to the bot_outbox table and return; the bot long-polls GET /bot/outbox?wait=25 for undelivered rows and acks them (POST /bot/outbox/ack) once Telegram has accepted the message. Server code never talks to Telegram and never pushes at the bot (see Deployment and message reliability below). Players with a non-numeric telegram_id (test fixtures like "u1") are skipped, not errored. "Except the caller" below means the authenticated user's linked telegram_id (the one resolve_user_or_telegram returned), never a telegram_id in the request body: a Bearer caller could put anyone's id there. Tests observe notifications through tests/reliability_helpers.OutboxProbe. A DM may carry inline buttons (buttons= → payload.buttons): turn processed, the 10-minute reminder, "you joined" and "game is full" carry game_buttons(game_id) — 📝 Enter orders / 🗺 Map / 🎮 Game menu (a turn DM to a player with nothing to order that phase omits 📝 Enter orders), as g|{game_id}|{action}|n callbacks that the bot's game menu (telegram_bot/hub.py) answers in a new message.
  • Linked group post — also a bot_outbox row, addressed to the group's chat id, from api/shared.py (post_to_game_group, _post_turn_to_channel) and the /games/{id}/channel/* routes; telegram_bot/channels.py only formats text. Gated by the link's settings (auto_post_notifications, auto_post_maps); a no-op for a game without a group. A channel_map row names the image to send by payload.path, and the bot fetches it at delivery (a turn map it has already uploaded is re-sent by its Telegram file_id, from a bounded in-memory map, and uploaded again if Telegram refuses the id). After each processed turn k those are /games/{id}/map/turn/{k}/orders (the board as the turn began, every order drawn and coloured by its result, standoffs marked -- skipped when nobody had anything to order) and /games/{id}/map/history/{k+1} (the board it produced, dislodged units included). By turn number, never "the current map": a post delivered late still shows the turn it announces. An image the API refuses is acked as failed rather than retried, so it cannot block the rows behind it. One group post ignores the settings: DELETE /games/{id}/channel/unlink called by anyone but the bot (a web player, an admin) tells the group the game was unlinked from its web page, that it no longer gets maps or reminders, that the game is open to anyone, and how to link it again (/linkgroup <id>). It names nobody, and is queued before the link is cleared. The bot's own unlinks (/unlinkgroup) post nothing: the bot answers in the group.

A group has at most one game (games.channel_id, unique when set). Linking a game to a group that has one (POST /games/{id}/channel/link: /linkgroup, /newgame) moves the link: the old game is unlinked in the same transaction and the response's replaced_game_id names it, which the bot's reply repeats. A move takes the group from a game — which then turns up in the public list and becomes joinable from the web — so only a player of the game that loses it may make one: the Telegram user the bot names in telegram_id, or an admin. Anyone else gets 409, decided on the rows link_game_to_channel holds locked.

A game is linked to a group only from inside it. POST /games/{id}/channel/link is bot secret or admin token only (403 for a web login, a player's included), and the bot sends the id of the chat the command was typed in, after checking the sender plays the game: /linkgroup (/link_channel is its old name, refused in a private chat), and /start link_<id>, which Telegram sends to the group the player picks after the web page's t.me/<bot>?startgroup=link_<id> (in a private chat it links nothing). That web control (TelegramGroupCard, shown to a player of the game) reads GET /games/{id}/channel (players, the bot or an admin): linked, the group's channel_name (its title, sent by the bot when it links), and bot_username (DIPLOMACY_BOT_USERNAME, default IronChancellorBot) to build that link. A linked game shows the group and an Unlink button (DELETE /games/{id}/channel/unlink, also open to a web player of the game), which asks for confirmation first; the group is then told (see Linked group post above). /newgame makes one call, POST /games/create with channel_id (bot only): the game is created linked to the group or, on a 409, deleted again, never left unlinked in the public list; the bot also checks the rule before it asks. When the group's game is still being played (GET /channels/{chat_id}/game carries its status and phase_code), /newgame first posts what would happen with Replace it / Cancel buttons (ngok|{anon}{random}|{old game}|{asker} / ngno|{asker}, answered in the group, by the asker only) and creates nothing until the asker confirms; a finished game's link is replaced without asking. A command typed in a group is about that group's game, never the caller's current game: the bot asks GET /channels/{chat_id}/game (bot secret only) — /status, /viewmap, /map and /players answer for it (or say how to link one), through game_context.group_read_game; a typed id for any other game is refused, not swapped for the group's game. /status leaves out the caller's power, which would unmask an anonymous game, and ends with the same seat list /players shows: all seven powers, each with its nickname, "no nickname", "taken" (anonymous), "open" or "civil disorder" (a private /players adds a line on /nickname <name> when the caller's own seat has no nickname); a bare /unlinkgroup detaches it. Every other game command is private (the group guard). - Web client — pull-only. The SPA polls GET /games/{id}/state; nothing is pushed. Any row below is therefore "visible on next poll" for the browser, and that is not a gap to close with websockets unless someone decides it is.

The maintainer (DIPLOMACY_ADMIN_TELEGRAM_ID, optional) gets two kinds of DM: every player's /feedback (routes/feedback.py, via notify_user), and every error either process logs (telegram_bot/alerting.py's throttled AdminAlertHandler). The API's alerts are bot_outbox rows like any DM; the bot sends its own directly, since the bot's errors are mostly the ones that happen while the API is unreachable. api/error_log.py logs every 5xx the API returns at ERROR, so a route's own HTTPException(500) alerts too.

(DaideServer.notify_game_processed is a fourth, protocol-level path — NOW/ORD/OUT/SLO to connected DAIDE bots; a game that ends with no winners (BL6, the last powers conceding together, or only dummies left) sends a bare DRW once per game, since OFF means the server is shutting down and a solo SLO needs a winner. It is orthogonal to the table below and fires from both process_turn call sites already.)

The matrix. Every trigger of an event notifies the same people; this table is the one place the full picture exists.

Event Telegram DM Channel post Web client Where
Turn processed (deadline) all players, but a power that is out (eliminated or conceded) is owed no "Orders are due" and its player gets no turn DM; the power a turn eliminates (resolution.eliminated, so never a concession) is announced once, in that turn's DM to every player ("Your power ITALY has been eliminated …" to its own player, "ITALY has been eliminated from game N: it has no units or supply centres left." to the rest) and in the group post notification (opening "The turn has been processed because its deadline passed.", where a manual or auto-processed turn reads "The turn has been processed.") + orders map + result map next poll notify_turn_processed(trigger="deadline")
Turn processed (manual, or auto-processed) all players except the caller, unless the caller owes orders in a new retreat or adjustment phase notification + orders map + result map (a turn followed by phases nobody orders in posts once for the chain: see BV2 below) next poll notify_turn_processed(trigger="manual")
Game ended by a turn (a solo: 18 centres; or the turn left one power or none) all players (on a manual trigger, all except the caller): "Game N has ended: FRANCE has won with a solo victory."; the winner reads "Game N has ended: you have won with a solo victory." A turn that eliminated the last opponent reads "Game N has ended: FRANCE is the last power standing and wins." (the winner: "you are the last power standing and win"), one that left nobody "Game N has ended: no power is left, so nobody wins.", one that left only dummies "Game N has ended: only civil-disorder powers are left, so nobody wins." (GameService.ending tells them apart). The message is the turn's own DM minus the "Orders are due" and deadline lines and with the ending sentence last: "The turn has been processed for game N[ because its deadline passed].", then that player's results block, centre changes, eliminations and vacant/unordered lines as in any turn DM, then the ending; the buttons are the ended-game ones. Every player's cached game list is invalidated "🔔 Turn Processed - Game N" + "The turn has been processed[ because its deadline passed]." + the group's turn lines (disorder, eliminations, vacant/unordered) + "Game N has ended: …" + the final turn's two maps next poll notify_turn_processed(game_ended=True)
Empty phase could not be processed (BX2: processing a phase that needs nobody raised) all players: "⚠️ Game N: nobody has anything to order in Spring 1901 retreats, but it could not be processed automatically. The game's creator can move it on with ⚙️ Process turn now in the game menu (or Process turn on the web game page)." and then "Otherwise it is processed at its deadline, …" or "No deadline is set, so until then the game waits." (no fallback deadline is armed); the error is logged at ERROR, which DMs the maintainer (install_admin_alerts). One notice per failure: only a processed turn or a player's change reaches it, never a timer the same text next poll api.shared.empty_phase_failed
Deadline reminder (10 min out) only the players of powers still owing orders (orders_status.missing; nobody, and so no post, when all have ordered), once per deadline (games.reminded_deadline, claimed by a conditional update, so neither a restart nor a second worker repeats it) DM "Reminder: orders for Fall 1903 movement in game N are due in 7 minutes." (the real time left, rounded, at least 1 minute); group "⏰ Game N: orders for Fall 1903 movement are due in 7 minutes (still to come: FRANCE, ITALY; in a public game each power carries its nickname, "ITALY (Zed)"). Orders go to me in private." — check_and_send_reminders / _send_deadline_reminder
Deadline set or cleared all players except the setter the same text, prefixed "⏰ " next poll routes/games.py set_deadline
Weekly deadline schedule set or removed all players except the setter the same text, prefixed "⏰ " next poll routes/games.py set_deadline_schedule
Player joined nobody by DM while the table is being seated (seven joins would send 21), but every seated player except the joiner by DM when a vacated seat is taken over mid-game; the joiner's own "You have joined" confirmation, and a group post "X has joined game N as POWER." (a nickname in a public game, "A new player" in an anonymous one) when the game has a group — next poll routes/games.py join
Game started (the last seat filled by a join, or the last unseated power made a dummy; DF3) each seated human, one DM: "Game N has started! You play ITALY. It is Spring 1901 movement: orders are due." plus " First deadline: …" when one is set or a weekly schedule just armed it, with the game's buttons (📝 Enter orders first); dummies get none. Once per game: games.start_announced_at is claimed by one conditional UPDATE (claim_game_start_announcement), so concurrent last-seat requests cannot both announce and a later join, replace or dummy toggle never does. Two paths claim it without sending this DM: a waiting-list fill (its own "Game N created! You've been assigned …" and "now full" messages are that game's announcement) and a saved-game import (a game already under way). Arming a weekly schedule does not wait on the claim: whenever such a write leaves every seat filled and no deadline running (an imported game whose last unlinked seat is then taken), the schedule's next slot is armed whether or not the start is announced "🎮 Game N is full -- the game has begun! …" next poll api.shared.announce_game_started, from routes/games.py join and set_dummy_power
Player quit the quitter: "You have quit game N." (instead of the general notice); all other players: "POWER has left game N. …" (the vacant-seat hint and "Until then its draw vote is still needed."), or, for an eliminated power, only "POWER (eliminated) has left game N." — next poll routes/games.py quit
Player replaced all players except the replacer: "A new player has taken over Power in game N." (a nickname in a public game) — next poll routes/games.py replace
Seat marked inactive (admin) all players: "{POWER} has been marked inactive by admin and is eligible for replacement." (an eliminated power: "{POWER} (eliminated) has been marked inactive by admin.") — next poll routes/games.py mark_player_inactive
Game rolled back (admin) all players: "Game N has been rolled back by an admin to phase …" (pending orders and draw votes cleared) — next poll routes/games.py restore
Game deleted (admin) all players, sent before the rows go: "Game N has been deleted by an admin." — — routes/admin.py delete game
Dummy toggled all players: "POWER in game N is now played by civil disorder." or "… is open again -- /join N to take it." (when the toggle completes a draw quorum the draw rows apply instead) — next poll routes/games.py set_dummy_power
Game unlinked from its group by another game taking it (link_or_409: /newgame, /linkgroup, an admin; only when the game is not finished) every seated human, one DM: "Game N is no longer linked to group ; its maps and reminders now come only by DM." (plain text, the title unescaped)</td> <td>—</td> <td>next poll</td> <td><code>routes/channels.py</code> <code>link_or_409</code></td> </tr> <tr> <td>Auto-process toggled</td> <td>all players except the caller: "Game N now processes each turn as soon as all orders are in. …" or "… no longer processes turns automatically."</td> <td>—</td> <td>next poll</td> <td><code>routes/games.py</code> auto-process</td> </tr> <tr> <td>Wait flag raised or lowered</td> <td>all players except the caller: "POWER asks game N to wait before the turn is processed." or "POWER is ready in game N."</td> <td>—</td> <td>next poll</td> <td><code>routes/games.py</code> <code>set_wait_flag</code></td> </tr> <tr> <td>Deadline proposal made</td> <td>all players except the proposer and any power that is out: "POWER proposes a 24-hour deadline for game N, counted from when the proposal passes." (or "clearing game N's deadline") + "Needs K yes votes (1/K so far). Vote with the buttons below.", with ✅ Vote yes / ❌ Vote no / 🎮 Game menu buttons; when the proposer is the only active power: "POWER's deadline proposal for game N was accepted immediately (they're the only active power): deadline now …"</td> <td>—</td> <td>next poll</td> <td><code>routes/games.py</code> deadline propose</td> </tr> <tr> <td>Deadline proposal expired</td> <td>all players except powers that are out: "The deadline proposal in game N (from POWER) expired without a majority; nothing changed." (the proposer: "Your deadline proposal in game N expired without a majority; nothing changed.")</td> <td>—</td> <td>next poll</td> <td>deadline scheduler, <code>api.shared</code></td> </tr> <tr> <td>Deadline passed with seats unfilled</td> <td>all players, with the game's buttons: "⏰ Game N: the deadline passed, but the turn waits for a full table. …" + the unseated powers + "The next deadline is …" (a schedule) or "Set a new deadline once the table is full."</td> <td>the same text</td> <td>next poll</td> <td>deadline scheduler, <code>api.shared</code></td> </tr> <tr> <td>Deadline proposal vote</td> <td>all players except the voter and any power that is out: a yes vote that does not decide ("POWER voted yes … (1/4 needed)"), the proposal passing, or its rejection (the proposer reads "Your deadline proposal …"). A "no" vote that does not reject sends nothing</td> <td>—</td> <td>next poll</td> <td><code>routes/games.py</code> deadline vote</td> </tr> <tr> <td>Broadcast message</td> <td>all players except the sender</td> <td>the broadcast text (when <code>auto_post_broadcasts</code>, default on)</td> <td>next poll</td> <td><code>routes/messages.py</code></td> </tr> <tr> <td>Rumour (anonymous broadcast)</td> <td>all players, <strong>the sender included</strong>: "🕵️ Rumour in game {id}: …"</td> <td>"🕵️ Rumour in game {id}: …" (same setting)</td> <td>next poll</td> <td><code>routes/messages.py</code></td> </tr> <tr> <td>Private message</td> <td>recipient only</td> <td>—</td> <td>next poll</td> <td><code>routes/messages.py</code></td> </tr> <tr> <td>Draw vote cast (not final)</td> <td>all players except the voter and any power that is out (conceded or eliminated): "FRANCE has voted to end game N in a draw (2/7 agreed). Draw votes last until this phase is processed. Use /draw to agree." (a recipient whose power has already voted reads "You have already voted. Use /nodraw to withdraw." instead), plus the vacant-seat hint when a seat is empty</td> <td>—</td> <td>next poll</td> <td><code>api.shared.after_draw_vote</code></td> </tr> <tr> <td>Draw vote withdrawn</td> <td>all players except the voter and any power that is out: "FRANCE has withdrawn its vote to end game N in a draw (1/7 agreed).", plus the vacant-seat hint when a seat is empty</td> <td>—</td> <td>next poll</td> <td><code>api.shared.after_draw_vote</code></td> </tr> <tr> <td>Draw vote repeated, or a withdrawal with no vote to withdraw</td> <td>nobody (<code>GameService.submit_draw_vote</code> returns <code>changed: false</code>)</td> <td>—</td> <td>—</td> <td><code>api.shared.after_draw_vote</code></td> </tr> <tr> <td>Draw quorum reached → game ends</td> <td>all players except the voter: "Game N has ended in a draw shared by AUSTRIA, ENGLAND and FRANCE."; a sharer reads itself as "you" ("… shared by you, AUSTRIA and ENGLAND."). When a concession or a new dummy completed the quorum, the cause leads ("ITALY has conceded, and game N has ended in a draw shared by …"; the conceder is left out, a dummy toggle leaves nobody out). Every player's cached game list is invalidated</td> <td>"🤝 Draw - Game N" + the same sentence; no maps (no turn was processed)</td> <td>next poll</td> <td><code>api.shared.announce_draw</code> → <code>notify_game_drawn</code></td> </tr> <tr> <td>Draw voted over DAIDE (<code>DRW</code>, <code>NOT (DRW)</code>)</td> <td>the three draw rows above, to every Telegram player (a DAIDE voter has no Telegram id to leave out); a completed draw, whichever surface cast the deciding vote, sends one <code>DRW</code> to every DAIDE session (<code>after_draw_vote</code> → <code>broadcast_draw_completion</code>, idempotent per game)</td> <td>as above</td> <td>next poll</td> <td><code>DaideServer(on_draw_vote=api.shared.after_draw_vote)</code>, wired in <code>_api_module</code></td> </tr> <tr> <td>Power conceded</td> <td>all players except the conceder</td> <td>"🏳️ POWER has conceded and left game N. …" (the same sentence; none when the concession ended the game: the ending's own post says why)</td> <td>next poll</td> <td><code>routes/games.py</code> <code>concede_game</code></td> </tr> <tr> <td>Game ended by a concession or a dummy toggle (last power standing, or nobody left)</td> <td>all players except the conceder, with the ended-game buttons: "FRANCE has conceded, and game N has ended: ITALY is the last power standing and wins." (the winner: "… you are the last power standing and win."), or "…: no power is left, so nobody wins." / "…: only civil-disorder powers are left, so nobody wins." (the cause may also be "ITALY is now played by civil disorder")</td> <td>"🏆 Game N has ended" + the same sentence</td> <td>next poll</td> <td><code>api.shared.notify_last_power_standing</code></td> </tr> <tr> <td>Password reset requested (web)</td> <td>the account's linked Telegram user only: "Someone asked to reset the password of your Diplomacy website account (email). If it was you, open this link within an hour …" with the link; email is the fallback for an unlinked account</td> <td>—</td> <td>—</td> <td><code>routes/auth.py</code> <code>_send_password_reset_link</code></td> </tr> <tr> <td>Waiting list filled</td> <td>all seven placed players, each told their own power ("🎮 Game N created! You've been assigned POWER.", with the game's buttons), then a second DM to every player, "Game N is now full. Good luck to all players.", with the game's buttons</td> <td>—</td> <td>—</td> <td><code>api/routes/waiting_list.py</code></td> </tr> </tbody> </table> <p><strong>What the turn-processed DM says</strong> is per player and names the new phase in words (<code>api.shared.turn_message</code>, fed by <code>GameService.phase_duties</code>, which uses the same <code>powers_with_orders_to_give</code> set <code>orders_status</code> waits on, civil-disorder dummies left out):</p> <ul> <li>movement — "Orders are due for Spring 1902 movement.";</li> <li>retreat — to each dislodged power, every dislodged unit with its retreat options as the adjudicator computed them ("…Fall 1901 retreats: your orders are due.\nYour A BUR was dislodged: it may retreat to GAS, PIC, RUH, or disband. With no order it is disbanded.", or "…has nowhere to retreat: it must disband."); a power whose dislodged units <em>all</em> have nowhere to retreat owes no order (<code>phase_duties</code>' <code>forced_disbands</code>): its player is told to wait, plus "Your A BUR was dislodged and has nowhere to retreat: it is disbanded, no order needed.", and the channel post does not list it as due;</li> <li>adjustment — the build count (<code>adjustments_owed</code>, plus how many more are waived for want of a free home centre) and the free home centres themselves, or the disband count ("You may build 2 units (free home centres: MAR, PAR; 1 more waived: no free home supply centre).", "You must disband 1 unit.");</li> <li>a power owed builds with no free home centre at all owes nothing, but is told so (<code>phase_duties</code>' <code>waived_builds</code>): "Your 2 builds are waived: no free home supply centre." under its wait line (or, if the next phase needs nobody, in the DM that carries the folded lines). The after-phase waived notice (below) does not repeat it;</li> <li>a player with nothing to order in a retreat or adjustment phase is told so and to wait;</li> <li>units an adjustment or retreat phase removed on its own (civil disorder, a bounced or unordered retreat) are told under the power's "Your results for Winter 1901 builds:" block, with the header the ordered results get.</li> </ul> <p><strong>A phase nobody has anything to order in runs at once</strong> (BV2): a retreat phase whose only dislodged units have nowhere to go, or an adjustment phase in which only dummies build or disband (<code>GameService.phase_needs_nobody</code>: a retreat or adjustment phase whose <code>powers_with_orders_to_give</code> are all dummies). Every trigger finishes a processed turn through <code>api.shared.after_turn_processed</code>, which calls <code>finish_processed_turn</code> and then, while the new phase needs nobody and the table is full, processes it through the same phase-checked <code>process_turn(expected_phase_code=…)</code>, whatever <code>auto_process</code> says (a <code>StaleGameError</code> means another worker did it). Each processed phase gets its snapshot, but no player DM and no group post of its own: what that DM would have said about the turn before it (the results block, a trapped unit's "has nowhere to retreat" notice, units removed) is folded into the DM for the phase that needs them, after its first line. The group, likewise, gets one post for the whole chain, as for any turn (<code>FoldCarry</code>): one text naming the phase that needs orders ("Fall 1901 movement: new orders are due …"), carrying the folded phases' group lines (each unit disbanded for want of a retreat — "FRANCE: A BEL was dislodged and had nowhere to retreat: it was disbanded." — the turn's disorder, eliminations, vacant/unordered lines), then two maps: the orders map of the turn the players ordered, and the board after the last folded phase (<code>/map/history/{last turn + 1}</code>), both captioned with the ordered phase ("Spring 1901 movement: the result"), since the folded phases had nothing to order. The ordered phase's deadline is spent with it; the next one is armed once, for the phase that needs orders, and "No deadline is set for …" goes with it when the ordered phase had one (<code>process_turn</code>'s <code>deadline_spent</code>). If the empty phase cannot be processed here (another worker got there first, or processing it raised), the folded lines go out on their own, and so does the group post the fold held back ("Spring 1901 retreats: nobody has anything to order." with its lines and maps); on an error the game stays in the empty phase, which gets the deadline any new phase gets (the schedule's next slot, or none), and the turn before it stands: the route still answers 200 with that turn's resolution, and the scheduler goes on to the next game. <code>POST /games/{id}/process_turn</code> answers with the phase the game is in after all this. The DAIDE <code>ORD</code>s for each processed phase carry that phase's resolution, read when it was processed (not the stored <code>last_resolution</code>, which the empty phase after it has replaced by the time the broadcast runs). An <code>ORD</code> names the true order: fleets as <code>FLT</code>, a supported or convoyed unit with its real power (both from the resolution's <code>units</code>, the pre-adjudication board), and a convoyed move's <code>VIA (...)</code> lists the fleets that ordered that convoy, in route order. <code>SUB</code> merges per unit (<code>submit_orders(merge=True)</code>): an order replaces only the earlier order for the same unit. A bare <code>SUB</code> is <code>HUH (SUB ERR)</code>. In an adjustment phase a build, waive or removal past the power's count is refused (<code>submit_orders(keep_stored=True)</code>) and the orders already submitted stand: <code>NMB</code> for a build or waive, <code>NMR</code> for a removal (the web and bot clients instead let the newest replace the oldest). THX notes: an order of the wrong phase <code>NRS</code>, a retreat or disband for a unit owing none <code>NRN</code> (<code>NSU</code> when the province has no unit at all), a move to the unit's own province <code>FAR</code>.</p> <p>A phase can also become empty while it stands (BX1): the creator makes the only power still owing a retreat, build or disband a dummy (<code>POST /games/{id}/dummies</code>), that power concedes (<code>POST /games/{id}/concede</code>), the seat completing the table is taken (<code>POST /games/{id}/join</code>) while the phase needs only dummies, or an admin restores a game from the archive in such a phase (<code>POST /games/import</code>, after everything it restores; its response's <code>auto_processed</code> counts the phases processed, and its <code>deadline</code> is then the new phase's). Each of those routes, after its change is committed and announced, calls <code>api.shared.process_if_phase_needs_nobody</code>, which processes the phase through the same phase-checked <code>process_turn</code> and <code>after_turn_processed</code> when it needs nobody and the table is full, whatever <code>auto_process</code> says, so the players read the change before the turn it caused. A <code>StaleGameError</code> or <code>GameOverError</code> means another worker (or the game's end) got there first; an error processing it is logged and leaves the phase under its current deadline, and the route still answers 200 for the change. Either failure (here or in <code>after_turn_processed</code>) goes through <code>empty_phase_failed</code>, which tells the players and the group the phase is stuck and how to move it (see the notification table). A player quitting is not such a change: the vacated seat's power still owes its orders.</p> <p><strong>Each player is told what the turn did to their own units</strong> (BW1), in a block after those lines (<code>GameService.turn_outcomes</code>, <code>api.shared.turn_results_lines</code>): "Your results for Spring 1901 movement:" and then one line per unit, sorted by province, worded like the web's results list:</p> <ul> <li>movement — "A PAR - BUR bounced.", "F BRE - MAO succeeded.", "A MUN S A PAR - BUR was cut.", "A KIE - BUR was invalid, so the unit held.", "A LON - BEL VIA failed: no convoy route." (or, when a fleet convoying it on a possible route was dislodged, "A LON - NWY VIA failed: the convoy was broken when F NTH was dislodged."), a support void because it would dislodge the supporter's own unit (DATC 6.D.10) "A VIE S A VEN - TRI had no effect: it would dislodge your own F TRI.", a legal support with nothing to support "A GAS S A SPA - MAR had no effect: A SPA did not move to MAR." (a support to hold of a unit that moved: "… had no effect: A SPA moved."; one that is out of reach or names no unit stays "was invalid, so the unit held") (all from <code>GameService.result_reason</code>, which the web shows too), "A BER held.", "A MUN held (no order)."; a dislodged unit names its attacker, power only, never a nickname: "F TRI was dislodged by A TYR (ITALY).", "A VIE - TRI bounced; dislodged by A BOH (RUSSIA)."; a bounced move names who it met (<code>bounce_rivals</code>, from the turn's other results; the web's entries carry <code>bounced_off</code> / <code>bounced_with</code>): "A VIE - GAL bounced off RUSSIA's A GAL." (a unit that kept the province, or swapped with the mover), "A VIE - GAL bounced (RUSSIA's A WAR also moved there)."; a power that ordered none of its several units gets one line: "No orders, so F BRE, A MAR and A PAR held.";</li> <li>retreat — "F TRI retreated to ALB.", "A BUR was disbanded." (a disband it ordered);</li> <li>adjustment — "A PAR was built.", "F KIE was disbanded." (a disband it ordered);</li> <li>after the turn that changed centre ownership (a Fall turn), a last line for each power whose centres changed: "Centres: +BEL, -TRI (now 5)." (from the resolution's <code>centres</code>).</li> </ul> <p>"Held (no order)" is read from the resolution's <code>unordered</code> mark, so an order refused at submission shows up here as the unit holding. The block leaves out what the DM's own notices already say: a trapped unit's disband and waived builds (below). A bounced or unordered retreat disband and a civil-disorder disband are lines of the same block (under its header, even when the power has no other result). A player holding several powers gets a block per power, headed "As FRANCE, your results for …:". The channel post carries no one's results.</p> <p>The DM addresses its reader as "you"; only a player owing orders for more than one power is told which is which ("your orders are due for AUSTRIA and ITALY", "Your F ION (ITALY) was dislodged…", "As FRANCE, you may build 1 unit."). The DM is plain text (no <code>parse_mode</code>). The channel post names the phase too, and in a retreat or adjustment phase the powers that owe orders. The caller of a manual process is skipped unless they owe orders in a new retreat or adjustment phase, or civil disorder or a bounced retreat removed one of their units (below): their HTTP response carries the resolution, not their retreat options or build count, and does not single out a civil-disorder removal.</p> <p><strong>A civil-disorder removal is announced.</strong> When the processed turn was an adjustment in which a power ordered fewer disbands than it owed, the units the engine removed for it (the results marked <code>civil_disorder</code>, read by <code>GameService.civil_disorder_disbands</code>) get one more line, in that power's DM and in the channel post (<code>api.shared.civil_disorder_line</code>):</p> <ul> <li>DM — "You were 2 disbands short, so F KIE and A MUN were disbanded (civil disorder)." or "You were 1 disband short, so A SIL was disbanded (civil disorder)." (true whether it sent none, too few, or void ones) ("As GERMANY, you were …" for a player holding more than one such power);</li> <li>channel post — the same sentence about the power: "FRANCE was 2 disbands short, so …", "GERMANY was 1 disband short, so …", one line per power, civil-disorder dummies included.</li> </ul> <p><strong>A unit a retreat phase removed without its power choosing it is announced the same way.</strong> <code>GameService.retreat_disbands</code> reads the processed retreat phase's results: a <code>Retreat</code> that <code>BOUNCE</code>d and a <code>civil_disorder</code> disband carrying <code>retreat_options</code>. Each gets one line in its owner's DM (prefixed "As FRANCE: " for a player holding more than one such power) and, prefixed with the power, in the channel post:</p> <ul> <li>"A MAR's retreat to PIE bounced (FRANCE and ITALY both retreated there): it was disbanded." ("FRANCE retreated 2 units there" when one power bounced its own units);</li> <li>"A WAR had no valid retreat order and was disbanded." (no order, or one that was rejected; the line does not say "civil disorder", which a present player did not cause).</li> </ul> <p><strong>A build waived without the power's asking is announced.</strong> <code>GameService.waived_builds</code> reads the processed adjustment's <code>WAIVE</code> results for a power that left builds unused (it sent no adjustment orders, or ordered fewer builds than it was owed), minus the <code>WAIVE</code> orders it sent itself, capped at the free home centres it had (a power with no free centre, or a dummy, is not announced). Its DM gets "Your 2 builds were waived: no orders came in." when it ordered nothing, or "Your 1 build was waived: it was not ordered." ("they were not ordered" for several) when it ordered some builds (prefixed "As FRANCE, your " for a player holding more than one such power), and the channel post "FRANCE: 2 builds were waived: no orders came in."</p> <p><strong>A build the power waived itself is acknowledged to it alone.</strong> <code>GameService.chosen_waives</code> counts the explicit <code>WAIVE</code> orders in the processed adjustment; the power's results block (so a power whose only adjustment was a waive still gets its block) ends "1 build was waived." or "2 builds were waived.". The group post does not mention it: unlike a waive for want of orders, nothing was missed.</p> <p>These lines come before "Next deadline: …", which still ends the DM and the post: on the first line's end when the DM is one line, on its own line otherwise. When a weekly schedule armed the new phase's deadline, the turn-processed DM and channel post end with "Next deadline: …", and the game-started DM with "First deadline: …". When the phase just processed had a deadline and the new one has none, they end with "No deadline is set for <phase>. To set one, use /deadline …" instead, in its own paragraph (the channel post, where <code>/deadline</code> is refused, says "A player can set one from the game menu in a private chat with the bot (/game <id>)." instead). A deadline announcement ("FRANCE set the deadline for game N to … (6h left)." -- the setter's power and the time left, to the nearest minute) adds "This deadline covers the current phase only." <code>POST /games/{id}/deadline</code> refuses a deadline at or before now (422, "That deadline has already passed. Choose a time in the future."). After a processed movement turn, a power whose seat is vacant (its player quit; not a dummy) and which still has units and ordered nothing that turn (orders it sent before quitting stand) adds "<Power>'s seat is vacant: its units held." to every DM and to the group post. A movement turn processed because its deadline passed also adds "<POWERS> had not ordered: their units held." (or "<POWER> had not ordered: its units held.") for each seated power with units and no orders; a player's DM leaves out their own powers (their "No orders, so ... held." line says so already) and drops the sentence when none is left, while the group post keeps the full list. A disband DM ends "With no order, civil disorder picks which units are disbanded." A deadline announcement and a proposal-passed notice give the time as the weekly schedule reads it ("2026-09-28 13:00 UTC (Mon 16:00 Europe/Helsinki)"); both say the deadline covers the current phase only. The draw-vote and withdrawal DMs and the deadline-proposal and vote DMs ("FRANCE proposes a 24h deadline for game N, counted from when the proposal passes. ...") go only to players with a power still in the game: <code>notify_players(..., skip_out=True)</code> leaves out a player whose every power is conceded or eliminated, as the turn DM does. The game-ended announcement still goes to everyone.</p> <p><strong>How a player is named</strong> depends on the game (<code>games.anonymous</code>, fixed at creation). Every notification that names a power — join, quit, takeover, wait flag, draw vote, concession, deadline proposals and votes, private messages and broadcasts (DM and group post) — names it through <code>api.shared.power_label</code>: <code>FRANCE</code> in an anonymous game, <code>FRANCE (Anna)</code> in a public one (the power alone for a player with no nickname). A join or takeover in an anonymous game says "A new player has joined … as ITALY". The bot relays every message between players, so in an anonymous game nobody learns who holds a power except by being told. The same rule holds for API reads (<code>api.shared.player_rows</code>; <code>docs/specs/data_spec.md</code> §4).</p> <p><strong>A DM about its reader's own power says "you"</strong> instead of naming it: the turn-processed DM above, the solo winner and the draw's sharers, and the proposer of a deadline proposal that is voted down ("Your deadline proposal in game N was voted down; nothing changed.") or expires ("Your deadline proposal in game N expired without a majority; nothing changed."). Everyone else's DM and the group post keep the power's label. <code>api.shared.notify_players(own=…)</code> picks the reader's text from the powers they hold. Events whose actor is the reader skip them altogether (the voter, the proposer, the conceder: the matrix's "except").</p> <p>A <strong>rumour</strong> (<code>POST /games/{id}/broadcast</code> with <code>anonymous: true</code>; the bot's <code>/rumour</code>, or "🕵️ Rumour (anonymous)" on the game menu's Messages screen) names nobody in any game: not the power, not the nickname, in the DMs, the group post or <code>GET /games/{id}/messages</code> (only the sender sees it as theirs). The sender is stored and appears only in the admin-only export. Unlike a signed broadcast, a rumour's DM goes to every seated player, <strong>the sender included</strong>: the same text, queued in the same <code>notify_players</code> loop, with no "you sent this" marker. Left out, the sender would be the one player without the DM, and players comparing notes could name them. The sender still gets the bot's "Rumour spread" reply (or the queue's delivery report) as well.</p> <p><strong>Message text</strong> (<code>routes/messages.py</code>, the same rule for a private message, a broadcast and a rumour): blank or whitespace-only text is a 400 ("A message cannot be empty."), and so is text longer than <code>MAX_MESSAGE_LENGTH</code> = 3500 UTF-16 code units ("A message can be at most 3500 characters long (this one is N)."). Telegram counts its 4096-character limit in UTF-16 units, so 3500 leaves room for the longest heading a DM or group post puts in front of the text; a message that didn't fit would be dropped by the bot as a permanent send error. The bot shows the 400's reason to the sender; the web composer has <code>maxLength</code> 3500 (a JS string length counts the same units), shows the characters left from 3000 on, and won't send blank text. <strong>Reading</strong> (<code>GET /games/{id}/messages</code>): no credentials reads the broadcasts only; a valid Bearer token, or <code>telegram_id</code> with the bot secret, adds the caller's own private messages. On this and every other request, GET or write, the bot sends the secret only in the <code>X-Bot-Secret</code> header: never in the URL, where it would end up in access logs and in error text, and never in a JSON body, which its offline queue stores on disk. A <code>bot_secret</code> query parameter is ignored, so a secret in a URL authenticates nothing (no credentials leak into logs from a request that works), and so is a <code>bot_secret</code> in a JSON body: the header is the only place a route reads it. A write the bot queued on disk under an older release, whose stored body still holds one, delivers anyway, because the bot drops it and sends the header at delivery time; credentials that are present but don't check out (an invalid or expired token, a <code>telegram_id</code> without the secret) are a 401, never a silent fall-back to the broadcasts-only view.</p> <p>A draw is announced once. A draw keeps the phase code, so the phase check alone cannot stop a second request that loaded the board before the draw committed (a double tap, or the web and the bot at once). <code>GameService.submit_draw_vote</code> passes <code>refuse_completed</code> to both <code>GameRepo.modify_draw_votes</code> and <code>save_state</code>. The row is locked, a finished game is refused and the late request gets a 409 that says how the game ended. It is never recorded as a vote ("(1/7 agreed)") and never announced as a second draw. A concession is guarded the same way: <code>GameService.concede</code> passes <code>refuse_completed</code> to <code>GameRepo.modify_state_json</code>, so a concession loaded before a draw committed is a 409 that says how the game ended, and never writes its still-active board over the finished game. The concession itself is a locked read-modify-write of <code>state_json</code>: the conceding power's units, dislodged units and centres are removed from the board read on the locked row, not from the one the request loaded, so two powers conceding at once both leave the board (a write of the loaded board put the first one's units and centres back). A concession from a phase that has since been processed is a 409.</p> <p>The draw rows need their own call because the game is finalized inline the moment quorum is reached and the outcome goes to the caller only. <code>GameService._end_if_draw_agreed</code> decides and writes in one transaction on the game row taken <code>FOR UPDATE</code> (<code>GameRepo.end_game_if</code>): it reads the board, the votes and the dummies on the locked row, and if every power in the quorum has voted yes writes <code>Game.draw()</code>'s board as <code>save_state</code> would. <code>refuse_completed</code> lets only the first of two writes completing the quorum at once end and announce the game. Every write that can complete a quorum commits its own change and then calls it: a yes vote (<code>submit_draw_vote</code>), a concession and a seat made a dummy, the last two because they take a power out of the quorum. Because each decision reads every input under the lock, of two such writes at once the one deciding second sees both; decided on separate unlocked reads, a vote and a dummy toggle could each miss the other's write and leave a completed quorum running. A draw completed by either is announced exactly as a voted one (<code>api.shared.announce_draw</code>: DAIDE <code>DRW</code>, the deadline cleared, every player's cached game list invalidated, the DM and the group post). The game is then <code>COMPLETED</code>, so the deadline scheduler skips it (<code>get_games_with_deadlines_and_active_status</code>) and <strong>no later turn-processed fan-out covers for it</strong>; without the explicit notification six of seven players would find out by refreshing. A concession is announced for the same reason.</p> <p>A non-final draw vote is announced too, deliberately: a draw is the one outcome every power holds a veto over, so discovering that one is being negotiated should not require running <code>/status</code>.</p> <p><strong>A turn is processed only at a full table</strong>: every power has a seat row (held, or vacated by a player who quit) or is a dummy (<code>api/shared.py</code>'s <code>seats_filled</code> / <code>unseated_powers</code>). All three triggers check it. The creator's <code>POST /games/{id}/process_turn</code> answers <strong>409</strong> naming the empty seats (<code>3 powers are unseated (Austria, Italy, Turkey): seat players or mark them as dummies.</code>) with the header <code>X-Error-Code: seats_unfilled</code>, whoever calls it, bot secret and admin token included. The web switches on the header and shows the message as is; the bot reads <code>unseated</code> from <code>GET /games/{id}/orders_status</code>, skips its "process anyway?" confirm when it is not empty, and shows the 409's message. On the opening phase (S1901M) a non-empty <code>unseated</code> also makes the bot's <code>/status</code> and game menu say "Game N hasn't started: waiting for K more players (...). Others can join with /join N" instead of the turn, waiting-on and draw-vote lines, drop the order buttons, and answer a stale order button (<code>/orderall</code>, <code>/selectunit</code>, the menu's) with that same text. <code>maybe_auto_process</code> processes nothing. When a deadline passes, the scheduler does not process the game; it spends the deadline, so it does not find it again every tick (a weekly schedule moves to its next slot, a one-off deadline is cleared; filling the last unseated power arms a scheduled one again), and tells the players and the game's group, naming the empty seats and the next deadline if there is one. It spends the deadline with a compare-and-set (<code>DatabaseService.replace_game_deadline_if_unchanged</code>): only while the game is still in the phase, with the deadline, the scheduler saw. A deadline armed meanwhile (the last seat filling) is kept, and no notice goes out. The bot's demo game is full from the start: Germany plus six dummies. The DAIDE listener's game (<code>games.daide</code>) is exempt: its seats are live DAIDE connections held in memory, not seat rows. A seat its player quits is never unseated: its row stays, so quitting leaves the deadline as it is, the scheduler processes the turn at it (the vacant power's units hold, as for any power without orders), and retaking the seat changes no deadline -- there is none to re-arm.</p> <p><strong>Nothing is played before the game starts.</strong> A game has started once its table is full (as above) or a turn has been processed; a game that has run a turn stays started even if a dummy seat is reopened later (that holds up only processing). Until then <code>POST /games/set_orders</code>, <code>POST /games/{id}/draw_vote</code> and <code>POST /games/{id}/concede</code> answer <strong>409</strong> with the header <code>X-Error-Code: seats_unfilled</code> and the detail <code>Game 2 hasn't started: 1 power is unseated (Russia): seat players or mark them as dummies.</code>, naming every open power (<code>api/shared.py</code>'s <code>require_started</code>). A power conceding in the lobby would otherwise be dead once the table filled. Orders a game already holds when it loses (or never had) a full table stay stored and are adjudicated as usual once it fills; reading the board, the pending orders and the order status is unaffected. A finished game is left to the service, which answers with how it ended.</p> <p>The web game page mirrors this. The API exposes no "started" flag, so the page derives the lobby: the opening phase (<code>S1901M</code>) with a power that has neither a seat row in <code>/players</code> nor dummy status. It then shows "Waiting for N more players" naming the open powers, and hides the turn-status card, the "You still need to submit orders" line and the order form; messages and the players list stay. Any action refused with <code>seats_unfilled</code> shows the server's own detail, not the generic stale-write text every other 409 gets.</p> <p><strong>Deadlines are never imposed by the server.</strong> A game has a deadline only when a player chose one: set explicitly via <code>POST /games/{id}/deadline</code> (the bot's <code>/deadline <game_id> <hours|clear></code>, or a majority vote through <code>deadline/propose</code>), or armed from the game's <strong>weekly schedule</strong>. A deadline is scoped to its phase: the write that adjudicates the phase spends it (<code>GameRepo.save_state</code> clears <code>deadline</code> and <code>reminded_deadline</code> on the locked row, in the same transaction as the phase change, so the deadline scheduler never sees the new phase with the old phase's deadline past due), <code>finish_processed_turn</code> then arms the new phase's deadline if a weekly schedule gives it one (and leaves alone one set for the new phase in between), and an admin restore to a snapshot (<code>POST /games/{id}/restore/{snapshot_id}</code>) drops the discarded phase's deadline and gives the restored phase the one a newly entered phase gets. <code>games.deadline</code> is stored as naive UTC; every API field that carries a deadline (<code>GET</code>/<code>POST /deadline</code>, <code>POST /deadline/schedule</code>, an accepted proposal, the archive restore) returns it as aware UTC ISO (<code>2026-10-27T18:00:00+00:00</code>, via <code>shared.utc_iso</code>), so a browser does not read it as local time. The web client also parses a naive deadline string as UTC (<code>parseUtc</code>).</p> <p><strong>Weekly schedules</strong> (<code>server/deadline_schedule.py</code>, <code>games.deadline_schedule</code>) are a standing choice such as "Mon, Wed, Fri at 16:00 (Europe/Helsinki)", set by any player via <code>POST /games/{id}/deadline/schedule</code> (the bot's <code>/deadline <game_id> schedule mon,wed,fri 16:00 [timezone]</code>) or at creation (<code>deadline_schedule</code>/<code>deadline_timezone</code>). While a game has one, each phase's deadline is armed to the next slot at least an hour away (<code>MIN_NOTICE</code>, so a turn processed at 15:55 is not given a five-minute phase): when the game fills, when the schedule is set on a started game, after every processed turn, in <code>finish_processed_turn</code> (and after a failed deadline run, so it retries at the next slot), and after an admin restore or an archive import. Slot times are wall-clock times in the schedule's timezone, so they hold across daylight saving. Every phase type gets the next slot, retreats and adjustments included. A one-off <code>POST /deadline</code> (or an accepted proposal) overrides only the current phase; removing the schedule leaves the current deadline and arms none after it.</p> <p><strong>Conceding removes the power's units <em>and</em> releases its supply centres</strong> (they become neutral, like the unowned centres at game start), so <code>Game.eliminated_powers()</code> reports it at once. Ownership otherwise persists until a unit stands there, so a conceded power that kept its centres would be owed builds at the next Winter and could walk back in. <code>/quit</code> is the other path: the seat is vacated for a replacement and the board is untouched. A finished game refuses <code>/quit</code> (409, "Game N is already over; there is no seat to quit."). A vacant seat's draw vote stays required, since the seat can be refilled: the quit announcement says "Vacant: Germany. Someone can take the seat with /replace N GERMANY, or the game's creator can make it a dummy with /dummy N GERMANY. Until then its draw vote is still needed." (with two or more vacant seats the commands say <code><power></code>), and <code>POST .../draw_vote</code> and <code>GET .../draw_vote_status</code> carry <code>vacant</code> (the vacant powers whose vote is still missing), which the bot's <code>/draw</code> reply and the vote announcement repeat.</p> <p><strong>An eliminated power has left the game</strong> (it conceded, or lost its last unit and centre; <code>GameService.is_eliminated</code>, false once the game has ended). While the game goes on it cannot concede again (409 <code>FRANCE has already conceded</code>, not announced a second time), vote on a draw (409 <code>... has been eliminated from game N; it cannot vote on a draw</code>), send private or broadcast press or a channel broadcast (409 <code>... it can no longer send messages</code>), and nobody can take its seat back through <code>/join</code> with that power, <code>/replace</code> or a random join (409 <code>... its seat cannot be taken</code>; a random join skips it), or raise a wait flag (409 <code>... it cannot ask the table to wait</code>; lowering one is accepted): conceding lowers the flag it held, and a flag still stored for a power out of the game holds up nothing. The service refusals are <code>PowerEliminatedError</code>, a <code>GameOverError</code>, so every route already mapping that to 409 maps them. <strong>When a concession or a processed turn leaves one power standing, the game ends with it as the sole winner; when it leaves none, or leaves only civil-disorder dummies (two or more: nobody is left to play them), the game ends with no winners</strong> (<code>COMPLETED</code>, <code>winners</code> empty). A seat its player quit is not a dummy: it can be taken again, so it keeps the game going. Making the last such seat a dummy (<code>POST /games/{id}/dummies</code>) ends the game the same way. All of these go through <code>GameService._last_standing_end</code> (<code>Game.draw</code> narrowed to the survivors, or to nobody). It is a server rule, not the engine's: under the rules adjudication alone can only eliminate every other power by taking all their home centres, which is already an 18-centre solo, so only after concessions (whose centres turn neutral) can a survivor be short of 18; and the engine's DATC boards hold only a few powers, which it must not end. A processed turn applies it before its one <code>save_state</code>, so the end and the turn are one write and one announcement; its <code>save_state</code> is also guarded by the dummies it was decided on (<code>expected_dummy_powers</code>), so a seat made a dummy mid-adjudication, whose own check still saw the board before the turn, makes the turn adjudicate again rather than leave only dummies playing. After a concession or a dummy toggle it is <code>_end_if_last_standing</code>, decided and written like a draw on the locked row (<code>end_game_if</code>), so two last powers conceding together leave no winner rather than crowning one who left. The dummy set itself changes only through the locked <code>GameRepo.modify_dummy_powers</code> (two seats made dummies at once both stay; a game that ended meanwhile is a 409), which reads who holds each seat under the same lock; a join or replace writes its seat (<code>DatabaseService.create_player</code> / <code>claim_vacant_seat</code> with <code>refuse_dummy</code>) only after taking that lock and finding the power is not a dummy. So a seat taken and the same seat made a dummy serialize: the second is refused (400 "held by a player" for the toggle, 409 "played by civil disorder" for the join). Every one of these takes only the game row's lock, one transaction at a time, so they cannot deadlock with each other or with the other <code>modify_*</code> paths. Only the concession that ended the game announces it: one landing at the same moment finds the game ended and returns it as ended, with no "play on" notice and no auto-processing. The concede response then carries <code>game_status: "COMPLETED"</code> and <code>winners: ["GERMANY"]</code>, and instead of the concession notice <code>notify_last_power_standing</code> clears the deadline, invalidates every player's cached game list, tells the players (the winner reads "you are the last power standing and win"; with nobody left, "no power is left, so nobody wins"; with only dummies left, "only civil-disorder powers are left, so nobody wins") and posts to the game's group. A dummy toggle that ends the game is announced the same way, led by "GERMANY is now played by civil disorder", instead of the plain dummy notice. The conceder, left out of that, is told by the reply to their concession (the bot: "You have conceded game N, and it has ended: ...").</p> <p><strong>A group broadcast (<code>POST /games/{id}/channel/broadcast</code>) is posted as the caller's own seat.</strong> A web user's broadcast carries their seat's power whatever the body's <code>power</code> says; naming another power is a 403 <code>You do not hold ENGLAND in game N</code>. The bot or an admin may name a power only if the Telegram user in <code>telegram_id</code> holds it (else the same 403), or omit it for a public broadcast. A player whose power is eliminated cannot post either way.</p> <p><strong>Seat writes go through <code>DatabaseService.assign_player_seat</code></strong>, never through attribute assignment on a row returned by a DAL getter — those rows are detached the moment the getter's session closes, and <code>DatabaseService.commit()</code> is a no-op, so such writes are silently discarded. A vacant seat is a row with <code>user_id NULL</code> and <code>is_active False</code>; <code>/join</code> takes it over the same way <code>/replace</code> does (the web client lists such seats as "Open"); <code>_authorize_power</code> treats it as held by nobody.</p> <p><strong>Private press belongs to the seat, not the person.</strong> <code>routes/messages.py</code> reads private messages by <code>recipient_power</code>, so whoever takes a seat (<code>/replace</code>, <code>/join</code> on a vacant seat) reads every message sent to that power before they held it: the newcomer learns what was promised to the power they now play. This is the maintainer's decision (issue #253).</p> <p><strong>A <code>COMPLETED</code> game accepts no writes, except press.</strong> <code>/message</code> and <code>/broadcast</code> stay open on purpose: a post-mortem chat is a normal Diplomacy custom (BZ5). <code>GameService.submit_orders</code>, <code>process_turn</code>, <code>submit_draw_vote</code> and <code>concede</code> all raise <code>GameOverError</code> (a <code>ValueError</code>, deliberately <em>not</em> an <code>OrderError</code> — routes map that to 404, and a finished game is found) once <code>state.status is COMPLETED</code>; the routes answer <strong>409</strong> with a message naming the outcome (<code>Game 12 is drawn between FRANCE, GERMANY; no further orders are accepted</code>, the clause fitted to the action), the bot shows that <code>detail</code> verbatim, and the DAIDE session answers <code>REJ</code>. <code>orders_status</code> reports no active or missing powers, <code>legal_orders</code> offers nothing (empty <code>units</code>, <code>orders_by_unit</code>, <code>orders</code>), and <code>draw_vote_status</code> of a draw-ended game reports the sharers as the votes (quorum reached); of a game ended any other way it reports no required, voting or missing powers. <code>/replace</code> and <code>/join</code> answer 409 on a finished game, deadline withdraw likewise, and <code>GET .../deadline</code> shows no pending proposal for one.</p> <p><strong>Rules for adding a notification.</strong></p> <ol> <li><strong>One fan-out per event, shared by every trigger.</strong> <code>notify_turn_processed</code> (called from <code>finish_processed_turn</code>, reached through <code>after_turn_processed</code>) serves the manual, deadline and auto-processing paths alike. If an event can be reached two ways, the second way calls the same function — do not bolt a <code>notify_players</code> call onto the new call site.</li> <li><strong>Never notify the caller of their own action twice.</strong> A player who presses "process turn" gets the resolution in their HTTP response; <code>exclude_telegram_id</code> skips their DM.</li> <li><strong>Every send is best-effort at the call site, durable after it.</strong> Wrap and log. A failure to <em>queue</em> (the database is down) must never fail a turn that is already committed to Postgres — the state change is the contract, the notification is not. But once queued, a notification is never dropped: only the bot's ack removes it.</li> <li><strong>Update this table in the same commit.</strong> It is the only place the full picture exists.</li> </ol> <p><code>notify_turn_processed</code> is deliberately <strong>synchronous</strong> so the sync scheduler path (<code>process_due_deadlines</code>) and the <code>async</code> HTTP route can share it with no bridge; each notification costs one short database write.</p> <h2 id="deployment-and-message-reliability">Deployment and message reliability<a class="headerlink" href="#deployment-and-message-reliability" title="Permanent link">¶</a></h2> <p>Every service — <code>postgres</code>, <code>diplomacy_api</code>, <code>diplomacy_bot</code>, <code>diplomacy_web</code> (nginx), <code>caddy</code>, <code>diplomacy_docs</code> — runs from one <code>docker-compose.yml</code> on one VPS; Caddy is the public entry (80/443). Two other ports are published by compose and bound by env: nginx on <code>${WEB_BIND:-0.0.0.0}:${WEB_PORT:-80}</code> (<code>ensure_env.sh</code> sets <code>WEB_BIND=127.0.0.1</code> and <code>WEB_PORT=8080</code> once <code>DOMAIN</code> is set, so with HTTPS on only Caddy is reachable; without a <code>DOMAIN</code>, nginx is the public HTTP entry) and DAIDE on <code>${DAIDE_BIND:-127.0.0.1}:8432</code> (loopback unless <code>DAIDE_BIND</code> says otherwise; <code>ensure_env.sh</code> does not set it). The API is published on <code>127.0.0.1</code> only and Postgres not at all. The bot and nginx reach the API by its compose service name (<code>docs/DEPLOYMENT.md</code>). The images of our four services (API, bot, web, docs) are built in GitHub Actions and pushed to GHCR tagged with the commit SHA (<code>ghcr.io/tenderi/diplomacy-<service>:<sha></code>, <code>.github/workflows/deploy.yml</code>); the host only pulls them (<code>upgrade.sh</code>), and builds them itself only when the pull fails or with <code>upgrade.sh --build</code>. A rollback is a deploy of the previous SHA. The deploy reaches the host through a forced-command SSH key (<code>host/deploy_hook.sh</code>) that deploys only main's commits and runs only the maintainer-installed copies of the host scripts; a change to <code>docker-compose.yml</code> or <code>docker/Caddyfile</code> ships only once the maintainer approves it on the host, so a merged commit changes the containers but never the host (<code>docs/DEPLOYMENT.md</code> §Hardening). The API is a separate process that is down during every deploy and after any crash, and a deadline may pass while it is. The contract is that <strong>no player message is ever lost in either direction</strong> — only delayed, and always with the original time preserved.</p> <p><strong>Player → server</strong> (<code>telegram_bot/outbox.py</code>, <code>api_client.api_post_reliable</code>). Orders and diplomatic messages are written to a SQLite queue (the <code>bot_data</code> volume) <em>before</em> the first attempt. Outcomes are <code>delivered</code> / <code>queued</code> / <code>rejected</code>; the handler shows the matching reply, and a background loop (<code>notifications.outbox_replay_loop</code>) retries queued entries strictly in id order — stopping at the first that is still unreachable so nothing overtakes an older write — and DMs each result. A 4xx is a definitive answer (<code>rejected</code>, "The server refused it: …"). No answer, or a gateway's 502/503/504, is an outage: the entry stays queued as long as it lasts, with the backoff of <code>outbox.backoff_seconds</code> (5 s doubling to 60 s). Any other 5xx (500, 501, …) is the API failing on the request — a database blip, a bug — and is retried the same way, but only <code>api_client.MAX_SERVER_ERRORS</code> (8) times, about four minutes: the queue is shared by every chat and strictly ordered, so a route that always answers 500 would otherwise hold back every player's writes behind it. Then the entry is <code>failed</code> and the player is told "The server kept failing (HTTP 500 on 8 tries), so I stopped trying. It did not refuse it: please send it again." No answer or a 502/503/504 in between neither counts nor resets the count, so an outage never makes the bot give up and a flapping gateway cannot keep a failing route at the head forever. A first attempt answered with a 5xx is told "I will retry it for a few minutes". An order retried after its phase ended gets the stale-order 409 below and is <code>rejected</code>. Each request carries:</p> <ul> <li><strong><code>client_timestamp</code></strong> — when the player composed it (the entry's creation time). <code>api/client_timestamp.py</code> normalises it to naive UTC, clamps far-future values, refuses ones older than 30 days. <code>MessageModel.timestamp</code> stores it; the recipient's notification gains "(sent HH:MM UTC)" when delivery was noticeably late. <strong>Order submissions composed before <code>games.phase_started_at</code> are refused with 409</strong> (<code>routes/orders.py::_refuse_if_stale</code>) — the turn was adjudicated without them, and applying last phase's orders to this phase's board would be worse than telling the player. A <code>client_timestamp</code> more than <code>FUTURE_TOLERANCE</code> (5 minutes) ahead of the server clock is refused with 422 on the same routes (the clamp above would otherwise turn it into "now" and let it pass as fresh). <code>phase_started_at</code> is stamped by <code>GameRepo</code> on every write that changes <code>phase_code</code>.</li> <li><strong><code>X-Bot-Secret</code></strong> — the bot secret, added at send time and only in this header: the stored entry never holds it (it would be on disk, and a write queued before a secret rotation would replay with the old one), and a <code>bot_secret</code> left in a stored payload is dropped before sending.</li> <li><strong><code>Idempotency-Key</code></strong> — a UUID per entry. <code>api/idempotency.py</code> stores the first response (status + JSON) and replays it, with <code>Idempotent-Replayed: true</code>, to any later request with the same key. The key alone identifies the entry: <code>endpoint</code> is stored but not compared on replay, so the same key sent to a different route would replay the first response. This does not occur, since only the bot sends keys and it generates one per write. Honoured only with <code>X-Bot-Secret</code>, only for mutating methods, only for responses below 500 (a 5xx should be retried, a 4xx is a definitive answer to relay). The key is <strong>reserved before the route runs</strong>: <code>DatabaseService.reserve_idempotency_key</code> inserts a pending row (<code>status_code</code> 0) on the key's primary key, so of two concurrent same-key requests, in any worker, exactly one runs the route. The other — a replay of a write the API is still applying — gets <strong>503 with <code>Retry-After: 5</code></strong>, which the bot counts as transient (<code>api_client.TRANSIENT_STATUSES</code>): the entry stays queued with no server error counted, and the next replay gets the stored reply. (Not 409: the bot reports a 4xx as rejected, which would tell the player a write had failed while it was being applied.) A request that stores nothing (a 5xx, a non-JSON body, an exception) releases its reservation so a retry runs the route afresh; a reservation left by a worker that died mid-request is taken over once older than <code>IDEMPOTENCY_STALE_AFTER</code> (5 minutes, far past any route's run time). The reservation's <code>created_at</code> is its owner token: the release and the fill both match on it, so a request that ran past the limit can neither free nor fill the reservation of the one that took its key over. Keys expire after 7 days (<code>run_housekeeping</code>).</li> </ul> <p><code>game_context.fetch_user_games</code> caches each user's games/powers in the same SQLite file and falls back to the cache when the API is unreachable, which is what lets <code>/order A PAR - BUR</code> resolve <em>which power you hold</em> and reach the queue while the server is down.</p> <p><strong>Server → player</strong> (<code>bot_outbox</code> table, <code>routes/bot_outbox.py</code>, <code>api/long_poll.py</code>, <code>notifications.notification_loop</code>). Described in the section above. Delivery is at-least-once: a row is acked only after Telegram accepts the message, so a crash between send and ack can repeat a DM. Permanent Telegram failures (user blocked the bot, chat not found) are acked as failed with the error kept on the row. Delivered rows are purged after 7 days.</p> <p>The poll is a <strong>long-poll</strong>. <code>GET /bot/outbox?wait=N</code> (<code>0 ≤ N ≤ 60</code>, default 0 = answer at once) answers immediately when rows are pending; otherwise it holds the request until a row is committed or <code>N</code> seconds pass, and then answers with what is there (on timeout <code>{"items": [], "count": 0}</code>; the count is also sent as <code>X-Outbox-Count</code>). The wait holds no database connection: the request registers an <code>asyncio.Event</code> and queries only when woken. Two things wake it: <code>DatabaseService.enqueue_bot_notification</code> calls its <code>bot_outbox</code> listeners after each commit, which wake every waiter <em>in that process</em>; and every <code>DIPLOMACY_OUTBOX_RECHECK_SECONDS</code> (default 2) the waiter queries anyway, which is how a row committed by <em>another</em> uvicorn worker is found. Postgres <code>LISTEN/NOTIFY</code> would wake across workers too, but costs a dedicated listener connection per worker, a thread to poll it and reconnect handling; one indexed query every two seconds for the one waiting request is simpler to get right, and its worst case is still faster than the fixed 3 s poll it replaced. Reading and acking are unchanged: the long-poll only changes <em>when</em> the response is sent.</p> <p>The bot asks for <code>wait=DIPLOMACY_NOTIFY_WAIT_SECONDS</code> (default 25) with an HTTP timeout ten seconds longer, and polls again at once after a poll that handed over rows. A poll that handed over nothing in less than <code>DIPLOMACY_NOTIFY_POLL_SECONDS</code> (default 3) — an API that ignores <code>wait</code>, the API unreachable, Telegram refusing — sleeps out the rest of that, so the loop never spins. Each cycle touches the heartbeat, at most ~35 s apart (the replay loop touches it every 5 s as well), well inside the healthcheck's 120 s staleness limit.</p> <p><strong>The access log.</strong> <code>api/access_log.py</code> keeps healthy noise out of uvicorn's access log: a <code>logging.Filter</code> on <code>uvicorn.access</code> (installed by <code>_api_module</code>, so it applies however uvicorn is started) drops <code>/healthz</code>, <code>/health</code> and <em>empty</em> <code>GET /bot/outbox</code> lines whose status is below 400. Every error on those paths is still logged, and so is a poll that handed rows over. uvicorn's access record carries no response body, so the route sets <code>X-Outbox-Count</code>, and the outermost middleware (<code>QuietAccessLogMiddleware</code>) marks an empty poll in a context variable for exactly the <code>send</code> that uvicorn logs from.</p> <p><strong>What the bot needs to run:</strong> <code>python-telegram-bot</code>, <code>requests</code>, and a writable <code>DIPLOMACY_BOT_DATA_DIR</code>. Nothing else — no database URL, no engine, no FastAPI. The Docker image installs <code>requirements-bot.txt</code> only; <code>tests/test_execution_context.py</code> and the image build are what keep that boundary honest. The bot starts and stays up whether or not the API is reachable; that is the whole point.</p> <h2 id="frontend">Frontend<a class="headerlink" href="#frontend" title="Permanent link">¶</a></h2> <p>React 18 + Vite + TypeScript SPA (<code>frontend/</code>), Tailwind + shadcn/ui. Consumes the GameState-native <code>GET /games/{id}/state</code> view directly (<code>units_by_power</code>, <code>ownership</code>, <code>dislodged</code>, <code>contested</code>, <code>phase_type</code>, <code>players</code>, ...). Vite proxies <code>/api</code> to <code>http://localhost:8000</code> in dev; in production nginx serves the built app.</p> <p>The <strong>sandbox</strong> (<code>/sandbox</code>, <code>/sandbox?game=<id></code>) is a scratch board on which a player orders all seven powers and steps through the phases, from a game's current position or the opening one. It is stateless on the server: the page holds the serialized <code>GameState</code> and sends it to <code>POST /sandbox/*</code> (<code>data_spec.md</code> §4), which validate, adjudicate and render it through <code>GameService</code> without touching the database. Leaving the page discards it.</p> <h2 id="out-of-scope-for-this-document">Out of scope for this document<a class="headerlink" href="#out-of-scope-for-this-document" title="Permanent link">¶</a></h2> <p>Route-by-route API reference, Telegram command list, and DB column-level schema live in <code>data_spec.md</code>, <code>src/server/README.md</code> and the user-facing docs in <code>docs/</code>. Map variants beyond <code>standard</code> and a rendering redesign are out of scope (<code>fix_plan.md</code>).</p> </article> </div> <script>var target=document.getElementById(location.hash.slice(1));target&&target.name&&(target.checked=target.name.startsWith("__tabbed_"))</script> </div> <button type="button" class="md-top md-icon" data-md-component="top" hidden> <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24"><path d="M13 20h-2V8l-5.5 5.5-1.42-1.42L12 4.16l7.92 7.92-1.42 1.42L13 8z"/></svg> Back to top </button> </main> <footer class="md-footer"> <nav class="md-footer__inner md-grid" aria-label="Footer" > <a href="../../LOCAL_DEVELOPMENT/" class="md-footer__link md-footer__link--prev" aria-label="Previous: Local development"> <div class="md-footer__button md-icon"> <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24"><path d="M20 11v2H8l5.5 5.5-1.42 1.42L4.16 12l7.92-7.92L13.5 5.5 8 11z"/></svg> </div> <div class="md-footer__title"> <span class="md-footer__direction"> Previous </span> <div class="md-ellipsis"> Local development </div> </div> </a> <a href="../adjudication/" class="md-footer__link md-footer__link--next" aria-label="Next: Adjudication"> <div class="md-footer__title"> <span class="md-footer__direction"> Next </span> <div class="md-ellipsis"> Adjudication </div> </div> <div class="md-footer__button md-icon"> <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24"><path d="M4 11v2h12l-5.5 5.5 1.42 1.42L19.84 12l-7.92-7.92L10.5 5.5 16 11z"/></svg> </div> </a> </nav> <div class="md-footer-meta md-typeset"> <div class="md-footer-meta__inner md-grid"> <div class="md-copyright"> <div class="md-copyright__highlight"> Free software under the GNU AGPL v3 or later </div> Made with <a href="https://squidfunk.github.io/mkdocs-material/" target="_blank" rel="noopener"> Material for MkDocs </a> </div> </div> </div> </footer> </div> <div class="md-dialog" data-md-component="dialog"> <div class="md-dialog__inner md-typeset"></div> </div> <script id="__config" type="application/json">{"annotate": null, "base": "../..", "features": ["navigation.sections", "navigation.top", "navigation.footer", "search.highlight", "content.code.copy"], "search": "../../assets/javascripts/workers/search.a7633da7.min.js", "tags": null, "translations": {"clipboard.copied": "Copied to clipboard", "clipboard.copy": "Copy to clipboard", "search.result.more.one": "1 more on this page", "search.result.more.other": "# more on this page", "search.result.none": "No matching documents", "search.result.one": "1 matching document", "search.result.other": "# matching documents", "search.result.placeholder": "Type to start searching", "search.result.term.missing": "Missing", "select.version": "Select version"}, "version": null}</script> <script src="../../assets/javascripts/bundle.a5f9d56c.min.js"></script> </body> </html>