From 7b804f4e5ea2075a352ff5dc9b961f65656000a4 Mon Sep 17 00:00:00 2001 From: Davide Cappellini Date: Tue, 17 Nov 2026 22:45:58 +0100 Subject: [PATCH] docs: analysis review and decisions --- docs/ANALYSIS-review.md | 109 +++++++++++ docs/ANALYSIS.md | 405 ++++++++++++++++++++++++++++++++++++++++ docs/DESIGN.md | 20 +- 3 files changed, 526 insertions(+), 8 deletions(-) create mode 100644 docs/ANALYSIS-review.md create mode 100644 docs/ANALYSIS.md diff --git a/docs/ANALYSIS-review.md b/docs/ANALYSIS-review.md new file mode 100644 index 0000000..8659a95 --- /dev/null +++ b/docs/ANALYSIS-review.md @@ -0,0 +1,109 @@ +# Review of `docs/ANALYSIS.md` + +Reviewed by the owner with the agent on 2026-11-17, against `main` at `287859d` (after #49/#50). +`docs/ANALYSIS.md` was written against `409d2c8` / DESIGN v0.27 and is kept unchanged. This file +records the decisions, the corrections to the analysis, and the technical items adopted into the +build list. + +## 1. Owner decisions (FIXED, 2026-11-17) + +### D1 - Build order: playable M4 first; walls/height logic after the playtest + +Thick walls (#45/#50) and wall/token heights + see-over (#41/#44) stay **FIXED design** and are +not cut. They 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 still lands **complete now**: `thickness`, `position` and `height` columns with +"as today" defaults (`0`, `center`, `NULL`) and the #49 migration. The later build therefore adds +behaviour, not a migration. + +ANALYSIS ref: §1.1, §4.5, §7 item 2. Recorded in DESIGN §1, §13. + +### D2 - Split DESIGN.md before `/to-spec` + +The current spec, ADRs in `docs/adr/`, and history move to separate files. Not built yet; a note +in DESIGN §14. Tracking issue: "Design doc split: current spec + ADRs + history". + +ANALYSIS ref: §1.3, §4.6, §7 item 8. + +### D3 - Minimum zoom 0.5 for players + +v1 clamps player zoom-out at 0.5. That bounds the visible tile count (about 1.3k tiles at 0.5, +about 5k at 0.25), which is the cheapest bound on phone tile requests. A per-player +explored-masked overview image is a **possible later** feature, not v1. + +ANALYSIS ref: §4.8, §6.6. + +### D4 - Walls-sourced `stuck`/`squeezed` visible to players: accepted + +A player seeing a `walls`-sourced status learns that some blocking wall touches that token. This +is an **accepted, documented effect**: a refused move already reveals the same fact through the +uniform nack. Leak note 6 (6.1) is **closed as accepted**; no source-free status is added. + +ANALYSIS ref: §4.7. + +## 2. Corrections to ANALYSIS + +- **§4.5 is stale on #49/#50.** It says #49 (wire/schema/migration) and #50 (thick doors and + push) are still open. Both are decided on `main` (#49 in v0.29, #50 in v0.28); thickness, + height and the door leaf are settled design. +- **§4.5, heights in the polygon: wrong.** Height never enters the sight polygon. DESIGN 5.9 + keeps the polygon strict and applies height as a **per-target predicate** (`visibleTo` = + `insideAny or predicate`); 5.10 evaluates it at every crossed face. The oracle-burden point + (leakcheck needs its own height test, band cells are oracle-*maybe*) stands. +- **§4.5, one-way "expensive in the ray fan": overstated/wrong.** #47 chose a per-viewer **sign + test on the hoisted, viewer-independent face list** inside the fan: one cross-product sign per + one-way wall per viewer, no per-viewer copy, no geometry. #43 measured the filter at + +0.15 ms/polygon on 5k sparse (2.8x thin, 0.24 vs 0.08 ms) and 1.1x dense; it is a small + inline predicate, not a fan rework. No separate one-way build item is needed. +- **§6.2, "near-face variant costs about the same as thin walls [measured]": INCORRECT as + applied.** Research §2.2's one-face row (0.174 ms sparse) includes building 5000 offset + segments **inside the timed call** and is an approximation that leaves the far half of the + band visible-ish; hoisted it is thin-like, but it is not the model DESIGN 5.10 needs. The + decided near+caps silhouette has three faces, is observer-dependent and **cannot be hoisted**; + `prototype-wall-sight/cost.txt` (branch `prototype/wall-sight`) measures: + - 5k sparse: thin 0.083 ms; 3-face silhouette per query **0.699 ms (8.4x)**; + 4-face quad per query 0.943 ms (11.3x), hoisted 0.263 ms (3.2x); + - 5k dense: thin 1.254 ms; silhouette per query 7.851 ms (6.3x); + 4-face quad per query 13.229 ms (10.6x), hoisted 12.721 ms (10.2x). + So the near-face route is not thin-priced; the quad is affordable only when hoisted. + DESIGN 5.10's citation "0.26 vs 0.94 ms on 5k sparse" compares hoisted vs per-query **4-face + quad**; the 3-face silhouette is 0.70 ms. The citation is corrected in 5.10 to name the rows. +- **§6.7, thick dense 6-token party 75.6 ms: correct.** Research §2.3: six thick polygons in + one dense recompute = 75.6 ms vs 7.7 ms thin [MEASURED, #39] (about 6 x 12.8 ms quad per + query vs 6 x 1.28 ms thin). The figure is per-query (not hoisted) and it is the stress layout, + as stated. +- Everything else checked against the tree (race §4.1, global lock/transactions §4.2, egress + §4.4, leakcheck non-independence §4.7, tile count §4.8) still holds at `287859d`. Note that + §4.1's quick fix is already in progress on branch `fix/jsonnode-race`. + +## 3. Adopted technical items - build list + +Sizes are S/M/L. "When" uses the owner order: before-M4 / M4 / M5; decisions and later work are +marked. + +| # | Item | Gist | ANALYSIS | Size | When | +|---|---|---|---|---|---| +| 1 | JsonNode race fix + small fixed `workerThreads` | Own/copy intent JSON before it enters the world; build referencing frames under the lock; pin a small worker pool instead of mummy's `10 x cores`. In progress on `fix/jsonnode-race`. | §4.1, §7.1 | S | before-M4 | +| 2 | Circle-segment-per-sector ray test | Each ray tests only the 64-gon segment in its sector; same polygon, same tests. | §4.3, §6.2(1) | S | before-M4 | +| 3 | Per-token polygon cache keyed `(pos, range, wallsVersion)` | A move recomputes one token's polygon, not the player's party; wall edits bump the version. | §4.3, §6.2(4) | M | M4 | +| 4 | Incremental wall-edit refresh by bbox | Recompute only tokens whose vision circle overlaps the edited wall's bbox. | §4.3, §6.2(5) | S | M4 | +| 5 | Angular sweep; keep the old ray fan as oracle | O(n log n) sweep for polygons; the old fan stays in leakcheck as an independent oracle, fixing §4.7's non-independence. | §4.3, §6.2(2-3), §4.7 | M | M5 | +| 6 | Session cache + tile gate off the global lock; explored as bitmap | In-memory session table and per-player explored bitmap snapshot; no DB/SHA-256 per tile request; explored is the on-disk bitmap, not a `HashSet`. | §4.2, §4.3, §6.2(7), §6.6 | S/M | before-M4 | +| 7 | World thread + group commit | One thread owns all ref-managed state; workers pass plain strings; one SQLite transaction per batch. Removes the race class and the M5 ordering work. | §4.1, §4.2, §6.1 | L | M5 | +| 8 | Integer/fixed-point wire coords; per-entity version diffs; affected-recipient egress | Quantised coordinates; diff by versions, not JSON trees; build each frame once and visit only affected recipients. | §4.4, §6.3 | M | M5 | +| 9 | Slow client: stop feeding + resync on pong lag | Stop feeding a lagging client and resync from `Known` on recovery; replaces "close when lag exceeds a bound" (impossible at the mummy pin). | §4.3, §6.4, §5 | S | M5 | +| 10 | Table-driven intent schema | One field table (name, type, required, range) replaces hand-written validation per intent. | §4.7 | M | M5 | +| 11 | Durability: one setting, measure first | Drop the FULL/NORMAL toggle if measurement shows no benefit; one setting for the home server. | §4.7, §5, §6.5 | S | M5 | +| 12 | Verify nginx HTTP/2 before the phone gate | HTTP/2 must be live end-to-end before the Note 10 gate; HTTP/1.1 caps six connections per host. | §6.6 | S | before-M4 | +| 13 | Thin sqlite3 binding replacing `db_connector` | **PROPOSED.** Prepared-statement cache, real NULL binding, `busy_timeout`, one transaction helper. Touches a [FIXED] stack item, so the owner decides at `/to-spec`. | §4.7, §5, §6.5 | M | at `/to-spec`, if accepted | + +Related to D3: the 0.5 minimum zoom is client work in M4; the explored-masked overview image is a +possible later (post-M5) item and is not on this list. + +## 4. Consequence for tickets + +Build tickets are generated from the split current spec at `/to-spec`, not from this review. +Thick walls and heights get build tickets only after the M4 playtest (D1). No issue is created +from the build list here; the only new tracker issue is the DESIGN split. diff --git a/docs/ANALYSIS.md b/docs/ANALYSIS.md new file mode 100644 index 0000000..f63b086 --- /dev/null +++ b/docs/ANALYSIS.md @@ -0,0 +1,405 @@ +# FFF_vtt: an outside analysis of requirements, design and engine + +Written 2026-11-17 against `main` at `409d2c8` (DESIGN draft v0.27, M1 to M3 done, M4 client not +started). I read the design, glossary, research notes, prototype reports and the whole server, and +skimmed the tests, tools and committed gate logs. I did not run anything. The numbers come from +the committed logs in `results/` and from the research notes. + +Evidence tags used below: +- **[measured]**: a number from a committed log or research note. +- **[read]**: I saw it in the code or the docs. +- **[inferred]**: my estimate. Treat it as a hypothesis to measure, not a fact. + +--- + +## 1. Verdict in one page + +**The core idea is right, and it is rare.** "The server alone decides what each player sees", with +one egress path and typed per-recipient views, is the correct architecture for a VTT that really +hides information. Most VTTs send everything and hide it in the client. This project doesn't, and +it has built the tests to prove it: an independent leak checker, fault-injection builds and 63 +mutations. That is the strongest part of the project, and it is better engineered than most +commercial VTTs on this specific point. + +**The compute engine is not the problem.** One visibility polygon costs about 0.04 ms, and a whole +mutation about 0.7 ms [measured]. One GM and six players produce a few intents per second. The CPU +has a margin of three to four orders of magnitude. For this load, "the most efficient engine" does +not mean faster geometry. It means: + +1. lower tail latency (the slowest acks come from SQLite COMMIT and lock queueing, not from vision), +2. fewer wire bytes and fewer tile requests on a phone, +3. no latent concurrency bugs, +4. less code and fewer documents for one person to carry. + +**The three biggest problems, in order:** + +1. **There is still no client, and the design keeps growing.** Six milestones of server work, then + eight design decisions (#41 to #48: heights, thick walls, one-way walls, windows, presets, + markers) were added before anyone has played a session in a browser. The riskiest unknowns are + all on the client side: cold tile load on the phone, iOS Safari, real map sizes. None of them is + retired. +2. **A real data race in the threading model** (section 4.1). The server runs mummy's worker + threads over shared ORC-managed `JsonNode`s that are not protected by the lock. Reference counts + in Nim's ORC are not atomic, so this can corrupt memory. It is rare and hard to reproduce, and it + is exactly the kind of bug that shows up once in a live session and never in tests. +3. **The design document has outgrown its author.** `docs/DESIGN.md` is 270 KB of layered, + partly superseded decisions, with no ADRs. It is now the main cost of every change, and that + includes changes made by agents. + +**My recommendation, short form:** freeze the wall-feature scope at what thin-segment geometry can +do cheaply. Fix the threading model by moving to a single world thread. Make the vision pass +incremental and cheaper using the known algorithmic fixes. Then build the M4 client and measure on +the phone before designing anything else. + +--- + +## 2. What the project is, as I understand the requirements + +- Self-hosted browser VTT for **one table**: 1 GM and up to 6 players, one scene in v1. +- **Server-authoritative sight.** Walls and doors are GM-only data. Each player receives only the + tokens inside their vision polygons, their own polygons, and their own explored cells. Map art is + served as 32 px tiles, gated per player by explored cells. No secret ever reaches a client + "hidden". +- Movement is validated on the server (swept circle, step cap, uniform nack) so that players cannot + map walls by probing. +- Stack, marked [FIXED] in the design: Nim 2.2 + mummy 0.4.8 + db_connector/SQLite WAL on the + server; TypeScript + PixiJS v8 on the client; nginx in front (TLS, `X-Accel-Redirect` tiles); + NixOS/devbox. +- The target device includes a 5-year-old Android phone (Note 10), which sets the client budget. + +These requirements are coherent. The single-table scale is the most important one and it should +drive every trade-off. Several parts of the design read as if they were sized for a bigger system +than this. + +--- + +## 3. What is good (keep it) + +| Idea | Why it is good | +|---|---| +| **Single egress, typed views** (`views.nim`: `GmView`/`PlayerView`, the `Known` diff) | A forbidden field cannot leak because it does not exist in the player type. This is the right way to enforce "the server decides". | +| **State-based diffs, not event replay** | Frames describe the current state, so reordering, dropped frames and a resync all converge. This choice already saves the current threading model from its ordering gaps (section 4.2). | +| **Independent leak checker + fault builds + mutation testing** | Proof that the rule holds, not just a belief. Fault injection is compiled out of shipped binaries. Few projects of any size do this. | +| **Measured-evidence discipline** ([MEASURED]/[INFERRED] tags, prototypes, research notes) | Decisions are traceable. Several research notes caught real errors in the design. | +| **Uniform move nack + step cap** | Closes the "probe the walls with moves" channel at low cost. 24/24 probing runs are identical [measured]. | +| **Explored stored as 64×64-cell chunk bitmaps** | Compact, bounded writes, simple to restore. | +| **Random 72-bit token ids** | Counted ids would leak hidden tokens through the gaps. A small detail, and it is right. | +| **Scanline `cellsTouched`** | About 10× faster than the prototype and differential-tested against it [measured]. | +| **Switch-based wall model (#42/#48)** backed by a survey of other VTTs | The model is right. The scope built on top of it is the problem (section 5). | +| **nginx serves tile bytes, Nim only authorises** | Correct split. Nim never reads image files. | +| **Glossary** | Short, precise, useful. Keep it as the vocabulary anchor. | + +--- + +## 4. What is bad or risky (the critique) + +Ordered by how much it matters, not by how easy it is to fix. + +### 4.1 Data race: shared `JsonNode`s across mummy worker threads [read, not reproduced] + +`main.nim` casts the `App` out of a raw pointer so that mummy's worker-thread handlers count as +`{.gcsafe.}`. That silences the compiler check that would have caught the following. + +In `wall.add` (`server/main.nim:1846-1872`): +- `flags` is a subtree of `env.node`, the JSON parsed on the worker thread. +- Under the lock, it is stored into `app.scene.walls`, so the global world now references that + node. +- After the lock is released, `wallObjectOf(added.get)` builds a frame that references the same + `flags` node (reference count +1). At the end of `dispatch`, `env`, `candidate` and `added` are + destroyed (reference count −1). Both happen **outside the lock**. +- At the same time, another worker thread can be inside the lock, walking `app.scene.walls` for a + GM resync or `wallsSnapshot`, which touches the same node's reference count. + +With `--mm:orc` (`nim.cfg`), reference counting is **not atomic**. Atomic counts exist only under +`--mm:atomicArc`. Two threads updating the same count without synchronisation can lose an update. +The result is a premature free (use-after-free) or a leak. The same pattern applies to `token.*` +flags and props, `scene.set` `extra`, and any `JsonNode` from an intent that ends up in the world. + +The probability is low (GM edits are rare and the windows are short). The cost when it happens is a +crash or silent corruption mid-session that no test reproduces. **Fix options**, from quickest to +best: +- Quick: `copy()` every `JsonNode` taken from an intent before it enters the world, and build every + frame that references world state inside the lock. +- Cheap and broad: compile with `--mm:atomicArc`. `JsonNodeObj` is `{.acyclic.}`, so ORC's cycle + collector gives nothing here. Measure the cost first; it is probably small at this load + [inferred]. +- Structural (recommended, section 6.1): one world thread owns all ref-managed state, and worker + threads pass it only plain strings. + +Related: mummy defaults to `10 × CPU cores` worker threads (`mummy.nim:1476`), and `newServer` is +called without `workerThreads`. On a 16-core machine that is 160 threads competing for one global +lock to serve seven people. + +### 4.2 One global lock, two critical sections, two to three transactions per mutation [read] + +A mutation runs the handler under `withLock app.dbLock`, releases it, then `settle` takes it again +for encounters, the ack and egress. Between the two sections, another mutation can run in full. +Each section opens its own transactions (`persistExplored`, `recordEncounters`, the row write). +Correctness is saved by the state-based diff, and the design admits the exact ordering is deferred +to the M5 outbox. + +- The measured tail is intent→ack p99 4.58 ms, worst ~20 ms, with an unexplained 583 ms spike + earlier [measured]. The research attributes the tail to COMMIT and queueing, not to compute. +- More transactions mean more fsync-shaped tail. One mutation should be one transaction. +- `tileGate` takes the **same global lock** and runs a SQLite session lookup plus SHA-256 **per + tile request** (`main.nim:614-625`). A connect burst is 292 tile requests [measured]. Each one + competes with gameplay mutations for the lock. +- Several paths query the DB under the lock for data that is already in memory (`rosterFrames` → + `allPlayers`, `resyncEveryone` → `playerById`). + +### 4.3 The vision pass does far more work than it needs to [read + measured] + +None of this matters for latency today (0.27 ms for six polygons [measured]). It matters for thick +walls and dense maps, where the research measured **12.8 ms per polygon and 75.6 ms for a six-token +party** with thick walls on a dense scene [measured]. + +- **Every ray is tested against all 64 circle segments as well as the walls** + (`geometry.nim:46-68`). The ray's angle tells you which single segment of the 64-gon it can hit, + so one test is enough. That gives the same output and removes most of the work on sparse scenes. + The research estimated a 5-9× saving [inferred there]. +- The algorithm is **rays × segments**: 3 rays per endpoint × all walls in the box. Thick walls + multiply both factors (4 edges each), which is why they blow up. An **angular sweep** (sort + endpoints, keep the active walls ordered by distance) is O(n log n) and is the standard solution. + For the dense case (~200 walls in the box) I would expect about 0.1 ms instead of 1.3 ms + [inferred]. +- **No caching.** `vision.refresh` recomputes **every** polygon of the player and re-rasterises all + of them, even if only one token moved. `geometryWalls(sc)` copies all walls on every + `computePolys`. `moveScene` copies all walls and tokens on every move and wall edit [read]. +- **A wall edit refreshes everyone.** `refreshAll()` recomputes every token of every player, + including tokens 3000 px away from the edited wall. +- Explored is an in-memory `HashSet[int]`, although it is persisted as bitmaps. The tile gate's + "is any cell explored" check would be one bit test on a bitmap. + +### 4.4 Egress rebuilds everything, every time [read] + +`egressAll` rebuilds the full typed view and every JSON frame for every connection on every +mutation. It compares `JsonNode` trees against `Known`, compares vision as a serialised string, and +resends the **full polygon** on any change (3.4-3.7 KB per move [measured]). `withN` deep-copies +each frame per connection. + +At seven users this is affordable. It is still the main cost after COMMIT, and it grows with thick +walls (2.5-3.7× more polygon vertices [measured]). The cheap wins: +- Send integer coordinates (or 0.1 px fixed point), not 17-digit floats. That cuts vision frames + roughly 3-4× [inferred]. +- Diff on typed values or a per-entity version counter, not on JSON trees. +- Recompute only the recipients the mutation can affect. + +### 4.5 Scope grew before the product exists [read] + +v1 started with `wall` | `door`. Decisions #41-#48 add wall heights with see-over, a switch-based +wall model with presets, thick walls, secret and locked doors, windows, one-way walls and player +markers. #49 (wire/schema/migration) and #50 (thick doors and push) are still open. + +My honest opinion, per feature: + +| Feature | Opinion | +|---|---| +| Secret / locked doors (#46) | **Good.** Cheap (a flag plus the egress rule) and high table value. | +| Windows, one-way walls (#47) | **Good and cheap, if** the vision code is a sweep: they become per-wall predicates (blocks sight from this side / blocks movement but not sight). Expensive in the current ray fan. | +| Presets / switch model (#42/#48) | **Good** as the data model. Keep the preset list short. | +| Player marker | Fine. | +| Thick walls (#45) | **Doubtful for v1.** Highest cost in algorithm, wire bytes and leak-checker rework (its zero-width `clearLine` oracle does not cover thick walls). Most tables are served by thin walls that follow the art. If kept, model them as closed polygons inside a sweep, not as four independent segments in a ray fan. | +| Heights / see-over low walls (#41) | **Bad idea for v1.** No surveyed VTT puts wall height into the sight polygon (Foundry explicitly refused it in core), the semantics are disputed at the table, it needs UI on a phone, and it doubles the leak-oracle burden. Defer it until people have played without it and asked for it. | + +UVTT 0.3 import cannot express movement blocking, secret, locked, one-way or windows [read], so +every advanced feature is GM hand-authoring on a phone or desktop client that does not exist yet. + +### 4.6 The design document [read] + +`docs/DESIGN.md` is 270 KB, draft v0.27. It has lines over 4000 characters, superseded decisions +kept inline next to their replacements, and no `docs/adr/` directory although the agent docs +expect one. The research notes found factual errors in it (mummy "has no upstream tags", and +"close when lag exceeds bound" is impossible at the pin). A document this large is no longer +reliably read in full, by a person or by an agent. That defeats its purpose as the source of truth. + +### 4.7 Smaller issues [read] + +- **`db_connector` limitations leak into the code:** no NULL binding (so `sqlLitId`/`sqlLit` build + SQL literals, guarded by an alphabet check), no prepared-statement reuse, no transaction API. A + ~200-line wrapper over the sqlite3 C API (bind_null, a cached statement table, busy_timeout) + would remove the literals and save CPU on every write. +- **`PRAGMA synchronous` toggled FULL↔NORMAL around each authoring transaction.** It is defensible, + but it adds code and tests for a small difference: in WAL mode, NORMAL only risks the last commits + on power loss, not on a process crash. Low priority. Consider simply FULL everywhere and measure. +- **`dispatch` is one ~1300-line `case`** with field validation written by hand for each intent. A + table-driven schema (field name, type, required, range) would remove most of it and the class of + bugs where one intent forgets a check. +- **The leak checker is less independent than it says.** Its polygon "truth" calls the server's own + `visibilityPolygon`, and its explored check calls the server's `cellsTouched`. Only the + clear-segment sanity check is independent. A wrong polygon would agree with itself. (Section 6.2 + turns this into an opportunity.) +- **`walls`-sourced statuses** tell a player that a wall touches a token (leak note 6, still open). + It is minor, but it is a leak by the project's own definition, so either accept it explicitly or + show players a source-free status. +- **mummy 0.4.8:** unbounded send queue, no backpressure, no close codes, no timeouts. The design + knows this; M5 must handle it (section 6.4). +- **Unknowns not retired:** phone cold viewport < 1 s at zoom 1 (unproven; the worst measured cold + load is 3.3 s at zoom 0.5 over HTTP/1.1 [measured]), iOS Safari, real map size and wall count + (Q2), the 583 ms spike, the T11 timing/size side channel (accepted, untested), and where the FFF + rules engine will live. + +### 4.8 Tiles at zoom-out [read + measured] + +The 32 px tile is the right leak granularity: tile = cell, so an allowed tile shows exactly +explored ground. But the request count grows with 1/zoom²: about 1.3k tiles at zoom 0.5 and about +5k at zoom 0.25 [inferred from the measured 1.3k]. A 16384 px map is 262,144 files, about 1.06 GB +[measured]. There is no lower-resolution pyramid, and a normal one would leak, because a coarse +tile would cover unexplored cells. + +--- + +## 5. Requirements I would challenge + +- **"Thick walls and heights in v1"**: covered in 4.5. Defer them. +- **"Close a slow client when lag exceeds a bound"**: impossible as an immediate close at the mummy + pin [research]. Replace it with "stop feeding, then resync" (section 6.4), which the state-based + diff makes easy. +- **"Durability FULL for authoring, NORMAL for the rest"**: correct in spirit, but the + implementation cost is out of proportion to the risk for a home server. Make it one setting. +- **mummy and db_connector as [FIXED]**: keep mummy, since replacing the HTTP layer gains little. + db_connector is worth replacing with a thin direct binding (4.7). Flagging this because it + touches a [FIXED] item. + +--- + +## 6. The engine I would build + +This is not a rewrite. Most of the modules are good: `moverules`, `views`, `explored`, `tiles`, +`characters`, `tokens`, `world`. What changes is the plumbing around them in `main.nim`, the vision +algorithm, and how state is published to the tile gate. + +### 6.1 Concurrency: one world thread, no global lock + +``` + mummy workers (few: 4-8) world thread (owns ALL game state) + ───────────────────────── ────────────────────────────────────────────── + ws text ─► rate limit ─► (connId, raw string) ──► inbox (MPSC channel, plain strings) + │ + ├─ parse + validate (table-driven schema) + ├─ apply to in-memory world (moverules, …) + ├─ ONE SQLite transaction for the whole batch + ├─ incremental vision + explored (6.2) + ├─ egress diff per affected recipient (6.3) + └─ ws.send(bytes) per connection outbox (6.4) + + tile gate (worker) ─► session cache + per-player explored bitmap snapshot + (plain bits, no refs; published by the world thread under a tiny lock + or as an immutable seq swapped atomically) +``` + +Why this design: +- **No shared refs between threads.** Workers hand over only `string`s. Every `JsonNode` lives and + dies on the world thread. The data race in 4.1 disappears as a category, not as one patched + instance. +- **Ordering is exact by construction.** One thread applies one intent after another, so the M5 + "exact per-connection ordering" problem goes away. +- **Group commit.** Intents that arrive while a COMMIT is running are applied together and + committed in one transaction. This attacks the measured tail (COMMIT + queueing) directly. Under a + burst, several acks share one fsync. +- **The tile gate never touches the world or the DB.** It reads a bitmap and an in-memory session + table. Revocation updates the cache from the world thread. +- **The mutation path is easier to reason about**: one loop instead of two critical sections, three + transactions and a borrow-the-world context. + +Cost: rewriting `settle`/`egressAll`/`dispatch` plumbing in `main.nim`. Handler bodies move almost +unchanged. Nim's built-in `Channel[string]` or `threading/channels` is enough for the inbox, and +mummy's `ws.send` can be called from any thread. + +### 6.2 Vision: sweep, cache, incremental + +1. **Now, same output:** test each ray against only the one circle segment in its sector. All + existing geometry tests and the bench still apply unchanged. +2. **Angular sweep** replacing the ray fan: O(n log n) in walls in range. Windows, one-way walls and + secret doors become a per-wall predicate inside the sweep. If thick walls survive, they enter as + closed polygons (only the near face matters for sight, and the research found the near-face + variant costs about the same as thin walls [measured]). +3. **Keep the old ray fan as the leak checker's oracle.** That turns the checker's weakness in 4.7 + into real independence: two different algorithms must agree. A single change both speeds up the + engine and strengthens the proof. +4. **Cache per token:** polygon and cell set keyed by `(pos, range, wallsVersion)`. A move + recomputes one polygon, not the player's whole party. +5. **Incremental wall edits:** recompute only tokens whose vision circle overlaps the edited wall's + bounding box. +6. **Uniform grid for walls** (for example 256 px buckets) only if Q2 says maps exceed about 1000 + walls. Below that, the bbox cull is enough [measured: 5k sparse is 0.08 ms]. +7. **Explored as the bitmap it already is on disk**, not a `HashSet[int]`. Restore is a memcpy, the + tile check is a bit test, and dirty-chunk tracking falls out naturally. + +### 6.3 Egress: smaller, cheaper frames + +- Integer or fixed-point coordinates on the wire. +- Per-entity version counters. Diff by comparing versions, build JSON only for what changed, and + build each shared frame once, not once per connection. +- Vision: keep full-polygon replacement (it is simple and safe) but quantised. A delta encoding is + not worth the complexity at this scale. +- Only recipients whose view the mutation can affect are visited: the mover's player plus anyone + who could see the token's old or new position. + +### 6.4 Slow clients (M5) + +mummy gives no queue depth. Use **pong lag** (already recorded) as the signal. When a connection's +lag exceeds a bound, **stop feeding it** and mark it dirty. When it recovers, send `hello` and a +full resync from its `Known` reset. The state-based diff makes the dropped frames harmless. This is +simpler than any outbox with byte accounting and fits the pin's limits. + +### 6.5 Persistence + +- A thin direct SQLite binding: prepared-statement cache, real NULL binding, `busy_timeout`, one + `transaction` helper. +- One transaction per batch (6.1), and one durability setting. +- Session lookups served from memory, written through. + +### 6.6 Tiles + +- Keep 32 px tiles and the explored gate. +- **Clamp the minimum zoom in v1** (for example 0.5). That alone bounds the request count. +- Later, if needed: a **per-player overview image** (for example 512 px for a 4096 px map), rendered + from the art and masked by that player's explored bitmap, regenerated when explored grows by more + than N cells. It is leak-free by construction and turns thousands of requests into one. +- Make sure nginx actually runs HTTP/2 to the browser before the phone gate. The h2 benefit is only + inferred so far, and HTTP/1.1 limits a browser to six connections per host. + +### 6.7 Expected effect [all inferred, to be measured] + +| Metric | Today | After | +|---|---|---| +| Ack p99 | 4.6 ms (worst ~20 ms) | ≈ one COMMIT; bursts share it | +| Polygon, dense 5k | 1.28 ms | ~0.1 ms (sweep) | +| Thick, dense, 6-token party | 75.6 ms | a few ms (sweep, near faces) | +| Vision frame per move | 3.4-3.7 KB | ~1 KB (quantised) | +| Tile request cost | global lock + DB + SHA-256 | lock-free map lookup + bit test | +| Data-race class | present | gone | + +--- + +## 7. What I would do next, in order + +| # | Action | Why now | Size | +|---|---|---|---| +| 1 | Patch the `JsonNode` race: `copy()` intent JSON before storing it, and build frames under the lock (or `--mm:atomicArc`). Set `workerThreads` small. | Memory safety, cheap | S | +| 2 | **Freeze wall scope:** keep secret/locked doors, windows and one-way walls. Defer heights (#41) and thick walls (#45, #50) to after M4 playtests. | Stop growth before the client | decision | +| 3 | Circle-segment fix plus per-token polygon cache. | Same output, big cut | S | +| 4 | Session cache; tile gate off the global lock. | Connect burst vs gameplay | S | +| 5 | **Build M4 client**; run the phone and iOS gates over real nginx h2; clamp the minimum zoom. | Biggest unretired risk | L | +| 6 | World-thread refactor with group commit. | Tail latency, ordering, removes M5 ordering work | M | +| 7 | Angular sweep; keep the ray fan as the leak-checker oracle. | Needed if windows/one-way stay; makes thick walls possible later | M | +| 8 | Split DESIGN.md: a short current spec, ADRs for decisions, and history moved out. | Every future change gets cheaper | M | +| 9 | Thin SQLite binding; table-driven intent schema. | Removes workarounds and repeated validation | M | +| 10 | Slow-client "stop feeding + resync" (M5). | Robustness | S | + +--- + +## 8. Final honest opinion + +This is a serious, carefully built server, more rigorous about information leaks than the VTTs +people pay for. The author's instinct to measure before deciding is the project's greatest asset. + +The weakness is the mirror image of that strength. Rigor is applied to the server and the design +document, while the thing that decides whether the project succeeds, a playable client on a real +phone at a real table, has not been started. Every week spent designing wall heights or thick-wall +push rules is a week of decisions made without player feedback. Every decision also lands in a +document that is already too large to hold in one head. + +The engine needs no heroic optimisation. It needs one structural fix (the world thread, which also +removes a real memory-safety bug), three or four textbook algorithmic fixes it already knows about, +and a scope freeze. After that, the fastest way to make it better is to play with it. diff --git a/docs/DESIGN.md b/docs/DESIGN.md index b311a62..9013168 100644 --- a/docs/DESIGN.md +++ b/docs/DESIGN.md @@ -1,6 +1,6 @@ # FFF_vtt design -Status: draft v0.29, 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. All of Q1-Q24 are RESOLVED or DEFERRED; none OPEN). Audience: the owner and coding agents. +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. Legend: - **[FIXED]** owner decision, not up for debate here. @@ -26,6 +26,7 @@ A browser virtual tabletop for one table (1 GM + up to 6 players [FIXED, Q1]), s - **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. @@ -223,8 +224,8 @@ Second limitation [INFERRED]: a fast drag sampled at ~50 ms can produce a straig - Worker threads: prototype uses 8; one table needs 2-4 [INFERRED]. - **Slow client [FIXED (owner decision), 2026-11-08, Q13 option A]**. mummy's send queue is one unbounded deque and per-socket backlog is invisible to app code (no forced close, no depth API at this pin). No mummy patch. Research: `docs/research/q13-mummy-slow-clients.md`. - **Bounded outbox per connection** (keyed by app `connId`), with byte and message caps. State messages (vision, token, explored, wall) are **latest-state-wins coalesced per key** (MQTT-retained-like). The diff against `known` is computed at **flush time**, not enqueue time, so a dropped intermediate state cannot desynchronise the client. - - **Ack by Ping/Pong**: server sends WS `Ping(seq)` (payload <= 125 B) on a timer; the client's Pong echoes `seq` (RFC 6455 §5.5.2-5.5.3; browsers answer without JS). Acks give bytes in flight and lag per connection. Interval [FIXED (owner-delegated), #18]: every 20 s, plus one Ping immediately after `hello` on each connection. Slice 3 sends the Ping and records the Pong per connection (`Conn.pongSeq`, `Conn.lastPongMs`); the lag measurement itself, the stop-feeding rule and the forced close of a silent peer stay M5. A Ping/Pong is a control frame and carries no `n` (6). - - **Lagging client** (outbox over cap, or no Pong within a bound): stop feeding it, keep the connection. On recovery, full resync (6.3). + - **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. - Forking mummy (per-socket depth, forced close) is fallback only, not planned. @@ -345,7 +346,7 @@ Normative for M2. Replaces the prototype move validation (5.1) and the move-rela 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). +- 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). @@ -460,7 +461,7 @@ What a wall's thickness does to the floor it covers, the vision fan and the coll - **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: 0.26 vs 0.94 ms on 5k sparse and 12.7 vs 13.2 dense, against the 3-face near+caps silhouette that is observer-dependent and cannot be hoisted]. 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. +- **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. @@ -651,7 +652,7 @@ All are built per recipient at egress (single egress rule, 2). "Sent" always mea 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. Open: a `walls`-sourced status still tells a viewer that some blocking wall touches the token; #4 argued LOS covers that, owner to confirm. (7) `encountered.grey` flipping and `token`/`token_gone` carry the same fact (the token left view), so deletion and moving away look identical to the player. +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. @@ -768,7 +769,8 @@ Prototype `client/src/main.ts`: explored rects appended to a `Graphics` mask for ### 7.4 Input and UI - Mouse: wheel zoom, drag pan, drag token. Touch: one finger drag/pan, two-finger pinch/pan [MEASURED works on Note 10]. -- Wall editor (GM) [FIXED, Q6, 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 M4's (5.7). 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). +- **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. @@ -981,7 +983,7 @@ Each is small, ends with a green gate, and no milestone depends on browser UI be 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 (5.8) and thickness/position (5.10), token drag with prediction/rollback, DOM overlay, reconnect backoff, reducer tests; after the client port, archive `prototype-*` dirs (Q24). + - 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.** @@ -1099,3 +1101,5 @@ Owner also decided 2026-11-16 [FIXED (owner decision), 2026-11-16, #48]: terrain 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.