The owner fixed the map cap at 1920 px on the long side and 1080 px on the short side (either orientation). fff-vtt import now shrinks a larger source with ImageMagick Lanczos before tiling (alpha kept, proportions preserved, no upscaling), prints `scaled WxH -> WxH`, and records the shrunk w/h; a source at or below the cap is untouched, so the pixel-identity tests still hold. A scene row already above the cap is not rewritten: the server logs `map_above_cap` at startup and serve prints the re-import advice. Docs: ADR-0023, DESIGN 3.3/5.3/8/11.1/13/14, TESTING 5.3/13, README, HANDOFF-M4, client README. The M4 phone gate and the fogbench measurement now use the Full HD maximum; the 16384 px / 262144-cell bench and test rows stay as labelled server stress references. import-scale now proves a 16384² input is shrunk to 1080x1080 (289 tiles at 64 px) quickly and bounded. Part of #63, #85. #77 is blocked by this issue.
50 KiB
FFF_vtt testing
Status: how docs/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):
docs/archive/prototypes/pixi-perf/(client perf; README holds all tables)docs/archive/prototypes/server-vision/(server + vision;README.md,HANDOFF.md,NOTES.md,results/,results/spike/investigation.md)docs/archive/prototypes/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. Run everything from the repo root through devbox run.
Do not export devbox's LD_LIBRARY_PATH into host tools or stale binaries. The devbox store is
built against glibc 2.44 while this host (NixOS) runs 2.42, so a 2.44-built libsqlite3 loaded by a
2.42 loader fails at load time (or loads a mismatched libc). Rebuild after a devbox.lock change
(devbox run test/bench do it on first use); never reuse a binary built before the change.
3. Security model
3.1 What each role receives
Rule: DESIGN §3.1.
gm_onlyis enforced in the view builder, before any frame is built; fault classGMONLY_TOKEN(§10.3).
3.3 Tiles
Rule: DESIGN §3.3.
- Direct hits on
/_tiles/give 404 [MEASURED:docs/archive/prototypes/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:
docs/archive/prototypes/tile-leak/README.md(desktop numbers; phone run 2026-11-08). M4's tile-size gates are in §13 below. Cache-Control: privateis 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:
404also for another scene or a stale art version,403also for a missing or unknown session (one response with "unexplored"), andCache-Control: private. The proving group is §10.3 Tiles (tools/tiles.test.mjs). - Map import (#79) writes the tree this gate parses:
tools/import.test.mjsruns the real binary'sfff-vtt import, checks the exact<x>_<y>.pngset and per-tile geometry, then starts the real server and test nginx and proves a player with an explored overlapping cell gets200(and an unexplored tile403, another art version404). A re-import growsart_versionand the restarted server serves thev<new>tree. The CLI also creates and migrates a fresh/empty state dir through the server's startup path (#82), so an import works before the first serve. Every refused import (bad/absent image, unsupported or multi-frame format, scene ≠ 1,tile_size % cell ≠ 0, malformed DB, or a running server holding the lock) exits non-zero and leaves no tile tree;serve --imageruns the import before starting the stack. This is §10.3 Tiles evidence.
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]; door-equivalence test (T17, §10.3) [MEASURED caught: fault secretgap]; MARKER_EARLY/MARKER_EXTRA/MARKER_OFF (§10.3) [MEASURED caught: tools/fault.test.mjs, Walls r1 #60]; scenario coverage of the rewritten leak world (Walls r1 #61) [MEASURED: tools/leak.test.mjs] |
| 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 [MEASURED], fault secretgap [MEASURED caught: SECRETGAP], door-key scan in tools/leakcheck.nim -> WALLDATA (Walls r1 #56) |
4. Server
4.1 State model
Rule: DESIGN §4.1.
- Monsters/NPCs have no vision [MEASURED design:
vision_ms move-monster0.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
WebSocketfields 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: the seeded 4096 px map / 32 px cell = 16 384 cells = 2 KB (2x2 chunks); the largest Full HD scene (60x34 cells) is one 512 B chunk (#85). - The chunk layout is pinned by
tests/texplored.nim(exact byte/bit positions) and re-read independently bytools/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 bytests/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 inresults/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
[MEASURED; single laptop, release build, loopback, power-save CPU]: results/bench.log,
results/concurrency-final1-server.log.
| item | avg | worst |
|---|---|---|
| 1 visibility polygon (prototype scene, 60 walls) | 0.038 ms | 0.18 ms |
1 polygon + cellsTouched |
0.451 ms | 0.98 ms |
6 polygons + cellsTouched |
2.95 ms | 3.73 ms |
| server vision recompute per player move (incl. cells + diff) | 1.18 ms | 4.55 ms |
| door toggle (2 players) | 0.20 ms | 0.30 ms |
| monster move | ~0 | 0.024 ms |
cellsTouchedis ~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].- The prototype scene the table measures has 60 walls and 8 tokens, so its numbers say nothing about big maps; the 5k bench scenes below are the answer.
- Product maximum [FIXED (owner decision), 2026-11-21, #85]: map images are capped at Full HD, so the largest scene is 1920x1080 (60x34 cells at cell 32). The fog measurement and the M4 phone gate use that maximum; numbers below at 16384 px / 262144 cells are labelled server stress, not the product target.
- Bench scenes (
tools/scenegen.nim): the sparse stress layoutgenScene(16384, 5000, 1): 0.058 ms avg [MEASURED,results/bench.log]. The dense layoutgenScene(4096, 5000, 1)is also a stress reference (1.409 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 the committed baselines; the 2x threshold and its [PROPOSED] status are in DESIGN §5.3. - In-process egress gate (#28,
tests/tviews.nim): wall-clock gates are load-sensitive, so every asserted number is the fastest of 20 timed passes after a warm-up (min-of-N), never a mean: a pass the OS descheduled is not the minimum, while a regression raises every pass. Stated budgets are 10 us for oneContextbuild and 2 ms for one egress pass (M5's 7.5 ms is a whole-mutation p99, not a per-pass mean; the #28 shape measured 0.79 ms GM / 0.32 ms player on the reference build, 0.5-1.7 ms in the debug suite depending on CPU clocks). The gate allows a documented 2x around each budget (20 us, 4 ms) for a saturated box. The load-insensitive explored-size invariantsmallMs <= gmMs*3 + 0.5(synthetic 16384 vs 262144 cells; the Full HD product maximum is 2040 cells, #85) is kept on minima. Absolute averages are recorded, not asserted, bydevbox run bench(results/bench.log: GM egress pass 0.24 ms, player 0.08 ms, release build).
5.4 Known limitations
Rule: DESIGN §5.4.
- Token exactly on a wall cannot move off it [MEASURED limit,
tests/tgeometry.nimtest "KNOWN LIMITATION: token exactly on a wall cannot move off it"; also in theserver/geometry.nimheader]. - 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).
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" =
visibilityPolygonandcellsTouchedon the prototype leak transcripts plustests/fixtures/scene.json.moveBlockedis excluded: its results change on purpose.
5.7 Heights
Rule: DESIGN §5.7.
- A wall's
heightis in leakcheck'sBannedAlways(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
labelis in the leak checker'sBannedAlwayskey scan (§10.3), so a player frame carryinglabelisWALLDATA. - One-way sight (built, #58): the two sides, the direction flip, monotone explored/tiles and the
restart are proven by
tools/oneway.test.mjs; the checker's own side test and theONEWAYfault are in §10.3.
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'sclearLinegets 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 (a200on a band cell is legitimate, a withheld proof cell never). A token hidden only by the band gives notokenframe, 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,thicknessandpositionwith their own code, never by callingvision.nimor 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 inclient/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
knowntable gives correct enter/leave [MEASURED, leak test (c)]. - The stored diff base is the frame before the per-connection
nis stamped:protocol.withNdeep-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 fullvisionpolygon +exploreddiff), GM 145 B; door toggle 45 B (prototypedoormessage; the M3wallupsert is a little larger).
6.5 Refusals, errors and connection outcomes
Rule: DESIGN §6.5.
- Consequence for tests: every close assertion is "the last message is
closingwith 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
Rule: DESIGN §10 (the pointer section that keeps 10.1-10.4 as references to this section).
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). Walls r1 #61 rewrote the scenario into one world (a marked window, a one-way wall, a secret and a locked door, marked walls on both sides of the sight test) and tools/leak.test.mjs asserts that coverage. |
| 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/test/*.test.ts (Vitest) |
Pure frame/ack -> state; hello resets every slice. No Pixi or DOM import at the seam. |
| 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 oldcellsTouchedvs 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=<name>) and an exact-class assertion; the shipped binary must contain noLEAK_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,KEY_IN_LOG,ONEWAY(#58),MARKER_EARLY,MARKER_EXTRA,MARKER_OFF(#60). Walls r1 built:secretgap(#56), asserted as exactlySECRETGAPbytools/doors.test.mjs(the differential group, not the transcript checker);MARKER_EARLY/MARKER_EXTRA/MARKER_OFF(#60), each asserted as exactly its own class bytools/fault.test.mjs(the leak transcript checker, with the scenario's unseen marked window and marked solid wall as the negative controls). The scenario itself (Walls r1 #61) is one coherent world, not appended fragments: a room with an opening door, a far wall holding a solid stretch, a secret door and a locked door with a token behind each, a one-way screen, a marked window the subject sees, the same window's switch cleared and restored (retraction and re-earn), a marked solid wall and a marked window the subject never sees.tools/leak.test.mjsasserts that coverage from the GM's wall frames and the subject's marker frames, so a rewrite that drops an element fails on its own, not only inside a fault. The world also holds a wall lying along one of the subject's vision rays with a token beyond it on the same line: a zero-width wall hides exactly that line, andHIDDEN_TOKENis the token-level assertion for it (#26) — the class checks a token's own centre and the viewer -> token segment against the walls, not sampled polygon points, because theGEOMETRYclass only tests missing vision and cannot see an over-approximation. All pre-existing classes still fire under the rewrite, each as exactly its own class (all 21 entries of theFAULTStable oftools/fault.test.mjs, 22 tests with the clean-build gate).tools/leakcheck.nimrefuses thegmbucket, theownerbucket on a non-controller and anysourceon a player status entry. Two consequences: thehiddenandgmOnlyfaults also produceNO_REMOVE(a leaked token whose frame never changes leaves the client holding it with no correcting message, indistinguishable from a withheldtoken_gone; both invariants are broken), and the tile gate is HTTP-plane, sotools/tiles.test.mjsproves it (10.3 Tiles), not the WS transcript checker.GLOBAL_COUNTERis structurally impossible (per-connectionn). - 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_onlyflip (greyed) and are removed only by the GM;gm_onlytokens 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.mjsis 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"): a200must be oracle-maybe (no invented disclosure) and oracle-sure must be200(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 gets403; another player gets403on a tile its neighbour sees; direct/_tiles/is404(the file exists) for every identity; malformed/canonical/out-of-range/stale-version/scene paths are404(with and without a session, including the GM); traversal and encoded shapes never reach a file; the direct-from-Nim answer carriesX-Accel-Redirect: /_tiles/1/v1/<x>_<y>.png,Cache-Control: privateand an empty body. Fixture tiles are 32 px PNGs written bytools/tilefixture.mjsunder the state dir at test time; the test asserts the repo tracks no.pngat all. - Map import CLI (#79):
tools/import.test.mjsis the black-box harness for the offlinefff-vtt importsubcommand (DESIGN 11.1, 3.3). It writes a real fixture PNG at test time, runs the binary, and asserts the exact gate tree (tiles/1/v1/<x>_<y>.png, row-major, 4x3 at 64 px), each tile's 64x64 geometry, the scene row viahello.scene(w, h, tile_size, art_version), and a player with an explored overlapping cell getting200through the real nginx+server stack while an unexplored tile gets403and a stale version404. A second import must growart_versionand a restarted server must serve thev<new>tree (the persisted explored grid still allows it). Negative cases each exit non-zero and leave no tile tree: missing/unsupported/multi-frame image,--sceneother than 1,tile_size % cell != 0, absent state dir, state dir withoutstate.db, and a running server holding the state-dir lock (exit 3).tools/groups.mjsregisters the first title as Tiles evidence. - 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) — built: Walls r1 #56,
tools/doors.test.mjs. It 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): two servers, fresh state, two scenes identical except one segment, one identical scripted sequence. Pairs: (i) solidwallvs a closeddoorwithsecret; (ii) solid wall vs a closed door withsecretandlocked; (iii) closeddoorvs a closeddoorwithlocked(since #48 there are nosecret_door/locked_doorpresets: 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 GMdoor.set openon the secret/locked segment, refusedinvalidand GM-side only. Assertion: each player's complete received frame sequence —hello,roster,vision,explored(full and delta),token(statuses included),encountered, and everyack/nack with itscodeandpos— is identical between the two runs after JSON canonicalisation (keys sorted, no numeric reformatting). Normalisation allowed: the one run-local value a fresh two-server world forces is an opaque token id (the server CSPRNG, DESIGN 8); the harness maps each run's ids toTOK<n>in creation order and sorts an encountered list by that id before comparison. Nothing else is normalised:n, player ids, positions, statuses, polygons, explored cells and tile statuses compare byte for byte. Tiles: the same per-player tile sweep in both runs, through the test nginx (tools/nginx.mjs, §11.1), must give the same status and body per tile. Closing push: the script closes an ordinary door over a token and pins the resulting position (320,350), the zero-thickness push gate unchanged. Positive control: the same script against a scene whose segment is an open door must produce different transcripts, otherwise the harness cannot fail (this file's first principles). Negative control: a-d:leakfaultbuild withLEAK_FAULT=secretgapmakes a secret door not block sight in the player-facing computation; the pair then fails as exactlySECRETGAP, the clean build passes, and the shipped binary carries no fault hook (10.1,tools/fault.test.mjs). Refusal codes:door.seton a secret or locked door isinvalidfor the GM; a playerdoor.setisnot-allowedfor 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 byrwith the along-axis coordinate kept; past an end, push toraround the nearest end corner; inside the body, out of theprevside (left with no history); first side invalid (another blocking body or out of bounds) falls back to the other; both invalid leaves the token andsqueezedwhile the door closes;positionleft/rightmoves 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 ignoringprev; validity check on the door only — each fails at least one test. - One-way direction (#47; built: Walls r1 #58):
tools/leakcheck.nimand the independent explored/tile oracle apply their own side test — sign of the cross product ofviewer - awith the(-dy, dx)normal ofa -> b, positive = left — never by callingvision.nim: a sight-blocking one-way wall stays in the oracle's wall list only for a viewer on its blind side (the sidesight_dirnames), and a wall that isblocks_sight:falseis 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 notokenframe, no name and no encountered entry; a viewer on the seeing side does see across (the positive control, so the oracle can fail).tools/oneway.test.mjsruns the two sides, thesight_dirflip with fixed endpoints, the monotone explored/tile set across flips and a restart, and the per-tile sweep with the same own side test. Tolerances as elsewhere: the 0.5 px boundary band along the blind side is oracle-maybe (a200there is legitimate, but never sure), and anything clearly behind the blind wall is oracle-refused (a withheld proof cell still fails). Fault classONEWAY(built) — the player-facing computation dropssight_dir, so the one-way wall becomes two-way — with its injected fault (LEAK_FAULT=oneWay) and exact-class assertion, shaped like the existing classes. - Player marker (#48; shape fixed by #49; emission/storage/oracle built #59; retraction and the
exact fault classes #60).
leakcheck.nimallows themarkertype and, with its own code (never callingvision.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 isplayer_marker:trueand deriveswindow, and that the frame carries only the opaque marker id and the anchor: anything else isWALLDATA/PROTOCOL. Positive control: a marked window the subject sees yields exactly one marker at its drawn midpoint; a wall behind a sight blocker,player_marker:false, or a solid wall with the switch on yields none. The oracle's expected set accumulates like explored memory, so walking away, a door or lost sight never makes a sent marker wrong; a wall removal, a cleared switch, a lostwindowor a geometry move retract it (the oracle drops the entry when the GM's wall frame shows the cause changed, mirroring the server). An extra marker at a candidate's anchor before its extent was seen isMARKER_EARLY; an extra marker with no candidate wall isMARKER_EXTRA; an expected marker never sent isMARKER_OFF. The oracle keys a sent marker id by the GM-truth wall it belongs to (resolved by anchor), never by the anchor alone, so two candidate walls that share a midpoint remain two obligations. Marker ids are stable across refreshes: asetthat re-mints a wall's marker while its old id is still live isPROTOCOL— the four marker classes describe the emission gate, while id stability is a frame invariant (5.8: minted once, fresh only after a retraction). FaultsMARKER_EARLY,MARKER_EXTRA,MARKER_OFF(markerEarly/markerExtra/markerOff) are built and asserted as exactly their own class bytools/fault.test.mjs, with the scenario's far unseen marked window and marked solid wall as the negative controls. The WS grouptools/markers.test.mjsproves the four retraction causes (del only), a fresh id on re-earn, no re-send of an untouched marker, nosetanddelfor one id in a frame, no explored write from a pure retraction, and durability of the deletes across a restart. ALEAK_FAULT=markerCrashhook quits in a-d:leakfaultbuild between the wall commit and the derived write; after a restart the changed wall's marker is gone for all four causes while the untouched window's marker is restored (the positive control). The leak scenario (#61) also drives one retraction and one re-earn end to end, so the transcript checker's own memory drop is exercised inside the world. - Wall fields, storage and migration (#49). Three gates. Leak:
BannedAlwayscontains 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 isWALLDATA;markeris an allowed server type with its own oracle (built #59); positive control: a wallheightinjected into a playertokenframe fails with exactlyWALLDATA. Migration: a schema-7 fixture (both wall kinds, an open door, non-emptyflags, tokens and a character with props) migrates under the real binary, every decoded row equals the DESIGN §4.4 mapping,props_gm.heightis1.8on every token and character andeye_heightuntouched; a second run is a no-op and a failing step rolls back. Behaviour: one scene built throughwall.addwith 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.nimLatestVersion8,tools/persistence.test.mjsschema-8 assertions and the schema-7 fixture, and every hand-builtwallrow 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 (closing4003, nohello); unknown intent type (unknown-type) with unknown fields ignored; exactly oneackperreqId(reqId 0 and 2^31-1 included);hellofirst withn = 1and a per-connectionnthereafter;error malformedfor unreadable frames; the malformed flood (nine tolerated, the tenth closes 1008); the intent bucket (burst thenrate-limited, connection stays open, a refused intent applies nothing,error rate-limitedfor 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 asclosingthen 1005. - Persistence: migration tests (old DB -> new), chunked explored round trip, restart extended to
wall CRUD and entity props.
tests/texplored.nimpins the chunk layout, whole-chunk encoding, upsert replacement, per-player keying, restore and write cost;tools/persistence.test.mjscovers 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.mjsis 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 aprop.unset, a character with props, a per-player reveal and a tokenreveal_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-connectionnis dropped) and deep-equal. Both SIGTERM and SIGKILL are checked, because every ack follows its COMMIT (DESIGN §4.2). - Logs (#25):
tools/logs.test.mjsis the "logs" accept group. It records every GM key (the CLI key, a--newrotation, 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 wholeserver.logfor every value: none may appear. The second test is the negative control: a-d:leakfaultbuild withLEAK_FAULT=keylogwrites a raw key to stdout pasteventlog, 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
/wssocket within its configured timeout. - Browser e2e (new, none in prototype): headless Chromium via playwright-core (the perf prototype
already drives devbox chromium,
docs/archive/prototypes/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. The harness isclient/e2e/(the client package ownsplaywright-core, outsidetools/; TESTING 10.4 keeps the black-box harnesses npm-free) and the gate isdevbox run e2e, which builds the real client and is separate fromdevbox run test(§11.1). T4's slice of it (client/e2e/shell.test.mjs,mismatch.test.mjs): no session shows only the sign-in door and no canvas; a wrong and an unknown key give the same401and the same "Key not recognised." text; GM and player join, get the canvas and thehello/rosterHUD; a serverclosing{proto-mismatch}shows reload and stops; a revoked key returns the page to sign-in with no reconnection. - TLS/HTTP2 vhost (#66):
tools/vhost.test.mjs(built-ins,node:http2) is the independent client for the vhost itself: the generated certificate is self-signed and names loopback, ALPN selectsh2,/serves the clientdistwith indexno-cache,/assets/with a year-immutable cache and no SPA fallback for a missing hash, a client route falls back toindex.html, and direct/_tiles/is still 404.client/e2e/h2.test.mjsproves the same from real Chromium against the real Vite build (client/e2e/run.shrunsnpm run buildfirst):performance.getEntriesByType('navigation')[0].nextHopProtocolish2over TLS. The vhost group keeps a local stub dist becausedevbox run testmust not depend on the client's npm install. - Independent traffic audit in e2e:
client/e2e/audit.test.mjsrecords every WS frame and every HTTP response the player browser receives and judges them with its own catalogue and banned-key list (never importingtools/leakcheck.nim): only the 13 player frame types; no wall geometry or GM-only column at any depth; vision polygons only for the player's own tokens; no other player's id or out-of-sight token id; explored cells only inside a historical own-vision bbox and never near the other player; tiles only on/tiles/, only 200/403, every 200 covering an explored cell, and/_tiles/unreachable (direct fetch 404). It runs indevbox run e2ebeside the fog, drag and reconnect files. A negative control runs the same rules against a-d:leakfaultbuild withLEAK_FAULT=otherVision, so the rule that rejects a foreign vision polygon is proven able to fail.
10.4 Test tools [FIXED, owner decision 2026-11-14, #9]
- Black-box (outside) WS/HTTP harnesses: Node 26 only, repo-root
tools/, ported fromdocs/archive/prototypes/server-vision/tools/(smoke.mjs,leak.mjs,restart.mjs,concurrency.mjs,lib.mjs,withserver.shincl. 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 intools/withserver.mjs; the test nginx istools/nginx.mjs. - Harness tooling: built-ins only, no npm deps. Global
WebSocketwith{headers}for Cookie/Origin;node:netfor raw and malformed frames (oversize, bad opcode/rsv, unmasked, flood);node:testas runner. Node 26 header behaviour [MEASURED, 2026-11-14, #16, node v26.11.1]:{headers}still putsCookieandOriginon the wire, and without{headers}noOriginis sent; pinned bytools/wsheaders.test.mjsso a Node upgrade that drops the option fails loudly. - Root
devbox.jsonpinsnodejs26 and thenginxused only by the test harness (DESIGN §11.1); no global tooling. M4 (#66) addschromium(the browser e2e) andopenssl(generating the test certificate); the e2e's only npm dependency,playwright-core, is pinned byclient/package-lock.jsonand lives with the client, outsidetools/, so this built-ins-only rule keeps holding. devbox run test= Nim tests first, then Node harnesses.devbox run client-test= the client's Vitest seam (pure reducer, protocol client, envelope);devbox run e2e= the built client through the real server and vhost;devbox run fogbench= the 50-token Full HD (1920x1080, the max scene) server measurement (results/m4-fog-bench.log). The finish gate (#76) runs all of them plusmutationandbench.- The nine M3 accept groups and their proving harness tests are mapped in
tools/groups.mjs;tools/groups.test.mjsfails 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 and the client-side extension rules (append-only reducer slices and render
modules):
client/README.md.
11. Ops
11.1 Deployment on NixOS
Rule: DESIGN §11.1 (module, config keys, vhost shape).
- Test nginx [FIXED (owner-delegated), #24]:
tools/nginx.mjsstarts the devboxnginxpackage 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,/wsupgrade,/healthzreadiness, andlocation /_tiles/ { internal; alias <state>/tiles/; }. Tile bytes are 32 px fixture PNGs fromtools/tilefixture.mjs, written under<state>/tiles/; none is committed.- TLS + HTTP/2 + client dist (#66, spec #63 decision 6): the listener is TLS-only with
http2 on, because browsers negotiate h2 only over TLS and the session cookie isSecure.tools/tlsdev.mjsgenerates the self-signed certificate per run (SANlocalhost/127.0.0.1, never committed) and appends it to the process's default CA list, so fetch/WebSocket/node:http2verify it with verification on.distDir(default<state>/dist) is served at/with the production cache split; the tile/doors/oneway harnesses keep theirpublicOriginat the vhost, so they now run through the same TLS origin the browser uses.
- TLS + HTTP/2 + client dist (#66, spec #63 decision 6): the listener is TLS-only with
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
SLOWline (total >SLOW_MS, default 50) with breakdownlock_wait / vision / sqlite / send / otherand 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).
- M3 accept result. Measured 2026-11-20:
devbox run testexit 0 (Nim suite all pass; 149 Node harness tests) anddevbox run mutationexit 0 (control passes, all 78 mutations fail at least one expected test). The nine groups map to their proving tests intools/groups.mjs. Evidence is executable, not a title substring (#36):tools/groups.test.mjspins each test's exact title, a minimum assertion count and the calls its body must keep, and the last step ofdevbox run test(tools/evidence.mjs) parses the reporter output inresults/node-test.logand fails unless every registered test ran and passed. The restart group takes its baseline from the as-built state on the first server instance, before any restart, not from a state that has already been through one (#36). - M4 automatable gates result. Measured 2026-11-21 at the build commit (#76):
devbox run testexit 0 (Nim suite all pass, 419 OK checks; 159 Node harness tests with the group evidence step),devbox run client-test164,devbox run e2e27/27 (join, fog pixel probes, drag + rollback, reconnect, the independent traffic audit and the 50-token measurement),devbox run mutationcontrol + 80 mutations each failing at least its expected test,devbox run benchPASS anddevbox run fogbenchPASS. Evidence:results/nimble-test.log,results/mutation.log,results/bench.log,results/m4-fog-bench.md(+.log); the e2e/client logs are regenerated per run and not committed. The phone gate's scene is the Full HD maximum (1920x1080) [FIXED (owner decision), 2026-11-21, #85]; the fog-update test's 4096 px / 128x128-cell scene is a synthetic correctness/stress fixture above the cap, not the product target. The manual Note 10 + laptop 60 fps run is #77 and is the only open M4 accept item: M4 is accepted after it passes, not before. Mutation housekeeping found here:c1/c2still patched the pre-#65 tile-gate expression and had silently becomesedno-ops; both now patchcy * sc.cols + cx in exploredand fail the tile gate group again. - M4 gate harness. (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. Gate (a)'s fill is the fastest of 4 fresh page loads after a
warm-up (min-of-N, §5.3), asserted against 2x the 1 s DESIGN budget (the documented saturated-host
tolerance); every sample is printed on every run. Measured 2026-11-21: 439 ms fastest on the dev
host (628, 778, 444, 439), 1.3-1.9 s fastest under a saturated 16-core host, same binary, and a
planted 50 ms/tile decode delay raised the minimum to 4264 ms so the gate fails. The
data-tiles=readywait is a completed-pass signal: a stored transient tileerroris terminal until the next window or reconnect, so one host hiccup cannot hold every e2e wait atloading(proven by aborting one tile: the wait timed out before the fix, passed after). 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). - M4/M5 proving harnesses. Headless e2e (§10.3 Browser e2e), the independent traffic audit (§10.3) and the slow-client test (§10.3) are the gates' harnesses; the pass criteria stay in DESIGN §13.
- M6 proof.
/_tiles/404 and the log grep (§10.3 Logs), the WS upgrade (§10.3 Protocol), and the restore drill (§11.2).