Files
FFF_vtt_frozen/docs/DESIGN.md
T
SirStone db22b33567 design: record the closing message and the protocol-shell decisions (#18)
Owner decision (#18), option A: mummy 0.4.8 cannot send an application close code
(close(ws) -> an empty close frame -> the browser sees 1005), and mummy is not forked
for it. Every server-initiated close now sends one closing {reason, code} message and
then the close frame; the client reads the reason from that last message. Amends 3.2
(the OPEN note is FIXED) and 6.5, and adds the message to the 6.1 catalogue (server
messages 14 -> 15) with the reason/code table.

Also recorded FIXED: proto is a required query parameter (400 when absent, 4003 on a
mismatch, no hello); the server Ping interval (20 s, plus one right after hello, lag
enforcement stays M5); the n rule (server frames only, no number for Ping/Pong); the
explicit 64 KB maxMessageLen; and the slice-3 rollout note that catalogue intents
whose slice has not landed answer unknown-type. 10.3 lists the protocol test group.
2026-11-15 08:33:16 +01:00

835 lines
137 KiB
Markdown

# FFF_vtt design
Status: draft v0.15, 2026-11-15 (owner decisions recorded in section 14; v0.4 records Q4 (tile_size 32 px), the outbox lock invariant (4.2, 4.3), and the follow-ups in 3.4, 8, 11.1, 12, 13; v0.5 records the M2 move-rule decisions in 5.5 and updates 3.4, 4.2, 5.1, 5.4, 6.1, 7.4, 8, 10.3, 12, 13; v0.6 records #14 (characters and player data) in 3.1, 3.4, 4.1, 4.4, 6.1, 8, 9, 10.3, 13, 14; v0.7 records #6 (players and invites) in 3.1, 3.2, 3.4, 4.4, 6.1, 8, 12, 13, 14; v0.8 records #7 (map tiles) in 3.3, 3.4, 11.1, 13, 14; v0.9 records #9 (test tools) in 2, 10.4, 13, 14; v0.10 records #12 (what M3 done means) in 13, 14; v0.11 records #15 (M3 limits) in 4.3, 6.4, 10.1, 13, 14; v0.12 records #11 (M3 message list) in 3.1, 3.2, 3.4, 4.2, 4.3, 5.5, 5.6, 6, 7.5, 13, 14; v0.13 records the owner review of #11 flags in 1, 3.1, 5.5, 6.1, 8, 14; v0.14 records #17 (getting in: keys, sessions, the auth slice) in 3.2, 4.4, 6.5, 6.6, 8, 11.1, 13, 14; v0.15 records #18 (talking safely: the protocol shell and the `closing` close-reason message) in 3.2, 4.3, 6, 6.1, 6.2, 6.4, 6.5, 10.3, 13, 14. All of Q1-Q24 are RESOLVED or DEFERRED; none OPEN). Audience: the owner and coding agents.
Legend:
- **[FIXED]** owner decision, not up for debate here.
- **[MEASURED]** number/behaviour taken from a prototype run (cited by path).
- **[INFERRED]** my reading of code or reasoning; not tested.
- **[PROPOSED]** design choice made in this doc; the owner may overturn it.
Evidence roots (relative to repo root):
- `prototype-pixi-perf/` (client perf; README holds all tables)
- `prototype-server-vision/` (server + vision; `README.md`, `HANDOFF.md`, `NOTES.md`, `results/`, `results/spike/investigation.md`)
- `prototype-tile-leak/` (tile size vs leak; `README.md` holds desktop tables and the 2026-11-08 phone run; `results/phone-20261108T113701.jsonl`)
- `docs/prototype.md` is only the original brief for the perf prototype.
- No FFF engine notes exist in the repo. `GLOSSARY.md` and `docs/adr/` do not exist yet; AGENTS.md requires them (Q24, FIXED). `prototype-*` dirs stay in-tree until the M4 client port, then are archived (Q24, FIXED). Nothing here is FFF-specific beyond the seam in section 9.
---
## 1. Goal and non-goals
### Goal
A browser virtual tabletop for one table (1 GM + up to 6 players [FIXED, Q1]), self-hosted, where the **server alone decides what each player sees**. A modified client must learn nothing it is not entitled to.
### v1 scope [PROPOSED, trimmed to what the prototypes proved plus the minimum to be usable]
- One table, 1 GM + up to 6 players (max 6 [FIXED, owner decision 2026-11-08, Q1]), a shared site link and per-player keys, no accounts.
- Exactly one scene in v1 (Q3, FIXED): large tiled map image, optional visual grid, walls and doors (kinds `wall`|`door` only, Q6), tokens.
- GM tools: author walls/doors in the browser (Q6, FIXED), create/move/delete tokens, toggle doors, edit token properties, manage players and player keys.
- Player: move owned tokens only; see only line-of-sight area, previously explored area (dimmed), and tokens inside LOS. Character creation and edits and all prop writes are GM-only in v1; opening them to players later is a permission change on the existing intents (6.1), not a redesign.
- Automatic LOS from owned tokens against walls/doors, server-side. Explored area = per-player cell grid, persisted.
- Persistence across restarts; reconnect resync; backups.
- Generic entity model (typed properties with visibility buckets) as the seam for FFF.
### Non-goals for v1 (later or never)
- RPG rules, dice, character sheets, initiative. FFF engine plug-in: seam only (section 9).
- Dynamic lighting, light sources, darkvision tiers, per-token vision radius beyond one numeric property, windows/transparent walls, one-way walls.
- Accounts, passwords, OAuth, multiple tables/campaigns per server, public hosting.
- Feeding from the owner's map generator [FIXED: does not feed in]. Map import is a CLI step in v1; browser upload is post-v1 (Q5, FIXED).
- Freehand drawing, rulers, pings, chat, audio, video (order decided at M7, Q8).
- Mobile-first UI polish (the client must work on a phone [MEASURED render], but layout is not a v1 goal). Devices in scope: phones, tablets, laptops (Q1, FIXED).
- Network exposure and reachability: owner's concern (Q23, FIXED). Built-in protections stay (127.0.0.1 bind, connection cap, frame/rate limits, Origin check); internet-only hardening (fail2ban etc.) is not in scope.
- Horizontal scaling, multi-process server.
---
## 2. Architecture overview
### Fixed stack [FIXED]
- Client: TypeScript + PixiJS v8 + Vite; plain HTML/DOM overlay for UI (no UI framework). Agents use the official pixijs-skills (already in `.agents/skills/pixijs*`).
- Server: Nim 2.x; `mummy` pinned to tag `0.4.8` (commit `77a7563e`; `src/` identical to the former pin `01deb1ff694988635c7bf0f24f6088a0bdf6db5d`) [FIXED (owner decision), 2026-11-08; tags 0.4.6-0.4.8 exist]. `prototype-server-vision/servervision.nimble` still pins the commit until ported; `db_connector/db_sqlite`, WAL. No Nim in the browser.
- nginx (existing, HTTPS) in front: static client, reverse proxy for `/ws`, `/join`, `/tiles/`; internal location for tile bytes.
- Dev env: NixOS, devbox per project for toolchains, nothing global. Node 26 (devbox) runs the black-box test harnesses only; in-process tests stay Nim [FIXED, owner decision 2026-11-14, #9] (10.4). devbox also carries `sqlite` (output `out` + `bin`): `db_connector` dlopens `libsqlite3.so`, so the devbox env sets `LD_LIBRARY_PATH=$DEVBOX_PACKAGES_DIR/lib`.
### Component diagram
```
Browser (untrusted; players, GM) NixOS server
+-----------------------------+ HTTPS +--------------------------------------------+
| Vite bundle (TS + Pixi v8) | <-------------> | nginx (existing, TLS) |
| - renderer, fog, input | static, /ws, | / -> client/dist (store) |
| - DOM overlay UI | /tiles/,/join | /ws -> proxy, Upgrade |
| - reducer (protocol state) | | /join /tiles/ -> proxy to Nim |
+-----------------------------+ | /_tiles/ -> internal alias, bytes |
+-------------------+------------------------+
127.0.0.1 only | X-Accel-Redirect
+-------------------v------------------------+
| Nim server (mummy, 1 process) |
| TRUST BOUNDARY = egress module |
| ingress: parse -> authz -> validate |
| core: world state (walls, entities, |
| explored grids), vision, rules hook |
| egress: per-recipient view -> diff -> ws |
| persistence: SQLite WAL (state dir) |
+-------------------+------------------------+
|
state dir: state.db, tiles/ (immutable art)
```
### Data flow (one move)
1. Client sends intent `token.move` over WS.
2. Ingress: authenticate (connection already bound to a player at upgrade), parse, authorize (owns token), validate (shape, bounds, step cap, collision).
3. Core: apply to in-memory state, recompute vision for affected players, update explored grids.
4. Persist in one SQLite transaction (inside the lock, ack after commit).
5. Egress: for each connection build that recipient's view, diff against what that connection already knows, send only the diff.
6. Client reducer applies, renderer redraws what changed.
### Trust boundary
- Everything on the right of the browser is trusted; everything in the browser is not, including the GM's browser for anything the GM is not entitled to (the GM sees everything, so the GM client is trusted only for GM-authorized intents; it still gets validated).
- **Single egress rule [PROPOSED]:** all bytes to a player leave through one egress module that takes a recipient and a typed per-recipient view. Raw world state (walls, hidden entities, other players' explored grids) has no code path into that module. The prototype enforces this by discipline in `sync()` (`prototype-server-vision/src/server.nim`); the real build should enforce it by types (distinct `PlayerView` and `GmView` structures, no `JsonNode` of world state passed around).
- Client-side fog is cosmetic. Security never depends on the client hiding anything (section 7).
---
## 3. Security model and hidden-information rules
### 3.1 What each role receives [PROPOSED, extends the prototype's behaviour]
| Data | GM | Player (own) | Player (others) |
|---|---|---|---|
| Walls, doors (geometry, open/closed) | all, always | **never** (WS or HTTP) | never |
| Tokens/entities (position, radius, statuses without `source`, name per 8) | all | controlled by this player (`entity.owner`): always. Others: only if inside own LOS polygon **and** not `gm_only` | -- |
| Token props, `public` bucket | all | for visible tokens | -- |
| Token props, `owner` bucket (owner = token controller) | all | only for tokens this player controls | never |
| Token props, `gm` bucket | all | never | never |
| Character records (owner, names, character props) | all | own characters: always. Others: never; no browsable list of characters | never |
| Character props, `public` bucket | all | for characters with a visible token | -- |
| Character props, `owner` bucket (owner = character owner) | all | own characters only | never |
| Character props, `gm` bucket | all | never | never |
| Names (descriptive / actual, 8) | all actual | descriptive; actual for own characters and where revealed to this player | descriptive, or actual where revealed to that player |
| Encountered list (8) | all players' lists; GM may remove an entry | own list only | never |
| Vision polygons | none needed (GM sees all) | own tokens' polygons only | never |
| Explored grid | none | own grid only | never other players' |
| Map tiles | all | only tiles touching own explored cells (403 otherwise) | -- |
| Player roster | all (names, connected) | names of all players (Q9, FIXED) | names of all players (Q9, FIXED) |
| Player keys, sessions | GM only (keys re-showable, Q11 FIXED) | own session cookie only | never |
| Global activity counters (`gseq`) | yes | **no**: per-connection counter only | -- |
Notes:
- Prototype gap [INFERRED from code reading]: `Tok.gmOnly` is loaded from `scene.json` but never consulted in `sync()`; a GM-only token inside a player's LOS would be sent. Real build must enforce `gm_only` in the view builder and test it (new fault class, section 10).
- Prototype gap [INFERRED]: every message carries the global `gseq`; player-visible gaps in `gseq` reveal that hidden mutations occurred. Real build: players get a per-connection monotonic counter.
- `hello` to a player carries world size, tile size, explored cell size, scene default token and vision radius, art version, own player id and name. None of these is secret (owned token ids travel as `mine` on `token`, 6.1). It must not carry scene/entity counts or wall counts.
- A token's radius and statuses go to every recipient who sees the token [FIXED, owner decision 2026-11-10, #4]. Amended 2026-11-14: a status entry's `source` goes to the GM only; viewers see the status (e.g. `squeezed`), not its cause. The controlling owner gets no `source` either (the doc has no owner-view rule for statuses; revisit if wanted).
- [FIXED, #14] Names and lists: no code path sends an actual name, a reveal state, or another player's character or encountered entry to a player, unless the rules in 8 allow it. Players learn a character only through a token they saw or controlled, or through their own encountered list. A character owner change never changes token controllers.
### 3.2 Authentication: shared link, player keys, GM key
- **Shared site link [FIXED, #6].** One link for everyone: `https://host/`. Without a session it shows only the sign-in page, no data.
- **Player key [FIXED, #6].** Each player has a personal secret, the **player key**, generated by the GM (no name at creation). It identifies the player and grants access to their data. Format: 20 characters in groups of 4 with dashes, alphabet without look-alikes (no 0/O, 1/I/L), from the OS CSPRNG (~100 bits) [FIXED, owner accepted default, #6].
- **Sign-in [path FIXED (owner-delegated, 2026-11-14, #17): `POST /join` implemented in slice 2; behaviour FIXED].** The sign-in page POSTs the key to `/join` (HTTP; key in the body, never in the URL). Valid key: the server issues a fresh random session token cookie (`HttpOnly; Secure; SameSite=Strict; Path=/`), stores only its hash server-side, then redirects to `/`. Request and response: 6.6. Sessions never expire (Q10); one key works on many devices [FIXED, Q10].
- **First-sign-in name [FIXED, #6].** A player with no name is asked once for a display name (`player.setname`, 6.1). Names are unique among players. Renames: GM only (`player.rename`).
- **No rate limit on key entry [FIXED, owner, #6].** The ~100-bit key space makes guessing infeasible; no lockout, no `limit_req` on sign-in. Owner explicitly rejected guessing protection.
- **Replace a key [FIXED, #6].** GM can do this any time while the server runs: old key invalid, all that player's sessions revoked, live connections closed at once. Identity, characters and encountered list kept; no name re-prompt.
- **Remove a player [FIXED, #6].** Key invalid, sessions revoked, connections closed. Their characters and controlled tokens pass to the GM (character owner and token controller set to GM). Name leaves the roster; slot freed; their encountered list deleted.
- **Cap [FIXED, #6].** Max 6 players; unused keys count toward the cap.
- Keys are stored plaintext so the GM can re-show them [FIXED, Q11]. Key and session are separate: the cookie is never the key. Never log keys or session tokens (Nim or nginx).
- Session separate from key: the prototype's secret-as-cookie design is dropped (permanent bearer, sits in access logs and history).
- One cookie jar = one identity; same cookie in two tabs = same player, shared vision, both connections synced [MEASURED, prototype README].
- WS upgrade: authenticate by cookie **and** verify the `Origin` header equals the configured public origin, checked before the session and the upgrade [FIXED (owner-delegated, 2026-11-14, #17); mitigates cross-site WebSocket hijack, SameSite=Strict is the first line].
- **Rejected [FIXED, #6]:** per-person invite links; GM types the name at key creation; delete-and-reinvite only; deleting a player's characters with the player; a shared-link visit creating a player; a separate GM link path.
- **First GM login [FIXED, owner decision 2026-11-10, #5; amended #6].** Only the server CLI creates the GM: `fff-vtt gm-key` creates the single GM player (role `gm`, display name `GM`) if none exists, and prints the GM key. Re-running prints the same key; existing GM sessions are unaffected. `fff-vtt gm-key --new` rotates: new GM key, old one invalid, all GM sessions revoked. `--new` refuses while the running server holds its lock on the data dir; the read-only print works at any time. The GM's own key rotates only this way (no live replace). The GM signs in like a player: shared link, then GM key. Access control is filesystem permissions on the data files; no extra password. A visitor without a key never becomes GM (no first-visitor claim); they see only a "need a key" page. The GM may rename.
- Rejected: env/config seed (secret leaks via config, repo, backups); auto-print at startup (secrets in logs); first visitor claims GM (takeover); rotate on every lookup (logs out GM devices); live rotation while the server runs (needs an admin channel to the running server).
- **Key and session formats [FIXED (owner-delegated, 2026-11-14, #17)].** Player and GM keys are 20 symbols in 5 groups of 4 separated by dashes (24 characters shown), alphabet `ABCDEFGHJKMNPQRSTUVWXYZ23456789` (no `0/O`, `1/I/L`), drawn from the OS CSPRNG (`std/sysrand`, `getrandom`): ~99 bits. Comparison normalizes ASCII case, dashes and spaces and is length-independent (no early exit); at most 7 stored keys are compared. A session token is 32 CSPRNG bytes as lowercase hex (64 characters); only `sha256(token)` is stored. SHA-256 is a small in-repo implementation (`server/crypto.nim`, FIPS known-answer tested) because the pinned Nim stdlib has no SHA-2 and this adds no dependency. The cookie is `fff_session` (6.6).
- **`fff-vtt gm-key` wiring [FIXED (owner-delegated, 2026-11-14, #17)].** `fff-vtt gm-key [--new] [config flags]` opens (and migrates) the DB with the normal config keys, creates the GM (role `gm`, name `GM`) when absent, and prints one line `GM key: <key>`; re-runs print the same key. `--new` rotates, revokes all GM sessions, and prints `GM key (new): <key>`. The server holds an exclusive `fcntl(F_SETLK)` write lock on `<stateDir>/instance.lock` for its lifetime (also refusing a second server); `--new` tries the same lock and exits **3** without touching the DB while it is held. The read-only print takes no lock and works while the server runs. Other exit codes: 0 ok, 1 DB/state-dir error, 2 config error.
- **Application close codes at the mummy pin [FIXED, owner decision #18, 2026-11-15: option A, accept 1005 plus a reason message].** Mummy 0.4.8 exposes only `close(ws)`, which sends an empty close frame (a browser reports **1005**), so the app codes of 6.5 cannot ride the close frame; mummy is not forked or patched for this. The server therefore sends one final application message, `closing {reason, code}` (6.1), immediately before every server-initiated close, and then closes. A client reads the reason from that last message and 1005 from the close event; the numeric `code` keeps the 6.5 table's mapping (`revoked` 4001, `evicted` 4002, `proto-mismatch` 4003, `malformed-flood` 1008). Slice 2's revocation and eviction paths already send it. Consequence: a server-initiated close is always two steps (message, then close), and the message is the last app frame that connection ever sees.
### 3.3 Tiles
- Browser asks `GET /tiles/<scene>/v<art_version>/<x>_<y>.png` (Nim path). Nim parses strictly (digits only, length-bounded, range-checked against scene size; malformed or out-of-range -> `404`), checks the session's explored grid (the explored-area logic of 5.1), and answers `200` with `X-Accel-Redirect: /_tiles/<scene>/v<art_version>/<x>_<y>.png`, or `403` if unexplored [FIXED, owner decision 2026-11-14, #7]. nginx serves the bytes from an `internal` location; direct hits on `/_tiles/` give 404 [MEASURED: `prototype-server-vision/results/smoke.log`, README "Phase 2a"].
- GM is always allowed.
- Rule: a tile is allowed iff at least one explored cell of that player overlaps it [MEASURED semantics: leak test (d), 9984 + 7424 requests, 0 failures, `results/leak-A.log`, `results/leak-B.log`].
- **Residual tile-edge leak (accepted for v1, documented) [FIXED, Q4]:** a tile is the unit of disclosure. v1 sets `tile_size` = explored cell = 32 px (section 8), tile grid origin = world origin, so a tile is allowed iff its one cell is explored. The residual is the whole 32 px cell that a vision polygon grazed, including art the LOS did not actually see. Once revealed it is never revoked. No server-side masking is built [FIXED, Q4]. Static art only: door state is never in tiles. Consequences for map authors: do not paint secrets (secret doors, hidden traps, notes) in map art within ~32 px of areas players can reach; keep secrets as GM-only entities. Evidence: `prototype-tile-leak/README.md` (desktop numbers; phone run 2026-11-08). Fallback if the M4 gates fail: `tile_size` 64 px (per-scene config, no code change; leak <= 3 cells per allowed tile, 4x fewer files).
- A second consequence: map art itself may depict walls/doors. Art is "what players see once there", walls data is "what physics/vision uses". Authoring must keep them consistent; mismatch is GM error, not a leak.
- Tile URLs include the scene's `art_version` so that re-imported art does not hit stale caches [FIXED, owner decision 2026-11-14, #7]: from M3 on, always `1` in M3. The gate reads `<state>/tiles/<scene>/v<art_version>/` (layout fixed in M3; writing versions and cleanup are M6, 11.1). Response `Cache-Control: private` [FIXED, owner decision 2026-11-14, #7], not the prototype's `no-store`.
### 3.4 Threat list
| # | Threat | Mitigation | Test |
|---|---|---|---|
| T1 | Player reads hidden token/entity/prop from WS | view builder filters by LOS, `gm_only`, bucket; single egress | leak test + fault classes |
| T2 | Player reads wall/door data | walls only in GM view | fault `walls` [MEASURED caught] |
| T3 | Player reads other player's vision/explored/ownership | per-player view only | faults `other-*` [MEASURED caught] |
| T4 | Player fetches unexplored tiles | Nim gate + internal nginx location | leak (d) against the independent oracle, smoke steal check, direct `/_tiles/` -> 404 (M3 test nginx) |
| T5 | Tile-edge over-disclosure: one 32 px cell grazed by vision, never revoked | tile_size = explored cell = 32 px, no server masking, authoring rule ~32 px (Q4 FIXED) | documented, not testable as a leak; M4 timing gates (13) |
| T6 | Player key / session theft via logs, referrer, history | key in POST body, never in URL; session != key (hash stored); log redaction; no-referrer on sign-in; HTTPS only | config test (grep logs for secret) [new] |
| T7 | Cross-site WS hijack | Origin check + SameSite=Strict | new test |
| T8 | **Wall-probing oracle via move validation** [INFERRED, not in prototype tests]: `moveBlocked` answers `ok:false` for any chosen segment, with unlimited length; binary searching lets a player map walls beyond LOS and tell open from closed doors | cap step length per intent (= token's effective vision radius, scene default if no vision; 5.5, Q18 FIXED), rate limit intents per connection (6.4), uniform nack that carries only the old position (5.5) | M2 in-process probing test (5.5, 13); WS version in M3 (10.3): count wall/door facts recoverable from nacks beyond LOS |
| T9 | Info via error replies (`not yours` echoing a position) | refusals are static codes, never state (6.5); a move of a non-controlled or unknown token gives `ack {ok:false, code:"not-allowed"}` without position, one code for both [MEASURED rule, README Findings] | leak test (e) |
| T10 | Message-size or rate DoS, slow client memory growth | max frame size (6.4), per-connection rate limit (6.4), connection cap (4.3); **bounded per-connection outbox** (byte/message caps, state coalescing), lagging clients stopped and resynced (4.3, Q13); mummy queue is unbounded [MEASURED finding, README mummy caveats] | new tests (10.3 slow client, protocol) |
| T11 | Timing/size side channels (message bytes reveal hidden activity) | accepted; only deliver messages when state visible to that recipient changes | not tested |
| T12 | Path tricks on static/tile routes | strict parsing; webby rejected `%2f`/`%00` [MEASURED, NOTES Phase 2a] | smoke |
| T13 | Player-controlled strings (token names, props) as XSS in DOM overlay | render with `textContent`, never `innerHTML`; CSP | new test |
| T14 | Boundary ambiguity: token exactly on vision edge | documented epsilon; tests use 0.5 px tolerance [MEASURED] | leak test |
| T15 | Backend reachable bypassing nginx (prototype nginx binds 0.0.0.0, `HANDOFF.md`) | Nim binds 127.0.0.1 only [MEASURED: prototype does], systemd `IPAddressAllow`, TLS at nginx | deploy check |
| T16 | Name leak: actual name or reveal state of an unrevealed character/token, another player's character or encountered entry, or a browsable character list reaches a player | names and lists built per recipient at egress (8); no list-all message; encountered list is per player | fault classes `ACTUAL_NAME`, `CHAR_LIST` (10.3) |
---
## 4. Server
### 4.1 State model
Single process, in-memory authoritative state, SQLite as write-through persistence (loaded at start, never queried at runtime for reads).
- **World**: scenes; per scene: dimensions, tile config, grid, walls (per-scene stable id, never reused; see 8), entities (tokens). Characters, name reveals and encountered lists (8) are world state too.
- **Players**: id, name, role (`gm`|`player`), colour; a player is a real person, not a character. Controlled tokens derive from `entity.owner` (token controller); owned characters from `character.owner`.
- **Per-player runtime** (`Role` in prototype, renamed `PlayerState`): current vision polygons (one per owned entity with `vision` enabled), `ver` counter bumped on change, explored set, `fresh` cells added by the current mutation.
- **Per-connection runtime**: `known` table (entity id -> last sent view), last-sent vision `ver`, per-connection counter, player id, role.
- Prototype used fixed roles `gm`/`A`/`B`; real build uses player ids. Multiple connections per player are allowed and share the player's vision/explored (as prototype).
- Monsters/NPCs have no vision [MEASURED design: `vision_ms move-monster` 0.000 ms]; only player-owned entities with `vision` produce polygons.
### 4.2 Mutation pipeline
`intent -> validate -> apply -> per-player visibility -> diff -> persist -> ack -> send`
Under the single global lock (as prototype, order proven correct by 3 x 60 s runs):
1. **Parse** with strict type checks (prototype pattern: kind checks per field). Unknown `t` -> `ack unknown-type` (`error malformed` if the envelope is unreadable; 6.5).
2. **Authorize**: role/ownership.
3. **Validate**: bounds, step cap (T8), collision (player moves: 5.5; GM moves skip walls and step cap), referential integrity, property schema.
4. **Apply** to memory.
5. **Recompute** vision only for players whose input changed (mover's owner; all players for door/wall changes). Update explored; collect `fresh`.
6. **Persist**: `BEGIN; ...; COMMIT` including dirty explored chunks.
7. **Ack** to sender, then **egress**: for each connection compute the recipient view and enqueue it in that connection's bounded outbox (4.3; state keys coalesced). The diff against `known` happens at flush time; only changed items (`token`/`token_gone`/`vision`/`explored`/`wall`/...) get bytes.
8. Clear `fresh`.
Invariants (carry from prototype):
- Enqueue order per connection == mutation order: messages are appended to the connection's outbox **while holding the lock**; network sends happen **outside** the lock, at flush. Non-state messages are FIFO. State messages are coalesced per key (latest wins, 4.3), so their position relative to other messages is flush order, not mutation order.
- Ack after COMMIT (a client never sees a state that a crash can undo, except under `synchronous=NORMAL` power loss, 4.4).
- A failed validation mutates nothing, bumps nothing, persists nothing.
- Refusals never echo state: only a refused move of a controlled token acks with its old position (uniform nack, 5.5); every other refusal is an `ack` with a static `code` and no position (6.5). Each intent gets exactly one `ack` (6).
Known limitation of the prototype, fixed in M2 [FIXED, accepted default; 5.5]: it checks only the centre path a->b and the destination circle, not the swept circle (corner clipping possible, `HANDOFF.md`). M2 adds the capsule (swept-circle) check and the step cap.
Second limitation [INFERRED]: a fast drag sampled at ~50 ms can produce a straight segment that cuts a corner the pointer path did not, causing a nack and a snap-back. Mitigation: client sends intermediate points when the step would exceed the cap (token's effective vision radius, 5.5, Q18); server clamps nothing silently (clamping would leak the hit distance, T8).
### 4.3 Locking and threading
- mummy: `WebSocket.send` appends the encoded frame to one server-wide deque under `sendQueueLock` and wakes the IO thread; worker threads handle events; per-socket events are serialized [MEASURED reading, `prototype-server-vision/README.md` "mummy suitability", mummy.nim ~L262-311].
- **One global lock** around intent handling and outbox enqueue; network sends happen outside it (flush, see 4.2). [MEASURED] 13748 mutations / ~36k messages in 60 s with 3 clients (~223 intents/s): no crash, no reorder, no loss, consistent final views (`results/concurrency-final{1,2,3}.log`); intent->ack avg 1.40 ms, p99 4.58 ms, worst 20.31 ms.
- Decision [PROPOSED]: keep the global lock in v1. A table of <= ~10 clients is 2 orders of magnitude below the single-core limit (server total per mutation avg 0.70 ms [MEASURED]). Revisit only if a measured p99 > 50 ms appears in production logs.
- Worker threads: prototype uses 8; one table needs 2-4 [INFERRED].
- **Slow client [FIXED (owner decision), 2026-11-08, Q13 option A]**. mummy's send queue is one unbounded deque and per-socket backlog is invisible to app code (no forced close, no depth API at this pin). No mummy patch. Research: `docs/research/q13-mummy-slow-clients.md`.
- **Bounded outbox per connection** (keyed by app `connId`), with byte and message caps. State messages (vision, token, explored, wall) are **latest-state-wins coalesced per key** (MQTT-retained-like). The diff against `known` is computed at **flush time**, not enqueue time, so a dropped intermediate state cannot desynchronise the client.
- **Ack by Ping/Pong**: server sends WS `Ping(seq)` (payload <= 125 B) on a timer; the client's Pong echoes `seq` (RFC 6455 §5.5.2-5.5.3; browsers answer without JS). Acks give bytes in flight and lag per connection. Interval [FIXED (owner-delegated), #18]: every 20 s, plus one Ping immediately after `hello` on each connection. Slice 3 sends the Ping and records the Pong per connection (`Conn.pongSeq`, `Conn.lastPongMs`); the lag measurement itself, the stop-feeding rule and the forced close of a silent peer stay M5. A Ping/Pong is a control frame and carries no `n` (6).
- **Lagging client** (outbox over cap, or no Pong within a bound): stop feeding it, keep the connection. On recovery, full resync (6.3).
- **Dead or stuck peers**: closed by nginx proxy timeouts [PROPOSED mechanism; verify in M5 that `/ws` goes through nginx and which directive fires, `send_timeout` is the candidate]. `close(ws)` cannot force-close at this pin (it queues behind the backlog).
- Connection limits [FIXED (owner-delegated, 2026-11-14, #15)]: 4 connections per player (a 5th closes that player's oldest); 16 total (1 GM + 6 players x ~2 devices + headroom); the 17th is refused. Replaces the PROPOSED cap of 8. Enforced in `websocketHandler` (mummy's inbound queue is unbounded). Frame and intent limits: 6.4.
- Forking mummy (per-socket depth, forced close) is fallback only, not planned.
- `WebSocket` **does** have generic field-wise `==` and `hash` at the pin (fields `server`, `clientSocket`, `clientId`; Nim 2.2 stdlib) [MEASURED reading, `docs/research/q13-mummy-slow-clients.md`, Corrections]. The earlier "no `==`/hash, keyed by raw bytes" note is stale. Prototype keys connections by the raw bytes of the ref (`key(ws)`), flagged as shortcut. Real build: assign an app `connId` at upgrade and key the outbox table by `connId`, not by `WebSocket` [PROPOSED, per Q13 research]; add a test that fails if mummy's `WebSocket` fields change (the pin makes this stable, the test makes it explicit) [PROPOSED].
- Handler discipline: no blocking I/O under the lock except the one SQLite COMMIT; no logging formatting of large structures under the lock; metrics are O(1) updates (section 11).
- SQLite tail: server worst ~20 ms is the COMMIT (WAL autocheckpoint / OS scheduling [INFERRED]) and every other mutation queues behind it as `lock_wait` (`results/spike/investigation.md`). Accepted for v1. Moving persist out of the lock breaks ack-after-commit and order; not done.
- 583 ms intent->ack outlier: **not reproduced**, cause undetermined (host stall or node harness pause; not proven either way, `results/spike/investigation.md`). Production logging (section 11) must make a recurrence diagnosable (SLOW lines with breakdown).
### 4.4 Persistence
Engine: SQLite via `db_connector/db_sqlite`, `journal_mode=WAL`, one connection used under the global lock. Also `busy_timeout=5000` and `foreign_keys=ON` at open [FIXED (owner-delegated, 2026-11-14, #16)].
**synchronous choice [FIXED, Q12]: `NORMAL`; `FULL` around GM authoring transactions.**
- [MEASURED] avg commit 0.60 -> 0.17 ms, server total avg 1.16 -> 0.74 ms; tail unchanged (~20 ms worst) (`results/spike/investigation.md`).
- Process kill (SIGKILL) loses nothing [MEASURED: `results/final-restart.log`, SIGTERM and SIGKILL, same DB, identical state].
- OS crash/power loss can drop the last few commits; never corrupts. For a VTT (positions, explored cells) that is acceptable; GM-authored content (walls, scenes) is the expensive loss, so GM authoring transactions run with `synchronous=FULL` [FIXED, Q12].
- Acceptance of ack-before-durable on power loss is stated, not hidden.
Schema sketch (columns indicative, not final DDL):
```
meta(k PRIMARY KEY, v) -- schema_version also via PRAGMA user_version
player(id PK, name NULL, role, colour, created_at) -- name NULL until first sign-in; unique among players [FIXED, #6]
player_key(player_id PK FK, secret, created_at) -- indicative; one current key per player; secret plaintext (Q11); replace overwrites [FIXED, #6]
session(id PK, player_id FK, token_hash, created_at, last_seen) -- never expires (Q10)
scene(id PK, name, w, h, tile_size, cell, grid_size, vision_radius_default, token_radius_default,
art_version, active, next_wall_id, extra_json) -- next_wall_id: monotonic, §8 [FIXED, #3]; token_radius_default [FIXED, #4]
wall(scene_id FK, id, ax, ay, bx, by, kind, open, flags, PRIMARY KEY(scene_id, id)) -- kind: wall|door|(later: window, one-way)
character(id PK, owner_player_id FK NOT NULL, descriptive_name, actual_name, reveal_all BOOL,
props_public JSON, props_owner JSON, props_gm JSON) -- NOT NULL: exactly one owner; GM owns via the GM's player id [FIXED, #14]
entity(id TEXT PK, scene_id FK, kind, character_id FK NULL, descriptive_name NULL, actual_name NULL, reveal_all BOOL,
x, y, radius REAL NULL, owner_player_id NULL, -- token controller; NULL = GM-controlled; never copied from the character [FIXED, #14]
gm_only, flags, props_public JSON, props_owner JSON, props_gm JSON) -- names NULL when character_id is set
name_reveal(player_id FK, subject_id, PRIMARY KEY(player_id, subject_id)) -- subject = character or plain token id; per player [FIXED, #14]
encountered(player_id FK, entity_id, character_id NULL, descriptive_name, actual_name NULL,
PRIMARY KEY(player_id, entity_id)) -- snapshot, no FK cascade: survives token/character delete; never auto-removed [PROPOSED]
entity_status(entity_id FK, status, source, PRIMARY KEY(entity_id, status, source)) -- status: stuck|squeezed; source: walls|GM [FIXED, #4]
explored_chunk(player_id, scene_id, cx, cy, bits BLOB, PRIMARY KEY(player_id, scene_id, cx, cy))
```
- Exactly one scene in v1 (Q3): `scene_id` keys stay in the schema.
- Prototype stores one row per explored cell (`exp(role, c)`, one INSERT per new cell, `HANDOFF.md`); real build stores **chunked bitmaps**: a chunk is e.g. 64x64 cells = 512 B; dirty chunks upserted per mutation [PROPOSED]. Sizes [INFERRED]: 4096 px map / 32 px cell = 16 384 cells = 2 KB bitmap; 16384 px map = 262 144 cells = 32 KB.
- Entity move = one UPSERT of x,y (prototype: `INSERT OR REPLACE INTO tok`).
- Migrations: `PRAGMA user_version` + forward-only migration list; startup refuses to run on a newer DB [PROPOSED]. Detail [FIXED (owner-delegated, 2026-11-14, #16)]: `schema_migration(version INTEGER PRIMARY KEY, name TEXT NOT NULL, applied_at TEXT NOT NULL)` is the history; `user_version` carries the same latest version, and startup refuses when the two disagree or the history is not contiguous from 1. One transaction per step (DDL + history row + `user_version`); a failing step rolls back completely, and an up-to-date DB is not written at all (re-open is a no-op). Step 1 (M3 slice 1) creates `meta(k TEXT PRIMARY KEY, v TEXT NOT NULL)`. Step 2 (M3 slice 2, `auth`) creates `player(id, name TEXT UNIQUE NULL until first sign-in, role 'gm'|'player', colour, created_at)`, a partial unique index `player_single_gm` on `role='gm'`, `player_key(player_id PK FK ON DELETE CASCADE, secret TEXT plaintext, created_at)`, and `session(id, player_id FK ON DELETE CASCADE, token_hash TEXT UNIQUE, created_at, last_seen)` plus `session_player`; removing a player therefore removes its key and sessions. `session.last_seen` exists but is not updated in M3 (sessions never expire, Q10). A step may hold several statements; the runner executes them in order inside the step's transaction (db_connector prepares one statement per call).
- Startup: load everything into memory, recompute vision for all players (prototype does, in one transaction) so `vision` is never stale vs walls.
- Shutdown: install a SIGTERM handler [prototype has only SIGINT, `HANDOFF.md`]: stop accepting, close sockets, final `wal_checkpoint(TRUNCATE)`, exit. Durability does not depend on it (WAL commit before ack).
---
## 5. Vision and explored
### 5.1 Algorithm (ported from `prototype-server-vision/src/geometry.nim`)
- **Visibility polygon** from token centre: cast rays to every blocking wall endpoint at angle -eps, 0, +eps (`RayEps` = 1e-4 rad), plus an inscribed 64-gon of radius R as range limit; sort by angle; each ray returns nearest hit among wall segments + circle segments; result = CCW polygon. Open doors (`door && open`) do not block.
- **Explored**: `cellsTouched(poly, cell)` marks every grid cell that the polygon overlaps; union into the player's explored set. Vertex-in-cell test added after a bug (polygon wholly inside one cell) [MEASURED bug log, prototype `NOTES.md`; covered by `tests/tgeometry.nim`, suite "cells", test "tiny polygon inside one cell"].
- **Token visibility** to a player: token centre inside any of the player's polygons (even-odd `inside`).
- **Move validation (prototype)**: inclusive segment intersection on blocking walls (touching = blocked, so no squeezing through shared vertices) AND destination circle at distance >= token radius from every blocking wall. Replaced by the M2 rules in 5.5; the prototype result is a baseline only.
### 5.2 Edge cases handled and tested [MEASURED, `tests/tgeometry.nim`; M1 port baseline (history): 33 test blocks / 98 checks, none dropped; current count: 92 `[OK]` test cases in `results/nimble-test.log` (M2, 2026-11-08)]
- Collinear rays skipped (neighbouring +-eps rays cover them).
- Token standing on an endpoint: that endpoint skipped, hits at t <= 1e-9 ignored.
- T-junction, shared vertex, free-standing wall, '<' apex, box corner, behind-viewer fan, long thin corridor.
- Angle-sort bug: circle angles must use the same (-pi, pi] range as wall angles (`atan2(sin,cos)`), otherwise bow-tie polygon (position dependent) [MEASURED bug, prototype `NOTES.md` "Post-phase-3"]. Regression test: `tests/tgeometry.nim`, suite "visibility", test "wall endpoints behind the viewer: fan stays angularly ordered".
- Vision circle is an inscribed 64-gon: error <= ~0.12% of R [MEASURED, prototype `NOTES.md`].
### 5.3 Performance [MEASURED; single laptop, release build, loopback, power-save CPU; `results/bench.log`, `results/concurrency-final1-server.log`]
| item | avg | worst |
|---|---|---|
| 1 visibility polygon (prototype scene, 60 walls) | 0.038 ms | 0.18 ms |
| 1 polygon + `cellsTouched` | 0.451 ms | 0.98 ms |
| 6 polygons + `cellsTouched` | 2.95 ms | 3.73 ms |
| server vision recompute per player move (incl. cells + diff) | 1.18 ms | 4.55 ms |
| door toggle (2 players) | 0.20 ms | 0.30 ms |
| monster move | ~0 | 0.024 ms |
Conclusions:
- `cellsTouched` is ~12x the polygon itself and dominates [MEASURED]. M2 target: replace per-cell polygon tests with scanline rasterization of the polygon over the explored grid, differential-tested against the ported implementation [PROPOSED].
- Polygon cost is O(rays x walls in bbox) [MEASURED code reading, `server/geometry.nim` `visibilityPolygon` (ported unchanged from prototype)]. Prototype scene has 60 walls and 8 tokens, so this says nothing about big maps. With radius-bbox culling the cost scales with local wall density, not total walls [INFERRED]; a uniform spatial grid over walls is needed when scenes reach thousands of walls (M2 gate: bench with a synthetic 5k-wall scene, target polygon < 1 ms [PROPOSED test target, Q2: owner has no map size yet; revisit with real maps]). The 5k target is the sparse primary layout `genScene(16384, 5000, 1)` (`tools/scenegen.nim`): 0.082 ms avg [MEASURED, `results/bench.log`]. The dense layout `genScene(4096, 5000, 1)` is a stress reference (1.28 ms avg, ~207 walls in the vision bbox) [MEASURED]; revisit the uniform grid if real maps approach that density.
- Skip recompute when the token moved but its polygon is unchanged (prototype already compares `np == r.polys`).
### 5.4 Known limitations (carry forward)
- Token exactly on a wall cannot move off it: `moveBlocked` counts any touch as a hit, so every move from that point is blocked, even a perpendicular step to the open side [MEASURED limit, `tests/tgeometry.nim` test "KNOWN LIMITATION: token exactly on a wall cannot move off it"; also in the `server/geometry.nim` header]. Known limitation, not a policy. Fixed in M2 by the escape rule (5.5). The escape is required by Q14 so the GM can move such a token: mechanism [PROPOSED], requirement [FIXED]. A validated move cannot reach this state (a destination within r of a wall is rejected) [INFERRED from `moveBlocked`]; it arises from a wall/door edit (`stuck` trigger, 5.5) or from a GM placement on a wall (GM placements ignore walls, 5.5); the escape rule covers both.
- Closing a door on a token [FIXED, owner 2026-11-08, supersedes the earlier `blocked` decision for doors; 2026-11-10 #4: failure is `squeezed`]: the token is pushed aside (5.5), `squeezed` only if neither side is valid. Editing or adding a wall on a token [FIXED, Q14]: the token gets `stuck` (trigger narrowed to circle overlap, 5.5). The server refuses that token's player moves; the GM can still move it; status clears per the 5.5 Keep/Clear rules (wall removed or door opened and no other wall overlaps, GM move to a free spot, or GM clear). Current pin: `tests/tgeometry.nim`, suite "door/wall closing on a token", test "door closed on a token: Q14 undecided, DESIGN 5.4 vs 12 H2 conflict": a token whose centre is 10 px off a closed door may move to a clear spot, may not stay overlapped, and may not cross the door. It pins `moveBlocked` only; it is replaced in M2 by tests of the 5.5 policy (under the 5.5 trigger this token is `stuck`, so player moves are refused).
- Boundary epsilon ambiguity (RayEps 1e-4, inclusive tolerances).
- Explored and tile checks in the leak test recompute with the server's own `cellsTouched`: self-consistency only (caveat in 10.2). New independent oracle in section 10.
- Doors/walls changing does not un-explore anything; explored only grows [MEASURED behaviour].
- Single uniform vision radius in prototype; v1 uses a per-entity numeric property (`vision_radius`) with scene default; no light/darkvision [FIXED, Q7].
- Vision origin = token centre, radius is not clipped by the token's own size.
### 5.5 Move rules and statuses (M2 decisions, 2026-11-08; status model 2026-11-10, #4)
Normative for M2. Replaces the prototype move validation (5.1) and the move-related limitations in 4.2 and 5.4. Implemented as a pure in-process module with unit tests; the WebSocket layer only maps its result to `ack` (6.1). The WebSocket probing test is M3.
Notation: token centre `c`, radius `r` (entity `radius` if set, else scene `token_radius_default`; 5.6), start `s`, destination `d`. Blocking wall: segment with `kind=wall`, or `kind=door` with `open=false`; open doors do not block. `dist(X, W)` = distance from point or segment `X` to segment `W`. "Overlaps" = `dist < r` (strict; touching at exactly r is clear).
**Statuses `stuck` and `squeezed`** (replace the M2 `blocked` bool) [FIXED, owner (B), Q14, refined 2026-11-08; FIXED, owner 2026-11-10, #4]. Both are cause-agnostic lock conditions: a locked token cannot be moved by its player; the GM always can. `stuck` = held in place (wall through it, ropes, magic grasp); `squeezed` = pressed, no room (walls around it, closing hand).
- Storage: a token holds a set of `(status, source)` entries (stored on the entity, persisted); the same status may come from several sources. Locked while any entry exists. Both statuses may show at once. Sources: `walls` (set by the rules below) and `GM` (GM sets either status by hand for any reason; GM can clear any single entry at any time). Visibility: every recipient who sees the token gets `status` only; `source` is GM-only (6.1, amended 2026-11-14).
- Overlap: `dist(c, W) < r` for a blocking wall `W`. An open door stops blocking, so opening = removing that wall for this rule; closing = adding it. Centre-on-wall is not required.
- Set (source `walls`): a wall is added or updated -> every token overlapping that wall gets `stuck`. (A door CLOSING on a token does not set it: push rule below.) The GM places or moves a token to a position overlapping any blocking wall -> `stuck`.
- Keep: while any blocking wall still overlaps the token, its `walls`-sourced entries stay (opening a door does not free it if another wall overlaps).
- Clear: a wall is removed or a door opened -> each token that overlapped that wall keeps its `walls`-sourced entries only if it still overlaps a remaining blocking wall; otherwise they clear. A shrink (5.6) that ends the overlap clears them likewise. The GM moves the token to a position overlapping no blocking wall -> `walls`-sourced entries cleared. `GM`-sourced entries clear only by GM action (any single `(status, source)` entry; wire intent `status.clear`, 6.1).
- **Door closing on a token = push aside, not stuck** [FIXED, owner, 2026-11-08; changes the door case only]: each token (player or GM-owned) with `dist(c, door) < r` is moved perpendicular to the door segment, to the side its centre is already on, by the minimal distance that ends `>= r` from the door (+ `PushEps` = 1e-6 px; past the door's end the offset is `sqrt(r^2 - e^2)`, `e` = along-axis overshoot). Centre exactly on the door line: side of the token's previous position (position before its most recent move or push; `prev`/`hasPrev` on the token); no history, or previous also on the line: left of the door's a->b direction (deterministic default). The pushed position must be in bounds and `>= r` from every blocking wall (the closed door included); else the opposite side is tried; if neither is valid the token stays and gets `squeezed` (source `walls`), and opening that door later clears it per the Clear rule. A pushed token is clear of walls, so its `walls`-sourced entries clear. The push is a server-originated position change returned by the move-rules module (list of token index + new position) so M3 can broadcast it and recompute vision; no step cap applies. Each token is pushed independently; tokens do not block tokens (no token-token collision; the `blocks_move` flag is not modelled in M2), so pushed tokens may overlap each other. Wall add / wall update / GM placement or move inside a wall are unchanged (stuck). Door open is unchanged.
- An event changes only the tokens it touches (those overlapping the changed wall, or the moved token). An unrelated wall change elsewhere never re-sets a GM-cleared token.
- After the GM clears the `walls`-sourced entries while a wall still overlaps and no other entry remains, the player escape rule (step 3 below) applies unchanged: the token may step out without crossing, destination >= r from every blocking wall.
- `wall.update` = remove then add for this rule [PROPOSED; not in the owner's list].
- Player moves while locked (any entry): the uniform nack (unchanged).
**Player move `s -> d`** [FIXED, accepted default]. Checks in order; any failure gives the uniform nack.
1. Controller check (not controlled -> `ack{ok:false, code:"not-allowed"}`, no position; 6.5) and token not locked (no status entry).
2. Step cap [FIXED, owner]: `|d - s| <= cap`, where `cap` = the token's `vision_radius` if the token has `vision` and sets it, else the scene's `vision_radius_default`.
3. For each blocking wall `W`:
- if `dist(s, W) < r` (start overlaps `W`, escape case): allowed only if the path `s->d` does not cross `W` (crossing at parameter t > eps; collinear overlap counts as crossing) AND `dist(d, W) >= r`;
- otherwise (swept/capsule check): allowed only if `dist(segment s->d, W) >= r`, which also gives `dist(d, W) >= r`.
4. Accept: `ack{ok:true, pos:d}`. Nack: `ack{ok:false, pos:s}` for locked, over-cap and collision alike. No reason field, no `code`.
**GM move** [FIXED, owner (D)]: no wall check, no step cap, ignores locks. Bounds and referential checks still apply; after the move its `walls`-sourced entries are recomputed (set/clear rules above). A GM move out of bounds gets the same uniform nack as a player move (`ack{ok:false, pos:old}`) [RECORDED, as implemented].
**Wall index** [FIXED, accepted default, H3]: radius-bbox cull first; uniform spatial grid over walls only if the 5k-wall bench misses target (13, M2).
**Thresholds and tolerances** [FIXED, accepted default]: `eps` and any float tolerance are chosen by the implementer and documented in the module header. Oracle comparisons use 0.5 px, as the leak checker (T14).
**Regression baseline** [FIXED, accepted default]: "results equal old implementation" = `visibilityPolygon` and `cellsTouched` on the prototype leak transcripts plus `tests/fixtures/scene.json`. `moveBlocked` is excluded: its results change on purpose.
**Unconfirmed** [PROPOSED, owner to confirm]: (a) `wall.update` as remove + add. Former (b) (door opened while another wall overlaps clears `stuck`) is closed by the Keep rule above [FIXED, owner, 2026-11-08].
### 5.6 Token size and grow push [FIXED, owner decision 2026-11-10, #4]
- **Size:** `r` = entity `radius` if set, else scene `token_radius_default`. Units: px (map units). Client size presets (S/M/L, squares) are UI convenience only. Validation: `radius > 0`; no upper cap. Only the GM sets a radius; anyone who sees a token sees its radius.
- **Scene default change:** every token using the default is resized by the same rule, per token.
- **Shrink** never pushes. It can clear `walls`-sourced entries (5.5 Clear).
- **Grow push:** GM grows a token -> the server pushes it away from every blocking wall it overlaps, by the minimal displacement that ends `>= r` from every blocking wall, stays in bounds, and does not enter any other wall. No step cap. Deterministic; the tie-break is fixed and documented in the module header [PROPOSED]. Each token is pushed independently (tokens do not block tokens). The position change is server-originated: broadcast like the door push, vision recomputed for affected players.
- **Grow fails** (no valid position): the token stays (its graphic may overlap walls) and gets `squeezed` (source `walls`).
- Wire intents: `token.resize`, `status.set`, `status.clear` (6.1) [FIXED (owner-delegated, 2026-11-14, #11)].
---
## 6. Protocol
Transport: one WebSocket per client at `/ws`, JSON text frames (a binary frame counts as malformed, 6.5). Envelope: `{t: string, ...fields}`; every server frame adds a per-connection counter `n` (starts at 1 on the connection's first frame; replaces the global `gseq` for everyone, section 3.1).
The whole of 6 is [FIXED (owner-delegated, 2026-11-14, #11)] unless a line says otherwise: the owner delegated the wire shapes and accepted the set. It is the complete M3 wire catalogue (29 intents, 15 server messages); nothing outside it exists in M3.
Conventions:
- **Naming.** Client -> server `t` is `<noun>.<verb>`: lowercase ASCII, exactly one dot. Nouns follow GLOSSARY.md: `token` (the map figure; the word "entity" never appears on the wire), `character`, `player`, `key` (a player key), `status`, `name`, `encountered`, plus `wall`, `door`, `scene`, `prop`, `conn`, `act`. Server -> client `t` is a bare state or event noun, snake_case, **no dot** (`token`, `token_gone`). A server `t` therefore never equals a client `t`.
- **Correlation.** Every intent carries `reqId` (client-chosen integer, 0 <= reqId < 2^31, unique among that connection's pending intents; the server echoes it and never interprets it). The server sends **exactly one** `ack` per intent, whatever the outcome. Frames whose envelope cannot be read (not a JSON object, no string `t`, no integer `reqId`) cannot be acked and get `error` instead (6.5).
- **Ack.** `ack {reqId, ok:bool, code?, id?, pos?, key?, ts?}`. `ok:true` carries only the result fields listed per intent (`id` of a created thing, `pos` of a move, `key`, `ts`). `ok:false` carries a static `code` from 6.5, except the uniform move refusal (T9, next bullet). An ack means "decided". It is enqueued after COMMIT and before the effect messages (4.2), but state messages are coalesced (4.3), so a client must not rely on any order between an ack and the state messages it caused.
- **Uniform move refusal (T9).** A refused move by a controller (locked, over step cap, wall collision; 5.5) and a GM move out of bounds both give `ack {ok:false, pos:<old position>}` with **no `code`**: one shape, no reason. Every other refusal carries a `code` and never carries a position.
- **Effects.** An intent's effects reach clients only as state messages, each built per recipient (3.1, 8) and sent only when that recipient's view changed (T11). "GM" below = every GM connection; "player X" = every connection of player X; "visible" = per the view rules in 3.1.
- **Roles.** Sender column: P = player, G = GM. A P-sender intent from a connection whose player has no name yet is refused `not-allowed`, except `conn.ping` and `player.setname`.
- **Not in M3:** `act.do` is reserved (v1 answers `no-rules`); server -> client `event` is reserved (9); GM `view.player` (7.3) is later; none is built in M3. Wire changes for M4/M5/M6 are limited to what 6.5 marks.
- **Slice-3 rollout note [FIXED (owner-delegated), #18].** The catalogue below is the contract; the handlers land slice by slice. Until a slice lands, its intents still get exactly one `ack` with the static code `unknown-type` and no state, so a half-built server never lies about having applied anything. Slice 3 builds the envelope, `hello`, `error`, `closing`, `conn.ping`, `act.do` (`no-rules`), and the three auth intents of slice 2 (`key.create`, `key.replace`, `player.remove`).
### 6.1 Catalogue
Field notes shared by all rows: `pos:[x,y]` px floats, in bounds `0 <= x <= w`, `0 <= y <= h`; `scene` = the one scene's id (kept on the wire per 8); ids are the server-assigned ids of 8; `props` = `{public?:{}, owner?:{}, gm?:{}}`; a prop key is a string of 1..64 chars, a value is any JSON whose serialized size is <= 8 KB, at most 64 keys per bucket [numbers delegated, #11]. Unknown fields in an intent are ignored (6.2); a missing or wrongly typed field is `invalid`.
#### Client -> server (intents)
Every row also carries `reqId` (omitted below). Codes are those of 6.5; `not-allowed` for a P sender on any G-only intent is implied and not repeated.
**Connection and reserved (2)**
| t | fields | who | ack ok `{...}` / extra codes | effects and recipients |
|---|---|---|---|---|
| `conn.ping` | `ts:int` | P, G | `{ts}` (echo) | none; liveness only, lag is measured with WS Ping/Pong (4.3) |
| `act.do` | `actor, action, args` | P, G | never ok: `no-rules` | none; **reserved** for the FFF hook (9) |
**Players and keys (6)**
| t | fields | who | ack ok / extra codes | effects and recipients |
|---|---|---|---|---|
| `player.setname` | `name` | P, only while own name is null | `{}`; `invalid`, `name-taken`, `not-allowed` (already named, or GM) | every connection of that player gets `hello` with `me.name` set, then the full resync (6.3); `roster` to all [FIXED, #6: asked once; GM-only renames after] |
| `player.rename` | `id, name` | G | `{}`; `not-found`, `invalid`, `name-taken` | `roster` to all connections of named players and to GM |
| `player.remove` | `id` | G | `{}`; `not-found`, `not-allowed` (the GM) | key and sessions invalidated; that player's connections closed with WS 4001 (6.5); characters and controlled tokens pass to the GM (`character` with owner GM to the GM; `token` updates per view); their encountered list and name reveals deleted (GM gets `encountered {player, full:true, set:[]}`); `roster` to all (3.2) |
| `key.create` | none | G | `{id:<new player id>, key}`; `cap-reached` (6 players incl. unused keys) | `roster` to GM (the new entry has `name:null`; players do not see unnamed players) |
| `key.replace` | `id` | G | `{key}`; `not-found`, `not-allowed` (the GM's own key rotates only by CLI, 3.2) | old key invalid, all sessions of that player revoked, all its connections closed with WS 4001; identity, characters, encountered list kept; `roster` (connected flags) |
| `key.show` | `id` | G | `{key}`; `not-found`, `not-allowed` (GM key: CLI only) | none |
**Scene, walls, doors (5)**
| t | fields | who | ack ok / extra codes | effects and recipients |
|---|---|---|---|---|
| `scene.set` | `scene`; any of `name, grid_size, vision_radius_default, token_radius_default, extra` (at least one) | G | `{}`; `invalid`, `not-found` | `hello` plus full resync to **every** connection (hello-equivalent reset; no `scene.activate`, Q3). `token_radius_default` change resizes tokens using the default with grow push (5.6): `token` updates per view, `vision`/`explored` as needed. `w, h, tile_size, cell, art_version` are not settable on the wire (import is M6 CLI) |
| `wall.add` | `scene, a:[x,y], b:[x,y], kind:"wall"|"door", open?:bool (default false), flags?` | G | `{id}`; `invalid`, `not-found` | `wall` to GM; vision recompute for all players (`vision`, `explored`, `token` as their views change); tokens whose circle overlaps get `stuck` source `walls` (5.5): `token` per view |
| `wall.update` | `scene, id`; any of `a, b, kind, flags` | G | `{}`; `not-found`, `invalid` | as `wall.add` (update = remove + add for the status rules, 5.5; PROPOSED there) |
| `wall.remove` | `scene, id` | G | `{}`; `not-found` | `wall_gone` to GM; recompute; `walls`-sourced entries re-evaluated (Keep/Clear, 5.5) |
| `door.set` | `scene, id, open:bool` | G | `{}`; `not-found`, `invalid` (wall is not a door) | `wall` to GM (a door is a wall); recompute all players; close pushes overlapped tokens aside (server-originated position change: `token` per view; `squeezed` only if no side is valid), open re-evaluates `walls`-sourced entries (5.5). Players learn only through LOS changes |
Validation for `wall.*`: `a != b`, both in bounds, `kind` in `wall|door`, `flags` an object or absent.
**Tokens, statuses, props (9)**
| t | fields | who | ack ok / extra codes | effects and recipients |
|---|---|---|---|---|
| `token.create` | `scene, kind, pos`; plain token (no `character_id`): `descriptive_name, actual_name` required; linked: `character_id` and **no** names; optional `controller` (player id or null = GM; default: the character's owner if linked, else GM), `radius` (px > 0), `vision_radius`, `gm_only`, `flags`, `props` | G | `{id}`; `invalid`, `not-found` (scene, character or controller) | `token` to the GM and to each recipient who sees it (the controller always); vision recompute; GM placement ignores walls, `stuck` if it overlaps one (5.5); a new `encountered` entry for a player who sees it (diff) |
| `token.update` | `id`; any of `kind, descriptive_name, actual_name, character_id (string = link, null = unlink), controller (player id or null), gm_only, flags, vision_radius (number or null)` | G | `{}`; `not-found`, `invalid` (links with names; unlinking without both names) | `token` per view. Controller change: `mine` flips, the old controller loses the token unless it is in their LOS (`token_gone` by diff), vision recomputed for both; **never** changes the character owner. `gm_only` set: players lose it (`token_gone`); their `encountered` entry stays, greyed (8) |
| `token.move` | `id, pos` | P (controlled) / G (any) | `{pos}` (accepted position); P refused: uniform `{ok:false, pos:old}` (5.5); non-controlled or unknown id for P: `not-allowed` (one code for both, no existence oracle); G unknown id: `not-found`; G out of bounds: uniform nack | `token` per view; vision for the mover's player; `explored` fresh cells; pushes/status changes as server-originated `token` updates |
| `token.resize` | `id, radius:number>0 or null` (null = back to the scene default) | G | `{}`; `not-found`, `invalid` | `token` per view (effective `radius`); grow pushes or sets `squeezed`, shrink may clear `walls`-sourced entries (5.6) |
| `token.remove` | `id` | G | `{}`; `not-found` | `token_gone` to every recipient who knew it; its `encountered` entries stay and turn grey (never auto-removed, 8) |
| `status.set` | `id, status:"stuck"|"squeezed"` | G | `{}`; `not-found`, `invalid` | adds entry `(status, source GM)`; `token` per view (#4) |
| `status.clear` | `id, status, source:"walls"|"GM"` | G | `{}`; `not-found` (token or entry) | removes that single entry; `token` per view; then the escape rule (5.5) |
| `prop.set` | `target:"token"|"character", id, bucket:"public"|"owner"|"gm", key, value` | G (v1; owner-bucket writes by players come with FFF actions, 9) | `{}`; `not-found`, `invalid` | token target: `token` per view (bucket filtered). Character target: `character` to GM and to the owner (public/owner buckets only), and `token` updates (`cprops`, public bucket) to recipients who see a token of that character |
| `prop.unset` | `target, id, bucket, key` | G | `{}`; `not-found`, `invalid` | as `prop.set`; unsetting an absent key is ok |
**Characters, names, encountered (7)**
| t | fields | who | ack ok / extra codes | effects and recipients |
|---|---|---|---|---|
| `character.create` | `descriptive_name, actual_name, owner?:player id (default: the GM), props?` | G | `{id}`; `invalid`, `not-found` (owner) | `character` to GM and to the owner |
| `character.update` | `id`; any of `descriptive_name, actual_name` (props go through `prop.set`) | G | `{}`; `not-found`, `invalid` | `character` to GM and owner; `token` names per view for its tokens; `encountered` upserts for players who met it |
| `character.remove` | `id` | G | `{}`; `not-found`, `in-use` (any token still links it; GM removes or unlinks the tokens first) | `character_gone` to GM and owner |
| `character.reassign` | `id, owner:player id` | G | `{}`; `not-found`, `invalid` | `character` to GM and the new owner, `character_gone` to the old owner; **no** token controller changes (3.1); reveals kept [PROPOSED, 8]; `token` per view (`character_id` and actual name visibility follow the owner) |
| `name.reveal` | `subject:"character"|"token", id, player` (the player's id) | G | `{}`; `not-found`, `invalid` (a token that has a character: reveal through the character) | to that player only: `token`, `character`, `encountered` updated with the actual name; to GM: the updated `revealed` list. Reveals never revoke (8); there is no un-reveal intent in M3 |
| `name.reveal_all` | `subject, id` | G | `{}`; `not-found`, `invalid` | sets `reveal_all`; as `name.reveal` for every player. Idempotent |
| `encountered.remove` | `player, id` (token id) | G | `{}`; `not-found` (player or entry) | `encountered {del:[id]}` to that player, same to GM |
Count: 29 intents (2 + 6 + 5 + 9 + 7).
#### Server -> client
All are built per recipient at egress (single egress rule, 2). "Sent" always means: only when that recipient's view changed. Fields marked (GM) go to GM connections only; (P) to player connections only.
| t | content | recipient |
|---|---|---|
| `hello` | `proto:int, role:"gm"|"player", me:{id, name|null}`; unless the player is unnamed: `scene:{id, name, w, h, tile_size, cell, grid_size, vision_radius_default, token_radius_default, art_version}` plus `extra` (GM). No counts, no wall data, no owned ids (`mine` is on `token`) | the connecting connection, first frame; again on `scene.set` (all connections) and after `player.setname` (that player's connections). The client resets all state on receipt. An unnamed player gets only `proto, role, me` and nothing else until named |
| `ack` | see Conventions | sender connection only |
| `error` | `code` (`malformed` or `rate-limited`; 6.5) | sender connection only; only for frames that cannot be acked |
| `roster` | `players:[{id, name, role, colour, connected}]`, always the full list | everyone (Q9). Players receive named players only (an unused key is not visible); GM receives all, `name:null` for unnamed |
| `walls` | `scene, walls:[{id, a, b, kind, open, flags}]` | GM, on connect and resync (6.3) |
| `wall` | `scene, id, a, b, kind, open, flags` (upsert; doors included; this replaces the old `door` message) | GM only |
| `wall_gone` | `scene, id` | GM only |
| `vision` | `polys:[{id:<token id>, pts:[[x,y],...]}]` integer px, the full set for this player's controlled tokens with `vision` | player only; never GM |
| `explored` | `full:true, rle:[[cy, x0, len, x0, len, ...], ...]` on connect and resync; `full:false, cells:[[cx,cy],...]` afterwards (fresh cells) [format PROPOSED, 6.4] | player only; never GM |
| `token` | `id, scene, name, pos, radius, mine, statuses:[{status}], props`; `name` = the one name this recipient may see (8), no reveal state; `radius` = effective px; `props` = only the buckets this recipient may read (public; plus owner for the controller; all three for GM). More for specific recipients: `statuses[].source` (GM only); `character_id` (GM, and a player who owns that character); `cprops:{public:{}}` the character's public props (player who does not own the character; `{}` for a plain token); `kind, controller (id or null), gm_only, flags, vision_radius, radius_own (number or null)` (GM); `vision_radius` also for the controller (the step cap, 5.5); plain tokens, GM: `descriptive_name, actual_name, reveal_all, revealed:[player ids]` | GM: all tokens; player: tokens they control, plus tokens inside own LOS and not `gm_only` (3.1). Whole view of one token per message |
| `token_gone` | `id` | a recipient who had it in their `known` table and no longer may see it (left LOS, removed, `gm_only` set, controller lost it). Never sent for a token the recipient never saw |
| `character` | GM: `id, owner, descriptive_name, actual_name, reveal_all, revealed:[player ids], props:{public,owner,gm}`. Owner (P): `id, descriptive_name, actual_name, props:{public,owner}`; the owner is never sent `reveal_all` or `revealed` | GM: every character; player: only the characters they own. No other player ever gets a character record (no browsable list, T16) |
| `character_gone` | `id` | GM; and the previous owner on reassign |
| `encountered` | `full:bool, set:[{id:<token id>, name, grey:bool}], del:[id]`; `full:true` replaces the whole list (on connect, resync); (GM) adds `player:<id>` | player: own list only; GM: one message per player and list. `name` = the name that recipient's player knows (8); `grey` = no longer in that player's view ("met before, whereabouts unknown"); no position, no `character_id` for players |
| `closing` | `reason` (one of the static strings of 6.5: `revoked`, `evicted`, `proto-mismatch`, `malformed-flood`) and `code` (the 6.5 close code: 4001, 4002, 4003, 1008) | sender connection only; the last frame a server-initiated close sends, immediately before the close frame (FIXED #18, 6.5). No other frame follows it |
Count: 15 server messages. Reserved, not built: `event` (9).
Leak notes (R5 review, #11): (1) `kind` is GM-only because a value like `npc` would tell a player what a visible token is; the client names tokens from `name` and `props`. (2) `character_id` goes only to the character's owner and the GM; showing it to others would link two tokens of one character and mark a token as "a character, not a monster". (3) `cprops` is public bucket only and always present (even empty) for non-owners so presence does not mark a token as character-linked. (4) The roster omits unnamed players for players so an unused key (or the number of keys) is not visible. (5) `hello` carries `vision_radius_default` so the client can respect the step cap (5.5); it states a distance only, no wall fact. (6) `statuses[].source` goes to the GM only (amends #4, 2026-11-14): viewers see the status, not its cause, so a player does not learn that a wall or GM action caused it. Open: a `walls`-sourced status still tells a viewer that some blocking wall touches the token; #4 argued LOS covers that, owner to confirm. (7) `encountered.grey` flipping and `token`/`token_gone` carry the same fact (the token left view), so deletion and moving away look identical to the player.
### 6.2 Versioning [PROPOSED]
- `proto` is an integer compiled into both client and server; M3 ships `proto = 1`. The client announces it in the upgrade request (`/ws?proto=N`), and the parameter is required: absent or not a plain integer is HTTP 400, no upgrade (6.5 row 3). Any mismatch, older or newer, is refused (6.5 row 5): the upgrade completes and the server sends `closing {reason:"proto-mismatch", code:4003}` and closes, because a browser `WebSocket` cannot read an HTTP status, only a close code (and the code itself cannot be sent at the mummy pin, 3.2). The client then shows "reload" (assets are content-hashed by Vite, so a reload fetches the matching client). No `hello` and no state are sent on a mismatch. `hello.proto` is checked again on receipt as a backstop.
- Within one proto version: additive only (new optional fields, new message types). The client ignores unknown server message types and unknown fields; the server ignores unknown fields in intents and answers an unknown `t` with `ack {ok:false, code:"unknown-type"}` (or `error {code:"malformed"}` if there is no `reqId`).
- Breaking change -> bump `proto`, document in `docs/` changelog.
### 6.3 Reconnect and resync
- Reconnect = full resync. After `hello` the server sends, in this order [PROPOSED]: `roster`; GM: `walls`, `character` for all, `encountered` per player (full), then `token` for all; player: `character` for owned, `encountered` (full), `vision`, `explored` (full), then `token` for all visible and controlled. An unnamed player gets only `hello` until `player.setname` succeeds, which triggers the same sequence on that connection. The client reducer resets everything on `hello` (reconnect-reset bug fixed in prototype, test in `client/src/state.test.ts`, 4/4 pass) [MEASURED]. Clients must tolerate any order after `hello`.
- No gap detection and no `resume(since)`: WS over TCP is ordered and lossless while connected, and a reconnect restarts from a full snapshot. Full resync on every reconnect [FIXED, Q15]. Revisit if a measured snapshot exceeds ~100 KB.
- Client reconnect: exponential backoff with jitter, cap ~10 s (prototype: fixed 2 s). Pending `reqId`s are dropped with the old connection (client-side, M4); a `hello` on a live connection (`scene.set`, first name) does **not** drop them: their acks still arrive. Assets (tiles) are kept across reconnect because explored only grows [MEASURED prototype behaviour].
- Same player on two connections: both synced; each has its own `known` table. Multiple devices per player allowed (Q10, FIXED), up to 4 (4.3).
### 6.4 Deltas and size
- Tokens: `token` only when the recipient's view of it changed; `token_gone` on leaving view; per-connection `known` table gives correct enter/leave [MEASURED, leak test (c)].
- Bytes [MEASURED, `results/concurrency-final1-server.log`]: monster move 145 B to a seeing player, 244 B to GM; player move: mover 3359-3653 B (worst 4.9 KB, dominated by the full `vision` polygon + `explored` diff), GM 145 B; door toggle 45 B (prototype `door` message; the M3 `wall` upsert is a little larger).
- v1 decisions [FIXED, Q16]: full vision polygon, integer px (halves the text size [INFERRED]), owner only, sent only on change; deltas/binary post-v1. Explored on connect as run-length rows, later diffs as cell lists [PROPOSED].
- Move rate [FIXED (owner-delegated, 2026-11-14, #15)]: client sends at most ~20 Hz while dragging (prototype 50 ms) plus a final position. Server: token bucket per connection, 30 intents/s sustained, burst 100, same for GM and players. Excess intents are refused with `ack {ok:false, code:"rate-limited"}`; no rollback: each intent is atomic (accepted ones stay, rejected ones are never applied); the connection stays open. Reconciling refused optimistic edits is client behaviour (M4).
- Max inbound WS message [FIXED (owner-delegated, 2026-11-14, #15)]: 64 KB = mummy 0.4.8 default `maxMessageLen` (inbound only, cumulative across fragments). The server passes it explicitly (`protocol.MaxInboundBytes`), so a mummy default change cannot move the limit silently. Over the limit mummy closes TCP without a close frame (mummy.nim :658-660). No config; outbound unaffected.
- Per-connection `n` counts **server frames only**, starting at 1 with `hello`; a Ping/Pong (4.3) is a control frame and does not consume a number. There is no global counter on the wire (H25).
- Server Ping [FIXED (owner-delegated), #18]: one immediately after `hello`, then one every 20 s on every connection (`protocol.PingIntervalMs`); payload = the sequence number the client echoes in its Pong. Sending, recording and the interval are slice 3; lag measurement and the stop-feeding rule are M5 (4.3).
### 6.5 Refusals, errors and connection outcomes [FIXED (owner-delegated, 2026-11-14, #11)]
**Intent pipeline (order of checks).** The first failing step decides the reply; nothing is applied on any failure.
1. Frame over 64 KB: mummy closes TCP, no reply (6.4).
2. Not a UTF-8 text frame holding a JSON object with string `t` and integer `reqId` in range: `error {code:"malformed"}`, and it counts toward the malformed flood limit.
3. Rate limit (token bucket, 6.4): empty bucket -> `ack rate-limited` (or `error rate-limited` if step 2 failed).
4. Unknown `t` -> `ack unknown-type`.
5. P sender without a name, other than `conn.ping` and `player.setname` -> `not-allowed`.
6. Role: a G-only intent from a player -> `not-allowed`.
7. Field types and ranges -> `invalid`.
8. Target lookup. Player senders: a target that is not theirs or does not exist is one and the same `not-allowed` (no existence oracle, T9). GM senders: missing target -> `not-found`.
9. Semantic validation (GM: `invalid`; player move: the uniform nack, 5.5).
**Ack codes (static strings, never carry state).**
| code | meaning |
|---|---|
| `rate-limited` | token bucket empty (6.4); nothing applied |
| `unknown-type` | `t` is not in 6.1 |
| `not-allowed` | wrong role, not the controller, unknown or not-theirs target (players), unnamed player, GM key via the wire, `player.setname` when already named |
| `not-found` | GM-only: scene, wall, token, character, player or entry does not exist |
| `invalid` | missing or mistyped field, out of bounds, bad geometry, names/links inconsistent, bad name text |
| `name-taken` | player name already used (case-insensitive, includes `GM`) |
| `cap-reached` | `key.create` would exceed 6 players (3.2) |
| `in-use` | `character.remove` while a token links the character |
| `no-rules` | `act.do` (reserved, 9) |
Player name text: trimmed, NFC, 1 to 32 code points, no control characters. Character and plain-token names: 1 to 64 code points, same rules. All are rendered with `textContent` (T13).
**`error` frame (no `reqId`).** Codes `malformed`, `rate-limited` only; connection stays open unless the flood rule fires.
**Connection-level outcomes.** Order of checks on a `GET /ws` request, then on the open socket:
| # | condition | outcome | stage |
|---|---|---|---|
| 1 | `Origin` header missing or not equal to the configured public origin (T7) | HTTP 403, no upgrade | before upgrade |
| 2 | no session cookie, or its hash is unknown or revoked | HTTP 401, no upgrade | before upgrade |
| 3 | `proto` query missing or not an integer; request is not a WebSocket upgrade | HTTP 400 | before upgrade |
| 4 | total connections would exceed 16 after the player's own oldest is evicted (#15): the 17th | HTTP 503 with `Retry-After: 5`, no upgrade | before upgrade |
| 5 | `proto` differs from the server's (6.2) | upgrade completes, then WS close **4003** `proto-mismatch`; no `hello`, no state | open |
| 6 | the player already has 4 connections (#15): the 5th | the oldest of that player stops receiving at once and is closed with WS **4002** `evicted` (the close frame queues behind its backlog, 4.3); the new one proceeds | open |
| 7 | key replaced, player removed, or GM key rotated: the session is revoked (3.2) | WS **4001** `revoked` on every affected connection (client must not auto-reconnect: it goes to the sign-in page) | open |
| 8 | 10 `malformed` frames within any 10 s on one connection [numbers delegated, #11] | WS **1008** `malformed-flood` | open |
| 9 | inbound message over 64 KB, bad opcode/rsv, unmasked or oversized control frame | mummy closes TCP with **no close frame** (client sees 1006); not catchable by app code | open |
| 10 | server shutdown (SIGTERM) | WS **1001** (going away) [M5, 4.4 handler] | M5 |
**How the outcome reaches the client [FIXED, owner decision #18, 2026-11-15: option A].** At the mummy 0.4.8 pin `close(ws)` emits an **empty** close frame, so a browser reports **1005** and none of the codes above can be sent; mummy is neither patched nor forked. Instead, every server-initiated close (rows 5-8) is sent as **two frames**: one final application message `closing {reason, code}` (6.1 `closing`), then the close frame. `reason` is the bold static string of the row; `code` is the row's numeric code (4001, 4002, 4003, 1008); `closing` also carries the connection's `n`. The client's rule: on 1005, the reason is the `reason` field of the last message it received. A close with no preceding `closing` is a transport failure (row 9 or a dead peer), not an application outcome. Rows 1-4 refuse before the upgrade, so they are plain HTTP statuses with no frame; row 10 (M5) is the same two-step shape with `reason:"server-shutdown"`, `code:1001`, and is not built yet.
Why not the alternatives: patching/forking mummy is fallback only (4.3), and a client-side heuristic on 1005 alone cannot tell eviction from revocation from a proto mismatch. Consequence for tests: every close assertion is "the last message is `closing` with this reason and code, then the close event reports 1005".
WS close reasons are the static strings in bold above. Close codes 4001-4003 are the app's range; 1008 and 1001 are the RFC 6455 standard codes. Lagging clients (M5, 4.3) get no close and no frame: they are not fed until resync, and nginx closes dead peers (M5).
### 6.6 HTTP surface in M3
- `POST /join` (the sign-in page; HTTP, not WS; 3.2). Body `application/x-www-form-urlencoded`, one field `key`, at most 1 KB (the server answers `400` above that; mummy closes far above it). Key comparison ignores case, dashes and spaces and is constant-time. Valid key (player or GM): `303` to `/` with `Set-Cookie: fff_session=<random>; HttpOnly; Secure; SameSite=Strict; Path=/` and `Referrer-Policy: no-referrer`; the session token is a fresh 32-byte hex value and only its SHA-256 is stored (3.2). Invalid key: `401`, no body detail, no cookie. Wrong method `405`; missing `key` or wrong content type `400`. No rate limit (owner, #6). The body is never logged (T6). Cookie name `fff_session` [FIXED (owner-delegated, 2026-11-14, #17)].
- `GET /ws`: 6.5 (rows 1-4).
- `GET /tiles/<scene>/v<art_version>/<x>_<y>.png`: 3.3 (`200` with `X-Accel-Redirect`, `403` unexplored, `404` malformed/out of range).
- `GET /healthz`: 200 `{"status":"ok"}` from M3 slice 1 [FIXED (owner-delegated, 2026-11-14, #16)]; M5 makes it report whether the global lock can be acquired within a bound (11.3).
---
## 7. Client
### 7.1 Layers (bottom to top, one Pixi stage under a world container with pan/zoom)
1. **Map tiles**: sprites per tile, loaded lazily for tiles the server allows.
2. **Grid**: one `TilingSprite` over a small cell texture, toggleable [MEASURED technique, `prototype-pixi-perf/README.md` Techniques].
3. **Entities/tokens**: pooled containers, shared `GraphicsContext` per colour, `BitmapText` labels.
4. **Fog (players)**: explored dim layer + vision cut-out (7.3).
5. **GM overlay (GM only)**: walls/doors Graphics, wall editor handles; hidden from players by never receiving the data.
6. **DOM overlay**: toolbars, token panel, player keys dialog, connection status; plain HTML on top of the canvas (no framework) [FIXED].
### 7.2 Rendering techniques kept from the perf prototype [MEASURED, `prototype-pixi-perf/README.md`]
- Verdict: Pixi v8 renders a VTT scene at 60 fps on Radeon 780M (WebGL and WebGPU) and Galaxy Note 10 (WebGL) up to 1000 tokens (Note 10 js ~14 ms, 2000 tokens -> 32-36 fps, CPU-bound; laptop js 9-12 ms at 2000). Only per-frame token JS scales; a table needs tens of tokens.
- **Update only changed entities**, never all per frame (chaos worst case is not a workload here).
- **BitmapText** with a pre-installed `BitmapFont` for labels (no raster/upload on change); limit: single font size blurs on zoom. Decision [FIXED, Q17]: names via BitmapText; glyph set = Latin incl. accented characters + Nerd Font icon glyphs. No non-Latin or emoji requirement, so no HTMLText/Text fallback in v1.
- **Shared GraphicsContext** per colour, tessellated once; pooled tokens.
- **Culling**: map tiles/baked sprites `cullable`; tokens fixed `cullArea`.
- **Map larger than max texture -> tiles**; WebGPU maxTex 8192 vs WebGL 16384 on the same GPU; phone maxTex 4096. A single 16384 texture ~1 GB VRAM: never upload big single textures, always tiles.
- **Baked strokes** (live Graphics chunks <= 48 pts, bake on pointer up) are available if drawing arrives post-v1; 200 strokes cost nothing on real HW [MEASURED], SwiftShader result was an artifact.
- **Input**: hand-rolled DOM pointer events for pan/zoom/pinch (pixi-viewport declared v8-compatible but custom token drag/pinch needed anyway); Pixi federated events off; O(N) hit test on press only.
- Fixed per-frame overhead on phone ~3 ms at 50 tokens vs 0.4 ms laptop [MEASURED, cause hypothesised overlay/culling]: keep the DOM overlay and per-frame work minimal.
- Unverified (carry as risks): iOS/Safari, WebGPU on mobile, tablets, HP-churn timing.
### 7.3 Fog rendering (new design; prototype's approach is explicitly not kept)
Prototype `client/src/main.ts`: explored rects appended to a `Graphics` mask forever (re-tessellated, flagged shortcut), one `Text` per token (heavy), unverified in a browser [HANDOFF.md]. Both replaced.
- Fog is a presentation of two server facts: `explored` cells and `vision` polygons. It is **cosmetic**: hidden tokens are never sent, so no client clip is needed for security.
- Three states per point: unexplored (opaque black), explored not visible (dim, ~0.6 alpha black), visible (clear).
- **Explored layer [PROPOSED]**: keep explored as a bitmap/RenderTexture at cell resolution (map/cell, e.g. 128x128 for 4096/32), updated by writing new cells; display scaled with smoothing. Memory fixed regardless of exploration; no unbounded Graphics. Exact Pixi mechanism (RenderTexture draw vs Uint8 texture resource) to be chosen in M4 with the pixijs skills; acceptance criterion is below.
- **Vision layer [PROPOSED]**: polygons (few, ~64-300 vertices each) drawn into a mask only when a `vision` message arrives; cut-out through a mask/erase blend.
- Soft edges: optional blur filter on the fog texture at cell scale; measure on Note 10 before enabling.
- GM view: fog disabled by default; optional "preview as player X" is a GM-side toggle that must not require extra data (GM client would need the player's polygons: it can request them as GM-only message `view.player` computed server-side) [PROPOSED, later].
- Browser rendering of fog/drag/reconnect is unverified in prototype (no browser in build env). M4 adds a headless-browser pixel check.
### 7.4 Input and UI
- Mouse: wheel zoom, drag pan, drag token. Touch: one finger drag/pan, two-finger pinch/pan [MEASURED works on Note 10].
- Wall editor (GM) [FIXED, Q6: in v1, kinds `wall`|`door` only]: click-click segments, snap to grid/endpoints optional, door tool, delete, undo of last edit [PROPOSED]; submits `wall.*` intents; server is the validator.
- Grid snap on drop: client option, off by default [FIXED, Q18]. Server accepts any in-bounds position within the step cap and clear of walls (5.5; step cap = effective vision radius, Q18 FIXED).
### 7.5 Prediction and rollback for own moves
- Players do **not** know the walls, so the client cannot predict collisions [INFERRED, consequence of strict model]. Prediction = optimistic placement of the dragged sprite, send `token.move` with `reqId` at <= 20 Hz, and a final send on release.
- While dragging, incoming authoritative positions for that token are ignored (prototype behaviour) so the sprite does not fight the pointer.
- `ack{ok:true,pos}` -> nothing to do (server pos == requested). `ack{ok:false,pos}` (no `code`) -> snap to `pos` if not dragging; if dragging, snap on release (do not teleport under the finger).
- Rollback visual: short tween back to `pos` (cosmetic).
- Pending request map keyed by `reqId`; dropped when the connection closes (6.3).
- Others' tokens: render the latest `token` message; interpolate between updates (client-side only, <= 100 ms) [PROPOSED].
---
## 8. Data model
All ids are server-assigned. **Walls [FIXED, owner decision 2026-11-10, #3]**: per-scene ids, each scene counts from 1. Removal never renumbers; ids are never reused. Each scene stores `next_wall_id` (monotonic, never decreases, even if the newest wall is deleted). Wall identity = `(scene, id)` in DB, server and wire. Wall ids are GM-only in v1. **Tokens/entities [FIXED, owner decision 2026-11-10, #3]**: random opaque id, 12 chars from `[A-Za-z0-9_-]`, from a CSPRNG; server checks collision on create. Unique game-wide (not per-scene), so a token may later change scene keeping its id (cross-scene move not in M3). Counted ids would leak hidden tokens through gaps. **Doors are walls** and use wall ids; toggling is GM-only in v1, so any door-id exposure later leaks at most about the wall count (accepted). Rejected: dense ids with renumber broadcast (in-flight intents hit the wrong wall); game-wide wall counter (per-scene ids keep scene copy/export stable).
- **Scene** (exactly one in v1, Q3): `id, name, w, h` (px), `tile_size` (32 default = `explored_cell` [FIXED, Q4]; 64 is the per-scene fallback), `explored_cell` (32 default; `tile_size % cell == 0` required, prototype assumes it silently), `grid_size`, `vision_radius_default`, `token_radius_default` (px, > 0, no upper cap [FIXED, #4]), `art_version`, `active`, free-form `extra`.
- **Wall/Door**: `scene, id` (per-scene, see above), `a:[x,y], b:[x,y], kind ('wall'|'door'), open:bool, flags`. `blocks = not (door and open)`. GM-only everywhere. Later kinds (window, one-way, secret door) are extra `kind`/`flags` values; v1 geometry treats any non-open blocker identically.
- **Entity (token and anything else) [PROPOSED, FFF seam]**:
- `id` (random text, see above), `scene, kind` (free string: `pc`, `npc`, `item`...), `character_id` (NULL = plain token, e.g. monster or item; else the character it figures), `descriptive_name`, `actual_name` (plain tokens only; a character's tokens use the character's names), `pos`, `radius` (px, > 0, no upper cap; NULL = use scene `token_radius_default`; GM-only to set [FIXED, #4]; 5.6), `owner` = token controller (player id or null = GM-controlled; independent of the character's owner, 8), `gm_only`, `flags` (`vision`, `blocks_move`...), `vision_radius` (optional; per-entity numeric with scene default, Q7 FIXED; also the player step cap, 5.5), `statuses` (set of `(status, source)` entries; status `stuck`|`squeezed`, source `walls`|`GM`; locked while any entry exists; Q14, 5.5, #4).
- `props`: three JSON objects by visibility bucket: `public` (anyone who sees the entity), `owner` (token controller + GM), `gm` (GM only). Keys are strings, values JSON scalars/arrays/objects with a size cap. No hidden state beyond these buckets and `gm_only` in v1 [FIXED, Q19].
- The server never interprets props in v1 except via a registered property schema (type, bucket, writable-by) used for validation and for FFF later.
- **Character [FIXED, owner decision 2026-11-10, #14]**: own record, separate from tokens. Fields (indicative): `id` (random, same format as token ids), `owner` (exactly one player id; the GM is a player, so GM ownership = the GM's player id; the GM reassigns), `descriptive_name`, `actual_name` (names rule below), `reveal_all`, `props` (three buckets, identity/base values). A character has any number of tokens in any scene. A new token for a character starts controlled by the character's owner; the GM may change it. Changing a character's owner never changes its tokens' controllers (GM adjusts by hand). Rejected: token controller derived from character; auto-follow on reassignment; all data on the token (duplicated stats); all data on the character.
- **Character props vs token props [FIXED, #14]**: the character holds who the figure is (identity, base values); the token holds what is happening to that figure (damage, conditions, scene effects). Plain tokens (monsters, items) keep their own data. Both use the three buckets: `owner` for a character = character owner + GM; for a token = token controller + GM. The server stores both and never interprets them; FFF decides the split (9). A recipient's view of a token is built from its own props and its character's props, each under its own bucket rule [PROPOSED].
- **Names [FIXED, #14]**: every character and every plain token has a `descriptive_name` (e.g. "a grumpy man") and an `actual_name` (e.g. "Lord Vex"). Players see the descriptive name until the GM reveals the actual name to that player; the GM can also reveal to all at once (`reveal_all`). The owner of a character always sees its actual name. A character's tokens use the character's names, so one reveal covers all of them. Applies to player characters too (introductions). A reveal cannot be undone in v1 (no un-reveal intent). Reveals are not revoked when ownership changes [PROPOSED].
- **Encountered list [FIXED, #14]**: per player, every token that the player's controlled tokens have ever seen, shown under the name that player knows. Out of sight: greyed ("met before, whereabouts unknown"). `gm_only` tokens never enter it; a token that becomes `gm_only` after a player met it keeps its entry (greyed). Entries are never removed automatically (not on token removal, scene change or a `gm_only` flip); only the GM removes an entry for a player. Server tracks and persists it. No browsable list of all characters for players. Not the player roster (Q9 lists players only).
- **Player**: `id, name (NULL until first sign-in; unique among players), role (gm|player), colour`. Exactly one GM. A player is a real person who signs in with a player key; not a character. A player may own several characters. Max 6 players; unused keys count toward the cap. GM can rename. Remove: see 3.2 [FIXED, #6].
- **Player key**: `player_id, secret (plaintext, re-showable by GM, Q11 FIXED), created`; one current key per player; replace overwrites. Format: 20 symbols in 5 groups of 4 with dashes, alphabet without look-alikes, CSPRNG (~99 bits) [FIXED, #6; implementation detail #17 in 3.2]. The GM's key is the GM player's key (3.2). Not a session [FIXED, #6].
- **Session**: `id, player_id, token_hash (SHA-256 hex of a 32-byte CSPRNG token; the token itself is never stored), created, last_seen`; never expires (Q10 FIXED).
- **Explored grid**: per `(player, scene)`, strictly per player (Q9 FIXED): bitset over `ceil(w/cell) x ceil(h/cell)` cells; persisted as chunked bitmaps (4.4). Only grows. Players with no vision-enabled entity have an empty grid.
- **Vision polygons**: runtime only, never persisted (recomputed at start).
- **Connection (runtime)**: id, player, `known` map, last vision ver, counter.
Prototype entity (for mapping): `Tok{id,name,kind,pos,gmOnly}` + `tokenRadius` global in scene (`prototype-server-vision/data/scene.json`: 4096 px world, 256 px tiles, radius 400, token radius 20, cell 32, 60 walls, 8 tokens).
---
## 9. FFF integration seam (design only, not built)
Principle: v1 has no rules, but every state change already flows through a validated mutation with a recipient-aware view, and entities already carry bucketed properties. FFF later adds **interpretation**, not new plumbing.
- **Characters and tokens with properties**: FFF characters are character records (8); monsters and items are plain tokens. Both carry `props` in the three buckets. FFF decides which keys live where (token state vs character identity and base values); the VTT enforces the bucket on egress and never interprets the values.
- **Action hook** (server side): the reserved `act` intent carries `actor, action, args`. Handling = `rules.handle(world, actor, action, args) -> list of mutations | error`. Mutations are the same primitive set the pipeline already validates (set prop, move, create/remove entity, emit event). Hook output is validated like any client intent; FFF cannot bypass the egress filter.
- **Events**: `event{kind, data}` server->client messages with per-recipient filtering (e.g. roll results visible to all, GM-only whispers). Not implemented in v1; message type name reserved.
- **Schema registry**: `property schema` (key, type, bucket, writable-by role, default) registered by the rules module; v1 ships an empty/default registry.
- **Where does FFF run?** Undecided. Q19 answered only the hidden-state question (no state beyond the buckets and `gm_only`, FIXED); engine language, runtime and location are not answered. Revisit when FFF starts (schema change accepted then). Options: (a) compile-time Nim module linked into the server (simplest, fastest, requires FFF in Nim or a Nim port); (b) out-of-process sidecar speaking a small request/response protocol over a Unix socket (language-agnostic, adds latency and a failure mode inside the global lock; must run outside the lock or be time-bounded); (c) WASM. No decision made.
- Client side: a generic property panel driven by the schema registry; FFF-specific UI later as additional DOM panels (plain HTML overlay [FIXED] keeps this simple).
- Non-goal now: any assumption about dice, turns, or stat names.
---
## 10. Testing strategy
Principles carried from the prototype: the checker must be independent of the code under test where possible, and every check needs a negative control that proves it can fail.
### 10.1 Carry over (port, keep as acceptance gates)
| Test | From | Notes |
|---|---|---|
| Geometry unit tests (M1 port baseline: 33 test blocks / 98 checks, none dropped; current count in `results/nimble-test.log`) | `tests/tgeometry.nim`, `results/nimble-test.log` | Port with `geometry.nim`. |
| Geometry mutation check | `tools/mutation.sh` (a: no +-RayEps rays, b/c: upper/lower segment end exclusive) | Control passes, each mutation fails >= 1 test [MEASURED 1, 2, 2]. Port. |
| Leak test | `tools/leak.mjs`, `leakcheck.nim`, `leaktest.sh` | Subject A and B, fresh DB, ~240 steps; asserts (a)-(e) in README. Independent LOS oracle for token visibility (added after the bow-tie bug). |
| Negative control / fault injection | `tools/faulttest.sh`, `-d:leakfault` build | 8 faults, exact failure-class set each, clean build passes, `LEAK_FAULT` string asserted absent from clean binary [MEASURED 8/8]. Port and extend. |
| Restart | `tools/restart.mjs` | SIGTERM + SIGKILL, identical player keys/positions/doors/vision/explored/hello+state. |
| Concurrency | `tools/concurrency.mjs` | 60 s, 3 clients, gseq monotonic, every intent acked, quiesced views == fresh connection. **M5 port [FIXED, #15]:** 6 walkers on one GM socket (~200/s) exceeds the 30/s per-connection rate (6.4); spread walkers across connections (4 per player, 16 total; 4.3). |
| Client reducer tests | `client/src/state.test.ts` | Incl. reconnect reset. |
| Smoke | `tools/smoke.mjs` | auth/cookie/tile/steal/garbage. |
| Isolation harness | `tools/withserver.sh` | own DB/ports (`run/test/`), never touch a live session. |
### 10.2 Known test gaps to fix while porting
- Shared-endpoint test passes with the horizontal arm removed [MEASURED, `HANDOFF.md`]: port a test that fails if either arm is missing, verified by a new mutation (d) in the mutation script.
- Explored/tile checks use the server's own `cellsTouched` (self-consistency). New **independent explored oracle**: brute-force per-cell sampling with the clear-LOS segment test over cell centres/corners; compare as superset/subset with a stated tolerance [PROPOSED]. Differential test old `cellsTouched` vs scanline version (M2).
- Leak checker oracle initially only checked "nothing extra", not "everything visible shows"; completeness check is kept (assert (b)).
### 10.3 New
- **Fault classes** for new data: `GMONLY_TOKEN`, `OWNER_PROP`, `GM_PROP`, `GLOBAL_COUNTER` (gseq side channel), `WALL_DELTA` (wall.add reaches player), `KEY_IN_LOG`, `CHAR_OWNER_PROP`, `ACTUAL_NAME`, `CHAR_LIST`, `CONTROLLER_CHANGE` (#14). Each with an injected fault and exact-class assertion, same as existing.
- **Characters and names (#14)**: tests for reveal per player and reveal to all; owner sees own actual name; character owner change leaves token controllers unchanged; encountered entries survive token removal and scene change and are removed only by the GM; `gm_only` tokens never enter an encountered list. Fault classes: `ACTUAL_NAME` = unrevealed actual name sent to a player; `CHAR_LIST` = another player's character or encountered entry sent; `CONTROLLER_CHANGE` = owner change altering controllers; `CHAR_OWNER_PROP` = character owner-bucket prop sent to a non-owner.
- **Probing test (T8)**: M2, in-process against the move-rules module (5.5): arbitrary far moves; assertion: facts about walls/doors beyond LOS recoverable from replies <= a bounded amount (step cap), and uniform nack shape. M3: same test over WS with a hostile client (moved from M2).
- **Auth tests**: key replace (old key invalid, sessions revoked, live connections closed), remove player (key invalid, characters and tokens pass to GM), one key reused on several devices (Q10 FIXED), Origin mismatch rejected, cookie flags present.
- **Protocol tests** (#18, `tools/protocol.test.mjs`): proto missing/non-integer (HTTP 400) and mismatch (`closing` 4003, no `hello`); unknown intent type (`unknown-type`) with unknown fields ignored; exactly one `ack` per `reqId` (reqId 0 and 2^31-1 included); `hello` first with `n = 1` and a per-connection `n` thereafter; `error malformed` for unreadable frames; the malformed flood (nine tolerated, the tenth closes 1008); the intent bucket (burst then `rate-limited`, connection stays open, a refused intent applies nothing, `error rate-limited` for an unreadable frame on an empty bucket); the 64 KB inbound boundary (exactly 64 KB is a message, 64 KB + 1 drops the TCP connection with no close frame); unmasked and bad-opcode frames; the server Ping and the Pong answer to a client Ping; the connection cap (503 + `Retry-After: 5`); and every server-initiated close as `closing` then 1005.
- **Persistence**: migration tests (old DB -> new), chunked explored round trip, restart test extended to wall CRUD and entity props.
- **Slow client** (Q13, 4.3): a client that stops reading; outbox stays under cap, no further state is queued to it, RSS flat, full resync on recovery equals a fresh connection; nginx closes the dead `/ws` socket within its configured timeout.
- **Browser e2e (new, none in prototype)**: headless Chromium via playwright-core (the perf prototype already drives devbox chromium, `prototype-pixi-perf/bench.mjs`; SwiftShader is fine for correctness, not for perf). Checks: join -> canvas renders; pixel probe shows unexplored area black, visible area map-coloured, dimmed explored area; GM sees walls, player DOM/network contains none; reconnect restores view; drag moves token and rollback works.
- **Independent traffic audit in e2e**: record all WS frames and HTTP responses seen by a player browser and run the leak checker's (a)(e) assertions over them.
- **Load/perf regression gate**: `bench` + concurrency numbers (section 5.3 and 4.3) compared with committed baselines; fail on > 2x regression [PROPOSED].
- **Wall-count scaling bench**: 5k-wall synthetic scene (section 5.3; PROPOSED test target, Q2).
- Timings from the prototype are single machine loopback power-save CPU; no real network, no client render [MEASURED caveat]. A real-network run (laptop over the intended HTTPS path, phone on LAN) is an M7 item.
### 10.4 Test tools [FIXED, owner decision 2026-11-14, #9]
- Black-box (outside) WS/HTTP harnesses: Node 26 only, repo-root `tools/`, ported from `prototype-server-vision/tools/` (`smoke.mjs`, `leak.mjs`, `restart.mjs`, `concurrency.mjs`, `lib.mjs`, `withserver.sh` incl. the M3 test nginx). No Nim rewrite. Reason: Node is already required for the client (Vite/TS, playwright-core e2e, reducer tests); a harness in another language from the server cannot share its protocol bugs; zero deps; already measured. Fix the stale "Node 22" note in `lib.mjs` on port.
- Harness tooling: built-ins only, no npm deps. Global `WebSocket` with `{headers}` for Cookie/Origin; `node:net` for raw and malformed frames (oversize, bad opcode/rsv, unmasked, flood); `node:test` as runner. Node 26 header behaviour [MEASURED, 2026-11-14, #16, node v26.11.1]: `{headers}` still puts `Cookie` and `Origin` on the wire, and without `{headers}` no `Origin` is sent; pinned by `tools/wsheaders.test.mjs` so a Node upgrade that drops the option fails loudly (#8 had verified v24 only; the prototype's "Node 22" note is stale).
- Root `devbox.json` pins `nodejs` 26 (port step).
- `devbox run test` = Nim tests first, then Node harnesses.
- In-process tests stay Nim (`nimble test`, unchanged).
- Browser e2e details: M4, not decided here.
---
## 11. Ops
### 11.1 Deployment on NixOS [PROPOSED]
- **Service** [FIXED, Q20; research: `docs/research/q20-nix-packaging.md`]: NixOS module `services.fffVtt` in `nix/module.nix`, defining: package from `nix/package.nix` (`buildNimPackage`; dependencies from committed `nix/lock.json` generated by `nim_lk`; mummy tag `0.4.8`; nixpkgs input pinned to match devbox Nim 2.2.12; fallback: vendored deps via `nimFlags --path:`), a systemd unit, state dir, options for `publicOrigin`, `port`. Imported from the owner's server NixOS config, like `foundryvtt.nix`.
- Config keys [FIXED (owner-delegated, 2026-11-14, #16)]: `--public-origin` / `FFF_VTT_PUBLIC_ORIGIN`, `--port` / `FFF_VTT_PORT`, `--state-dir` / `FFF_VTT_STATE_DIR`. Flag wins over env wins over default; defaults `http://localhost:8080`, `9000`, `run`. The origin is canonicalised (lowercase scheme/host, no trailing slash) because it is compared byte for byte with the browser's `Origin` (3.2). The listen address is not a key: the binary always binds `127.0.0.1`.
- Unit hardening: `DynamicUser` or dedicated user, `StateDirectory=fff-vtt`, `ProtectSystem=strict`, `ProtectHome`, `NoNewPrivileges`, `PrivateTmp`, `RestrictAddressFamilies=AF_INET AF_INET6`, `MemoryMax`. Add `AF_UNIX` only if the FFF sidecar (section 9, option b) is chosen; revisit at Q19. Listen on `127.0.0.1:<port>` only [MEASURED prototype binds 127.0.0.1].
- `fff-vtt gm-key` (3.2) must run as the service user (e.g. `sudo -u <service user> fff-vtt gm-key`, or a wrapper in the module), so the DB and its WAL files stay owned by that user; with `DynamicUser` the module needs a fixed user name or a wrapper. [FIXED, owner-delegated, 2026-11-14, #13]
- The server takes the state-dir lock at startup and the CLI honours it (3.2): an `fcntl` write lock on `<stateDir>/instance.lock`; `gm-key --new` exits 3 while the server runs. [FIXED, owner-delegated, 2026-11-14, #17]
- `Restart=on-failure`; `TimeoutStopSec` short; SIGTERM handler flushes (4.4).
- **Client build**: Vite `dist/` produced by Nix (or CI), served by nginx from the store path. Hashed assets, long cache; `index.html` no-cache.
- **nginx** (shape of the vhost, adapt to the existing server config; reference only, I did not read the owner's NixOS repo for this doc):
- `location /` -> static client `dist`, SPA fallback to `index.html`.
- `location = /ws` (prototype uses `/ws`) -> `proxy_pass` to backend, `proxy_http_version 1.1`, `Upgrade`/`Connection` via the `$http_upgrade` -> `$conn_up` map as in the prototype, `proxy_read_timeout` long (prototype 1 h; app-level ping makes this robust), `proxy_buffering off`. The map must be declared at `http{}` level.
- `location = /join` -> proxy, **`access_log off`**, `add_header Referrer-Policy no-referrer`.
- `location /tiles/` -> proxy (Nim decides, returns `X-Accel-Redirect`).
- `location /_tiles/` -> `internal; alias <state dir>/tiles/;` `Cache-Control private`. Must be readable by the nginx user (group read on the tiles dir) [INFERRED NixOS gotcha]; do not expose the state dir otherwise.
- Response headers: HSTS, CSP (no inline scripts, `connect-src 'self'` wss), `X-Content-Type-Options`, `Referrer-Policy`.
- No `limit_req` on `/join` (owner, #6: no rate limit on key entry; ~100-bit key space).
- Prototype nginx config (`prototype-server-vision/nginx/nginx.conf`) is the functional reference; its `listen` has no address (binds all) and its temp/log paths are dev-only.
- Map import: offline CLI that slices an image into `tile_size` PNG/WebP tiles into `<state>/tiles/<scene>/v<art_version>/` and registers/updates the scene (prototype: `tools/genmap.mjs`, deterministic, hand-authored, not reusable as the importer). Browser upload is post-v1; CLI-only import in v1 (Q5 FIXED).
### 11.2 Backups [PROPOSED]
- SQLite: systemd timer running an online backup (`.backup` or `VACUUM INTO`) to a dated file in a backup folder the server creates under its data root (Q21 FIXED), keep N; WAL means a plain file copy is unsafe.
- Tiles: immutable after import, include in the normal file backup, or regenerate from source art (keep the source image).
- Restore drill documented and tested once (M6): restore into a temp dir, start server, run the restart-equivalence assertions.
- Off-box copy: out of v1 scope (Q21 FIXED).
### 11.3 Logging and metrics (bounded, outside the lock) [PROPOSED]
- Prototype's instrumentation is prototype-only: it appends every sample to unbounded arrays, and `printStats` copies and sorts all of them inside `finish()` under the global lock; **do not port** [MEASURED/HANDOFF].
- Real: under the lock only O(1) updates: a fixed-size ring buffer or fixed-bucket histogram per metric (lock_wait, vision, sqlite, send, total) and atomic counters (mutations, errors, nacks, connections, bytes). A separate timer thread (not holding the lock) snapshots and computes percentiles every N s and logs one line.
- Keep the `SLOW` line (total > `SLOW_MS`, default 50) with breakdown `lock_wait / vision / sqlite / send / other` and intent type: it is what diagnosed the SQLite COMMIT tail [MEASURED, `results/spike/investigation.md`]. Formatting of the line happens after releasing the lock; at most O(1) rate-limited lines per second.
- Log to stdout -> journald; levels; never log player key/session secrets, token positions of hidden entities are fine in server logs (server is trusted) but logs are GM-readable only (file perms).
- Redaction mechanism [FIXED (owner-delegated, 2026-11-14, #16)]: the logger (`server/eventlog.nim`) keeps a registry of secret *values* (`addSecret`, refuses anything shorter than 8 chars) and replaces each occurrence with `[redacted]` on every line, wherever it appears; independently, a field whose *name* is in the sensitive set (`key`, `player_key`, `gm_key`, `secret`, `session`, `session_token`, `cookie`, `set-cookie`, `token_hash`, `authorization`) is masked even when its value was never registered. Call sites still must not pass secrets; the registry is the safety net behind them.
- Metrics exposure: journald lines only in v1, no `/metrics` endpoint (Q22 FIXED).
- Health: `GET /healthz` internal-only returning 200 when the lock can be acquired within a bound. `/healthz` stays (Q22 FIXED).
---
## 12. HANDOFF items -> decisions / open questions
Source: `prototype-server-vision/HANDOFF.md` (and README/NOTES worries).
| # | Item | Decision / open | Milestone |
|---|---|---|---|
| H1 | Port geometry + tests as-is | Decision: port `geometry.nim`, `tgeometry.nim`, mutation check, leak harness first | M1 |
| H2 | Token on a wall can't leave (inclusive `segsCross`); closing a door or editing a wall on a token | Decision [FIXED, Q14; door case revised by owner 2026-11-08]: wall add/edit on a token gives it `stuck` (player moves refused, GM moves allowed); a door closing on a token pushes it aside instead (5.5; `squeezed` only if no side is valid; status names per #4, was `blocked`). Set/Keep/Clear per 5.5: stays while any blocking wall overlaps; clears on wall removal or door open only if no other wall overlaps, on a GM move to a free spot, or on GM clear; GM placements/moves onto a wall set it. Trigger = circle overlap [FIXED, owner]; escape + capsule rule [FIXED, accepted default]; both in 5.5. Pin tests replaced in M2. | M2 |
| H3 | O(rays x walls) vision | Decision: radius-bbox cull now; uniform spatial grid over walls only if the 5k-wall bench misses target (5.5) | M2 |
| H4 | `cellsTouched` ~12x polygon | Decision: scanline rasterization, differential test vs ported version | M2 |
| H5 | Shared-endpoint test gap | Decision: port with a test that fails if either arm is removed; new mutation (d) | M1 |
| H6 | Single machine, loopback, power-save timings | Decision: keep as baseline only; real-network run required | M7 |
| H7 | Boundary epsilon ambiguity | Decision: keep `RayEps`, 0.5 px tolerance in checkers; documented | M1 |
| H8 | Tile leak: whole 256 px tile | Decision [FIXED, Q4]: `tile_size` = explored cell = 32 px; residual leak <= one cell, never revoked; no server masking; M4 gates (headless mobile-emulation + phone run); fallback 64 px per-scene config | M4 |
| H9 | Prototype secret = cookie = permanent bearer, no expiry, binds 0.0.0.0, needs HTTPS | Decision: session != key, key replace (GM, live), remove player, log redaction, bind 127.0.0.1, HTTPS via nginx. Sessions never expire; one player key usable across devices (Q10 FIXED); keys plaintext (Q11 FIXED); no key-entry rate limit (owner, #6) | M3 |
| H10 | Move collision: centre path + dest circle, not swept circle | Decision: capsule (swept-circle) check + escape rule, 5.5; step cap = effective vision radius, 5.5 (T8) | M2 |
| H11 | Leak test explored/tile checks self-consistent | Decision: add independent explored oracle | M2 |
| H12 | Full vision polygon (~3 KB) per player move | Decision [FIXED, Q16]: full polygon, integer px, only on change; delta/binary post-v1 | M3 |
| H13 | Explored sent whole + one SQLite row per cell | Decision: chunked bitmaps in DB; RLE on connect | M3 |
| H14 | No SIGTERM handler | Decision: add; durability independent of it | M5 |
| H15 | `synchronous=NORMAL` vs FULL | Decision [FIXED, Q12]: NORMAL; FULL around GM authoring transactions | M3 |
| H16 | Timing instrumentation unbounded and under lock | Decision: do not port; ring buffer/histogram, snapshot outside lock | M5 |
| H17 | 583 ms spike unexplained | Open: not reproduced; production SLOW logging to catch recurrence | M5/M7 |
| H18 | mummy: unbounded send queue, no backpressure | Decision [FIXED (owner decision), Q13]: app-level bounded per-client outbox, coalescing, WS Ping(seq)/Pong lag tracking, stop feeding + full resync; no mummy patch; fork is fallback only (4.3) | M5 |
| H19 | `WebSocket` keyed by raw bytes | Decision: app `connId` table (not raw bytes; `WebSocket` has field-wise `==`/hash at pin, Q13 research) + layout test | M3 |
| H20 | Fog masks Graphics grow unbounded | Decision: fixed-size baked fog texture (7.3) | M4 |
| H21 | Pixi `Text` per token heavy | Decision: BitmapText; glyph set Latin incl. accents + Nerd Font icons (Q17 FIXED) | M4 |
| H22 | Browser rendering never verified | Decision: headless browser e2e | M4 |
| H23 | Tiles don't update on door change | Decision: by design (static art); doors never part of art | -- |
| H24 | Prototype `gmOnly` unused (my finding, not in HANDOFF) | Decision: enforce + fault class | M3 |
| H25 | Player-visible `gseq` side channel (my finding) | Decision: per-connection counter | M3 |
| H26 | Move-validation wall-probing oracle (my finding) | Decision: step cap + rate limit + uniform nack + test (in-process M2, over WS M3; 5.5) | M2/M3 |
---
## 13. Milestones
Each is small, ends with a green gate, and no milestone depends on browser UI before M4.
- **M1 - Port geometry + tests.**
- Scope: new repo layout (`server/`, `tools/`, `tests/`), devbox config, `geometry.nim` + `tgeometry.nim`, mutation script, add mutation (d) and the shared-endpoint arm test.
- Accept: `nimble test` green: M1 port baseline 33 test blocks / 98 checks, none dropped (plus new tests on top; current count in `results/nimble-test.log`); mutations a-d each fail >= 1 test (M1; M2 adds e-o in `tools/mutation.sh`), control passes; repo builds with devbox only.
- **M2 - Vision engine v2 and move rules** (decisions in 5.5, recorded 2026-11-08).
- Scope: scanline `cellsTouched`, differential + independent explored oracle tests, radius-bbox wall cull (spatial grid only if the 5k bench misses), capsule/swept move check and token-on-wall escape (5.5), step cap = effective vision radius (5.5), `blocked` flag with circle-overlap trigger and Set/Keep/Clear policy (5.5), GM moves ignore walls and step cap (and set/clear `blocked`), bench harness incl. 5k-wall scene, pure in-process move-rules module with unit tests. The WS/hostile-client harness is M3, not M2.
- Accept: `visibilityPolygon` and `cellsTouched` equal the old implementation on the corpus (5.5); `moveBlocked` excluded (its results change on purpose); polygon+cells bench <= prototype (0.451 ms) on the prototype scene and polygon < 1 ms on the 5k-wall scene [targets PROPOSED]; in-process probing test passes; escape and capsule positive and negative unit tests pass; door-push tests pass (each side, centre on the line uses the previous side, other-side fallback for a blocking wall and for out of bounds, both invalid -> blocked and opening frees it, GM-owned token pushed, wall add still sticks); `blocked` tests pass (every Set/Keep/Clear rule of 5.5: overlap trigger, doorway, two overlapping walls, GM drop/move sets and clears, GM clear then escape, unrelated change does not re-block); mutations k (no Keep), l (GM moves do not set blocked), m (push to the wrong side), n (push skips the validity check) and o (previous side ignored) each fail >= 1 test; over-cap move gives the same nack as a blocked move; thresholds documented in the module header; oracle tolerance 0.5 px. The KNOWN LIMITATION test and the Q14 pin test are replaced with positive assertions and `blocked`-policy tests.
- **M3 - Server core.**
- Scope: entities with bucketed props, characters with names, name reveal and encountered list (8, #14), players, player keys/sessions, scenes, chunked explored persistence, typed per-recipient views and single egress, per-connection counters, proto versioning, the wire catalogue of 6 (29 intents, 15 server messages), wall/token/character CRUD intents, Origin check, plaintext player keys and non-expiring sessions (Q10, Q11), SQLite schema + migrations. Tile gate `/tiles/` (3.3), fixture tiles at 32 px generated at test time by a helper (not committed), minimal local test nginx with internal `/_tiles/` (production vhost and tile import CLI stay M6) [FIXED, owner decision 2026-11-14, #7]. Black-box harnesses ported to `tools/` on Node 26; `devbox run test` runs Nim then Node (10.4) [FIXED, owner decision 2026-11-14, #9].
- Accept: `devbox run test` green on a clean checkout, and that run includes the nine named groups below; details live at the § refs, not here. Out of M3 accept: concurrency (M5), 127.0.0.1 bind check (M6 deploy) [FIXED, owner decision 2026-11-14, #12].
1. **leak+fault**: ported leak test A and B; fault test catches every class with exact class sets, incl. characters and names; clean build passes (10.1, 10.3).
2. **tiles**: Tile gate: leak test (d) and smoke tile-steal checks pass through the test nginx; gate decisions match the independent explored oracle (10.2); direct `/_tiles/` fetch -> 404; malformed or out-of-range path -> 404; unexplored -> 403 [FIXED, owner decision 2026-11-14, #7].
3. **probing**: M2 in-process probing test (T8, H26) re-run over WS with a hostile client (10.3, 5.5).
4. **protocol**: proto mismatch refused, unknown type rejected, oversized frame rejected, malformed flood closed, rate limit hit, connection cap enforced (10.3, T10, 6.2, 6.5; codes and close codes in 6.5; limits and numbers in 4.3 (connections) and 6.4 (frame, intent rate) [FIXED, owner-delegated, #15]).
5. **auth**: key create; key replace (old sessions and live connections closed); remove player; one key on several devices; Origin mismatch rejected; cookie flags present (T7, H9, 3.2, 10.3).
6. **characters and names**: as #14 (10.3).
7. **restart**: identical state after restart, incl. CRUD (10.1).
8. **persistence**: explored chunks round trip; old DB migrates to new (H13, 4.4, 10.3; migrations are PROPOSED in 4.4).
9. **logs**: no secret in any log; the test greps the logs for every key and session value it used (T6, 11.3 PROPOSED).
- **M4 - Client v1.**
- Scope: new `client/` dir (first real client build): Vite + TS + Pixi v8 client: layers, tiles, grid, tokens (BitmapText), character list, encountered list (greyed), reveal buttons (#14 UI; server side in M3), fog textures, wall/door editor, token drag with prediction/rollback, DOM overlay, reconnect backoff, reducer tests; after the client port, archive `prototype-*` dirs (Q24).
- Accept: headless e2e: fog pixel checks, player traffic audit clean, reconnect restores; manual run on laptop and Note 10 at 60 fps with 50 tokens, 16384 px map (tiled; PROPOSED test target, Q2), fog active.
- Tile-size gates [FIXED, Q4]: (a) automated headless-Chromium test with mobile emulation (viewport, dpr, CPU + network throttle) against the real server path (nginx HTTP/2 + caching): viewport fills in < 1 s at zoom 1; (b) one manual run on the owner's 5-year-old Android phone (worst-case reference). If either fails: `tile_size` 64 px (per-scene config, no code change). The 2026-11-08 prototype phone run (`prototype-tile-leak/README.md`) is evidence, not the gate: HTTP/1.1, no-store, zoom 0.5 only, first cold load up to 3.3 s.
- **M5 - Robustness and observability.**
- Scope: SIGTERM handler, bounded metrics + SLOW lines, connection cap, frame/rate limits, per-client bounded outbox with coalescing and Ping(seq)/Pong lag tracking (Q13, 4.3), verify `/ws` goes through nginx and its timeouts, healthz.
- Accept: concurrency 60 s x3 pass with p99 <= prototype (4.98 ms) +50%; slow-client test: client that stops reading -> outbox stays under cap, RSS flat, no further state queued to it, full resync on recovery equals a fresh connection; nginx closes a dead `/ws` within its configured timeout (measured); stats computation shown outside the lock (lock hold time unchanged with metrics on, measured).
- **M6 - NixOS deployment.**
- Scope: `nix/` dir per Q20: un-ignore `nix/` in `.gitignore`; `lock.json` (nim_lk), `package.nix` (buildNimPackage, nixpkgs pinned to devbox Nim 2.2.12, mummy tag 0.4.8), `module.nix` (`services.fffVtt`); declare a nimble `bin` in `fff_vtt.nimble` (nim_builder builds only `bin` entries, so the package is empty without it); client build; nginx vhost; systemd hardening; backups timer (Q21), restore drill, import CLI for maps (slices at `tile_size`, Q4).
- Accept: deployed behind HTTPS on the owner's server; `/_tiles/` 404 directly; WS upgrade works; player key sign-in works from phone; access log has no secret; backup + restore drill passes.
- **M7 - Real-world pass.**
- Scope: real-network latency/throughput run, iOS/Safari check (if available), one real session with the owner's table, collect SLOW lines.
- Accept: documented numbers; defects triaged to issues; go/no-go for v1.
- **M3 build slices** [FIXED, owner decision 2026-11-14, #13]: vertical slices, each runnable end-to-end with its own test. Order and blocking: each slice blocked by the previous, except 9 (blocked by 5 only) and 10 (blocked by 1-9). Open technical details (DDL, property-schema registry format, config keys, redaction mechanism) are decided by the builder inside the slice that needs them and recorded here as FIXED (owner-delegated).
1. Bare server (#16) 2. Getting in (#17) 3. Talking safely (#18) 4. Walls and doors (#19) 5. Tokens and sight (#20) 6. Explored persistence (#21) 7. Token details (#22) 8. Characters and names (#23) 9. Map tiles (#24) 10. Finish line (#25).
- **Post-v1 candidates**: FFF seam implementation (section 9), drawings/pings/ruler, chat/dice (order decided at M7, Q8), light sources, browser upload UI (Q5), multi-scene (Q3), vision deltas/binary protocol (Q16).
---
## 14. Open questions for the owner
1. Q1 - Table size and device mix: how many players max, and which devices (phones, tablets, iOS)? Drives iOS testing priority and token/message budgets. **RESOLVED [FIXED (owner decision), 2026-11-08]:** devices are phones, tablets and laptops. Max players: 6 [FIXED, owner decision 2026-11-08] (section 1). Connection cap 8 (6 players + GM + headroom) stays [PROPOSED] (sections 4.3, 13).
2. Q2 - Largest map you plan to use (px), and typical wall count per scene? Drives tile size, spatial grid priority and explored chunking. **DEFERRED [FIXED (owner decision), 2026-11-08]:** owner does not know yet. 16384 px map and 5k walls stay [PROPOSED] test targets; revisit with real maps.
3. Q3 - Multiple scenes in v1 (GM switches the active scene, per-scene explored grids), or exactly one scene per table to start? **RESOLVED [FIXED (owner decision), 2026-11-08]:** exactly one scene in v1; schema may stay `scene_id`-keyed.
4. Q4 - Tile-edge leak: accept as documented, or reduce it (smaller tiles = more requests; gate tiles only when explored cells cover a minimum fraction; or server-side masked tiles at the cost of image processing in Nim)? What detail do you paint in map art that must stay secret? **RESOLVED [FIXED (owner decision), 2026-11-08]:** `tile_size` = explored cell size = 32 px. Residual leak is at most one cell, never revoked; no server-side masking. Authoring rule shrinks from ~256 px to ~32 px. M4 acceptance: (a) headless mobile-emulation test on the real server path, (b) one manual phone run; fallback 64 px (per-scene config). Evidence: `prototype-tile-leak/README.md`. Applied in 3.3, 3.4 (T5), 8, 12 (H8), 13 (M4, M6).
5. Q5 - Map import: CLI-only for v1, or upload + tiling from the browser (GM) from the start? **RESOLVED [FIXED (owner decision), 2026-11-08]:** map import is CLI-only in v1; browser upload is post-v1.
6. Q6 - Wall/door authoring: is an in-browser GM wall editor required in v1 (no generator feeds in), or is hand-edited/imported wall data acceptable at first? What other wall kinds are needed soon (windows, one-way, secret doors, locked doors)? **RESOLVED [FIXED (owner decision), 2026-11-08]:** in-browser GM wall editor in v1; wall kinds `wall` and `door` only.
7. Q7 - Vision model: single radius per token or per-token property from day one? Is any "darkvision/light" concept needed before FFF? **RESOLVED [FIXED (owner decision), 2026-11-08]:** per-entity numeric `vision_radius` plus scene default; no light sources or darkvision.
8. Q8 - Which "table convenience" features come first after v1, if any: freehand drawing (exists in the perf prototype), pings, ruler, chat, dice, token images/portraits, initiative tracker? **DEFERRED [FIXED (owner decision), 2026-11-08]:** decided at M7.
9. Q9 - Should players see each other's names/presence, and should party members share vision (shared explored/LOS) or is it strictly per player? **RESOLVED [FIXED (owner decision), 2026-11-08]:** vision and explored strictly per player; player names visible to all.
10. Q10 - Session lifetime and invite policy: session expiry, how often invites rotate, single-use vs reusable invite links, can one player use multiple devices at once? **RESOLVED [FIXED (owner decision), 2026-11-08]:** sessions never expire; one player key is usable on multiple devices (wording amended #6: was invite link).
11. Q11 - Invite secrets: stored hashed (shown once, GM regenerates to re-share) or stored plaintext so the GM can re-copy a link? **RESOLVED [FIXED (owner decision), 2026-11-08]:** player and GM key secrets stored plaintext so the GM can re-show them (wording amended #6: was invite secrets).
12. Q12 - Durability: is `synchronous=NORMAL` (can lose the last few commits on power loss/OS crash, never corrupts) acceptable, or should it be FULL for some or all writes? **RESOLVED [FIXED (owner decision), 2026-11-08]:** `synchronous=NORMAL`; `FULL` around GM authoring transactions.
13. Q13 - Slow/dead client policy: acceptable to disconnect clients that fall behind? Willing to patch/fork the pinned mummy commit if per-socket queue depth cannot be read from outside? **RESOLVED [FIXED (owner decision), 2026-11-08]:** option A: app-level bounded per-client outbox, latest-state-wins coalescing per key (MQTT-retained-like), diff at flush time, server Ping(seq)/Pong ack tracking for lag, stop feeding lagging clients + full resync on recovery; no mummy patch. Dead/stuck peers closed by nginx proxy timeouts (mechanism PROPOSED; verify WS goes through nginx in M5). Fork of mummy (option B) is fallback only, not planned. Research: `docs/research/q13-mummy-slow-clients.md`; detail in 4.3.
14. Q14 - Moving tokens when walls change: what should happen if the GM closes a door (or edits a wall) on top of a token? Allow the token to walk out, auto-nudge it, or refuse the edit? **RESOLVED [FIXED (owner decision), 2026-11-08]:** a GM edit that lands on a token gives it status `blocked`: server refuses that token's player moves; GM can still move it; status clears when the wall is removed or the door opened, or when the GM clears it. **Door case revised [FIXED (owner decision), 2026-11-08]:** spell walls and wall edits stay stuck; a door closing on a token pushes the token aside (5.5), stuck only if neither side is valid. Status names superseded by #4 (2026-11-10): `blocked` is now `stuck`/`squeezed` (5.5); door-push failure is `squeezed`.
15. Q15 - Reconnect: is a full resync on every reconnect fine up to what explored/state size, or do you want `resume since N` later? **RESOLVED [FIXED (owner decision), 2026-11-08]:** full resync on every reconnect; revisit if a measured snapshot exceeds ~100 KB.
16. Q16 - Vision payload: OK with full polygon per move (~3.4-3.7 KB per mover delivery, measured on loopback) for v1, or do you want deltas/binary earlier (e.g. for mobile data plans)? **RESOLVED [FIXED (owner decision), 2026-11-08]:** full vision polygon, integer px, sent only on change; deltas post-v1.
17. Q17 - Names/labels: which character sets must labels support (Latin only, accents, non-Latin, emoji)? Affects BitmapText glyph atlas vs Text/HTMLText. **RESOLVED [FIXED (owner decision), 2026-11-08]:** labels in Latin incl. accented characters plus Nerd Font icon glyphs.
18. Q18 - Grid and movement: snap to grid on drop? Any server-side speed/distance limit per move, given there are no rules yet? **RESOLVED [FIXED (owner decision), 2026-11-08]:** grid snap off by default (client option); server step cap = token vision radius.
19. Q19 - FFF engine: implementation language/runtime, current maturity, and whether it should run inside the VTT server process, as a sidecar, or in the browser for display only? Does it need hidden/secret state beyond the three property buckets (public / owner / GM)? **RESOLVED for hidden state [FIXED (owner decision), 2026-11-08]:** no hidden state beyond the `public`/`owner`/`gm` buckets and `gm_only` flag in v1; revisit when FFF starts (schema change accepted then). Engine language, runtime and location: **DEFERRED** to FFF start (section 9 options a/b/c; no decision now).
20. Q20 - Nix packaging: how do you want the Nim server built (nimble lock + `buildNimPackage` or a vendored deps approach), and which repo hosts the NixOS module (this repo or your nixos-configuration repo)? **RESOLVED [FIXED (owner decision), 2026-11-08]:** `buildNimPackage` with a committed `nix/lock.json` (`nim_lk` JSON lock). `nix/package.nix` and `nix/module.nix` (`services.fffVtt`) live in this repo and are imported from the owner's server NixOS config, like `foundryvtt.nix`. nixpkgs input pinned to match devbox Nim (2.2.12). Fallback: vendored deps if `nim_lk` cannot resolve the mummy pin. `nix/` un-ignored in `.gitignore` when M6 starts, not now. mummy pinned to tag `0.4.8` (same `src/` as `01deb1ff`). Research: `docs/research/q20-nix-packaging.md`; detail in 11.1.
21. Q21 - Backups: where should off-box backups go (existing mechanism on the server?), and how many dated copies to keep? **RESOLVED [FIXED (owner decision), 2026-11-08]:** v1 backups go to a backup folder the server creates under its data root; off-box backups out of v1 scope.
22. Q22 - Observability: journald lines only, or also an internal metrics endpoint scraped by something you run? **RESOLVED [FIXED (owner decision), 2026-11-08]:** journald lines only; `/healthz` stays.
23. Q23 - Public exposure: reachable from the internet (domain, rate-limiting, fail2ban expectations) or LAN/VPN only? **RESOLVED [FIXED (owner decision), 2026-11-08]:** network exposure and access are out of project scope (owner handles reachability). Built-in protections stay (127.0.0.1 bind, connection cap, frame/rate limits, Origin check); internet-only hardening (fail2ban etc.) not in scope.
24. Q24 - Repo conventions: should this design live in `docs/DESIGN.md` plus ADRs under `docs/adr/` and a `GLOSSARY.md` (AGENTS.md references both, neither exists yet)? Should prototypes remain in-tree or move to an archive branch once ported? **RESOLVED [FIXED (owner decision), 2026-11-08]:** `GLOSSARY.md` and `docs/adr/` per AGENTS.md; prototypes stay in-tree until the M4 client port, then archived.
Owner also decided 2026-11-08 [FIXED (owner decision)]: restore drill belongs in M6 (sections 11.2, 13).
Owner also decided 2026-11-08 (M2): move rules, `blocked` trigger and GM move bypass are recorded in 5.5; M2 scope and accept criteria in 13.
Owner also decided 2026-11-10 [FIXED (owner decision), #14]: characters are separate records from tokens (one owner: a player or the GM; a token may link to one character; token controller is independent of the character owner); character holds identity, token holds the state of the figure; descriptive and actual names, revealed per player or to all; per-player encountered list, persisted, removed only by the GM; storage on the server only (SQLite). Character export/import as a file is future, not M3. See 3.1, 4.4, 8.
Owner also decided 2026-11-10 [FIXED (owner decision), #6]: one shared site link (alone it shows only the sign-in page); each player has a personal player key, generated by the GM with no name, identifying the player and granting access to their data. The player types their display name at first sign-in; names are unique among players; the GM can rename. The GM signs in the same way with a GM key printed by `fff-vtt gm-key` (replaces `gm-link`, #5; rest of #5 unchanged). The GM can replace a player's key at any time while the server runs: old key invalid, all that player's sessions revoked, live connections closed; identity, characters and encountered list kept; no name re-prompt. Removing a player: key invalid, sessions revoked, connections closed; their characters and controlled tokens pass to the GM; name and slot freed; encountered list deleted. Defaults accepted: one key on many devices; sessions never expire; keys stored plaintext; 20-character key in groups of 4 with dashes, no look-alikes, CSPRNG (~100 bits); 6-player cap counts unused keys; sign-in sets the session cookie as in 3.2. No rate limit or lockout on key entry (owner rejected guessing protection). Rejected: per-person invite links; GM types the name at key creation; delete-and-reinvite only; deleting characters with the player; shared-link visit creates a player; separate GM link path. Terms: "player key" and "GM key"; "token" stays reserved for map figures. Message names: #11.
Owner also decided 2026-11-14 [FIXED (owner decision), #7]: map tiles in M3. The tile gate (`/tiles/`, Nim, `X-Accel-Redirect`) and a minimal local test nginx with generated 32 px fixture tiles are M3 scope; tile import CLI and the production nginx vhost stay M6. Tile URLs carry `art_version` from M3 (always 1 in M3); responses are `Cache-Control: private`; malformed or out-of-range paths get 404, unexplored tiles 403. The gate reuses the server's explored-area logic, checked against the independent oracle (10.2). On-disk layout `<state>/tiles/<scene>/v<art_version>/` fixed in M3. See 3.3, 11.1, 13.
Owner also decided 2026-11-14 [FIXED (owner decision), #9]: test tools. Black-box WS/HTTP harnesses are Node 26 only (repo-root `tools/`, built-ins and `node:net` for raw frames, `node:test`, no npm deps), ported from the prototype; no Nim rewrite. In-process tests stay Nim. Root devbox pins nodejs 26; `devbox run test` runs Nim then Node. Browser e2e details stay open (M4). See 2, 10.4, 13.
Owner also decided 2026-11-14 [FIXED (owner decision), #12]: what M3 done means. Done = `devbox run test` green on a clean checkout, with the nine named groups in 13 (M3 Accept), each pointing to its details in 10.3, 3.4, 5.5 and 6. Concurrency moves to M5 and the 127.0.0.1 bind check to M6 deploy. Protocol limits (frame size, intent rate, connection caps) are a separate open card, "M3 limits", not decided here. See 10.3, 13.
Owner also decided 2026-11-14 [FIXED (owner-delegated, 2026-11-14, #15)]: M3 limits. The owner delegated the numbers to the agent and accepted the set. Max inbound WS message 64 KB (mummy default; inbound only; no config). Intent rate: token bucket per connection, 30/s sustained, burst 100, same for GM and players; excess refused with `rate limited`, no rollback (each intent atomic), connection stays open. Connections: 4 per player (a 5th closes the oldest), 16 total (the 17th is refused); replaces the PROPOSED cap of 8. Consequence: the M5 concurrency port spreads load across connections (10.1). See 4.3, 6.4, 10.1, 13.
Owner also decided 2026-11-14 [FIXED (owner-delegated, 2026-11-14, #11)]: M3 message list. The owner delegated the wire shapes; the set is the complete M3 catalogue in 6 (29 client intents, 14 server messages, 15 with #18's `closing`). Client `t` is `<noun>.<verb>` (GLOSSARY nouns: `token`, never "entity"), server `t` is a dotless state noun, so they never collide. Every intent carries `reqId` and gets exactly one `ack` (`ok`, new `id`, `pos` for moves); a refused player move stays the uniform nack (old position, no code), every other refusal has a static code (`rate-limited`, `not-allowed`, `not-found`, `invalid`, `name-taken`, `cap-reached`, `in-use`, `no-rules`, `unknown-type`); frames without a readable `reqId` get `error` (`malformed`, `rate-limited`). `invite.*`, `gmClearBlocked` and `blocked` are retired: `key.*`/`player.*` for player keys and players, `status.set`/`status.clear` and `token.resize` for #4. Connection outcomes: HTTP 403 (Origin), 401 (no session), 400, 503 (17th connection); WS close 4001 revoked, 4002 evicted (5th connection), 4003 proto mismatch, 1008 malformed flood; oversize closes TCP with no frame. `POST /join` is HTTP (6.6). Server `door` is folded into `wall`; `presence` into `roster`; `pong` into the ping `ack`. See 3.1, 3.2, 3.4, 4.2, 4.3, 5.5, 5.6, 6, 7.5, 13.
Owner also decided 2026-11-14 (review of #11 flags) [FIXED (owner decision)]: (1) players cannot create or edit characters or props in v1 (GM only); opening that later is a permission change on the existing intents, not a redesign (1). (2) A revealed name cannot be un-revealed: no un-reveal intent (8, 6.1). (3) `character.remove` is refused with `in-use` while tokens link the character (6.1, 6.5). (4) Encountered stays encountered: a `gm_only` flip leaves the entry, greyed (8, 6.1). (5) Status markers do not reveal their cause to non-GM viewers: `statuses[].source` goes to the GM only (3.1, 5.5, 6.1; amends #4). The controlling owner is not given `source` either, as the doc has no owner-view rule for statuses; revisit if wanted.
Owner also decided 2026-11-14 [FIXED (owner-delegated, 2026-11-14, #17)]: M3 slice 2 ("getting in"). Storage is migration step 2 (`auth`): `player`, `player_key`, `session`, a single-GM partial unique index, cascading deletes (4.4). Players/keys/sessions: 3.2 and 8. Cookie `fff_session`, `POST /join` as in 6.6. `fff-vtt gm-key [--new]` and the `<stateDir>/instance.lock` fcntl lock with exit 3 are recorded in 3.2/11.1. Slice 2 implements only the three GM intents auth needs (`key.create`, `key.replace`, `player.remove`) with the 6.1 ack shape; the rest of the envelope, error frames, rate limits and unknown-type answers stay slice 3 (#18). The application close codes of 6.5 are not expressible at the mummy pin (3.2); slice 3 decides. See 3.2, 4.4, 6.5, 6.6, 8, 11.1, 13.
Owner also decided 2026-11-15 [FIXED (owner decision), #18]: close codes at the mummy pin, option A. Mummy 0.4.8 cannot send an application close code (`close(ws)` -> an empty close frame -> the browser sees 1005); mummy is not forked or patched for it. Every server-initiated close is preceded by exactly one `closing {reason, code}` message carrying the reason of 6.5, then the close frame; a client treats 1005 plus that last message as the reason. `closing` is a catalogue message (server -> client, dotless noun) and the catalogue count is 15. Slice 2's eviction and revocation paths send it. Also recorded FIXED here: the server Ping interval (20 s, plus one right after `hello`; lag enforcement stays M5), the per-connection `n` rule (server frames only, no number for Ping/Pong, no global counter), the own `maxMessageLen` (64 KB) rather than mummy's default, and the slice-3 rollout note that catalogue intents whose slice has not landed answer `unknown-type`. See 3.2, 4.3, 6, 6.1, 6.2, 6.4, 6.5, 10.3.
Owner also decided 2026-11-14 [FIXED (owner-delegated, 2026-11-14, #16)]: M3 slice 1 groundwork ("bare server"). Config keys, defaults, precedence and the canonical origin: 11.1. Migration history DDL, the agreement/contiguity rule and one-transaction-per-step: 4.4. Secret redaction (value registry plus sensitive field names, minimum secret length 8): 11.3. `GET /healthz` answers `200 {"status":"ok"}` from slice 1; the lock-bounded health check stays M5: 6.6, 11.3. `devbox run test` runs `nimble test` first and only then `node --test tools/*.test.mjs` (10.4); both logs land in `results/`. The server's listen address is the constant `config.BindAddress` = `127.0.0.1`, not a config key (T15). Dependencies: `fff_vtt.nimble` requires `mummy == 0.4.8` and `db_connector == 0.1.0`; devbox adds nodejs 26 and sqlite (`out`+`bin`, with `LD_LIBRARY_PATH=$DEVBOX_PACKAGES_DIR/lib` for the dlopen). Node 26 `{headers}` re-check: 10.4.