diff --git a/docs/DESIGN.md b/docs/DESIGN.md index f602db6..9252ffe 100644 --- a/docs/DESIGN.md +++ b/docs/DESIGN.md @@ -1,6 +1,6 @@ # FFF_vtt design -Status: draft v0.16, 2026-11-15 (owner decisions recorded in section 14; v0.4 records Q4 (tile_size 32 px), the outbox lock invariant (4.2, 4.3), and the follow-ups in 3.4, 8, 11.1, 12, 13; v0.5 records the M2 move-rule decisions in 5.5 and updates 3.4, 4.2, 5.1, 5.4, 6.1, 7.4, 8, 10.3, 12, 13; v0.6 records #14 (characters and player data) in 3.1, 3.4, 4.1, 4.4, 6.1, 8, 9, 10.3, 13, 14; v0.7 records #6 (players and invites) in 3.1, 3.2, 3.4, 4.4, 6.1, 8, 12, 13, 14; v0.8 records #7 (map tiles) in 3.3, 3.4, 11.1, 13, 14; v0.9 records #9 (test tools) in 2, 10.4, 13, 14; v0.10 records #12 (what M3 done means) in 13, 14; v0.11 records #15 (M3 limits) in 4.3, 6.4, 10.1, 13, 14; v0.12 records #11 (M3 message list) in 3.1, 3.2, 3.4, 4.2, 4.3, 5.5, 5.6, 6, 7.5, 13, 14; v0.13 records the owner review of #11 flags in 1, 3.1, 5.5, 6.1, 8, 14; v0.14 records #17 (getting in: keys, sessions, the auth slice) in 3.2, 4.4, 6.5, 6.6, 8, 11.1, 13, 14; v0.15 records #18 (talking safely: the protocol shell and the `closing` close-reason message) in 3.2, 4.3, 6, 6.1, 6.2, 6.4, 6.5, 10.3, 13, 14; 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. All of Q1-Q24 are RESOLVED or DEFERRED; none OPEN). Audience: the owner and coding agents. +Status: draft v0.17, 2026-11-15 (owner decisions recorded in section 14; v0.4 records Q4 (tile_size 32 px), the outbox lock invariant (4.2, 4.3), and the follow-ups in 3.4, 8, 11.1, 12, 13; v0.5 records the M2 move-rule decisions in 5.5 and updates 3.4, 4.2, 5.1, 5.4, 6.1, 7.4, 8, 10.3, 12, 13; v0.6 records #14 (characters and player data) in 3.1, 3.4, 4.1, 4.4, 6.1, 8, 9, 10.3, 13, 14; v0.7 records #6 (players and invites) in 3.1, 3.2, 3.4, 4.4, 6.1, 8, 12, 13, 14; v0.8 records #7 (map tiles) in 3.3, 3.4, 11.1, 13, 14; v0.9 records #9 (test tools) in 2, 10.4, 13, 14; v0.10 records #12 (what M3 done means) in 13, 14; v0.11 records #15 (M3 limits) in 4.3, 6.4, 10.1, 13, 14; v0.12 records #11 (M3 message list) in 3.1, 3.2, 3.4, 4.2, 4.3, 5.5, 5.6, 6, 7.5, 13, 14; v0.13 records the owner review of #11 flags in 1, 3.1, 5.5, 6.1, 8, 14; v0.14 records #17 (getting in: keys, sessions, the auth slice) in 3.2, 4.4, 6.5, 6.6, 8, 11.1, 13, 14; v0.15 records #18 (talking safely: the protocol shell and the `closing` close-reason message) in 3.2, 4.3, 6, 6.1, 6.2, 6.4, 6.5, 10.3, 13, 14; 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. All of Q1-Q24 are RESOLVED or DEFERRED; none OPEN). Audience: the owner and coding agents. Legend: - **[FIXED]** owner decision, not up for debate here. @@ -258,7 +258,8 @@ explored_chunk(player_id, scene_id, cx, cy, bits BLOB, PRIMARY KEY(player_id, sc - 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). -- Startup: load everything into memory, recompute vision for all players (prototype does, in one transaction) so `vision` is never stale vs walls. +- 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). +- 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. Explored persistence (slice 6, #21) is what will make the reloaded grid survive. - 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). --- @@ -411,6 +412,15 @@ Validation for `wall.*`: `a != b`, both in bounds, `kind` in `wall|door`, `flags - `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. +**Token payload rules [FIXED (owner-delegated, 2026-11-15, #20)]** (6.1 was silent on these; slice 5 builds them): +- Slice 5 is plain tokens only: `token.create` requires `kind`, `pos`, `descriptive_name` and `actual_name`. `radius`, `props` and `character_id` are *known* fields this slice cannot honour and answer `invalid` (silently dropping a GM's field would lose data); `token.update` does the same for `character_id`. `token.resize`, `status.*`, `prop.*` and the character link land in slices 7-8. +- A token's effective `radius` is the scene's `token_radius_default` for everyone (5.6/#4 is `token.resize`, slice 7). Per-token size does not exist yet, so the move rules keep their single scene radius. +- 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. + **Tokens, statuses, props (9)** | t | fields | who | ack ok / extra codes | effects and recipients | @@ -471,7 +481,7 @@ Leak notes (R5 review, #11): (1) `kind` is GM-only because a value like `npc` wo - Breaking change -> bump `proto`, document in `docs/` changelog. ### 6.3 Reconnect and resync -- Reconnect = full resync. After `hello` the server sends, in this order [PROPOSED]: `roster`; GM: `walls`, `character` for all, `encountered` per player (full), then `token` for all; player: `character` for owned, `encountered` (full), `vision`, `explored` (full), then `token` for all visible and controlled. Slice 4 sends the `walls` part: one frame to every GM connection immediately after `hello` (players never get one); the rest of the order lands with slices 5-8. 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`. +- Reconnect = full resync. After `hello` the server sends, in this order [PROPOSED]: `roster`; GM: `walls`, `character` for all, `encountered` per player (full), then `token` for all; player: `character` for owned, `encountered` (full), `vision`, `explored` (full), then `token` for all visible and controlled. 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. `roster`, `character` and `encountered` land with slices 6-8. 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). @@ -654,7 +664,7 @@ Principles carried from the prototype: the checker must be independent of the co - 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. +- **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`, `ACTUAL_NAME`, `CHAR_LIST`, `CONTROLLER_CHANGE` arrive with slices 7-8; `TILE` with slice 9; `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. - **Probing test (T8)**: M2, in-process against the move-rules module (5.5): arbitrary far moves; assertion: facts about walls/doors beyond LOS recoverable from replies <= a bounded amount (step cap), and uniform nack shape. M3: same test over WS with a hostile client (moved from M2). - **Auth tests**: key replace (old key invalid, sessions revoked, live connections closed), remove player (key invalid, characters and tokens pass to GM), one key reused on several devices (Q10 FIXED), Origin mismatch rejected, cookie flags present. @@ -845,3 +855,5 @@ Owner also decided 2026-11-15 [FIXED (owner decision), #18]: close codes at the 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.