From 39615afdf6e4343c18306b08e483be31f6be3580 Mon Sep 17 00:00:00 2001 From: Davide Cappellini Date: Tue, 17 Nov 2026 23:21:16 +0100 Subject: [PATCH] docs: add TESTING.md with the proof detail split out of DESIGN New file holds test, acceptance, oracle, fault-class, gate and bench detail, organised by DESIGN section number with a back-link per block. Tags, tickets and evidence paths are preserved. --- docs/TESTING.md | 573 ++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 573 insertions(+) create mode 100644 docs/TESTING.md diff --git a/docs/TESTING.md b/docs/TESTING.md new file mode 100644 index 0000000..4fc864d --- /dev/null +++ b/docs/TESTING.md @@ -0,0 +1,573 @@ +# FFF_vtt testing + +Status: how [`docs/DESIGN.md`](DESIGN.md) is proven, 2026-11-17. This file holds the test, acceptance, +oracle, fault-class, gate and bench detail; DESIGN holds the rules. Both are current: a rule is stated +once in DESIGN, its proof once here. + +Organised by DESIGN section number: every block names the rule it proves. Section numbers mirror the +spec's, so `DESIGN §x.y` and `TESTING §x.y` are the same subject, and the old `DESIGN 10.x` citations in +code and test comments still resolve (DESIGN §10 is now a pointer to §10 here; the mapping is +10.1 → §10.1, 10.2 → §10.2, 10.3 → §10.3, 10.4 → §10.4). + +Tags are the spec's: **[MEASURED]** a number or behaviour from a prototype run (cited by path), +**[INFERRED]** a reading or reasoning, **[PROPOSED]** a choice the owner may overturn, **[FIXED]** an +owner decision. A moved block keeps its tag, its tickets and its evidence path. + +Two principles carried from the prototype, and they apply to everything below: the checker must be +independent of the code under test where possible, and every check needs a negative control that proves +it can fail. + +Evidence roots (relative to repo root): +- `prototype-pixi-perf/` (client perf; README holds all tables) +- `prototype-server-vision/` (server + vision; `README.md`, `HANDOFF.md`, `NOTES.md`, `results/`, + `results/spike/investigation.md`) +- `prototype-tile-leak/` (tile size vs leak; README tables and the 2026-11-08 phone run) + +How to run: `devbox run test` = Nim in-process tests first, then the Node black-box harnesses; +`devbox run mutation` = the mutation suite. + +--- + +## 3. Security model + +### 3.1 What each role receives + +**Rule:** DESIGN §3.1. + +- `gm_only` is enforced in the view builder, before any frame is built; fault class `GMONLY_TOKEN` + (§10.3). + +### 3.3 Tiles + +**Rule:** DESIGN §3.3. + +- Direct hits on `/_tiles/` give 404 [MEASURED: `prototype-server-vision/results/smoke.log`, README + "Phase 2a"]. +- A tile is allowed iff at least one explored cell of that player overlaps it [MEASURED semantics: leak + test (d), 9984 + 7424 requests, 0 failures, `results/leak-A.log`, `results/leak-B.log`]. +- The residual 32 px edge leak's sizing evidence: `prototype-tile-leak/README.md` (desktop numbers; + phone run 2026-11-08). M4's tile-size gates are in §13 below. +- `Cache-Control: private` is set by the Nim gate and rides through nginx's internal redirect + unchanged; nginx adds nothing of its own there (the test vhost records this, §11.1). +- Slice 9 (#24) pins the full status split of DESIGN §3.3: `404` also for another scene or a stale art + version, `403` also for a missing or unknown session (one response with "unexplored"), and + `Cache-Control: private`. The proving group is §10.3 Tiles (`tools/tiles.test.mjs`). + +### 3.4 Threat list + +**Rule:** DESIGN §3.4 (threat, mitigation and the accepted residuals). The `Test` column moved here. + +| # | Proving test | +|---|---| +| T1 | leak test + fault classes | +| T2 | fault `walls` [MEASURED caught]; `MARKER_EARLY`/`MARKER_EXTRA`/`MARKER_OFF` (§10.3); door-equivalence test (T17, §10.3) | +| T3 | faults `other-*` [MEASURED caught] | +| T4 | leak (d) against the independent oracle, smoke steal check, direct `/_tiles/` -> 404 (M3 test nginx) | +| T5 | documented, not testable as a leak; M4 timing gates (§13) | +| T6 | config test (grep logs for secret) [new] | +| T7 | new test | +| T8 | M2 in-process probing test (§5.5, §13); WS version in M3 (§10.3): count wall/door facts recoverable from nacks beyond LOS | +| T9 | leak test (e) | +| T10 | new tests (§10.3 slow client, protocol) | +| T11 | not tested | +| T12 | smoke | +| T13 | new test | +| T14 | leak test | +| T15 | deploy check | +| T16 | fault classes `ACTUAL_NAME`, `CHAR_LIST` (§10.3) | +| T17 | differential door-equivalence test `tools/doors.test.mjs` (§10.3, #46), positive control on an open door, fault `secretgap`, door-key scan in `tools/leakcheck.nim` -> `WALLDATA` | + +--- + +## 4. Server + +### 4.1 State model + +**Rule:** DESIGN §4.1. + +- Monsters/NPCs have no vision [MEASURED design: `vision_ms move-monster` 0.000 ms; the bench row is in + §5.3]. + +### 4.2 Mutation pipeline + +**Rule:** DESIGN §4.2. + +- The pipeline order under one global lock is proven correct by 3 x 60 s concurrency runs (§4.3). + +### 4.3 Locking and threading + +**Rule:** DESIGN §4.3 (one global lock, the p99 trigger, slow-client handling, connection limits). + +- [MEASURED] 13748 mutations / ~36k messages in 60 s with 3 clients (~223 intents/s): no crash, no + reorder, no loss, consistent final views (`results/concurrency-final{1,2,3}.log`); intent->ack avg + 1.40 ms, p99 4.58 ms, worst 20.31 ms. +- A table of <= ~10 clients is 2 orders of magnitude below the single-core limit (server total per + mutation avg 0.70 ms [MEASURED]). This is why the global lock is kept; the revisit trigger is a + measured p99 > 50 ms in production (§11.3). +- Proposed: add a test that fails if mummy's `WebSocket` fields change (the pin makes this stable, the + test makes it explicit) [PROPOSED]. +- SQLite tail: server worst ~20 ms is the COMMIT (WAL autocheckpoint / OS scheduling [INFERRED]) and + every other mutation queues behind it as `lock_wait` (`results/spike/investigation.md`). Accepted for + v1; moving persist out of the lock would break ack-after-commit and order. +- 583 ms intent->ack outlier: **not reproduced**, cause undetermined (host stall or node harness pause; + not proven either way, `results/spike/investigation.md`). Production logging (DESIGN §11.3) must make + a recurrence diagnosable (SLOW lines with breakdown). + +### 4.4 Persistence + +**Rule:** DESIGN §4.4. + +- Commit cost [MEASURED] avg 0.60 -> 0.17 ms, server total avg 1.16 -> 0.74 ms; tail unchanged (~20 ms + worst) (`results/spike/investigation.md`). +- Process kill (SIGKILL) loses nothing [MEASURED: `results/final-restart.log`, SIGTERM and SIGKILL, same + DB, identical state]. +- Chunked explored, measured cost of one mutation-scale write (BEGIN; 512 B upsert; COMMIT): avg + 0.015 ms, p99 0.035 ms (DESIGN §4.3's accepted commit tail is ~20 ms), and a real move's ack stays at + avg 0.7 ms / p99 1-2 ms with explored writes on (`tests/texplored.nim`, `tools/persistence.test.mjs`). + Sizes: 4096 px map / 32 px cell = 16 384 cells = 2 KB (2x2 chunks); 16384 px map = 262 144 cells = + 32 KB (8x8 chunks). +- The chunk layout is pinned by `tests/texplored.nim` (exact byte/bit positions) and re-read + independently by `tools/persistence.test.mjs`, so a refactor cannot silently swap axes or bit order. +- Seeding the scene in migration step 3 keeps it identical on every start and lets the migration test + assert it (§10.3). + +--- + +## 5. Vision and explored + +### 5.1 Algorithm + +**Rule:** DESIGN §5.1. + +- The vertex-in-cell case was added after a bug (polygon wholly inside one cell) [MEASURED bug log, + prototype `NOTES.md`; covered by `tests/tgeometry.nim`, suite "cells", test "tiny polygon inside one + cell"]. + +### 5.2 Edge cases handled + +**Rule:** DESIGN §5.2 (the list of handled cases is the rule). + +- Port baseline [MEASURED, `tests/tgeometry.nim`]: M1 port baseline (history) 33 test blocks / 98 + checks, none dropped; current count 92 `[OK]` test cases in `results/nimble-test.log` (M2, + 2026-11-08). +- Angle-sort bug [MEASURED bug, prototype `NOTES.md` "Post-phase-3"]: circle angles must use the same + (-pi, pi] range as wall angles (`atan2(sin,cos)`), otherwise the polygon is a bow-tie (position + dependent). Regression test: `tests/tgeometry.nim`, suite "visibility", test "wall endpoints behind + the viewer: fan stays angularly ordered". +- Vision circle is an inscribed 64-gon: error <= ~0.12% of R [MEASURED, prototype `NOTES.md`]. + +### 5.3 Performance + +**Rule:** DESIGN §5.3 (targets and accepted decisions). Measurements and the bench methodology: +`results/bench.log`, `results/concurrency-final1-server.log`, single laptop, release build, loopback, +power-save CPU. + +| item | avg | worst | +|---|---|---| +| 1 visibility polygon (prototype scene, 60 walls) | 0.038 ms | 0.18 ms | +| 1 polygon + `cellsTouched` | 0.451 ms | 0.98 ms | +| 6 polygons + `cellsTouched` | 2.95 ms | 3.73 ms | +| server vision recompute per player move (incl. cells + diff) | 1.18 ms | 4.55 ms | +| door toggle (2 players) | 0.20 ms | 0.30 ms | +| monster move | ~0 | 0.024 ms | + +- `cellsTouched` is ~12x the polygon itself and dominates [MEASURED]. M2 replaced per-cell polygon + tests with scanline rasterization over the explored grid, differential-tested against the ported + implementation [PROPOSED; built in M2]. +- Polygon cost is O(rays x walls in bbox) [MEASURED code reading, `server/geometry.nim` + `visibilityPolygon`, ported unchanged from the prototype]. The prototype scene has 60 walls and 8 + tokens, so this says nothing about big maps. With radius-bbox culling the cost scales with local wall + density, not total walls [INFERRED]. +- Bench scenes (`tools/scenegen.nim`): the 5k target is the sparse primary layout + `genScene(16384, 5000, 1)`: 0.082 ms avg [MEASURED, `results/bench.log`]. The dense layout + `genScene(4096, 5000, 1)` is a stress reference (1.28 ms avg, ~207 walls in the vision bbox) + [MEASURED]; the uniform spatial grid is revisited if real maps approach that density. +- **Thickness cost** [#43, DESIGN §5.10]: a thick body is a quad, and the fan costs about 10x on a dense + scene (13.2 ms vs 1.25 ms baseline on the 5k dense layout; 0.26 ms per polygon, 3.15x, on the 5k + sparse one). The owner accepted that and re-baselined the per-move budget [FIXED (owner decision), + #43]; polygon optimisation is deferred. +- Timings are single machine loopback power-save CPU; no real network, no client render [MEASURED + caveat]. A real-network run (laptop over the intended HTTPS path, phone on LAN) is an M7 item. +- Load/perf regression gate: `bench` + concurrency numbers (this section and §4.3) compared with + committed baselines; fail on > 2x regression [PROPOSED]. + +### 5.4 Known limitations + +**Rule:** DESIGN §5.4. + +- Token exactly on a wall cannot move off it [MEASURED limit, `tests/tgeometry.nim` test "KNOWN + LIMITATION: token exactly on a wall cannot move off it"; also in the `server/geometry.nim` header]. +- Explored and tile checks in the leak test recompute with the server's own `cellsTouched`: + self-consistency only (caveat in §10.2). The independent oracle exists now (§10.2, §10.3). +- Doors/walls changing does not un-explore anything; explored only grows [MEASURED behaviour]. + +### 5.5 Move rules and statuses + +**Rule:** DESIGN §5.5. + +- Implemented as a pure in-process module with unit tests; the WebSocket layer only maps its result to + `ack` (DESIGN §6.1). The WebSocket probing test is M3. +- The push rule's arithmetic: a zero-thickness door must return identical values on the same inputs; + the unchanged existing tests are the regression gate (§10.3 Door push with thickness). +- Oracle comparisons use 0.5 px, as the leak checker (DESIGN §3.4 T14). +- **Regression baseline** [FIXED, accepted default]: "results equal old implementation" = + `visibilityPolygon` and `cellsTouched` on the prototype leak transcripts plus + `tests/fixtures/scene.json`. `moveBlocked` is excluded: its results change on purpose. + +### 5.7 Heights + +**Rule:** DESIGN §5.7. + +- A wall's `height` is in leakcheck's `BannedAlways` (`WALLDATA`, §10.3) because no player frame ever + carries it. + +### 5.8 Wall switches, presets, doors, windows and one-way + +**Rule:** DESIGN §5.8. + +- The oracle that pins the secret/locked door obligation is the differential door-equivalence test + (§10.3, DESIGN §3.4 T17, #46). +- A wall `label` is in the leak checker's `BannedAlways` key scan (§10.3), so a player frame carrying + `label` is `WALLDATA`. + +### 5.9 Low walls: see-over + +**Rule:** DESIGN §5.9 (the predicate, the strict polygon and the GM-only fraction). + +- Oracles [FIXED (owner-delegated), #44]. `tools/leakcheck.nim`'s `clearLine` gets its own height test + (walls carry their height; a target's top is compared independently of the server's code, never by + calling vision.nim). Cells in a low wall's hidden band are **maybe** for the independent + explored/tile oracle: a tile there may be allowed or refused, both correct, but a band cell may never + be **sure** (a `200` on a band cell is legitimate, a withheld proof cell never). A token hidden only + by the band gives no `token` frame, no name and no encountered entry, and no churn: no alternating + frames as a position crosses the line. The assertions land with the build tickets (/to-spec), not + here (DESIGN §13 build order: heights are built after the M4 playtest). + +### 5.10 Thick walls: the body, sight and movement + +**Rule:** DESIGN §5.10. + +- Sight input cost [FIXED (owner-delegated), #45; #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. +- Joints [FIXED (owner-delegated), #45]: #43 measured that joints need no thickness: zero-width corners + show no crack either. +- Oracles build the body rectangle from `a`, `b`, `thickness` and `position` with their own code, never + by calling `vision.nim` or the move rules, and use it for both the sight footprint and the distance + test (§10.2, §10.3). + +--- + +## 6. Protocol + +### 6.3 Reconnect and resync + +**Rule:** DESIGN §6.3. + +- The client reducer resets everything on `hello` (reconnect-reset bug fixed in the prototype; test in + `client/src/state.test.ts`, 4/4 pass) [MEASURED]. +- Assets (tiles) are kept across reconnect because explored only grows [MEASURED prototype behaviour]. +- The turn-over point for a snapshot size is measured, not guessed: revisit if a measured full resync + exceeds ~100 KB (DESIGN §6.3). + +### 6.4 Deltas and size + +**Rule:** DESIGN §6.4. + +- The per-connection `known` table gives correct enter/leave [MEASURED, leak test (c)]. +- The stored diff base is the frame **before** the per-connection `n` is stamped: `protocol.withN` + deep-copies, so stamping cannot make the next comparison see a different frame and re-send unchanged + state (this was a live bug until slice 8; the leak checker now sees a genuinely sparse stream). +- Bytes [MEASURED, `results/concurrency-final1-server.log`]: monster move 145 B to a seeing player, + 244 B to GM; player move: mover 3359-3653 B (worst 4.9 KB, dominated by the full `vision` polygon + + `explored` diff), GM 145 B; door toggle 45 B (prototype `door` message; the M3 `wall` upsert is a + little larger). +- Full vision polygon in integer px halves the text size [INFERRED]. + +### 6.5 Refusals, errors and connection outcomes + +**Rule:** DESIGN §6.5. + +- Consequence for tests: every close assertion is "the last message is `closing` with this reason and + code, then the close event reports 1005". The proving group is §10.3 Protocol. + +### 6.6 HTTP surface in M3 + +**Rule:** DESIGN §6.6. + +- `GET /tiles/...`: the full status split (DESIGN §3.3) is pinned by the tiles group (§3.3, §10.3 + Tiles). + +--- + +## 7. Client + +### 7.3 Fog rendering + +**Rule:** DESIGN §7.3. + +- Browser rendering of fog/drag/reconnect is unverified in the prototype (no browser in the build env). + M4 adds a headless-browser pixel check (§10.3 Browser e2e), which is the acceptance criterion for the + explored/vision layers. + +--- + +## 10. Testing strategy + +Every rule in DESIGN maps to a block above; this section is the test plan itself: what carries over +from the prototype, what was missing, what the M3 build added, and the tools it uses. + +### 10.1 Carry over (port, keep as acceptance gates) + +| Test | From | Notes | +|---|---|---| +| Geometry unit tests (M1 port baseline: 33 test blocks / 98 checks, none dropped; current count in `results/nimble-test.log`) | `tests/tgeometry.nim`, `results/nimble-test.log` | Port with `geometry.nim`. | +| Geometry mutation check | `tools/mutation.sh` (a: no +-RayEps rays, b/c: upper/lower segment end exclusive) | Control passes, each mutation fails >= 1 test [MEASURED 1, 2, 2]. Port. | +| Leak test | `tools/leak.mjs`, `leakcheck.nim`, `leaktest.sh` | Subject A and B, fresh DB, ~240 steps; asserts (a)-(e) in README. Independent LOS oracle for token visibility (added after the bow-tie bug). | +| Negative control / fault injection | `tools/faulttest.sh`, `-d:leakfault` build | 8 faults, exact failure-class set each, clean build passes, `LEAK_FAULT` string asserted absent from clean binary [MEASURED 8/8]. Port and extend. | +| Restart | `tools/restart.mjs` | SIGTERM + SIGKILL, identical player keys/positions/doors/vision/explored/hello+state. | +| Concurrency | `tools/concurrency.mjs` | 60 s, 3 clients, gseq monotonic, every intent acked, quiesced views == fresh connection. **M5 port [FIXED, #15]:** 6 walkers on one GM socket (~200/s) exceeds the 30/s per-connection rate (DESIGN §6.4); spread walkers across connections (4 per player, 16 total; DESIGN §4.3). | +| Client reducer tests | `client/src/state.test.ts` | Incl. reconnect reset. | +| Smoke | `tools/smoke.mjs` | auth/cookie/tile/steal/garbage. | +| Isolation harness | `tools/withserver.sh` | own DB/ports (`run/test/`), never touch a live session. | + +### 10.2 Known test gaps to fix while porting + +- Shared-endpoint test passes with the horizontal arm removed [MEASURED, `HANDOFF.md`]: port a test + that fails if either arm is missing, verified by a new mutation (d) in the mutation script. +- Explored/tile checks use the server's own `cellsTouched` (self-consistency). New **independent + explored oracle**: brute-force per-cell sampling with the clear-LOS segment test over cell + centres/corners; compare as superset/subset with a stated tolerance [PROPOSED]. Differential test + old `cellsTouched` vs scanline version (M2). +- Leak checker oracle initially only checked "nothing extra", not "everything visible shows"; the + completeness check is kept (assert (b)). + +### 10.3 New + +- **Fault classes.** Each class has an injected fault (`-d:leakfault`, `LEAK_FAULT=`) and an + exact-class assertion; the shipped binary must contain no `LEAK_FAULT`. Built: `HIDDEN_TOKEN`, + `GMONLY_TOKEN`, `WALLDATA`, `WITHHELD`, `NO_REMOVE`, `OWN_VIEW`, `OTHER_PLAYER`, `EXPLORED`, + `OWNER_PROP`, `GM_PROP`, `STATUS_SOURCE`, `ACTUAL_NAME`, `STALE_NAME`, `CHAR_LIST`, + `CONTROLLER_CHANGE`, `CHAR_OWNER_PROP`, `MARKER_EARLY`, `MARKER_EXTRA`, `MARKER_OFF`, `ONEWAY`, + `KEY_IN_LOG`, `secretgap`. `tools/leakcheck.nim` refuses the `gm` bucket, the `owner` bucket on a + non-controller and any `source` on a player status entry. Two consequences: the `hidden` and + `gmOnly` faults also produce `NO_REMOVE` (a leaked token whose frame never changes leaves the client + holding it with no correcting message, indistinguishable from a withheld `token_gone`; both + invariants are broken), and the tile gate is HTTP-plane, so `tools/tiles.test.mjs` proves it (10.3 + Tiles), not the WS transcript checker. `GLOBAL_COUNTER` is structurally impossible (per-connection + `n`). +- **Characters and names (#14)**: tests for reveal per player and reveal to all; owner sees own actual + name; a character owner change leaves token controllers unchanged; encountered entries survive token + removal and a `gm_only` flip (greyed) and are removed only by the GM; `gm_only` tokens never enter an + encountered list. Group: `tools/characters.test.mjs`, including "a status source is not shown to a + non-GM" (the controller included). Fault classes: `ACTUAL_NAME`, `CHAR_LIST`, `CONTROLLER_CHANGE`, + `CHAR_OWNER_PROP`. +- **Tiles (#24)**: `tools/tiles.test.mjs` is the group's leak check (d) and the smoke tile-steal + checks, through the real binary and a test nginx (`tools/nginx.mjs`, nginx from devbox; config + generated per run in the state dir). An **independent explored oracle** (born in 10.2) recomputes + visibility per cell from the GM's walls and the token's vision radius with its own clear-segment + maths (inscribed 64-gon radius - 0.5 px for "sure", radius + 0.5 px and proper crossings for + "maybe"): a `200` must be oracle-maybe (no invented disclosure) and oracle-sure must be `200` (no + withheld tile). The 32x32-tile sweep is 1024 requests; slice 9's scene allows 283, all 283 + oracle-sure, 0 maybe-refused. Also checked: a player with no sight state gets `403`; another player + gets `403` on a tile its neighbour sees; direct `/_tiles/` is `404` (the file exists) for every + identity; malformed/canonical/out-of-range/stale-version/scene paths are `404` (with and without a + session, including the GM); traversal and encoded shapes never reach a file; the direct-from-Nim + answer carries `X-Accel-Redirect: /_tiles/1/v1/_.png`, `Cache-Control: private` and an empty + body. Fixture tiles are 32 px PNGs written by `tools/tilefixture.mjs` under the state dir at test + time; the test asserts the repo tracks no `.png` at all. +- **Probing test (T8)**: M2, in-process against the move-rules module (DESIGN §5.5): arbitrary far + moves; assertion: facts about walls/doors beyond LOS recoverable from replies <= a bounded amount + (step cap), and uniform nack shape. M3: same test over WS with a hostile client (moved from M2). +- **Door equivalence (#46, T17)**: `tools/doors.test.mjs` is the accept group for the "a player cannot + tell a secret or locked door from a wall" obligation DESIGN §5.8 states. Node harness, built-ins only + (10.4), shaped like `tools/probing.test.mjs`: two servers, fresh state, two scenes identical except + one segment, one identical scripted sequence. Pairs: (i) solid `wall` vs a closed `door` with + `secret`; (ii) solid wall vs a closed door with `secret` and `locked`; (iii) closed `door` vs a + closed `door` with `locked` (since #48 there are no `secret_door`/`locked_door` presets: the switches + are the same, only the name changed). Script, run against both servers in lockstep: player tokens + with vision near and around the segment; player moves along, into and across it (accepted, collision + nacks, over-cap nacks); the GM adds the segment over a player token (`stuck`); the GM edits and + toggles unrelated walls and doors elsewhere and moves tokens; a resync/reconnect; a GM `door.set + open` on the secret/locked segment, refused `invalid` and GM-side only. **Assertion:** each player's + complete received frame sequence — `hello`, `vision`, `explored` (full and delta), `token` (statuses + included), `encountered`, and every `ack`/nack with its `code` and `pos` — is identical between the + two runs after JSON canonicalisation (keys sorted, no numeric reformatting). **Normalisation allowed: + none**; `n` is per connection and wall ids never reach a player, so nothing run-local leaks into the + comparison. If the build ever forces a run-local difference it must be named in the test header with + the reason. **Tiles:** the same per-player tile sweep in both runs, through the test nginx + (`tools/nginx.mjs`, §11.1), must give the same status per tile. **Positive control:** the same script + against a third scene whose segment is an open door (or absent) must produce *different* transcripts, + otherwise the harness cannot fail (this file's first principles). **Negative control:** a + `-d:leakfault` build with `LEAK_FAULT=secretgap` makes a secret door not block sight (or movement) + in the player-facing computation; the doors group must fail with that build, pass on a clean one, and + the shipped binary must carry no fault hook (10.1, `tools/fault.test.mjs`). **Refusal codes:** + `door.set` on a secret or locked door is `invalid` for the GM; a player `door.set` is `not-allowed` + for every door (DESIGN §6.5), so the player side has one code and no oracle. **Not covered:** timing + and size side channels (T11), accepted and unchanged. +- **Door push with thickness (#50).** In-process pins in `tests/tmoverules.nim` (DESIGN §5.5). + **Zero-thickness regression gate:** the existing push tests run unchanged and keep their exact + positions (including "past the end", where the along-axis coordinate does not move). **Thick cases:** + face push by `r` with the along-axis coordinate kept; past an end, push to `r` around the nearest end + corner; inside the body, out of the `prev` side (left with no history); first side invalid (another + blocking body or out of bounds) falls back to the other; both invalid leaves the token and `squeezed` + while the door closes; `position` `left`/`right` moves the body and the target by the thickness. + **Equivalence:** the #46 two-server test gains thick pairs (thick secret door vs thick solid wall; + thick locked door vs thick plain door), byte-identical. Also pinned: a fixed window and an open door + never push, and no wall edit pushes. **Mutations:** push from the drawn line; push ignoring the normal + span; ambiguous side ignoring `prev`; validity check on the door only — each fails at least one test. +- **One-way direction (#47)**: `tools/leakcheck.nim` and the independent explored/tile oracle apply + **their own** side test — sign of the cross product of `viewer - a` with the `(-dy, dx)` normal of + `a -> b`, positive = left — never by calling `vision.nim`: a sight-blocking one-way wall is dropped + from the oracle's wall list for a viewer on its blind side, and a wall that is `blocks_sight:false` + is dropped for everyone. Assertions: a token on the blind side gets no polygon point, explored cell + or tile beyond the wall, and a token across it gives no `token` frame, no name and no encountered + entry; a viewer on the seeing side does see across (the positive control, so the oracle can fail). + Tolerances as elsewhere: the 0.5 px boundary band along the blind side is oracle-*maybe* (a `200` + there is legitimate, but never *sure*), and anything clearly behind the blind wall is + oracle-refused (a withheld proof cell still fails). New fault class `ONEWAY` — the player-facing + computation drops `sight_dir` and lets the blind side see across — with its injected fault and + exact-class assertion, shaped like the existing classes. +- **Player marker (#48; shape fixed by #49).** `leakcheck.nim` allows the `marker` type and, with its + own code (never calling `vision.nim`), checks that a marker exists for a player exactly when some + point of the wall's visible extent has entered that player's polygon **and** the wall is + `player_marker:true` and derives `window`, and that the frame carries only the opaque marker id and + the anchor: anything else is `WALLDATA`/`MARKER_EXTRA`. Positive control: a window in the open yields + exactly one marker once its anchor is seen; a wall behind a sight blocker, `player_marker:false`, or a + solid wall with the switch on yields none. Faults: `MARKER_EARLY`, `MARKER_EXTRA`, `MARKER_OFF`. + Retraction is checked GM-side: removing the wall, clearing the switch or moving the geometry retracts + the marker, never sends the new position early, and writes no explored cell or tile. +- **Wall fields, storage and migration (#49).** Three gates. **Leak:** `BannedAlways` contains every + wall field name (`thickness`, `position`, `height`, `blocks_sight`, `blocks_movement`, `sight_dir`, + `player_marker`, `door`, `open`, `secret`, `locked`, `label`, `a`, `b`), so any of them in a player + frame is `WALLDATA`; `marker` is an allowed server type with its own oracle; positive control: a wall + `height` injected into a player `token` frame fails with exactly `WALLDATA`. **Migration:** a + schema-7 fixture (both wall kinds, an open door, non-empty `flags`, tokens and a character with props) + migrates under the real binary, every decoded row equals the DESIGN §4.4 mapping, `props_gm.height` + is `1.8` on every token and character and `eye_height` untouched; a second run is a no-op and a + failing step rolls back. **Behaviour:** one scene built through `wall.add` with today's switch set and + one migrated schema-7 scene holding the same walls produce byte-identical player frames, refusals and + per-tile statuses for the same script; the #50 zero-thickness push tests pass unchanged against + migrated rows. Fixture churn: `tests/tdb.nim` `LatestVersion` 8, `tools/persistence.test.mjs` + schema-8 assertions and the schema-7 fixture, and every hand-built `wall` row gains the columns. +- **Auth tests**: key replace (old key invalid, sessions revoked, live connections closed), remove + player (key invalid, characters and tokens pass to GM), one key reused on several devices (Q10 + FIXED), Origin mismatch rejected, cookie flags present. +- **Protocol tests** (#18, `tools/protocol.test.mjs`): proto missing/non-integer (HTTP 400) and mismatch + (`closing` 4003, no `hello`); unknown intent type (`unknown-type`) with unknown fields ignored; + exactly one `ack` per `reqId` (reqId 0 and 2^31-1 included); `hello` first with `n = 1` and a + per-connection `n` thereafter; `error malformed` for unreadable frames; the malformed flood (nine + tolerated, the tenth closes 1008); the intent bucket (burst then `rate-limited`, connection stays + open, a refused intent applies nothing, `error rate-limited` for an unreadable frame on an empty + bucket); the 64 KB inbound boundary (exactly 64 KB is a message, 64 KB + 1 drops the TCP connection + with no close frame); unmasked and bad-opcode frames; the server Ping and the Pong answer to a client + Ping; the connection cap (503 + `Retry-After: 5`); and every server-initiated close as `closing` then + 1005. +- **Persistence**: migration tests (old DB -> new), chunked explored round trip, restart extended to + wall CRUD and entity props. `tests/texplored.nim` pins the chunk layout, whole-chunk encoding, upsert + replacement, per-player keying, restore and write cost; `tools/persistence.test.mjs` covers the + fresh-resync round trip, per-player isolation, SIGTERM/SIGKILL equality, a wall removal's revealed + cells after the wall returns, independently decoded chunk rows, move-ack timing, and a fixture DB + migrated by the real binary. +- **Restart (#25)**: `tools/restart.test.mjs` is the "restart" accept group. It builds one world that + exercises every CRUD path (walls and an open door, plain/monster/player/linked tokens, a resize and a + GM status, props in three buckets with a `prop.unset`, a character with props, a per-player reveal + and a token `reveal_all`, a sighting in the encountered list, players and a name) and compares the + complete DESIGN §6.3 resync of a fresh GM connection and a fresh player connection before and after + the restart: hello scene block, roster, walls, characters, tokens, encountered, vision and the full + explored RLE, all normalized (only the per-connection `n` is dropped) and deep-equal. Both SIGTERM + and SIGKILL are checked, because every ack follows its COMMIT (DESIGN §4.2). +- **Logs (#25)**: `tools/logs.test.mjs` is the "logs" accept group. It records every GM key (the CLI + key, a `--new` rotation, an old key after rotation), every player key (`key.create`, `key.show`, + `key.replace`), every session cookie from `/join` (several devices) and its SHA-256 hash, plus a + wrong key, a refused tile, a proto mismatch and a malformed frame, across two server runs on the same + state dir, then greps the whole `server.log` for every value: none may appear. The second test is the + negative control: a `-d:leakfault` build with `LEAK_FAULT=keylog` writes a raw key to stdout past + `eventlog`, and the same grep must find it (so a log that was never captured cannot pass). +- **Slow client** (Q13, DESIGN §4.3): a client that stops reading; outbox stays under cap, no further + state is queued to it, RSS flat, full resync on recovery equals a fresh connection; nginx closes the + dead `/ws` socket within its configured timeout. +- **Browser e2e (new, none in prototype)**: headless Chromium via playwright-core (the perf prototype + already drives devbox chromium, `prototype-pixi-perf/bench.mjs`; SwiftShader is fine for correctness, + not for perf). Checks: join -> canvas renders; pixel probe shows unexplored area black, visible area + map-coloured, dimmed explored area; GM sees walls, player DOM/network contains none; reconnect + restores view; drag moves token and rollback works. +- **Independent traffic audit in e2e**: record all WS frames and HTTP responses seen by a player + browser and run the leak checker's (a)(e) assertions over them. + +### 10.4 Test tools [FIXED, owner decision 2026-11-14, #9] + +- Black-box (outside) WS/HTTP harnesses: Node 26 only, repo-root `tools/`, ported from + `prototype-server-vision/tools/` (`smoke.mjs`, `leak.mjs`, `restart.mjs`, `concurrency.mjs`, + `lib.mjs`, `withserver.sh` incl. the M3 test nginx). No Nim rewrite. Reason: Node is already required + for the client (Vite/TS, playwright-core e2e, reducer tests); a harness in another language from the + server cannot share its protocol bugs; zero deps; already measured. The harness lives in + `tools/withserver.mjs`; the test nginx is `tools/nginx.mjs`. +- Harness tooling: built-ins only, no npm deps. Global `WebSocket` with `{headers}` for Cookie/Origin; + `node:net` for raw and malformed frames (oversize, bad opcode/rsv, unmasked, flood); `node:test` as + runner. Node 26 header behaviour [MEASURED, 2026-11-14, #16, node v26.11.1]: `{headers}` still puts + `Cookie` and `Origin` on the wire, and without `{headers}` no `Origin` is sent; pinned by + `tools/wsheaders.test.mjs` so a Node upgrade that drops the option fails loudly. +- Root `devbox.json` pins `nodejs` 26 and the `nginx` used only by the test harness (DESIGN §11.1); no + global tooling. +- `devbox run test` = Nim tests first, then Node harnesses. +- The nine M3 accept groups and their proving harness tests are mapped in `tools/groups.mjs`; + `tools/groups.test.mjs` fails if a group file or its named evidence test disappears, so the + acceptance checklist cannot silently go stale. Harnesses that are not an accept group (`smoke`, + `walls`, `tokens`, `details`, `scene`, `wsheaders`) run in the same pass. +- In-process tests stay Nim (`nimble test`, unchanged). +- Browser e2e details: M4, not decided here. + +--- + +## 11. Ops + +### 11.1 Deployment on NixOS + +**Rule:** DESIGN §11.1 (module, config keys, vhost shape). + +- Test nginx [FIXED (owner-delegated), #24]: `tools/nginx.mjs` starts the devbox `nginx` package on a + free loopback port in front of the harness server, with a config generated per run under the + server's state dir (ports and state paths never committed). It mirrors the vhost shape DESIGN §11.1 + describes: `/join` (`access_log off`), `/tiles/` proxy, `/ws` upgrade, `/healthz` readiness, and + `location /_tiles/ { internal; alias /tiles/; }`. Tile bytes are 32 px fixture PNGs from + `tools/tilefixture.mjs`, written under `/tiles/`; none is committed. + +### 11.2 Backups + +**Rule:** DESIGN §11.2. + +- Restore drill documented and tested once (M6): restore into a temp dir, start server, run the + restart-equivalence assertions (§10.3 Restart). + +### 11.3 Logging and metrics + +**Rule:** DESIGN §11.3. + +- The `SLOW` line (total > `SLOW_MS`, default 50) with breakdown `lock_wait / vision / sqlite / send / + other` and intent type is what diagnosed the SQLite COMMIT tail [MEASURED, + `results/spike/investigation.md`]. +- The prototype's instrumentation appends every sample to unbounded arrays and sorts them inside + `finish()` under the global lock; **do not port** [MEASURED/HANDOFF]. + +--- + +## 13. Build status and milestones + +**Rule:** DESIGN §13 (milestones and their accept criteria). Gate mechanics and measured results: + +- **M1.** `geometry.nim`, `tgeometry.nim`, the mutation script and the shared-endpoint arm test. +- **M3 accept result.** Measured 2026-11-15: `devbox run test` exit 0 (Nim suite all pass; 103 Node + harness tests) and `devbox run mutation` exit 0 (control passes, all 63 mutations fail at least one + expected test). The nine groups map to their proving tests in `tools/groups.mjs`; + `tools/groups.test.mjs` fails if a group or its named evidence test disappears. +- **M4 client gates.** (a) automated headless-Chromium test with mobile emulation (viewport, dpr, CPU + and network throttle) against the real server path (nginx HTTP/2 + caching); (b) one manual run on + the owner's 5-year-old Android phone. The 2026-11-08 prototype phone run is evidence, not the gate + (HTTP/1.1, no-store, zoom 0.5 only, first cold load up to 3.3 s). If either fails, the fallback in + DESIGN §13 applies. +- **M5 accept.** Concurrency 60 s x3 with p99 <= the prototype's 4.98 ms + 50%; the slow-client test + (§10.3); nginx closes a dead `/ws` within its configured timeout; stats computed outside the lock. +- **M6 accept.** Deployed behind HTTPS; direct `/_tiles/` 404; WS upgrade works; phone sign-in works; + no secret in the access log; backup and restore drill passes.