diff --git a/docs/DESIGN.md b/docs/DESIGN.md index 9013168..fb1b6bf 100644 --- a/docs/DESIGN.md +++ b/docs/DESIGN.md @@ -1,6 +1,14 @@ # FFF_vtt design -Status: draft v0.30, 2026-11-17 (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; v0.16 records #19 (walls and doors: the scene/wall schema, the wall payload rules and the slice-4 rollout) in 4.4, 6.1, 8, 13, 14; v0.17 records #20 (tokens and sight: the `entity` step, the typed views and the single egress, vision and explored, and the slice-5 rollout) in 4.4, 6.1, 6.3, 8, 10.3, 13, 14; v0.18 records #23 (characters and names: the `character`/`name_reveal`/`encountered` step, the name rule, the players' names and the `roster` frame, and the four name/character fault classes) in 4.1, 4.4, 6.1, 6.3, 6.4, 6.5, 8, 10.3, 13, 14; v0.19 records the owner confirmation of the #22 property-schema registry (keep the empty registry with the permissive fallback in v1; strict mode comes with the FFF seam, post-v1) in 6.1, 14; v0.20 records the #27-#31 correctness and cost fixes (per-player reveal persistence, one encountered rewrite path, link-by-update, the borrowed egress context, one scene read per request) in 4.3, 6.1, 10.3, 14; v0.21 records #41 (the height model: metres, `height` and `eye_height` as GM-only registered props with a token override, eye height 93% by default, walls full height unless the GM gives a height) in 5.7, 6.1, 8, 9, 14; v0.22 records #42 (the wall model: independent sight/movement switches with door settings and a sight-only direction, kinds as presets, a derived `kind` label, the v1 preset table, and secret/locked unobservable to players) in 1, 3.1, 5.1, 5.5, 5.8, 6.1, 7.4, 8, 14; v0.23 records #44 (low walls: see-over as a per-target predicate over the strict fog polygon, movement blind to height, the floor behind a low wall left unexplored, and the GM-only who-sees-it view) in 5.7, 5.8, 5.9, 7.4, 14; v0.24 records #46 (secret and locked doors: doors stay GM-only in v1, a locked door refuses to open, and the differential door-equivalence oracle with its fault, leakcheck and tile sweeps) in 1, 3.4, 5.8, 6.1, 6.5, 7.4, 10.3, 14; v0.25 records #45 (thick walls: the rectangular body and its placement, the shared sight/collider rectangle with square ends, see-over at every crossed face, no push on a wall edit, and the shape seam) in 1, 5.1, 5.3, 5.5, 5.7, 5.8, 5.9, 5.10, 6.1, 7.4, 8, 13, 14; v0.26 records #47 (windows as see-through wall pieces with no sill or top and the `window` preset, one-way direction wording, the body opaque from both sides, and the one-way oracle and fault class) in 1, 5.1, 5.8, 5.9, 5.10, 6.1, 7.4, 8, 10.3, 14; v0.27 records #48 (`terrain` dropped, four presets, the `player_marker` switch and its player-wire exception, the GM-only wall `label`, and the "fewest things" principle) in 1, 3.1, 3.4, 5.1, 5.8, 5.9, 5.10, 6.1, 7.4, 8, 10.3, 14; v0.28 records #50 (door geometry: the door leaf is the wall's own body, an open door is only a gap, and the thick-door push geometry) in 5.4, 5.5, 5.8, 5.10, 10.3, 14; v0.29 records #49 (the wall record's wire fields, typed columns with CHECK constraints, migration step 8 with the legacy `kind` dropped and `marker_seen` added, existing heights backfilled to 1.8 m, the player `marker` message, and `proto` 2) in 3.1, 4.4, 5.7, 5.8, 5.9, 5.10, 6.1, 6.2, 6.3, 8, 10.3, 14; v0.30 records the 2026-11-17 review of `docs/ANALYSIS.md` (build order after the M4 phone playtest, minimum zoom 0.5, walls statuses accepted, slow-client close superseded by stop-feed + resync, and the DESIGN split note) in 1, 4.3, 5.10, 6.1, 7.4, 13, 14. All of Q1-Q24 are RESOLVED or DEFERRED; none OPEN). Audience: the owner and coding agents. +Status: current spec, 2026-11-17. This file states only what is true and binding now. + +This is the current file produced by the 2026-11-17 split of DESIGN v0.30 (issue #51, +`docs/ANALYSIS-review.md` D2). +Section numbers are unchanged, so every existing `DESIGN §x.y` reference still resolves; `§14` +now holds only open items. The durable reasoning behind the non-obvious rules lives in +[`docs/adr/`](adr/); the change log, the dated owner-decision log (Q1-Q24) and all superseded +statements are in [`docs/DESIGN-history.md`](DESIGN-history.md), which is **not normative**. +Audience: the owner and coding agents. Legend: - **[FIXED]** owner decision, not up for debate here. @@ -10,42 +18,82 @@ Legend: 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`) +- `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. +- No FFF engine notes exist in the repo. `GLOSSARY.md` and `docs/adr/` exist per AGENTS.md (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. +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. ### Principles [FIXED (owner decision), 2026-11-16, #48] -- **Do the most with the fewest things: one object, switches on top, names are only labels.** A wall is one record; its behaviour is a small set of independent switches; preset names (`wall`, `door`, `window`, `one-way`) are editor shortcuts and labels over those switches, never storage and never a second kind of object. Apply this principle to future cards: prefer a new switch or field on the existing object over a new object, a new message or a new enum. Corollary: if two features have the same switches, they have the same rules and the same name — no parallel implementations. +- **Do the most with the fewest things: one object, switches on top, names are only labels.** A wall + is one record; its behaviour is a small set of independent switches; preset names (`wall`, `door`, + `window`, `one-way`) are editor shortcuts and labels over those switches, never storage and never + a second kind of object. Apply this principle to future cards: prefer a new switch or field on the + existing object over a new object, a new message or a new enum. Corollary: if two features have + the same switches, they have the same rules and the same name — no parallel implementations. ### v1 scope [PROPOSED, trimmed to what the prototypes proved plus the minimum to be usable] -- **Build order [FIXED (owner decision), 2026-11-17, `docs/ANALYSIS-review.md` D1]:** all wall design stays FIXED, but thick walls (5.10) and wall/token heights with see-over (5.7, 5.9) are **built after the first playable M4 client and a phone playtest**. The v1-first build is thin walls with the 5.8 switches, doors, secret/locked, windows, one-way and player markers. The #49 schema lands complete now - `thickness`/`position`/`height` columns with today's defaults (`0`, `center`, `NULL`) - so the later build needs no migration. -- 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, tokens. A wall's behaviour is a set of switches (blocks sight, blocks movement, sight direction, player marker) plus door settings; the editor's four presets (`wall`, `door`, `window`, `one-way`) are one-drag defaults over them, and `secret`/`locked` are checkboxes on any door (5.8; supersedes Q6's `wall`|`door` only and #42/#47's longer preset list). A wall also has a per-wall thickness and height (5.10, 5.7). -- GM tools: author walls, doors, windows and one-way barriers in the browser (Q6, FIXED; presets plus an advanced toggle, 5.8, 7.4), 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. +- **Build order [FIXED (owner decision), 2026-11-17, `docs/ANALYSIS-review.md` D1]:** all wall + design stays FIXED, but thick walls (5.10) and wall/token heights with see-over (5.7, 5.9) are + **built after the first playable M4 client and a phone playtest**. The v1-first build is thin + walls with the 5.8 switches, doors, secret/locked, windows, one-way and player markers. The #49 + schema lands complete now - `thickness`/`position`/`height` columns with today's defaults (`0`, + `center`, `NULL`) - so the later build needs no migration. +- 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, + tokens. A wall's behaviour is a set of switches (blocks sight, blocks movement, sight direction, + player marker) plus door settings; the editor's four presets (`wall`, `door`, `window`, `one-way`) + are one-drag defaults over them, and `secret`/`locked` are checkboxes on any door (5.8). A wall + also has a per-wall thickness and height (5.10, 5.7). +- GM tools: author walls, doors, windows and one-way barriers in the browser (Q6, FIXED; presets + plus an advanced toggle, 5.8, 7.4), 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 that see only within a distance: a v1 window is see-through along its whole drawn length, with no distance rule (5.8, #47). Windows with a real sill and top height, light coming through windows, and per-wall material (stone, wood, glass): future effort, to be discussed when lighting arrives (#48). -- Difficult terrain, movement cost and pit/fall semantics: a rules-engine judgement (FFF), not a wall behaviour; v1 walls only block or pass movement (5.9, #48). +- Dynamic lighting, light sources, darkvision tiers, per-token vision radius beyond one numeric + property. Windows that see only within a distance: a v1 window is see-through along its whole + drawn length, with no distance rule (5.8, #47). Windows with a real sill and top height, light + coming through windows, and per-wall material (stone, wood, glass): future effort, to be discussed + when lighting arrives (#48). +- Difficult terrain, movement cost and pit/fall semantics: a rules-engine judgement (FFF), not a + wall behaviour; v1 walls only block or pass movement (5.9, #48). - Accounts, passwords, OAuth, multiple tables/campaigns per server, public hosting. -- Players opening or closing doors, and players discovering secret doors (searching, revealing, finding a way in): in v1 only the GM touches a door, so the lock and `secret` are GM authoring state (#46, 5.8). Future effort; moving it to players is a permission change on the existing `door.set`, not a redesign. -- 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). +- Players opening or closing doors, and players discovering secret doors (searching, revealing, + finding a way in): in v1 only the GM touches a door, so the lock and `secret` are GM authoring + state (#46, 5.8). Future effort; moving it to players is a permission change on the existing + `door.set`, not a redesign. +- 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). -- Curved, freeform or image-traced walls: v1 walls are straight segments with a rectangular body, and a cave wall is a chain of straight segments (5.10). A future effort (#45); the shape sits behind a seam so this stays a change of one function, not a redesign. -- 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. +- Curved, freeform or image-traced walls: v1 walls are straight segments with a rectangular body, + and a cave wall is a chain of straight segments (5.10). A future effort (#45); the shape sits + behind a seam so this stays a change of one function, not a redesign. +- 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. --- @@ -53,10 +101,18 @@ A browser virtual tabletop for one table (1 GM + up to 6 players [FIXED, Q1]), s ## 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`. +- 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 ``` @@ -84,15 +140,24 @@ A browser virtual tabletop for one table (1 GM + up to 6 players [FIXED, Q1]), s ### 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). +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. +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). +- 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). --- @@ -122,41 +187,145 @@ A browser virtual tabletop for one table (1 GM + up to 6 players [FIXED, Q1]), s | 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. -- **The one exception: a player marker [FIXED (owner decision), 2026-11-16, #48; shape 2026-11-17, #49].** A wall with `player_marker` on and a derived `kind` of `window` sends a player, once that player has seen part of it, exactly one thing: an **anchor point** (integer px, 6.1 `marker`) and the player's own opaque marker id. No type, no `kind`, no `open`/`closed`, no `sight_dir`, no `label`, no thickness, height, wall id or switch. The client draws the window icon from the anchor alone. Everything else about walls stays GM-only (T2), and the marker never carries a second fact: this is the only wall-derived data on a player wire in v1. Details (defaults, anchor, lifetime, retraction) are in 5.8; the message is `marker {full, set:[{id, pos}], del}`, player-bound only. **The GM receives no `marker` frame:** a player's marker set is that player's own memory, like their explored grid (this table's "Explored grid" row: GM `none`), and the GM already holds every wall fact the marker could carry. The marker id is a per-player opaque 12-character string from the token alphabet, never the wall id. +- `gm_only` is enforced in the view builder, before any frame is built; fault class `GMONLY_TOKEN` + (10.3). +- Players get a per-connection monotonic counter `n`, never a global one; a gap in `n` reveals + nothing about hidden mutations (6.4). +- `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. +- **The one exception: a player marker [FIXED (owner decision), 2026-11-16, #48; shape 2026-11-17, + #49].** A wall with `player_marker` on that derives `window` sends a player, once part of it has + been seen, exactly one anchor point (integer px) and that player's own opaque marker id: no type, + kind, open/closed, direction, label, thickness, height, wall id or switch. It is the only + wall-derived data on a player wire in v1, and the GM never receives it (a player's markers are + that player's own memory, like the explored grid). The rule is stated once in 5.8; the frame is + 6.1 `marker`. ### 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. +- **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`; 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: `; re-runs print the same key. `--new` rotates, revokes all GM sessions, and prints `GM key (new): `. The server holds an exclusive `fcntl(F_SETLK)` write lock on `/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. +- 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: `; re-runs print the same key. + `--new` rotates, revokes all GM sessions, and prints `GM key (new): `. The server holds an + exclusive `fcntl(F_SETLK)` write lock on `/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].** + A server-initiated close is one final application message `closing {reason, code}` (6.1) and + then the close frame; a browser reports **1005** for that close, so the client reads the reason + from the last message. `reason` and `code` are the static values of 6.5; the two-step + consequence and the rejected alternatives are stated there. ### 3.3 Tiles -- Browser asks `GET /tiles//v/_.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//v/_.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"]. +- Browser asks `GET /tiles//v/_.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//v/_.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 `/tiles//v/` (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`. -- **URL grammar and status split [FIXED (owner-delegated), 2026-11-15, #24].** Every numeric component is canonical decimal: digits only, no sign, no space, **no leading zero** (`0` alone is the only zero), bounded at 9 digits for `` and `` (`v` + digits) and 5 digits per coordinate. One spelling per tile, so no cache or test sees an alias. `x in [0, ceil(w/tile_size))`, `y in [0, ceil(h/tile_size))`; the tile grid's origin is the world origin. A malformed component, a coordinate outside the grid, a scene id that is not the one v1 scene, and an art version that is not the scene's all answer **404** (the tile does not exist). The URL is parsed **before** the session is looked at, so an anonymous request gets the same 404 for a nonexistent tile. A missing session, an unknown session and an unexplored tile all answer **403** with the same empty body: the route never distinguishes "no identity" from "not yours", and never reads tile bytes. The GM is always allowed for an in-range tile. The gate reads the player's explored set under the global lock; a player with no sight state has explored nothing. `X-Accel-Redirect` is built only from the parsed integers (`/_tiles//v/_.png`), never from request text, so no path shape can steer it. `Cache-Control: private` is set by the Nim gate and rides through nginx's internal redirect unchanged; nginx adds nothing of its own there (the test vhost records this, 11.1). Nim sends no body and no `Content-Type`. +- 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 + `/tiles//v/` (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`. +- **URL grammar and status split [FIXED (owner-delegated), 2026-11-15, #24].** Every numeric + component is canonical decimal: digits only, no sign, no space, **no leading zero** (`0` alone is + the only zero), bounded at 9 digits for `` and `` (`v` + digits) and 5 digits + per coordinate. One spelling per tile, so no cache or test sees an alias. `x in [0, + ceil(w/tile_size))`, `y in [0, ceil(h/tile_size))`; the tile grid's origin is the world origin. A + malformed component, a coordinate outside the grid, a scene id that is not the one v1 scene, and + an art version that is not the scene's all answer **404** (the tile does not exist). The URL is + parsed **before** the session is looked at, so an anonymous request gets the same 404 for a + nonexistent tile. A missing session, an unknown session and an unexplored tile all answer **403** + with the same empty body: the route never distinguishes "no identity" from "not yours", and never + reads tile bytes. The GM is always allowed for an in-range tile. The gate reads the player's + explored set under the global lock; a player with no sight state has explored nothing. + `X-Accel-Redirect` is built only from the parsed integers + (`/_tiles//v/_.png`), never from request text, so no path shape can + steer it. `Cache-Control: private` is set by the Nim gate and rides through nginx's internal + redirect unchanged; nginx adds nothing of its own there (the test vhost records this, 11.1). Nim + sends no body and no `Content-Type`. ### 3.4 Threat list @@ -185,64 +354,142 @@ Notes: ## 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). +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: `characters: seq[CharacterRec]`, `reveals: (player, subject) -> one row each` and `encountered: player -> token -> snapshot`, all loaded at startup (slice 8 / #23, `server/characters.nim`). -- **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. +- **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: `characters: seq[CharacterRec]`, `reveals: (player, subject) -> one row each` and + `encountered: player -> token -> snapshot`, all loaded at startup (slice 8 / #23, + `server/characters.nim`). +- **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). +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. +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`. +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. +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). +- 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). +- 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. +Move validation is the capsule (swept-circle) check plus the step cap [FIXED, accepted default; +5.5], not the prototype's centre path plus destination circle. -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). +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. +- 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 and the stop-feeding + resync rule stay M5. A Ping/Pong is a control frame and carries no `n` (6). There is no application-level forced close for lag at this pin; only nginx proxy timeouts close a dead peer (below). - - **Lagging client** (outbox over cap, or no Pong within a bound): stop feeding it, keep the connection. On recovery, full resync (6.3). **This supersedes the earlier "close a slow client when lag exceeds a bound" rule** [FIXED (owner-delegated), 2026-11-17, `docs/ANALYSIS-review.md` §6.4]: lag never closes a connection; a client that never recovers is closed only by the nginx proxy timeout, because a forced close is impossible at the mummy pin anyway. - - **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. +- **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 and the stop-feeding + + resync rule stay M5. A Ping/Pong is a control frame and carries no `n` (6). There is no + application-level forced close for lag at this pin; only nginx proxy timeouts close a dead peer + (below). + - **Lagging client** (outbox over cap, or no Pong within a bound): stop feeding it, keep the + connection. On recovery, full resync (6.3). Lag never closes a connection [FIXED + (owner-delegated), 2026-11-17, `docs/ANALYSIS-review.md` §6.4]: a client that never recovers is + closed only by the nginx proxy timeout, because a forced close is impossible at the mummy pin + anyway. + - **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). -- **Borrow, do not copy, under the lock** (#28): the egress reads the live tables through `views.Context`, six pointers into the `App`, because a per-mutation copy of `visions` costs a whole explored `HashSet` per player (~4.9 ms at 262144 cells on the review build, measured). Nothing that egress holds may outlive the lock hold. -- **The scene is a value swapped, never mutated, under the lock** (#31): every reader takes one snapshot under `dbLock` and uses it for the whole request — `tileGate` (parse, explored check and `X-Accel-Redirect` from one record), `checkScene` (the id), the wall/door handlers (the post-lock log and effect frame). A handler that reads `app.scene` twice can see two records; one that reads it outside the lock races the assignment and ORC's free of the old `walls`. -- 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). +- `WebSocket` has 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]. 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). +- **Borrow, do not copy, under the lock** (#28): the egress reads the live tables through + `views.Context`, six pointers into the `App`, because a per-mutation copy of `visions` costs a + whole explored `HashSet` per player (~4.9 ms at 262144 cells on the review build, measured). + Nothing that egress holds may outlive the lock hold. +- **The scene is a value swapped, never mutated, under the lock** (#31): every reader takes one + snapshot under `dbLock` and uses it for the whole request — `tileGate` (parse, explored check and + `X-Accel-Redirect` from one record), `checkScene` (the id), the wall/door handlers (the post-lock + log and effect frame). A handler that reads `app.scene` twice can see two records; one that reads + it outside the lock races the assignment and ORC's free of the old `walls`. +- 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)]. +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]. +- [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): @@ -270,49 +517,205 @@ entity_status(entity_id FK, status, source, PRIMARY KEY(entity_id, status, sourc 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`); the real build stores **chunked bitmaps** [FIXED (owner-delegated, 2026-11-15, #21)]: a chunk is 64x64 cells = 512 B, upserted per mutation and only when the mutation dirtied it. Sizes: 4096 px map / 32 px cell = 16 384 cells = 2 KB (2x2 chunks); 16384 px map = 262 144 cells = 32 KB (8x8 chunks). Measured cost of one mutation-scale write (BEGIN; 512 B upsert; COMMIT): avg 0.015 ms, p99 0.035 ms (4.3's accepted commit tail is ~20 ms), and a real move's ack stays at avg 0.7 ms / p99 1-2 ms with explored writes on (`tests/texplored.nim`, `tools/persistence.test.mjs`). +- Prototype stores one row per explored cell (`exp(role, c)`, one INSERT per new cell, + `HANDOFF.md`); the real build stores **chunked bitmaps** [FIXED (owner-delegated, 2026-11-15, + #21)]: a chunk is 64x64 cells = 512 B, upserted per mutation and only when the mutation dirtied + it. Sizes: 4096 px map / 32 px cell = 16 384 cells = 2 KB (2x2 chunks); 16384 px map = 262 144 + cells = 32 KB (8x8 chunks). Measured cost of one mutation-scale write (BEGIN; 512 B upsert; + COMMIT): avg 0.015 ms, p99 0.035 ms (4.3's accepted commit tail is ~20 ms), and a real move's ack + stays at avg 0.7 ms / p99 1-2 ms with explored writes on (`tests/texplored.nim`, + `tools/persistence.test.mjs`). - 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). -- Step 3 (M3 slice 4, `world`) [FIXED (owner-delegated, 2026-11-15, #19)]: creates `scene` and `wall` and seeds the single v1 scene. `scene(id PK, name, w REAL, h REAL, tile_size INT, cell INT, grid_size REAL, vision_radius_default REAL, token_radius_default REAL, art_version INT, active INT, next_wall_id INT, extra TEXT)`; the seeded row is `id 1, name 'Scene', 4096x4096, tile_size 32, cell 32, grid_size 0 (no grid), vision_radius_default 400, token_radius_default 20, art_version 1, active 1, next_wall_id 1, extra '{}'` (the prototype's world and radii, Q4's 32 px cell). `wall(scene_id FK ON DELETE CASCADE, id, ax, ay, bx, by REAL, kind TEXT CHECK (kind IN ('wall','door')), open INT CHECK (open IN (0,1)), flags TEXT JSON DEFAULT '{}', PRIMARY KEY (scene_id, id))`. Two consequences: (a) M3 has a scene without waiting for the M6 import CLI, so `wall.*` and `door.set` work in slice 4; `w, h, tile_size, cell, art_version` stay off the wire (6.1 `scene.set`). (b) The scene row carries `next_wall_id`, so wall ids survive restarts, removals and re-imports of the same scene (#3). Seeding in the migration rather than at startup keeps the scene identical on every start and lets the migration test assert it (10.3). -- Step 4 (M3 slice 5, `tokens`) [FIXED (owner-delegated, 2026-11-15, #20)]: creates `entity`, the map figures (`id TEXT PK`, `scene_id FK ON DELETE CASCADE`, `kind`, `descriptive_name`, `actual_name`, `x`, `y`, `radius REAL NULL`, `owner_player_id INTEGER REFERENCES player(id) ON DELETE SET NULL`, `gm_only`, `vision_radius REAL NULL`, `flags TEXT` default `'{}'`, `created_at`). `owner_player_id` NULL is GM-controlled, so `player.remove` hands that player's tokens to the GM through the FK alone (3.2) and memory (`0` = GM-controlled) mirrors it. `radius`, the three property buckets, `character_id` and `reveal_all` are NOT columns yet: slices 7 (#22, `token.resize` and props) and 8 (#23, characters and names) own them, and `entity_status` / `explored_chunk` arrive with slice 7 and slice 6. Ids are 12 random characters, so no counter column is needed (8). -- Step 5 (M3 slice 6, `explored`) [FIXED (owner-delegated, 2026-11-15, #21)]: creates `explored_chunk(player_id INTEGER NOT NULL REFERENCES player(id) ON DELETE CASCADE, scene_id INTEGER NOT NULL REFERENCES scene(id) ON DELETE CASCADE, cx INTEGER NOT NULL, cy INTEGER NOT NULL, bits BLOB NOT NULL CHECK (length(bits) = 512), PRIMARY KEY (player_id, scene_id, cx, cy))`. `(cx, cy)` are **chunk** coordinates (`cell div 64`), not cell coordinates; `bits` is a 512-byte bitmap of 64x64 cells, row-major inside the chunk, least-significant bit first (cell `(cx, cy)` is bit `(cy mod 64) * 64 + (cx mod 64)`, byte `bit div 8`, mask `1 shl (bit mod 8)`). Cells outside the scene stay 0, so a map whose cell count is not a multiple of 64 needs no special case; the v1 scene is 128x128 cells = 2x2 chunks, a 16384 px map 8x8. Both FKs cascade, so `player.remove` and a scene delete take the explored rows with them. The layout is pinned by `tests/texplored.nim` (exact byte/bit positions) and re-read independently by `tools/persistence.test.mjs`, so a refactor cannot silently swap axes or bit order. -- Step 6 (M3 slice 7, `token details`) [FIXED (owner-delegated, 2026-11-15, #22)]: adds `entity.props_public`, `props_owner`, `props_gm` (`TEXT NOT NULL DEFAULT '{}'`: one JSON object per visibility bucket) and creates `entity_status(entity_id TEXT REFERENCES entity(id) ON DELETE CASCADE, status TEXT CHECK (status IN ('stuck','squeezed')), source TEXT CHECK (source IN ('walls','GM')), PRIMARY KEY (entity_id, status, source))` - the `(status, source)` set of 5.5. `radius` was already a column from step 4; step 6 is what makes the buckets and the statuses persistent. A token's status rows are rewritten with its row (one transaction), so a status change and the `token` frame that reports it can never disagree after a crash; a wall-derived status change (no row write) rewrites them in the mutation's `NORMAL` transaction. Both FKs cascade, so removing a token removes its entries. -- Step 5 write policy [FIXED (owner-delegated), #21]: a mutation persists **only the chunks its refresh dirtied**, and each of those is encoded from the **whole** explored set (a bitmap is a value, not a delta; writing just the new cells would erase the rest). Durability is `NORMAL` (Q12): explored is derived and monotone, unlike GM-authored content. A `token.move` writes the position and its chunks in **one** transaction (both NORMAL); a GM authoring write (`wall.*`, `door.set`, `token.create`/`update`/`remove`) keeps its own `FULL` row transaction and writes the chunks in a second `NORMAL` transaction, both inside the global lock and before the ack, so no ack precedes the cells it reports and no lock hold grows beyond one extra 512 B upsert. Those two commits are not atomic with each other; a crash between them loses explored cells the client was never told about, and the next refresh re-adds any the token can still see (explored never un-explores). -- Step 7 (M3 slice 8, `characters`) [FIXED (owner-delegated, 2026-11-15, #23)]: creates `character(id TEXT PK, owner_player_id INTEGER NOT NULL REFERENCES player(id), descriptive_name, actual_name, reveal_all INTEGER, props_public/owner/gm TEXT '{}', created_at)`, `name_reveal(player_id FK ON DELETE CASCADE, subject_id TEXT, created_at, PRIMARY KEY (player_id, subject_id))` and `encountered(player_id FK ON DELETE CASCADE, entity_id TEXT, character_id TEXT NULL, descriptive_name TEXT NOT NULL, actual_name TEXT NULL, created_at TEXT, PRIMARY KEY (player_id, entity_id))` plus an index on `characters(owner_player_id)` and `encountered(character_id)`; and adds `entity.character_id TEXT REFERENCES character(id)` and `entity.reveal_all INTEGER NOT NULL DEFAULT 0`. Decisions the sketch in 8 left open, all recorded here: - - **One id namespace.** A character id comes from the same 12-character alphabet and the same collision check as a token id (`tokens.freshId` with *both* lists), so `name_reveal.subject_id` can hold either without an ambiguity column. - - **`character.owner_player_id` never dangles.** It is `NOT NULL` with no cascade; `player.remove` calls `characters.transferToGm` before the player DELETE, inside one transaction (3.2). A raw DELETE would raise instead of orphaning a record. `name_reveal` and `encountered` do cascade on the player, because 6.1 deletes that player's reveals and encountered list with them. - - **`encountered` has no FK to `entity` or `character`.** Entries survive token removal, character removal and a `gm_only` flip (8), and only `encountered.remove` deletes one. `character_id` is stored so a rename and a `reveal_all` can follow the snapshots of everyone who met the character; `actual_name NULL` means "this player was never told it" (the writer stores `''`, db_connector cannot bind NULL). - - **`entity.character_id` is nullable and written as a SQL literal**, because db_connector quotes every bound argument as text and cannot send NULL; the value is always an id from the checked alphabet (`tokens.sqlLitId` raises otherwise). The FK is what makes a dangling link impossible, and `character.remove` pre-checks `in-use` so the FK never fires. - - **`entity.descriptive_name`/`actual_name` stay `NOT NULL`**: a token linked to a character stores `''` in both and its names come from the character record (8). Validation refuses a linked token that carries names and a plain token that lacks them, in both directions (6.1). -- Step 8 (wall record: fields, storage and migration) [FIXED (owner-delegated, 2026-11-17, #49)]: rebuilds `wall` into the typed record 8 describes and adds `marker_seen`; the legacy `kind` column is **dropped** (its values are mapped, not preserved; the project has no real data before M4). The `Migration` entry gains a `data` hook (a `proc(db: DbConn)` run inside the same transaction, after `stmts`, before the history row) for the one part SQL cannot express portably: the height backfill. Statements: +- 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). +- Step 3 (`world`) [FIXED (owner-delegated, 2026-11-15, #19)]: creates `scene` and `wall` and seeds + the single v1 scene. `scene(id PK, name, w REAL, h REAL, tile_size INT, cell INT, grid_size REAL, + vision_radius_default REAL, token_radius_default REAL, art_version INT, active INT, next_wall_id + INT, extra TEXT)`; the seeded row is `id 1, name 'Scene', 4096x4096, tile_size 32, cell 32, + grid_size 0 (no grid), vision_radius_default 400, token_radius_default 20, art_version 1, active + 1, next_wall_id 1, extra '{}'` (the prototype's world and radii, Q4's 32 px cell). `wall(scene_id + FK ON DELETE CASCADE, id, ax, ay, bx, by REAL, kind TEXT CHECK (kind IN ('wall','door')), open INT + CHECK (open IN (0,1)), flags TEXT JSON DEFAULT '{}', PRIMARY KEY (scene_id, id))`. `w, h, + tile_size, cell, art_version` stay off the wire (6.1 `scene.set`). The scene row carries + `next_wall_id`, so wall ids survive restarts, removals and re-imports of the same scene (#3); + seeding in the migration keeps the scene identical on every start and lets the migration test + assert it (10.3). +- Step 4 (`tokens`) [FIXED (owner-delegated, 2026-11-15, #20)]: creates `entity`, the map figures + (`id TEXT PK`, `scene_id FK ON DELETE CASCADE`, `kind`, `descriptive_name`, `actual_name`, `x`, + `y`, `radius REAL NULL`, `owner_player_id INTEGER REFERENCES player(id) ON DELETE SET NULL`, + `gm_only`, `vision_radius REAL NULL`, `flags TEXT` default `'{}'`, `created_at`). + `owner_player_id` NULL is GM-controlled, so `player.remove` hands that player's tokens to the GM + through the FK alone (3.2) and memory (`0` = GM-controlled) mirrors it. Later steps add the + property buckets and `entity_status` (step 6), `character_id` and `reveal_all` (step 7), and + `explored_chunk` (step 5). Ids are 12 random characters, so no counter column is needed (8). +- Step 5 (`explored`) [FIXED (owner-delegated, 2026-11-15, #21)]: creates `explored_chunk(player_id + INTEGER NOT NULL REFERENCES player(id) ON DELETE CASCADE, scene_id INTEGER NOT NULL REFERENCES + scene(id) ON DELETE CASCADE, cx INTEGER NOT NULL, cy INTEGER NOT NULL, bits BLOB NOT NULL CHECK + (length(bits) = 512), PRIMARY KEY (player_id, scene_id, cx, cy))`. `(cx, cy)` are **chunk** + coordinates (`cell div 64`), not cell coordinates; `bits` is a 512-byte bitmap of 64x64 cells, + row-major inside the chunk, least-significant bit first (cell `(cx, cy)` is bit `(cy mod 64) * 64 + + (cx mod 64)`, byte `bit div 8`, mask `1 shl (bit mod 8)`). Cells outside the scene stay 0, so a + map whose cell count is not a multiple of 64 needs no special case; the v1 scene is 128x128 cells + = 2x2 chunks, a 16384 px map 8x8. Both FKs cascade, so `player.remove` and a scene delete take the + explored rows with them. The layout is pinned by `tests/texplored.nim` (exact byte/bit positions) + and re-read independently by `tools/persistence.test.mjs`, so a refactor cannot silently swap axes + or bit order. +- Step 6 (`token details`) [FIXED (owner-delegated, 2026-11-15, #22)]: adds `entity.props_public`, + `props_owner`, `props_gm` (`TEXT NOT NULL DEFAULT '{}'`: one JSON object per visibility bucket) + and creates `entity_status(entity_id TEXT REFERENCES entity(id) ON DELETE CASCADE, status TEXT + CHECK (status IN ('stuck','squeezed')), source TEXT CHECK (source IN ('walls','GM')), PRIMARY KEY + (entity_id, status, source))` - the `(status, source)` set of 5.5. `radius` was already a column + from step 4; step 6 is what makes the buckets and the statuses persistent. A token's status rows + are rewritten with its row (one transaction), so a status change and the `token` frame that + reports it can never disagree after a crash; a wall-derived status change (no row write) rewrites + them in the mutation's `NORMAL` transaction. Both FKs cascade, so removing a token removes its + entries. +- Step 5 write policy [FIXED (owner-delegated), #21]: a mutation persists **only the chunks its + refresh dirtied**, and each of those is encoded from the **whole** explored set (a bitmap is a + value, not a delta; writing just the new cells would erase the rest). Durability is `NORMAL` + (Q12): explored is derived and monotone, unlike GM-authored content. A `token.move` writes the + position and its chunks in **one** transaction (both NORMAL); a GM authoring write (`wall.*`, + `door.set`, `token.create`/`update`/`remove`) keeps its own `FULL` row transaction and writes the + chunks in a second `NORMAL` transaction, both inside the global lock and before the ack, so no ack + precedes the cells it reports and no lock hold grows beyond one extra 512 B upsert. Those two + commits are not atomic with each other; a crash between them loses explored cells the client was + never told about, and the next refresh re-adds any the token can still see (explored never + un-explores). +- Step 7 (`characters`) [FIXED (owner-delegated, 2026-11-15, #23)]: creates `character(id TEXT PK, + owner_player_id INTEGER NOT NULL REFERENCES player(id), descriptive_name, actual_name, reveal_all + INTEGER, props_public/owner/gm TEXT '{}', created_at)`, `name_reveal(player_id FK ON DELETE + CASCADE, subject_id TEXT, created_at, PRIMARY KEY (player_id, subject_id))` and + `encountered(player_id FK ON DELETE CASCADE, entity_id TEXT, character_id TEXT NULL, + descriptive_name TEXT NOT NULL, actual_name TEXT NULL, created_at TEXT, PRIMARY KEY (player_id, + entity_id))` plus an index on `characters(owner_player_id)` and `encountered(character_id)`; and + adds `entity.character_id TEXT REFERENCES character(id)` and `entity.reveal_all INTEGER NOT NULL + DEFAULT 0`. Decisions the sketch in 8 left open, all recorded here: + - **One id namespace.** A character id comes from the same 12-character alphabet and the same + collision check as a token id (`tokens.freshId` with *both* lists), so `name_reveal.subject_id` + can hold either without an ambiguity column. + - **`character.owner_player_id` never dangles.** It is `NOT NULL` with no cascade; `player.remove` + calls `characters.transferToGm` before the player DELETE, inside one transaction (3.2). A raw + DELETE would raise instead of orphaning a record. `name_reveal` and `encountered` do cascade on + the player, because 6.1 deletes that player's reveals and encountered list with them. + - **`encountered` has no FK to `entity` or `character`.** Entries survive token removal, character + removal and a `gm_only` flip (8), and only `encountered.remove` deletes one. `character_id` is + stored so a rename and a `reveal_all` can follow the snapshots of everyone who met the + character; `actual_name NULL` means "this player was never told it" (the writer stores `''`, + db_connector cannot bind NULL). + - **`entity.character_id` is nullable and written as a SQL literal**, because db_connector quotes + every bound argument as text and cannot send NULL; the value is always an id from the checked + alphabet (`tokens.sqlLitId` raises otherwise). The FK is what makes a dangling link impossible, + and `character.remove` pre-checks `in-use` so the FK never fires. + - **`entity.descriptive_name`/`actual_name` stay `NOT NULL`**: a token linked to a character + stores `''` in both and its names come from the character record (8). Validation refuses a + linked token that carries names and a plain token that lacks them, in both directions (6.1). +- Step 8 (wall record: fields, storage and migration) [FIXED (owner-delegated, 2026-11-17, #49)]: + rebuilds `wall` into the typed record 8 describes and adds `marker_seen`; the legacy `kind` column + is **dropped** (its values are mapped, not preserved; the project has no real data before M4). The + `Migration` entry gains a `data` hook (a `proc(db: DbConn)` run inside the same transaction, after + `stmts`, before the history row) for the one part SQL cannot express portably: the height + backfill. Statements: 1. `ALTER TABLE wall RENAME TO wall_v1` - 2. `CREATE TABLE wall (scene_id INTEGER NOT NULL REFERENCES scene(id) ON DELETE CASCADE, id INTEGER NOT NULL, ax/ay/bx/by REAL NOT NULL, thickness REAL NOT NULL DEFAULT 0 CHECK (thickness >= 0 AND thickness <= 256), position TEXT NOT NULL DEFAULT 'center' CHECK (position IN ('center','left','right')), blocks_sight INTEGER NOT NULL DEFAULT 1 CHECK (blocks_sight IN (0,1)), blocks_movement INTEGER NOT NULL DEFAULT 1 CHECK (blocks_movement IN (0,1)), sight_dir TEXT NOT NULL DEFAULT 'both' CHECK (sight_dir IN ('both','left','right')), player_marker INTEGER NOT NULL DEFAULT 0 CHECK (player_marker IN (0,1)), door INTEGER NOT NULL DEFAULT 0 CHECK (door IN (0,1)), open INTEGER NOT NULL DEFAULT 0 CHECK (open IN (0,1)), secret INTEGER NOT NULL DEFAULT 0 CHECK (secret IN (0,1)), locked INTEGER NOT NULL DEFAULT 0 CHECK (locked IN (0,1)), height REAL NULL CHECK (height IS NULL OR (height > 0 AND height <= 100)), label TEXT NULL CHECK (label IS NULL OR (length(label) >= 1 AND length(label) <= 64)), flags TEXT NOT NULL DEFAULT '{}', PRIMARY KEY (scene_id, id), CHECK (open = 0 OR door = 1), CHECK (secret = 0 OR (door = 1 AND open = 0 AND blocks_sight = 1 AND blocks_movement = 1 AND sight_dir = 'both')), CHECK (locked = 0 OR door = 1), CHECK (sight_dir = 'both' OR blocks_sight = 1))` - 3. `INSERT INTO wall (...) SELECT ..., 0, 'center', 1, 1, 'both', 0, CASE kind WHEN 'door' THEN 1 ELSE 0 END, CASE kind WHEN 'door' THEN open ELSE 0 END, 0, 0, NULL, NULL, flags FROM wall_v1` — every existing wall becomes today's behaviour: `thickness 0`, `position center`, `blocks_sight`/`blocks_movement` 1, `sight_dir both`, `player_marker` 0, `secret`/`locked` 0, `height` NULL (full height), `label` NULL; `kind='door'` becomes `door=1` with the **same `open`**, `kind='wall'` becomes `door=0` with `open=0`. + 2. `CREATE TABLE wall (scene_id INTEGER NOT NULL REFERENCES scene(id) ON DELETE CASCADE, id + INTEGER NOT NULL, ax/ay/bx/by REAL NOT NULL, thickness REAL NOT NULL DEFAULT 0 CHECK (thickness + >= 0 AND thickness <= 256), position TEXT NOT NULL DEFAULT 'center' CHECK (position IN + ('center','left','right')), blocks_sight INTEGER NOT NULL DEFAULT 1 CHECK (blocks_sight IN + (0,1)), blocks_movement INTEGER NOT NULL DEFAULT 1 CHECK (blocks_movement IN (0,1)), sight_dir + TEXT NOT NULL DEFAULT 'both' CHECK (sight_dir IN ('both','left','right')), player_marker INTEGER + NOT NULL DEFAULT 0 CHECK (player_marker IN (0,1)), door INTEGER NOT NULL DEFAULT 0 CHECK (door + IN (0,1)), open INTEGER NOT NULL DEFAULT 0 CHECK (open IN (0,1)), secret INTEGER NOT NULL + DEFAULT 0 CHECK (secret IN (0,1)), locked INTEGER NOT NULL DEFAULT 0 CHECK (locked IN (0,1)), + height REAL NULL CHECK (height IS NULL OR (height > 0 AND height <= 100)), label TEXT NULL CHECK + (label IS NULL OR (length(label) >= 1 AND length(label) <= 64)), flags TEXT NOT NULL DEFAULT + '{}', PRIMARY KEY (scene_id, id), CHECK (open = 0 OR door = 1), CHECK (secret = 0 OR (door = 1 + AND open = 0 AND blocks_sight = 1 AND blocks_movement = 1 AND sight_dir = 'both')), CHECK + (locked = 0 OR door = 1), CHECK (sight_dir = 'both' OR blocks_sight = 1))` + 3. `INSERT INTO wall (...) SELECT ..., 0, 'center', 1, 1, 'both', 0, CASE kind WHEN 'door' THEN 1 + ELSE 0 END, CASE kind WHEN 'door' THEN open ELSE 0 END, 0, 0, NULL, NULL, flags FROM wall_v1` — + every existing wall becomes today's behaviour: `thickness 0`, `position center`, + `blocks_sight`/`blocks_movement` 1, `sight_dir both`, `player_marker` 0, `secret`/`locked` 0, + `height` NULL (full height), `label` NULL; `kind='door'` becomes `door=1` with the **same + `open`**, `kind='wall'` becomes `door=0` with `open=0`. 4. `DROP TABLE wall_v1` - 5. `CREATE TABLE marker_seen (player_id INTEGER NOT NULL REFERENCES player(id) ON DELETE CASCADE, scene_id INTEGER NOT NULL, wall_id INTEGER NOT NULL, marker_id TEXT NOT NULL, PRIMARY KEY (player_id, scene_id, wall_id), UNIQUE (player_id, marker_id), FOREIGN KEY (scene_id, wall_id) REFERENCES wall(scene_id, id) ON DELETE CASCADE)` - - **Why a rebuild and not `ALTER TABLE ... DROP COLUMN`:** the step must drop `kind` and add nine NOT NULL columns (plus two nullable) with CHECKs at once, and SQLite's `DROP COLUMN` refuses a column named in a CHECK constraint; the table is thousands of rows at most, so one rebuild is cheaper than a chain of ALTERs plus a rewrite, and it leaves exactly one schema shape. Nothing references `wall` except `marker_seen`, created after it in the same step, so no other FK moves. - - **Why columns and not one JSON object:** precedent (`scene` and `entity` keep every interpreted field as a typed column and reserve `flags`/`props_*` for data the server never reads); CHECKs (a JSON object cannot reject `open:true` on a non-door or a one-way window without triggers); the load path (`loadScene` reads a row into a typed `WallRec`, no parse-and-validate step at every startup beside the wire's own validation); the closed switch set (a new axis is a schema step either way). 5.8's "one object" is about the domain and the wire; the columns are how that one object is stored. - - **Height backfill (the `data` hook):** for every row of `entity` and `character`, if `props_gm` parses as a JSON object without a `height` key, set `height: 1.8` and write it back with a bound TEXT parameter (JSON, so no NULL problem); `eye_height` is never written (the 93 % rule derives it, 5.7). A row with a hand-set `height` is untouched. This is #41's deferred question and #49's answer (5.7). - - **`label` and `height` NULL binding:** db_connector quotes every bound argument as text and cannot bind NULL, so both columns are written as SQL literals (`NULL` when absent) by one helper in `server/world.nim` (`world.sqlLitText` doubles `'`; a real is formatted with a fixed locale-free form). The `''`-for-NULL trick used by `encountered.actual_name` does not apply: `''` is not a legal label (`1..64`) and `0` is not a legal height (`> 0`), so a sentinel would make the load path lie about the domain. - - **Startup and write timing:** `marker_seen` rows are loaded per player with the explored chunks before the first connection (like `explored.restore`); marker inserts/deletes are derived player memory and ride the mutation's `NORMAL` transaction (the same one as the explored chunks), never the `FULL` authoring one. They run before the ack, after the wall row commits, so a retraction's `del` can never precede the wall change it reports. -- Startup: load everything into memory, recompute vision for all players (prototype does, in one transaction) so `vision` is never stale vs walls. Slice 5 loads the scene and its tokens; a player's sight state (`PlayerVision`) is created on that player's first connection and recomputed from the current walls, so nothing is stale after a restart. Slice 6 (#21) restores every stored `explored_chunk` row into that player's set before the first connection (`explored.restore`), so a reloaded grid is the grid the player had; polygons are never stored (they are recomputed, 8). -- 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. `CREATE TABLE marker_seen (player_id INTEGER NOT NULL REFERENCES player(id) ON DELETE CASCADE, + scene_id INTEGER NOT NULL, wall_id INTEGER NOT NULL, marker_id TEXT NOT NULL, PRIMARY KEY + (player_id, scene_id, wall_id), UNIQUE (player_id, marker_id), FOREIGN KEY (scene_id, wall_id) + REFERENCES wall(scene_id, id) ON DELETE CASCADE)` + - **Rebuild, not `ALTER TABLE ... DROP COLUMN`:** SQLite's `DROP COLUMN` refuses a column named in + a CHECK constraint, and the step drops `kind` and adds the CHECKed columns in one shape. + Rationale and rejected alternatives: ADR-0010. Nothing else references `wall` except + `marker_seen`, created after it in the same step. + - **Columns, not one JSON object:** the domain rule is §5.8's one object; the storage decision and + its trade-offs are ADR-0010. + - **Height backfill (the `data` hook):** for every row of `entity` and `character`, if `props_gm` + parses as a JSON object without a `height` key, set `height: 1.8` and write it back with a bound + TEXT parameter (JSON, so no NULL problem); `eye_height` is never written (the 93 % rule derives + it, 5.7). A row with a hand-set `height` is untouched. This is #41's deferred question and #49's + answer (5.7). + - **`label` and `height` NULL binding:** db_connector quotes every bound argument as text and + cannot bind NULL, so both columns are written as SQL literals (`NULL` when absent) by one helper + in `server/world.nim` (`world.sqlLitText` doubles `'`; a real is formatted with a fixed + locale-free form). The `''`-for-NULL trick used by `encountered.actual_name` does not apply: + `''` is not a legal label (`1..64`) and `0` is not a legal height (`> 0`), so a sentinel would + make the load path lie about the domain. + - **Startup and write timing:** `marker_seen` rows are loaded per player with the explored chunks + before the first connection (like `explored.restore`); marker inserts/deletes are derived player + memory and ride the mutation's `NORMAL` transaction (the same one as the explored chunks), never + the `FULL` authoring one. They run before the ack, after the wall row commits, so a retraction's + `del` can never precede the wall change it reports. +- Startup: load everything into memory, recompute vision for all players (prototype does, in one + transaction) so `vision` is never stale vs walls. Startup loads the scene, its tokens and every + stored `explored_chunk` and `marker_seen` row before the first connection (`explored.restore`), so + a reloaded grid and marker set are what the player had. A player's sight state (`PlayerVision`) is + created on that player's first connection and recomputed from the current walls, so nothing is + stale after a restart; polygons are never stored (they are recomputed, 8). +- 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 (for a thick wall, every corner of its body quad, 5.10) 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 (body faces for a thick wall) + circle segments; result = CCW polygon. The wall list holds only walls whose sight switch is on; an open door and a window (`blocks_sight:false`) are absent from it, and a one-way wall is skipped for a viewer on its blind side (5.8). -- **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. +- **Visibility polygon** from token centre: cast rays to every blocking wall endpoint (for a thick + wall, every corner of its body quad, 5.10) 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 (body faces for a thick wall) + circle segments; result = CCW polygon. The wall list + holds only walls whose sight switch is on; an open door and a window (`blocks_sight:false`) are + absent from it, and a one-way wall is skipped for a viewer on its blind side (5.8). +- **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". +- 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`] @@ -326,96 +729,375 @@ explored_chunk(player_id, scene_id, cx, cy, bits BLOB, PRIMARY KEY(player_id, sc | 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`). -- **Thickness cost** [#43, 5.10]: a thick body is a quad, and the fan costs about 10x on a dense scene (13.2 ms vs 1.25 ms baseline on the 5k dense layout; 0.26 ms per polygon, 3.15x, on the 5k sparse one). The owner accepted that and re-baselined the per-move budget [FIXED (owner decision), #43]; polygon optimisation is deferred. The quad is hoisted per wall edit, so the extra cost is in the fan, never in per-viewer geometry. +- `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`). +- **Thickness cost** [#43, 5.10]: a thick body is a quad, and the fan costs about 10x on a dense + scene (13.2 ms vs 1.25 ms baseline on the 5k dense layout; 0.26 ms per polygon, 3.15x, on the 5k + sparse one). The owner accepted that and re-baselined the per-move budget [FIXED (owner decision), + #43]; polygon optimisation is deferred. The quad is hoisted per wall edit, so the extra cost is in + the fan, never in per-viewer geometry. ### 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. With thickness the push is measured from the door's body, not its drawn line (5.5, 5.10; #50), and the leaf is that same body — a close is never a swing. 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). +- 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, #4: failure is `squeezed`]: the token is + pushed aside (5.5), `squeezed` only if neither side is valid. With thickness the push is measured + from the door's body, not its drawn line (5.5, 5.10; #50), and the leaf is that same body — a + close is never a swing. 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). The old `moveBlocked` pin is replaced + by the 5.5 move-rule tests: under the 5.5 trigger such a token is `stuck`, so its 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. +- 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]. +- 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. +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 `blocks_movement` on, and for a door only while it is closed (5.8); open doors do not block, and a one-way wall blocks movement both ways. `dist(X, W)` = distance from point or segment `X` to `W`'s body: the segment itself, or the rectangle of 5.10 when the wall has thickness (a centre inside the rectangle is distance 0). "Overlaps" = `dist < r` (strict; touching at exactly r is clear). +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 `blocks_movement` on, and for a door +only while it is closed (5.8); open doors do not block, and a one-way wall blocks movement both +ways. `dist(X, W)` = distance from point or segment `X` to `W`'s body: the segment itself, or the +rectangle of 5.10 when the wall has thickness (a centre inside the rectangle is distance 0). +"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). The `walls`-sourced case is an accepted, documented effect (6.1 leak note 6, 2026-11-17). -- 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, and a centre inside a thick body is distance 0, so it overlaps (5.10). -- 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; thick-door geometry FIXED (owner-delegated), 2026-11-17, #50; changes the door case only]: a door is a wall like any other, so its **body is the leaf** (5.10) and the push is measured from that body, never from the drawn line. Each token (player or GM-owned) with `dist(c, body) < r` is moved out of the side its centre is on, along that side's normal, by the smallest offset that ends `>= r` from the body (+ `PushEps` = 1e-6 px) — minimal on the push line, which is the owner's "minimal distance" whenever the foot falls on the body; past an end the radial line from the corner would be shorter, but it would also move the token along the axis and is rejected below (it would change today's zero-thickness result). *Geometry:* let `u = (b-a)/|ab|`, `n = (-dy, dx)` (the left normal, 5.8/5.10), `s = (c-a)·u`, `q = (c-a)·n`, and the body's normal span `[q0, q1]` (`center`: `[-t/2, t/2]`; `left`: `[0, t]`; `right`: `[-t, 0]`). *Side:* the face the centre is beyond — `q > q1` is the `+n` (left) side, `q < q0` the `-n` (right) side. A centre inside the body, or past an end but within the normal span (`q0 <= q <= q1`, `Eps` slack), has no side of its own: it takes the side of its previous position (before its most recent move or push; `prev`/`hasPrev` on the token), and if that is undetermined too (also within the span) or there is no history, the left side of `a -> b` — the same test and the same default as today's centre-on-the-line rule. *Target:* with `e = max(0, -s, s-|ab|)` the along-axis overshoot and `F` the chosen face (`q1` on the left, `q0` on the right), `c' = foot + n·(F + σ·(sqrt(max(0, r^2 - e^2)) + PushEps))` where `foot = a + u·s` and `σ = ±1` is the chosen side. Within the axial span (`e = 0`) that is the face offset by `r`; past an end it is the offset from the nearest end corner, keeping the along-axis coordinate so the displacement stays on the normal line — today's `foot + n·sqrt(r^2 - e^2)` generalised to a thick end face. Rejected: a radial displacement from the end corner, which would move the token along the axis as well and change today's zero-thickness result. *Zero thickness:* with `t = 0`, `q0 = q1 = 0`, so `c' = foot + n·σ·(sqrt(r^2 - e^2) + PushEps)`, which is today's `pushFrom` term for term — keep that arithmetic shape (`foot` from the same projection, `perp = sqrt(max(0, r^2 - e^2)) + PushEps`, then `foot + n·σ·perp`), so a zero-thickness door returns identical values on the same inputs; the unchanged existing tests are the regression gate (10.3). *Validity:* the pushed position must be in bounds and `>= r` from every blocking wall's body (the closed door included, other thick bodies included), using the same rectangle-distance primitive as the collider (5.10); 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. *Effects:* 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 and no token's result feeds another's: tokens do not block tokens (no token-token collision; the `blocks_move` flag is not modelled), pushed tokens may overlap each other, and scene order decides nothing — it only rewrites `prev`/`hasPrev` on each pushed token (its pre-push position) exactly as a move would. Explicitly not added later as a "fix": no axial slide out of a doorway, no chain push, no retry loop, no leaf swing or slide. *Which doors:* a locked door, an opening window (`door` on, `blocks_sight:false`) and a secret door all push exactly as a plain closed door — the lock and `secret` are GM authoring state and reach no player, so #46's equivalence holds for thick doors too; a fixed window (`door:false`) never closes and so never pushes; an open door has no body for this rule and never pushes; height never enters the push (5.9). A wall add, a wall update, a thickness change, a position flip and a GM placement or move inside a wall are unchanged: `stuck`, never a push (5.10). -- 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. +**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 (3.1, amended 2026-11-14). The `walls`-sourced case is an + accepted, documented effect (6.1 leak note 6, 2026-11-17). +- 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, and a + centre inside a thick body is distance 0, so it overlaps (5.10). +- 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; thick-door geometry + FIXED (owner-delegated), 2026-11-17, #50; changes the door case only]: a door is a wall like any + other, so its **body is the leaf** (5.10) and the push is measured from that body, never from the + drawn line. Each token (player or GM-owned) with `dist(c, body) < r` is moved out of the side its + centre is on, along that side's normal, by the smallest offset that ends `>= r` from the body (+ + `PushEps` = 1e-6 px) — minimal on the push line, which is the owner's "minimal distance" whenever + the foot falls on the body; past an end the radial line from the corner would be shorter, but it + would also move the token along the axis and is rejected below (it would change today's + zero-thickness result). *Geometry:* let `u = (b-a)/|ab|`, `n = (-dy, dx)` (the left normal, + 5.8/5.10), `s = (c-a)·u`, `q = (c-a)·n`, and the body's normal span `[q0, q1]` (`center`: `[-t/2, + t/2]`; `left`: `[0, t]`; `right`: `[-t, 0]`). *Side:* the face the centre is beyond — `q > q1` is + the `+n` (left) side, `q < q0` the `-n` (right) side. A centre inside the body, or past an end but + within the normal span (`q0 <= q <= q1`, `Eps` slack), has no side of its own: it takes the side + of its previous position (before its most recent move or push; `prev`/`hasPrev` on the token), and + if that is undetermined too (also within the span) or there is no history, the left side of `a -> + b` — the same test and the same default as today's centre-on-the-line rule. *Target:* with `e = + max(0, -s, s-|ab|)` the along-axis overshoot and `F` the chosen face (`q1` on the left, `q0` on + the right), `c' = foot + n·(F + σ·(sqrt(max(0, r^2 - e^2)) + PushEps))` where `foot = a + u·s` and + `σ = ±1` is the chosen side. Within the axial span (`e = 0`) that is the face offset by `r`; past + an end it is the offset from the nearest end corner, keeping the along-axis coordinate so the + displacement stays on the normal line — today's `foot + n·sqrt(r^2 - e^2)` generalised to a thick + end face. Rejected: a radial displacement from the end corner, which would move the token along + the axis as well and change today's zero-thickness result. *Zero thickness:* with `t = 0`, `q0 = + q1 = 0`, so `c' = foot + n·σ·(sqrt(r^2 - e^2) + PushEps)`, which is today's `pushFrom` term for + term — keep that arithmetic shape (`foot` from the same projection, `perp = sqrt(max(0, r^2 - + e^2)) + PushEps`, then `foot + n·σ·perp`), so a zero-thickness door returns identical values on + the same inputs; the unchanged existing tests are the regression gate (10.3). *Validity:* the + pushed position must be in bounds and `>= r` from every blocking wall's body (the closed door + included, other thick bodies included), using the same rectangle-distance primitive as the + collider (5.10); 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. *Effects:* + 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 and no token's result feeds another's: tokens do not block tokens (no token-token + collision; the `blocks_move` flag is not modelled), pushed tokens may overlap each other, and + scene order decides nothing — it only rewrites `prev`/`hasPrev` on each pushed token (its pre-push + position) exactly as a move would. Explicitly not added later as a "fix": no axial slide out of a + doorway, no chain push, no retry loop, no leaf swing or slide. *Which doors:* a locked door, an + opening window (`door` on, `blocks_sight:false`) and a secret door all push exactly as a plain + closed door — the lock and `secret` are GM authoring state and reach no player, so #46's + equivalence holds for thick doors too; a fixed window (`door:false`) never closes and so never + pushes; an open door has no body for this rule and never pushes; height never enters the push + (5.9). A wall add, a wall update, a thickness change, a position flip and a GM placement or move + inside a wall are unchanged: `stuck`, never a push (5.10). +- 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`. +**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`. + - 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]. +**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). +**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). +**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. +**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]. +**Unconfirmed** [PROPOSED, owner to confirm]: `wall.update` counts as remove + add for the status +rule. (A door opened while another wall overlaps does not clear `stuck`: 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. +- **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 a displacement that ends `>= r` from every blocking wall, stays in bounds, and does not enter any other wall. No step cap. Deterministic; the search and its tie-break are fixed and documented in the module header [FIXED (owner-delegated), #22]: a greedy relaxation, one wall per round in scene order, radial from that wall's closest point, at most 16 rounds, plus one flipped-side pass; a step whose centre path would cross a wall is refused, so the push never carries a token through a wall. 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)]. +- **Grow push:** GM grows a token -> the server pushes it away from every blocking wall it overlaps, + by a displacement that ends `>= r` from every blocking wall, stays in bounds, and does not enter + any other wall. No step cap. Deterministic; the search and its tie-break are fixed and documented + in the module header [FIXED (owner-delegated), #22]: a greedy relaxation, one wall per round in + scene order, radial from that wall's closest point, at most 16 rounds, plus one flipped-side pass; + a step whose centre path would cross a wall is refused, so the push never carries a token through + a wall. 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)]. ### 5.7 Heights [FIXED (owner decision), 2026-11-15, #41] -What the vertical dimension is made of, and in what unit. Vision only: what a low wall does to sight is 5.9 (#44), thickness is 5.10 (#45), the wall kinds were #42 (5.8), the wire, the storage and the migration are settled by #49 (6.1, 8). -- **Unit: metres, decimal.** Map distances stay px and no map scale is introduced: see-over compares heights with heights, so no px -> m conversion exists anywhere [FIXED (owner decision), 2026-11-15, #41]. Research #39 3.3 needs only `h_eye` and `h_wall` for the hidden band behind a low wall (`d_floor = s * h_eye / (h_eye - h_wall)`), never a ground distance in metres. -- **Height is a property, not a field.** `height` and `eye_height` live in the `gm` bucket of the three-bucket `props` (8), on the character or on the token; there is no dedicated column and no wire field of their own. **[Narrowed 2026-11-17, #49: this bullet is about tokens and characters. A wall has no `props` buckets, so a wall's height is a typed field on the wall record (metres, optional, absent/`null` = full height), stored as a wall column and carried on the GM `wall`/`walls` frames only; it never reaches a player, and the property-schema registry still holds exactly `height` and `eye_height`.]** -- **Token height.** A character carries its base `height` (the character-sheet value). A plain token (no character) carries its own `height`, and `token.create` without one is refused `invalid` (`invalid`, not `not-found`: a missing field, 6.5). A linked token uses its character's `height` by default; it may carry its own `height` as a temporary on-map override (an enlarge spell doubling it) that never writes the character. Removing the override restores the character's value. **Effective token height** = the token's override, else the character's `height`, else the plain token's own `height`. -- **Eye height** follows the same pattern: `eye_height` on the character (base) with an optional token override. Effective eye height = the token override, else the character's `eye_height`, else, if nobody set one by hand anywhere, **93% of the effective token height**, following height changes live (an enlarge doubles the eyes too). A hand-set value is used as is and is never rescaled [93% FIXED (owner-delegated), 2026-11-15, #41]. -- **Walls**: a wall is full height unless the GM gives it a height in metres; full height means nobody sees over it, a giant included. Existing walls (no height stored) keep behaving exactly as today [FIXED (owner decision), 2026-11-15, #41]. The field is GM-only like all wall data. **The field itself [FIXED (owner-delegated), 2026-11-17, #49]:** `height` is a typed wall field, metres, a finite number `> 0` and `<= 100`; absent or `null` means full height and is stored as SQL `NULL`, never as `0` or `100`. It is set by `wall.add`/`wall.update` (6.1), stored as a wall column (8), and carried only on the GM's `wall`/`walls` frames — it is in leakcheck's `BannedAlways` (`WALLDATA`, 10.3) because no player frame ever carries it. 100 m is a finite wall: every legal figure is `<= 100 m` tall and equality is hidden (5.9), so a 100 m wall hides everyone, and `NULL` differs from it only in a hypothetical taller thing. -- **GM-only.** Both keys are in the `gm` bucket, so no player frame carries either: the `token` frame's `props` is `public` plus `owner` for the controller (6.1), and a player never reads the `gm` bucket. Players see only the outcome, their sight. -- **Limits** [FIXED (owner-delegated), 2026-11-15, #41]: every height > 0; `height` <= 100 m; `eye_height` <= 100 m and **may exceed** `height` (a floating eye); a wall's height > 0 and <= 100 m. The registered kind is enforced on write, so a non-number is `invalid` (8, 9). -- **First registered keys.** `height` and `eye_height` are the first two keys of the property-schema registry (8, 9): `kind` number, bucket `gm`. This is the first time the server interprets props, so the "the server never interprets props in v1" wording of 8 and 9 is narrowed to **the server interprets only registered keys used by core sight rules** (6.1, 8, 9). -- **Migration [FIXED (owner decision), 2026-11-17, #49].** Every existing token and every existing character gets `height: 1.8 m` in its `gm` bucket, filled in code by migration step 8 only when the key is absent (4.4, 8). 1.8 m is a standing adult, so the 93 % rule gives an eye height of 1.674 m live and an old figure sees over a 1.0 m low wall from behind, matching the scenario #43 prototyped. `eye_height` is not written by the migration: the 93 % rule derives it, and a hand-set value is never overwritten. -- Deferred: nothing. What height existing tokens and characters get at migration is settled above (#49); the *target's* height in see-over (a giant's head over a fence) is settled by #44 (5.9): the target's top is what has to clear the line. -- Conflict note (settled later): section 1's non-goals (windows/transparent walls, one-way walls) and Q6's `wall`|`door` only were contradicted by the wall-model work. That is 5.8 [FIXED, 2026-11-15, #42], which superseded both; this block fixed heights and units only, and what a low wall hides (#44) and thickness (#45) were settled afterwards in 5.9 and 5.10. +What the vertical dimension is made of, and in what unit. Vision only: what a low wall does to sight +is 5.9 (#44), thickness is 5.10 (#45), the wall kinds were #42 (5.8), the wire, the storage and the +migration are settled by #49 (6.1, 8). +- **Unit: metres, decimal.** Map distances stay px and no map scale is introduced: see-over compares + heights with heights, so no px -> m conversion exists anywhere [FIXED (owner decision), + 2026-11-15, #41]. Research #39 3.3 needs only `h_eye` and `h_wall` for the hidden band behind a + low wall (`d_floor = s * h_eye / (h_eye - h_wall)`), never a ground distance in metres. +- **Height is a property, not a field.** `height` and `eye_height` live in the `gm` bucket of the + three-bucket `props` (8), on the character or on the token; there is no dedicated column and no + wire field of their own. **[Narrowed 2026-11-17, #49: this bullet is about tokens and characters. + A wall has no `props` buckets, so a wall's height is a typed field on the wall record (metres, + optional, absent/`null` = full height), stored as a wall column and carried on the GM + `wall`/`walls` frames only; it never reaches a player, and the property-schema registry still + holds exactly `height` and `eye_height`.]** +- **Token height.** A character carries its base `height` (the character-sheet value). A plain token + (no character) carries its own `height`, and `token.create` without one is refused `invalid` + (`invalid`, not `not-found`: a missing field, 6.5). A linked token uses its character's `height` + by default; it may carry its own `height` as a temporary on-map override (an enlarge spell + doubling it) that never writes the character. Removing the override restores the character's + value. **Effective token height** = the token's override, else the character's `height`, else the + plain token's own `height`. +- **Eye height** follows the same pattern: `eye_height` on the character (base) with an optional + token override. Effective eye height = the token override, else the character's `eye_height`, + else, if nobody set one by hand anywhere, **93% of the effective token height**, following height + changes live (an enlarge doubles the eyes too). A hand-set value is used as is and is never + rescaled [93% FIXED (owner-delegated), 2026-11-15, #41]. +- **Walls**: a wall is full height unless the GM gives it a height in metres; full height means + nobody sees over it, a giant included. Existing walls (no height stored) keep behaving exactly as + today [FIXED (owner decision), 2026-11-15, #41]. The field is GM-only like all wall data. **The + field itself [FIXED (owner-delegated), 2026-11-17, #49]:** `height` is a typed wall field, metres, + a finite number `> 0` and `<= 100`; absent or `null` means full height and is stored as SQL + `NULL`, never as `0` or `100`. It is set by `wall.add`/`wall.update` (6.1), stored as a wall + column (8), and carried only on the GM's `wall`/`walls` frames — it is in leakcheck's + `BannedAlways` (`WALLDATA`, 10.3) because no player frame ever carries it. 100 m is a finite wall: + every legal figure is `<= 100 m` tall and equality is hidden (5.9), so a 100 m wall hides + everyone, and `NULL` differs from it only in a hypothetical taller thing. +- **GM-only.** Both keys are in the `gm` bucket, so no player frame carries either: the `token` + frame's `props` is `public` plus `owner` for the controller (6.1), and a player never reads the + `gm` bucket. Players see only the outcome, their sight. +- **Limits** [FIXED (owner-delegated), 2026-11-15, #41]: every height > 0; `height` <= 100 m; + `eye_height` <= 100 m and **may exceed** `height` (a floating eye); a wall's height > 0 and <= 100 + m. The registered kind is enforced on write, so a non-number is `invalid` (8, 9). +- **First registered keys.** `height` and `eye_height` are the first two keys of the property-schema + registry (8, 9): `kind` number, bucket `gm`. This is the first time the server interprets props, + so the "the server never interprets props in v1" wording of 8 and 9 is narrowed to **the server + interprets only registered keys used by core sight rules** (6.1, 8, 9). +- **Migration [FIXED (owner decision), 2026-11-17, #49].** Every existing token and every existing + character gets `height: 1.8 m` in its `gm` bucket, filled in code by migration step 8 only when + the key is absent (4.4, 8). 1.8 m is a standing adult, so the 93 % rule gives an eye height of + 1.674 m live and an old figure sees over a 1.0 m low wall from behind, matching the scenario #43 + prototyped. `eye_height` is not written by the migration: the 93 % rule derives it, and a hand-set + value is never overwritten. +- Deferred: nothing. What height existing tokens and characters get at migration is settled above + (#49); the *target's* height in see-over (a giant's head over a fence) is settled by #44 (5.9): + the target's top is what has to clear the line. ### 5.8 Wall switches, presets, doors, windows and one-way [FIXED (owner decision), 2026-11-15, #42; windows and the direction settled 2026-11-16, #47; presets, `player_marker` and `label` settled 2026-11-16, #48; the door leaf and its push settled 2026-11-17, #50] -What a wall's behaviour is made of. Heights are 5.7; what a low wall does to sight and movement is 5.9 (#44); thickness is 5.10 (#45); the wire fields, the storage and the migration are settled by #49 (6.1, 8, 4.4). -- **Behaviour is independent switches, not a kind [FIXED (owner decision), Q1].** A wall carries its own settings and the server reads those. A named kind is only a preset over them. Rejected: a fixed kind enum as the record's behaviour, and client-interpreted free flags; the client may send a preset name, and the **server** expands it and validates the resulting switch set (6.1). -- **v1 switches [FIXED (owner decision), Q2; `player_marker` added 2026-11-16, #48].** `blocks_sight: bool`, `blocks_movement: bool`, `player_marker: bool` (default `false`; what it sends a player is below); door settings `door: bool`, `open: bool`, `secret: bool`, `locked: bool`; one direction field `sight_dir: "both"|"left"|"right"` (default `both`). `label` is a separate GM-only free-text field, not a switch (below). No light axis, no sound axis and no material in v1 (and none on the map) (#48: material is future lighting effort). -- **One object, names are labels [FIXED (owner decision), 2026-11-16, #48].** There is no `terrain` name, preset or derived kind: a railing, a bush, a pit edge and a fixed window are all the same switch set (`blocks_sight:false`, `blocks_movement:true`) and all derive `window`. They differ only in the GM's `label`. This is the §1 principle applied to walls: one object, switches on top, names are labels. -- **Direction is sight only, and `left` names the blind side [FIXED (owner decision), Q4; wording settled 2026-11-16, #47].** `sight_dir` says sight is blocked from one side only; movement is always governed by `blocks_movement` and is two-way (a one-way wall blocks movement both ways). `left`/`right` are the sides of the wall's `a -> b` order: **left is the `(-dy, dx)` normal of `a -> b`**, the same side and the same formula as `position` (5.10) and 5.5's default door-push side. **`sight_dir:"left"` means a viewer standing on the left side cannot see across the wall; a viewer on the right side sees across it** — the field names the side that is blind, never the side that sees. The `one_way` preset defaults to `sight_dir:"left"`, and the editor's flip swaps `left`/`right` without moving `a`/`b` (7.4). `sight_dir != "both"` with `blocks_sight:false` is `invalid` (a direction with nothing to block), and a secret door stays two-way (below). -- **Doors are walls with `door` set, and their settings are independent [FIXED (owner decision), Q3].** `open`, `secret` and `locked` exist only with `door` (`invalid` otherwise). `door.set` keeps working and keeps meaning "set `open`" (6.1); it is not replaced by a door-state enum, and secret/locked are not separate kinds. -- **Closed vs open.** The switches describe the *closed* wall. An open door blocks neither sight nor movement, both sides and direction included, and its stored switches are unchanged; closing restores them. This keeps today's rule (`blocks = not (door and open)`, 5.5) and makes opening a door the only way a door stops blocking. An open door leaves nothing behind: no leaf, no hinge, no drawn arc. The doorway is simply the gap between the wall pieces on either side (the jambs are ordinary walls), so opening removes the door's block and closing puts it back (5.5's push, #50). -- **The door leaf is its own body [FIXED (owner decision), 2026-11-17, #50].** There is no separate leaf rectangle inside an opening and no clamp to the neighbouring pieces: a door stores the same `a`, `b`, `thickness` and `position` as any wall (5.10) and its leaf **is** that body, for sight, movement and the push alike. A thick door therefore bulges out of the doorway on its placement's side, or leaves a step behind its jambs, exactly as the GM drew it; that is authoring, not a rule. A deep opening between thick jambs keeps the thick-jamb tunnel/keyhole view accepted in #43. Nothing swings, slides or hinges: opening and closing are the same body appearing and disappearing, so a close never sweeps an arc through the room. -- **A secret door is always closed, two-way and opaque.** `door.set open:true` on a secret door is `invalid`; the GM clears `secret` first (one click in the editor). `secret` with `sight_dir != both`, with `blocks_sight:false` or with `blocks_movement:false` is also `invalid`; `secret` with `locked` is allowed. Why: a secret door must be indistinguishable from a solid wall to every player (3.1), and an open, one-way or see-through secret door would show a gap or a sight seam. A see-through door cannot be secret; it can be locked (an opening window whose lock the GM must clear first). -- **Player-observability [FIXED (owner-delegated), #42; marker exception 2026-11-16, #48].** `secret` and `locked` never reach a player in any form: wall data is GM-only (3.1), and the only player-visible effects of a wall are the vision polygon, the explored grid, tiles, token frames and — for a marked wall only — the marker (next two bullets). Consequences: a closed secret door must give byte-identical player frames and identical refusals to a solid wall of the same switches; a locked door is just a closed door to sight and movement; no refusal names locked, secret, solid or any other cause (the uniform move nack, 5.5/6.5, already holds). The oracle that pins this is the differential door-equivalence test (10.3, T17, #46). **No other hint of a barrier ever reaches a player**: a refused move stays the uniform nack, with no marker added, no shape change and no cause. -- **Player marker: the one wall fact a player receives [FIXED (owner decision), 2026-11-16, #48; shape and storage 2026-11-17, #49].** `player_marker` is a switch on the wall. On for the `window` preset, **off** for every other preset and for raw switches (a GM may toggle it on any wall). A marker is emitted only for a wall that is **both** `player_marker:true` and derives `kind:"window"`: that is the retraction rule (above) read forward, so a solid wall with the switch on stores the switch and sends nothing. It sends a player **one anchor point and nothing else** — no type, no `kind`, no open/closed, no `sight_dir`, no `label`, no thickness, no height, no wall id, no switch — and the client draws the window icon there. An invisible barrier is simply a window with the marker off. This is the exact, only exception to "walls never reach a player" (3.1) and it is deliberately thin: the marker says "a window is around here", never what it does. - - **Anchor [FIXED (owner-delegated), #48].** The anchor is the wall's drawn midpoint, fixed for the wall (it never follows the viewer). The marker qualifies for a player once **any point of the wall's visible extent** — the segment for a zero-thickness wall, the body's boundary for a thick one — has been inside that player's vision polygon: the same polygon that decides token visibility (5.1). *Why not the midpoint inside the polygon:* a thick wall's midpoint lies inside its own opaque body (5.10), which is never in any polygon, so a thick marked window would never fire. *Why this cannot leak:* the gate is the player's own vision polygon, so nothing behind a sight-blocking wall qualifies; the marker carries no geometry, so the only imprecision is that the anchor may sit up to half a wall piece beyond the visible end — and a window piece is short by construction (`wall | window | wall`), like a door. - - **Lifetime [FIXED (owner-delegated), #48; storage #49].** Once seen, the marker is that player's memory, like the explored grid: it rides with explored, is persisted per player in `marker_seen` (8), survives disconnect and never retracts because the player walked away, a door closed or sight was lost. It **is** retracted when the GM changes the cause: the wall is removed, `player_marker` is turned off, the wall stops being a window (a switch or `sight_dir` change), or its geometry moves (`a`/`b`, `thickness`, `position`). A retraction reveals only that the GM changed something there, never a new position: a moved wall re-earns its marker only when the player sees the new geometry. Retraction never un-explores a cell and never revokes a tile. - - **Wire [FIXED (owner-delegated), #48; shape #49].** The message is the dotless server noun `marker`: `{full:bool, set:[{id, pos}], del:[id]}`, mirroring `encountered`'s full/set/del spelling, with `pos` in integer px (the wall's drawn midpoint, rounded once) and `id` an opaque per-player 12-character string from the token alphabet. It is sent to a player only, never to the GM (3.1). The full set goes on connect and resync (6.3); afterwards a diff carries additions in `set` and retractions in `del`, never both for one id, and a marker is never updated in place (a moved anchor is a retraction plus a re-earned marker). The id is opaque and **per player** (assigned by the server, never the wall id, never shared between players) so the frame can be diffed and a marker removed without exposing wall identity or count. -- **Wall `label` [FIXED (owner-delegated), 2026-11-16, #48].** Every wall may carry an optional GM-only free-text `label` (e.g. "railing", "pit edge", "the king's window"): at most 64 code points, trimmed, no control characters, the 6.5 text rule. It has no behaviour, is stored verbatim, never derived from the switches and never feeds the derived `kind`. It never reaches a player: it is in the leak checker's `BannedAlways` key scan (`10.3`), so a player frame carrying `label` is `WALLDATA`. -- **Only the GM touches a door [FIXED (owner decision), 2026-11-15, #46].** In v1 `door.set` stays G-only: a player sender is refused `not-allowed` at the role step (6.5), whatever the door's settings and whether it is locked or secret. Player-opened doors, lock refusals addressed to a player and player discovery of secret doors (searching, revealing, finding a way in) are not in v1 and not in this map; they are future effort (1). The lock and `secret` are therefore GM authoring state: no player-facing lock message, no lock/unlock intent, and the uniform move nack (5.5) is the only refusal a player ever gets from a wall. -- **A locked door does not open [FIXED (owner decision), 2026-11-15, #46].** `door.set open:true` on a door with `locked` is `invalid`, exactly as for a secret door: the GM unlocks first (editor: one click, hint "locked: unlock first", 7.4). Any write that would store `open:true` together with `locked` or `secret` is `invalid` too — `wall.add`, `wall.update` and a preset expansion alike (6.1) — so no path reaches that state. Closing a locked door is allowed (it is already closed; the setting only refuses opening). Otherwise a locked door is an ordinary closed door: same sight, same explored cells, same tiles, same door push, same refusals. -- **v1 presets: four [FIXED (owner decision), 2026-11-16, #48; supersedes #42/#47's longer list].** A preset is a named switch set used by the editor's one-drag default (7.4) and as the GM's label; never storage. The editor shows four buttons; `secret` and `locked` are checkboxes on any door, not presets. +What a wall's behaviour is made of. Heights are 5.7; what a low wall does to sight and movement is +5.9 (#44); thickness is 5.10 (#45); the wire fields, the storage and the migration are settled by +#49 (6.1, 8, 4.4). +- **Behaviour is independent switches, not a kind [FIXED (owner decision), Q1].** A wall carries its + own settings and the server reads those. A named kind is only a preset over them. Rejected: a + fixed kind enum as the record's behaviour, and client-interpreted free flags; the client may send + a preset name, and the **server** expands it and validates the resulting switch set (6.1). +- **v1 switches [FIXED (owner decision), Q2; `player_marker` added 2026-11-16, #48].** + `blocks_sight: bool`, `blocks_movement: bool`, `player_marker: bool` (default `false`; what it + sends a player is below); door settings `door: bool`, `open: bool`, `secret: bool`, `locked: + bool`; one direction field `sight_dir: "both"|"left"|"right"` (default `both`). `label` is a + separate GM-only free-text field, not a switch (below). No light axis, no sound axis and no + material in v1 (and none on the map) (#48: material is future lighting effort). +- **One object, names are labels [FIXED (owner decision), 2026-11-16, #48].** There is no `terrain` + name, preset or derived kind: a railing, a bush, a pit edge and a fixed window are the same switch + set (`blocks_sight:false`, `blocks_movement:true`) and all derive `window`; they differ only in + the GM's `label`. The §1 principle applied to walls. +- **Direction is sight only, and `left` names the blind side [FIXED (owner decision), Q4; wording + settled 2026-11-16, #47].** `sight_dir` says sight is blocked from one side only; movement is + always governed by `blocks_movement` and is two-way (a one-way wall blocks movement both ways). + `left`/`right` are the sides of the wall's `a -> b` order: **left is the `(-dy, dx)` normal of `a + -> b`**, the same side and the same formula as `position` (5.10) and 5.5's default door-push side. + **`sight_dir:"left"` means a viewer standing on the left side cannot see across the wall; a viewer + on the right side sees across it** — the field names the side that is blind, never the side that + sees. The `one_way` preset defaults to `sight_dir:"left"`, and the editor's flip swaps + `left`/`right` without moving `a`/`b` (7.4). `sight_dir != "both"` with `blocks_sight:false` is + `invalid` (a direction with nothing to block), and a secret door stays two-way (below). +- **Doors are walls with `door` set, and their settings are independent [FIXED (owner decision), + Q3].** `open`, `secret` and `locked` exist only with `door` (`invalid` otherwise). `door.set` + keeps working and keeps meaning "set `open`" (6.1); it is not replaced by a door-state enum, and + secret/locked are not separate kinds. +- **Closed vs open.** The switches describe the *closed* wall. An open door blocks neither sight nor + movement, both sides and direction included, and its stored switches are unchanged; closing + restores them. This keeps today's rule (`blocks = not (door and open)`, 5.5) and makes opening a + door the only way a door stops blocking. An open door leaves nothing behind: no leaf, no hinge, no + drawn arc. The doorway is simply the gap between the wall pieces on either side (the jambs are + ordinary walls), so opening removes the door's block and closing puts it back (5.5's push, #50). +- **The door leaf is its own body [FIXED (owner decision), 2026-11-17, #50].** There is no separate + leaf rectangle inside an opening and no clamp to the neighbouring pieces: a door stores the same + `a`, `b`, `thickness` and `position` as any wall (5.10) and its leaf **is** that body, for sight, + movement and the push alike. A thick door therefore bulges out of the doorway on its placement's + side, or leaves a step behind its jambs, exactly as the GM drew it; that is authoring, not a rule. + A deep opening between thick jambs keeps the thick-jamb tunnel/keyhole view accepted in #43. + Nothing swings, slides or hinges: opening and closing are the same body appearing and + disappearing, so a close never sweeps an arc through the room. +- **A secret door is always closed, two-way and opaque.** `door.set open:true` on a secret door is + `invalid`; the GM clears `secret` first (one click in the editor). `secret` with `sight_dir != + both`, with `blocks_sight:false` or with `blocks_movement:false` is also `invalid`; `secret` with + `locked` is allowed. Why: a secret door must be indistinguishable from a solid wall to every + player (3.1), and an open, one-way or see-through secret door would show a gap or a sight seam. A + see-through door cannot be secret; it can be locked (an opening window whose lock the GM must + clear first). +- **Player-observability [FIXED (owner-delegated), #42; marker exception 2026-11-16, #48].** + `secret` and `locked` never reach a player in any form: wall data is GM-only (3.1), and the only + player-visible effects of a wall are the vision polygon, the explored grid, tiles, token frames + and — for a marked wall only — the marker (next two bullets). Consequences: a closed secret door + must give byte-identical player frames and identical refusals to a solid wall of the same + switches; a locked door is just a closed door to sight and movement; no refusal names locked, + secret, solid or any other cause (the uniform move nack, 5.5/6.5, already holds). The oracle that + pins this is the differential door-equivalence test (10.3, T17, #46). A refused move stays the + uniform nack (5.5), with no marker, shape change or cause. +- **Player marker: the one wall fact a player receives [FIXED (owner decision), 2026-11-16, #48; + shape and storage 2026-11-17, #49].** `player_marker` is a switch on the wall. On for the `window` + preset, **off** for every other preset and for raw switches (a GM may toggle it on any wall). A + marker is emitted only for a wall that is **both** `player_marker:true` and derives + `kind:"window"`: that is the retraction rule (above) read forward, so a solid wall with the switch + on stores the switch and sends nothing. It sends a player **one anchor point and nothing else** — + no type, no `kind`, no open/closed, no `sight_dir`, no `label`, no thickness, no height, no wall + id, no switch — and the client draws the window icon there. An invisible barrier is simply a + window with the marker off. This is the exact, only exception to "walls never reach a player" + (3.1) and it is deliberately thin: the marker says "a window is around here", never what it does. + - **Anchor [FIXED (owner-delegated), #48].** The anchor is the wall's drawn midpoint, fixed for + the wall (it never follows the viewer). The marker qualifies for a player once **any point of + the wall's visible extent** — the segment for a zero-thickness wall, the body's boundary for a + thick one — has been inside that player's vision polygon: the same polygon that decides token + visibility (5.1). *Why not the midpoint inside the polygon:* a thick wall's midpoint lies inside + its own opaque body (5.10), which is never in any polygon, so a thick marked window would never + fire. *Why this cannot leak:* the gate is the player's own vision polygon, so nothing behind a + sight-blocking wall qualifies; the marker carries no geometry, so the only imprecision is that + the anchor may sit up to half a wall piece beyond the visible end — and a window piece is short + by construction (`wall | window | wall`), like a door. + - **Lifetime [FIXED (owner-delegated), #48; storage #49].** Once seen, the marker is that player's + memory, like the explored grid: it rides with explored, is persisted per player in `marker_seen` + (8), survives disconnect and never retracts because the player walked away, a door closed or + sight was lost. It **is** retracted when the GM changes the cause: the wall is removed, + `player_marker` is turned off, the wall stops being a window (a switch or `sight_dir` change), + or its geometry moves (`a`/`b`, `thickness`, `position`). A retraction reveals only that the GM + changed something there, never a new position: a moved wall re-earns its marker only when the + player sees the new geometry. Retraction never un-explores a cell and never revokes a tile. + - **Wire [FIXED (owner-delegated), #48; shape #49].** The message is the dotless server noun + `marker`: `{full:bool, set:[{id, pos}], del:[id]}`, mirroring `encountered`'s full/set/del + spelling, with `pos` in integer px (the wall's drawn midpoint, rounded once) and `id` an opaque + per-player 12-character string from the token alphabet. It is sent to a player only, never to + the GM (3.1). The full set goes on connect and resync (6.3); afterwards a diff carries additions + in `set` and retractions in `del`, never both for one id, and a marker is never updated in place + (a moved anchor is a retraction plus a re-earned marker). The id is opaque and **per player** + (assigned by the server, never the wall id, never shared between players) so the frame can be + diffed and a marker removed without exposing wall identity or count. +- **Wall `label` [FIXED (owner-delegated), 2026-11-16, #48].** Every wall may carry an optional + GM-only free-text `label` (e.g. "railing", "pit edge", "the king's window"): at most 64 code + points, trimmed, no control characters, the 6.5 text rule. It has no behaviour, is stored + verbatim, never derived from the switches and never feeds the derived `kind`. It never reaches a + player: it is in the leak checker's `BannedAlways` key scan (`10.3`), so a player frame carrying + `label` is `WALLDATA`. +- **Only the GM touches a door [FIXED (owner decision), 2026-11-15, #46].** In v1 `door.set` stays + G-only: a player sender is refused `not-allowed` at the role step (6.5), whatever the door's + settings and whether it is locked or secret. Player-opened doors, lock refusals addressed to a + player and player discovery of secret doors (searching, revealing, finding a way in) are not in v1 + and not in this map; they are future effort (1). The lock and `secret` are therefore GM authoring + state: no player-facing lock message, no lock/unlock intent, and the uniform move nack (5.5) is + the only refusal a player ever gets from a wall. +- **A locked door does not open [FIXED (owner decision), 2026-11-15, #46].** `door.set open:true` on + a door with `locked` is `invalid`, exactly as for a secret door: the GM unlocks first (editor: one + click, hint "locked: unlock first", 7.4). Any write that would store `open:true` together with + `locked` or `secret` is `invalid` too — `wall.add`, `wall.update` and a preset expansion alike + (6.1) — so no path reaches that state. Closing a locked door is allowed (it is already closed; the + setting only refuses opening). Otherwise a locked door is an ordinary closed door: same sight, + same explored cells, same tiles, same door push, same refusals. +- **v1 presets: four [FIXED (owner decision), 2026-11-16, #48].** + A preset is a named switch set used by the editor's one-drag default (7.4) and as the GM's label; + never storage. The editor shows four buttons; `secret` and `locked` are checkboxes on any door, + not presets. | preset | `blocks_sight` | `blocks_movement` | door settings | `player_marker` | |---|---|---|---|---| @@ -424,79 +1106,281 @@ What a wall's behaviour is made of. Heights are 5.7; what a low wall does to sig | window | no | yes | `door`, closed | **yes** | | one-way | yes, one side (`sight_dir:"left"` default) | yes | none | no | - `window` is the **opening** form: see-through while closed, passable once opened, because opening a door clears both blocks (above). The **fixed** window is the same see-through switch set with `door` off (the preset, then uncheck `door`): it derives `window` too, keeps `player_marker` on, and needs no second preset. `secret`/`locked` on a door are checkboxes: a secret door is `door` + `secret` (opaque, closed, two-way), a locked door is `door` + `locked`, a locked opening window is `window` + `locked`. There is no distance-limited window: Foundry's distance rule is not expressible with switches, is not in v1 (1), and belongs to the lighting-era effort. No "blocks nothing" preset either: a segment that blocks nothing is not a barrier, and the editor deletes instead; the marker switch belongs to a real wall, it is not a wall of its own. -- **Window [FIXED (owner decision), 2026-11-16, #47].** A window is **see-through along its whole drawn length**: it is not a hole with a sill and a top, and no sill/top height is stored or used (a window's wall `height` is irrelevant, because its sight switch is off and 5.9/5.10 never read it). It is drawn as **its own wall piece inside a wall**, like a door — `wall | window | wall`, three segments — so it needs no new geometry, thickness rule or position rule. Two forms, both already expressible by the switches: **fixed** (`blocks_sight:false`, `blocks_movement:true`, no door: see through, never pass) and **opening** (the same plus `door:true`: see through while closed, pass when opened). A window piece of a thick wall is a thick window: its body occludes sight from both sides (5.10), so it is a see-through slot in a deep wall, not a widened hole. -- **Derived kind: a shape label, never a preset match [FIXED (owner-delegated), 2026-11-16, #48; supersedes #47's two-form kind rule].** With `secret`/`locked` as flags and two window forms, exact preset matching can no longer work. `kind` is derived by shape, in this order: `window` (`blocks_sight:false`, `blocks_movement:true`; door either way), else `one_way` (`blocks_sight:true`, `sight_dir != "both"`), else `door` (`blocks_sight:true`, `blocks_movement:true`, `door:true`), else `wall` (`blocks_sight:true`, `blocks_movement:true`, `door:false`, `sight_dir:"both"`), else `custom`. So the kind list is exactly `wall`, `door`, `window`, `one_way`, `custom`: `secret` and `locked` are flags that never change the label, and a one-way door is labelled `one_way`. The label is GM-facing only (a player sees no wall frame; the marker carries no type). -- **What a one-way wall does to the floor [FIXED (owner decision), 2026-11-16, #47].** Explored cells and tiles differ per side **by construction, not by a new mechanism**: each viewer's sight wall list drops the one-way walls whose blind side that viewer stands on, so polygon, `cellsTouched`, explored and therefore tiles differ between the two sides with no extra state. Explored only grows (5.4), so flipping the direction or `a`/`b` never un-explores a cell and never revokes a tile; a flip only widens what the newly-seeing side may explore next. Movement is two-way (above). With a low wall the direction filters first, then 5.9/5.10 evaluate every crossed face of the walls that remain. -- **Per-viewer filter [FIXED (owner-delegated), 2026-11-16, #47].** Nothing per-viewer is stored or copied: the 5.10 quad faces stay hoisted and viewer-independent, and the fan skips a sight-blocking wall inline when it is one-way and the viewer is on its blind side — one sign test per **one-way** wall per viewer (cross product with `(-dy, dx)`), after the radius-bbox cull; two-way walls pay only a type check. Rejected: a per-viewer copy of the wall list (the prototype measured ~0.15 ms per viewer per frame for the copy, times tokens) and two prebuilt left/right lists (choosing between them needs the same per-viewer side test, and they duplicate the list). -- **Derived label, not a stored kind [FIXED (owner-delegated), #42; derivation rule #48].** The record stores the switches. `kind` survives on the wire as a read-only shape label derived from them (rule above, else `custom`); it is never an input and never the authority, so the label and what the rules do cannot drift. Rejected: storing `kind` next to the switches. -- **Where the switches live [FIXED (owner-delegated), #42; columns #49].** Typed, validated fields on the wall record and in the wall payloads, defaulted server-side; never inside `flags`, because the server interprets sight and movement and `flags` stays the never-interpreted free object (6.1, 8). **They are columns [FIXED (owner-delegated), 2026-11-17, #49]:** one typed column per switch with CHECK constraints, one per geometry field (`thickness`, `position`, `height`), plus `label`; `flags` keeps only data the server never interprets. The rationale and the DDL are in 8 and 4.4; "one object" holds in the domain and on the wire, columns are how the one object is stored. -- **Composition with thickness and height (height decided in 5.9, thickness in 5.10).** The switches choose *which* predicate reads a wall: the sight wall list holds a wall only when `blocks_sight` (one-way: only for the blind side, 5.8), the movement collider only when `blocks_movement`. 5.9 then decides how the sight predicate treats a wall's height, 5.10 how thickness widens the sight footprint and the movement collider. A wall with `blocks_sight=false` is absent from the vision input entirely, height and thickness included — that is what keeps a window cheap. -- **Status model (5.5).** "Blocking wall" for `stuck`, `squeezed`, the door push and the move checks means `blocks_movement` and, for a door, closed. So a fixed or closed window sticks exactly as a solid wall; a closed opening window or a secret door pushes exactly as a solid wall would on a close, with no signal; a fixed window (`door:false`) never closes, so it never pushes (5.5, #50); a one-way wall blocks movement both ways. + `window` is the **opening** form: see-through while closed, passable once opened, because opening + a door clears both blocks (above). The **fixed** window is the same see-through switch set with + `door` off (the preset, then uncheck `door`): it derives `window` too, keeps `player_marker` on, + and needs no second preset. `secret`/`locked` on a door are checkboxes: a secret door is `door` + + `secret` (opaque, closed, two-way), a locked door is `door` + `locked`, a locked opening window is + `window` + `locked`. There is no distance-limited window: Foundry's distance rule is not + expressible with switches, is not in v1 (1), and belongs to the lighting-era effort. No "blocks + nothing" preset either: a segment that blocks nothing is not a barrier, and the editor deletes + instead; the marker switch belongs to a real wall, it is not a wall of its own. +- **Window [FIXED (owner decision), 2026-11-16, #47].** A window is **see-through along its whole + drawn length**: it is not a hole with a sill and a top, and no sill/top height is stored or used + (a window's wall `height` is irrelevant, because its sight switch is off and 5.9/5.10 never read + it). It is drawn as **its own wall piece inside a wall**, like a door — `wall | window | wall`, + three segments — so it needs no new geometry, thickness rule or position rule. Two forms, both + already expressible by the switches: **fixed** (`blocks_sight:false`, `blocks_movement:true`, no + door: see through, never pass) and **opening** (the same plus `door:true`: see through while + closed, pass when opened). A window piece of a thick wall is a thick window: its body occludes + sight from both sides (5.10), so it is a see-through slot in a deep wall, not a widened hole. +- **Derived kind: a shape label, never a preset match [FIXED (owner-delegated), 2026-11-16, #48].** + With `secret`/`locked` as flags and two window forms, + exact preset matching can no longer work. `kind` is derived by shape, in this order: `window` + (`blocks_sight:false`, `blocks_movement:true`; door either way), else `one_way` + (`blocks_sight:true`, `sight_dir != "both"`), else `door` (`blocks_sight:true`, + `blocks_movement:true`, `door:true`), else `wall` (`blocks_sight:true`, `blocks_movement:true`, + `door:false`, `sight_dir:"both"`), else `custom`. So the kind list is exactly `wall`, `door`, + `window`, `one_way`, `custom`: `secret` and `locked` are flags that never change the label, and a + one-way door is labelled `one_way`. The label is GM-facing only (a player sees no wall frame; the + marker carries no type). +- **What a one-way wall does to the floor [FIXED (owner decision), 2026-11-16, #47].** Explored + cells and tiles differ per side **by construction, not by a new mechanism**: each viewer's sight + wall list drops the one-way walls whose blind side that viewer stands on, so polygon, + `cellsTouched`, explored and therefore tiles differ between the two sides with no extra state. + Explored only grows (5.4), so flipping the direction or `a`/`b` never un-explores a cell and never + revokes a tile; a flip only widens what the newly-seeing side may explore next. Movement is + two-way (above). With a low wall the direction filters first, then 5.9/5.10 evaluate every crossed + face of the walls that remain. +- **Per-viewer filter [FIXED (owner-delegated), 2026-11-16, #47].** Nothing per-viewer is stored or + copied: the 5.10 quad faces stay hoisted and viewer-independent, and the fan skips a + sight-blocking wall inline when it is one-way and the viewer is on its blind side — one sign test + per **one-way** wall per viewer (cross product with `(-dy, dx)`), after the radius-bbox cull; + two-way walls pay only a type check. Rejected: a per-viewer copy of the wall list (the prototype + measured ~0.15 ms per viewer per frame for the copy, times tokens) and two prebuilt left/right + lists (choosing between them needs the same per-viewer side test, and they duplicate the list). +- **Where the switches live [FIXED (owner-delegated), #42; columns #49].** Typed, validated fields + on the wall record and in the wall payloads, defaulted server-side; never inside `flags`, because + the server interprets sight and movement and `flags` stays the never-interpreted free object (6.1, + 8). They are columns with CHECK constraints (ADR-0010). +- **Composition with thickness and height.** The switches choose *which* predicate reads a wall: the + sight wall list holds a wall only when `blocks_sight` (one-way: only for the blind side), the + movement collider only when `blocks_movement`. 5.9 then decides what a wall's height does to that + predicate, 5.10 how thickness widens its footprint and the collider; a `blocks_sight:false` wall + is absent from the vision input entirely, height and thickness included. +- **Status model (5.5).** "Blocking wall" for `stuck`, `squeezed`, the door push and the move checks + means `blocks_movement` and, for a door, closed. So a fixed or closed window sticks exactly as a + solid wall; a closed opening window or a secret door pushes exactly as a solid wall would on a + close, with no signal; a fixed window (`door:false`) never closes, so it never pushes (5.5, #50); + a one-way wall blocks movement both ways. ### 5.9 Low walls: see-over [FIXED (owner decision), 2026-11-15, #44] -What a wall shorter than a figure does to sight and movement. Heights and units are 5.7; the switches and the one-way direction are 5.8; thickness is 5.10 (#45); the wire and the migration are settled by #49 (6.1, 8). Answers #41's open question: the *target's* height matters. +What a wall shorter than a figure does to sight and movement. Heights and units are 5.7; the +switches and the one-way direction are 5.8; thickness is 5.10 (#45); the wire and the migration are +settled by #49 (6.1, 8). Answers #41's open question: the *target's* height matters. -- **Movement is blind to height [FIXED (owner decision), #44].** "Does a low wall block movement?" is answered by `blocks_movement` alone, exactly as in 5.5/5.8. Height is a sight input and never enters the move rules, the collider, `stuck`/`squeezed` or the door push: a knee-high wall with the switch on stops a walker, and a wall with it off is walked through however tall it is. -- **See-over is a per-target predicate, not a wall flag [FIXED (owner decision), #43].** A token is visible iff its top clears the wall on the line from the viewer's eye; the visibility polygon stays **strict**, i.e. it still stops at every sight wall's line (5.1). Consequence, accepted: a visible token may stand on a cell its viewer has not explored ("floating on black"). Rejected: a permissive polygon that fogs a band nobody can see, and a "see-over" switch on the wall. -- **Geometry.** Viewer eye at the viewer token's centre with effective eye height `h_e` (5.7); target at its centre with effective height `h_t` (so its top is `h_t`). For each sight-blocking wall `W` the 2D segment eye -> target crosses (the viewer's filtered sight list, 5.8: `blocks_sight` on, closed if a door, direction permitting the block from the viewer's side), let `d_W` = distance eye -> crossing point and `d_T` = distance eye -> target centre. The sight line to the top is `h_e + (h_t - h_e)·(d_W/d_T)` high where it crosses `W`. The target is visible iff that height is **strictly greater** than `W`'s height for **every** crossed wall; equality is hidden. A full-height wall (no `height` prop, 5.7) is absolute: nobody sees over it, a giant included. -- **Consequences, all intended [FIXED (owner decision), #44].** No "adjacent always visible" exception and no distance rule. A crouched figure right behind a low wall is hidden while a distant figure behind the same wall is seen; a figure shorter than the viewer's eye is seen over a wall from far away and not from close up. A giant's head over a fence: yes, when it clears the line. -- **No per-cell height test [FIXED (owner decision), #44].** The floor behind a low wall stays unexplored and black, no tile is sent, and neither the polygon, `cellsTouched` nor `tiles.nim` learns about the band. There is no per-cell elevation in v1; the predicate is per target, not per cell. -- **Players get a binary answer [FIXED (owner decision), #44].** Visible or not; when visible the whole token is drawn and its name/status behave as today. No clipping, no partial-body drawing, no cover rules (a rules-engine judgement, non-goal 1). -- **GM-only who-sees-it view [FIXED (owner decision), in v1, #44].** The GM can see, per token, which player(s)/characters see it and its **visible fraction**: the share of the token's height above the highest blocking sight line, 100 % when nothing is crossed (definition below). GM-only, derived from data the GM already receives (all walls, all tokens, the `gm` props), so no player-visible field is added; never on a player wire in any form. The panel's shape is M4 editor/fog work (7.4). +- **Movement is blind to height [FIXED (owner decision), #44].** "Does a low wall block movement?" + is answered by `blocks_movement` alone, exactly as in 5.5/5.8. Height is a sight input and never + enters the move rules, the collider, `stuck`/`squeezed` or the door push: a knee-high wall with + the switch on stops a walker, and a wall with it off is walked through however tall it is. +- **See-over is a per-target predicate, not a wall flag [FIXED (owner decision), #43].** A token is + visible iff its top clears the wall on the line from the viewer's eye; the visibility polygon + stays **strict**, i.e. it still stops at every sight wall's line (5.1). Consequence, accepted: a + visible token may stand on a cell its viewer has not explored ("floating on black"). Rejected: a + permissive polygon that fogs a band nobody can see, and a "see-over" switch on the wall. +- **Geometry.** Viewer eye at the viewer token's centre with effective eye height `h_e` (5.7); + target at its centre with effective height `h_t` (so its top is `h_t`). For each sight-blocking + wall `W` the 2D segment eye -> target crosses (the viewer's filtered sight list, 5.8: + `blocks_sight` on, closed if a door, direction permitting the block from the viewer's side), let + `d_W` = distance eye -> crossing point and `d_T` = distance eye -> target centre. The sight line + to the top is `h_e + (h_t - h_e)·(d_W/d_T)` high where it crosses `W`. The target is visible iff + that height is **strictly greater** than `W`'s height for **every** crossed wall; equality is + hidden. A full-height wall (no `height` prop, 5.7) is absolute: nobody sees over it, a giant + included. +- **Consequences, all intended [FIXED (owner decision), #44].** No "adjacent always visible" + exception and no distance rule. A crouched figure right behind a low wall is hidden while a + distant figure behind the same wall is seen; a figure shorter than the viewer's eye is seen over a + wall from far away and not from close up. A giant's head over a fence: yes, when it clears the + line. +- **No per-cell height test [FIXED (owner decision), #44].** The floor behind a low wall stays + unexplored and black, no tile is sent, and neither the polygon, `cellsTouched` nor `tiles.nim` + learns about the band. There is no per-cell elevation in v1; the predicate is per target, not per + cell. +- **Players get a binary answer [FIXED (owner decision), #44].** Visible or not; when visible the + whole token is drawn and its name/status behave as today. No clipping, no partial-body drawing, no + cover rules (a rules-engine judgement, non-goal 1). +- **GM-only who-sees-it view [FIXED (owner decision), in v1, #44].** The GM can see, per token, + which player(s)/characters see it and its **visible fraction**: the share of the token's height + above the highest blocking sight line, 100 % when nothing is crossed (definition below). GM-only, + derived from data the GM already receives (all walls, all tokens, the `gm` props), so no + player-visible field is added; never on a player wire in any form. The panel's shape is M4 + editor/fog work (7.4). - **Delegated knobs [FIXED (owner-delegated), #44].** - - Comparison strict, equality hidden, evaluated at every face of the wall the line crosses — 5.10 fixes the thick case (with zero thickness the faces coincide with the wall line, so this is today's point). *Why: a body exactly level with the wall top is not above it.* - - Every crossed sight wall must clear; the predicate is an AND, so one failing wall hides the token. Candidate walls come from the existing radius-bbox cull, so the cost is per crossed wall and adds no fan (research #39: the predicate is not part of the polygon). *Why: one rule, one pass, zero geometry.* - - Hook at `visibleTo` (`server/vision.nim`): visible iff `insideAny(pos)` **or** the predicate. `visibilityPolygon`, `cellsTouched` and `tiles.nim` never read a height. *Why: the token-visibility rule stays in one copy (10.3's fault classes rely on it) and the fan is untouched.* - - Visible fraction: per crossed wall the required top is `h_req(W) = h_e + (h_w - h_e)·(d_T/d_W)`, and `f_W = clamp((h_t - h_req(W))/h_t, 0, 1)`; the token's fraction is the **minimum** over crossed walls, 1 when none is crossed. `f = 0` exactly when the predicate hides it, because the comparison is strict. *Why: the same predicate read as a number cannot drift from the binary answer.* - - In the GM view a player's fraction for a token = the **maximum** over that player's tokens that see it. *Why: the player does see it from that one.* - - Oracles [FIXED (owner-delegated), #44]. `tools/leakcheck.nim`'s `clearLine` gets its own height test (walls carry their height; a target's top is compared independently of the server's code, never by calling vision.nim). Cells in a low wall's hidden band are **maybe** for the independent explored/tile oracle: a tile there may be allowed or refused, both correct, but a band cell may never be **sure** (a `200` on a band cell is legitimate, a withheld proof cell never). A token hidden only by the band gives no `token` frame, no name and no encountered entry, and no churn: no alternating frames as a position crosses the line. The assertions land with the build tickets (/to-spec), not here. -- Deferred: nothing about see-over itself. A window is unaffected (its `blocks_sight` is off, so it never reaches sight, 5.8). Whether the client or the server computes the GM's numbers is M4's build call. + - Comparison strict, equality hidden, evaluated at every face of the wall the line crosses — 5.10 + fixes the thick case (with zero thickness the faces coincide with the wall line, so this is + today's point). *Why: a body exactly level with the wall top is not above it.* + - Every crossed sight wall must clear; the predicate is an AND, so one failing wall hides the + token. Candidate walls come from the existing radius-bbox cull, so the cost is per crossed wall + and adds no fan (research #39: the predicate is not part of the polygon). *Why: one rule, one + pass, zero geometry.* + - Hook at `visibleTo` (`server/vision.nim`): visible iff `insideAny(pos)` **or** the predicate. + `visibilityPolygon`, `cellsTouched` and `tiles.nim` never read a height. *Why: the + token-visibility rule stays in one copy (10.3's fault classes rely on it) and the fan is + untouched.* + - Visible fraction: per crossed wall the required top is `h_req(W) = h_e + (h_w - h_e)·(d_T/d_W)`, + and `f_W = clamp((h_t - h_req(W))/h_t, 0, 1)`; the token's fraction is the **minimum** over + crossed walls, 1 when none is crossed. `f = 0` exactly when the predicate hides it, because the + comparison is strict. *Why: the same predicate read as a number cannot drift from the binary + answer.* + - In the GM view a player's fraction for a token = the **maximum** over that player's tokens that + see it. *Why: the player does see it from that one.* + - Oracles [FIXED (owner-delegated), #44]. `tools/leakcheck.nim`'s `clearLine` gets its own height + test (walls carry their height; a target's top is compared independently of the server's code, + never by calling vision.nim). Cells in a low wall's hidden band are **maybe** for the + independent explored/tile oracle: a tile there may be allowed or refused, both correct, but a + band cell may never be **sure** (a `200` on a band cell is legitimate, a withheld proof cell + never). A token hidden only by the band gives no `token` frame, no name and no encountered + entry, and no churn: no alternating frames as a position crosses the line. The assertions land + with the build tickets (/to-spec), not here. +- Deferred: nothing about see-over itself. A window is unaffected (its `blocks_sight` is off, so it + never reaches sight, 5.8). Whether the client or the server computes the GM's numbers is M4's + build call. ### 5.10 Thick walls: the body, sight and movement [FIXED (owner decision), 2026-11-15, #45] -What a wall's thickness does to the floor it covers, the vision fan and the collider. Heights and units are 5.7, the switches 5.8, see-over 5.9; the wire fields and the migration are settled by #49 (6.1, 8); a thick door's leaf is the body itself and its push is 5.5 (settled 2026-11-17, #50, 5.8). +What a wall's thickness does to the floor it covers, the vision fan and the collider. Heights and +units are 5.7, the switches 5.8, see-over 5.9; the wire fields and the migration are settled by #49 +(6.1, 8); a thick door's leaf is the body itself and its push is 5.5 (settled 2026-11-17, #50, 5.8). -- **The body.** Thickness is a strip of floor: a rectangle of length `|ab|` with **square ends** and no extension past `a` or `b`, and width `thickness`. `position` places it: `center` (default) straddles the drawn `a -> b` line, half the thickness each side; `left` keeps the whole body on the left of `a -> b`, so the line is the inner face and the room's interior; `right` on the other side. A flip moves only the body: `a` and `b` never move, so the GM draws the exact interior size and puts the thickness outward. `left`/`right` are the sides of the `a -> b` order, the same pair `sight_dir` uses (5.8): left is the `(-dy, dx)` normal of `a -> b`, the same left as 5.5's default door-push side. The editor draws each one-way wall's direction as an arrow at its middle and offers a flip (7.4, 5.8, #47). -- **Zero thickness is today, exactly.** `thickness: 0` degrades the rectangle to the segment: same polygon, same collider, same see-over crossing point. Every existing wall migrates to `thickness: 0, position: "center"` and changes nothing [FIXED (owner decision), #45]. -- **Unit and limits** [FIXED (owner-delegated), 2026-11-15, #45]. Thickness is **px**, a map distance like length and token radius: heights are metres (5.7) and no scale converts between the two (5.7). `0 <= thickness <= 256` px (8 tiles): 0 is the line, and 256 is already a room-sized block better drawn as several walls; the cap bounds the quad. The body may cross the map edge (a border wall thickened outward); only the map area exists, so nothing is drawn or explored outside it. -- **The body is opaque floor [FIXED (owner decision), #45; both sides for a one-way wall, #47].** It is never inside a player's polygon and its own area is never newly explored, so a player's fog stays black under it and no tile is newly revealed there. This holds on both sides of a one-way wall (5.8). Explored only grows (5.4), so cells explored before a body was thickened over stay explored and tiles already held stay held; the rule is that a body reveals nothing, ever. -- **One shape, two readers [FIXED (owner decision), #45].** Sight and movement read the same exact rectangle, with the same square ends, so a corner cannot be generous to one and tight to the other. A wall with `blocks_sight: false` contributes nothing to sight, body included (a window's thickness is movement-only, 5.8); its collider still uses the thickness. -- **Sight: the body quad.** A sight-blocking thick wall enters the vision input as the four faces of its rectangle (two long, two square ends), hoisted once per wall edit and reused for every viewer and frame — viewer-independent, so it caches [#43 measured: 4-face quad 0.263 ms hoisted vs 0.943 ms per query on 5k sparse, 12.721 vs 13.229 ms dense; the 3-face near+caps silhouette is observer-dependent, cannot be hoisted, and costs 0.699 ms per query sparse (8.4x thin), so the hoisted quad is the cheaper exact model]. The fan and `cellsTouched` are otherwise unchanged, and zero thickness is the segment of today. A one-way wall's own body is opaque floor on **both** sides (5.8, #47): the blind side gets no face at all, and the seeing side sees up to the near face — never into or past the body's floor. -- **Movement: exact circle-vs-rectangle.** `dist(c, body)` is the true Euclidean distance from the token's centre to the rectangle, and a centre **inside** the body is distance 0, so it overlaps (`0 < r`). One rectangle-distance primitive, in one place, serves every reader: `pathClear` (the capsule/segment check and the escape rule of 5.5), the `stuck`/`squeezed` overlap check, the door push, `pushOutOfWalls` and resize/grow push. Movement still never reads height (5.9). -- **See-over across a body [FIXED (owner decision), #45].** 5.9's comparison is evaluated at **every face the eye -> target-top line crosses**: entering and leaving a body is two crossings (near and far), and an oblique line may cross an end face instead, so the rule is "every crossed face of the rectangle", strictly above the wall's height at each. Both must clear: a target shorter than the viewer's eye has the line falling, so the far face is stricter; a taller one has it rising, so the near face is. With zero thickness the two faces coincide with the wall line, and 5.9 is unchanged. The visible fraction's per-wall minimum becomes a minimum over that wall's crossed faces, so the number cannot drift from the binary answer. Candidate walls still come from the radius-bbox cull, now over the body's box. -- **A viewer inside a sight-blocking body sees nothing [FIXED (owner decision), #45].** A token whose vision origin (its centre) lies inside such a body gets an empty polygon until it leaves: no cells, no other tokens, no tiles. It normally overlaps the body and is `stuck` too, so it cannot walk out by itself; the GM moves it out. -- **A wall edit never pushes [FIXED (owner decision), #45].** A thickness change, a position flip or a move that puts a body over a token leaves the token where it is and makes it `stuck` (5.5's rule for a wall edit over a token: it may only move to reduce or leave the overlap). Only a door **closing** pushes (5.5; with thickness the push is measured from this same body, and the body is the leaf, 5.8 and 5.5, #50). So the GM can thicken a wall through a crowd and nobody teleports. -- **Joints: overlap, never a mitre [FIXED (owner-delegated), #45].** Two walls meeting at a corner keep their own rectangles; the bodies overlap at the joint and the outside corner shows a small notch. No mitre, no merged joint, no joint object, and no crack: the overlap is what closes it. A cave is a chain of straight walls. #43 measured that joints need no thickness: zero-width corners show no crack either. -- **Shape behind a seam [FIXED (owner-delegated), #45].** A wall's occupied area is produced by **one** wall-shape function, and no other code reads `a`/`b` to build geometry; in v1 that function returns the 5.10 rectangle. Curved, freeform and image-traced walls are out of v1 (1) and land by changing that function alone, so no sight, move, editor or wire code may assume "a wall is a straight segment". -- **Editor and fields** [FIXED (owner-delegated), #45]. The GM editor gains a thickness control and a **position flip** with a live preview of the body, the flip never moving `a`/`b` (7.4). A new wall starts at the GM's last-used thickness, held as editor state for the session (not a scene field, not on the wire); a fresh editor starts at 0. The record and the payloads carry `thickness` (number, px, 0..256) and `position` (`center|left|right`, default `center`); the payload shape and the existing-row migration are settled in 6.1 and 8 (#49). -- Oracles: the independent explored/tile oracle and the leak checker build the body rectangle from `a`, `b`, `thickness` and `position` with their own code, never by calling `vision.nim` or the move rules, and use it for both the sight footprint and the distance test. Assertions land with the build tickets (10.2, 10.3). -- Deferred: nothing about thickness. The columns, the payload shape and the migration are settled in 6.1, 8 and 4.4 (#49). What a door is with thickness is settled: the leaf is the wall's own body (5.8) and the push is measured from that body, reducing to today exactly at zero thickness (5.5) [FIXED, 2026-11-17, #50]. +- **The body.** Thickness is a strip of floor: a rectangle of length `|ab|` with **square ends** and + no extension past `a` or `b`, and width `thickness`. `position` places it: `center` (default) + straddles the drawn `a -> b` line, half the thickness each side; `left` keeps the whole body on + the left of `a -> b`, so the line is the inner face and the room's interior; `right` on the other + side. A flip moves only the body: `a` and `b` never move, so the GM draws the exact interior size + and puts the thickness outward. `left`/`right` are the sides of the `a -> b` order, the same pair + `sight_dir` uses (5.8): left is the `(-dy, dx)` normal of `a -> b`, the same left as 5.5's default + door-push side. The editor draws each one-way wall's direction as an arrow at its middle and + offers a flip (7.4, 5.8, #47). +- **Zero thickness is today, exactly.** `thickness: 0` degrades the rectangle to the segment: same + polygon, same collider, same see-over crossing point. Every existing wall migrates to `thickness: + 0, position: "center"` and changes nothing [FIXED (owner decision), #45]. +- **Unit and limits** [FIXED (owner-delegated), 2026-11-15, #45]. Thickness is **px**, a map + distance like length and token radius: heights are metres (5.7) and no scale converts between the + two (5.7). `0 <= thickness <= 256` px (8 tiles): 0 is the line, and 256 is already a room-sized + block better drawn as several walls; the cap bounds the quad. The body may cross the map edge (a + border wall thickened outward); only the map area exists, so nothing is drawn or explored outside + it. +- **The body is opaque floor [FIXED (owner decision), #45; both sides for a one-way wall, #47].** It + is never inside a player's polygon and its own area is never newly explored, so a player's fog + stays black under it and no tile is newly revealed there. This holds on both sides of a one-way + wall (5.8). Explored only grows (5.4), so cells explored before a body was thickened over stay + explored and tiles already held stay held; the rule is that a body reveals nothing, ever. +- **One shape, two readers [FIXED (owner decision), #45].** Sight and movement read the same exact + rectangle, with the same square ends, so a corner cannot be generous to one and tight to the + other. A wall with `blocks_sight: false` contributes nothing to sight, body included (a window's + thickness is movement-only, 5.8); its collider still uses the thickness. +- **Sight: the body quad.** A sight-blocking thick wall enters the vision input as the four faces of + its rectangle (two long, two square ends), hoisted once per wall edit and reused for every viewer + and frame — viewer-independent, so it caches [#43 measured: 4-face quad 0.263 ms hoisted vs 0.943 + ms per query on 5k sparse, 12.721 vs 13.229 ms dense; the 3-face near+caps silhouette is + observer-dependent, cannot be hoisted, and costs 0.699 ms per query sparse (8.4x thin), so the + hoisted quad is the cheaper exact model]. The fan and `cellsTouched` are otherwise unchanged, and + zero thickness is the segment of today. A one-way wall's own body is opaque floor on **both** + sides (5.8, #47): the blind side gets no face at all, and the seeing side sees up to the near face + — never into or past the body's floor. +- **Movement: exact circle-vs-rectangle.** `dist(c, body)` is the true Euclidean distance from the + token's centre to the rectangle, and a centre **inside** the body is distance 0, so it overlaps + (`0 < r`). One rectangle-distance primitive, in one place, serves every reader: `pathClear` (the + capsule/segment check and the escape rule of 5.5), the `stuck`/`squeezed` overlap check, the door + push, `pushOutOfWalls` and resize/grow push. Movement still never reads height (5.9). +- **See-over across a body [FIXED (owner decision), #45].** 5.9's comparison is evaluated at **every + face the eye -> target-top line crosses**: entering and leaving a body is two crossings (near and + far), and an oblique line may cross an end face instead, so the rule is "every crossed face of the + rectangle", strictly above the wall's height at each. Both must clear: a target shorter than the + viewer's eye has the line falling, so the far face is stricter; a taller one has it rising, so the + near face is. With zero thickness the two faces coincide with the wall line, and 5.9 is unchanged. + The visible fraction's per-wall minimum becomes a minimum over that wall's crossed faces, so the + number cannot drift from the binary answer. Candidate walls still come from the radius-bbox cull, + now over the body's box. +- **A viewer inside a sight-blocking body sees nothing [FIXED (owner decision), #45].** A token + whose vision origin (its centre) lies inside such a body gets an empty polygon until it leaves: no + cells, no other tokens, no tiles. It normally overlaps the body and is `stuck` too, so it cannot + walk out by itself; the GM moves it out. +- **A wall edit never pushes [FIXED (owner decision), #45].** A thickness change, a position flip or + a move that puts a body over a token leaves the token where it is and makes it `stuck` (5.5's rule + for a wall edit over a token: it may only move to reduce or leave the overlap). Only a door + **closing** pushes (5.5; with thickness the push is measured from this same body, and the body is + the leaf, 5.8 and 5.5, #50). So the GM can thicken a wall through a crowd and nobody teleports. +- **Joints: overlap, never a mitre [FIXED (owner-delegated), #45].** Two walls meeting at a corner + keep their own rectangles; the bodies overlap at the joint and the outside corner shows a small + notch. No mitre, no merged joint, no joint object, and no crack: the overlap is what closes it. A + cave is a chain of straight walls. #43 measured that joints need no thickness: zero-width corners + show no crack either. +- **Shape behind a seam [FIXED (owner-delegated), #45].** A wall's occupied area is produced by + **one** wall-shape function, and no other code reads `a`/`b` to build geometry; in v1 that + function returns the 5.10 rectangle. Curved, freeform and image-traced walls are out of v1 (1) and + land by changing that function alone, so no sight, move, editor or wire code may assume "a wall is + a straight segment". +- **Editor and fields** [FIXED (owner-delegated), #45]. The GM editor gains the thickness control, + the position flip and a live preview (7.4); a new wall starts at the GM's last-used thickness (0 + in a fresh editor), which is editor session state, not a scene field and not on the wire. The wire + fields and their validation are 6.1; the record is 8. +- Oracles build the body rectangle from `a`, `b`, `thickness` and `position` with their own code, + never by calling `vision.nim` or the move rules, and use it for both the sight footprint and the + distance test (10.2, 10.3). +- Deferred: nothing about thickness. The columns, the payload shape and the migration are settled in + 6.1, 8 and 4.4 (#49). What a door is with thickness is settled: the leaf is the wall's own body + (5.8) and the push is measured from that body, reducing to today exactly at zero thickness (5.5) + [FIXED, 2026-11-17, #50]. --- ## 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). +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); `marker` is the one M4-era message added by #49 (2026-11-17), so the current catalogue is 29 intents and 16 server messages, of which M3 has built 15 and M4's wall-model build adds `marker` plus the new wall fields (6.2 `proto` 2). Nothing outside it exists in M3. +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. This is the complete wire catalogue: 29 intents and +16 server messages. M3 built 15 server messages; M4's wall-model build adds `marker` and the new +wall fields (`proto` 2, 6.2). Nothing outside it exists. Conventions: -- **Naming.** Client -> server `t` is `.`: 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:}` 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; `marker` and the new wall fields plus `proto` 2 are M4's (6.2, #49); none of these 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`). Slice 4 (#19) builds `wall.add`, `wall.update`, `wall.remove` and `door.set`, plus the `walls` snapshot a GM gets on connect; everything else still answers `unknown-type`. Slice 10 (#25) builds `scene.set`: with it every one of the 29 catalogue intents has a handler, and `unknown-type` remains only the answer for a `t` outside the catalogue. +- **Naming.** Client -> server `t` is `.`: 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:}` 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; `marker` and the new wall fields plus `proto` 2 are M4's + (6.2, #49); none of these is built in M3. Wire changes for M4/M5/M6 are limited to what 6.5 marks. +- **Catalogue is the contract [FIXED (owner-delegated), #18].** Every intent in 6.1 has a handler. + Until a handler lands, its intent answers `unknown-type` with no state, so a half-built server + never lies about having applied anything; today `unknown-type` is only the answer for a `t` + outside the catalogue (6.5). ### 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`. +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. +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)** @@ -526,78 +1410,235 @@ Every row also carries `reqId` (omitted below). Codes are those of 6.5; `not-all | `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, is a secret door, or is a locked door and `open:true`) | `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. A player sender is `not-allowed` at the role step for every door (5.8, #46) | -Validation for `wall.*`: `a != b`, both in bounds; `thickness` a finite number `0 <= t <= 256`; `position` one of `center|left|right`; `height` a finite number `> 0` and `<= 100` or `null`; each switch a boolean and `sight_dir` one of `both|left|right`, with a non-`both` `sight_dir` requiring `blocks_sight:true` (#47); `open`/`secret`/`locked` only with `door`; a secret door closed, two-way and opaque (`blocks_sight` and `blocks_movement` both true); `open:true` with `secret` or `locked` is `invalid` (#46, 5.8); `label` an optional 6.5 text string of 1..64 code points, or `null`; `preset` is `wall|door|window|one_way` and never with a raw switch in the same payload (5.8, #48). **One expand-and-validate path [FIXED (owner-delegated), 2026-11-17, #49]:** `wall.add`, `wall.update` and the M6 UVTT importer build the same candidate (geometry + expanded switches + label) and run the same validation function; a preset is expanded before validation and sets only switches, never `thickness`, `position` or `height` (#50). +Validation for `wall.*`: `a != b`, both in bounds; `thickness` a finite number `0 <= t <= 256`; +`position` one of `center|left|right`; `height` a finite number `> 0` and `<= 100` or `null`; each +switch a boolean and `sight_dir` one of `both|left|right`, with a non-`both` `sight_dir` requiring +`blocks_sight:true` (#47); `open`/`secret`/`locked` only with `door`; a secret door closed, two-way +and opaque (`blocks_sight` and `blocks_movement` both true); `open:true` with `secret` or `locked` +is `invalid` (#46, 5.8); `label` an optional 6.5 text string of 1..64 code points, or `null`; +`preset` is `wall|door|window|one_way` and never with a raw switch in the same payload (5.8, #48). +**One expand-and-validate path [FIXED (owner-delegated), 2026-11-17, #49]:** `wall.add`, +`wall.update` and the M6 UVTT importer build the same candidate (geometry + expanded switches + +label) and run the same validation function; a preset is expanded before validation and sets only +switches, never `thickness`, `position` or `height` (#50). -**Wall payload rules [FIXED (owner-delegated, 2026-11-15, #19); amended by the 5.8 wall model, #42]** (6.1 was silent on these; slice 4 builds them): -- `scene` is an integer scene id. v1 has exactly one scene (Q3), seeded by migration step 3 with id `1` (4.4); any other value is `not-found`, a non-integer is `invalid`. -- `a`/`b` are `[x,y]` arrays of exactly two finite JSON numbers (integers accepted); `a == b` and any endpoint outside `0 <= x <= w, 0 <= y <= h` are `invalid`. The border itself is in bounds. -- A wall's behaviour is the 5.8 switches, defaulted as the `wall` preset (`blocks_sight:true`, `blocks_movement:true`, `sight_dir:"both"`, `player_marker:false`, `door:false`, `open:false`, `secret:false`, `locked:false`). A payload gives either `preset` (the server expands it from the 5.8 table; `window` also sets `player_marker:true`) or raw switches, never both; a switch that is not a boolean or a `sight_dir` outside the three values is `invalid`. A raw switch payload defaults `player_marker` to `false`: the marker is on by default only through the `window` preset (5.8, #48). -- `open`, `secret` and `locked` without `door:true` are `invalid`; a secret door with `open:true`, with `sight_dir != "both"`, or with either block switch off is `invalid` (5.8: it must look exactly like a solid wall), and so is a locked door with `open:true` (#46, 5.8: unlock first). A `sight_dir` other than `"both"` with `blocks_sight:false` is `invalid` (a direction with nothing to block, #47). A stored non-door always has `open=false`, `secret=false`, `locked=false`, so clearing `door` through `wall.update` closes and de-secrets it. -- `label` is optional: absent or `null` clears it; otherwise a string of 1..64 code points, trimmed, no control characters (the 6.5 text rule). It is GM-only, has no behaviour and never appears in a player frame (5.8, #48). -- `player_marker` is a boolean switch (default `false`; the `window` preset sets `true`). It only decides whether a player gets a marker once they have seen part of the wall **and the wall derives `window`** (5.8: a solid wall with the switch on sends nothing); it changes no sight, movement or status rule. -- `flags` is a JSON object or absent (absent = `{}`); anything else is `invalid`. It is stored verbatim and never interpreted — the switches are fields, not flags (5.8). -- `wall.update` patches `a`, `b`, `thickness`, `position`, `height`, the switches (or one `preset`), `label` and `flags`; at least one of them is required, otherwise `invalid`. A patch is absolute, not additive: everything named is set to the value given (`null` clears `height` and `label`), and a `preset` replaces the whole switch set, so `preset:"door"` on a window turns it into a closed opaque door, and `preset:"window"` sets `player_marker:true` as part of the expansion. `open` is not a patch field: it belongs to `door.set`, and an `open` field in `wall.update` is an unknown field (ignored, 6.2; a `preset` carrying `open:true` is `invalid` as above). Fields are checked before the target lookup (6.5 steps 7 then 8), so a fieldless `wall.update` is `invalid` whatever the id. -- `id` is an integer; lookup failures are `not-found` (a GM's missing target, 6.5 step 8). `door.set` on a row whose `door` is false is `invalid`, and so is `open:true` on a secret door (5.8) or on a locked door (#46, 5.8). -- `thickness`, `position` and `height` are the wall's geometry fields and are typed, validated server-side, and never live in `flags` (5.10, 5.7). `thickness` is a finite number in px `0 <= t <= 256` (absent/default `0`, the drawn line); `position` is one of `center|left|right` (absent/default `center`); `height` is metres, a finite number `> 0` and `<= 100`, and **absent or `null` means full height** (5.7, #49). A preset never implies or resets them: `wall.add {preset:"door", thickness:20, position:"left"}` is legal, and a `wall.update {preset:"window"}` on a thick wall keeps the thick body. `height:null` in `wall.update` restores full height; `height` absent leaves it alone. -- **Preset or raw switches, and what a patch replaces [FIXED (owner-delegated), 2026-11-17, #49].** A payload carries `preset` or raw switches, never both (`player_marker` counts as a raw switch). `preset` replaces the **whole** switch set with its expansion, exactly as before. A raw-switch payload on `wall.add` leaves every switch it omits at the `wall` preset default; on `wall.update` it patches **only** the switches present, so `{player_marker:false}` is how a GM turns off the `window` preset's marker without restating the switches, and `{door:true, open:true}` on a fixed window turns it into a closed opening window. -- `kind` is **output only** on the `wall`/`walls` frames: the shape label derived from the switches (`wall`, `door`, `window`, `one_way`, else `custom`; `secret`/`locked` never change it, 5.8 #48). It is not accepted as an input field; an input `kind` is an unknown field (ignored, 6.2). **No sender may rely on that** — an old client's `{"kind":"door"}` would silently create a solid wall — which is why the field set changes with `proto` 2 (6.2). Storage, field names, defaults and the existing-row migration are 8 and 4.4; the rule here is that the switches are the authority and the label is derived. -- **Storage [FIXED (owner-delegated), 2026-11-17, #49].** Every field above is a typed column on `wall` with CHECK constraints (8, 4.4 step 8); `flags` stays a JSON object for GM data the server never interprets. The wire names and the column names are identical, and booleans are `0`/`1` in storage. -- **The M6 UVTT importer uses this same path [FIXED (owner-delegated), 2026-11-17, #49].** UVTT expresses only sight lines and `closed` (#40), so an imported wall is `thickness:0, position:"center", blocks_sight:true, blocks_movement:true, sight_dir:"both", player_marker:false, height:null, label:null`; a portal imports as `door:true` with `open = not closed`, everything else as `door:false, open:false`; `secret`/`locked`/`flags` stay off/`{}` and no marker is written. No ticket: the M6 import CLI carries it. -- `wall.add` assigns the id from the scene's `next_wall_id`, which is monotonic and never reused (#3, 8; removal does not touch it, and a restart reloads it from the DB). -- Every write is one transaction with `synchronous=FULL` around it (Q12: GM authoring is the data that is expensive to lose) and `NORMAL` again afterwards; the in-memory scene is updated only after COMMIT, so a failed write leaves memory and DB identical. +**Wall payload rules [FIXED (owner-delegated, 2026-11-15, #19; amended by the 5.8 wall model, +#42]:** +- `scene` is an integer scene id. v1 has exactly one scene (Q3), seeded by migration step 3 with id + `1` (4.4); any other value is `not-found`, a non-integer is `invalid`. +- `a`/`b` are `[x,y]` arrays of exactly two finite JSON numbers (integers accepted); `a == b` and + any endpoint outside `0 <= x <= w, 0 <= y <= h` are `invalid`. The border itself is in bounds. +- A wall's behaviour is the 5.8 switches, defaulted as the `wall` preset (`blocks_sight:true`, + `blocks_movement:true`, `sight_dir:"both"`, `player_marker:false`, `door:false`, `open:false`, + `secret:false`, `locked:false`). A payload gives either `preset` (the server expands it from the + 5.8 table; `window` also sets `player_marker:true`) or raw switches, never both; a switch that is + not a boolean or a `sight_dir` outside the three values is `invalid`. A raw switch payload + defaults `player_marker` to `false`: the marker is on by default only through the `window` preset + (5.8, #48). +- `open`, `secret` and `locked` without `door:true` are `invalid`; a secret door with `open:true`, + with `sight_dir != "both"`, or with either block switch off is `invalid` (5.8: it must look + exactly like a solid wall), and so is a locked door with `open:true` (#46, 5.8: unlock first). A + `sight_dir` other than `"both"` with `blocks_sight:false` is `invalid` (a direction with nothing + to block, #47). A stored non-door always has `open=false`, `secret=false`, `locked=false`, so + clearing `door` through `wall.update` closes and de-secrets it. +- `label` is optional: absent or `null` clears it; otherwise a string of 1..64 code points, trimmed, + no control characters (the 6.5 text rule). It is GM-only, has no behaviour and never appears in a + player frame (5.8, #48). +- `player_marker` is a boolean switch (default `false`; the `window` preset sets `true`). It changes + no sight, movement or status rule; a marker is emitted only for a wall that is both + `player_marker:true` and derives `window` (5.8). +- `flags` is a JSON object or absent (absent = `{}`); anything else is `invalid`. It is stored + verbatim and never interpreted — the switches are fields, not flags (5.8). +- `wall.update` patches `a`, `b`, `thickness`, `position`, `height`, the switches (or one `preset`), + `label` and `flags`; at least one of them is required, otherwise `invalid`. A patch is absolute, + not additive: everything named is set to the value given (`null` clears `height` and `label`), and + a `preset` replaces the whole switch set, so `preset:"door"` on a window turns it into a closed + opaque door, and `preset:"window"` sets `player_marker:true` as part of the expansion. `open` is + not a patch field: it belongs to `door.set`, and an `open` field in `wall.update` is an unknown + field (ignored, 6.2; a `preset` carrying `open:true` is `invalid` as above). Fields are checked + before the target lookup (6.5 steps 7 then 8), so a fieldless `wall.update` is `invalid` whatever + the id. +- `id` is an integer; lookup failures are `not-found` (a GM's missing target, 6.5 step 8). + `door.set` on a row whose `door` is false is `invalid`, and so is `open:true` on a secret door + (5.8) or on a locked door (#46, 5.8). +- `thickness`, `position` and `height` are the wall's geometry fields and are typed, validated + server-side, and never live in `flags` (5.10, 5.7). `thickness` is a finite number in px `0 <= t + <= 256` (absent/default `0`, the drawn line); `position` is one of `center|left|right` + (absent/default `center`); `height` is metres, a finite number `> 0` and `<= 100`, and **absent or + `null` means full height** (5.7, #49). A preset never implies or resets them: `wall.add + {preset:"door", thickness:20, position:"left"}` is legal, and a `wall.update {preset:"window"}` on + a thick wall keeps the thick body. `height:null` in `wall.update` restores full height; `height` + absent leaves it alone. +- **Preset or raw switches, and what a patch replaces [FIXED (owner-delegated), 2026-11-17, #49].** + A payload carries `preset` or raw switches, never both (`player_marker` counts as a raw switch). + `preset` replaces the whole switch set with its expansion. A raw-switch `wall.add` leaves omitted + switches at the `wall` preset default; a raw-switch `wall.update` patches only the switches + present (so `{player_marker:false}` turns off a window's marker, and `{door:true, open:true}` + turns a fixed window into a closed opening window). +- `kind` is **output only** on the `wall`/`walls` frames: the shape label derived from the switches + (5.8), never an input (an input `kind` is an unknown field and is ignored). A `proto` 1 client's + `{"kind":"door"}` would silently create a solid wall, which is why the field set changes with + `proto` 2 (6.2). +- **Storage [FIXED (owner-delegated), 2026-11-17, #49].** Every field above is a typed column on + `wall` with CHECK constraints (8, 4.4 step 8, ADR-0010); the wire names and the column names are + identical, and booleans are `0`/`1` in storage. +- **The M6 UVTT importer uses this same path [FIXED (owner-delegated), 2026-11-17, #49].** UVTT + expresses only sight lines and `closed` (#40), so an imported wall is `thickness:0, + position:"center", blocks_sight:true, blocks_movement:true, sight_dir:"both", player_marker:false, + height:null, label:null`; a portal imports as `door:true` with `open = not closed`, everything + else as `door:false, open:false`; `secret`/`locked`/`flags` stay off/`{}` and no marker is + written. No ticket: the M6 import CLI carries it. +- `wall.add` assigns the id from the scene's `next_wall_id`, which is monotonic and never reused + (#3, 8; removal does not touch it, and a restart reloads it from the DB). +- Every write is one transaction with `synchronous=FULL` around it (Q12: GM authoring is the data + that is expensive to lose) and `NORMAL` again afterwards; the in-memory scene is updated only + after COMMIT, so a failed write leaves memory and DB identical. -**Scene payload rules [FIXED (owner-delegated), 2026-11-15, #25)]** (6.1 was silent on these; slice 10 builds them): -- `scene` is an integer scene id; any value but the one v1 scene (id `1`) is `not-found`, a non-integer is `invalid` (the same split as `wall.*`). -- At least one of `name`, `grid_size`, `vision_radius_default`, `token_radius_default`, `extra` must be present. A declared field must have its own shape; a JSON `null` is a wrong type, not "absent": +**Scene payload rules [FIXED (owner-delegated), 2026-11-15, #25)]:** +- `scene` is an integer scene id; any value but the one v1 scene (id `1`) is `not-found`, a + non-integer is `invalid` (the same split as `wall.*`). +- At least one of `name`, `grid_size`, `vision_radius_default`, `token_radius_default`, `extra` must + be present. A declared field must have its own shape; a JSON `null` is a wrong type, not "absent": - `name`: the 6.5 text rule, 1..64 code points, already trimmed, no control characters. - `grid_size`: a finite number `>= 0` (0 = no grid; `classify` rejects NaN/Inf). - `vision_radius_default`, `token_radius_default`: a finite number `> 0`, no upper cap (#4). - `extra`: a JSON object, stored verbatim and never interpreted; the GM sees it in `hello`. -- `w`, `h`, `tile_size`, `cell` and `art_version` are **not** patch fields (import is the M6 CLI): they are unknown fields and ignored (6.2), so a patch carrying only one of them has no field at all and is `invalid`. -- Persistence: one `FULL` transaction writes the scene row and every token whose effective radius the new `token_radius_default` changed (its position and `walls`-sourced statuses too), then memory follows COMMIT. A token with its own radius is untouched (#4); a default-radius token follows the 5.6 grow/shrink rule: grow pushes or squeezes, shrink clears the `walls` entries only when the overlap ends. -- Effects: the ack, then `hello` plus the full 6.3 resync on **every** connection (unnamed players included: they get `hello` only). A `hello` also resets the server-side per-connection diff base, so a resync after it re-sends state the client just reset instead of treating it as unchanged. No `scene.activate` (Q3). +- `w`, `h`, `tile_size`, `cell` and `art_version` are **not** patch fields (import is the M6 CLI): + they are unknown fields and ignored (6.2), so a patch carrying only one of them has no field at + all and is `invalid`. +- Persistence: one `FULL` transaction writes the scene row and every token whose effective radius + the new `token_radius_default` changed (its position and `walls`-sourced statuses too), then + memory follows COMMIT. A token with its own radius is untouched (#4); a default-radius token + follows the 5.6 grow/shrink rule: grow pushes or squeezes, shrink clears the `walls` entries only + when the overlap ends. +- Effects: the ack, then `hello` plus the full 6.3 resync on **every** connection (unnamed players + included: they get `hello` only). A `hello` also resets the server-side per-connection diff base, + so a resync after it re-sends state the client just reset instead of treating it as unchanged. No + `scene.activate` (Q3). -**Character and name payload rules [FIXED (owner-delegated), 2026-11-15, #23]** (6.1 was silent on these; slice 8 builds them, module `server/characters.nim`): -- `character.create` takes `descriptive_name`, `actual_name` (the 6.5 text rule, 1..64 code points), an optional `owner` (a player id, default the GM's own) and optional `props`; a missing name, an unknown prop bucket or a mistyped field is `invalid`, an owner player that does not exist is `not-found`. -- `character.update` patches `descriptive_name`/`actual_name` only, at least one of them; `props` is an unknown field there (6.2) and so cannot smuggle a bucket past `prop.*`. -- `character.remove` answers `in-use` while any token links the character (6.5). `character.reassign` takes an existing player id and **never** touches a token's controller (3.1, 8); it also keeps every reveal (8: reveals are not revoked by an owner change). -- **A link is a name handover** (#29): `token.update {id, character_id: }` with no names drops the token's own `descriptive_name`/`actual_name` as part of the link patch, because a linked token carries no names of its own. Supplying names alongside a link stays `invalid`, and unlinking still requires both names on the same patch. Without this a plain token could never be linked by update: validation requires a linked token to have empty names, while the patch kept the plain token's own. -- `name.reveal` / `name.reveal_all` carry `subject:"character"|"token"` and the subject id; a token that has a character is `invalid` (reveal through the character, 6.1), an unknown subject or player is `not-found`. A reveal writes one `(player, subject)` row; `reveal_all` writes the subject's `reveal_all` flag instead, so it covers players who join later and is idempotent. There is no un-reveal (8). -- `encountered.remove` takes `player` and a token id; a missing player and a missing entry are both `not-found`. -- **The name rule lives once** (`characters.knowsActual` + `visibleName`): a player is told a subject's actual name when the subject is a character they own, when `reveal_all` is set, or when the GM revealed it to them. The token frame, the character frame and every `encountered.name` call it; nothing else re-derives it. -- **`token` frames** gain `character_id` (string for a joined token, `null` for a plain one) **to the GM only**, plus `character_id` for a player who *owns* that character (6.1 leak note 2), and `cprops:{public:{…}}` — the character's `public` bucket for a player who sees a token of a character they do not own, `{}` for a plain token and for the owner, always present so its presence marks nothing (6.1 leak note 3). The GM frame of a linked token carries no `descriptive_name`/`actual_name`/`reveal_all`/`revealed`: those live on the character record. A plain token keeps all four. -- **A token's wire `name`** is `visibleName` of its subject: the character's names when linked, its own when plain. It is no longer always the descriptive name (that was slice 5's placeholder, 6.1 "Names"). -- **`encountered`** is per player and is recorded when a token enters that player's view (main.recordEncounters, before the ack, NORMAL durability like explored): one row per `(player, token)` holding the names that player knows *at that moment*, `grey` = the token is not in that player's view now (moved, removed, or `gm_only`) and never deletes it. **One rewrite path** (`characters.rewriteEncountered`) updates the SQLite row and the live in-memory entry together for `character.update`, a plain-token rename, a link change and an owner change, applying the 8 name rule per player, so the wire and a post-restart reload cannot disagree (#30). `name.reveal` rewrites exactly the revealed player's snapshot and `name.reveal_all` every player's (#27). On a diff the message carries only the entries that changed plus a `del` list (the only way an entry disappears is `encountered.remove`); on connect/resync it is `full:true`. -- **`roster`** is sent on connect (first, 6.3), after `player.setname`/`player.rename`, and after `key.create`/`key.replace`/`player.remove`: the full list every time, `connected` = that player has a live connection. Players receive named players only (6.1 leak note 4); the GM receives every player with `name:null` for an unused key. -- **`player.setname`** is a normalise-then-store intent (trim, then 6.5): `invalid` for a name that is empty or has a control character or exceeds 32 code points, `name-taken` regardless of case ("GM" included: it is an ordinary name in the `player` table), `not-allowed` for the GM, for a player that is already named, or for an unknown player. On success every connection of that player gets `hello` again with `me.name`, then the full resync, and everyone gets `roster`. -- **`player.rename`** (G) takes `id` + `name` and answers `invalid`, `not-found`, `name-taken`; the whole table is in 6.1. **`key.show`** (G) answers `{key}` with the stored plaintext secret (Q11) and refuses the GM's own key with `not-allowed` (CLI only, 3.2). +**Character and name payload rules [FIXED (owner-delegated), 2026-11-15, #23]** (module +`server/characters.nim`): +- `character.create` takes `descriptive_name`, `actual_name` (the 6.5 text rule, 1..64 code points), + an optional `owner` (a player id, default the GM's own) and optional `props`; a missing name, an + unknown prop bucket or a mistyped field is `invalid`, an owner player that does not exist is + `not-found`. +- `character.update` patches `descriptive_name`/`actual_name` only, at least one of them; `props` is + an unknown field there (6.2) and so cannot smuggle a bucket past `prop.*`. +- `character.remove` answers `in-use` while any token links the character (6.5). + `character.reassign` takes an existing player id and **never** touches a token's controller (3.1, + 8); it also keeps every reveal (8: reveals are not revoked by an owner change). +- **A link is a name handover** (#29): `token.update {id, character_id: }` with no names drops + the token's own `descriptive_name`/`actual_name` as part of the link patch, because a linked token + carries no names of its own. Supplying names alongside a link stays `invalid`, and unlinking still + requires both names on the same patch. Without this a plain token could never be linked by update: + validation requires a linked token to have empty names, while the patch kept the plain token's + own. +- `name.reveal` / `name.reveal_all` carry `subject:"character"|"token"` and the subject id; a token + that has a character is `invalid` (reveal through the character, 6.1), an unknown subject or + player is `not-found`. A reveal writes one `(player, subject)` row; `reveal_all` writes the + subject's `reveal_all` flag instead, so it covers players who join later and is idempotent. There + is no un-reveal (8). +- `encountered.remove` takes `player` and a token id; a missing player and a missing entry are both + `not-found`. +- **The name rule lives once** (`characters.knowsActual` + `visibleName`): a player is told a + subject's actual name when the subject is a character they own, when `reveal_all` is set, or when + the GM revealed it to them. The token frame, the character frame and every `encountered.name` call + it; nothing else re-derives it. +- **`token` frames** gain `character_id` (string for a joined token, `null` for a plain one) **to + the GM only**, plus `character_id` for a player who *owns* that character (6.1 leak note 2), and + `cprops:{public:{…}}` — the character's `public` bucket for a player who sees a token of a + character they do not own, `{}` for a plain token and for the owner, always present so its + presence marks nothing (6.1 leak note 3). The GM frame of a linked token carries no + `descriptive_name`/`actual_name`/`reveal_all`/`revealed`: those live on the character record. A + plain token keeps all four. +- **A token's wire `name`** is `visibleName` of its subject: the character's names when linked, its + own when plain. +- **`encountered`** is per player and is recorded when a token enters that player's view + (main.recordEncounters, before the ack, NORMAL durability like explored): one row per `(player, + token)` holding the names that player knows *at that moment*, `grey` = the token is not in that + player's view now (moved, removed, or `gm_only`) and never deletes it. **One rewrite path** + (`characters.rewriteEncountered`) updates the SQLite row and the live in-memory entry together for + `character.update`, a plain-token rename, a link change and an owner change, applying the 8 name + rule per player, so the wire and a post-restart reload cannot disagree (#30). `name.reveal` + rewrites exactly the revealed player's snapshot and `name.reveal_all` every player's (#27). On a + diff the message carries only the entries that changed plus a `del` list (the only way an entry + disappears is `encountered.remove`); on connect/resync it is `full:true`. +- **`roster`** is sent on connect (first, 6.3), after `player.setname`/`player.rename`, and after + `key.create`/`key.replace`/`player.remove`: the full list every time, `connected` = that player + has a live connection. Players receive named players only (6.1 leak note 4); the GM receives every + player with `name:null` for an unused key. +- **`player.setname`** is a normalise-then-store intent (trim, then 6.5): `invalid` for a name that + is empty or has a control character or exceeds 32 code points, `name-taken` regardless of case + ("GM" included: it is an ordinary name in the `player` table), `not-allowed` for the GM, for a + player that is already named, or for an unknown player. On success every connection of that player + gets `hello` again with `me.name`, then the full resync, and everyone gets `roster`. +- **`player.rename`** (G) takes `id` + `name` and answers `invalid`, `not-found`, `name-taken`; the + whole table is in 6.1. **`key.show`** (G) answers `{key}` with the stored plaintext secret (Q11) + and refuses the GM's own key with `not-allowed` (CLI only, 3.2). -**Token payload rules [FIXED (owner-delegated), #20 and #22]** (6.1 was silent on these; slices 5 and 7 build them): -- `token.create` requires `kind`, `pos`, `descriptive_name` and `actual_name` for a plain token, and accepts `radius` (px > 0; null or absent = the scene default) and `props` (the three buckets, validated below) from slice 7 on. `character_id` is a *known* field no slice can honour yet: it answers `invalid` (silently dropping a GM's field would lose data), and `token.update` does the same for it. The character link lands in slice 8. -- A token's effective `radius` is its own `radius` when set, else the scene's `token_radius_default` (5.6). Both the wire `radius` and the move rules use the effective value, so a resize changes the escape/capsule/push geometry immediately (`worldmap.ruleToken`). -- `token.update` does not take `radius` or `props`: `token.resize` and `prop.set`/`prop.unset` own them (6.1's field list), so both are unknown fields there and are ignored (6.2). +**Token payload rules [FIXED (owner-delegated), #20 and #22]:** +- `token.create` requires `kind`, `pos`, `descriptive_name` and `actual_name` for a plain token, and + accepts `radius` (px > 0; null or absent = the scene default) and `props` (the three buckets, + validated below) from slice 7 on. `character_id` is a *known* field no slice can honour yet: it + answers `invalid` (silently dropping a GM's field would lose data), and `token.update` does the + same for it. The character link lands in slice 8. +- A token's effective `radius` is its own `radius` when set, else the scene's `token_radius_default` + (5.6). Both the wire `radius` and the move rules use the effective value, so a resize changes the + escape/capsule/push geometry immediately (`worldmap.ruleToken`). +- `token.update` does not take `radius` or `props`: `token.resize` and `prop.set`/`prop.unset` own + them (6.1's field list), so both are unknown fields there and are ignored (6.2). -**Status payload rules [FIXED (owner-delegated, 2026-11-15, #22)]** (slice 7): -- A token holds a set of `(status, source)` entries: status `stuck`|`squeezed`, source `walls`|`GM` (5.5). Stored order is by status (`stuck` before `squeezed`) then source (`walls` before `GM`), so the frames are deterministic and the diff never churns. -- `statuses:[{status, source}]` to the GM; `statuses:[{status}]` to everyone else, controller included (6.1 leak note 6). `status.set {id, status}` adds `(status, GM)`; adding an existing entry is `ok` and changes nothing. `status.clear {id, status, source}` removes exactly that entry: a missing token **or a missing entry** is `not-found` (6.1). After clearing the `walls` source the player escape rule of 5.5 applies unchanged, so no extra intent is needed. -- `source` is a stored wire word, not an enum index: `walls` and `GM` verbatim (`GM` is capitalised in the catalogue, so the check is exact). +**Status payload rules [FIXED (owner-delegated, 2026-11-15, #22)]:** +- A token holds a set of `(status, source)` entries: status `stuck`|`squeezed`, source `walls`|`GM` + (5.5). Stored order is by status (`stuck` before `squeezed`) then source (`walls` before `GM`), so + the frames are deterministic and the diff never churns. +- `statuses:[{status, source}]` to the GM; `statuses:[{status}]` to everyone else, controller + included (3.1; accepted effect, leak note 6). `status.set {id, status}` adds `(status, GM)`; + adding an existing + entry is `ok` and changes nothing. `status.clear {id, status, source}` removes exactly that entry: + a missing token **or a missing entry** is `not-found` (6.1). After clearing the `walls` source the + player escape rule of 5.5 applies unchanged, so no extra intent is needed. +- `source` is a stored wire word, not an enum index: `walls` and `GM` verbatim (`GM` is capitalised + in the catalogue, so the check is exact). -**Property payload rules [FIXED (owner-delegated, 2026-11-15, #22)]** (6.1 delegated the numbers to #11, #22 fixes them; module `server/props.nim`): -- Buckets `public`|`owner`|`gm`; caps **64 keys per bucket**, key **1..64 code points** trimmed with no control characters (the name rule of 6.5), value **serialized JSON <= 8 KB**; a `null` value is not a value. Caps are per bucket: a full `public` bucket still leaves `owner` and `gm` writable. -- `prop.set {target, id, bucket, key, value}` / `prop.unset {target, id, bucket, key}`; `target` is `token` or `character`; a bad target, bucket, key, value or cap is `invalid`, a missing token is `not-found`; `prop.unset` of an absent key is `ok`. `target:"character"` is `not-found` in M3 because characters do not exist before slice 8. -- The **property-schema registry** (8, 9) is `key -> PropSchema{kind, bucket}` plus a fallback rule, shipped **empty with a permissive fallback** (`pkAny`, any bucket) — **[amended 2026-11-15, #41]**: no longer empty, its first two keys are `height` and `eye_height` (`number`, `gm`, 5.7), which the core sight rules read; every other key still falls back to `pkAny`. DESIGN 8 said the server never interprets props in v1 (narrowed by #41: only the registered keys the core sight rules use are interpreted), so an unregistered key is accepted in any bucket; a key the rules module registers is enforced (JSON kind, bucket), and a write that disagrees is `invalid`. **[FIXED, owner decision 2026-11-15, #22]** (owner-confirmed as specified): keep the permissive fallback in v1; strict mode (every key must be registered) comes with the FFF seam, post-v1. Flipping the fallback to strict is a one-line change when FFF lands. -- Egress: the `public` bucket to everyone who sees the token, `owner` additionally to the controller, all three to the GM (6.1). The filter lives in the typed view: `PlayerTokenView` has no field for the `gm` bucket, so a later frame change cannot leak it. +**Property payload rules [FIXED (owner-delegated, 2026-11-15, #22)]** (6.1 delegated the numbers to +#11, #22 fixes them; module `server/props.nim`): +- Buckets `public`|`owner`|`gm`; caps **64 keys per bucket**, key **1..64 code points** trimmed with + no control characters (the name rule of 6.5), value **serialized JSON <= 8 KB**; a `null` value is + not a value. Caps are per bucket: a full `public` bucket still leaves `owner` and `gm` writable. +- `prop.set {target, id, bucket, key, value}` / `prop.unset {target, id, bucket, key}`; `target` is + `token` or `character`; a bad target, bucket, key, value or cap is `invalid`, a missing token is + `not-found`; `prop.unset` of an absent key is `ok`. `target:"character"` with an unknown id is + `not-found`. +- The **property-schema registry** (defined in 8) ships with `height` and `eye_height` registered + (`number`, `gm`, 5.7) and a permissive fallback (`pkAny`) for every other key, so an unregistered + key is accepted in any bucket. A registered key is enforced (JSON kind, bucket) and a disagreeing + write is `invalid`; strict mode comes with the FFF seam [FIXED, owner decision 2026-11-15, #22]. +- Egress: the `public` bucket to everyone who sees the token, `owner` additionally to the + controller, all three to the GM (6.1). The filter lives in the typed view: `PlayerTokenView` has + no field for the `gm` bucket, so a later frame change cannot leak it. -**Grow push and squeeze [FIXED (owner-delegated, 2026-11-15, #22)]** (5.6's tie-break, now decided): -- `token.resize {id, radius: number>0 | null}`; `radius` is required (absent is `invalid`), `null` returns the token to the scene default. The resize and its position/status outcome are one `FULL` transaction. -- Shrink never pushes and clears the `walls`-sourced entries only when the overlap actually ends. -- Grow: if the circle overlaps no blocking wall, nothing moves. Otherwise the server displaces the centre by a **deterministic greedy relaxation**: repeat at most 16 times "take the first blocking wall (scene order) the circle overlaps and move radially away from its closest point by the distance that ends at `r + 1e-6`", stopping as soon as the circle is clear and in bounds; a centre exactly on a wall takes the wall normal on the side of `prev` (no history: the left normal of `a->b`), and a second pass tries the flipped side once. A step whose own centre path crosses a blocking wall is refused, so the push never carries a token through a wall; if neither pass ends clear the token stays where it was and gets `squeezed` (source `walls`). The gate is one transaction: size, position and statuses. -- `token.resize` is GM-only (5.6: only the GM sets a size); the ack is `{}` with `not-found`/`invalid`. -- Names: both names are stored, the wire `name` of a `token` frame is always the descriptive name; the actual name has no egress path to a player until slice 8 provides the reveal rules. `token.update` on the names is a rename and reaches whoever may see the token. -- `controller` is a player id, or `null` = the GM. The GM's own player id is stored as GM-controlled, so `controller: null` is the only GM spelling on the wire. In a patch, `controller: null` and `vision_radius: null` are real patch fields (they mean "the GM" and "the scene default"); an absent field means "keep the stored value". -- `flags` carries the `vision` flag (DESIGN 8); `vision_radius` is the token's own range and the player step cap (5.5). -- `token` frame contents: a player gets `statuses: []` (no `source`), `props` with the `public` bucket and `owner` for the controller, `vision_radius` only for the controller (the step cap), and never `kind`, `controller`, `gm_only`, `flags`, `radius_own` or either raw name. The GM gets all of those plus `descriptive_name`/`actual_name` and `props` with all three buckets. `vision` polygons are integer px (6.4). `explored` on connect/resync is `{full:true, rle:[[cy, x0, len, ...], ...]}`; afterwards `{full:false, cells:[[cx,cy],...]}` with the cells that mutation added. -- A token that a recipient may no longer see is withdrawn with one `token_gone`; a recipient never gets `token_gone` for a token it was never shown. +**Grow push and squeeze [FIXED (owner-delegated, 2026-11-15, #22)].** The deterministic greedy +relaxation, its tie-break, the no-crossing rule and the `squeezed` outcome are specified once in +5.6. `token.resize {id, radius: number>0 | null}` is GM-only; `radius` is required (absent is +`invalid`), `null` returns the token to the scene default, and the size, position and status outcome +are one `FULL` transaction. The ack is `{}` with `not-found`/`invalid`. +- Names: a token's wire `name` is `visibleName` (8); the actual name reaches a player only through + the reveal rules. `token.update` on the names is a rename and reaches whoever may see the token. +- `controller` is a player id, or `null` = the GM. The GM's own player id is stored as + GM-controlled, so `controller: null` is the only GM spelling on the wire. In a patch, `controller: + null` and `vision_radius: null` are real patch fields (they mean "the GM" and "the scene + default"); an absent field means "keep the stored value". +- `flags` carries the `vision` flag (DESIGN 8); `vision_radius` is the token's own range and the + player step cap (5.5). +- `token` frame contents: a player gets `statuses: []` (no `source`), `props` with the `public` + bucket and `owner` for the controller, `vision_radius` only for the controller (the step cap), and + never `kind`, `controller`, `gm_only`, `flags`, `radius_own` or either raw name. The GM gets all + of those plus `descriptive_name`/`actual_name` and `props` with all three buckets. `vision` + polygons are integer px (6.4). `explored` on connect/resync is `{full:true, rle:[[cy, x0, len, + ...], ...]}`; afterwards `{full:false, cells:[[cx,cy],...]}` with the cells that mutation added. +- A token that a recipient may no longer see is withdrawn with one `token_gone`; a recipient never + gets `token_gone` for a token it was never shown. **Tokens, statuses, props (9)** @@ -629,7 +1670,9 @@ 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. +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 | |---|---|---| @@ -650,42 +1693,122 @@ All are built per recipient at egress (single egress rule, 2). "Sent" always mea | `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 | | `marker` | `full:bool, set:[{id, pos}], del:[id]`; `id` an opaque per-player 12-char string (never the wall id), `pos` integer px (the wall's drawn midpoint, rounded once); `full:true` replaces the whole set on connect/resync; a diff carries additions in `set` and retractions in `del`, never both for one id | player only, own markers only; **never the GM** (a player's markers are their own memory, like `explored`; 3.1, 5.8) | -Count: 16 server messages (15 M3 + `marker`, 6.2 `proto` 2). Reserved, not built: `event` (9). The player marker of 5.8 (#48/#49) is the only player-bound wall frame. +Count: 16 server messages (15 M3 + `marker`, 6.2 `proto` 2). Reserved, not built: `event` (9). The +player marker of 5.8 (#48/#49) is the only player-bound wall frame. -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. A `walls`-sourced status still tells a viewer that some blocking wall touches the token; **CLOSED as accepted [FIXED (owner decision), 2026-11-17, `docs/ANALYSIS-review.md` D4]**: a refused move already reveals the same fact, so this is a documented, accepted effect, not a leak to fix. (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. +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. A `walls`-sourced status still tells a viewer that some blocking wall touches the +token; **CLOSED as accepted [FIXED (owner decision), 2026-11-17, `docs/ANALYSIS-review.md` D4]**: a +refused move already reveals the same fact, so this is a documented, accepted effect, not a leak to +fix. (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. `proto = 1` is M3 as shipped. **`proto = 2` is the wall-model build [FIXED (owner decision), 2026-11-17, #49]**: `wall.add`/`wall.update` take `thickness`, `position`, `height`, `label` and the typed switches/`preset` instead of `kind`, `walls`/`wall` carry `height`, and the `marker` message exists. This is breaking because an old client sends `{"kind":"door"}` and the server, which ignores unknown fields, would silently create a solid wall; nothing else in the catalogue changes. 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`). +- `proto` is an integer compiled into both client and server. `proto = 1` is M3 as shipped. **`proto + = 2` is the wall-model build [FIXED (owner decision), 2026-11-17, #49]**: `wall.add`/`wall.update` + take `thickness`, `position`, `height`, `label` and the typed switches/`preset` instead of `kind`, + `walls`/`wall` carry `height`, and the `marker` message exists. This is breaking because an old + client sends `{"kind":"door"}` and the server, which ignores unknown fields, would silently create + a solid wall; nothing else in the catalogue changes. 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. -- **Proto history.** `1` (M3, 2026-11-15): 29 intents, 15 server messages, `wall` records as `kind` + `open` + `flags`. `2` (#49, 2026-11-17): the wall record's typed fields (`thickness`, `position`, `height`, `label`, `player_marker`, the eight switches), `kind` output-only, and the player `marker` message; the same build ships migration step 8, so a `proto` 1 client and a migrated DB cannot be paired by accident. +- **Proto history.** `1` (M3, 2026-11-15): 29 intents, 15 server messages, `wall` records as `kind` + + `open` + `flags`. `2` (#49, 2026-11-17): the wall record's typed fields (`thickness`, + `position`, `height`, `label`, `player_marker`, the eight switches), `kind` output-only, and the + player `marker` message; the same build ships migration step 8, so a `proto` 1 client and a + migrated DB cannot be paired by accident. ### 6.3 Reconnect and resync -- Reconnect = full resync. After `hello` the server sends, in this order: `roster`; GM: `walls`, `character` for all, `encountered` per player (full), then `token` for all; player: `character` for owned, `encountered` (full), `vision`, `explored` (full), `marker` (full), then `token` for all visible and controlled. **`marker` sits after `explored` because it is the same kind of state [FIXED (owner-delegated), 2026-11-17, #49]:** it is that player's persisted memory, restored at startup with the explored chunks (`marker_seen`, 4.4, 8), and the client draws it over the fog the `explored` frame has just rebuilt. The GM sequence does not change: no `marker` frame is ever sent to the GM (3.1, 6.1). Slice 4 sends the `walls` part: one frame to every GM connection immediately after `hello` (players never get one). Slice 5 sends the token half of the sequence: the GM's `token` for every token, and for a named player `vision`, `explored` (full) then `token` for every token it may see or control. Slice 6 built the explored restore, and slice 8 (#23) completes the sequence: `roster`, `character` and `encountered` are sent in the order above, and a sighting is recorded before the list is built, so a token that walked into an offline player's sight is in their `encountered` list on the next connect. 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). +- Reconnect = full resync. After `hello` the server sends, in this order: `roster`; GM: `walls`, + `character` for all, `encountered` per player (full), then `token` for all; player: `character` + for owned, `encountered` (full), `vision`, `explored` (full), `marker` (full), then `token` for + all visible and controlled. **`marker` sits after `explored` because it is the same kind of state + [FIXED (owner-delegated), 2026-11-17, #49]:** it is that player's persisted memory, restored at + startup with the explored chunks (`marker_seen`, 4.4, 8), and the client draws it over the fog the + `explored` frame has just rebuilt. The GM sequence does not change: no `marker` frame is ever sent + to the GM (3.1, 6.1). The sequence is built in the order above: `roster`, then the GM's + `walls`/`character`/`encountered`/`token`, or the player's owned `character`, `encountered`, + `vision`, `explored`, `marker`, then `token` for every token it may see or control. A sighting is + recorded before the list is built, so a token that walked into an offline player's sight is in + their `encountered` list on the next connect. 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)]. The stored diff base is the frame **before** the per-connection `n` is stamped: `protocol.withN` deep-copies, so stamping cannot make the next comparison see a different frame and re-send unchanged state (this was a live bug until slice 8; the leak checker now sees a genuinely sparse stream). -- 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). +- 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)]. The stored diff + base is the frame **before** the per-connection `n` is stamped: `protocol.withN` deep-copies, so + stamping cannot make the next comparison see a different frame and re-send unchanged state (this + was a live bug until slice 8; the leak checker now sees a genuinely sparse stream). +- 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. +**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). +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`. `door.set` is included, whatever the door's settings: one code for every door, open, closed, locked or secret, so the reply carries no door oracle (5.8, #46). +6. Role: a G-only intent from a player -> `not-allowed`. `door.set` is included, whatever the door's + settings: one code for every door, open, closed, locked or secret, so the reply carries no door + oracle (5.8, #46). 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`. +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).** @@ -702,9 +1825,15 @@ Leak notes (R5 review, #11): (1) `kind` is GM-only because a value like `npc` wo | `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. Deviation [FIXED (owner-delegated), #23]: Nim 2.2.12's stdlib has no Unicode normalisation (it lives in a package the pinned dependency set does not include) and adding one is out of slice scope, so a player name is trimmed and compared case-insensitively but stored as typed; two visually identical names written with precomposed vs combining accents would be different names. Nothing else changes. Character and plain-token names: 1 to 64 code points, same rules. All are rendered with `textContent` (T13). +Player name text: trimmed, NFC, 1 to 32 code points, no control characters. Deviation [FIXED +(owner-delegated), #23]: Nim 2.2.12's stdlib has no Unicode normalisation (it lives in a package the +pinned dependency set does not include) and adding one is out of slice scope, so a player name is +trimmed and compared case-insensitively but stored as typed; two visually identical names written +with precomposed vs combining accents would be different names. Nothing else changes. 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. +**`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: @@ -721,17 +1850,42 @@ Player name text: trimmed, NFC, 1 to 32 code points, no control characters. Devi | 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. +**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". +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). +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=; 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)]. +- `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=; 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//v/_.png`: 3.3 (`200` with `X-Accel-Redirect`, `403` unexplored, `404` malformed/out of range). Slice 9 (#24) pins the full status split in 3.3: `404` also for another scene or a stale art version, `403` also for a missing or unknown session (one response with "unexplored"), and `Cache-Control: private`. -- `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). +- `GET /tiles//v/_.png`: 3.3 (`200` with `X-Accel-Redirect`, `403` + unexplored, `404` malformed/out of range). Slice 9 (#24) pins the full status split in 3.3: `404` + also for another scene or a stale art version, `403` also for a missing or unknown session (one + response with "unexplored"), and `Cache-Control: private`. +- `GET /healthz`: 200 `{"status":"ok"}` [FIXED (owner-delegated, 2026-11-14, #16)]; M5 makes it + report whether the global lock can be acquired within a bound (11.3). --- @@ -739,96 +1893,286 @@ WS close reasons are the static strings in bold above. Close codes 4001-4003 are ### 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]. +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]. +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. +- 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. +- **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. +- **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. +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]. -- **Minimum zoom [FIXED (owner decision), 2026-11-17, `docs/ANALYSIS-review.md` D3]:** player zoom-out clamps at 0.5, which bounds the visible tile requests (about 1.3k at 0.5; about 5k at 0.25). A per-player explored-masked overview image is a possible later feature, not v1. -- Wall editor (GM) [FIXED, Q6, extended by 5.8, 5.10, #47, #48]: click-click segments, snap to grid/endpoints optional, delete, undo of last edit [PROPOSED]; submits `wall.*` intents; server is the validator. A preset row of **four** buttons (`wall` (default), `door`, `window`, `one-way`) sets the switches for a one-drag default, so a window is authoring `wall | window | wall`; `secret` and `locked` are **checkboxes on any door**, so a secret door is the door preset with `secret` ticked (no separate preset), and an opening window can be locked. A **fixed window** is the window preset with `door` unticked. A **`player_marker` checkbox** ("players see a marker", on by default for a window, off otherwise) and a free-text **`label`** field (GM-only, at most 64 characters) sit beside the preset row; neither changes vision or movement. An **advanced** toggle exposes the raw switches (`blocks_sight`, `blocks_movement`, `sight_dir`, `player_marker`, `door`, `open`, `secret`, `locked`) for a custom wall. A thickness control and a **position flip** (`center|left|right`) sit beside them, the flip previewing the body live and never moving `a`/`b`; a new wall starts at the GM's last-used thickness (0 in a fresh editor). A **one-way wall is drawn as an arrow at the wall's middle** pointing the way the view goes — from the seeing side toward the watched side — with a **direction flip** that swaps `sight_dir` `left`/`right` and never moves `a`/`b`, the same flip control as the position flip. Arrow, flip, marker and label are GM-only like every wall fact and never on a player wire, except the marker itself (3.1, 5.8); the editor draws `kind` (the derived label) only, and no preset is a stored kind. The height control is not M4's: height and thickness controls are built after the M4 playtest (build order, 1; 5.7, 5.10). A locked door's open action is the `invalid` case of 5.8, so the editor shows the hint "locked: unlock first" and offers the one click that clears `locked`; no door action is offered to players (#46). -- 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). -- Who-sees-it view (GM only) [FIXED (owner decision), 2026-11-15, #44]: for each token, which player(s)/characters see it and its visible fraction (5.9, 100 % when unobstructed). GM-only and never on a player wire; the panel's shape belongs to the M4 editor/fog work. +- Mouse: wheel zoom, drag pan, drag token. Touch: one finger drag/pan, two-finger pinch/pan + [MEASURED works on Note 10]. +- **Minimum zoom [FIXED (owner decision), 2026-11-17, `docs/ANALYSIS-review.md` D3]:** player + zoom-out clamps at 0.5, which bounds the visible tile requests (about 1.3k at 0.5; about 5k at + 0.25). A per-player explored-masked overview image is a possible later feature, not v1. +- Wall editor (GM) [FIXED, Q6, extended by 5.8, 5.10, #47, #48]: click-click segments, snap to + grid/endpoints optional, delete, undo of last edit [PROPOSED]; submits `wall.*` intents; server is + the validator. A preset row of **four** buttons (`wall` (default), `door`, `window`, `one-way`) + sets the switches for a one-drag default, so a window is authoring `wall | window | wall`; + `secret` and `locked` are **checkboxes on any door**, so a secret door is the door preset with + `secret` ticked (no separate preset), and an opening window can be locked. A **fixed window** is + the window preset with `door` unticked. A **`player_marker` checkbox** ("players see a marker", on + by default for a window, off otherwise) and a free-text **`label`** field (GM-only, at most 64 + characters) sit beside the preset row; neither changes vision or movement. An **advanced** toggle + exposes the raw switches (`blocks_sight`, `blocks_movement`, `sight_dir`, `player_marker`, `door`, + `open`, `secret`, `locked`) for a custom wall. A thickness control and a **position flip** + (`center|left|right`) sit beside them, the flip previewing the body live and never moving `a`/`b`; + a new wall starts at the GM's last-used thickness (0 in a fresh editor). A **one-way wall is drawn + as an arrow at the wall's middle** pointing the way the view goes — from the seeing side toward + the watched side — with a **direction flip** that swaps `sight_dir` `left`/`right` and never moves + `a`/`b`, the same flip control as the position flip. Arrow, flip, marker and label are GM-only + like every wall fact and never on a player wire, except the marker itself (3.1, 5.8); the editor + draws `kind` (the derived label) only, and no preset is a stored kind. The height control is not + M4's: height and thickness controls are built after the M4 playtest (build order, 1; 5.7, 5.10). A + locked door's open action is the `invalid` case of 5.8, so the editor shows the hint "locked: + unlock first" and offers the one click that clears `locked`; no door action is offered to players + (#46). +- 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). +- Who-sees-it view (GM only) [FIXED (owner decision), 2026-11-15, #44]: for each token, which + player(s)/characters see it and its visible fraction (5.9, 100 % when unobstructed). GM-only and + never on a player wire; the panel's shape belongs to the M4 editor/fog work. ### 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). +- 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]. +- 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). The column lives on the `scene` row created by migration step 3 (4.4), and the wire rules for the four wall intents are in 6.1. 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). +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). The column lives on the `scene` +row created by migration step 3 (4.4), and the wire rules for the four wall intents are in 6.1. 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 [FIXED, owner decision 2026-11-15, #42; fields, storage and migration 2026-11-17, #49]**: `scene, id` (per-scene, see above), `a:[x,y], b:[x,y]`, the geometry `thickness` (px, 0..256, default 0 = the drawn line), `position` (`center|left|right`, default `center`; 5.10) and `height` (metres, optional, `> 0` and `<= 100`, absent = full height; 5.7), the switches `blocks_sight`, `blocks_movement`, `sight_dir` (`both|left|right`), `player_marker` (bool, default false, 5.8 #48), the door settings `door, open, secret, locked`, the GM-only free-text `label` (optional, 1..64 code points, 5.8 #48) and the free `flags`. Behaviour comes from the switches (5.8); `blocks = blocks_movement and not (door and open)`; a window (`blocks_sight:false`) is absent from the sight input. `kind` is only a derived output label (`wall`, `door`, `window`, `one_way`, else `custom`; `secret`/`locked` are flags, not kinds, #48) and is never stored: the legacy `kind` column is dropped by migration step 8 (4.4). GM-only everywhere except the player marker: a player receives only an integer-px anchor and its own opaque marker id (3.1, 5.8, 6.1), and the per-player marker set is state like the explored grid (persisted per player in `marker_seen` below, retracted only by a GM change). - - **Storage: typed columns, not one JSON object [FIXED (owner-delegated), 2026-11-17, #49].** One column per field listed above, with CHECK constraints for the invariants the wire enforces (`open`/`secret`/`locked` require `door`; a secret door is closed, two-way and opaque; a `sight_dir` other than `both` requires `blocks_sight`), so the store cannot hold a switch set the server would refuse. `flags` stays a JSON object for GM data the server never interprets. *Why columns:* the precedent is columns for everything the server reads (`scene`, `entity.radius`, `vision_radius`, `gm_only`) while `flags` and `props_*` exist for data it never reads; CHECKs can reject an impossible switch set, which a JSON blob cannot without triggers; `loadScene` reads a row straight into the typed `WallRec`, with no second parse-and-validate path at startup beside the wire's own; and the switch set is closed in v1, so a new axis is a schema step either way. 5.8's "one object" is about the domain and the wire; the columns are how that one object is stored. `height` and `label` are nullable and are written as SQL literals because db_connector cannot bind NULL (4.4). - - **Marker storage: `marker_seen` [FIXED (owner-delegated), 2026-11-17, #49].** `marker_seen(player_id INTEGER NOT NULL REFERENCES player(id) ON DELETE CASCADE, scene_id INTEGER NOT NULL, wall_id INTEGER NOT NULL, marker_id TEXT NOT NULL, PRIMARY KEY (player_id, scene_id, wall_id), UNIQUE (player_id, marker_id), FOREIGN KEY (scene_id, wall_id) REFERENCES wall(scene_id, id) ON DELETE CASCADE)`. One row per `(player, wall)` once seen; `marker_id` is the opaque per-player 12-character id on the wire. Cascades mirror explored/`name_reveal`: a removed player takes their markers, a removed scene takes them through its walls, and a removed wall retracts its marker for everyone (5.8's retraction rule; the composite FK is why a marker can never dangle). The other retraction causes (`player_marker` off, no longer a window, geometry moved) are a deliberate delete in the update path, not an FK. - - **Migration [FIXED (owner decision), 2026-11-17, #49].** Step 8 (4.4) rebuilds `wall` and maps every existing row to today's behaviour exactly: `thickness 0`, `position center`, `blocks_sight`/`blocks_movement` 1, `sight_dir both`, `player_marker` 0, `secret`/`locked` 0, `height` NULL, `label` NULL; `kind='door'` becomes `door=1` with the same `open`, `kind='wall'` becomes `door=0` with `open=0`. Every existing token and character gets `height: 1.8 m` in `props_gm` (5.7). The M6 UVTT importer's defaults are in 6.1. #45's "existing walls get `0`/`center`" and #41's "existing walls carry no height" are the same rows under this step. A door stores no leaf field of its own: its leaf is this same body (5.8, 5.5). +- **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 [FIXED, owner decision 2026-11-15, #42; fields, storage and migration 2026-11-17, #49]**: + `scene, id` (per-scene, see above), `a:[x,y], b:[x,y]`, the geometry `thickness` (px, 0..256, + default 0 = the drawn line), `position` (`center|left|right`, default `center`; 5.10) and `height` + (metres, optional, `> 0` and `<= 100`, absent = full height; 5.7), the switches `blocks_sight`, + `blocks_movement`, `sight_dir` (`both|left|right`), `player_marker` (bool, default false, 5.8 + #48), the door settings `door, open, secret, locked`, the GM-only free-text `label` (optional, + 1..64 code points, 5.8 #48) and the free `flags`. Behaviour comes from the switches (5.8); `blocks + = blocks_movement and not (door and open)`; a window (`blocks_sight:false`) is absent from the + sight input. `kind` is only a derived output label (`wall`, `door`, `window`, `one_way`, else + `custom`; `secret`/`locked` are flags, not kinds, #48) and is never stored: the legacy `kind` + column is dropped by migration step 8 (4.4). GM-only everywhere except the player marker: a player + receives only an integer-px anchor and its own opaque marker id (3.1, 5.8, 6.1), and the + per-player marker set is state like the explored grid (persisted per player in `marker_seen` + below, retracted only by a GM change). + - **Storage: typed columns with CHECK constraints [FIXED (owner-delegated), 2026-11-17, #49].** + One column per field above (ADR-0010); `flags` stays a JSON object for GM data the server never + interprets. `height` and `label` are nullable and are written as SQL literals because + db_connector cannot bind NULL (4.4). + - **Marker storage: `marker_seen` [FIXED (owner-delegated), 2026-11-17, #49].** + `marker_seen(player_id INTEGER NOT NULL REFERENCES player(id) ON DELETE CASCADE, scene_id + INTEGER NOT NULL, wall_id INTEGER NOT NULL, marker_id TEXT NOT NULL, PRIMARY KEY (player_id, + scene_id, wall_id), UNIQUE (player_id, marker_id), FOREIGN KEY (scene_id, wall_id) REFERENCES + wall(scene_id, id) ON DELETE CASCADE)`. One row per `(player, wall)` once seen; `marker_id` is + the opaque per-player 12-character id on the wire. Cascades mirror explored/`name_reveal`: a + removed player takes their markers, a removed scene takes them through its walls, and a removed + wall retracts its marker for everyone (5.8's retraction rule; the composite FK is why a marker + can never dangle). The other retraction causes (`player_marker` off, no longer a window, + geometry moved) are a deliberate delete in the update path, not an FK. + - **Migration [FIXED (owner decision), 2026-11-17, #49].** Step 8 (4.4) rebuilds `wall` and maps + every existing row to today's behaviour (`thickness 0`, `position center`, both block switches + 1, `sight_dir both`, `player_marker`/`secret`/`locked` 0, `height`/`label` NULL; `kind='door'` + -> `door=1` with the same `open`). Every existing token and character gets `height: 1.8 m` in + `props_gm` (5.7). The M6 UVTT importer's defaults are in 6.1. A door stores no leaf field: its + leaf is this same body (5.8, 5.5). - **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]. **`height` and `eye_height` (5.7) are the first two registered keys**, both in the `gm` bucket and both `number`: on a plain token they are its own values, on a linked token the token's values are a temporary override of the character's base (5.7) [FIXED, 2026-11-15, #41]. - - The server interprets only registered keys used by core sight rules: `height` and `eye_height` (5.7) are read by them and enforced as numbers in the `gm` bucket; every other key is stored and never interpreted (FFF later). Interpretation beyond that arrives only through a registered property schema (`{kind, bucket}`), which is also the validation table; before #41 this bullet said "the server never interprets props in v1". Property writes are GM-only in v1 (6.1, #11); the writable-by role and a default value are deferred to the FFF seam (9, post-v1), not part of this registry. -- **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; `height` and `eye_height` are the base values of 5.7, `gm` bucket). 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, apart from the registered sight keys `height`/`eye_height` (5.7), never interprets them; FFF decides the rest of the split (9). The character's `height`/`eye_height` are the base values; a token's are an on-map override that leaves the character alone (5.7) [FIXED, 2026-11-15, #41]. 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]. Built in slice 8 (#23): a reveal is one `(player, subject)` row, and the subject is a character id **or a plain token id** — the two share one id namespace (4.4), so no column distinguishes them. `reveal_all` is a flag on the subject, not a fan-out of rows, so a player who joins later is covered. The one rule that turns a reveal, an owner or a flag into the name a recipient sees is `characters.knowsActual`/`visibleName`; no frame builder re-derives it. -- **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. Built in slice 8 (#23): each entry is a *snapshot* of the names the player knew when it was first sighted (plus the character link, so a rename and a later reveal can follow it), `grey` is computed at frame time, and an entry is recorded on every mutation that could show the token, before the ack. 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. + - `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]. + **`height` and `eye_height` (5.7) are the first two registered keys**, both in the `gm` bucket + and both `number`: on a plain token they are its own values, on a linked token the token's + values are a temporary override of the character's base (5.7) [FIXED, 2026-11-15, #41]. + - The server interprets only registered keys used by core sight rules: `height` and `eye_height` + (5.7) are read by them and enforced as numbers in the `gm` bucket; every other key is stored and + never interpreted (FFF later). Interpretation beyond that arrives only through a registered + property schema (`{kind, bucket}`), which is also the validation table; before #41 this bullet + said "the server never interprets props in v1". Property writes are GM-only in v1 (6.1, #11); + the writable-by role and a default value are deferred to the FFF seam (9, post-v1), not part of + this registry. +- **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; `height` and + `eye_height` are the base values of 5.7, `gm` bucket). 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 alternatives: ADR-0020. +- **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, apart from the registered sight keys `height`/`eye_height` (5.7), never interprets them; + FFF decides the rest of the split (9). The character's `height`/`eye_height` are the base values; + a token's are an on-map override that leaves the character alone (5.7) [FIXED, 2026-11-15, #41]. 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]. Built in slice 8 (#23): a reveal is one `(player, subject)` row, and the subject is a + character id **or a plain token id** — the two share one id namespace (4.4), so no column + distinguishes them. `reveal_all` is a flag on the subject, not a fan-out of rows, so a player who + joins later is covered. The one rule that turns a reveal, an owner or a flag into the name a + recipient sees is `characters.knowsActual`/`visibleName`; no frame builder re-derives it. +- **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. Built in slice 8 (#23): each entry is a *snapshot* of the names the player + knew when it was first sighted (plus the character link, so a rename and a later reveal can follow + it), `grey` is computed at frame time, and an entry is recorded on every mutation that could show + the token, before the ack. 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). +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. +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 interprets nothing except the registered sight keys `height`/`eye_height` (5.7, #41). -- **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, `{kind, bucket}`) registered by the rules module; v1 ships it with the two keys the core sight rules read, `height` and `eye_height` (`number`, `gm`, 5.7), and a permissive fallback for every other key (6.1). The server interprets only registered keys used by core sight rules, which is the one narrowing of "no interpretation in v1" (#41, 8); everything else is stored unread until FFF registers it. A writable-by role and a default value are not part of it: prop writes are GM-only in v1, and which role may write which key, plus any default, belongs to the FFF seam (post-v1). -- **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). +- **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 + interprets nothing except the registered sight keys `height`/`eye_height` (5.7, #41). +- **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:** the registry, its two registered sight keys and the permissive fallback are + defined in 8; FFF later registers the keys it uses, which is the intended narrowing of "no + interpretation in v1" (#41). A writable-by role and a default value are not part of it: prop + writes are GM-only in v1, and which role may write which key, plus any default, belongs to the FFF + seam (post-v1). +- **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. +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 | @@ -844,43 +2188,197 @@ Principles carried from the prototype: the checker must be independent of the co | 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)). +- 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. **Slice 5 built** the classes that exist at this slice: `HIDDEN_TOKEN`, `GMONLY_TOKEN`, `WALLDATA`, `WITHHELD`, `NO_REMOVE`, `OWN_VIEW`, `OTHER_PLAYER`, `EXPLORED` (`-d:leakfault` + `LEAK_FAULT=`, `tools/fault.test.mjs`, exact class set per fault, and the shipped binary asserted to contain no `LEAK_FAULT`). `OWNER_PROP`, `GM_PROP` and the new `STATUS_SOURCE` arrive with slice 7 (#22): the leak scenario writes props into all three buckets and sets a GM-sourced status on a token the subject can see, and `tools/leakcheck.nim` refuses the `gm` bucket, the `owner` bucket on a non-controller and any `source` on a player status entry. `ACTUAL_NAME`, `CHAR_LIST`, `CONTROLLER_CHANGE` and `CHAR_OWNER_PROP` **arrive with slice 8 (#23)**: the leak scenario creates a character, puts a token of it next to the subject, writes the character's three prop buckets, renames it, reveals it to one player and to all, reassigns it twice, reveals a plain token, flips a `gm_only` token that the subject had met, removes a token the subject had met and removes one encountered entry. `tools/leakcheck.nim` adds the four classes: an actual name a player may not see in a `token` or an `encountered` frame (`ACTUAL_NAME`), plus `STALE_NAME` (v0.20, #30: an encountered entry whose name is neither the actual nor the descriptive name that player knows, e.g. a snapshot a rename failed to update); another player's `character` record, a `character_id` on somebody else's token, or an encountered entry the subject never saw (`CHAR_LIST`); a token controller that moved in a group whose intents asked for no controller change — the transcript logs every intent, so `token.create`/`token.update{controller}`/`player.remove` are the only allowed causes (`CONTROLLER_CHANGE`); a `cprops` object carrying anything but the character's `public` bucket (`CHAR_OWNER_PROP`). Two consequences worth recording: the `hidden` and `gmOnly` faults now also produce `NO_REMOVE`, because a leaked token whose frame never changes leaves the client holding it with no message to correct it, which is indistinguishable from a withheld `token_gone` at the client (both invariants really are broken, so both classes are asserted); and the tile gate is HTTP-plane, so it is proven by `tools/tiles.test.mjs` against the test nginx (10.3 Tiles), not by the WS transcript checker. `GLOBAL_COUNTER` is already structurally impossible (per-connection `n`). -- **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. **Built in slice 8** as the `tools/characters.test.mjs` group, which also carries the two checks 10.3 was missing: "a status source is not shown to a non-GM" (the controller included) and "an encountered entry survives a `gm_only` flip and a token removal" (greyed, never deleted). -- **Tiles (#24)**: `tools/tiles.test.mjs` is the group's leak check (d) and the smoke tile-steal checks, through the real binary and a test nginx (`tools/nginx.mjs`, nginx from devbox; config generated per run in the state dir). An **independent explored oracle** (born in 10.2) recomputes visibility per cell from the GM's walls and the token's vision radius with its own clear-segment maths (inscribed 64-gon radius - 0.5 px for "sure", radius + 0.5 px and proper crossings for "maybe"): a `200` must be oracle-maybe (no invented disclosure) and oracle-sure must be `200` (no withheld tile). The 32x32-tile sweep is 1024 requests; slice 9's scene allows 283, all 283 oracle-sure, 0 maybe-refused. Also checked: a player with no sight state gets `403`; another player gets `403` on a tile its neighbour sees; direct `/_tiles/` is `404` (the file exists) for every identity; malformed/canonical/out-of-range/stale-version/scene paths are `404` (with and without a session, including the GM); traversal and encoded shapes never reach a file; the direct-from-Nim answer carries `X-Accel-Redirect: /_tiles/1/v1/_.png`, `Cache-Control: private` and an empty body. Fixture tiles are 32 px PNGs written by `tools/tilefixture.mjs` under the state dir at test time; the test asserts the repo tracks no `.png` at all. -- **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). -- **Door equivalence (#46, T17)**: `tools/doors.test.mjs` is the accept group for the "a player cannot tell a secret or locked door from a wall" obligation 5.8 states. Node harness, built-ins only (10.4), shaped like `tools/probing.test.mjs`: two servers, fresh state, two scenes identical except one segment, one identical scripted sequence. Pairs: (i) solid `wall` vs a closed `door` with `secret`; (ii) solid wall vs a closed door with `secret` and `locked`; (iii) closed `door` vs a closed `door` with `locked` (since #48 there are no `secret_door`/`locked_door` presets: the switches are the same, only the name changed). Script, run against both servers in lockstep: player tokens with vision near and around the segment; player moves along, into and across it (accepted, collision nacks, over-cap nacks); the GM adds the segment over a player token (`stuck`); the GM edits and toggles unrelated walls and doors elsewhere and moves tokens; a resync/reconnect; a GM `door.set open` on the secret/locked segment, refused `invalid` and GM-side only. **Assertion:** each player's complete received frame sequence — `hello`, `vision`, `explored` (full and delta), `token` (statuses included), `encountered`, and every `ack`/nack with its `code` and `pos` — is identical between the two runs after JSON canonicalisation (keys sorted, no numeric reformatting). **Normalisation allowed: none**; `n` is per connection and wall ids never reach a player, so nothing run-local leaks into the comparison. If the build ever forces a run-local difference it must be named in the test header with the reason. **Tiles:** the same per-player tile sweep in both runs, through the test nginx (`tools/nginx.mjs`, 11.1), must give the same status per tile. **Positive control:** the same script against a third scene whose segment is an open door (or absent) must produce *different* transcripts, otherwise the harness cannot fail (10, first paragraph). **Negative control:** a `-d:leakfault` build with `LEAK_FAULT=secretgap` makes a secret door not block sight (or movement) in the player-facing computation; the doors group must fail with that build, pass on a clean one, and the shipped binary must carry no fault hook (10.1, `tools/fault.test.mjs`). **Refusal codes:** `door.set` on a secret or locked door is `invalid` for the GM; a player `door.set` is `not-allowed` for every door (6.5), so the player side has one code and no oracle. **Not covered:** timing and size side channels (T11), accepted and unchanged. -- **Door push with thickness (#50)**: in-process pins in `tests/tmoverules.nim` (5.5). **Zero-thickness regression gate:** the existing push tests run **unchanged** and keep their exact positions (including "past the end", where the along-axis coordinate does not move), so a zero-thickness door's `pushFrom` must return byte-identical values to today's — no expectation may be rewritten to fit the generalised rule. **Thick cases:** a token beside a long face is pushed off the body face by `r` with its along-axis coordinate kept; a token past an end is pushed to `r` around the nearest end corner with its along-axis coordinate kept; a token inside the body is pushed out of its `prev` side (left with no history); the first side's target overlapping another blocking body or leaving the map falls back to the other side, and both invalid leaves the token in place with `squeezed` while the door closes; the validity check runs over the full collider, so a neighbouring thick body or the thick closed door itself refuses a target the old segment test would have accepted; `position` `left`/`right` move the body, and with it the pushed target, by the thickness. **Equivalence:** the #46 two-server test (T17) gains thick pairs — a thick secret door against a thick solid wall of the same body, and a thick locked door against a thick plain door — with byte-identical player frames, statuses, refusals and per-tile statuses. Also pinned: a fixed window (`door:false`) and an open door never push, and neither does any wall edit. **Mutations:** the push measured from the drawn line instead of the body; the push ignoring the body's normal span; the ambiguous side ignoring `prev`; the validity check testing only the door instead of every blocking body. Each must fail >= 1 test. -- **Door settings in the leak checker (#46)**: `tools/leakcheck.nim`'s `BannedAlways` deep-key scan grows the wall setting keys — `secret`, `locked`, `door`, `blocks_sight`, `blocks_movement`, `sight_dir`, plus `thickness`, `position`, `height`, `player_marker` and `label` (#49's names, 10.3 below) — so a door or wall field that reaches a player frame is `WALLDATA` (T2/T17). The existing `walls` fault already injects the frame class; a new fault variant leaks one door setting key inside a player frame and asserts exactly `WALLDATA`, nothing more. Because the scan is deep, the leak and doors fixtures must not name a player-visible prop like a wall setting (that would be a false positive; `height` is safe: it is a `gm`-bucket key, 5.7). -- **One-way direction (#47)**: `tools/leakcheck.nim` and the independent explored/tile oracle apply **their own** side test — sign of the cross product of `viewer - a` with the `(-dy, dx)` normal of `a -> b`, positive = left — never by calling `vision.nim`: a sight-blocking one-way wall is dropped from the oracle's wall list for a viewer on its blind side, and a wall that is `blocks_sight:false` is dropped for everyone. Assertions: a token on the blind side gets no polygon point, explored cell or tile beyond the wall, and a token across it gives no `token` frame, no name and no encountered entry; a viewer on the seeing side does see across (the positive control, so the oracle can fail). Tolerances as elsewhere: the 0.5 px boundary band along the blind side is oracle-*maybe* (a `200` there is legitimate, but never *sure*), and anything clearly behind the blind wall is oracle-refused (a withheld proof cell still fails). New fault class `ONEWAY` — the player-facing computation drops `sight_dir` and lets the blind side see across — with its injected fault and exact-class assertion, shaped like the existing classes. -- **Player marker (#48; shape fixed by #49)**: the first wall-derived player data, so it gets its own oracle. The frame is `marker {full:bool, set:[{id, pos}], del:[id]}` (6.1), `pos` integer px, `id` a 12-character per-player string that is never a wall id; `tools/leakcheck.nim` must add `"marker"` to its allowed server types, compute by its own code (never calling `vision.nim`) that a marker frame exists for a player exactly when some point of the wall's visible extent (segment, or body boundary for a thick wall) has entered that player's vision polygon **and** the wall is `player_marker:true` and derives `window`, and check that the frame carries **only** the player's opaque marker id and the anchor point: any `kind`, `open`/`closed`, `sight_dir`, `label`, `thickness`, `height`, wall id or switch in a player frame is `WALLDATA`/`MARKER_EXTRA`. Positive control: a window placed in the open yields exactly one marker once its anchor is seen (so the oracle can fail); a marker-bearing wall behind a sight-blocking wall, a `player_marker:false` wall or a solid wall with the switch on yields none. The `BannedAlways` deep-key scan grows `label`, `player_marker`, `thickness`, `position` and `height` alongside the door keys, with the same caveat that fixtures must not name a player-visible prop with those keys. Three fault classes, each with an injected fault and an exact-class set, shaped like the existing ones: **`MARKER_EARLY`** — a marker sent before any part of the wall entered the polygon; **`MARKER_EXTRA`** — a marker frame carrying one extra field (a `kind`, a `label` or the wall id); **`MARKER_OFF`** — a marker sent for a wall whose `player_marker` is off. Retraction is checked on the GM side: removing the wall, clearing the marker switch or moving the geometry retracts the marker and never sends the new position early; a marker change writes no explored cell and revokes no tile. -- **Wall fields, storage and migration (#49)**: the record's new surface gets three gates (leak, migration, behaviour) plus a fixture list; the assertions land with the build tickets (/to-spec), not here. - - **Leak gate.** `tools/leakcheck.nim`'s `BannedAlways` grows every wall field name — `thickness`, `position`, `height`, `blocks_sight`, `blocks_movement`, `sight_dir`, `player_marker`, `door`, `open`, `secret`, `locked`, `label`, `a`, `b` — so any of them in a player frame is `WALLDATA`; `marker` joins the allowed server types and its oracle above applies. Positive control: the same scene with one wall's `height` injected into a player `token` frame fails with exactly `WALLDATA`. - - **Migration gate.** A **schema-7 fixture** (pre-#49: `wall` rows of both `kind`s including an open door and a non-empty `flags`, tokens and a character with props) migrates under the real binary to schema 8, and the decoded rows must equal the mapping exactly: `thickness 0`, `position center`, both block switches 1, `sight_dir both`, `player_marker`/`secret`/`locked` 0, `height`/`label` NULL, `door` from `kind` with the same `open`, `flags` byte-identical; `props_gm` has `height: 1.8` on every token and character and `eye_height` is untouched. A second run is a no-op (`migrate` returns 0), and a failing step rolls back completely (existing `tdb` checks). - - **Behaviour-preservation gate.** Because the project has no real user data (pre-M4), correctness is proven on the wire, not on rows: one scene created through `wall.add` with today's switch set (`wall`, closed `door`, open `door`) and one migrated schema-7 scene holding the same walls must produce **byte-identical player frames, refusals and per-tile statuses** for the same scripted session — the #46 two-server harness with the migration as the third arm, same canonicalisation and no normalisation. The #50 zero-thickness push tests stay unchanged and must pass against the migrated rows, and the 5.8 rule that a player frame carries no wall fact is the leak gate above. - - **Fixture churn (build tickets).** `tests/tdb.nim`: `LatestVersion == 7` -> `8`, the "steps 3 to 7" count -> "3 to 8", the newer-DB fixture stays above the latest. `tools/persistence.test.mjs`: the schema-4 fixture's assertion `schema_version=7 applied=3` -> `schema_version=8 applied=4`, plus the new schema-7 fixture and its mapping assertions. `server/world.nim` (`WallRec`, `rowToWall`, `insertRow`/`replaceRow`, `WallPatch`, the parsers), `server/worldmap.nim` (`ruleWall` reads switches, not `kind`), `server/views.nim` and `tests/tworld.nim`, `tests/tviews.nim`, `tests/tokens.nim`, `tests/tcharacters.nim`, `tools/walls.test.mjs`, `tokens.test.mjs`, `details.test.mjs`, `scene.test.mjs`, `restart.test.mjs`, `walls.test.mjs`, `doors.test.mjs` and the leak/fault fixtures all gain the new fields, the `marker` message or the height backfill; any test that builds a `wall` row by hand gains the columns. -- **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. **Slice 6 built** the explored half: `tests/texplored.nim` (chunk layout pinned, whole-chunk encoding, upsert replacement, per-player keying, restore, write cost) and `tools/persistence.test.mjs` (round trip through a fresh resync, per-player isolation, SIGTERM and SIGKILL restart equality, a wall removal's revealed cells after the wall returns, chunk rows decoded independently, move-ack timing, and a fixture schema-4 DB migrated by the real binary). -- **Restart (#25)**: `tools/restart.test.mjs` is the "restart" accept group. It builds one world that exercises every CRUD path (walls and an open door, plain/monster/player/linked tokens, a resize and a GM status, props in three buckets with a `prop.unset`, a character with props, a per-player reveal and a token `reveal_all`, a sighting in the encountered list, players and a name) and compares the complete 6.3 resync of a fresh GM connection and a fresh player connection before and after the restart: hello scene block, roster, walls, characters, tokens, encountered, vision and the full explored RLE, all normalized (only the per-connection `n` is dropped) and deep-equal. Both SIGTERM and SIGKILL are checked, because every ack follows its COMMIT (4.2). -- **Logs (#25)**: `tools/logs.test.mjs` is the "logs" accept group. It records every GM key (the CLI key, a `--new` rotation, an old key after rotation), every player key (`key.create`, `key.show`, `key.replace`), every session cookie from `/join` (several devices) and its SHA-256 hash, plus a wrong key, a refused tile, a proto mismatch and a malformed frame, across two server runs on the same state dir, then greps the whole `server.log` for every value: none may appear. The second test is the negative control: a `-d:leakfault` build with `LEAK_FAULT=keylog` writes a raw key to stdout past `eventlog`, and the same grep must find it (so a log that was never captured cannot pass). -- **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. +- **Fault classes.** Each class has an injected fault (`-d:leakfault`, `LEAK_FAULT=`) and an + exact-class assertion; the shipped binary must contain no `LEAK_FAULT`. Built: `HIDDEN_TOKEN`, + `GMONLY_TOKEN`, `WALLDATA`, `WITHHELD`, `NO_REMOVE`, `OWN_VIEW`, `OTHER_PLAYER`, `EXPLORED`, + `OWNER_PROP`, `GM_PROP`, `STATUS_SOURCE`, `ACTUAL_NAME`, `STALE_NAME`, `CHAR_LIST`, + `CONTROLLER_CHANGE`, `CHAR_OWNER_PROP`, `MARKER_EARLY`, `MARKER_EXTRA`, `MARKER_OFF`, `ONEWAY`, + `KEY_IN_LOG`, `secretgap`. `tools/leakcheck.nim` refuses the `gm` bucket, the `owner` bucket on a + non-controller and any `source` on a player status entry. Two consequences: the `hidden` and + `gmOnly` faults also produce `NO_REMOVE` (a leaked token whose frame never changes leaves the + client holding it with no correcting message, indistinguishable from a withheld `token_gone`; both + invariants are broken), and the tile gate is HTTP-plane, so `tools/tiles.test.mjs` proves it (10.3 + Tiles), not the WS transcript checker. `GLOBAL_COUNTER` is structurally impossible (per-connection + `n`). +- **Characters and names (#14)**: tests for reveal per player and reveal to all; owner sees own + actual name; a character owner change leaves token controllers unchanged; encountered entries + survive token removal and a `gm_only` flip (greyed) and are removed only by the GM; `gm_only` + tokens never enter an encountered list. Group: `tools/characters.test.mjs`, including "a status + source is not shown to a non-GM" (the controller included). Fault classes: `ACTUAL_NAME`, + `CHAR_LIST`, `CONTROLLER_CHANGE`, `CHAR_OWNER_PROP`. +- **Tiles (#24)**: `tools/tiles.test.mjs` is the group's leak check (d) and the smoke tile-steal + checks, through the real binary and a test nginx (`tools/nginx.mjs`, nginx from devbox; config + generated per run in the state dir). An **independent explored oracle** (born in 10.2) recomputes + visibility per cell from the GM's walls and the token's vision radius with its own clear-segment + maths (inscribed 64-gon radius - 0.5 px for "sure", radius + 0.5 px and proper crossings for + "maybe"): a `200` must be oracle-maybe (no invented disclosure) and oracle-sure must be `200` (no + withheld tile). The 32x32-tile sweep is 1024 requests; slice 9's scene allows 283, all 283 + oracle-sure, 0 maybe-refused. Also checked: a player with no sight state gets `403`; another + player gets `403` on a tile its neighbour sees; direct `/_tiles/` is `404` (the file exists) for + every identity; malformed/canonical/out-of-range/stale-version/scene paths are `404` (with and + without a session, including the GM); traversal and encoded shapes never reach a file; the + direct-from-Nim answer carries `X-Accel-Redirect: /_tiles/1/v1/_.png`, `Cache-Control: + private` and an empty body. Fixture tiles are 32 px PNGs written by `tools/tilefixture.mjs` under + the state dir at test time; the test asserts the repo tracks no `.png` at all. +- **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). +- **Door equivalence (#46, T17)**: `tools/doors.test.mjs` is the accept group for the "a player + cannot tell a secret or locked door from a wall" obligation 5.8 states. Node harness, built-ins + only (10.4), shaped like `tools/probing.test.mjs`: two servers, fresh state, two scenes identical + except one segment, one identical scripted sequence. Pairs: (i) solid `wall` vs a closed `door` + with `secret`; (ii) solid wall vs a closed door with `secret` and `locked`; (iii) closed `door` vs + a closed `door` with `locked` (since #48 there are no `secret_door`/`locked_door` presets: the + switches are the same, only the name changed). Script, run against both servers in lockstep: + player tokens with vision near and around the segment; player moves along, into and across it + (accepted, collision nacks, over-cap nacks); the GM adds the segment over a player token + (`stuck`); the GM edits and toggles unrelated walls and doors elsewhere and moves tokens; a + resync/reconnect; a GM `door.set open` on the secret/locked segment, refused `invalid` and GM-side + only. **Assertion:** each player's complete received frame sequence — `hello`, `vision`, + `explored` (full and delta), `token` (statuses included), `encountered`, and every `ack`/nack with + its `code` and `pos` — is identical between the two runs after JSON canonicalisation (keys sorted, + no numeric reformatting). **Normalisation allowed: none**; `n` is per connection and wall ids + never reach a player, so nothing run-local leaks into the comparison. If the build ever forces a + run-local difference it must be named in the test header with the reason. **Tiles:** the same + per-player tile sweep in both runs, through the test nginx (`tools/nginx.mjs`, 11.1), must give + the same status per tile. **Positive control:** the same script against a third scene whose + segment is an open door (or absent) must produce *different* transcripts, otherwise the harness + cannot fail (10, first paragraph). **Negative control:** a `-d:leakfault` build with + `LEAK_FAULT=secretgap` makes a secret door not block sight (or movement) in the player-facing + computation; the doors group must fail with that build, pass on a clean one, and the shipped + binary must carry no fault hook (10.1, `tools/fault.test.mjs`). **Refusal codes:** `door.set` on a + secret or locked door is `invalid` for the GM; a player `door.set` is `not-allowed` for every door + (6.5), so the player side has one code and no oracle. **Not covered:** timing and size side + channels (T11), accepted and unchanged. +- **Door push with thickness (#50).** In-process pins in `tests/tmoverules.nim` (5.5). + **Zero-thickness regression gate:** the existing push tests run unchanged and keep their exact + positions (including "past the end", where the along-axis coordinate does not move). **Thick + cases:** face push by `r` with the along-axis coordinate kept; past an end, push to `r` around the + nearest end corner; inside the body, out of the `prev` side (left with no history); first side + invalid (another blocking body or out of bounds) falls back to the other; both invalid leaves the + token and `squeezed` while the door closes; `position` `left`/`right` moves the body and the + target by the thickness. **Equivalence:** the #46 two-server test gains thick pairs (thick secret + door vs thick solid wall; thick locked door vs thick plain door), byte-identical. Also pinned: a + fixed window and an open door never push, and no wall edit pushes. **Mutations:** push from the + drawn line; push ignoring the normal span; ambiguous side ignoring `prev`; validity check on the + door only — each fails at least one test. +- **One-way direction (#47)**: `tools/leakcheck.nim` and the independent explored/tile oracle apply + **their own** side test — sign of the cross product of `viewer - a` with the `(-dy, dx)` normal of + `a -> b`, positive = left — never by calling `vision.nim`: a sight-blocking one-way wall is + dropped from the oracle's wall list for a viewer on its blind side, and a wall that is + `blocks_sight:false` is dropped for everyone. Assertions: a token on the blind side gets no + polygon point, explored cell or tile beyond the wall, and a token across it gives no `token` + frame, no name and no encountered entry; a viewer on the seeing side does see across (the positive + control, so the oracle can fail). Tolerances as elsewhere: the 0.5 px boundary band along the + blind side is oracle-*maybe* (a `200` there is legitimate, but never *sure*), and anything clearly + behind the blind wall is oracle-refused (a withheld proof cell still fails). New fault class + `ONEWAY` — the player-facing computation drops `sight_dir` and lets the blind side see across — + with its injected fault and exact-class assertion, shaped like the existing classes. +- **Player marker (#48; shape fixed by #49).** `leakcheck.nim` allows the `marker` type and, with + its own code (never calling `vision.nim`), checks that a marker exists for a player exactly when + some point of the wall's visible extent has entered that player's polygon **and** the wall is + `player_marker:true` and derives `window`, and that the frame carries only the opaque marker id + and the anchor: anything else is `WALLDATA`/`MARKER_EXTRA`. Positive control: a window in the open + yields exactly one marker once its anchor is seen; a wall behind a sight blocker, + `player_marker:false`, or a solid wall with the switch on yields none. Faults: `MARKER_EARLY`, + `MARKER_EXTRA`, `MARKER_OFF`. Retraction is checked GM-side: removing the wall, clearing the + switch or moving the geometry retracts the marker, never sends the new position early, and writes + no explored cell or tile. +- **Wall fields, storage and migration (#49).** Three gates. **Leak:** `BannedAlways` contains every + wall field name (`thickness`, `position`, `height`, `blocks_sight`, `blocks_movement`, + `sight_dir`, `player_marker`, `door`, `open`, `secret`, `locked`, `label`, `a`, `b`), so any of + them in a player frame is `WALLDATA`; `marker` is an allowed server type with its own oracle; + positive control: a wall `height` injected into a player `token` frame fails with exactly + `WALLDATA`. **Migration:** a schema-7 fixture (both wall kinds, an open door, non-empty `flags`, + tokens and a character with props) migrates under the real binary, every decoded row equals the + 4.4 mapping, `props_gm.height` is `1.8` on every token and character and `eye_height` untouched; a + second run is a no-op and a failing step rolls back. **Behaviour:** one scene built through + `wall.add` with today's switch set and one migrated schema-7 scene holding the same walls produce + byte-identical player frames, refusals and per-tile statuses for the same script; the #50 + zero-thickness push tests pass unchanged against migrated rows. Fixture churn: `tests/tdb.nim` + `LatestVersion` 8, `tools/persistence.test.mjs` schema-8 assertions and the schema-7 fixture, and + every hand-built `wall` row gains the columns. +- **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 extended to + wall CRUD and entity props. `tests/texplored.nim` pins the chunk layout, whole-chunk encoding, + upsert replacement, per-player keying, restore and write cost; `tools/persistence.test.mjs` covers + the fresh-resync round trip, per-player isolation, SIGTERM/SIGKILL equality, a wall removal's + revealed cells after the wall returns, independently decoded chunk rows, move-ack timing, and a + fixture DB migrated by the real binary. +- **Restart (#25)**: `tools/restart.test.mjs` is the "restart" accept group. It builds one world + that exercises every CRUD path (walls and an open door, plain/monster/player/linked tokens, a + resize and a GM status, props in three buckets with a `prop.unset`, a character with props, a + per-player reveal and a token `reveal_all`, a sighting in the encountered list, players and a + name) and compares the complete 6.3 resync of a fresh GM connection and a fresh player connection + before and after the restart: hello scene block, roster, walls, characters, tokens, encountered, + vision and the full explored RLE, all normalized (only the per-connection `n` is dropped) and + deep-equal. Both SIGTERM and SIGKILL are checked, because every ack follows its COMMIT (4.2). +- **Logs (#25)**: `tools/logs.test.mjs` is the "logs" accept group. It records every GM key (the CLI + key, a `--new` rotation, an old key after rotation), every player key (`key.create`, `key.show`, + `key.replace`), every session cookie from `/join` (several devices) and its SHA-256 hash, plus a + wrong key, a refused tile, a proto mismatch and a malformed frame, across two server runs on the + same state dir, then greps the whole `server.log` for every value: none may appear. The second + test is the negative control: a `-d:leakfault` build with `LEAK_FAULT=keylog` writes a raw key to + stdout past `eventlog`, and the same grep must find it (so a log that was never captured cannot + pass). +- **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]. +- 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. The port lives in `tools/withserver.mjs`, and slice 9 (#24) added the test nginx as `tools/nginx.mjs`. -- 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) and, since slice 9 (#24), the `nginx` used only by the test harness (DESIGN 11.1); no global tooling. +- 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. The harness + lives in `tools/withserver.mjs`; the test nginx is `tools/nginx.mjs`. +- 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. +- Root `devbox.json` pins `nodejs` 26 and the `nginx` used only by the test harness (11.1); no + global tooling. - `devbox run test` = Nim tests first, then Node harnesses. -- The nine M3 accept groups and their proving harness tests are mapped in `tools/groups.mjs`; `tools/groups.test.mjs` fails if a group file or its named evidence test disappears, so the checklist of 14 (#12) cannot silently go stale. Slice-level harnesses that are not an accept group (`smoke`, `walls`, `tokens`, `details`, `scene`, `wsheaders`) run in the same pass. +- The nine M3 accept groups and their proving harness tests are mapped in `tools/groups.mjs`; + `tools/groups.test.mjs` fails if a group file or its named evidence test disappears, so the + acceptance checklist cannot silently go stale. Harnesses that are not an accept group + (`smoke`, `walls`, `tokens`, `details`, `scene`, `wsheaders`) run in the same pass. - In-process tests stay Nim (`nimble test`, unchanged). - Browser e2e details: M4, not decided here. @@ -889,217 +2387,224 @@ Principles carried from the prototype: the checker must be independent of the co ## 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:` only [MEASURED prototype binds 127.0.0.1]. - - `fff-vtt gm-key` (3.2) must run as the service user (e.g. `sudo -u 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 `/instance.lock`; `gm-key --new` exits 3 while the server runs. [FIXED, owner-delegated, 2026-11-14, #17] +- **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:` only [MEASURED + prototype binds 127.0.0.1]. + - `fff-vtt gm-key` (3.2) must run as the service user (e.g. `sudo -u 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 `/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): +- **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 = /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 /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. [FIXED (owner-delegated), #24] The `Cache-Control: private` on a served tile comes from the Nim gate (3.3) and nginx passes it through the internal redirect; the location adds no header of its own, so the header is not duplicated. - - Test nginx [FIXED (owner-delegated), #24]: `tools/nginx.mjs` starts the devbox `nginx` package on a free loopback port in front of the harness server, with a config generated per run under the server's state dir (ports and state paths never committed). It mirrors this vhost shape: `/join` (`access_log off`), `/tiles/` proxy, `/ws` upgrade, `/healthz` readiness, and `location /_tiles/ { internal; alias /tiles/; }`. Tile bytes are 32 px fixture PNGs from `tools/tilefixture.mjs`, written under `/tiles/`; none is committed. - - Response headers: HSTS, CSP (no inline scripts, `connect-src 'self'` wss), `X-Content-Type-Options`, `Referrer-Policy`. + - `location /_tiles/` -> `internal; alias /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. [FIXED (owner-delegated), #24] The `Cache-Control: private` on a served + tile comes from the Nim gate (3.3) and nginx passes it through the internal redirect; the + location adds no header of its own, so the header is not duplicated. + - Test nginx [FIXED (owner-delegated), #24]: `tools/nginx.mjs` starts the devbox `nginx` package + on a free loopback port in front of the harness server, with a config generated per run under + the server's state dir (ports and state paths never committed). It mirrors this vhost shape: + `/join` (`access_log off`), `/tiles/` proxy, `/ws` upgrade, `/healthz` readiness, and `location + /_tiles/ { internal; alias /tiles/; }`. Tile bytes are 32 px fixture PNGs from + `tools/tilefixture.mjs`, written under `/tiles/`; none is committed. + - 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 `/tiles//v/` 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). +- 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 + `/tiles//v/` 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. +- 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. +- 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). +- 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 +## 12. HANDOFF traceability -Source: `prototype-server-vision/HANDOFF.md` (and README/NOTES worries). +Every item of the prototype's `HANDOFF.md` (H1-H26) is resolved; each decision is stated once in the +section it belongs to (geometry and move rules in 5, persistence in 4.4, protocol in 6, tests in 10, +deployment in 11). The old item-by-item table is preserved verbatim in +[`docs/DESIGN-history.md`](DESIGN-history.md) §B. The one open item from it (the unexplained 583 ms +spike) is in §14. -| # | Item | Decision / open | Milestone | +--- + +## 13. Build status and milestones + +Build order is FIXED (owner decision 2026-11-17, `docs/ANALYSIS-review.md` D1, ADR-0012): thick +walls (5.10) and wall/token heights with see-over (5.7, 5.9) are built **after** the first playable +M4 client and a phone playtest. The v1-first build is thin walls with the 5.8 switches, doors, +secret/locked, windows, one-way and player markers. The #49 schema (thickness, position, height +columns with today's defaults) lands complete now, so the later build needs no migration. + +- **M1 - Port geometry + tests.** Done. `geometry.nim`, `tgeometry.nim`, the mutation script, the + shared-endpoint arm test; repo builds with devbox only. +- **M2 - Vision engine v2 and move rules.** Done. Scanline `cellsTouched`, differential and + independent explored oracles, radius-bbox cull, capsule move check and escape rule, step cap, + status model, in-process move-rules module (5.5). +- **M3 - Server core.** Done. 29 intents and 15 server messages, characters/names, chunked explored, + typed views and single egress, auth, tile gate, schema and migrations. Accept = `devbox run test` + green on a clean checkout with the nine groups: leak+fault, tiles, probing, protocol, auth, + characters and names, restart, persistence, logs. Measured 2026-11-15: `devbox run test` exit 0 + (Nim suite all pass; 103 Node harness tests) and `devbox run mutation` exit 0 (control passes, all + 63 mutations fail at least one expected test). The nine groups map to their proving tests in + `tools/groups.mjs`; `tools/groups.test.mjs` fails if a group or its named evidence test + disappears. Out of M3 accept: concurrency (M5), the 127.0.0.1 bind check (M6). +- **M4 - Client v1.** Vite + TS + Pixi v8 client: layers, tiles, grid, tokens (BitmapText), + character and encountered lists, reveal controls, fog textures, the wall editor (four presets, + switches, marker, label, one-way arrow and flips), token drag with prediction/rollback, DOM + overlay, reconnect backoff, reducer tests; then archive `prototype-*` (Q24). Thickness and height + controls are not in M4 (build order above; 5.7, 5.10). + - 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 on a 16384 px tiled map (test target + PROPOSED, Q2), fog active. + - Tile-size gates [FIXED, Q4]: (a) automated headless-Chromium test with mobile emulation + (viewport, dpr, CPU and 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. + If either fails: `tile_size` 64 px (per-scene config, no code change). The 2026-11-08 prototype + phone run 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.** SIGTERM handler, bounded metrics and SLOW lines, per-client + bounded outbox with coalescing and Ping/Pong lag tracking (4.3), verify `/ws` goes through nginx + and which timeout closes a dead peer, healthz lock check. Accept: concurrency 60 s x3 with p99 <= + the prototype's 4.98 ms +50%; the slow-client test (outbox under cap, RSS flat, no further state + queued, full resync equals a fresh connection); nginx closes a dead `/ws` within its configured + timeout; stats computation outside the lock. +- **M6 - NixOS deployment.** `nix/` per Q20 (`lock.json`, `package.nix`, `module.nix` with + `services.fffVtt`), client build, nginx vhost, systemd hardening, backups timer and restore drill, + map import CLI. Accept: deployed behind HTTPS; direct `/_tiles/` 404; WS upgrade works; phone + sign-in works; no secret in the access log; backup and restore drill passes. +- **M7 - Real-world pass.** Real-network latency/throughput run, iOS/Safari check if available, one + real session with the owner's table, SLOW lines collected. Accept: documented numbers, defects + triaged, go/no-go for v1. + +M3 build slices [FIXED, owner decision 2026-11-14, #13] are complete: 1 bare server, 2 auth, 3 +protocol shell, 4 walls and doors, 5 tokens and sight, 6 explored, 7 token details, 8 characters and +names, 9 map tiles, 10 finish line. + +Post-v1 candidates: FFF seam implementation (9), drawings/pings/ruler, chat/dice (order at M7, Q8), +light sources, browser upload UI (Q5), multi-scene (Q3), vision deltas/binary protocol (Q16), a +per-player masked overview image (7.4). + +--- + +## 14. Open items + +None of these changes a FIXED rule; they are the questions still open and the PROPOSED choices the +owner may overturn. The full Q1-Q24 decision log is in [`docs/DESIGN-history.md`](DESIGN-history.md) +§C. + +### Open questions + +- **Q2, map size and wall count.** The owner does not know yet; a 16384 px map and 5k walls are + PROPOSED test targets (5.3, 13). Revisit with real maps. +- **Q8, table conveniences after v1.** Order decided at M7. +- **Q19, where FFF runs.** Hidden state is settled (no state beyond the three buckets and + `gm_only`); engine language, runtime and location are not. Options in 9. +- **583 ms intent-to-ack outlier.** Not reproduced, cause undetermined; production SLOW logging + (11.3) must make a recurrence diagnosable (4.3). + +### PROPOSED choices awaiting use or owner review + +- Keep the single global lock in v1; revisit only on a measured p99 > 50 ms in production (4.3). +- Enforce the single egress with distinct `PlayerView`/`GmView` types, not discipline alone (2). +- Keep the permissive property fallback in v1; strict schema mode comes with the FFF seam (6.1, 9). +- Explored diff wire format (RLE on connect, cell lists after) and the fog/vision rendering + mechanism (6.4, 7.3). +- `wall.update` counts as remove + add for the status rule (5.5). +- The nginx directive that closes a dead peer; verified in M5 (4.3). +- The uniform spatial grid, only if the 5k-wall bench misses its target (5.3, 5.5). +- Client-side interpolation of others' token moves (7.5); load/perf regression gate at 2x (10.3); + backup mechanism detail (11.2). + +### Decisions recorded as ADRs + +Each ADR states the context, the decision, the alternatives and the consequences, and links back to +the section here that it constrains. + +| ADR | Decision | Spec | Tickets | |---|---|---|---| -| 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. `scene.set` is the one scene-writing intent (6.1 payload rules) and completes the 29-intent catalogue (#25). 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]. **Built by slice 9 (#24):** `tools/tiles.test.mjs` (three tests: the oracle sweep of 1024 tile requests through the test nginx, the full refusal/path matrix plus direct `/_tiles/`, and the generated-fixture/no-committed-PNG check), with `tools/nginx.mjs` and `tools/tilefixture.mjs`; the decided URL grammar and status split are in 3.3. - 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). Built by slice 8 (#23): `tools/characters.test.mjs` (ten tests: `player.setname` + `roster`, `player.rename` + `key.show`, `character.create`, reveal per player and `reveal_all`, a plain token's own names and `cprops`, `reassign` leaving controllers alone, `update`/`remove` with `in-use`, the encountered list and `encountered.remove`, the status source, and a restart), plus the four new fault classes in group 1. - 7. **restart**: identical state after restart, incl. CRUD (10.1). **Built by slice 10 (#25):** `tools/restart.test.mjs` (two tests: full-state equality over SIGTERM and over SIGKILL, every CRUD path in one world; details in 10.3). - 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). **Built by slice 10 (#25):** `tools/logs.test.mjs` (two runs incl. a GM-key rotation, keys/sessions/hashes, and a `keylog` leak-fault negative control; details in 10.3). -- **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 editor with presets and switches (5.8) and player markers, token drag with prediction/rollback, DOM overlay, reconnect backoff, reducer tests; after the client port, archive `prototype-*` dirs (Q24). Thickness and height controls (5.10, 5.7) are **not** in M4: they follow the phone playtest (build order, 1). - - 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, done) 9. Map tiles (#24, done) 10. Finish line (#25, done). -- **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. **Kind set SUPERSEDED [FIXED (owner decision), 2026-11-15, #42]** by 5.8: a wall's behaviour is independent switches and named kinds are presets; v1 presets are `wall`, `door`, `secret door`, `locked door`, `terrain` and `one-way wall`, and `window` was added by #47 (2026-11-16) as a see-through opening, its fixed form being `terrain`. **Preset list SUPERSEDED AGAIN [FIXED (owner decision), 2026-11-16, #48]:** there are four presets (`wall`, `door`, `window`, `one-way`), `secret` and `locked` are checkboxes on any door rather than presets, and `terrain` is dropped entirely (the name, the preset and the kind); the derived kinds are `wall`, `door`, `window`, `one_way`, `custom`. The editor requirement is unchanged. -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 `/tiles//v/` 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 `.` (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 `/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-15 [FIXED (owner-delegated, 2026-11-15, #19)]: walls and doors (M3 slice 4). Schema is migration step 3 (`world`): `scene` and `wall`, with the single v1 scene seeded at `id 1` (4096x4096, tile 32 = cell 32, no grid, vision 400, token radius 20, art_version 1, `next_wall_id` 1) (4.4). Wall ids are per scene from `next_wall_id`, monotonic and never reused across removal or restart (#3). The four intents `wall.add`/`wall.update`/`wall.remove`/`door.set` are GM-only and answer the 6.1 acks; the payload rules 6.1 left open are fixed there: integer `scene` (else `not-found`), `a`/`b` finite and in bounds with `a != b`, `open` boolean and never true on a plain wall, `flags` an object (default `{}`), `wall.update` patches only `a`/`b`/`kind`/`flags` and needs at least one, `door.set` on a non-door is `invalid`, fields before lookup. Effects: `wall`/`wall_gone` to every GM connection only, and a `walls` snapshot right after `hello` on a GM connection; players never receive wall data in any message (3.1, T2). Every wall write is one transaction with `synchronous=FULL` (Q12) and memory follows COMMIT, so a restart reloads exactly what was acked. See 4.4, 6.1, 6.3, 8, 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. - -Owner also decided 2026-11-15 [FIXED (owner-delegated, 2026-11-15, #20)]: tokens and sight (M3 slice 5). Schema is migration step 4 (`tokens`): `entity` as listed in 4.4, no `radius`/props/`character_id` columns yet (slices 7-8 add them, `entity_status` with slice 7, `explored_chunk` with slice 6). Token ids are 12 random characters from `[A-Za-z0-9_-]` (a 64-symbol alphabet, so 6 uniform bits per character, 72 bits) from `std/sysrand`, collision-checked against every loaded token. The token payload rules 6.1 left open are fixed in 6.1 ("Token payload rules"); the load-bearing ones are: plain tokens only, `radius`/`props`/`character_id` refused `invalid` rather than dropped, effective radius = the scene default, the wire `name` is always the descriptive name, `controller: null` is the only GM spelling, and `explored` on connect is RLE rows. **Modules**: `server/tokens.nim` (records, validation, write-through persistence with FULL for GM authoring and NORMAL for moves), `server/vision.nim` (per-player polygons, explored set, the one copy of the visibility rule), `server/views.nim` (the single egress: typed `GmView`/`PlayerView`, then frames, then the per-connection diff), `server/worldmap.nim` (records -> geometry/move-rule inputs), `server/faults.nim` (test-only hook). `main.nim` holds the state (`tokens`, `visions` per player, `known` per connection keyed by app connId) and never builds a state frame itself, so raw world state has no path to a socket outside the egress (2, 10.1). **Egress timing**: a mutation's ack and its per-recipient diffs are enqueued under the global lock, in that order, and every frame is built from the state at enqueue time (mummy's `send` only appends to its deque, 4.3). Exact per-connection ordering between two concurrent mutations, and the coalescing that keeps that cheap, stay the M5 outbox. **Runtime rules**: polygons exist only for tokens a player controls that carry the `vision` flag, with the token's `vision_radius` or the scene default; only their token centres count for visibility; explored is the union of `cellsTouched` over history, only grows, drops cells outside the world, and the `fresh` set is cleared after one egress fan-out. A door closing pushes tokens aside (5.5) and persists the new positions; `stuck`/`squeezed` are slice 7's status model, so a failed push leaves the token overlapped and unflagged for now. `token.move` maps the move rules to the wire exactly: `ack {pos}`, the uniform nack for locked/over-cap/collision and for an out-of-bounds GM move, and `not-allowed` (players, one code for unknown and not-yours) or `not-found` (GM) before any geometry runs; accepted moves are persisted with NORMAL durability. `hello` carries the scene block for every named recipient and `extra` for the GM; an unnamed player still gets only `proto, role, me` and is not fed any state at all (6.3), so slice 5's player-side acceptance is reached through a harness fixture that writes the name into the DB before connecting: `player.setname` is slice 8 (#23) and the unnamed gate itself is pinned by `tools/tokens.test.mjs`. **Tests** (10.1, 10.3): `tools/leak.mjs` builds a 27-group scene over the real wire (enter/leave by movement, a closed door, create/remove, `gm_only`, a controller hand-over, another player walking in and out, a wall added and removed, a door push) and records every frame; `tools/leakcheck.nim` replays it with the GM socket as truth, recomputes polygons from `geometry.nim`, and checks explored against both that recomputation and an independent clear-segment sampler; A and B both pass with zero failures. `tools/fault.test.mjs` catches `hidden`, `gmOnly`, `walls`, `withhold`, `otherOwner`, `otherVision`, `otherExplored`, `noremove` and `explored` under their exact class sets and asserts the shipped binary contains no `LEAK_FAULT` string. `tools/probing.test.mjs` re-runs T8/H26 over WS: over-cap probes give the one uniform nack, two scenes differing only beyond cap + token radius produce identical reply sequences over 90 hostile probes inside the 6.4 burst, and a wall inside that bound does change the replies. Nim units: `tests/ttokens.nim`, `tests/tvision.nim`, `tests/tviews.nim`. Mutations aa-af pin the view rule, the egress `token_gone`, the absence of GM-only fields in a player frame and the "explored only grows" rule. - -Owner also decided 2026-11-15 [FIXED (owner-delegated, 2026-11-15, #22)]: token details (M3 slice 7). Schema is migration step 6 (`token details`): the three prop buckets on `entity` and `entity_status` (4.4). Intents: `token.resize`, `status.set`, `status.clear`, `prop.set`, `prop.unset`, all GM-only in v1 (6.1; owner-bucket writes by players come with FFF actions, 9, and are a permission change, not a redesign). The payload rules 6.1 left open are fixed in 6.1: the status set and its `source`, the three-bucket caps (64 keys, 1..64-char keys, 8 KB values, per bucket), the property-schema registry (empty at start with a permissive fallback, so v1 accepts any key in any bucket because 8 says the server never interprets props; a registered key is enforced) and the grow-push search. **Modules**: `server/props.nim` (buckets, caps, registry, parsing), `server/moverules.nim` (the status model replaces the M2 `blocked` bool: `stuckWalls`/`squeezedWalls` are the `walls` source, `locked` is the caller's "any entry" bit, per-token radius everywhere, `resizeToken` with the grow search, `placeToken` for GM placement/move), `server/text.nim` (the one copy of the 6.5 text rule, shared by names and prop keys), `server/tokens.nim` (statuses and props on the record and in the row), `server/worldmap.nim` (`ruleToken`/`ruleWall`/`applyOutcome`/`wallsStatuses`: the bridge between the record's entry set and the rules' two booleans), `server/views.nim` (typed per-recipient statuses and buckets). **One rule, one place**: every wall/door edit and every resize runs the pure rules on a snapshot taken *before* the write, then the write, then `applyRuleOutcome` (positions and `walls` statuses in one `NORMAL` transaction, memory after COMMIT); `token.create` computes the placement status before writing the row, so a new token is born with `stuck` if it lands on a wall. Status sources are owned by different layers on purpose: the rules never see `GM` entries, the record never derives `walls` entries. **Tests** (10.1, 10.3): `tests/tprops.nim` (caps, key/value rules, registry enforcement, set/unset, clone isolation), `tests/ttokens.nim` (radius, buckets, statuses round trip, the FK cascade), `tests/tmoverules.nim` (per-token radius, shrink/grow/squeeze, the no-crossing rule, the source independence), `tests/tviews.nim` (bucket and source filtering, one `token` frame per change), `tools/details.test.mjs` (the five intents' acks and codes, grow push and squeeze, stuck/clear, prop caps, who reads which bucket, restart equality), plus the leak scenario's prop/status groups and the `OWNER_PROP`, `GM_PROP`, `STATUS_SOURCE` faults. Mutations am-au pin the bucket filter, the per-bucket cap, the status set/clear, the shrink/grow rules and the push. See 4.4, 5.5, 5.6, 6.1, 8, 10.3. - -Owner also decided 2026-11-15 [FIXED (owner decision), #22]: the property-schema registry of 6.1 is confirmed as the agent specified it — v1 ships the registry **empty with a permissive fallback** (`pkAny`), so any key is accepted in any bucket and only a registered key is enforced, which matches 8's "the server never interprets props in v1". **Strict mode comes with the FFF seam (post-v1)**, where the rules module registers every key it uses; flipping the fallback is a one-line change and no v1 payload, wire shape or test changes. **[amended 2026-11-15, #41: the v1 registry is no longer empty — `height` and `eye_height` are registered (`number`, `gm`, 5.7); the rest of this entry stands]**. The rest of the #22 token-details decisions stay owner-delegated. - -Owner also decided 2026-11-15 [FIXED (owner-delegated, 2026-11-15, #23)]: characters and names (M3 slice 8). Schema is migration step 7 (`characters`, 4.4): `character`, `name_reveal`, `encountered`, plus `entity.character_id` and `entity.reveal_all`. The decisions 4.4 leaves open are recorded there and the wire rules in 6.1 ("Character and name payload rules"): one id namespace for tokens and characters, an owner that never dangles (`player.remove` transfers to the GM first), an encountered entry with no FK that outlives everything, a linked token that stores `''` names, and `character_id`/`cprops` on the token frame with the ownership rules of 6.1 leak notes 2-3. **Modules**: `server/characters.nim` (records, the name rule, the reveal set, the encountered snapshots, their rows), `server/views.nim` (the typed character and encountered views plus the token-frame additions), `server/tokens.nim` (`characterId`/`revealAll`, the linked-token validation and `sqlLitId`), `server/text.nim` (`normalizedPlayerName`, `validPlayerName`, `sameName`), `server/auth.nim` (`allPlayers`, `nameTaken`, `setName`, `renamePlayer`), `server/main.nim` (`recordEncounters` in every mutation path before the ack, the roster fan-out, `sendHello`/`resync` for `player.setname`). Also fixed here: `protocol.withN` deep-copies before stamping `n`, because the stored diff base was being mutated and every state frame was re-sent on every mutation. **Tests** (10.1, 10.3): `tests/tcharacters.nim` (the name rule, the reveal set, the encounter snapshot, validation, persistence incl. the GM transfer and the `in-use` count), `tests/tviews.nim` (character frames, the owner/non-owner split, `cprops`, `character_gone`, the encountered diff), `tools/characters.test.mjs` (the acceptance group of 13), the leak scenario's ten character/name/encountered groups and the `ACTUAL_NAME`, `CHAR_LIST`, `CONTROLLER_CHANGE`, `CHAR_OWNER_PROP` faults. Mutations av-b4 pin the name rule, the encountered snapshot, the linked-token validation, `in-use`, the GM transfer, the snapshot rename and the `cprops` bucket. See 3.1, 4.1, 4.4, 6.1, 6.3, 6.4, 6.5, 8, 10.3, 13. - -Owner also decided 2026-11-15 [FIXED (owner-delegated, 2026-11-15, #21)]: explored persistence (M3 slice 6). Schema is migration step 5 (`explored`): `explored_chunk` keyed by `(player_id, scene_id, cx, cy)` with a 512-byte blob, both FKs cascading (4.4). Chunk format and size are fixed at 64x64 cells = 512 B, row-major LSB-first bits, `(cx, cy)` = chunk coordinates; the layout is pinned by tests and re-read independently by the Node harness. **Write timing**: a mutation writes only the chunks its refresh dirtied, each encoded from the whole explored set, with `NORMAL` durability; a move writes position and chunks in one transaction, a GM authoring write adds a second `NORMAL` chunk transaction under the same lock, both before the ack — the two commits are deliberately not atomic with each other, and the only loss they can cause after a crash is cells no client was acked about, which the next refresh re-adds. Measured: 0.015 ms avg / 0.035 ms p99 per chunk write, 0.7 ms avg / 1-2 ms p99 per move ack (4.3's budget is untouched). **Load**: `explored.restore` fills every player's set at startup from the chunk rows and logs `explored_loaded players= chunks=`; polygons stay recomputed (8). **Tests** (10.1, 10.3): `tests/texplored.nim` (format, whole-chunk encoding, upsert replacement, per-player keying, restore, cost) and `tools/persistence.test.mjs` (fresh-resync round trip, per-player isolation, SIGTERM and SIGKILL restart equality, wall-removal cells surviving after the wall returns, chunk rows decoded independently, move-ack timing, and a schema-4 fixture DB migrated by the real binary). Mutations ag-al pin the bit layout, the chunk coordinate, the restore, the per-player key, the upsert and the dirty-chunk dedupe. See 4.4, 8, 10.3. - -Owner also decided 2026-11-15 [FIXED (owner-delegated, 2026-11-15, #27-#31)]: five M3 correctness and cost fixes found by review, all owner-authorized to land on `main` with a regression test each. (1) **`name.reveal` is per player on disk too** (#27): the persisted snapshot write took only the subject, so every player who had met the subject got the actual name in their `encountered` row and saw it only after a restart; the write is now scoped by `player_id` and a reveal to one player changes exactly one row. `name.reveal_all` keeps all-players scope through the same helper. (2) **`token.update {character_id}` links a plain token** (#29): the link patch now drops the token's own two names, so the candidate satisfies `validToken`; names supplied *with* a link stay `invalid`, unlinking still needs both names (6.1). (3) **One encountered rewrite path** (#30): `characters.rewriteEncountered` takes the subject's `SubjectNames` plus the reveal set and rewrites every matching snapshot in SQLite *and* in `app.encountered` from the 8 name rule, so a rename, a link change and an owner change reach the live list immediately and the DB never disagrees with the wire. The old DB-only `renameEncountered*`/`revealEncountered*` helpers are gone, which is what let the two stores drift. (4) **Egress borrows the world** (#28): `views.Context` now holds six pointers (`contextOf`/`borrow`) instead of owning copies of `scene`, `tokens`, `characters`, `reveals`, `encountered` and `visions`, `playerView`/`gmView` read a `ptr PlayerVision` instead of `getOrDefault`, and a view computes each player's visible-id set once per frame so `grey` is a set test rather than a token scan plus a `PlayerVision` copy per encountered entry. Measured on this build's types (debug, 6 players, 40 encountered entries, 40 world tokens): context construction 0.227 ms / 4.87 ms at 16384 / 262144 explored cells before, 0.008 us after; one `getOrDefault` of a `PlayerVision` 28.8 us / 591 us before (gone); a GM egress pass 8.0 ms / 142.8 ms before, 0.79 ms / 0.80 ms after; a player pass 1.45 ms / 25.7 ms before, 0.32 ms after. Behaviour is unchanged and pinned by `tests/tviews.nim` (identity: a borrow sees a later in-place mutation; six pointers, no container; both sizes inside the M5 7.5 ms budget) plus the unchanged leak/fault suites. (5) **One scene read per request** (#31): `tileGate` reads `app.scene` once under `dbLock` and uses that local for the URL parse, the explored check and the redirect; `checkScene` reads the scene id under the lock; `scene.set` patches under the lock; the wall/door handlers capture `sceneId` inside their lock for the log and the effect frame. `tests/ttiles.nim` pins that one record gives one whole answer, and `tools/tiles.test.mjs` pins the handler shape (source scan) and interleaves 20 `scene.set` + wall edits with 200 tile fetches (only whole tiles, no crash). **Tests added**: `tests/tcharacters.nim` (per-player reveal row, one rewrite path, link handover), `tests/ttokens.nim`-style `patched` unit (in `tcharacters.nim`), `tools/characters.test.mjs` (link via update end to end), `tools/restart.test.mjs` (three named players + per-player reveals across SIGTERM/SIGKILL, with a direct `encountered` row assertion and a name oracle; a mid-session rename for a plain token and a character), `tools/leak.mjs`/`leakcheck.nim` (a second player meets the same subject; `STALE_NAME` pins each entry's expected name), `tests/tviews.nim` and `tests/ttiles.nim` as above. Mutations e1-e3 and the repointed b2 pin the reveal scope, the live snapshot update and the link handover. - -Owner also decided 2026-11-15 [FIXED (owner-delegated, 2026-11-15, #25)]: the M3 finish line. `scene.set` is built as the 29th and last catalogue intent; its payload rules are in 6.1 ("Scene payload rules"), with the decision that `hello` also resets the server-side per-connection diff base (otherwise a resync after `hello` would skip state the client just reset). The two missing accept groups are built: **restart** = `tools/restart.test.mjs` (full 6.3 resync equality over SIGTERM and SIGKILL, every CRUD path) and **logs** = `tools/logs.test.mjs` (every key, session cookie and session hash absent from both runs' log, with a `LEAK_FAULT=keylog` negative control). `tools/groups.mjs` + `tools/groups.test.mjs` map the nine groups of 13 to their named proving tests, so the checklist cannot silently go stale. Fixture clean-up (acceptance 5): `tests/fixtures/scene.json` loses the stale `tileSize: 256`, the scene-wide `tokenRadius` (now a fixture constant, the server has per-token radius, #4) and its index token ids (`A`/`M1`); the geometry/corpus fixture keeps its walls, radii and positions. The `blocked` boolean is already gone from code (`stuck`/`squeezed`, #4). **M3 acceptance checklist (all nine groups, `devbox run test`, measured on the final tree):** - -| # | group (13 M3 Accept) | proving test | status | -|---|---|---|---| -| 1 | leak+fault | `tools/leak.test.mjs` (leak A/B), `tools/fault.test.mjs` (exact class sets incl. `ACTUAL_NAME`, `CHAR_LIST`, `CONTROLLER_CHANGE`, `CHAR_OWNER_PROP`) | pass | -| 2 | tiles | `tools/tiles.test.mjs` (oracle sweep through the test nginx, refusal/path matrix, no committed PNG) | pass | -| 3 | probing | `tools/probing.test.mjs` (hostile client over WS, bounded replies) | pass | -| 4 | protocol | `tools/protocol.test.mjs` (proto, unknown type, envelope, flood, rate limit, 64 KB, cap, closing) | pass | -| 5 | auth | `tools/auth.test.mjs` (cookie flags, Origin, devices, key replace, remove, gm-key) | pass | -| 6 | characters and names | `tools/characters.test.mjs` (names, reveals, reassign, in-use, encountered, status source) | pass | -| 7 | restart | `tools/restart.test.mjs` (full state, all CRUD, SIGTERM and SIGKILL) | pass | -| 8 | persistence | `tools/persistence.test.mjs` (chunk round trip, migration, restart, write cost) | pass | -| 9 | logs | `tools/logs.test.mjs` (keys/sessions/hashes across two runs, `keylog` control) | pass | - -Out of M3 accept, unchanged: concurrency (M5) and the 127.0.0.1 bind check (M6 deploy) [FIXED, #12]. **Measured 2026-11-15 on the final tree:** `devbox run test` exit 0 (Nim suite all pass; 103 Node harness tests, 0 fail) and `devbox run mutation` exit 0 (control passes, all 63 mutations fail >= 1 expected test, the new `d3` included; log `results/mutation.log`). See 6.1, 10.3, 10.4, 13. - -Owner also decided 2026-11-15 [FIXED (owner decision), 2026-11-15, #41]: the height model. Heights are metres, decimal; map distances stay px and no map scale is introduced, because see-over compares heights with heights (research #39 3.3). `height` and `eye_height` are properties, not fields: a character carries the base value, a plain token must carry its own (`token.create` without one is refused), a linked token uses the character's value and may carry a temporary on-map override that never writes the character. Effective token height = token override, else character, else the plain token's own. Eye height follows the same pattern; if nobody set one by hand anywhere it is 93% of the effective token height and follows changes live [93% FIXED (owner-delegated)]. A wall is full height (nobody sees over it) unless the GM gives it one in metres; existing walls are unchanged. Both keys live in the `gm` bucket, so players see only the outcome, their sight. They are the first two keys of the property-schema registry (`number`, `gm`), so "the server never interprets props in v1" becomes "the server interprets only registered keys used by core sight rules". Limits [FIXED (owner-delegated)]: all heights > 0; `height` <= 100 m; `eye_height` <= 100 m and may exceed `height`; a wall's height > 0 and <= 100 m. Deferred: the target's height in see-over (#44) and the height existing tokens and characters get at migration (#49); wall kinds were settled afterwards by #42 (5.8, v0.22), and what a low wall hides (#44) and thickness (#45) were settled afterwards in 5.9 and 5.10. See 5.7, 6.1, 8, 9. - -Owner also decided 2026-11-15 [FIXED (owner decision), 2026-11-15, #42]: the wall model. A wall's behaviour is **independent switches**, and a named kind is only a **preset** over them: never a fixed kind enum in the record, and never client-interpreted free flags (the client may send a preset name; the server expands and validates it). v1 switches are `blocks_sight` and `blocks_movement` plus the door settings `door`, `open`, `secret`, `locked` and one direction field `sight_dir` (`both|left|right`); no light or sound axis. Direction is **sight only**: movement is two-way governed by its switch. A door is a wall with `door` set and independent `open`/`secret`/`locked` settings, not a separate kind or a state enum, and `door.set` keeps working as "set `open`". The switches describe the closed wall: an open door blocks neither sight nor movement. A secret door is always closed and two-way (`open:true` or `sight_dir != both` on it is `invalid`), so it can look exactly like a solid wall. `secret` and `locked` are GM-only and never observable to a player in any form; the obligations are byte-identical player frames and refusals for a closed secret door against a solid wall, and one uniform move nack. v1 presets (one-drag editor defaults and the GM's label) are `wall` (default), `door`, `secret door`, `locked door`, `terrain` (blocks movement, not sight: railing, bushes) and `one-way wall`; windows were left to #47, which added the `window` preset (2026-11-16), and "blocks nothing" is not a preset. The record stores the switches; `kind` survives on the wire as a derived read-only label (exact preset match, else `custom`), never an input and never the authority [FIXED (owner-delegated)]. The switches are typed validated fields on the record and in the payloads, not entries in the never-interpreted `flags`; columns vs one validated object, and the existing-row migration, are #49's [FIXED (owner-delegated)]. The GM editor has a preset row plus an **advanced** toggle that exposes the raw switches [FIXED (owner decision)]. Thickness and height compose through the switches (a wall with `blocks_sight=false` never reaches the sight predicate) and are decided in 5.10 and 5.9. See 1, 3.1, 5.1, 5.5, 5.8, 6.1, 7.4, 8, 14. **[Superseded 2026-11-16, Q6/#48: the preset list is `wall`|`door`|`window`|`one_way`, `terrain` is dropped, and `kind` is derived by shape rather than by exact preset match; the switch model itself stands.]** - -Owner also decided 2026-11-15 [FIXED (owner decision), 2026-11-15, #44]: low walls. A token is visible iff **its top clears every sight wall the line from the viewer's eye crosses**, strictly: the sight line's height at the wall (`h_e + (h_t - h_e)·d_W/d_T`) must exceed the wall's height, and one failing wall hides it. The target's own height therefore matters (a giant's head over a fence, a crouched figure hidden next to the wall it would clear from further away); there is no adjacent-visible exception and no distance rule. The visibility polygon stays **strict**, so the floor behind a low wall stays unexplored and black, no tile is sent, and a visible token may stand on a black cell; no per-cell height is tested anywhere. Movement never reads height: `blocks_movement` alone decides, so a knee-high wall with the switch on stops a walker. Players get a binary answer and the whole token, with no clipping and no cover percentages (a rules-engine judgement, still a non-goal). The GM gets a GM-only **who-sees-it** view: per token, which player(s)/characters see it and its visible fraction (the share of its height above the highest blocking sight line, 100 % unobstructed), derived from data the GM already receives, never on a player wire, its panel shape M4's. Knobs delegated: strict comparison with equality hidden, evaluated at the wall near face (a thick wall: every crossed face, 5.10, #45); every crossed wall must clear; the hook sits at `visibleTo` as `insideAny or predicate` with heights never entering `visibilityPolygon`; no "see-over" switch on the wall; the hidden band's cells and tiles are oracle-*maybe*, a band-hidden token gives no frame, name or churn, and the leak checker's clear-line oracle gets its own height test. See 5.7, 5.8, 5.9, 7.4. - -Owner also decided 2026-11-15 [FIXED (owner decision), 2026-11-15, #46]: secret and locked doors. (1) **Player door opening is out of v1** [FIXED (owner decision)]: only the GM opens or closes a door; `door.set` stays G-only and a player sender is `not-allowed` at the role step (6.5) whatever the door's settings. Player-opened doors, lock refusals addressed to players and player discovery of secret doors (searching, revealing, finding a way in) are future effort, not v1 and not this map; the lock is GM authoring state. (2) **A locked door does not open** [FIXED (owner decision)]: `door.set open:true` on a door with `locked` is `invalid`, exactly like a secret door, and the GM unlocks first (editor hint "locked: unlock first"); any write that would store `open:true` with `locked` or `secret` — `wall.add`, `wall.update`, a preset expansion — is `invalid`; closing a locked door is allowed. Otherwise a locked door is an ordinary closed door. (3) **The equivalence oracle** [FIXED (owner-delegated)]: `tools/doors.test.mjs` is a new Node accept group (built-ins only, 10.4) in the shape of `tools/probing.test.mjs` — two servers, fresh state, one identical script, scenes differing only in one segment (solid wall vs secret door; solid wall vs secret+locked; closed door vs locked closed door), player frames and per-tile statuses identical after canonicalisation with **no** normalisation; the positive control is the same script against an open door, which must differ; the negative control is `LEAK_FAULT=secretgap` (a secret door not blocking the player-facing computation), which must fail the doors group while a clean build passes and ships no fault string; `tools/leakcheck.nim`'s banned-key scan grows `secret`, `locked`, `door`, `blocks_sight`, `blocks_movement`, `sight_dir` (and #49's names) into `WALLDATA`, with a new fault leaking one door setting key and asserting exactly `WALLDATA`; a GM `door.set` on a secret or locked door is `invalid` and a player `door.set` is `not-allowed` for every door; timing and size side channels (T11) stay accepted and untested. See 1, 3.4, 5.8, 6.1, 6.5, 7.4, 10.3. - -Owner also decided 2026-11-15 [FIXED (owner decision), 2026-11-15, #45]: thick walls. (1) **Placement** [FIXED (owner decision)]: `position` is `center` (default), `left` or `right` of the drawn `a -> b` line, using 5.8's side convention; the line is the room's interior, the body grows outward, and a flip changes only the body, never `a`/`b`. (2) **Body** [FIXED (owner decision)]: a rectangle `|ab|` x `thickness` with square ends, offset per `position`; `thickness: 0` is today exactly and every existing wall migrates to zero and unchanged. It is opaque floor: never in a player polygon, never newly explored, no tile newly revealed under it. (3) **One shape** [FIXED (owner decision)]: sight footprint and movement collider are the same exact rectangle, sight as the 4-face quad hoisted per wall edit (#43 measured) and movement as exact circle-vs-rectangle distance with a centre inside the body counting as overlap; one rectangle-distance primitive serves `pathClear`, the overlap/`stuck` check, the door push, `pushOutOfWalls` and resize; a `blocks_sight:false` wall contributes nothing to sight, body included, while its collider keeps the thickness. (4) **Default thickness** [FIXED (owner decision)]: a new wall starts at the GM's last-used thickness, 0 in a fresh editor. (5) **See-over** [FIXED (owner decision)]: 5.9's line must clear **every crossed face** of the body, near and far, strictly; the faces coincide at zero thickness, so 5.9 stands. (6) **Edits never push** [FIXED (owner decision)]: a thickness change, flip or move that covers a token leaves it in place and `stuck`; only a door close pushes. (7) **A viewer inside a sight-blocking body sees nothing** [FIXED (owner decision)]: empty polygon until it leaves. (8) **No dead end** [FIXED (owner decision)]: v1 walls stay straight rectangles (a cave is a chain of walls; joints overlap with a small outer notch and no crack), the shape sits behind one seam, and curved/freeform walls and tracing walls from a map image are future effort. Delegated: px thickness `0..256`; the `(-dy, dx)` side formula; joints by overlap, no mitre; field names `thickness` and `position`; the last-used default as editor state. Downstream: thick doors and push geometry #50, one-way body occlusion #47, wire/schema/migration #49. See 1, 5.1, 5.3, 5.5, 5.7, 5.8, 5.9, 5.10, 6.1, 7.4, 8, 13. - -Owner also decided 2026-11-16 [FIXED (owner decision), 2026-11-16, #47]: windows and one-way walls. (1) **Window** [FIXED (owner decision)]: v1 has no sill and no top — a window is see-through along its whole drawn length, height unused, drawn as its own wall piece inside a wall (`wall | window | wall`, like a door), with two forms: fixed (no pass) and opening (door settings; pass when open). The editor gets a `window` preset. No distance-limited window. (2) **One-way** [FIXED (owner decision)]: a thick one-way wall's body is opaque floor from **both** sides — no player polygon, never explored, no tile — and only pass-through past the wall is directional; explored cells and tiles differ per side with no new mechanism (per-viewer sight), and explored only grows, so a flip never takes anything back. (3) **Editor** [FIXED (owner decision)]: a one-way wall shows an arrow at its middle pointing the way the view goes (from the seeing side toward the watched side) plus a flip that swaps `sight_dir` without moving `a`/`b`; GM-only, never on a player wire. (4) **`left` wording** [FIXED (owner-delegated)]: `sight_dir:"left"` means a viewer on the left side — the `(-dy, dx)` normal of `a -> b`, the same side as `position` — cannot see across; a viewer on the right sees across. The one-way preset defaults to `left`; `sight_dir != "both"` with `blocks_sight:false` is `invalid`; `left` and `right` both derive `one_way`. (5) **Filter shape** [FIXED (owner-delegated)]: hoisted viewer-independent faces plus one sign test per one-way wall per viewer inline in the fan, no per-viewer list copy (the prototype's ~0.15 ms per viewer per frame, times tokens, rejected). (6) **Windows as a kind** [FIXED (owner-delegated)]: the `window` preset is the opening form and derives `window`; the fixed form's switches are `terrain`'s and derive `terrain` (the rules are identical), with no second preset and no new kind — the editor may hint at it. Downstream: the wire/schema/migration and the preset list are #49; terrain stays #48. Out of scope for v1: windows with a real sill and top height, and light through windows (future effort with lighting). See 1, 5.1, 5.8, 5.9, 5.10, 6.1, 7.4, 8, 10.3, 14. **[Superseded 2026-11-16, #48: `terrain` is dropped, the fixed form is a window, and the presets are four.]** - -Owner also decided 2026-11-16 [FIXED (owner decision), 2026-11-16, #48]: terrain walls, and the principle behind the answer. (1) **`terrain` is dropped, everywhere** [FIXED (owner decision)]: no preset, no derived kind and no stored name. The switch set `blocks_sight:false`, `blocks_movement:true`, no door, is a **fixed window** and derives `kind:"window"`. A railing, a bush, a pit edge and a fixed window are one object with one switch set; they differ only in the GM's `label`. This supersedes #42's and #47's `terrain` preset/kind (and #47's fixed-form wording) and is itself an application of the new principle. (2) **Principle** [FIXED (owner decision)]: "Do the most with the fewest things: one object, switches on top, names are only labels" — recorded in §1 and to be applied to future cards. (3) **Four editor presets** [FIXED (owner decision)]: `wall` (default), `door`, `window`, `one_way`; `secret` and `locked` are checkboxes on any door, including an opening window (`door` + `blocks_sight:false`), and keep #46's semantics (GM-only, a locked door refuses to open until the GM unlocks, never observable to a player). (4) **Preset names and kinds resolved** [FIXED (owner-delegated)]: `secret_door` and `locked_door` are **removed** as wire preset names (the wire takes `wall|door|window|one_way`; #49 implements), and the derived kind list is `wall`, `door`, `window`, `one_way`, else `custom`, derived by shape (window first, then one-way, then door, then wall) with `secret`/`locked` as flags that never change the label. A secret door also requires both block switches on and `sight_dir:"both"` (a secret window would show itself); a locked window is allowed. (5) **Player marker** [FIXED (owner decision); name and shape delegated]: a new wall switch `player_marker`, on by default for the `window` preset and off for every other preset (GM may toggle it on any wall); an invisible barrier is simply a window with the marker off. It is the **first and only wall-derived data on a player wire**, an exact exception to 3.1: once any point of the wall's visible extent has entered that player's vision polygon, the player receives an anchor (the wall's drawn midpoint; a thick wall's midpoint is inside its own opaque body, so the gate is the visible extent, not the midpoint in the polygon) and its own opaque marker id, and **nothing else** — no type, kind, open/closed, direction, label, thickness, height or wall id; the client draws the window icon. The marker is per-player memory like explored: persisted, survives disconnect, never lost to LOS or a door, and retracted only when the GM removes the wall, clears `player_marker`, makes it not a window, or moves its geometry; a moved wall re-earns its marker only when the new geometry is seen. (6) **Wall `label`** [FIXED (owner-delegated)]: every wall may carry an optional GM-only free-text `label`, at most 64 code points (the 6.5 text rule), no behaviour, never on a player wire and in `BannedAlways` (`WALLDATA`). (7) **No other hint** [FIXED (owner decision)]: players get no other sign of a barrier; a refused move stays the uniform nack. (8) **Out of scope** [FIXED (owner decision)]: per-wall material (stone, wood, glass) waits for the lighting effort, alongside sill/top and light through windows; difficult terrain, movement cost and pit/fall semantics are rules-engine work, not wall behaviour. Downstream: the preset set, `player_marker`, `label` and the player `marker` message are inputs to #49 (wire/schema/migration); locked/secret as door checkboxes and window doors are inputs to #50. See 1, 3.1, 3.4, 5.1, 5.8, 5.9, 5.10, 6.1, 7.4, 8, 10.3. - -Owner also decided 2026-11-17 [FIXED (owner decision), 2026-11-17, #50]: door geometry. (1) **The door leaf is the wall's own body** [FIXED (owner decision)]: a door is a wall like any other, and its leaf is the 5.10 body rectangle with the same `thickness` and `position` fields — no separate leaf inside a deep opening, no clamp to the neighbouring pieces. The jambs are ordinary walls, so the doorway is the gap between wall pieces. A thick door bulges out of its doorway or leaves a step behind the jambs, exactly as drawn (authoring, not a rule), and a deep opening between thick jambs keeps the tunnel/keyhole view accepted in #43. Opening and closing add and remove that body and nothing else: no swing, no slide, no hinge, no arc, and an open door is absent from sight and movement as today. (2) **The close push** [FIXED (owner decision)]: each token whose centre is within `r` of the door's **body** is pushed out of the side its centre is on, by the minimal distance that ends `>= r` from the body (+ `PushEps`); a centre inside the body takes the side of `prev` (its position before the most recent move or push), and the left side of `a -> b` when that is undetermined; if the first side's position is invalid (out of bounds or within `r` of any blocking body) the other side is tried; if both are invalid the token stays and gets `squeezed`, and the door still closes. No axial slide, no chain, no retry. Each token is pushed independently, tokens never block tokens, and scene order only rewrites `prev`. Edits never push (5.10) and height never enters (5.9). (3) **Delegated and picked** [FIXED (owner-delegated)]: within the body's axial span the target is the face offset by `r`; past an end it is the offset from the nearest end corner **keeping the along-axis coordinate**, i.e. today's `foot + n·sqrt(r^2 - e^2)` generalised to the end face — a radial displacement from the corner was rejected because it also moves the token along the axis and would break the zero-thickness gate. A centre "inside the body" for the side test means inside the body or past an end but within the body's normal span, which reduces to today's centre-on-the-line test at zero thickness. The target and the validity check use the same rectangle-distance primitive as the collider (other thick bodies included), and `PushEps` = 1e-6 px is reused. **Zero thickness must return byte-identical values to today's `pushFrom` on the same inputs**, and the existing push tests are the regression gate, unchanged (10.3). (4) **Settled consequences** [FIXED (owner decision)]: a locked door and an opening window push exactly like a plain closed door; a fixed window (`door:false`) never closes, so it never pushes; a secret door pushes exactly as a solid wall, so #46's equivalence holds for thick doors too; the independent-per-token, no-token-collision, `prev`-rewriting order rule above is final and not a later "fix". (5) **Downstream**: #49 needs **no new wire field for doors** — the leaf is the existing `thickness`/`position` body and the existing switch set, and an open door changes no geometry, only `open`. See 5.4, 5.5, 5.8, 5.10, 10.3. - -Owner also decided 2026-11-17 [FIXED (owner decision), 2026-11-17, #49]: the wall record's wire format, storage and migration. (1) **Wall height is a typed wall field** [FIXED (owner decision)]: metres, optional, `> 0` and `<= 100`, absent/`null` = full height; GM-only, carried on the GM `wall`/`walls` frames and never on a player frame (`WALLDATA`). This resolves the old contradiction — 5.7's "no dedicated column and no wire field" (narrowed there with a dated tag to tokens and characters, which have `props` buckets; a wall has none), 6.1's wall frames (which already carried the other fields) and 5.8's "no behaviour in `flags`". The property registry is unchanged: still `height` and `eye_height` for tokens and characters. (2) **Migration** [FIXED (owner decision)]: every existing token and character gets `height: 1.8 m` in `props_gm` (the 93 % eye rule is unchanged and `eye_height` is not written); every existing wall migrates to today's behaviour exactly — `thickness 0`, `position center`, `blocks_sight`/`blocks_movement` 1, `sight_dir both`, `player_marker` 0, `label` NULL, `height` NULL, `secret`/`locked` 0, `kind='door'` -> `door=1` with the same `open`, `kind='wall'` -> `door=0`. No real user data exists (pre-M4), so correctness is fixture/history hygiene plus byte-identical behaviour gates (5.8 player frames, #50 zero-thickness push). (3) **Storage: typed columns with CHECK constraints** [FIXED (owner-delegated)]: one column per field, CHECKs for the switch invariants, `flags` kept for uninterpreted GM data; chosen by precedent (interpreted data is always a column, `flags`/`props_*` are for unread data), because CHECKs can reject an impossible switch set, and because `loadScene` then has no second parse/validate path. 5.8's "one object" is the domain/wire object; the columns are its storage. (4) **Migration step 8, forward-only** [FIXED (owner-delegated)]: the `Migration` entry gains a `data` hook for the height backfill; the `wall` table is rebuilt and the legacy `kind` column is **dropped** (`kind` is output-only derived); the rebuild is preferred to `ALTER TABLE ... DROP COLUMN` because it must drop `kind` and add six NOT NULL CHECKed columns atomically and SQLite refuses to drop a column named in a CHECK. (5) **Wire** [FIXED (owner-delegated)]: `wall.add`/`wall.update` carry `thickness`, `position`, `height`, `label` and the switches; a preset XOR raw switches, raw switches patch only what is present, a preset replaces the whole switch set, and a preset never implies geometry; `wall.update` stays absolute and `door.set` unchanged; add, update and the M6 UVTT importer share one expand-and-validate path; `walls`/`wall` gain `height` and keep the derived `kind`. (6) **`proto` 2** [FIXED (owner decision)]: the input `kind` disappears and an old client's `{"kind":"door"}` would silently create a solid wall, so the version goes up with a 6.2 changelog line; `marker` is the one new server message. (7) **The `marker` message** [FIXED (owner-delegated)]: `{full:bool, set:[{id,pos}], del:[id]}`, mirroring `encountered`; `pos` is the drawn midpoint in integer px; `id` is an opaque per-player 12-character string, never the wall id; emission needs `player_marker` on **and** the wall deriving `window`; the full set goes after `explored` in the 6.3 player order; the GM never receives marker frames (a player's markers are their own memory, like explored); storage is `marker_seen` with cascades on player and wall (and through the scene via the wall). (8) **Label NULL** [FIXED (owner-delegated)]: `label` and `height` are written as SQL literals (`NULL` when absent) by one helper, because db_connector cannot bind NULL and neither `''` nor `0` is a legal value, unlike `encountered.actual_name`'s `''`. (9) **UVTT importer** [FIXED (owner-delegated)]: `thickness 0`, `center`, both blocks on, `sight_dir both`, `player_marker` false, no label/height; a portal is `door:true, open = not closed`; recorded in 6.1/8, no ticket. (10) **Oracles and tests**: `BannedAlways` gains every wall field name and `marker` joins the allowed types; the marker oracle's shape is fixed; the migration gets a schema-7 fixture, the mapping assertions and a byte-identical behaviour gate against a freshly built scene (10.3). See 3.1, 4.4, 5.7, 5.8, 5.9, 5.10, 6.1, 6.2, 6.3, 8, 10.3. - -Owner also decided 2026-11-17 [FIXED (owner decision), 2026-11-17, after review of `docs/ANALYSIS.md`; review in `docs/ANALYSIS-review.md`]: four decisions and one process note. (1) **Build order**: thick walls (5.10, #45/#50) and wall/token heights with see-over (5.7, 5.9, #41/#44) stay FIXED design but are **built after the first playable M4 client and a phone playtest**; the v1-first build is thin walls with the 5.8 switches, doors, secret/locked, windows, one-way and player markers; the #49 schema lands complete now with `thickness 0`, `position center`, `height NULL` defaults, so the later build needs no migration. (2) **Split DESIGN.md before `/to-spec`**: a short current spec, ADRs in `docs/adr/`, and history out to their own file; tracking issue "Design doc split: current spec + ADRs + history". (3) **Minimum zoom 0.5** for players in v1, which bounds tile requests (about 1.3k at 0.5, about 5k at 0.25); a per-player explored-masked overview image is possible later, not v1. (4) **Walls-sourced statuses accepted**: a player seeing `stuck`/`squeezed` source `walls` is an accepted, documented effect, not a leak to fix; leak note 6 is closed because a refused move already reveals the same fact. Technical, owner-delegated: "close a slow client when lag exceeds a bound" is superseded by **stop feeding on Pong lag and full resync on recovery**; only nginx proxy timeouts close a dead peer (4.3). See 1, 4.3, 5.5, 5.10, 6.1, 6.5, 7.4, 13. +| [0001](adr/0001-server-authoritative-sight-single-egress.md) | The server alone decides what each player sees; all bytes leave through one egress | 2, 3.1, 3.4 | #11, #20 | +| [0002](adr/0002-per-recipient-views-and-diffs.md) | Typed per-recipient views, state-based diffs, per-connection counter | 2, 3.1, 6.4 | #11, #20, #28, #31 | +| [0003](adr/0003-uniform-nack.md) | A refused move carries only the old position, never a reason | 5.5, 6, 6.5 | #11, Q18 | +| [0004](adr/0004-opaque-random-token-ids.md) | Tokens get random opaque ids, walls per-scene counters | 8 | #3, #20 | +| [0005](adr/0005-32px-tile-unit-of-disclosure.md) | A 32 px tile is the unit of disclosure; the edge leak is accepted | 3.3, 3.4 | Q4, #7, #24 | +| [0006](adr/0006-wall-switches-presets-labels.md) | A wall is switches; kinds are presets and derived labels | 1, 5.8 | #42, #47, #48 | +| [0007](adr/0007-see-over-per-target-strict-polygon.md) | See-over is a per-target predicate over a strict vision polygon | 5.7, 5.9 | #41, #44 | +| [0008](adr/0008-thick-wall-one-rectangle.md) | A thick wall is one rectangle read by both sight and movement | 5.10 | #45, #43 | +| [0009](adr/0009-open-door-gap-leaf-is-body.md) | An open door leaves only a gap; the leaf is the wall's own body | 5.5, 5.8, 5.10 | #46, #50 | +| [0010](adr/0010-wall-record-typed-columns.md) | The wall record is typed columns with CHECK constraints, not JSON | 4.4, 8 | #49 | +| [0011](adr/0011-proto-2-wall-record.md) | The wall-record change bumps `proto` to 2 | 6.2 | #49 | +| [0012](adr/0012-build-thick-heights-after-playtest.md) | Thick walls and heights are built after the M4 phone playtest | 1, 13 | D1 | +| [0013](adr/0013-minimum-zoom-05.md) | Player zoom-out clamps at 0.5 | 7.4 | D3 | +| [0014](adr/0014-wall-sourced-status-accepted.md) | Wall-sourced `stuck`/`squeezed` visible to players is accepted | 3.1, 5.5, 6.1 | #4, D4 | +| [0015](adr/0015-player-marker-one-wall-fact.md) | A player marker is the one wall fact a player ever receives | 3.1, 5.8 | #48, #49 | +| [0016](adr/0016-chunked-explored-bitmaps.md) | Explored area is stored as chunked 64x64 bitmaps | 4.4, 8 | #21 | +| [0017](adr/0017-bounded-outbox-stop-feed-resync.md) | Slow clients are stopped and resynced, never closed for lag | 4.3 | Q13, #18 | +| [0018](adr/0018-session-not-key-plaintext-keys.md) | Session tokens are not keys; keys stay plaintext and re-showable | 3.2, 6.6, 8 | #6, Q10, Q11, #17 | +| [0019](adr/0019-closing-message-at-mummy-pin.md) | Close reasons ride a final `closing` message at the mummy pin | 3.2, 6.5 | #18 | +| [0020](adr/0020-characters-separate-from-tokens.md) | Characters are records separate from tokens | 8 | #14, #23 | +| [0021](adr/0021-one-global-lock-v1.md) | One global lock in v1; persistence stays inside it | 4.2, 4.3 | #13 | +| [0022](adr/0022-synchronous-normal-full-authoring.md) | `synchronous=NORMAL`, `FULL` around GM authoring | 4.4 | Q12 |