Author SHA1 Message Date
SirStone 16351e56f5 prototype: sight with thick and low walls (#43, map #38)
Throwaway artifact for #43: six SVG scenarios (thin vs thick, corner joint, doorway in a
thick wall closed/open, 1 m wall with a tall and a short viewer, terrain = no wall, one-way
from both sides), each with explored cells and the sight polygon, plus a cost table against
the current thin baseline on the prototype scene and 5k sparse/dense.

server/ untouched: sightmodel.nim wraps geometry.visibilityPolygon and adds only the 5.8
filter, the thickness expansion (3-face silhouette / 4-face quad) and the per-target height
predicate. Headline numbers: hoisted quad 0.263 ms sparse / 12.7 ms dense (3.15x / 10.15x);
the 5.8 filter per query costs +0.15 ms per polygon at 5k walls. Open questions for #44/#45
are listed with suggested answers in prototype-wall-sight/index.html.

Branch prototype/wall-sight, not pushed.
2026-11-15 18:54:01 +01:00
SirStone 7511daa3c5 design: wall switches, presets and one-way sight (#42) 2026-11-15 18:23:26 +01:00
SirStone a7f302ec26 design: height model for tokens, eyes and walls (#41) 2026-11-15 16:47:40 +01:00
SirStone b4720779d4 research: sight with thick and low walls (#39) 2026-11-15 16:12:15 +01:00
SirStone d5147ec4db research: how tabletops model wall kinds (#40) 2026-11-15 15:54:46 +01:00
SirStone b6c006d08b agents: add bug and enhancement category labels 2026-11-15 15:30:23 +01:00
SirStone c78ed7969b glossary: wall term from #26 triage 2026-11-15 15:25:24 +01:00
SirStone e13fa905a4 results: rerun the gates on the fixed tree (#27-#31)
devbox run test: nimble suites and 107 node tests pass (was 103: +1 characters,
+2 tiles, +1 restart). devbox run mutation: control and every mutation pass,
including the new e1-e3 and the repointed b2.
2026-11-15 14:26:23 +01:00
SirStone b4bddf1d52 design: record the #27-#31 rules and the measured egress numbers (#27-#31)
6.1: a link patch hands the token's names over; the encountered snapshot is
written by one path in both stores, and a reveal is scoped to its player. 4.3:
egress borrows (never copies) under the lock, and the scene is a value swapped
under the lock that each request reads once. 10.3: STALE_NAME is a leakcheck
class. 14: the five fixes, their tests and mutations, with the before/after
egress measurements (context build 4.87 ms -> 0.008 us at 262144 cells; GM
egress 142.8 ms -> 0.80 ms). Doc bumped to v0.20.
2026-11-15 14:26:23 +01:00
SirStone f963e8f4d6 main: read the scene once per request, under the lock (#31)
scene.set reassigns app.scene under dbLock while the HTTP handlers read it with
no lock and no stable snapshot: tileGate read it three times (twice outside the
lock) and checkScene read the id unlocked, so a swap could hand a request two
records, or race ORC freeing the old walls seq. tileGate now takes one snapshot
under the lock and uses it for the URL parse, the explored check and the
X-Accel-Redirect; checkScene and scene.set read under the lock; the wall/door
handlers capture sceneId inside their lock for the post-lock log and effect
frame.

Tests: ttiles pins that one record gives one whole answer after a swap;
tiles.test.mjs pins the handler shape (one code read, after the lock) and
interleaves 20 scene.set plus wall edits with 200 tile fetches -- only whole
tiles, no crash.
2026-11-15 14:26:15 +01:00
SirStone e9d5f6815a views: borrow the world in egress instead of copying it (#28)
views.Context held copies of scene, tokens, characters, reveals, encountered
and visions, so every mutation deep-copied each player's explored HashSet under
the global lock; playerView then copied its own PlayerVision again and greyFor
copied one per encountered entry. Context now holds six pointers
(contextOf/borrow), playerView/gmView read a ptr PlayerVision and a view builds
each player's visible-id set once per frame, so grey is a set test.

Measured on this build's types (debug, 6 players, 40 encountered entries, 40
world tokens, 16384 / 262144 explored cells): context construction 0.227 ms /
4.87 ms -> 0.008 us; one getOrDefault of a PlayerVision 28.8 us / 591 us -> gone;
GM egress pass 8.0 ms / 142.8 ms -> 0.79 ms / 0.80 ms; player pass 1.45 ms /
25.7 ms -> 0.32 ms. Behaviour is unchanged (leak/fault suites and tviews green);
tviews pins the borrow by identity, the six-pointer size and both sizes inside
the M5 7.5 ms budget.
2026-11-15 14:26:11 +01:00
SirStone 8e045b0ac8 names: per-player reveal, one encountered write path, link by update (#27, #29, #30)
name.reveal wrote the subject's actual name into the encountered row of every
player who had met it: the SQL had no player predicate, so the leak was silent
live and visible only after a restart. rewriteEncountered is now the one path
that keeps a snapshot in step with its subject: it rewrites the SQLite row and
the live in-memory entry together from the name rule, takes onlyPlayer for
name.reveal (every player for reveal_all), and also runs on a rename, a link
change and an owner change, so the wire and a post-restart reload cannot
disagree (#30). The DB-only renameEncountered*/revealEncountered* helpers are
gone, which is what let the two stores drift.

token.update {character_id} now drops the token's own two names as part of the
link patch (#29): a plain token can be linked, names supplied with a link stay
invalid and unlinking still needs both names.

Tests: tcharacters covers the per-player row, the DB/memory equality, the link
handover; restart.test.mjs builds three named players, reveals to one of them
and asserts the rows directly and the whole resync over SIGTERM/SIGKILL, plus a
mid-session rename; leak.mjs/leakcheck.nim pit two players on the same subject
and pin each entry's expected name (STALE_NAME). Mutations e1-e3 and the
repointed b2 pin the three rules.
2026-11-15 14:26:07 +01:00
SirStone e68c6eefbf design: owner confirms prop registry fallback (#22)
Mark the 6.1 property-schema registry as an owner decision (2026-11-15):
keep the empty registry with the permissive fallback in v1, strict mode
with the FFF seam post-v1. Record it in 14 and bump the doc to v0.19.
2026-11-15 13:06:58 +01:00
SirStone 76ec6f4b3d results: rerun the M3 gates on the final tree (#25) 2026-11-15 13:03:54 +01:00
SirStone 2c0ce47134 design: record the measured M3 gate results (#25) 2026-11-15 13:03:51 +01:00
SirStone e713e05931 tools: define the scene.set mutation after the dispatcher (#25) 2026-11-15 12:55:58 +01:00
SirStone 14939afd81 design: record the finish line, the scene rules and the M3 acceptance checklist (#25) 2026-11-15 12:52:23 +01:00
SirStone cedb80aa96 tests: the restart and logs groups, the nine-group checklist and the fixture clean-up (#25) 2026-11-15 12:52:20 +01:00
SirStone 70a984c55a server: scene.set closes the 29-intent catalogue, plus a log-leak fault hook (#25) 2026-11-15 12:52:17 +01:00
SirStone df2b186267 results: rerun the slice 9 gates on the final tree (#24) 2026-11-15 12:30:53 +01:00
SirStone 7ef5cc433a design: record the map-tile gate and test nginx decisions (#24) 2026-11-15 12:30:53 +01:00
SirStone 30512127b0 tools: test nginx, generated tile fixtures and the tile group (#24) 2026-11-15 12:30:51 +01:00
SirStone 669e47e1ba server: the map-tile gate and the internal X-Accel path (#24) 2026-11-15 12:30:48 +01:00
SirStone 5ff15c4b36 results: rerun the slice 8 gates on the final tree (#23) 2026-11-15 12:11:42 +01:00
SirStone ea6d92bf76 server: refresh a player's sight when a connection starts receiving state (#23) 2026-11-15 12:11:42 +01:00
SirStone 1ad9f724f2 tests: drop the two unused imports (#23) 2026-11-15 12:02:52 +01:00
SirStone 74272c1e70 results: rerun the slice 8 gates on the final tree (#23) 2026-11-15 12:01:40 +01:00
SirStone dab7c77675 design: record the characters and names decisions (#23) 2026-11-15 12:01:33 +01:00
SirStone 54ecf7bf6a tools: nine mutations for the name rule, the snapshots and the character link (#23) 2026-11-15 12:01:30 +01:00
SirStone c4b97ec16c tools: name players through player.setname, and the character groups and four fault classes (#23) 2026-11-15 12:01:30 +01:00
SirStone f134534c6c tests: characters, names, the encountered list and migration step 7 (#23) 2026-11-15 12:01:30 +01:00
SirStone 20dcb87afb server: the character and name intents, player names and the roster (#23) 2026-11-15 12:01:26 +01:00
SirStone 5977d45a5a server: characters, names and the encountered list in the one egress (#23) 2026-11-15 12:01:26 +01:00
SirStone 75c3e046f8 server: the character, reveal and encountered records and migration step 7 (#23) 2026-11-15 12:01:21 +01:00
SirStone 34a33b5ead results: rerun the slice 7 gates on the final tree (#22)
devbox run test green: 317 Nim [OK] blocks and 77/77 Node harness tests
(migration step 6, the details group, the twelve fault classes).
devbox run mutation green: control plus a..au, no survivors, no no-ops.
2026-11-15 11:09:15 +01:00
SirStone 3c6e926122 design: record the token details decisions (#22)
Migration step 6, the status/source payload rules, the prop caps and the
property-schema registry (empty at start with a permissive fallback, because
8 says v1 never interprets props), and the grow-push search that 5.6 left
PROPOSED are all FIXED owner-delegated in 5.6/6.1 and summarised in 14. The
token payload rules now say `radius`/`props` are accepted on create from
slice 7 and refused nowhere else. 10.3 lists the three new fault classes,
and the glossary gains property, bucket and registry.
2026-11-15 11:02:43 +01:00
SirStone e103c3ed5c tools: the details group, the leak scenario's props and three fault classes (#22)
tools/details.test.mjs is the slice's WS acceptance: the five intents and
their codes, a grow push clear of a wall, a squeeze in a corridor too narrow
for the grown token, stuck from a wall and from a GM placement cleared by a
removal and by a shrink, the GM source of a status, the caps and who reads
which bucket, and a restart that brings size, props and statuses back. Waits
use a cursor taken before the intent, so a repeated state cannot be matched
by an older frame.

The leak scenario gains a token in view with props in all three buckets, a
GM-sourced status, a resize, a wall over it and the clears; leakcheck refuses
the `gm` bucket (GM_PROP), the `owner` bucket on a non-controller
(OWNER_PROP) and any `source` on a player status entry (STATUS_SOURCE), so
`fault.test.mjs` now asserts all twelve classes. The schema-version fixtures
in smoke/persistence move to 6, and mutation.sh gains am-au plus the renames.
2026-11-15 11:02:43 +01:00
SirStone 20575f2147 tests: props, statuses, the resize rules and migration step 6 (#22)
tests/tprops.nim is new: the caps (per bucket, keys, values), the key rules,
the registry (empty fallback, a registered key's kind and bucket), set/unset
and the clone that keeps an edit away from the original bucket.

ttokens covers radius, the three buckets, the status set (round trip, sorted,
replaced rather than appended, removed by the FK cascade). tmoverules covers
per-token radius, shrink/grow/squeeze, the no-crossing rule, the corner
relaxation and the independence of the two sources; the old `blocked` tests
became `stuckWalls`. tviews covers the bucket and source filtering, one
`token` frame per change and the effective radius. tdb/tdb's fixtures move to
step 6, and tprobing follows the rename.
2026-11-15 11:02:43 +01:00
SirStone 81898ab69c server: resize, status and prop intents in the mutation pipeline (#22)
`token.resize`, `status.set`, `status.clear`, `prop.set` and `prop.unset`
answer the 6.1 acks and codes; `token.create` now accepts `radius` and
`props` and computes the placement status before writing the row, so a token
dropped on a wall is born `stuck`. `token.update` keeps refusing the
character link and ignores `radius`/`props` (their intents own them).

Wall add/update/remove and door.set now run the pure rules on a snapshot
taken before the write and apply the outcome after it committed
(`applyRuleOutcome`: positions and walls-sourced statuses in one NORMAL
transaction, memory after COMMIT), which replaces the door-push-only helpers
and adds the 5.5 SET/KEEP/CLEAR rules and the squeeze of a failed push. A
value over the bucket cap is refused without touching the token (the clone
makes the cap check side-effect free). Prop keys are never logged.
2026-11-15 11:02:35 +01:00
SirStone dcc813225f server: per-recipient props and statuses in the one egress (#22)
The typed views carry the bucket filter: `PlayerTokenView` has `propsPublic`
always and `propsOwner` only when the recipient controls the token, and no
field for the `gm` bucket at all, so a later change to the frame builder
cannot leak one. Statuses are `StatusKind` values for a player (no `source`,
5.5/6.1 note 6) and full `(status, source)` entries for the GM.

Both negative controls for the new rules live behind `-d:leakfault` and in
the type, so the shipped binary has neither the fields nor the branches:
`gmProp` (the gm bucket reaches a player), `ownerProp` (the owner bucket
reaches a non-controller) and `statusSource` (a viewer learns the cause).
The `otherOwner` fault now carries the owner bucket too, so it stays one
class (the `mine` claim) instead of also tripping the bucket check.
2026-11-15 11:02:35 +01:00
SirStone 38d8962f84 server: the status model, per-token radius and the grow push (#22)
moverules.nim replaces the M2 `blocked` bool with the 5.5 status model: the
rules own the `walls` source (`stuckWalls`, `squeezedWalls`) and take
`locked` (any entry, any source) as input, so a GM-sourced lock refuses a
player move without the rules ever knowing what caused it. Identity is kept
on KEEP, cleared on CLEAR, and only tokens the event touches change.

Every geometry path now uses the token's own radius (5.6): the overlap test,
the escape check, the capsule, the door push and the step cap's neighbour
rules. `resizeToken` implements 5.6: a shrink never pushes and clears the
walls entries only when the overlap ends, a grow that overlaps is displaced
by a deterministic greedy relaxation (radial off the first overlapped wall,
scene order, at most 16 rounds, one flipped-side pass) and a grow that cannot
be placed stays put and becomes squeezed(walls). A step whose centre path
would cross a wall ends the pass, so the relaxation never carries a token
through a wall.

worldmap.nim is the bridge: `ruleToken`/`ruleWall`/`moveScene` build the
rules' input from the records, `applyOutcome` copies the position, the
door-push history and the walls-sourced entries back, and `wallsStatuses`
does the same for a caller that writes its own row. All of them return fresh
sequences instead of mutating a shared one.
2026-11-15 11:02:29 +01:00
SirStone 67762c1309 server: the property buckets, the registry and the status set (#22)
Migration step 6 ("token details") adds the three prop buckets to `entity`
and creates `entity_status`, the `(status, source)` set of 5.5. A token's
status rows are rewritten with its row, so a status change and the `token`
frame that reports it commit together.

server/props.nim owns the buckets, their caps (64 keys per bucket, a key of
1..64 code points, a value of at most 8 KB of serialized JSON) and the
property-schema registry: empty at start with a permissive fallback, because
DESIGN 8 says v1 never interprets props; a key the rules module registers is
enforced (kind and bucket). server/text.nim is the one copy of the 6.5 text
rule, shared by names and prop keys.

tokens.nim gains `props` and `statuses` on the record, the sorted-unique
entry helpers, `isLocked`, `parseRadius`/`parseStatusKind`/`parseStatusSource`,
the prop and status columns in insert/replace, and `loadStatuses` joined on
the scene. Every helper builds a fresh sequence: a copied record shares its
seq buffer, so an in-place edit would reach the authoritative list before
the transaction commits (4.2 step 6).
2026-11-15 11:02:23 +01:00
SirStone d773a5e2de results: rerun the slice 6 gates on the final tree (#21)
devbox run test: 273 Nim checks and 68 Node tests pass. devbox run mutation: control passes,
41 of 41 mutations (a-al) fail their expected tests, including the six new explored ones.
Chunk write avg 0.015 ms / p99 0.037 ms; move ack with explored writes avg 0.79 ms / p99 2 ms.
2026-11-15 10:03:37 +01:00
SirStone fe7ffb0000 design: record the explored persistence decisions (#21)
Step 5 DDL, the 64x64/512 B chunk format with its pinned bit layout, the write policy (dirty
chunks only, whole-chunk encoding, NORMAL durability, one transaction with a move and a
separate one after GM authoring), the startup restore and the measured costs, all tagged
FIXED (owner-delegated, #21), plus what slice 6 built in 10.3.
2026-11-15 09:58:51 +01:00
SirStone 8c7487bf62 tools: the persistence group and six explored mutations (#21)
tools/persistence.test.mjs proves the store end to end over the real binary: a fresh resync
round trip, strict per-player separation, SIGTERM and SIGKILL restart equality, a wall
removal's revealed cells surviving after the wall returns, chunk rows decoded independently
(512 B, blobs), move-ack timing (avg 0.8 ms, p99 2 ms) and a schema-4 fixture DB migrated by
the binary. Mutations ag-al pin the bit layout, the chunk coordinate, the restore, the
per-player key, the upsert and the dirty-chunk dedupe. smoke.test.mjs moves to version 5.
2026-11-15 09:58:51 +01:00
SirStone df4634d12a server: load and persist explored with every mutation (#21)
Startup restores each player's grid from its chunk rows (explored_loaded log) and every
mutation writes only the chunks its refresh dirtied, in the mutation's transaction: a move
keeps position and chunks in one NORMAL commit, a GM authoring write adds one NORMAL chunk
transaction under the same lock, before the ack. db.withTransaction is the shared seam.
2026-11-15 09:58:19 +01:00
SirStone 22014a36dc server: the chunked explored store (#21)
Migration step 5 creates explored_chunk: one 512-byte bitmap per (player, scene, 64x64-cell
chunk), both FKs cascading. server/explored.nim owns the format (row-major, LSB-first bits),
dirty-chunk detection, the upsert and the startup restore. tests/texplored.nim pins the layout,
the whole-chunk encoding, the upsert replacement, the per-player keying, the restore and the
write cost (0.015 ms avg / 0.035 ms p99); tests/tdb.nim covers step 5 and a schema-4 fixture.
2026-11-15 09:58:16 +01:00
SirStone 5d38e92c03 results: rerun the slice 5 gates on the final tree (#20) 2026-11-15 09:37:33 +01:00
SirStone 9c512e74bc server: tidy the slice comments after the rollout (#20) 2026-11-15 09:37:33 +01:00
SirStone c9de8c7116 tools: the protocol group's landed/unlanded intent split (#20)
token.create now answers on its fields, so the 'not landed yet' examples move to
status.set and character.create (slices 7-8).
2026-11-15 09:35:43 +01:00
SirStone ae6054ea94 results: slice 5 test and mutation logs (#20) 2026-11-15 09:35:37 +01:00
SirStone 91192b36ce design: record the tokens and sight decisions (#20)
v0.17: migration step 4 (entity) and what it deliberately leaves out, the token
payload rules 6.1 was silent on (plain tokens only, radius/props/character_id
refused invalid, effective radius = scene default, descriptive name only on the
wire, controller null as the single GM spelling, explored RLE on connect), the
slice-5 resync, the egress timing, the fault classes built at this slice, the
slice-5 rollout, and the full decision record as a FIXED owner-delegated entry.
2026-11-15 09:35:33 +01:00
SirStone cae20d7c89 tools: WS probing and the token wire tests (#20)
tools/probing.test.mjs re-runs the M2 T8 probing test over the wire with a hostile
client: over-cap probes always get the one uniform nack (old position, no code), two
servers whose walls differ only beyond cap + token radius answer 90 identical
probes identically, and a wall inside that bound does change the replies, so the
harness is shown able to fail. It stays inside the 6.4 burst, so no probe is a rate
limit.

tools/tokens.test.mjs pins the wire behaviour of the slice: the 6.1 acks and codes,
the controller-only and GM-only rules, the connect resync order, the unnamed-player
gate, the door push and a restart.

tools/mutation.sh gains aa-af: the egress ignoring the view rule, gm_only and the
owner arm of the rule, a missing token_gone, a GM-only field in a player frame, and
explored forgetting cells.
2026-11-15 09:35:29 +01:00
SirStone 959412ff09 tools: leak driver, checker and the fault controls (#20)
tools/leak.mjs builds a 27-group scene over the real wire (movement, a closed door,
create/remove, gm_only, a controller hand-over, another player walking in and out, a
wall added and removed, a door push) and records every frame each socket saw, one
group per mutation. tools/leakcheck.nim replays it: the GM socket is ground truth,
the subject's polygons and explored cells are recomputed from geometry.nim, and the
explored set is also probed with a clear-segment sampler. Subjects A and B both pass
with zero failures; the transcripts and logs land in results/.

tools/fault.test.mjs runs the same scenario against a -d:leakfault build for each
fault and asserts the EXACT class set (HIDDEN_TOKEN, GMONLY_TOKEN, WALLDATA,
WITHHELD, OTHER_PLAYER, NO_REMOVE, EXPLORED), plus that the shipped binary carries no
LEAK_FAULT string.

withserver can build a variant with extra -d: flags and pass an env to it; lib.mjs
can name a player out of band, the fixture the player-side tests need until slice 8
brings player.setname (the unnamed gate itself is pinned in tools/tokens.test.mjs).
2026-11-15 09:35:24 +01:00
SirStone 6fcf7f8271 server: token intents, the resync and the door push (#20)
token.create/update/remove (GM) and token.move (controller, or GM) through
moverules: the uniform nack for locked/over-cap/collision and for an out-of-bounds
GM move, one not-allowed code for a player's unknown and not-yours targets, not-found
for the GM; accepted moves are persisted with NORMAL durability and the mover's
vision recomputed. token.update honours kind, both names, controller, gm_only,
flags and vision_radius, and refuses character_id until slice 8.

connect now sends hello, the GM walls snapshot and the 6.3 token half (vision,
explored full, tokens) under the global lock, so hello is always the first frame and
the resync is the diff base. Egress runs under the same lock, per mutation, so no two
threads touch a connection's known table and an unnamed player is never fed state.

door.set applies the 5.5 push: the move rules compute the new positions against the
pre-write state, the positions are persisted in one transaction, then memory and
vision follow (stuck/squeezed are slice 7). player.remove hands the controlled
tokens to the GM in memory as the FK already does in the DB.
2026-11-15 09:35:19 +01:00
SirStone 5f5bf3293b server: typed recipient views and the single egress (#20)
server/views.nim is the only place where world state becomes bytes: a Recipient
builds a GmTokenView or a PlayerTokenView first, and only then a frame. Player
frames carry the public props bucket (plus owner for the controller), the
controller's vision_radius, and never kind, controller, gm_only, flags, radius_own
or either raw name; the GM gets all of it plus both names. The per-connection Known
table diffs on the built frame, so token/token_gone are exactly the changes and the
vision frame is re-sent only when the polygons move.

server/faults.nim compiles the negative-control hook only with -d:leakfault; the
shipped binary contains no LEAK_FAULT string and tools/fault.test.mjs asserts it.

hello gains the scene block (and extra for the GM); the protocol's implemented set
now names the four token intents.
2026-11-15 09:35:14 +01:00
SirStone e6b53e06f5 server: per-player vision, explored cells and the one view rule (#20)
server/vision.nim keeps one PlayerVision per player: a visibility polygon per
controlled token carrying the vision flag (range = the token's vision_radius or the
scene default), the explored set as the union of cellsTouched over history (only
grows, cells outside the world dropped), and the fresh cells of the current
mutation. The token-visibility rule of 3.1 (controlled always, otherwise inside own
LOS and not gm_only) exists exactly once there.

server/worldmap.nim translates the authoritative records into the inputs the pure
geometry and move-rule modules take, so those modules never see a wire field.
2026-11-15 09:35:09 +01:00
SirStone d38b871dfa server: token records and the entity migration step (#20)
Migration step 4 ("tokens") creates the entity table: the token id, scene, kind,
both names, position, nullable radius/owner/vision_radius, gm_only and flags. A
NULL owner is GM-controlled, so player.remove hands that player's tokens to the GM
through the FK; radius, props and character_id stay out until slices 7-8.

server/tokens.nim holds the record, the 6.1 field rules (12 CSPRNG characters from
a 64-symbol alphabet, trimmed names, kind, positive vision_radius), the write-through
persistence (FULL for GM authoring, NORMAL for a move) and the loader. db_connector
quotes every argument, so the three nullable columns are emitted as numeric literals
while text still goes through ? arguments.
2026-11-15 09:35:05 +01:00
SirStone 8b595156f0 results: slice 4 test and mutation logs (#19) 2026-11-15 08:49:44 +01:00
SirStone 864cf26e98 design: record the walls and doors decisions (#19)
v0.16. 4.4 gets migration step 3 (scene + wall DDL and the seeded v1 scene);
6.1 gets the wall payload rules the catalogue left open (scene id, a/b
validation, open never true on a wall, flags as an object, wall.update's
patch set, fields before lookup, ids from next_wall_id, synchronous=FULL);
6.1/6.3 note what slice 4 actually sends (`walls` on GM connect); 8 points
next_wall_id at the scene row; 14 records the whole slice as FIXED
(owner-delegated).
2026-11-15 08:49:42 +01:00
SirStone 6c3e8c6e18 tools: mutations t-z2 for the wall state (#19)
t: removal renumbers next_wall_id | u: the counter is not loaded from the DB |
v: the counter is never written | w: a wall may stay open | x: zero-length
walls accepted | y: endpoints unchecked against the world bounds | z:
door.set on a plain wall accepted | z2: persisted open state loaded inverted.
Control passes; every mutation fails its expected tests.
2026-11-15 08:49:24 +01:00
SirStone d72fc6ed20 tools: wall harness, and the walls frame in the existing groups (#19)
tools/walls.test.mjs: GM snapshot, CRUD acks and effects, ids monotonic and
never reused, the 6.1 validation table, door toggling, "players get no wall
data" (no walls/wall/wall_gone type and no wall coordinate in any player
frame) and a restart that leaves walls, door state and the id counter
identical. protocol.test.mjs/smoke.test.mjs follow the new frame and schema:
hello = 1, walls = 2, the first ack = 3; user_version 3 with the seeded scene.
2026-11-15 08:49:24 +01:00
SirStone a8f508ef2e server: wall and door intents, GM wall snapshot and fan-out (#19)
wall.add, wall.update, wall.remove and door.set leave the unknown-type rollout
list: field shapes and ranges per 6.1 (and the payload rules recorded FIXED in
4.4/6.1), lookup failures not-found, non-GM refused by the existing GM-only
gate. wall.add acks {id} from the scene's next_wall_id; wall.update patches
a/b/kind/flags only (open belongs to door.set); door.set is invalid on a plain
wall. Effects go to every GM connection only: wall / wall_gone, plus one walls
snapshot right after hello (the wall part of the 6.3 resync). Players receive
no wall data in any message (3.1, T2).

protocol.nim gains the wallObject/wallsFrame/wallFrame/wallGoneFrame builders
(no n: the sender stamps it per recipient) and the five wall intents in the
implemented set.
2026-11-15 08:49:20 +01:00
SirStone bf9ab3edfd server: scene and wall state, slice-4 migration (#19)
Migration step 3 ("world") creates scene and wall and seeds the single v1 scene
(id 1, 4096x4096, tile = cell 32, vision 400, token radius 20, art_version 1,
next_wall_id 1). server/world.nim holds the in-memory scene with SQLite as
write-through persistence: per-scene wall ids from next_wall_id (monotonic,
never reused, #3), 6.1 validation (a != b, in bounds, a wall is never open),
flags as an opaque JSON object, and one transaction with synchronous=FULL
around every GM authoring write (Q12); memory follows COMMIT, so a failed
write leaves both sides unchanged.

Tests: tests/tworld.nim (ids, reload, doors, validation, pragma, failed write),
tests/tdb.nim (version 3, history, a slice-2 DB migrating to slice 3).
2026-11-15 08:49:16 +01:00
SirStone 2a1e2dd71c results: slice 3 test and mutation logs (#18) 2026-11-15 08:33:16 +01:00
SirStone db22b33567 design: record the closing message and the protocol-shell decisions (#18)
Owner decision (#18), option A: mummy 0.4.8 cannot send an application close code
(close(ws) -> an empty close frame -> the browser sees 1005), and mummy is not forked
for it. Every server-initiated close now sends one closing {reason, code} message and
then the close frame; the client reads the reason from that last message. Amends 3.2
(the OPEN note is FIXED) and 6.5, and adds the message to the 6.1 catalogue (server
messages 14 -> 15) with the reason/code table.

Also recorded FIXED: proto is a required query parameter (400 when absent, 4003 on a
mismatch, no hello); the server Ping interval (20 s, plus one right after hello, lag
enforcement stays M5); the n rule (server frames only, no number for Ping/Pong); the
explicit 64 KB maxMessageLen; and the slice-3 rollout note that catalogue intents
whose slice has not landed answer unknown-type. 10.3 lists the protocol test group.
2026-11-15 08:33:16 +01:00
SirStone 951f37c3fb tools: mutations p-s for the protocol module and the n counter (#18) 2026-11-15 08:33:12 +01:00
SirStone 5e43ffa545 tools: raw WS client and the protocol test group (#18)
lib.mjs gains a node:net WebSocket client (frames, opcodes, masked sends, a close
handshake that mirrors a browser) so the harness can send what the global WebSocket
cannot: oversize, binary, unmasked, bad-opcode and garbage frames, and read Ping/Pong
and the empty close frame. wsUrl/rawUpgrade now carry the required proto query.

withserver.mjs gains the GM-server helpers (gm-key, withGmServer, signIn, openAs) that
auth.test.mjs used to keep privately, so both harnesses share one copy.

protocol.test.mjs is the protocol group of DESIGN 13 M3: hello/n, catalogue types,
proto, unknown type and ignored fields, exactly one ack per reqId, unnamed player,
malformed + binary frames, the flood close, the intent bucket, the 64 KB boundary,
unmasked/bad opcode, server Ping and Pong, the connection cap, and closing-then-1005.
auth.test.mjs now also asserts the closing reason on eviction and revocation.
2026-11-15 08:33:12 +01:00
SirStone 88dd27e2cc server: hello, one ack per intent, proto check, rate limit, flood, ping (#18)
The protocol shell over the socket, in DESIGN 6.5 order: spend a token, parse, then
unknown type / unnamed player / role / fields / lookup / semantics. Every readable
intent gets exactly one ack with a 6.5 code; an unreadable frame gets one error.

- hello {proto, role, me} as the first frame (n = 1); the scene block lands in slice 5
- /ws?proto=N is required: 400 when absent or not an integer, 101 + closing 4003 on
  a mismatch (no hello, no state)
- intent bucket 30/s burst 100 and the 10-in-10-s malformed flood (closing 1008);
  a rate-limited intent applies nothing and the connection stays open
- mummy maxMessageLen stated explicitly (64 KB) and mummy's own log lines routed
  through the event log instead of stdout
- server Ping(seq) right after hello and every 20 s (lag enforcement stays M5);
  inbound Pings are answered with a Pong, which mummy does not do itself
- close reasons: every server-initiated close sends closing {reason, code} then the
  close frame, and slice 2's eviction/revocation paths do the same (FIXED, #18)
2026-11-15 08:33:07 +01:00
SirStone 7e2d5b8dc0 server: per-connection wire state and closing frames in the conn registry (#18)
Conn now carries what DESIGN 6/6.4/6.5 need per connection, all under the one
registry lock: the outgoing n counter (starts at 1, server frames only), the intent
token bucket, the malformed-flood window, the player's named flag and the last Pong.
None of it is shared, so the n counter is not a global side channel (H25).

activate/revokePlayer now hand back the doomed Conn values instead of raw sockets:
the caller still has the frame count, so the final closing frame carries the right n
before the close. Tests cover per-connection counters, the bucket and the flood
window in isolation, and that a snapshot survives the lock.
2026-11-15 08:33:07 +01:00
SirStone eb48034eba server: wire protocol module - envelope, frames, rate limit, flood window (#18)
Pure, mummy-free module for the protocol shell: the envelope rules of DESIGN 6.5
step 2 (UTF-8 text, JSON object, string t, integer reqId in 0..2^31-1), the frame
builders of 6.1 including closal/closing, the per-connection intent token bucket
(30/s, burst 100) and the malformed-flood window (10 in any 10 s), plus the FIXED
constants: proto 1, 64 KB inbound, close codes 4001/4002/4003/1008 and their reason
strings. The 29-intent catalogue and the GM-only set live here so 'unknown type'
and role checks have one definition.

Found while testing: std/json parseJson("") returns nil instead of raising, and
node{"t"} is nil for a missing key, so both are guarded (a bare {} would have
crashed the handler).
2026-11-15 08:33:01 +01:00
SirStone 527e216c37 design: mark sign-in path and ws origin check fixed (#17) 2026-11-14 22:13:25 +01:00
SirStone 8ff66530d8 results: slice 2 test and mutation logs (#17) 2026-11-14 22:13:09 +01:00
SirStone f85665b53e design: record slice 2 decisions (#17) 2026-11-14 22:13:09 +01:00
SirStone 9d43aef9ed server: /join, session cookies, ws auth and gm-key CLI (#17) 2026-11-14 22:13:09 +01:00
SirStone e612db5826 server: auth schema, keys, sessions, connection registry (#17) 2026-11-14 22:13:04 +01:00
SirStone c89c8eab42 results: slice 1 test and mutation logs (#16) 2026-11-14 21:41:33 +01:00
SirStone 86e7ad397d design: record slice 1 decisions (#16) 2026-11-14 21:40:48 +01:00
SirStone a3c1ac36ef devbox: nodejs 26, sqlite, test runs Nim then Node (#16) 2026-11-14 21:40:44 +01:00
SirStone 65b8f0a148 tools: Node 26 harness base, smoke and ws-header checks (#16) 2026-11-14 21:40:44 +01:00
SirStone f376efdc39 server: config, migrations, redacted logging, /healthz entrypoint (#16) 2026-11-14 21:40:39 +01:00
SirStoneandClaude Haiku 5.5 143cb534dc design: retag gm-key service user as owner-delegated (#13)
Co-Authored-By: Claude Haiku 5.5 <noreply@anthropic.com>
2026-11-14 20:58:58 +01:00
SirStoneandClaude Sonnet 5.5 4465e7e89d design: M3 slices and gm-key service user (#13)
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-14 20:56:32 +01:00
SirStoneandClaude Haiku 5.5 7667e28f5e design: owner review of message list flags (#11)
Co-Authored-By: Claude Haiku 5.5 <noreply@anthropic.com>
2026-11-14 20:49:11 +01:00
SirStoneandClaude Sonnet 5.5 277cb5f896 design: fix M3 message list (#11)
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-14 20:42:16 +01:00
SirStoneandClaude Haiku 5.5 2801fbcca5 design: fix M3 limits (#15)
Co-Authored-By: Claude Haiku 5.5 <noreply@anthropic.com>
2026-11-14 20:12:15 +01:00
SirStoneandClaude Haiku 5.5 356a70f2b5 design: fix M3 done criteria (#12)
M3 done = devbox run test green on a clean checkout with nine named
groups (leak+fault, tiles, probing, protocol, auth, characters and
names, restart, persistence, logs). Concurrency moves to M5, bind check
to M6. Protocol limits pending on the "M3 limits" card.

Co-Authored-By: Claude Haiku 5.5 <noreply@anthropic.com>
2026-11-14 19:47:06 +01:00
SirStoneandClaude Haiku 5.5 acc69c9fb6 design: fix test tools (#9)
Node 26 black-box harnesses under tools/ (no Nim rewrite, no npm deps);
in-process tests stay Nim; devbox run test runs Nim then Node.

Co-Authored-By: Claude Haiku 5.5 <noreply@anthropic.com>
2026-11-14 19:35:54 +01:00
SirStoneandClaude Haiku 5.5 8c03224f2a design: fix map tiles in M3 (#7)
Tile gate, test nginx and generated 32 px fixtures in M3 scope.
Versioned private tile URLs (art_version, Cache-Control private).
404 for malformed paths, 403 for unexplored tiles.

Co-Authored-By: Claude Haiku 5.5 <noreply@anthropic.com>
2026-11-14 18:41:34 +01:00
SirStoneandClaude Haiku 5.5 0772f26400 design: fix players and player keys (#6)
One shared site link; each player signs in with a personal player key
generated by the GM. GM signs in the same way with a GM key from
`fff-vtt gm-key` (replaces gm-link, #5). GM can replace a key live
(old key invalid, sessions and connections revoked). Removing a player
passes characters and tokens to the GM. No rate limit on key entry
(owner decision: ~100-bit key space).

Co-Authored-By: Claude Haiku 5.5 <noreply@anthropic.com>
2026-11-10 19:27:22 +01:00
SirStoneandClaude Haiku 5.5 d9e135f6bd design: fix characters and player data (#14)
Characters are own records separate from tokens; tokens may link to one.
Character owner: exactly one (player or GM). Token controller is independent
and never changes with the character owner. Identity lives on the character,
per-figure state on the token. Descriptive/actual names revealed per player
or to all. Per-player encountered list, GM-removed only. Server-side SQLite only.

Co-Authored-By: Claude Haiku 5.5 <noreply@anthropic.com>
2026-11-10 19:11:16 +01:00
SirStoneandClaude Haiku 5.5 ae2f7c48dc design: fix first GM login bootstrap (#5)
Co-Authored-By: Claude Haiku 5.5 <noreply@anthropic.com>
2026-11-10 18:04:11 +01:00
SirStoneandClaude Haiku 5.5 90576381df design: fix token size and stuck/squeezed statuses (#4)
Co-Authored-By: Claude Haiku 5.5 <noreply@anthropic.com>
2026-11-10 17:51:02 +01:00
SirStoneandClaude Haiku 5.5 48b77888c6 design: fix wall and token ids (#3)
Co-Authored-By: Claude Haiku 5.5 <noreply@anthropic.com>
2026-11-10 17:13:25 +01:00
SirStoneandClaude Haiku 5.5 91cea1a364 research: mummy 0.4.8 and db_connector API facts (#10)
Co-Authored-By: Claude Haiku 5.5 <noreply@anthropic.com>
2026-11-10 16:54:03 +01:00
SirStoneandClaude Haiku 5.5 8f65680176 research: M3 test harness WebSocket options (#8)
Co-Authored-By: Claude Haiku 5.5 <noreply@anthropic.com>
2026-11-10 16:52:29 +01:00
SirStoneandClaude Haiku 5.5 c9d94e40b2 docs: handoff for M3 session
Co-Authored-By: Claude Haiku 5.5 <noreply@anthropic.com>
2026-11-08 19:22:51 +01:00
SirStoneandClaude Sonnet 5.5 809f219f42 results: regenerate mutation log (parallel run)
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-08 19:19:58 +01:00
SirStoneandClaude Sonnet 5.5 8d3b77add4 mutation: parallel jobs in temp copies, per-mutation test files, FFF_MUTATION reduced iterations, trap cleanup, sleep inhibit
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-08 19:19:58 +01:00
SirStoneandClaude Sonnet 5.5 dcb8efa422 results: regenerate test, mutation (a-o), bench logs
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-08 19:03:26 +01:00
SirStoneandClaude Sonnet 5.5 65c6b53c2a docs: DESIGN door push rule (5.5, 5.4, 6.1, H2, M2 accept, Q14)
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-08 18:56:22 +01:00
SirStoneandClaude Sonnet 5.5 a29bb0bb46 moverules: door close pushes overlapped tokens aside (valid-side check, blocked only if no side valid); Push list; tests; mutations m-o
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-08 18:56:06 +01:00
SirStoneandClaude Sonnet 5.5 153ff6cd18 docs: DESIGN blocked policy (set/keep/clear), 5k bench target, test-count baseline, GM OOB nack, wall id stability (M3)
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-08 18:53:12 +01:00
SirStoneandClaude Sonnet 5.5 0e67331b6c results: regenerate test, mutation (a-l), bench logs
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-08 18:53:12 +01:00
SirStoneandClaude Sonnet 5.5 388e901541 moverules: blocked policy set/keep/clear (GM moves and placements set/clear, KEEP while any wall overlaps); tests; mutations k, l
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-08 18:47:39 +01:00
SirStoneandClaude Sonnet 5.5 0e0b1a6052 mutation: run all test files, add mutations e-j (scanline fill, escape crossing, GM bypass, capsule, step cap, blocked trigger); header limitations updated
Control passes; a-d still caught (1,2,2,1,1 expected tests), new e-j each caught. Logs regenerated.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-08 18:33:12 +01:00
SirStoneandClaude Sonnet 5.5 e0705a8533 bench: harness with synthetic 5k-wall scenes (devbox run bench), scenegen + tests
Targets met without a spatial grid: polygon+cells 0.048 ms (<= 0.451) on the prototype scene, polygon 0.083 ms
(< 1 ms) on 5k sparse. 5k dense stress layout reported (1.28 ms). Logs: results/bench.log, nimble-test.log.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-08 12:15:31 +01:00
SirStoneandClaude Sonnet 5.5 afe84f2add moverules: swept-circle move check, token-on-wall escape, blocked flag, step cap, GM bypass
Pure in-process module (server/moverules.nim, plain data, no IO) per DESIGN 5.5. Replaces moveBlocked tests
(ported at r=0), the KNOWN LIMITATION pin and the Q14 pin with positive escape/capsule assertions and
blocked-policy tests. tests/tprobing.nim: in-process T8 probing test with a concrete bound (stepCap + r).

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-08 12:11:49 +01:00
SirStoneandClaude Sonnet 5.5 67fa96e23d geometry: scanline cellsTouched, differential + independent oracle tests, prototype corpus
cellsTouched is now a scanline over cell rows (prototype per-cell version kept test-only in
tests/refold.nim). Differential tests (random polygons, concave, grid-aligned) and a brute-force
explored oracle (0.5 px tolerance) cover it; regression corpus = prototype leak-run polygons.
moveBlocked leaves geometry.nim (replaced by server/moverules.nim next); geometry primitives exported.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-08 12:08:21 +01:00
SirStoneandClaude Haiku 5.5 206f99deda docs: M2 decisions (blocked trigger, GM moves, move rules scope)
Record owner decisions for M2 in DESIGN.md section 5.5 and update
sections 3.4 (T8), 4.2, 5.1, 5.4, 6.1, 7.4, 8, 10.3, 12 (H2, H3, H10,
H26), 13 (M2) and 14.

- blocked trigger: wall added / door closed overlapping any part of a
  token circle (dist centre-segment < r), not only centre-on-wall
- GM moves ignore walls, step cap and blocked
- player step cap = token vision radius, scene default if no vision
- capsule/swept check; escape rule for start-overlapping walls
- over-cap and blocked moves share one uniform nack
- M2 test layer: in-process move-rules module; WS probing test in M3

Co-Authored-By: Claude Haiku 5.5 <noreply@anthropic.com>
2026-11-08 11:59:55 +01:00
SirStoneandClaude Haiku 5.5 2cd0b1cd19 docs: Q4 resolved (32 px tiles), outbox lock invariant, cleanups — all §14 questions answered
Co-Authored-By: Claude Haiku 5.5 <noreply@anthropic.com>
2026-11-08 11:49:21 +01:00
SirStoneandClaude Haiku 5.5 eb1b128668 prototype-tile-leak: phone run results (Android 10, Chrome 157)
Co-Authored-By: Claude Haiku 5.5 <noreply@anthropic.com>
2026-11-08 11:48:09 +01:00
SirStoneandClaude Sonnet 5.5 b091882d7d prototype-tile-leak: phone test page (Pixi tile-size client check)
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-08 11:34:48 +01:00
SirStoneandClaude Sonnet 5.5 f28cb902e5 prototype-tile-leak: Q4 masked tiles vs cell-size tiles
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-08 11:22:44 +01:00
SirStoneandClaude Haiku 5.5 1078154b36 docs: record Q13 (bounded outbox) and Q20 (buildNimPackage) decisions
- 4.2 step 7: diff against known moves to flush time (outbox).
- 4.3 slow client: bounded per-client outbox, coalescing, Ping(seq)/Pong lag, no mummy patch.
- 6.1 ping row: lag is WS Ping/Pong, not app ping.
- 10.3 slow-client test expectations.
- 11.1 service: nix/package.nix + nix/module.nix + nix/lock.json; mummy tag 0.4.8.
- 12 H18, 13 M5/M6 scope and accept, 14 Q13/Q20 resolved.
- Status v0.3; mummy pin is tag 0.4.8 (fixes stale no-tags note).

Co-Authored-By: Claude Haiku 5.5 <noreply@anthropic.com>
2026-11-08 11:21:45 +01:00
SirStoneandClaude Haiku 5.5 9b3b154fc8 docs: add Q13/Q20 research notes
Q13: mummy slow WebSocket clients (pin 01deb1f), option analysis.
Q20: Nix packaging of the Nim server (buildNimPackage, nim_lk lock, NixOS module).

Co-Authored-By: Claude Haiku 5.5 <noreply@anthropic.com>
2026-11-08 11:21:19 +01:00
SirStoneandClaude Haiku 5.5 24fa9b25b8 docs: Q1 resolved, max 6 players in v1
Co-Authored-By: Claude Haiku 5.5 <noreply@anthropic.com>
2026-11-08 11:14:54 +01:00
SirStoneandClaude Haiku 5.5 69704b9c29 docs: record owner decisions on §14 open questions
Co-Authored-By: Claude Haiku 5.5 <noreply@anthropic.com>
2026-11-08 11:14:18 +01:00
SirStoneandClaude Haiku 5.5 b23993bcce chore: add .vscode IDE config
Co-Authored-By: Claude Haiku 5.5 <noreply@anthropic.com>
2026-11-08 10:39:20 +01:00
SirStoneandClaude Haiku 5.5 efc72d6859 docs: DESIGN.md fixes after M1 (layout, test counts, Q14 pointers, token-on-wall limitation, refs)
- 13 M1: drop client/ and nix/ from M1 scope; client/ -> M4, nix/ -> M6 (Q20)
- 33 checks -> 33 test blocks / 98 checks ported, none dropped (5.2, 10.1, 13 M1)
- 5.4 and 12 H2: door closing on a token left open (Q14), with pinning test
- 5.4: token-on-wall limitation stated as code behaviour + KNOWN LIMITATION test; escape fix as PROPOSED item in 13 M2
- 5.1/5.2/5.3/5.4: prototype README/NOTES/HANDOFF refs repointed to tests and server/geometry.nim; prototype NOTES kept as bug/measurement evidence

Co-Authored-By: Claude Haiku 5.5 <noreply@anthropic.com>
2026-11-08 10:24:12 +01:00
SirStoneandClaude Sonnet 5.5 8751b83ad8 tools/mutation.sh: temp-copy mutations a-d (d1/d2 = shared-vertex arms); logs results/mutation.log, nimble-test.log
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-08 10:09:20 +01:00
SirStoneandClaude Sonnet 5.5 b8d68cdb3a tests: shared-vertex both-arms test, door-closed-on-token pin (Q14), KNOWN LIMITATION token-on-wall pin
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-08 10:08:26 +01:00
SirStoneandClaude Sonnet 5.5 547458c37e m1: devbox, nimble, layout; port geometry.nim and 33 tgeometry tests (98 checks)
Fixture tests/fixtures/scene.json copied from prototype data/; seed test no longer skips if missing.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-08 10:06:58 +01:00
SirStoneandClaude Sonnet 5.5 daeadca9c2 docs: add DESIGN.md
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-08 10:06:07 +01:00
SirStoneandClaude Haiku 5.5 8ad7759665 prototype-server-vision: docs: fix shared-endpoint test comments, stale spike link, SLOW count; HANDOFF items
- tests/tgeometry.nim: shared-endpoint comments had hidden/visible sides inverted (ray y=10 at x=70; (70,9) hidden, (70,11) visible). Comments only.
- README: spike link -> results/spike/investigation.md
- investigation.md: base run 1 had three SLOW lines (gseq 136, 138, 152), not one
- HANDOFF: test gap (vertical-arm-only passes shared-endpoint test), timing instrumentation do-not-port, synchronous=NORMAL merged into existing item, caveats section

Co-Authored-By: Claude Haiku 5.5 <noreply@anthropic.com>
2026-11-07 18:28:24 +01:00
SirStoneandClaude Sonnet 5.5 f85a33df8b prototype-server-vision: close-out: final-run results (commit 18c9884), HANDOFF.md, README headers/numbers, commit leak transcripts + faults.log, move spike logs to results/spike
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-07 16:37:07 +01:00
SirStoneandClaude Sonnet 5.5 18c98844ad prototype-server-vision: concurrency script: no SLOW lines must not fail the run (grep rc under set -e)
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-07 16:29:52 +01:00
SirStoneandClaude Sonnet 5.5 1670e104a2 prototype-server-vision: devbox run clienttest (client reducer tests -> results/client-tests.log)
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-07 16:22:57 +01:00
SirStoneandClaude Sonnet 5.5 a337cec58a prototype-server-vision: synchronous=NORMAL (WAL), spike investigation (583 ms not reproduced), fixed runs, post-fix leak/fault/restart logs
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-07 16:21:38 +01:00
SirStoneandClaude Sonnet 5.5 b202eb62f3 prototype-server-vision: per-mutation timing (lock wait/vision/sqlite/send/total, SLOW_MS lines, percentiles), p99 in concurrency output, 3 baseline 60 s runs
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-07 16:15:08 +01:00
SirStoneandClaude Sonnet 5.5 6449c2cf5e prototype-server-vision: geometry corner tests ('<' apex, endpoint vertices, +-eps rays, shared vertex) + mutation check (devbox run mutation, results/mutation-{a,b,c}.log)
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-07 16:10:38 +01:00
SirStoneandClaude Sonnet 5.5 a865b39657 prototype-server-vision: README numbers from results/ logs (60 s concurrency, bench, leak A/B), new tests documented
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-07 13:11:08 +01:00
SirStoneandClaude Sonnet 5.5 74d612b55e prototype-server-vision: restore shared-endpoint probe, add visible/hidden probes to weak corner-case tests
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-07 13:05:49 +01:00
SirStoneandClaude Sonnet 5.5 819b120ba3 prototype-server-vision: restart durability test (SIGTERM + SIGKILL, same DB)
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-07 13:05:49 +01:00
SirStoneandClaude Sonnet 5.5 7339db04ce prototype-server-vision: deliberate-leak test (-d:leakfault build, 8 injected faults, exact checker class sets); checker failures carry classes
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-07 13:05:49 +01:00
SirStoneandClaude Sonnet 5.5 fd681f31a0 prototype-server-vision: leaktest writes results/leak-{A,B}.log (+ .jsonl transcripts, gitignored: >1 MB)
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-07 12:56:04 +01:00
SirStoneandClaude Sonnet 5.5 eef899e015 prototype-server-vision: token radius (r=20) clearance in move validation; tokenRadius in scene.json + hello
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-04 21:12:53 +01:00
SirStoneandClaude Haiku 5.5 217751f76c prototype-server-vision: NOTES smoke cmd uses isolated test path (devbox run smoke)
Co-Authored-By: Claude Haiku 5.5 <noreply@anthropic.com>
2026-11-01 23:46:38 +01:00
SirStoneandClaude Haiku 5.5 1924a45c84 prototype-server-vision: isolate tests from live session (run/test, ports 18088/19000, RUN_DIR/BACKEND_PORT env)
withserver.sh wiped run/state.db and built ./server; tests now use run/test/ (own DB, invites, nginx conf/logs, binary) and TEST_PORT/TEST_BACKEND_PORT (default 18088/19000), refusing 8088/9000. Server reads RUN_DIR and BACKEND_PORT (defaults run, 9000 unchanged). devbox test now runs smoke, leaktest, concurrency (DUR=15).

Co-Authored-By: Claude Haiku 5.5 <noreply@anthropic.com>
2026-11-01 23:35:52 +01:00
SirStoneandClaude Haiku 5.5 304e56d6e6 prototype-server-vision: status bar shows identity (player A/B, gm) derived from hello.tokens
Co-Authored-By: Claude Haiku 5.5 <noreply@anthropic.com>
2026-11-01 23:25:57 +01:00
SirStoneandClaude Sonnet 5.5 ef19d362c6 prototype-server-vision: fix scrambled visibility fan (angle range mix), leaktest SUBJECT=A|B + independent LOS oracle
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-01 23:25:10 +01:00
SirStoneandClaude Sonnet 5.5 26d7079084 prototype-server-vision: phase 3 (integration fixes, leaktest, concurrency, bench, README)
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-01 23:03:24 +01:00
SirStoneandClaude Sonnet 5.5 013c29e4da prototype-server-vision: phase 2a (mummy server, nginx conf, neutral doors in tiles, smoke)
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-01 22:52:00 +01:00
SirStoneandClaude Sonnet 5.5 2b8aa6b233 prototype-server-vision: phase 2b client (Vite+TS+Pixi v8, fog masks, drag, reducer test)
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-01 22:47:14 +01:00
SirStoneandClaude Sonnet 5.5 3a7c9af9f2 prototype-server-vision: phase 1 (devbox, nimble skeleton, map gen, geometry + tests)
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-01 22:44:34 +01:00
218 changed files with 68786 additions and 9 deletions
+15
View File
@@ -0,0 +1,15 @@
.devbox/
# devbox package plugins (nginx, slice 9) regenerate these helper files on every shell; not source
devbox.d/
nix/
nimbledeps/
nimble.paths
nimcache/
tests/t[a-z]*
!tests/*.nim
!tests/fixtures/
tools/bench
tools/mkcorpus
run/
# node-test.log carries per-run durations; regenerate it, do not commit it
results/node-test.log
+32
View File
@@ -0,0 +1,32 @@
{
"workbench.colorCustomizations": {
"activityBar.activeBackground": "#c88765",
"activityBar.activeBorder": "#15202b",
"activityBar.background": "#c88765",
"activityBar.foreground": "#15202b",
"activityBar.inactiveForeground": "#15202b99",
"activityBarBadge.background": "#b9e6c8",
"activityBarBadge.foreground": "#15202b",
"activityBarTop.activeBackground": "#c88765",
"activityBarTop.activeBorder": "#15202b",
"activityBarTop.background": "#c88765",
"activityBarTop.foreground": "#15202b",
"activityBarTop.inactiveForeground": "#15202b99",
"commandCenter.border": "#e7e7e799",
"commandCenter.foreground": "#e7e7e7",
"sash.hoverBorder": "#c88765",
"statusBar.background": "#b86b42",
"statusBar.debuggingBackground": "#b86b42",
"statusBar.debuggingForeground": "#e7e7e7",
"statusBar.foreground": "#e7e7e7",
"statusBar.inactiveBackground": "#b86b42",
"statusBarItem.hoverBackground": "#c88765",
"statusBarItem.remoteBackground": "#72cc92",
"statusBarItem.remoteForeground": "#e7e7e7",
"titleBar.activeBackground": "#b86b42",
"titleBar.activeForeground": "#e7e7e7",
"titleBar.inactiveBackground": "#b86b4299",
"titleBar.inactiveForeground": "#e7e7e799"
},
"peacock.color": "#b86b42"
}
+1 -1
View File
@@ -8,7 +8,7 @@ Gitea issues at `git.fossellini.top`, repo `SirStone/FFF_vtt`. See `docs/agents/
### Triage labels
Five default roles, label strings equal to role names: `needs-triage`, `needs-info`, `ready-for-agent`, `ready-for-human`, `wontfix`. See `docs/agents/triage-labels.md`.
Two category roles (`bug`, `enhancement`) and five state roles (`needs-triage`, `needs-info`, `ready-for-agent`, `ready-for-human`, `wontfix`), label strings equal to role names. See `docs/agents/triage-labels.md`.
### Domain docs
+103
View File
@@ -0,0 +1,103 @@
# FFF_vtt
A browser virtual tabletop for one table: the GM and players share a map with walls, doors and tokens. This glossary holds the terms that are specific to that table.
## Language
**Token size**:
How big a token is on the map, as a radius in map pixels. A token uses its own size if one is set, otherwise the scene's default size. This is its footprint on the map, not how tall the figure is (see Height).
_Avoid_: token scale, token diameter, size preset
**Height**:
How tall a figure is, in metres. A character has a base height; a token may carry its own instead, a temporary on-map override (a spell that enlarges the figure) that never changes the character and disappears with the token. A plain token has only its own height and must have one. Players never see the number, only what it lets them see.
_Avoid_: elevation, z, altitude (those are position above the ground)
**Eye height**:
How high a figure's eyes are, in metres. Follows the same rule as Height: a character value with an optional token override. Unless someone sets it by hand it is 93% of the figure's height and follows any change to that height; it may also be higher than the figure itself (a floating eye).
_Avoid_: eye level, vision height
**Stuck**:
A lock condition meaning the token is held in place: a wall runs through it, or something holds it (ropes, a magic grasp). A player cannot move a stuck token; the GM always can.
_Avoid_: blocked
**Squeezed**:
A lock condition meaning the token is pressed with no room: walls surround it, or a closing hand presses it. A player cannot move a squeezed token; the GM always can.
_Avoid_: blocked, crushed
Neither term names its cause. Stuck and squeezed both lock a token for its player in the same way; they differ only in why.
**GM**:
The one person who runs the table and sees everything: all walls, all tokens, all hidden state. A player can never become the GM.
_Avoid_: DM, admin, host
**Player key**:
A personal secret the GM gives one player. It signs that player in from the shared site link and identifies them; the GM can show it again or replace it.
_Avoid_: token, invite link, password
**GM key**:
The secret that signs the GM in from the shared site link. It is made by the server's command line, not in the browser.
_Avoid_: token, invite link, password
**Player**:
A real person at the table who signs in with a player key. A player is not a character; one player may own several characters.
_Avoid_: user, account, member
**Character**:
A named record of who someone is: identity and base values. Has exactly one owner, a player or the GM. Its tokens show it on the map.
_Avoid_: PC, hero
**Token**:
A figure on the map. It may belong to a character; a plain token (monster, item) belongs to none. Holds what is happening to the figure. Its controller is set on its own and does not follow the character's owner.
_Avoid_: entity, piece, counter
**Wall**:
A barrier on the map with a length, a thickness and a height. It hides what its dimensions hide. What it *does* is a set of **switches** it carries: blocks sight, blocks movement, and (for sight) a direction; a door is a wall with the door setting plus open/secret/locked. A named wall kind is only a preset over those switches, never the wall's own identity. A wall is full height unless the GM gives it a height in metres, so by default nobody sees over it; an older wall without a height keeps hiding everything behind it. In v1 a wall has zero thickness; per-wall thickness and what a low wall hides are pending (map #38).
_Avoid_: blocker, collider, obstacle, sight blocker, wall type (use preset)
**Wall switch**:
One independent setting a wall's behaviour is made of: `blocks sight` or `blocks movement`. Neither implies the other: a wall can hide what is behind it and let people walk through, or the reverse. A door's settings (open, secret, locked) and the sight direction are settings of the same wall but not switches. Switches are stored on the wall and read by the server.
_Avoid_: flag, bit, property (that word already means token data), restriction type
**Wall preset**:
A named combination of switches and door settings the GM picks in one action: wall, door, secret door, locked door, terrain, one-way wall. It is a shortcut and a label, not a stored kind: the wall keeps the switches, and the name is derived when they match a preset exactly (`custom` otherwise). So two presets can never drift from what the wall actually does.
_Avoid_: wall kind, wall type, category
**One-way wall**:
A wall whose sight switch carries a direction: it blocks sight from one side and lets the other side see across it. Movement is unaffected by the direction, so a one-way wall still blocks (or lets through) movement on both sides alike. Which side is blocked is decided by the wall's `a -> b` order.
_Avoid_: one-sided wall, directed wall, mirror wall
**Secret door**:
A door the players never learn exists. It is always closed and, to a player, behaves exactly like a solid wall: same sight, same explored cells, same refusals, nothing that marks it as a door. The GM reveals it by making it an ordinary door and opening it.
_Avoid_: hidden door, concealed door, illusionary wall
**Locked door**:
A closed door the server refuses to open until it is unlocked. The lock is the GM's business only: players get no signal of it, and a locked door behaves exactly as a closed door to sight and movement. In v1 only the GM opens doors, so the setting is authoring state waiting for player door interaction.
_Avoid_: barred door
**Terrain**:
A wall preset that blocks movement and not sight: a railing, bushes, a low barrier, a pit edge. People see over or through it and cannot pass. It is absent from the sight rules entirely, so its thickness and height never affect sight.
_Avoid_: transparent wall, invisible wall, obstacle (that names the thing, not the preset)
**Property**:
One named value a token carries, e.g. "aura" or "hp". The server stores it and does not interpret it in v1, apart from the few sight keys it reads itself (see Height and Eye height); FFF does the rest later.
_Avoid_: attribute, stat, metadata
**Property bucket**:
The visibility a property is filed under: `public` (anyone who sees the token), `owner` (the token's controller and the GM) or `gm` (the GM only). A prop key may live in all three at once with different values.
_Avoid_: layer, scope, channel
**Property schema registry**:
The rules module's table of known property keys, each with a value kind and a bucket. It ships empty in v1, so any key is accepted in any bucket; a registered key is enforced on every write.
_Avoid_: prop whitelist, schema cache
**Descriptive name**:
The name a player sees for a character or plain token until the GM reveals the actual name, e.g. "a grumpy man". Every character and plain token has one.
_Avoid_: alias, label, nickname
**Actual name**:
The true name of a character or plain token, e.g. "Lord Vex". Its character's owner always sees it; a player sees it once the GM reveals it to them.
_Avoid_: real name (ambiguous with a player's real name), true name
**Encountered list**:
Per player, every token that the player's tokens have ever seen, under the name that player knows. Out of sight, an entry is greyed ("met before, whereabouts unknown"). Only the GM removes entries.
_Avoid_: roster (that is the player list), contacts
+38
View File
@@ -0,0 +1,38 @@
{
"$schema": "https://raw.githubusercontent.com/jetify-com/devbox/0.17.2/.schema/devbox.schema.json",
"packages": {
"nim": "2",
"nimble": "latest",
"coreutils": "latest",
"gnused": "latest",
"diffutils": "latest",
"gnugrep": "latest",
"nodejs": "26",
"sqlite": {
"version": "latest",
"outputs": [
"out",
"bin"
]
},
"nginx": "latest"
},
"shell": {
"init_hook": [],
"scripts": {
"test": [
"tools/test.sh"
],
"mutation": [
"tools/mutation.sh"
],
"bench": [
"mkdir -p results; nim c -d:release --hints:off -r tools/bench.nim > results/bench.log 2>&1; rc=$?; cat results/bench.log; exit $rc"
]
}
},
"env": {
"NIMBLE_DIR": "$DEVBOX_PROJECT_ROOT/.devbox/nimble",
"LD_LIBRARY_PATH": "$DEVBOX_PACKAGES_DIR/lib"
}
}
+687
View File
@@ -0,0 +1,687 @@
{
"lockfile_version": "1",
"packages": {
"coreutils@latest": {
"last_modified": "2026-10-08T19:21:32Z",
"resolved": "github:NixOS/nixpkgs/8edc0c72e3a38faf5434e40d1f19431125fe4b30#coreutils",
"source": "devbox-search",
"version": "9.11",
"systems": {
"aarch64-darwin": {
"outputs": [
{
"name": "out",
"path": "/nix/store/82fb09q2gbhbhpc8ykkqwkcdj6h9c7f1-coreutils-9.11",
"default": true
},
{
"name": "info",
"path": "/nix/store/60lm7sjnjcw93h8c6bgk1lgams4a0z8z-coreutils-9.11-info"
}
],
"store_path": "/nix/store/82fb09q2gbhbhpc8ykkqwkcdj6h9c7f1-coreutils-9.11"
},
"aarch64-linux": {
"outputs": [
{
"name": "out",
"path": "/nix/store/dq1apsyiah48nmc4n45dpwc33k887hdn-coreutils-9.11",
"default": true
},
{
"name": "debug",
"path": "/nix/store/zf1kvml4h5wk3n22h17fnqvyzm1cjnbc-coreutils-9.11-debug"
},
{
"name": "info",
"path": "/nix/store/982a6ix3bby4pqw5gqs9lhzbkay0h19z-coreutils-9.11-info"
}
],
"store_path": "/nix/store/dq1apsyiah48nmc4n45dpwc33k887hdn-coreutils-9.11"
},
"x86_64-darwin": {
"outputs": [
{
"name": "out",
"path": "/nix/store/rg42k0h3hj1mwldhywll29n7m0kcpxq2-coreutils-9.11",
"default": true
},
{
"name": "info",
"path": "/nix/store/8jc9262zif5m5gh6h5n1kbs5yrv594xn-coreutils-9.11-info"
}
],
"store_path": "/nix/store/rg42k0h3hj1mwldhywll29n7m0kcpxq2-coreutils-9.11"
},
"x86_64-linux": {
"outputs": [
{
"name": "out",
"path": "/nix/store/2gfxiwls9hbgwdwcy43mprchwsq36mg6-coreutils-9.11",
"default": true
},
{
"name": "info",
"path": "/nix/store/afwhyjd9mwhk09dql7n25q0l7005a5gd-coreutils-9.11-info"
},
{
"name": "debug",
"path": "/nix/store/phqk9ra56bnhhi6f5scyvnfbxfd7bffd-coreutils-9.11-debug"
}
],
"store_path": "/nix/store/2gfxiwls9hbgwdwcy43mprchwsq36mg6-coreutils-9.11"
}
}
},
"diffutils@latest": {
"last_modified": "2026-10-02T22:55:44Z",
"resolved": "github:NixOS/nixpkgs/55ba7f49ef2962b42cbd126522b7df5f95037679#diffutils",
"source": "devbox-search",
"version": "3.12",
"systems": {
"aarch64-darwin": {
"outputs": [
{
"name": "out",
"path": "/nix/store/i5gfxrhmkxqjdk4r8ar1gq80sg180z9d-diffutils-3.12",
"default": true
},
{
"name": "info",
"path": "/nix/store/16plsg2g71qywwsakysmcyhnwxxqn81y-diffutils-3.12-info"
}
],
"store_path": "/nix/store/i5gfxrhmkxqjdk4r8ar1gq80sg180z9d-diffutils-3.12"
},
"aarch64-linux": {
"outputs": [
{
"name": "out",
"path": "/nix/store/19m79n6f7c3ay59121jqgacf8bw4wcq2-diffutils-3.12",
"default": true
},
{
"name": "info",
"path": "/nix/store/r6da78vrvnqfbrx7jlbmhwnj5kig5zik-diffutils-3.12-info"
}
],
"store_path": "/nix/store/19m79n6f7c3ay59121jqgacf8bw4wcq2-diffutils-3.12"
},
"x86_64-darwin": {
"outputs": [
{
"name": "out",
"path": "/nix/store/lwghldxh6irjmbp73lpxv6mrdwb4aqhv-diffutils-3.12",
"default": true
},
{
"name": "info",
"path": "/nix/store/7rh8a74vwdb6lvvvwjd0dlpv84hl6mr6-diffutils-3.12-info"
}
],
"store_path": "/nix/store/lwghldxh6irjmbp73lpxv6mrdwb4aqhv-diffutils-3.12"
},
"x86_64-linux": {
"outputs": [
{
"name": "out",
"path": "/nix/store/1jhkxfbnx35m08gv5fyamp6ai5qhbjdh-diffutils-3.12",
"default": true
},
{
"name": "info",
"path": "/nix/store/lzbs18ypdiv6b4zvryfwr3sdy2n7f81l-diffutils-3.12-info"
}
],
"store_path": "/nix/store/1jhkxfbnx35m08gv5fyamp6ai5qhbjdh-diffutils-3.12"
}
}
},
"gawk@latest": {
"last_modified": "2026-10-02T22:55:44Z",
"resolved": "github:NixOS/nixpkgs/55ba7f49ef2962b42cbd126522b7df5f95037679#gawk",
"source": "devbox-search",
"version": "5.4.1",
"systems": {
"aarch64-darwin": {
"outputs": [
{
"name": "out",
"path": "/nix/store/49jhcfya6jlc7p2hibbl2y5sfz132j3i-gawk-5.4.1",
"default": true
},
{
"name": "man",
"path": "/nix/store/1sclicd2js7iipqnw4vn1rmy3scjg72v-gawk-5.4.1-man",
"default": true
},
{
"name": "info",
"path": "/nix/store/n8gfvirxjm8z5zq7cx30qrmhn40w7jrb-gawk-5.4.1-info"
}
],
"store_path": "/nix/store/49jhcfya6jlc7p2hibbl2y5sfz132j3i-gawk-5.4.1"
},
"aarch64-linux": {
"outputs": [
{
"name": "out",
"path": "/nix/store/2bwpli20ff4f7hg5ck477p8s57kj857w-gawk-5.4.1",
"default": true
},
{
"name": "man",
"path": "/nix/store/wfnxkfk386wl2plrhqx7lwfj4z84r493-gawk-5.4.1-man",
"default": true
},
{
"name": "info",
"path": "/nix/store/l6wddbkc3rxavhbxyl48gn47rw8fq0pd-gawk-5.4.1-info"
}
],
"store_path": "/nix/store/2bwpli20ff4f7hg5ck477p8s57kj857w-gawk-5.4.1"
},
"x86_64-linux": {
"outputs": [
{
"name": "out",
"path": "/nix/store/63g104xwbzfpcq0h7c99w19m6j9ly3p1-gawk-5.4.1",
"default": true
},
{
"name": "man",
"path": "/nix/store/0azvqykndxs3clnj974q99cjfnmpprjv-gawk-5.4.1-man",
"default": true
},
{
"name": "info",
"path": "/nix/store/l4pwpdc6hrgy8n3diy24n389k53jqqjk-gawk-5.4.1-info"
}
],
"store_path": "/nix/store/63g104xwbzfpcq0h7c99w19m6j9ly3p1-gawk-5.4.1"
}
}
},
"gettext@latest": {
"last_modified": "2026-10-02T22:55:44Z",
"resolved": "github:NixOS/nixpkgs/55ba7f49ef2962b42cbd126522b7df5f95037679#gettext",
"source": "devbox-search",
"version": "1.0",
"systems": {
"aarch64-darwin": {
"outputs": [
{
"name": "out",
"path": "/nix/store/d73j7348argskpyvj28wq8n65mj6yg9x-gettext-1.0",
"default": true
},
{
"name": "man",
"path": "/nix/store/arv8546qvpn8cr2bsgvzbzzzypmdv1kp-gettext-1.0-man",
"default": true
},
{
"name": "doc",
"path": "/nix/store/4myr9gbsxvryjnwanyyhnnpqrdh56d5n-gettext-1.0-doc"
},
{
"name": "info",
"path": "/nix/store/b4d4imijjkkzr49zh5mq4gz2j9m2s047-gettext-1.0-info"
}
],
"store_path": "/nix/store/d73j7348argskpyvj28wq8n65mj6yg9x-gettext-1.0"
},
"aarch64-linux": {
"outputs": [
{
"name": "out",
"path": "/nix/store/8aimx510wyy0rzy7mllcjad5299jd17a-gettext-1.0",
"default": true
},
{
"name": "man",
"path": "/nix/store/qllbgswyx416d7r7kqkyxvafpfbasmr8-gettext-1.0-man",
"default": true
},
{
"name": "doc",
"path": "/nix/store/r2d6saacyqv8m9d8bvaidv4x2raqjb7z-gettext-1.0-doc"
},
{
"name": "info",
"path": "/nix/store/hsrnhwfpvrs4x4a5807cprpyz4qclgxy-gettext-1.0-info"
}
],
"store_path": "/nix/store/8aimx510wyy0rzy7mllcjad5299jd17a-gettext-1.0"
},
"x86_64-darwin": {
"outputs": [
{
"name": "out",
"path": "/nix/store/9mxzw5vwn99vx2b74ipjzk8x4b784fjy-gettext-1.0",
"default": true
},
{
"name": "man",
"path": "/nix/store/r87hlf9pn8q3a8rnplzhy9lbgaadqcr8-gettext-1.0-man",
"default": true
},
{
"name": "doc",
"path": "/nix/store/xmssbi5i2w3fv67hrv6c29wdiv8gxywi-gettext-1.0-doc"
},
{
"name": "info",
"path": "/nix/store/j4lz4zqicd1mw2l5c272ialxhl0nkc0b-gettext-1.0-info"
}
],
"store_path": "/nix/store/9mxzw5vwn99vx2b74ipjzk8x4b784fjy-gettext-1.0"
},
"x86_64-linux": {
"outputs": [
{
"name": "out",
"path": "/nix/store/gfkkr23q11kvyz6xxyxz3qbsp1msxdcv-gettext-1.0",
"default": true
},
{
"name": "man",
"path": "/nix/store/njdszjnrb0n7c6m6jzmx5539ac0ybn9g-gettext-1.0-man",
"default": true
},
{
"name": "doc",
"path": "/nix/store/z2p7kr1a45gz9m9g3s6rary2avk3gs9x-gettext-1.0-doc"
},
{
"name": "info",
"path": "/nix/store/8vqnaf3h4vlb8q5w9z9kscqld7m5rdif-gettext-1.0-info"
}
],
"store_path": "/nix/store/gfkkr23q11kvyz6xxyxz3qbsp1msxdcv-gettext-1.0"
}
}
},
"github:NixOS/nixpkgs/nixpkgs-unstable": {
"last_modified": "2026-10-20T14:23:57Z",
"resolved": "github:NixOS/nixpkgs/5adc50831c259f87faeb09ddf930d43597197473?lastModified=1792506237&narHash=sha256-Q%2F8KLB6jNfpaUN1HAedE%2Fu%2FEt9feE%2FzYSsutBLKrCFk%3D"
},
"gnugrep@latest": {
"last_modified": "2026-10-02T22:55:44Z",
"resolved": "github:NixOS/nixpkgs/55ba7f49ef2962b42cbd126522b7df5f95037679#gnugrep",
"source": "devbox-search",
"version": "3.12",
"systems": {
"aarch64-darwin": {
"outputs": [
{
"name": "out",
"path": "/nix/store/f14505vy0sckbv11qb22s7yd2a7dxq1r-gnugrep-3.12",
"default": true
},
{
"name": "info",
"path": "/nix/store/h8bfc07gly890mlfy46ypgj3k9p8lcf2-gnugrep-3.12-info"
}
],
"store_path": "/nix/store/f14505vy0sckbv11qb22s7yd2a7dxq1r-gnugrep-3.12"
},
"aarch64-linux": {
"outputs": [
{
"name": "out",
"path": "/nix/store/82643wb56lminz3a4b6gk92d2g4ydwks-gnugrep-3.12",
"default": true
},
{
"name": "info",
"path": "/nix/store/abjzd0f148kdgb2c4hbmch63swjv6s03-gnugrep-3.12-info"
}
],
"store_path": "/nix/store/82643wb56lminz3a4b6gk92d2g4ydwks-gnugrep-3.12"
},
"x86_64-darwin": {
"outputs": [
{
"name": "out",
"path": "/nix/store/c7yhik3dfpz5csbfc2v8lg0lgnfhz7wy-gnugrep-3.12",
"default": true
},
{
"name": "info",
"path": "/nix/store/pyd0kfynkm5h94ms170a5fvaf4yy57gz-gnugrep-3.12-info"
}
],
"store_path": "/nix/store/c7yhik3dfpz5csbfc2v8lg0lgnfhz7wy-gnugrep-3.12"
},
"x86_64-linux": {
"outputs": [
{
"name": "out",
"path": "/nix/store/3668q0d9zhc5n9l2pnyvpd44kz9bjsjm-gnugrep-3.12",
"default": true
},
{
"name": "info",
"path": "/nix/store/b9darrc5lshz7x9zxda2d5s9fkbdafk0-gnugrep-3.12-info"
}
],
"store_path": "/nix/store/3668q0d9zhc5n9l2pnyvpd44kz9bjsjm-gnugrep-3.12"
}
}
},
"gnused@latest": {
"last_modified": "2026-10-02T22:55:44Z",
"resolved": "github:NixOS/nixpkgs/55ba7f49ef2962b42cbd126522b7df5f95037679#gnused",
"source": "devbox-search",
"version": "4.10",
"systems": {
"aarch64-darwin": {
"outputs": [
{
"name": "out",
"path": "/nix/store/s5mhqidsrm8aw2982k3mv82ajanirjm8-gnused-4.10",
"default": true
},
{
"name": "info",
"path": "/nix/store/f3i35na89qgpdblj1jf9qmpciq77imv3-gnused-4.10-info"
}
],
"store_path": "/nix/store/s5mhqidsrm8aw2982k3mv82ajanirjm8-gnused-4.10"
},
"aarch64-linux": {
"outputs": [
{
"name": "out",
"path": "/nix/store/2jk00rxplr3qjmjl2q46l7izbf8gxcs6-gnused-4.10",
"default": true
},
{
"name": "info",
"path": "/nix/store/4fklshzmpnha3wqvv91ivyr3ypfqncq8-gnused-4.10-info"
}
],
"store_path": "/nix/store/2jk00rxplr3qjmjl2q46l7izbf8gxcs6-gnused-4.10"
},
"x86_64-linux": {
"outputs": [
{
"name": "out",
"path": "/nix/store/1ggxndc1gd5061j5hqprhnhx9p30yilv-gnused-4.10",
"default": true
},
{
"name": "info",
"path": "/nix/store/c27vx9wa4v50lrb30d60sa57iga6mc98-gnused-4.10-info"
}
],
"store_path": "/nix/store/1ggxndc1gd5061j5hqprhnhx9p30yilv-gnused-4.10"
}
}
},
"nginx@latest": {
"last_modified": "2026-10-02T22:55:44Z",
"plugin_version": "0.0.4",
"resolved": "github:NixOS/nixpkgs/55ba7f49ef2962b42cbd126522b7df5f95037679#nginx",
"source": "devbox-search",
"version": "1.30.5",
"systems": {
"aarch64-darwin": {
"outputs": [
{
"name": "out",
"path": "/nix/store/81a75xq2ilmn8dnrb1b7m8siyprmaq94-nginx-1.30.5",
"default": true
},
{
"name": "doc",
"path": "/nix/store/s9zq3wyd2bdfwb58rk2648yf2wsryvhj-nginx-1.30.5-doc"
}
],
"store_path": "/nix/store/81a75xq2ilmn8dnrb1b7m8siyprmaq94-nginx-1.30.5"
},
"aarch64-linux": {
"outputs": [
{
"name": "out",
"path": "/nix/store/7yvpd3svx846fybmc2d5ddxq3jxf94qm-nginx-1.30.5",
"default": true
},
{
"name": "doc",
"path": "/nix/store/skp8nki2v0li5h44zyp1gp8s2ahz3g4j-nginx-1.30.5-doc"
}
],
"store_path": "/nix/store/7yvpd3svx846fybmc2d5ddxq3jxf94qm-nginx-1.30.5"
},
"x86_64-linux": {
"outputs": [
{
"name": "out",
"path": "/nix/store/6k4rgdzx05z7yk2l98r28p6wrbnlv63z-nginx-1.30.5",
"default": true
},
{
"name": "doc",
"path": "/nix/store/d8v365rflmpicpcnxjqfxbbzlpk0q844-nginx-1.30.5-doc"
}
],
"store_path": "/nix/store/6k4rgdzx05z7yk2l98r28p6wrbnlv63z-nginx-1.30.5"
}
}
},
"nim@2": {
"last_modified": "2026-10-02T22:55:44Z",
"resolved": "github:NixOS/nixpkgs/55ba7f49ef2962b42cbd126522b7df5f95037679#nim",
"source": "devbox-search",
"version": "2.2.12",
"systems": {
"aarch64-darwin": {
"outputs": [
{
"name": "out",
"path": "/nix/store/h055h3lxxsm8kql0mannw3706x740x7f-arm64-apple-darwin-nim-wrapper-2.2.12",
"default": true
}
],
"store_path": "/nix/store/h055h3lxxsm8kql0mannw3706x740x7f-arm64-apple-darwin-nim-wrapper-2.2.12"
},
"aarch64-linux": {
"outputs": [
{
"name": "out",
"path": "/nix/store/2fh7rg634j8969c1r394llrsjmmhaip7-aarch64-unknown-linux-gnu-nim-wrapper-2.2.12",
"default": true
}
],
"store_path": "/nix/store/2fh7rg634j8969c1r394llrsjmmhaip7-aarch64-unknown-linux-gnu-nim-wrapper-2.2.12"
},
"x86_64-linux": {
"outputs": [
{
"name": "out",
"path": "/nix/store/0cbdz34lsakfirycixckf6ypsd8hazhg-x86_64-unknown-linux-gnu-nim-wrapper-2.2.12",
"default": true
}
],
"store_path": "/nix/store/0cbdz34lsakfirycixckf6ypsd8hazhg-x86_64-unknown-linux-gnu-nim-wrapper-2.2.12"
}
}
},
"nimble@latest": {
"last_modified": "2026-10-02T22:55:44Z",
"resolved": "github:NixOS/nixpkgs/55ba7f49ef2962b42cbd126522b7df5f95037679#nimble",
"source": "devbox-search",
"version": "0.24.1",
"systems": {
"aarch64-darwin": {
"outputs": [
{
"name": "out",
"path": "/nix/store/clxsxdsqjfcc43rfd7rad733nd0ndrkf-nimble-0.24.1",
"default": true
}
],
"store_path": "/nix/store/clxsxdsqjfcc43rfd7rad733nd0ndrkf-nimble-0.24.1"
},
"aarch64-linux": {
"outputs": [
{
"name": "out",
"path": "/nix/store/c5d0r4a8qi1vqs8q82pr3c652q8d6jv7-nimble-0.24.1",
"default": true
}
],
"store_path": "/nix/store/c5d0r4a8qi1vqs8q82pr3c652q8d6jv7-nimble-0.24.1"
},
"x86_64-linux": {
"outputs": [
{
"name": "out",
"path": "/nix/store/8f5wx2s80gnw0lkmdpbl63n1xlilcfxi-nimble-0.24.1",
"default": true
}
],
"store_path": "/nix/store/8f5wx2s80gnw0lkmdpbl63n1xlilcfxi-nimble-0.24.1"
}
}
},
"nodejs@26": {
"last_modified": "2026-10-08T19:21:32Z",
"plugin_version": "0.0.2",
"resolved": "github:NixOS/nixpkgs/8edc0c72e3a38faf5434e40d1f19431125fe4b30#nodejs_26",
"source": "devbox-search",
"version": "26.11.1",
"systems": {
"aarch64-darwin": {
"outputs": [
{
"name": "out",
"path": "/nix/store/42hvw959dvc16w7p79xns4p4sgfx2wiv-nodejs-26.11.1",
"default": true
}
],
"store_path": "/nix/store/42hvw959dvc16w7p79xns4p4sgfx2wiv-nodejs-26.11.1"
},
"aarch64-linux": {
"outputs": [
{
"name": "out",
"path": "/nix/store/zzx8zal1hmjkamrp8y9k6mjim08pzwz8-nodejs-26.11.1",
"default": true
}
],
"store_path": "/nix/store/zzx8zal1hmjkamrp8y9k6mjim08pzwz8-nodejs-26.11.1"
},
"x86_64-linux": {
"outputs": [
{
"name": "out",
"path": "/nix/store/m7vfpzl1rjwjpwlcsqs166jn3lywzpq1-nodejs-26.11.1",
"default": true
}
],
"store_path": "/nix/store/m7vfpzl1rjwjpwlcsqs166jn3lywzpq1-nodejs-26.11.1"
}
}
},
"sqlite@latest": {
"last_modified": "2026-10-08T19:21:32Z",
"resolved": "github:NixOS/nixpkgs/8edc0c72e3a38faf5434e40d1f19431125fe4b30#sqlite",
"source": "devbox-search",
"version": "3.53.3",
"systems": {
"aarch64-darwin": {
"outputs": [
{
"name": "bin",
"path": "/nix/store/9miwmq08y0pg4m97ws8b2gcqxrbr8d2c-sqlite-3.53.3-bin",
"default": true
},
{
"name": "man",
"path": "/nix/store/wlwc2gz7r5884rdmfjnqjk38lwv94qsy-sqlite-3.53.3-man",
"default": true
},
{
"name": "doc",
"path": "/nix/store/p6bsmbp6a5dz55isxvfr7941wbfjmjvf-sqlite-3.53.3-doc"
},
{
"name": "out",
"path": "/nix/store/0k4r9hnfbnyngn5f3j31siddfs0iglwl-sqlite-3.53.3"
},
{
"name": "dev",
"path": "/nix/store/r9cljv2bvqi3ci3n6m0z0wi3ldpvlyzq-sqlite-3.53.3-dev"
}
],
"store_path": "/nix/store/9miwmq08y0pg4m97ws8b2gcqxrbr8d2c-sqlite-3.53.3-bin"
},
"aarch64-linux": {
"outputs": [
{
"name": "bin",
"path": "/nix/store/kw0mkd9znldi5l0s4jygygdh4p9sms8r-sqlite-3.53.3-bin",
"default": true
},
{
"name": "man",
"path": "/nix/store/9q84sy842rw7k4z4jdsb4hkbiapr7pm0-sqlite-3.53.3-man",
"default": true
},
{
"name": "debug",
"path": "/nix/store/q39crs8z0dafx19dv0l2y4jxc8ahvy03-sqlite-3.53.3-debug"
},
{
"name": "dev",
"path": "/nix/store/74r7ps7mmjw10fl23xsgcp7ss09jrkjr-sqlite-3.53.3-dev"
},
{
"name": "doc",
"path": "/nix/store/g4f5y9laa7l7lbriv8x05clyi9x7w14z-sqlite-3.53.3-doc"
},
{
"name": "out",
"path": "/nix/store/2lyx0wc6ccabpdwpviksww3x5xhsmnvk-sqlite-3.53.3"
}
],
"store_path": "/nix/store/kw0mkd9znldi5l0s4jygygdh4p9sms8r-sqlite-3.53.3-bin"
},
"x86_64-linux": {
"outputs": [
{
"name": "bin",
"path": "/nix/store/iy2zkfn4l0w24xabv6ryi0vh7bpjvqm6-sqlite-3.53.3-bin",
"default": true
},
{
"name": "man",
"path": "/nix/store/is1ld1bxvwqqjwv89kl6vcnlpypbkg5r-sqlite-3.53.3-man",
"default": true
},
{
"name": "doc",
"path": "/nix/store/l778wamidjdrjyahinx63c7n50fwh0il-sqlite-3.53.3-doc"
},
{
"name": "out",
"path": "/nix/store/9x0m6s73sg89fv5awb95vsac2mbns8n0-sqlite-3.53.3"
},
{
"name": "debug",
"path": "/nix/store/1vbdchnss15n90chl72l80z16shxjp7l-sqlite-3.53.3-debug"
},
{
"name": "dev",
"path": "/nix/store/xrcjl59yi7zswbv0vzm8cmvw4vplsbgj-sqlite-3.53.3-dev"
}
],
"store_path": "/nix/store/iy2zkfn4l0w24xabv6ryi0vh7bpjvqm6-sqlite-3.53.3-bin"
}
}
}
}
}
+991
View File
@@ -0,0 +1,991 @@
# FFF_vtt design
Status: draft v0.22, 2026-11-15 (owner decisions recorded in section 14; v0.4 records Q4 (tile_size 32 px), the outbox lock invariant (4.2, 4.3), and the follow-ups in 3.4, 8, 11.1, 12, 13; v0.5 records the M2 move-rule decisions in 5.5 and updates 3.4, 4.2, 5.1, 5.4, 6.1, 7.4, 8, 10.3, 12, 13; v0.6 records #14 (characters and player data) in 3.1, 3.4, 4.1, 4.4, 6.1, 8, 9, 10.3, 13, 14; v0.7 records #6 (players and invites) in 3.1, 3.2, 3.4, 4.4, 6.1, 8, 12, 13, 14; v0.8 records #7 (map tiles) in 3.3, 3.4, 11.1, 13, 14; v0.9 records #9 (test tools) in 2, 10.4, 13, 14; v0.10 records #12 (what M3 done means) in 13, 14; v0.11 records #15 (M3 limits) in 4.3, 6.4, 10.1, 13, 14; v0.12 records #11 (M3 message list) in 3.1, 3.2, 3.4, 4.2, 4.3, 5.5, 5.6, 6, 7.5, 13, 14; v0.13 records the owner review of #11 flags in 1, 3.1, 5.5, 6.1, 8, 14; v0.14 records #17 (getting in: keys, sessions, the auth slice) in 3.2, 4.4, 6.5, 6.6, 8, 11.1, 13, 14; v0.15 records #18 (talking safely: the protocol shell and the `closing` close-reason message) in 3.2, 4.3, 6, 6.1, 6.2, 6.4, 6.5, 10.3, 13, 14; v0.16 records #19 (walls and doors: the scene/wall schema, the wall payload rules and the slice-4 rollout) in 4.4, 6.1, 8, 13, 14; v0.17 records #20 (tokens and sight: the `entity` step, the typed views and the single egress, vision and explored, and the slice-5 rollout) in 4.4, 6.1, 6.3, 8, 10.3, 13, 14; 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. 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.
- **[MEASURED]** number/behaviour taken from a prototype run (cited by path).
- **[INFERRED]** my reading of code or reasoning; not tested.
- **[PROPOSED]** design choice made in this doc; the owner may overturn it.
Evidence roots (relative to repo root):
- `prototype-pixi-perf/` (client perf; README holds all tables)
- `prototype-server-vision/` (server + vision; `README.md`, `HANDOFF.md`, `NOTES.md`, `results/`, `results/spike/investigation.md`)
- `prototype-tile-leak/` (tile size vs leak; `README.md` holds desktop tables and the 2026-11-08 phone run; `results/phone-20261108T113701.jsonl`)
- `docs/prototype.md` is only the original brief for the perf prototype.
- No FFF engine notes exist in the repo. `GLOSSARY.md` and `docs/adr/` do not exist yet; AGENTS.md requires them (Q24, FIXED). `prototype-*` dirs stay in-tree until the M4 client port, then are archived (Q24, FIXED). Nothing here is FFF-specific beyond the seam in section 9.
---
## 1. Goal and non-goals
### Goal
A browser virtual tabletop for one table (1 GM + up to 6 players [FIXED, Q1]), self-hosted, where the **server alone decides what each player sees**. A modified client must learn nothing it is not entitled to.
### v1 scope [PROPOSED, trimmed to what the prototypes proved plus the minimum to be usable]
- 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) plus door settings; named presets (`wall`, `door`, `secret door`, `locked door`, `terrain`, `one-way wall`) are one-drag defaults over them (5.8; supersedes Q6's `wall`|`door` only).
- GM tools: author walls, doors, terrain and one-way barriers in the browser (Q6, FIXED; presets plus an advanced toggle, 5.8, 7.4), create/move/delete tokens, toggle doors, edit token properties, manage players and player keys.
- Player: move owned tokens only; see only line-of-sight area, previously explored area (dimmed), and tokens inside LOS. Character creation and edits and all prop writes are GM-only in v1; opening them to players later is a permission change on the existing intents (6.1), not a redesign.
- Automatic LOS from owned tokens against walls/doors, server-side. Explored area = per-player cell grid, persisted.
- Persistence across restarts; reconnect resync; backups.
- Generic entity model (typed properties with visibility buckets) as the seam for FFF.
### Non-goals for v1 (later or never)
- RPG rules, dice, character sheets, initiative. FFF engine plug-in: seam only (section 9).
- Dynamic lighting, light sources, darkvision tiers, per-token vision radius beyond one numeric property. Windows that see only within a distance: v1 has see-through/pass-through switches and a one-way sight direction (5.8), but no distance rule (window semantics are #47; the see-over, impassable barrier is the `terrain` preset).
- Accounts, passwords, OAuth, multiple tables/campaigns per server, public hosting.
- Feeding from the owner's map generator [FIXED: does not feed in]. Map import is a CLI step in v1; browser upload is post-v1 (Q5, FIXED).
- Freehand drawing, rulers, pings, chat, audio, video (order decided at M7, Q8).
- Mobile-first UI polish (the client must work on a phone [MEASURED render], but layout is not a v1 goal). Devices in scope: phones, tablets, laptops (Q1, FIXED).
- Network exposure and reachability: owner's concern (Q23, FIXED). Built-in protections stay (127.0.0.1 bind, connection cap, frame/rate limits, Origin check); internet-only hardening (fail2ban etc.) is not in scope.
- Horizontal scaling, multi-process server.
---
## 2. Architecture overview
### Fixed stack [FIXED]
- Client: TypeScript + PixiJS v8 + Vite; plain HTML/DOM overlay for UI (no UI framework). Agents use the official pixijs-skills (already in `.agents/skills/pixijs*`).
- Server: Nim 2.x; `mummy` pinned to tag `0.4.8` (commit `77a7563e`; `src/` identical to the former pin `01deb1ff694988635c7bf0f24f6088a0bdf6db5d`) [FIXED (owner decision), 2026-11-08; tags 0.4.6-0.4.8 exist]. `prototype-server-vision/servervision.nimble` still pins the commit until ported; `db_connector/db_sqlite`, WAL. No Nim in the browser.
- nginx (existing, HTTPS) in front: static client, reverse proxy for `/ws`, `/join`, `/tiles/`; internal location for tile bytes.
- Dev env: NixOS, devbox per project for toolchains, nothing global. Node 26 (devbox) runs the black-box test harnesses only; in-process tests stay Nim [FIXED, owner decision 2026-11-14, #9] (10.4). devbox also carries `sqlite` (output `out` + `bin`): `db_connector` dlopens `libsqlite3.so`, so the devbox env sets `LD_LIBRARY_PATH=$DEVBOX_PACKAGES_DIR/lib`.
### Component diagram
```
Browser (untrusted; players, GM) NixOS server
+-----------------------------+ HTTPS +--------------------------------------------+
| Vite bundle (TS + Pixi v8) | <-------------> | nginx (existing, TLS) |
| - renderer, fog, input | static, /ws, | / -> client/dist (store) |
| - DOM overlay UI | /tiles/,/join | /ws -> proxy, Upgrade |
| - reducer (protocol state) | | /join /tiles/ -> proxy to Nim |
+-----------------------------+ | /_tiles/ -> internal alias, bytes |
+-------------------+------------------------+
127.0.0.1 only | X-Accel-Redirect
+-------------------v------------------------+
| Nim server (mummy, 1 process) |
| TRUST BOUNDARY = egress module |
| ingress: parse -> authz -> validate |
| core: world state (walls, entities, |
| explored grids), vision, rules hook |
| egress: per-recipient view -> diff -> ws |
| persistence: SQLite WAL (state dir) |
+-------------------+------------------------+
|
state dir: state.db, tiles/ (immutable art)
```
### Data flow (one move)
1. Client sends intent `token.move` over WS.
2. Ingress: authenticate (connection already bound to a player at upgrade), parse, authorize (owns token), validate (shape, bounds, step cap, collision).
3. Core: apply to in-memory state, recompute vision for affected players, update explored grids.
4. Persist in one SQLite transaction (inside the lock, ack after commit).
5. Egress: for each connection build that recipient's view, diff against what that connection already knows, send only the diff.
6. Client reducer applies, renderer redraws what changed.
### Trust boundary
- Everything on the right of the browser is trusted; everything in the browser is not, including the GM's browser for anything the GM is not entitled to (the GM sees everything, so the GM client is trusted only for GM-authorized intents; it still gets validated).
- **Single egress rule [PROPOSED]:** all bytes to a player leave through one egress module that takes a recipient and a typed per-recipient view. Raw world state (walls, hidden entities, other players' explored grids) has no code path into that module. The prototype enforces this by discipline in `sync()` (`prototype-server-vision/src/server.nim`); the real build should enforce it by types (distinct `PlayerView` and `GmView` structures, no `JsonNode` of world state passed around).
- Client-side fog is cosmetic. Security never depends on the client hiding anything (section 7).
---
## 3. Security model and hidden-information rules
### 3.1 What each role receives [PROPOSED, extends the prototype's behaviour]
| Data | GM | Player (own) | Player (others) |
|---|---|---|---|
| Walls: geometry, switches, door settings and the derived `kind` label (5.8) | all, always | **never** (WS or HTTP) | never |
| Tokens/entities (position, radius, statuses without `source`, name per 8) | all | controlled by this player (`entity.owner`): always. Others: only if inside own LOS polygon **and** not `gm_only` | -- |
| Token props, `public` bucket | all | for visible tokens | -- |
| Token props, `owner` bucket (owner = token controller) | all | only for tokens this player controls | never |
| Token props, `gm` bucket | all | never | never |
| Character records (owner, names, character props) | all | own characters: always. Others: never; no browsable list of characters | never |
| Character props, `public` bucket | all | for characters with a visible token | -- |
| Character props, `owner` bucket (owner = character owner) | all | own characters only | never |
| Character props, `gm` bucket | all | never | never |
| Names (descriptive / actual, 8) | all actual | descriptive; actual for own characters and where revealed to this player | descriptive, or actual where revealed to that player |
| Encountered list (8) | all players' lists; GM may remove an entry | own list only | never |
| Vision polygons | none needed (GM sees all) | own tokens' polygons only | never |
| Explored grid | none | own grid only | never other players' |
| Map tiles | all | only tiles touching own explored cells (403 otherwise) | -- |
| Player roster | all (names, connected) | names of all players (Q9, FIXED) | names of all players (Q9, FIXED) |
| Player keys, sessions | GM only (keys re-showable, Q11 FIXED) | own session cookie only | never |
| Global activity counters (`gseq`) | yes | **no**: per-connection counter only | -- |
Notes:
- Prototype gap [INFERRED from code reading]: `Tok.gmOnly` is loaded from `scene.json` but never consulted in `sync()`; a GM-only token inside a player's LOS would be sent. Real build must enforce `gm_only` in the view builder and test it (new fault class, section 10).
- Prototype gap [INFERRED]: every message carries the global `gseq`; player-visible gaps in `gseq` reveal that hidden mutations occurred. Real build: players get a per-connection monotonic counter.
- `hello` to a player carries world size, tile size, explored cell size, scene default token and vision radius, art version, own player id and name. None of these is secret (owned token ids travel as `mine` on `token`, 6.1). It must not carry scene/entity counts or wall counts.
- A token's radius and statuses go to every recipient who sees the token [FIXED, owner decision 2026-11-10, #4]. Amended 2026-11-14: a status entry's `source` goes to the GM only; viewers see the status (e.g. `squeezed`), not its cause. The controlling owner gets no `source` either (the doc has no owner-view rule for statuses; revisit if wanted).
- [FIXED, #14] Names and lists: no code path sends an actual name, a reveal state, or another player's character or encountered entry to a player, unless the rules in 8 allow it. Players learn a character only through a token they saw or controlled, or through their own encountered list. A character owner change never changes token controllers.
### 3.2 Authentication: shared link, player keys, GM key
- **Shared site link [FIXED, #6].** One link for everyone: `https://host/`. Without a session it shows only the sign-in page, no data.
- **Player key [FIXED, #6].** Each player has a personal secret, the **player key**, generated by the GM (no name at creation). It identifies the player and grants access to their data. Format: 20 characters in groups of 4 with dashes, alphabet without look-alikes (no 0/O, 1/I/L), from the OS CSPRNG (~100 bits) [FIXED, owner accepted default, #6].
- **Sign-in [path FIXED (owner-delegated, 2026-11-14, #17): `POST /join` implemented in slice 2; behaviour FIXED].** The sign-in page POSTs the key to `/join` (HTTP; key in the body, never in the URL). Valid key: the server issues a fresh random session token cookie (`HttpOnly; Secure; SameSite=Strict; Path=/`), stores only its hash server-side, then redirects to `/`. Request and response: 6.6. Sessions never expire (Q10); one key works on many devices [FIXED, Q10].
- **First-sign-in name [FIXED, #6].** A player with no name is asked once for a display name (`player.setname`, 6.1). Names are unique among players. Renames: GM only (`player.rename`).
- **No rate limit on key entry [FIXED, owner, #6].** The ~100-bit key space makes guessing infeasible; no lockout, no `limit_req` on sign-in. Owner explicitly rejected guessing protection.
- **Replace a key [FIXED, #6].** GM can do this any time while the server runs: old key invalid, all that player's sessions revoked, live connections closed at once. Identity, characters and encountered list kept; no name re-prompt.
- **Remove a player [FIXED, #6].** Key invalid, sessions revoked, connections closed. Their characters and controlled tokens pass to the GM (character owner and token controller set to GM). Name leaves the roster; slot freed; their encountered list deleted.
- **Cap [FIXED, #6].** Max 6 players; unused keys count toward the cap.
- Keys are stored plaintext so the GM can re-show them [FIXED, Q11]. Key and session are separate: the cookie is never the key. Never log keys or session tokens (Nim or nginx).
- Session separate from key: the prototype's secret-as-cookie design is dropped (permanent bearer, sits in access logs and history).
- One cookie jar = one identity; same cookie in two tabs = same player, shared vision, both connections synced [MEASURED, prototype README].
- WS upgrade: authenticate by cookie **and** verify the `Origin` header equals the configured public origin, checked before the session and the upgrade [FIXED (owner-delegated, 2026-11-14, #17); mitigates cross-site WebSocket hijack, SameSite=Strict is the first line].
- **Rejected [FIXED, #6]:** per-person invite links; GM types the name at key creation; delete-and-reinvite only; deleting a player's characters with the player; a shared-link visit creating a player; a separate GM link path.
- **First GM login [FIXED, owner decision 2026-11-10, #5; amended #6].** Only the server CLI creates the GM: `fff-vtt gm-key` creates the single GM player (role `gm`, display name `GM`) if none exists, and prints the GM key. Re-running prints the same key; existing GM sessions are unaffected. `fff-vtt gm-key --new` rotates: new GM key, old one invalid, all GM sessions revoked. `--new` refuses while the running server holds its lock on the data dir; the read-only print works at any time. The GM's own key rotates only this way (no live replace). The GM signs in like a player: shared link, then GM key. Access control is filesystem permissions on the data files; no extra password. A visitor without a key never becomes GM (no first-visitor claim); they see only a "need a key" page. The GM may rename.
- Rejected: env/config seed (secret leaks via config, repo, backups); auto-print at startup (secrets in logs); first visitor claims GM (takeover); rotate on every lookup (logs out GM devices); live rotation while the server runs (needs an admin channel to the running server).
- **Key and session formats [FIXED (owner-delegated, 2026-11-14, #17)].** Player and GM keys are 20 symbols in 5 groups of 4 separated by dashes (24 characters shown), alphabet `ABCDEFGHJKMNPQRSTUVWXYZ23456789` (no `0/O`, `1/I/L`), drawn from the OS CSPRNG (`std/sysrand`, `getrandom`): ~99 bits. Comparison normalizes ASCII case, dashes and spaces and is length-independent (no early exit); at most 7 stored keys are compared. A session token is 32 CSPRNG bytes as lowercase hex (64 characters); only `sha256(token)` is stored. SHA-256 is a small in-repo implementation (`server/crypto.nim`, FIPS known-answer tested) because the pinned Nim stdlib has no SHA-2 and this adds no dependency. The cookie is `fff_session` (6.6).
- **`fff-vtt gm-key` wiring [FIXED (owner-delegated, 2026-11-14, #17)].** `fff-vtt gm-key [--new] [config flags]` opens (and migrates) the DB with the normal config keys, creates the GM (role `gm`, name `GM`) when absent, and prints one line `GM key: <key>`; re-runs print the same key. `--new` rotates, revokes all GM sessions, and prints `GM key (new): <key>`. The server holds an exclusive `fcntl(F_SETLK)` write lock on `<stateDir>/instance.lock` for its lifetime (also refusing a second server); `--new` tries the same lock and exits **3** without touching the DB while it is held. The read-only print takes no lock and works while the server runs. Other exit codes: 0 ok, 1 DB/state-dir error, 2 config error.
- **Application close codes at the mummy pin [FIXED, owner decision #18, 2026-11-15: option A, accept 1005 plus a reason message].** Mummy 0.4.8 exposes only `close(ws)`, which sends an empty close frame (a browser reports **1005**), so the app codes of 6.5 cannot ride the close frame; mummy is not forked or patched for this. The server therefore sends one final application message, `closing {reason, code}` (6.1), immediately before every server-initiated close, and then closes. A client reads the reason from that last message and 1005 from the close event; the numeric `code` keeps the 6.5 table's mapping (`revoked` 4001, `evicted` 4002, `proto-mismatch` 4003, `malformed-flood` 1008). Slice 2's revocation and eviction paths already send it. Consequence: a server-initiated close is always two steps (message, then close), and the message is the last app frame that connection ever sees.
### 3.3 Tiles
- Browser asks `GET /tiles/<scene>/v<art_version>/<x>_<y>.png` (Nim path). Nim parses strictly (digits only, length-bounded, range-checked against scene size; malformed or out-of-range -> `404`), checks the session's explored grid (the explored-area logic of 5.1), and answers `200` with `X-Accel-Redirect: /_tiles/<scene>/v<art_version>/<x>_<y>.png`, or `403` if unexplored [FIXED, owner decision 2026-11-14, #7]. nginx serves the bytes from an `internal` location; direct hits on `/_tiles/` give 404 [MEASURED: `prototype-server-vision/results/smoke.log`, README "Phase 2a"].
- GM is always allowed.
- Rule: a tile is allowed iff at least one explored cell of that player overlaps it [MEASURED semantics: leak test (d), 9984 + 7424 requests, 0 failures, `results/leak-A.log`, `results/leak-B.log`].
- **Residual tile-edge leak (accepted for v1, documented) [FIXED, Q4]:** a tile is the unit of disclosure. v1 sets `tile_size` = explored cell = 32 px (section 8), tile grid origin = world origin, so a tile is allowed iff its one cell is explored. The residual is the whole 32 px cell that a vision polygon grazed, including art the LOS did not actually see. Once revealed it is never revoked. No server-side masking is built [FIXED, Q4]. Static art only: door state is never in tiles. Consequences for map authors: do not paint secrets (secret doors, hidden traps, notes) in map art within ~32 px of areas players can reach; keep secrets as GM-only entities. Evidence: `prototype-tile-leak/README.md` (desktop numbers; phone run 2026-11-08). Fallback if the M4 gates fail: `tile_size` 64 px (per-scene config, no code change; leak <= 3 cells per allowed tile, 4x fewer files).
- A second consequence: map art itself may depict walls/doors. Art is "what players see once there", walls data is "what physics/vision uses". Authoring must keep them consistent; mismatch is GM error, not a leak.
- Tile URLs include the scene's `art_version` so that re-imported art does not hit stale caches [FIXED, owner decision 2026-11-14, #7]: from M3 on, always `1` in M3. The gate reads `<state>/tiles/<scene>/v<art_version>/` (layout fixed in M3; writing versions and cleanup are M6, 11.1). Response `Cache-Control: private` [FIXED, owner decision 2026-11-14, #7], not the prototype's `no-store`.
- **URL grammar and status split [FIXED (owner-delegated), 2026-11-15, #24].** Every numeric component is canonical decimal: digits only, no sign, no space, **no leading zero** (`0` alone is the only zero), bounded at 9 digits for `<scene>` and `<art_version>` (`v` + digits) and 5 digits per coordinate. One spelling per tile, so no cache or test sees an alias. `x in [0, ceil(w/tile_size))`, `y in [0, ceil(h/tile_size))`; the tile grid's origin is the world origin. A malformed component, a coordinate outside the grid, a scene id that is not the one v1 scene, and an art version that is not the scene's all answer **404** (the tile does not exist). The URL is parsed **before** the session is looked at, so an anonymous request gets the same 404 for a nonexistent tile. A missing session, an unknown session and an unexplored tile all answer **403** with the same empty body: the route never distinguishes "no identity" from "not yours", and never reads tile bytes. The GM is always allowed for an in-range tile. The gate reads the player's explored set under the global lock; a player with no sight state has explored nothing. `X-Accel-Redirect` is built only from the parsed integers (`/_tiles/<scene>/v<art_version>/<x>_<y>.png`), never from request text, so no path shape can steer it. `Cache-Control: private` is set by the Nim gate and rides through nginx's internal redirect unchanged; nginx adds nothing of its own there (the test vhost records this, 11.1). Nim sends no body and no `Content-Type`.
### 3.4 Threat list
| # | Threat | Mitigation | Test |
|---|---|---|---|
| T1 | Player reads hidden token/entity/prop from WS | view builder filters by LOS, `gm_only`, bucket; single egress | leak test + fault classes |
| T2 | Player reads wall/door data | walls only in GM view | fault `walls` [MEASURED caught] |
| T3 | Player reads other player's vision/explored/ownership | per-player view only | faults `other-*` [MEASURED caught] |
| T4 | Player fetches unexplored tiles | Nim gate + internal nginx location | leak (d) against the independent oracle, smoke steal check, direct `/_tiles/` -> 404 (M3 test nginx) |
| T5 | Tile-edge over-disclosure: one 32 px cell grazed by vision, never revoked | tile_size = explored cell = 32 px, no server masking, authoring rule ~32 px (Q4 FIXED) | documented, not testable as a leak; M4 timing gates (13) |
| T6 | Player key / session theft via logs, referrer, history | key in POST body, never in URL; session != key (hash stored); log redaction; no-referrer on sign-in; HTTPS only | config test (grep logs for secret) [new] |
| T7 | Cross-site WS hijack | Origin check + SameSite=Strict | new test |
| T8 | **Wall-probing oracle via move validation** [INFERRED, not in prototype tests]: `moveBlocked` answers `ok:false` for any chosen segment, with unlimited length; binary searching lets a player map walls beyond LOS and tell open from closed doors | cap step length per intent (= token's effective vision radius, scene default if no vision; 5.5, Q18 FIXED), rate limit intents per connection (6.4), uniform nack that carries only the old position (5.5) | M2 in-process probing test (5.5, 13); WS version in M3 (10.3): count wall/door facts recoverable from nacks beyond LOS |
| T9 | Info via error replies (`not yours` echoing a position) | refusals are static codes, never state (6.5); a move of a non-controlled or unknown token gives `ack {ok:false, code:"not-allowed"}` without position, one code for both [MEASURED rule, README Findings] | leak test (e) |
| T10 | Message-size or rate DoS, slow client memory growth | max frame size (6.4), per-connection rate limit (6.4), connection cap (4.3); **bounded per-connection outbox** (byte/message caps, state coalescing), lagging clients stopped and resynced (4.3, Q13); mummy queue is unbounded [MEASURED finding, README mummy caveats] | new tests (10.3 slow client, protocol) |
| T11 | Timing/size side channels (message bytes reveal hidden activity) | accepted; only deliver messages when state visible to that recipient changes | not tested |
| T12 | Path tricks on static/tile routes | strict parsing; webby rejected `%2f`/`%00` [MEASURED, NOTES Phase 2a] | smoke |
| T13 | Player-controlled strings (token names, props) as XSS in DOM overlay | render with `textContent`, never `innerHTML`; CSP | new test |
| T14 | Boundary ambiguity: token exactly on vision edge | documented epsilon; tests use 0.5 px tolerance [MEASURED] | leak test |
| T15 | Backend reachable bypassing nginx (prototype nginx binds 0.0.0.0, `HANDOFF.md`) | Nim binds 127.0.0.1 only [MEASURED: prototype does], systemd `IPAddressAllow`, TLS at nginx | deploy check |
| T16 | Name leak: actual name or reveal state of an unrevealed character/token, another player's character or encountered entry, or a browsable character list reaches a player | names and lists built per recipient at egress (8); no list-all message; encountered list is per player | fault classes `ACTUAL_NAME`, `CHAR_LIST` (10.3) |
---
## 4. Server
### 4.1 State model
Single process, in-memory authoritative state, SQLite as write-through persistence (loaded at start, never queried at runtime for reads).
- **World**: scenes; per scene: dimensions, tile config, grid, walls (per-scene stable id, never reused; see 8), entities (tokens). Characters, name reveals and encountered lists (8) are world state too: `characters: seq[CharacterRec]`, `reveals: (player, subject) -> one row each` and `encountered: player -> token -> snapshot`, all loaded at startup (slice 8 / #23, `server/characters.nim`).
- **Players**: id, name, role (`gm`|`player`), colour; a player is a real person, not a character. Controlled tokens derive from `entity.owner` (token controller); owned characters from `character.owner`.
- **Per-player runtime** (`Role` in prototype, renamed `PlayerState`): current vision polygons (one per owned entity with `vision` enabled), `ver` counter bumped on change, explored set, `fresh` cells added by the current mutation.
- **Per-connection runtime**: `known` table (entity id -> last sent view), last-sent vision `ver`, per-connection counter, player id, role.
- Prototype used fixed roles `gm`/`A`/`B`; real build uses player ids. Multiple connections per player are allowed and share the player's vision/explored (as prototype).
- Monsters/NPCs have no vision [MEASURED design: `vision_ms move-monster` 0.000 ms]; only player-owned entities with `vision` produce polygons.
### 4.2 Mutation pipeline
`intent -> validate -> apply -> per-player visibility -> diff -> persist -> ack -> send`
Under the single global lock (as prototype, order proven correct by 3 x 60 s runs):
1. **Parse** with strict type checks (prototype pattern: kind checks per field). Unknown `t` -> `ack unknown-type` (`error malformed` if the envelope is unreadable; 6.5).
2. **Authorize**: role/ownership.
3. **Validate**: bounds, step cap (T8), collision (player moves: 5.5; GM moves skip walls and step cap), referential integrity, property schema.
4. **Apply** to memory.
5. **Recompute** vision only for players whose input changed (mover's owner; all players for door/wall changes). Update explored; collect `fresh`.
6. **Persist**: `BEGIN; ...; COMMIT` including dirty explored chunks.
7. **Ack** to sender, then **egress**: for each connection compute the recipient view and enqueue it in that connection's bounded outbox (4.3; state keys coalesced). The diff against `known` happens at flush time; only changed items (`token`/`token_gone`/`vision`/`explored`/`wall`/...) get bytes.
8. Clear `fresh`.
Invariants (carry from prototype):
- Enqueue order per connection == mutation order: messages are appended to the connection's outbox **while holding the lock**; network sends happen **outside** the lock, at flush. Non-state messages are FIFO. State messages are coalesced per key (latest wins, 4.3), so their position relative to other messages is flush order, not mutation order.
- Ack after COMMIT (a client never sees a state that a crash can undo, except under `synchronous=NORMAL` power loss, 4.4).
- A failed validation mutates nothing, bumps nothing, persists nothing.
- Refusals never echo state: only a refused move of a controlled token acks with its old position (uniform nack, 5.5); every other refusal is an `ack` with a static `code` and no position (6.5). Each intent gets exactly one `ack` (6).
Known limitation of the prototype, fixed in M2 [FIXED, accepted default; 5.5]: it checks only the centre path a->b and the destination circle, not the swept circle (corner clipping possible, `HANDOFF.md`). M2 adds the capsule (swept-circle) check and the step cap.
Second limitation [INFERRED]: a fast drag sampled at ~50 ms can produce a straight segment that cuts a corner the pointer path did not, causing a nack and a snap-back. Mitigation: client sends intermediate points when the step would exceed the cap (token's effective vision radius, 5.5, Q18); server clamps nothing silently (clamping would leak the hit distance, T8).
### 4.3 Locking and threading
- mummy: `WebSocket.send` appends the encoded frame to one server-wide deque under `sendQueueLock` and wakes the IO thread; worker threads handle events; per-socket events are serialized [MEASURED reading, `prototype-server-vision/README.md` "mummy suitability", mummy.nim ~L262-311].
- **One global lock** around intent handling and outbox enqueue; network sends happen outside it (flush, see 4.2). [MEASURED] 13748 mutations / ~36k messages in 60 s with 3 clients (~223 intents/s): no crash, no reorder, no loss, consistent final views (`results/concurrency-final{1,2,3}.log`); intent->ack avg 1.40 ms, p99 4.58 ms, worst 20.31 ms.
- Decision [PROPOSED]: keep the global lock in v1. A table of <= ~10 clients is 2 orders of magnitude below the single-core limit (server total per mutation avg 0.70 ms [MEASURED]). Revisit only if a measured p99 > 50 ms appears in production logs.
- 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).
- **Dead or stuck peers**: closed by nginx proxy timeouts [PROPOSED mechanism; verify in M5 that `/ws` goes through nginx and which directive fires, `send_timeout` is the candidate]. `close(ws)` cannot force-close at this pin (it queues behind the backlog).
- Connection limits [FIXED (owner-delegated, 2026-11-14, #15)]: 4 connections per player (a 5th closes that player's oldest); 16 total (1 GM + 6 players x ~2 devices + headroom); the 17th is refused. Replaces the PROPOSED cap of 8. Enforced in `websocketHandler` (mummy's inbound queue is unbounded). Frame and intent limits: 6.4.
- Forking mummy (per-socket depth, forced close) is fallback only, not planned.
- `WebSocket` **does** have generic field-wise `==` and `hash` at the pin (fields `server`, `clientSocket`, `clientId`; Nim 2.2 stdlib) [MEASURED reading, `docs/research/q13-mummy-slow-clients.md`, Corrections]. The earlier "no `==`/hash, keyed by raw bytes" note is stale. Prototype keys connections by the raw bytes of the ref (`key(ws)`), flagged as shortcut. Real build: assign an app `connId` at upgrade and key the outbox table by `connId`, not by `WebSocket` [PROPOSED, per Q13 research]; add a test that fails if mummy's `WebSocket` fields change (the pin makes this stable, the test makes it explicit) [PROPOSED].
- Handler discipline: no blocking I/O under the lock except the one SQLite COMMIT; no logging formatting of large structures under the lock; metrics are O(1) updates (section 11).
- **Borrow, do not copy, under the lock** (#28): the egress reads the live tables through `views.Context`, six pointers into the `App`, because a per-mutation copy of `visions` costs a whole explored `HashSet` per player (~4.9 ms at 262144 cells on the review build, measured). Nothing that egress holds may outlive the lock hold.
- **The scene is a value swapped, never mutated, under the lock** (#31): every reader takes one snapshot under `dbLock` and uses it for the whole request — `tileGate` (parse, explored check and `X-Accel-Redirect` from one record), `checkScene` (the id), the wall/door handlers (the post-lock log and effect frame). A handler that reads `app.scene` twice can see two records; one that reads it outside the lock races the assignment and ORC's free of the old `walls`.
- SQLite tail: server worst ~20 ms is the COMMIT (WAL autocheckpoint / OS scheduling [INFERRED]) and every other mutation queues behind it as `lock_wait` (`results/spike/investigation.md`). Accepted for v1. Moving persist out of the lock breaks ack-after-commit and order; not done.
- 583 ms intent->ack outlier: **not reproduced**, cause undetermined (host stall or node harness pause; not proven either way, `results/spike/investigation.md`). Production logging (section 11) must make a recurrence diagnosable (SLOW lines with breakdown).
### 4.4 Persistence
Engine: SQLite via `db_connector/db_sqlite`, `journal_mode=WAL`, one connection used under the global lock. Also `busy_timeout=5000` and `foreign_keys=ON` at open [FIXED (owner-delegated, 2026-11-14, #16)].
**synchronous choice [FIXED, Q12]: `NORMAL`; `FULL` around GM authoring transactions.**
- [MEASURED] avg commit 0.60 -> 0.17 ms, server total avg 1.16 -> 0.74 ms; tail unchanged (~20 ms worst) (`results/spike/investigation.md`).
- Process kill (SIGKILL) loses nothing [MEASURED: `results/final-restart.log`, SIGTERM and SIGKILL, same DB, identical state].
- OS crash/power loss can drop the last few commits; never corrupts. For a VTT (positions, explored cells) that is acceptable; GM-authored content (walls, scenes) is the expensive loss, so GM authoring transactions run with `synchronous=FULL` [FIXED, Q12].
- Acceptance of ack-before-durable on power loss is stated, not hidden.
Schema sketch (columns indicative, not final DDL):
```
meta(k PRIMARY KEY, v) -- schema_version also via PRAGMA user_version
player(id PK, name NULL, role, colour, created_at) -- name NULL until first sign-in; unique among players [FIXED, #6]
player_key(player_id PK FK, secret, created_at) -- indicative; one current key per player; secret plaintext (Q11); replace overwrites [FIXED, #6]
session(id PK, player_id FK, token_hash, created_at, last_seen) -- never expires (Q10)
scene(id PK, name, w, h, tile_size, cell, grid_size, vision_radius_default, token_radius_default,
art_version, active, next_wall_id, extra_json) -- next_wall_id: monotonic, §8 [FIXED, #3]; token_radius_default [FIXED, #4]
wall(scene_id FK, id, ax, ay, bx, by, kind, open, flags, PRIMARY KEY(scene_id, id)) -- behaviour = switches (5.8); `kind` is a derived label, never the authority; columns vs a validated object are #49's
character(id PK, owner_player_id FK NOT NULL, descriptive_name, actual_name, reveal_all BOOL,
props_public JSON, props_owner JSON, props_gm JSON) -- NOT NULL: exactly one owner; GM owns via the GM's player id [FIXED, #14]
entity(id TEXT PK, scene_id FK, kind, character_id FK NULL, descriptive_name NULL, actual_name NULL, reveal_all BOOL,
x, y, radius REAL NULL, owner_player_id NULL, -- token controller; NULL = GM-controlled; never copied from the character [FIXED, #14]
gm_only, flags, props_public JSON, props_owner JSON, props_gm JSON) -- names NULL when character_id is set
name_reveal(player_id FK, subject_id, PRIMARY KEY(player_id, subject_id)) -- subject = character or plain token id; per player [FIXED, #14]
encountered(player_id FK, entity_id, character_id NULL, descriptive_name, actual_name NULL,
PRIMARY KEY(player_id, entity_id)) -- snapshot, no FK cascade: survives token/character delete; never auto-removed [PROPOSED]
entity_status(entity_id FK, status, source, PRIMARY KEY(entity_id, status, source)) -- status: stuck|squeezed; source: walls|GM [FIXED, #4]
explored_chunk(player_id, scene_id, cx, cy, bits BLOB, PRIMARY KEY(player_id, scene_id, cx, cy))
```
- Exactly one scene in v1 (Q3): `scene_id` keys stay in the schema.
- Prototype stores one row per explored cell (`exp(role, c)`, one INSERT per new cell, `HANDOFF.md`); the real build stores **chunked bitmaps** [FIXED (owner-delegated, 2026-11-15, #21)]: a chunk is 64x64 cells = 512 B, upserted per mutation and only when the mutation dirtied it. Sizes: 4096 px map / 32 px cell = 16 384 cells = 2 KB (2x2 chunks); 16384 px map = 262 144 cells = 32 KB (8x8 chunks). Measured cost of one mutation-scale write (BEGIN; 512 B upsert; COMMIT): avg 0.015 ms, p99 0.035 ms (4.3's accepted commit tail is ~20 ms), and a real move's ack stays at avg 0.7 ms / p99 1-2 ms with explored writes on (`tests/texplored.nim`, `tools/persistence.test.mjs`).
- Entity move = one UPSERT of x,y (prototype: `INSERT OR REPLACE INTO tok`).
- Migrations: `PRAGMA user_version` + forward-only migration list; startup refuses to run on a newer DB [PROPOSED]. Detail [FIXED (owner-delegated, 2026-11-14, #16)]: `schema_migration(version INTEGER PRIMARY KEY, name TEXT NOT NULL, applied_at TEXT NOT NULL)` is the history; `user_version` carries the same latest version, and startup refuses when the two disagree or the history is not contiguous from 1. One transaction per step (DDL + history row + `user_version`); a failing step rolls back completely, and an up-to-date DB is not written at all (re-open is a no-op). Step 1 (M3 slice 1) creates `meta(k TEXT PRIMARY KEY, v TEXT NOT NULL)`. Step 2 (M3 slice 2, `auth`) creates `player(id, name TEXT UNIQUE NULL until first sign-in, role 'gm'|'player', colour, created_at)`, a partial unique index `player_single_gm` on `role='gm'`, `player_key(player_id PK FK ON DELETE CASCADE, secret TEXT plaintext, created_at)`, and `session(id, player_id FK ON DELETE CASCADE, token_hash TEXT UNIQUE, created_at, last_seen)` plus `session_player`; removing a player therefore removes its key and sessions. `session.last_seen` exists but is not updated in M3 (sessions never expire, Q10). A step may hold several statements; the runner executes them in order inside the step's transaction (db_connector prepares one statement per call).
- Step 3 (M3 slice 4, `world`) [FIXED (owner-delegated, 2026-11-15, #19)]: creates `scene` and `wall` and seeds the single v1 scene. `scene(id PK, name, w REAL, h REAL, tile_size INT, cell INT, grid_size REAL, vision_radius_default REAL, token_radius_default REAL, art_version INT, active INT, next_wall_id INT, extra TEXT)`; the seeded row is `id 1, name 'Scene', 4096x4096, tile_size 32, cell 32, grid_size 0 (no grid), vision_radius_default 400, token_radius_default 20, art_version 1, active 1, next_wall_id 1, extra '{}'` (the prototype's world and radii, Q4's 32 px cell). `wall(scene_id FK ON DELETE CASCADE, id, ax, ay, bx, by REAL, kind TEXT CHECK (kind IN ('wall','door')), open INT CHECK (open IN (0,1)), flags TEXT JSON DEFAULT '{}', PRIMARY KEY (scene_id, id))`. Two consequences: (a) M3 has a scene without waiting for the M6 import CLI, so `wall.*` and `door.set` work in slice 4; `w, h, tile_size, cell, art_version` stay off the wire (6.1 `scene.set`). (b) The scene row carries `next_wall_id`, so wall ids survive restarts, removals and re-imports of the same scene (#3). Seeding in the migration rather than at startup keeps the scene identical on every start and lets the migration test assert it (10.3).
- Step 4 (M3 slice 5, `tokens`) [FIXED (owner-delegated, 2026-11-15, #20)]: creates `entity`, the map figures (`id TEXT PK`, `scene_id FK ON DELETE CASCADE`, `kind`, `descriptive_name`, `actual_name`, `x`, `y`, `radius REAL NULL`, `owner_player_id INTEGER REFERENCES player(id) ON DELETE SET NULL`, `gm_only`, `vision_radius REAL NULL`, `flags TEXT` default `'{}'`, `created_at`). `owner_player_id` NULL is GM-controlled, so `player.remove` hands that player's tokens to the GM through the FK alone (3.2) and memory (`0` = GM-controlled) mirrors it. `radius`, the three property buckets, `character_id` and `reveal_all` are NOT columns yet: slices 7 (#22, `token.resize` and props) and 8 (#23, characters and names) own them, and `entity_status` / `explored_chunk` arrive with slice 7 and slice 6. Ids are 12 random characters, so no counter column is needed (8).
- Step 5 (M3 slice 6, `explored`) [FIXED (owner-delegated, 2026-11-15, #21)]: creates `explored_chunk(player_id INTEGER NOT NULL REFERENCES player(id) ON DELETE CASCADE, scene_id INTEGER NOT NULL REFERENCES scene(id) ON DELETE CASCADE, cx INTEGER NOT NULL, cy INTEGER NOT NULL, bits BLOB NOT NULL CHECK (length(bits) = 512), PRIMARY KEY (player_id, scene_id, cx, cy))`. `(cx, cy)` are **chunk** coordinates (`cell div 64`), not cell coordinates; `bits` is a 512-byte bitmap of 64x64 cells, row-major inside the chunk, least-significant bit first (cell `(cx, cy)` is bit `(cy mod 64) * 64 + (cx mod 64)`, byte `bit div 8`, mask `1 shl (bit mod 8)`). Cells outside the scene stay 0, so a map whose cell count is not a multiple of 64 needs no special case; the v1 scene is 128x128 cells = 2x2 chunks, a 16384 px map 8x8. Both FKs cascade, so `player.remove` and a scene delete take the explored rows with them. The layout is pinned by `tests/texplored.nim` (exact byte/bit positions) and re-read independently by `tools/persistence.test.mjs`, so a refactor cannot silently swap axes or bit order.
- Step 6 (M3 slice 7, `token details`) [FIXED (owner-delegated, 2026-11-15, #22)]: adds `entity.props_public`, `props_owner`, `props_gm` (`TEXT NOT NULL DEFAULT '{}'`: one JSON object per visibility bucket) and creates `entity_status(entity_id TEXT REFERENCES entity(id) ON DELETE CASCADE, status TEXT CHECK (status IN ('stuck','squeezed')), source TEXT CHECK (source IN ('walls','GM')), PRIMARY KEY (entity_id, status, source))` - the `(status, source)` set of 5.5. `radius` was already a column from step 4; step 6 is what makes the buckets and the statuses persistent. A token's status rows are rewritten with its row (one transaction), so a status change and the `token` frame that reports it can never disagree after a crash; a wall-derived status change (no row write) rewrites them in the mutation's `NORMAL` transaction. Both FKs cascade, so removing a token removes its entries.
- Step 5 write policy [FIXED (owner-delegated), #21]: a mutation persists **only the chunks its refresh dirtied**, and each of those is encoded from the **whole** explored set (a bitmap is a value, not a delta; writing just the new cells would erase the rest). Durability is `NORMAL` (Q12): explored is derived and monotone, unlike GM-authored content. A `token.move` writes the position and its chunks in **one** transaction (both NORMAL); a GM authoring write (`wall.*`, `door.set`, `token.create`/`update`/`remove`) keeps its own `FULL` row transaction and writes the chunks in a second `NORMAL` transaction, both inside the global lock and before the ack, so no ack precedes the cells it reports and no lock hold grows beyond one extra 512 B upsert. Those two commits are not atomic with each other; a crash between them loses explored cells the client was never told about, and the next refresh re-adds any the token can still see (explored never un-explores).
- Step 7 (M3 slice 8, `characters`) [FIXED (owner-delegated, 2026-11-15, #23)]: creates `character(id TEXT PK, owner_player_id INTEGER NOT NULL REFERENCES player(id), descriptive_name, actual_name, reveal_all INTEGER, props_public/owner/gm TEXT '{}', created_at)`, `name_reveal(player_id FK ON DELETE CASCADE, subject_id TEXT, created_at, PRIMARY KEY (player_id, subject_id))` and `encountered(player_id FK ON DELETE CASCADE, entity_id TEXT, character_id TEXT NULL, descriptive_name TEXT NOT NULL, actual_name TEXT NULL, created_at TEXT, PRIMARY KEY (player_id, entity_id))` plus an index on `characters(owner_player_id)` and `encountered(character_id)`; and adds `entity.character_id TEXT REFERENCES character(id)` and `entity.reveal_all INTEGER NOT NULL DEFAULT 0`. Decisions the sketch in 8 left open, all recorded here:
- **One id namespace.** A character id comes from the same 12-character alphabet and the same collision check as a token id (`tokens.freshId` with *both* lists), so `name_reveal.subject_id` can hold either without an ambiguity column.
- **`character.owner_player_id` never dangles.** It is `NOT NULL` with no cascade; `player.remove` calls `characters.transferToGm` before the player DELETE, inside one transaction (3.2). A raw DELETE would raise instead of orphaning a record. `name_reveal` and `encountered` do cascade on the player, because 6.1 deletes that player's reveals and encountered list with them.
- **`encountered` has no FK to `entity` or `character`.** Entries survive token removal, character removal and a `gm_only` flip (8), and only `encountered.remove` deletes one. `character_id` is stored so a rename and a `reveal_all` can follow the snapshots of everyone who met the character; `actual_name NULL` means "this player was never told it" (the writer stores `''`, db_connector cannot bind NULL).
- **`entity.character_id` is nullable and written as a SQL literal**, because db_connector quotes every bound argument as text and cannot send NULL; the value is always an id from the checked alphabet (`tokens.sqlLitId` raises otherwise). The FK is what makes a dangling link impossible, and `character.remove` pre-checks `in-use` so the FK never fires.
- **`entity.descriptive_name`/`actual_name` stay `NOT NULL`**: a token linked to a character stores `''` in both and its names come from the character record (8). Validation refuses a linked token that carries names and a plain token that lacks them, in both directions (6.1).
- Startup: load everything into memory, recompute vision for all players (prototype does, in one transaction) so `vision` is never stale vs walls. Slice 5 loads the scene and its tokens; a player's sight state (`PlayerVision`) is created on that player's first connection and recomputed from the current walls, so nothing is stale after a restart. Slice 6 (#21) restores every stored `explored_chunk` row into that player's set before the first connection (`explored.restore`), so a reloaded grid is the grid the player had; polygons are never stored (they are recomputed, 8).
- Shutdown: install a SIGTERM handler [prototype has only SIGINT, `HANDOFF.md`]: stop accepting, close sockets, final `wal_checkpoint(TRUNCATE)`, exit. Durability does not depend on it (WAL commit before ack).
---
## 5. Vision and explored
### 5.1 Algorithm (ported from `prototype-server-vision/src/geometry.nim`)
- **Visibility polygon** from token centre: cast rays to every blocking wall endpoint at angle -eps, 0, +eps (`RayEps` = 1e-4 rad), plus an inscribed 64-gon of radius R as range limit; sort by angle; each ray returns nearest hit among wall segments + circle segments; result = CCW polygon. The wall list holds only walls whose sight switch is on; an open door and a `terrain` wall are absent from it, and a one-way wall is evaluated per observer (5.8).
- **Explored**: `cellsTouched(poly, cell)` marks every grid cell that the polygon overlaps; union into the player's explored set. Vertex-in-cell test added after a bug (polygon wholly inside one cell) [MEASURED bug log, prototype `NOTES.md`; covered by `tests/tgeometry.nim`, suite "cells", test "tiny polygon inside one cell"].
- **Token visibility** to a player: token centre inside any of the player's polygons (even-odd `inside`).
- **Move validation (prototype)**: inclusive segment intersection on blocking walls (touching = blocked, so no squeezing through shared vertices) AND destination circle at distance >= token radius from every blocking wall. Replaced by the M2 rules in 5.5; the prototype result is a baseline only.
### 5.2 Edge cases handled and tested [MEASURED, `tests/tgeometry.nim`; M1 port baseline (history): 33 test blocks / 98 checks, none dropped; current count: 92 `[OK]` test cases in `results/nimble-test.log` (M2, 2026-11-08)]
- Collinear rays skipped (neighbouring +-eps rays cover them).
- Token standing on an endpoint: that endpoint skipped, hits at t <= 1e-9 ignored.
- T-junction, shared vertex, free-standing wall, '<' apex, box corner, behind-viewer fan, long thin corridor.
- Angle-sort bug: circle angles must use the same (-pi, pi] range as wall angles (`atan2(sin,cos)`), otherwise bow-tie polygon (position dependent) [MEASURED bug, prototype `NOTES.md` "Post-phase-3"]. Regression test: `tests/tgeometry.nim`, suite "visibility", test "wall endpoints behind the viewer: fan stays angularly ordered".
- Vision circle is an inscribed 64-gon: error <= ~0.12% of R [MEASURED, prototype `NOTES.md`].
### 5.3 Performance [MEASURED; single laptop, release build, loopback, power-save CPU; `results/bench.log`, `results/concurrency-final1-server.log`]
| 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 |
Conclusions:
- `cellsTouched` is ~12x the polygon itself and dominates [MEASURED]. M2 target: replace per-cell polygon tests with scanline rasterization of the polygon over the explored grid, differential-tested against the ported implementation [PROPOSED].
- Polygon cost is O(rays x walls in bbox) [MEASURED code reading, `server/geometry.nim` `visibilityPolygon` (ported unchanged from prototype)]. Prototype scene has 60 walls and 8 tokens, so this says nothing about big maps. With radius-bbox culling the cost scales with local wall density, not total walls [INFERRED]; a uniform spatial grid over walls is needed when scenes reach thousands of walls (M2 gate: bench with a synthetic 5k-wall scene, target polygon < 1 ms [PROPOSED test target, Q2: owner has no map size yet; revisit with real maps]). The 5k target is the sparse primary layout `genScene(16384, 5000, 1)` (`tools/scenegen.nim`): 0.082 ms avg [MEASURED, `results/bench.log`]. The dense layout `genScene(4096, 5000, 1)` is a stress reference (1.28 ms avg, ~207 walls in the vision bbox) [MEASURED]; revisit the uniform grid if real maps approach that density.
- Skip recompute when the token moved but its polygon is unchanged (prototype already compares `np == r.polys`).
### 5.4 Known limitations (carry forward)
- Token exactly on a wall cannot move off it: `moveBlocked` counts any touch as a hit, so every move from that point is blocked, even a perpendicular step to the open side [MEASURED limit, `tests/tgeometry.nim` test "KNOWN LIMITATION: token exactly on a wall cannot move off it"; also in the `server/geometry.nim` header]. Known limitation, not a policy. Fixed in M2 by the escape rule (5.5). The escape is required by Q14 so the GM can move such a token: mechanism [PROPOSED], requirement [FIXED]. A validated move cannot reach this state (a destination within r of a wall is rejected) [INFERRED from `moveBlocked`]; it arises from a wall/door edit (`stuck` trigger, 5.5) or from a GM placement on a wall (GM placements ignore walls, 5.5); the escape rule covers both.
- Closing a door on a token [FIXED, owner 2026-11-08, supersedes the earlier `blocked` decision for doors; 2026-11-10 #4: failure is `squeezed`]: the token is pushed aside (5.5), `squeezed` only if neither side is valid. Editing or adding a wall on a token [FIXED, Q14]: the token gets `stuck` (trigger narrowed to circle overlap, 5.5). The server refuses that token's player moves; the GM can still move it; status clears per the 5.5 Keep/Clear rules (wall removed or door opened and no other wall overlaps, GM move to a free spot, or GM clear). Current pin: `tests/tgeometry.nim`, suite "door/wall closing on a token", test "door closed on a token: Q14 undecided, DESIGN 5.4 vs 12 H2 conflict": a token whose centre is 10 px off a closed door may move to a clear spot, may not stay overlapped, and may not cross the door. It pins `moveBlocked` only; it is replaced in M2 by tests of the 5.5 policy (under the 5.5 trigger this token is `stuck`, so player moves are refused).
- Boundary epsilon ambiguity (RayEps 1e-4, inclusive tolerances).
- Explored and tile checks in the leak test recompute with the server's own `cellsTouched`: self-consistency only (caveat in 10.2). New independent oracle in section 10.
- Doors/walls changing does not un-explore anything; explored only grows [MEASURED behaviour].
- Single uniform vision radius in prototype; v1 uses a per-entity numeric property (`vision_radius`) with scene default; no light/darkvision [FIXED, Q7].
- Vision origin = token centre, radius is not clipped by the token's own size.
### 5.5 Move rules and statuses (M2 decisions, 2026-11-08; status model 2026-11-10, #4)
Normative for M2. Replaces the prototype move validation (5.1) and the move-related limitations in 4.2 and 5.4. Implemented as a pure in-process module with unit tests; the WebSocket layer only maps its result to `ack` (6.1). The WebSocket probing test is M3.
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 segment `W`. "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).
- 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.
- Set (source `walls`): a wall is added or updated -> every token overlapping that wall gets `stuck`. (A door CLOSING on a token does not set it: push rule below.) The GM places or moves a token to a position overlapping any blocking wall -> `stuck`.
- Keep: while any blocking wall still overlaps the token, its `walls`-sourced entries stay (opening a door does not free it if another wall overlaps).
- Clear: a wall is removed or a door opened -> each token that overlapped that wall keeps its `walls`-sourced entries only if it still overlaps a remaining blocking wall; otherwise they clear. A shrink (5.6) that ends the overlap clears them likewise. The GM moves the token to a position overlapping no blocking wall -> `walls`-sourced entries cleared. `GM`-sourced entries clear only by GM action (any single `(status, source)` entry; wire intent `status.clear`, 6.1).
- **Door closing on a token = push aside, not stuck** [FIXED, owner, 2026-11-08; changes the door case only]: each token (player or GM-owned) with `dist(c, door) < r` is moved perpendicular to the door segment, to the side its centre is already on, by the minimal distance that ends `>= r` from the door (+ `PushEps` = 1e-6 px; past the door's end the offset is `sqrt(r^2 - e^2)`, `e` = along-axis overshoot). Centre exactly on the door line: side of the token's previous position (position before its most recent move or push; `prev`/`hasPrev` on the token); no history, or previous also on the line: left of the door's a->b direction (deterministic default). The pushed position must be in bounds and `>= r` from every blocking wall (the closed door included); else the opposite side is tried; if neither is valid the token stays and gets `squeezed` (source `walls`), and opening that door later clears it per the Clear rule. A pushed token is clear of walls, so its `walls`-sourced entries clear. The push is a server-originated position change returned by the move-rules module (list of token index + new position) so M3 can broadcast it and recompute vision; no step cap applies. Each token is pushed independently; tokens do not block tokens (no token-token collision; the `blocks_move` flag is not modelled in M2), so pushed tokens may overlap each other. Wall add / wall update / GM placement or move inside a wall are unchanged (stuck). Door open is unchanged.
- An event changes only the tokens it touches (those overlapping the changed wall, or the moved token). An unrelated wall change elsewhere never re-sets a GM-cleared token.
- After the GM clears the `walls`-sourced entries while a wall still overlaps and no other entry remains, the player escape rule (step 3 below) applies unchanged: the token may step out without crossing, destination >= r from every blocking wall.
- `wall.update` = remove then add for this rule [PROPOSED; not in the owner's list].
- Player moves while locked (any entry): the uniform nack (unchanged).
**Player move `s -> d`** [FIXED, accepted default]. Checks in order; any failure gives the uniform nack.
1. Controller check (not controlled -> `ack{ok:false, code:"not-allowed"}`, no position; 6.5) and token not locked (no status entry).
2. Step cap [FIXED, owner]: `|d - s| <= cap`, where `cap` = the token's `vision_radius` if the token has `vision` and sets it, else the scene's `vision_radius_default`.
3. For each blocking wall `W`:
- if `dist(s, W) < r` (start overlaps `W`, escape case): allowed only if the path `s->d` does not cross `W` (crossing at parameter t > eps; collinear overlap counts as crossing) AND `dist(d, W) >= r`;
- otherwise (swept/capsule check): allowed only if `dist(segment s->d, W) >= r`, which also gives `dist(d, W) >= r`.
4. Accept: `ack{ok:true, pos:d}`. Nack: `ack{ok:false, pos:s}` for locked, over-cap and collision alike. No reason field, no `code`.
**GM move** [FIXED, owner (D)]: no wall check, no step cap, ignores locks. Bounds and referential checks still apply; after the move its `walls`-sourced entries are recomputed (set/clear rules above). A GM move out of bounds gets the same uniform nack as a player move (`ack{ok:false, pos:old}`) [RECORDED, as implemented].
**Wall index** [FIXED, accepted default, H3]: radius-bbox cull first; uniform spatial grid over walls only if the 5k-wall bench misses target (13, M2).
**Thresholds and tolerances** [FIXED, accepted default]: `eps` and any float tolerance are chosen by the implementer and documented in the module header. Oracle comparisons use 0.5 px, as the leak checker (T14).
**Regression baseline** [FIXED, accepted default]: "results equal old implementation" = `visibilityPolygon` and `cellsTouched` on the prototype leak transcripts plus `tests/fixtures/scene.json`. `moveBlocked` is excluded: its results change on purpose.
**Unconfirmed** [PROPOSED, owner to confirm]: (a) `wall.update` as remove + add. Former (b) (door opened while another wall overlaps clears `stuck`) is closed by the Keep rule above [FIXED, owner, 2026-11-08].
### 5.6 Token size and grow push [FIXED, owner decision 2026-11-10, #4]
- **Size:** `r` = entity `radius` if set, else scene `token_radius_default`. Units: px (map units). Client size presets (S/M/L, squares) are UI convenience only. Validation: `radius > 0`; no upper cap. Only the GM sets a radius; anyone who sees a token sees its radius.
- **Scene default change:** every token using the default is resized by the same rule, per token.
- **Shrink** never pushes. It can clear `walls`-sourced entries (5.5 Clear).
- **Grow push:** GM grows a token -> the server pushes it away from every blocking wall it overlaps, by a displacement that ends `>= r` from every blocking wall, stays in bounds, and does not enter any other wall. No step cap. Deterministic; the search and its tie-break are fixed and documented in the module header [FIXED (owner-delegated), #22]: a greedy relaxation, one wall per round in scene order, radial from that wall's closest point, at most 16 rounds, plus one flipped-side pass; a step whose centre path would cross a wall is refused, so the push never carries a token through a wall. Each token is pushed independently (tokens do not block tokens). The position change is server-originated: broadcast like the door push, vision recomputed for affected players.
- **Grow fails** (no valid position): the token stays (its graphic may overlap walls) and gets `squeezed` (source `walls`).
- Wire intents: `token.resize`, `status.set`, `status.clear` (6.1) [FIXED (owner-delegated, 2026-11-14, #11)].
### 5.7 Heights [FIXED (owner decision), 2026-11-15, #41]
What the vertical dimension is made of, and in what unit. Vision only: what a low wall does to sight is #44, thickness is #45, the wall kinds were #42 (5.8), the wire and migration are #49.
- **Unit: metres, decimal.** Map distances stay px and no map scale is introduced: see-over compares heights with heights, so no px -> m conversion exists anywhere [FIXED (owner decision), 2026-11-15, #41]. Research #39 3.3 needs only `h_eye` and `h_wall` for the hidden band behind a low wall (`d_floor = s * h_eye / (h_eye - h_wall)`), never a ground distance in metres.
- **Height is a property, not a field.** `height` and `eye_height` live in the `gm` bucket of the three-bucket `props` (8), on the character or on the token; there is no dedicated column and no wire field of their own.
- **Token height.** A character carries its base `height` (the character-sheet value). A plain token (no character) carries its own `height`, and `token.create` without one is refused `invalid` (`invalid`, not `not-found`: a missing field, 6.5). A linked token uses its character's `height` by default; it may carry its own `height` as a temporary on-map override (an enlarge spell doubling it) that never writes the character. Removing the override restores the character's value. **Effective token height** = the token's override, else the character's `height`, else the plain token's own `height`.
- **Eye height** follows the same pattern: `eye_height` on the character (base) with an optional token override. Effective eye height = the token override, else the character's `eye_height`, else, if nobody set one by hand anywhere, **93% of the effective token height**, following height changes live (an enlarge doubles the eyes too). A hand-set value is used as is and is never rescaled [93% FIXED (owner-delegated), 2026-11-15, #41].
- **Walls**: a wall is full height unless the GM gives it a height in metres; full height means nobody sees over it, a giant included. Existing walls (no height stored) keep behaving exactly as today [FIXED (owner decision), 2026-11-15, #41]. The field is GM-only like all wall data.
- **GM-only.** Both keys are in the `gm` bucket, so no player frame carries either: the `token` frame's `props` is `public` plus `owner` for the controller (6.1), and a player never reads the `gm` bucket. Players see only the outcome, their sight.
- **Limits** [FIXED (owner-delegated), 2026-11-15, #41]: every height > 0; `height` <= 100 m; `eye_height` <= 100 m and **may exceed** `height` (a floating eye); a wall's height > 0 and <= 100 m. The registered kind is enforced on write, so a non-number is `invalid` (8, 9).
- **First registered keys.** `height` and `eye_height` are the first two keys of the property-schema registry (8, 9): `kind` number, bucket `gm`. This is the first time the server interprets props, so the "the server never interprets props in v1" wording of 8 and 9 is narrowed to **the server interprets only registered keys used by core sight rules** (6.1, 8, 9).
- Deferred: whether the *target's* height matters for see-over (a giant's head over a fence) -> #44 "Low walls: sight and movement"; what height existing tokens and characters get at migration (`height` is required) -> #49 "Wall wire format, schema and migration".
- Conflict note (settled later): section 1's non-goals (windows/transparent walls, one-way walls) and Q6's `wall`|`door` only were contradicted by the wall-model work. That is 5.8 [FIXED, 2026-11-15, #42], which superseded both; this block fixed heights and units only, and what a low wall hides (#44) and thickness (#45) are still open.
### 5.8 Wall switches, presets, doors and one-way [FIXED (owner decision), 2026-11-15, #42]
What a wall's behaviour is made of. Heights are 5.7; what a low wall does to sight and movement is #44; thickness is #45; the wire and the migration are #49.
- **Behaviour is independent switches, not a kind [FIXED (owner decision), Q1].** A wall carries its own settings and the server reads those. A named kind is only a preset over them. Rejected: a fixed kind enum as the record's behaviour, and client-interpreted free flags; the client may send a preset name, and the **server** expands it and validates the resulting switch set (6.1).
- **v1 switches [FIXED (owner decision), Q2].** `blocks_sight: bool`, `blocks_movement: bool`; door settings `door: bool`, `open: bool`, `secret: bool`, `locked: bool`; one direction field `sight_dir: "both"|"left"|"right"` (default `both`). No light axis, no sound axis in v1 (and none on the map).
- **Direction is sight only [FIXED (owner decision), Q4].** `sight_dir` says sight is blocked from one side only; movement is always governed by `blocks_movement` and is two-way (a one-way wall blocks movement both ways). `left`/`right` are the sides of the wall's `a -> b` order read from `a` to `b`; `left` names the side whose view across the wall is blocked. Which side the editor offers first, and what a one-way wall does to explored cells and tiles, is #47.
- **Doors are walls with `door` set, and their settings are independent [FIXED (owner decision), Q3].** `open`, `secret` and `locked` exist only with `door` (`invalid` otherwise). `door.set` keeps working and keeps meaning "set `open`" (6.1); it is not replaced by a door-state enum, and secret/locked are not separate kinds.
- **Closed vs open.** The switches describe the *closed* wall. An open door blocks neither sight nor movement, both sides and direction included, and its stored switches are unchanged; closing restores them. This keeps today's rule (`blocks = not (door and open)`, 5.5) and makes opening a door the only way a door stops blocking.
- **A secret door is always closed.** `door.set open:true` on a secret door is `invalid`; the GM clears `secret` first (one click in the editor). `secret` with `sight_dir != both` is also `invalid`; `secret` with `locked` is allowed. Why: a secret door must be indistinguishable from a solid wall to every player (3.1), and an open or one-way secret door would show a gap or a sight seam.
- **Player-observability [FIXED (owner-delegated), #42].** `secret` and `locked` never reach a player in any form: wall data is GM-only (3.1), and the only player-visible effects of a wall are the vision polygon, the explored grid, tiles and token frames. Consequences: a closed secret door must give byte-identical player frames and identical refusals to a solid wall of the same switches; a locked door is just a closed door to sight and movement; no refusal names locked, secret, solid or any other cause (the uniform move nack, 5.5/6.5, already holds). The oracles that pin this are #46's.
- **v1 presets [FIXED (owner-delegated), #42].** A preset is a named switch set used by the editor's one-drag default (7.4) and as the GM's label; never storage.
| preset | `blocks_sight` | `blocks_movement` | door settings |
|---|---|---|---|
| wall (default) | yes | yes | none |
| door | yes | yes | `door`, closed |
| secret door | yes | yes | `door`, closed, `secret` |
| locked door | yes | yes | `door`, closed, `locked` |
| terrain | no | yes | none (railing, bushes, a low barrier: one preset) |
| one-way wall | yes, one side | yes | none |
No `window` preset in v1. The switch set *can* express the see-through door of Fantasy Grounds and Roll20 (a door with `blocks_sight:false`, `blocks_movement:true`: look through it while closed, open it to pass), but "window" also names Foundry's distance-limited wall, which two booleans cannot express, and `terrain` already covers the fixed see-over barrier. v1 therefore ships no preset under that ambiguous name; #47 picks the meaning. No "blocks nothing" preset either: a segment that blocks nothing is a marker, not a barrier, and the editor deletes instead.
- **Derived label, not a stored kind [FIXED (owner-delegated), #42].** The record stores the switches. `kind` survives on the wire as a read-only label derived from them (exact match with the preset table above, else `custom`); it is never an input and never the authority, so the label and what the rules do cannot drift. Rejected: storing `kind` next to the switches.
- **Where the switches live [FIXED (owner-delegated), #42].** Typed, validated fields on the wall record and in the wall payloads, defaulted server-side; never inside `flags`, because the server interprets sight and movement and `flags` stays the never-interpreted free object (6.1, 8). Whether they become columns or one validated restrictions object is #49's; the direction is named fields, not a free-form blob.
- **Composition with thickness and height (hook, decided in #44/#45, not here).** The switches choose *which* predicate reads a wall: the sight wall list holds a wall only when `blocks_sight` (one-way: only for the blocked side), the movement collider only when `blocks_movement`. #44 then decides how the sight predicate treats a wall's height, #45 how thickness widens the sight footprint and the movement collider. A wall with `blocks_sight=false` is absent from the vision input entirely, height and thickness included — that is what keeps `terrain` cheap.
- **Status model (5.5).** "Blocking wall" for `stuck`, `squeezed`, the door push and the move checks means `blocks_movement` and, for a door, closed. So a terrain wall sticks and pushes exactly as a solid wall; a one-way wall blocks movement both ways; a secret door pushes a token exactly as a solid wall would, with no signal.
---
## 6. Protocol
Transport: one WebSocket per client at `/ws`, JSON text frames (a binary frame counts as malformed, 6.5). Envelope: `{t: string, ...fields}`; every server frame adds a per-connection counter `n` (starts at 1 on the connection's first frame; replaces the global `gseq` for everyone, section 3.1).
The whole of 6 is [FIXED (owner-delegated, 2026-11-14, #11)] unless a line says otherwise: the owner delegated the wire shapes and accepted the set. It is the complete M3 wire catalogue (29 intents, 15 server messages); nothing outside it exists in M3.
Conventions:
- **Naming.** Client -> server `t` is `<noun>.<verb>`: lowercase ASCII, exactly one dot. Nouns follow GLOSSARY.md: `token` (the map figure; the word "entity" never appears on the wire), `character`, `player`, `key` (a player key), `status`, `name`, `encountered`, plus `wall`, `door`, `scene`, `prop`, `conn`, `act`. Server -> client `t` is a bare state or event noun, snake_case, **no dot** (`token`, `token_gone`). A server `t` therefore never equals a client `t`.
- **Correlation.** Every intent carries `reqId` (client-chosen integer, 0 <= reqId < 2^31, unique among that connection's pending intents; the server echoes it and never interprets it). The server sends **exactly one** `ack` per intent, whatever the outcome. Frames whose envelope cannot be read (not a JSON object, no string `t`, no integer `reqId`) cannot be acked and get `error` instead (6.5).
- **Ack.** `ack {reqId, ok:bool, code?, id?, pos?, key?, ts?}`. `ok:true` carries only the result fields listed per intent (`id` of a created thing, `pos` of a move, `key`, `ts`). `ok:false` carries a static `code` from 6.5, except the uniform move refusal (T9, next bullet). An ack means "decided". It is enqueued after COMMIT and before the effect messages (4.2), but state messages are coalesced (4.3), so a client must not rely on any order between an ack and the state messages it caused.
- **Uniform move refusal (T9).** A refused move by a controller (locked, over step cap, wall collision; 5.5) and a GM move out of bounds both give `ack {ok:false, pos:<old position>}` with **no `code`**: one shape, no reason. Every other refusal carries a `code` and never carries a position.
- **Effects.** An intent's effects reach clients only as state messages, each built per recipient (3.1, 8) and sent only when that recipient's view changed (T11). "GM" below = every GM connection; "player X" = every connection of player X; "visible" = per the view rules in 3.1.
- **Roles.** Sender column: P = player, G = GM. A P-sender intent from a connection whose player has no name yet is refused `not-allowed`, except `conn.ping` and `player.setname`.
- **Not in M3:** `act.do` is reserved (v1 answers `no-rules`); server -> client `event` is reserved (9); GM `view.player` (7.3) is later; none is built in M3. Wire changes for M4/M5/M6 are limited to what 6.5 marks.
- **Slice-3 rollout note [FIXED (owner-delegated), #18].** The catalogue below is the contract; the handlers land slice by slice. Until a slice lands, its intents still get exactly one `ack` with the static code `unknown-type` and no state, so a half-built server never lies about having applied anything. Slice 3 builds the envelope, `hello`, `error`, `closing`, `conn.ping`, `act.do` (`no-rules`), and the three auth intents of slice 2 (`key.create`, `key.replace`, `player.remove`). Slice 4 (#19) builds `wall.add`, `wall.update`, `wall.remove` and `door.set`, plus the `walls` snapshot a GM gets on connect; everything else still answers `unknown-type`. Slice 10 (#25) builds `scene.set`: with it every one of the 29 catalogue intents has a handler, and `unknown-type` remains only the answer for a `t` outside the catalogue.
### 6.1 Catalogue
Field notes shared by all rows: `pos:[x,y]` px floats, in bounds `0 <= x <= w`, `0 <= y <= h`; `scene` = the one scene's id (kept on the wire per 8); ids are the server-assigned ids of 8; `props` = `{public?:{}, owner?:{}, gm?:{}}`; a prop key is a string of 1..64 chars, a value is any JSON whose serialized size is <= 8 KB, at most 64 keys per bucket [numbers delegated, #11]. Unknown fields in an intent are ignored (6.2); a missing or wrongly typed field is `invalid`.
#### Client -> server (intents)
Every row also carries `reqId` (omitted below). Codes are those of 6.5; `not-allowed` for a P sender on any G-only intent is implied and not repeated.
**Connection and reserved (2)**
| t | fields | who | ack ok `{...}` / extra codes | effects and recipients |
|---|---|---|---|---|
| `conn.ping` | `ts:int` | P, G | `{ts}` (echo) | none; liveness only, lag is measured with WS Ping/Pong (4.3) |
| `act.do` | `actor, action, args` | P, G | never ok: `no-rules` | none; **reserved** for the FFF hook (9) |
**Players and keys (6)**
| t | fields | who | ack ok / extra codes | effects and recipients |
|---|---|---|---|---|
| `player.setname` | `name` | P, only while own name is null | `{}`; `invalid`, `name-taken`, `not-allowed` (already named, or GM) | every connection of that player gets `hello` with `me.name` set, then the full resync (6.3); `roster` to all [FIXED, #6: asked once; GM-only renames after] |
| `player.rename` | `id, name` | G | `{}`; `not-found`, `invalid`, `name-taken` | `roster` to all connections of named players and to GM |
| `player.remove` | `id` | G | `{}`; `not-found`, `not-allowed` (the GM) | key and sessions invalidated; that player's connections closed with WS 4001 (6.5); characters and controlled tokens pass to the GM (`character` with owner GM to the GM; `token` updates per view); their encountered list and name reveals deleted (GM gets `encountered {player, full:true, set:[]}`); `roster` to all (3.2) |
| `key.create` | none | G | `{id:<new player id>, key}`; `cap-reached` (6 players incl. unused keys) | `roster` to GM (the new entry has `name:null`; players do not see unnamed players) |
| `key.replace` | `id` | G | `{key}`; `not-found`, `not-allowed` (the GM's own key rotates only by CLI, 3.2) | old key invalid, all sessions of that player revoked, all its connections closed with WS 4001; identity, characters, encountered list kept; `roster` (connected flags) |
| `key.show` | `id` | G | `{key}`; `not-found`, `not-allowed` (GM key: CLI only) | none |
**Scene, walls, doors (5)**
| t | fields | who | ack ok / extra codes | effects and recipients |
|---|---|---|---|---|
| `scene.set` | `scene`; any of `name, grid_size, vision_radius_default, token_radius_default, extra` (at least one) | G | `{}`; `invalid`, `not-found` | `hello` plus full resync to **every** connection (hello-equivalent reset; no `scene.activate`, Q3). `token_radius_default` change resizes tokens using the default with grow push (5.6): `token` updates per view, `vision`/`explored` as needed. `w, h, tile_size, cell, art_version` are not settable on the wire (import is M6 CLI) |
| `wall.add` | `scene, a:[x,y], b:[x,y]`, then either a preset name (`preset:"wall"|"door"|"secret_door"|"locked_door"|"terrain"|"one_way"`) or the raw 5.8 switches (`blocks_sight?, blocks_movement?, sight_dir?, door?, open?, secret?, locked?`), `flags?` | G | `{id}`; `invalid`, `not-found` | `wall` to GM; vision recompute for all players (`vision`, `explored`, `token` as their views change); tokens whose circle overlaps get `stuck` source `walls` (5.5): `token` per view |
| `wall.update` | `scene, id`; any of `a, b`, a preset name or the raw switches, `flags` | G | `{}`; `not-found`, `invalid` | as `wall.add` (update = remove + add for the status rules, 5.5; PROPOSED there) |
| `wall.remove` | `scene, id` | G | `{}`; `not-found` | `wall_gone` to GM; recompute; `walls`-sourced entries re-evaluated (Keep/Clear, 5.5) |
| `door.set` | `scene, id, open:bool` | G | `{}`; `not-found`, `invalid` (wall is not a door, or is a secret door and `open:true`) | `wall` to GM (a door is a wall); recompute all players; close pushes overlapped tokens aside (server-originated position change: `token` per view; `squeezed` only if no side is valid), open re-evaluates `walls`-sourced entries (5.5). Players learn only through LOS changes |
Validation for `wall.*`: `a != b`, both in bounds; each switch a boolean and `sight_dir` one of `both|left|right`; `open`/`secret`/`locked` only with `door`; a secret door closed and two-way; `preset` and any raw switch in the same payload is `invalid` (5.8).
**Wall payload rules [FIXED (owner-delegated, 2026-11-15, #19); amended by the 5.8 wall model, #42]** (6.1 was silent on these; slice 4 builds them):
- `scene` is an integer scene id. v1 has exactly one scene (Q3), seeded by migration step 3 with id `1` (4.4); any other value is `not-found`, a non-integer is `invalid`.
- `a`/`b` are `[x,y]` arrays of exactly two finite JSON numbers (integers accepted); `a == b` and any endpoint outside `0 <= x <= w, 0 <= y <= h` are `invalid`. The border itself is in bounds.
- A wall's behaviour is the 5.8 switches, defaulted as the `wall` preset (`blocks_sight:true`, `blocks_movement:true`, `sight_dir:"both"`, `door:false`, `open:false`, `secret:false`, `locked:false`). A payload gives either `preset` (the server expands it from the 5.8 table) or raw switches, never both; a switch that is not a boolean or a `sight_dir` outside the three values is `invalid`.
- `open`, `secret` and `locked` without `door:true` are `invalid`; a secret door with `open:true` or with `sight_dir != "both"` is `invalid` (5.8: it must look exactly like a solid wall). A stored non-door always has `open=false`, `secret=false`, `locked=false`, so clearing `door` through `wall.update` closes and de-secrets it.
- `flags` is a JSON object or absent (absent = `{}`); anything else is `invalid`. It is stored verbatim and never interpreted — the switches are fields, not flags (5.8).
- `wall.update` patches `a`, `b`, the switches (or one `preset`), and `flags`; at least one of them is required, otherwise `invalid`. A patch is absolute, not additive: a `preset` replaces the whole switch set, so `preset:"door"` on a terrain wall turns it into a closed door. `open` is not a patch field: it belongs to `door.set`, and an `open` field in `wall.update` is an unknown field (ignored, 6.2; a `preset` carrying `open:true` is `invalid` as above). Fields are checked before the target lookup (6.5 steps 7 then 8), so a fieldless `wall.update` is `invalid` whatever the id.
- `id` is an integer; lookup failures are `not-found` (a GM's missing target, 6.5 step 8). `door.set` on a row whose `door` is false is `invalid`, and so is `open:true` on a secret door (5.8).
- `kind` is **output only** on the `wall`/`walls` frames: the label derived from the switches (`wall`, `door`, `secret_door`, `locked_door`, `terrain`, `one_way`, else `custom`). It is not accepted as an input field; an input `kind` is an unknown field (ignored, 6.2). Field names, defaults and the existing-row migration are #49's; the rule here is that the switches are the authority and the label is derived.
- `wall.add` assigns the id from the scene's `next_wall_id`, which is monotonic and never reused (#3, 8; removal does not touch it, and a restart reloads it from the DB).
- Every write is one transaction with `synchronous=FULL` around it (Q12: GM authoring is the data that is expensive to lose) and `NORMAL` again afterwards; the in-memory scene is updated only after COMMIT, so a failed write leaves memory and DB identical.
**Scene payload rules [FIXED (owner-delegated), 2026-11-15, #25)]** (6.1 was silent on these; slice 10 builds them):
- `scene` is an integer scene id; any value but the one v1 scene (id `1`) is `not-found`, a non-integer is `invalid` (the same split as `wall.*`).
- At least one of `name`, `grid_size`, `vision_radius_default`, `token_radius_default`, `extra` must be present. A declared field must have its own shape; a JSON `null` is a wrong type, not "absent":
- `name`: the 6.5 text rule, 1..64 code points, already trimmed, no control characters.
- `grid_size`: a finite number `>= 0` (0 = no grid; `classify` rejects NaN/Inf).
- `vision_radius_default`, `token_radius_default`: a finite number `> 0`, no upper cap (#4).
- `extra`: a JSON object, stored verbatim and never interpreted; the GM sees it in `hello`.
- `w`, `h`, `tile_size`, `cell` and `art_version` are **not** patch fields (import is the M6 CLI): they are unknown fields and ignored (6.2), so a patch carrying only one of them has no field at all and is `invalid`.
- Persistence: one `FULL` transaction writes the scene row and every token whose effective radius the new `token_radius_default` changed (its position and `walls`-sourced statuses too), then memory follows COMMIT. A token with its own radius is untouched (#4); a default-radius token follows the 5.6 grow/shrink rule: grow pushes or squeezes, shrink clears the `walls` entries only when the overlap ends.
- Effects: the ack, then `hello` plus the full 6.3 resync on **every** connection (unnamed players included: they get `hello` only). A `hello` also resets the server-side per-connection diff base, so a resync after it re-sends state the client just reset instead of treating it as unchanged. No `scene.activate` (Q3).
**Character and name payload rules [FIXED (owner-delegated), 2026-11-15, #23]** (6.1 was silent on these; slice 8 builds them, module `server/characters.nim`):
- `character.create` takes `descriptive_name`, `actual_name` (the 6.5 text rule, 1..64 code points), an optional `owner` (a player id, default the GM's own) and optional `props`; a missing name, an unknown prop bucket or a mistyped field is `invalid`, an owner player that does not exist is `not-found`.
- `character.update` patches `descriptive_name`/`actual_name` only, at least one of them; `props` is an unknown field there (6.2) and so cannot smuggle a bucket past `prop.*`.
- `character.remove` answers `in-use` while any token links the character (6.5). `character.reassign` takes an existing player id and **never** touches a token's controller (3.1, 8); it also keeps every reveal (8: reveals are not revoked by an owner change).
- **A link is a name handover** (#29): `token.update {id, character_id: <id>}` with no names drops the token's own `descriptive_name`/`actual_name` as part of the link patch, because a linked token carries no names of its own. Supplying names alongside a link stays `invalid`, and unlinking still requires both names on the same patch. Without this a plain token could never be linked by update: validation requires a linked token to have empty names, while the patch kept the plain token's own.
- `name.reveal` / `name.reveal_all` carry `subject:"character"|"token"` and the subject id; a token that has a character is `invalid` (reveal through the character, 6.1), an unknown subject or player is `not-found`. A reveal writes one `(player, subject)` row; `reveal_all` writes the subject's `reveal_all` flag instead, so it covers players who join later and is idempotent. There is no un-reveal (8).
- `encountered.remove` takes `player` and a token id; a missing player and a missing entry are both `not-found`.
- **The name rule lives once** (`characters.knowsActual` + `visibleName`): a player is told a subject's actual name when the subject is a character they own, when `reveal_all` is set, or when the GM revealed it to them. The token frame, the character frame and every `encountered.name` call it; nothing else re-derives it.
- **`token` frames** gain `character_id` (string for a joined token, `null` for a plain one) **to the GM only**, plus `character_id` for a player who *owns* that character (6.1 leak note 2), and `cprops:{public:{…}}` — the character's `public` bucket for a player who sees a token of a character they do not own, `{}` for a plain token and for the owner, always present so its presence marks nothing (6.1 leak note 3). The GM frame of a linked token carries no `descriptive_name`/`actual_name`/`reveal_all`/`revealed`: those live on the character record. A plain token keeps all four.
- **A token's wire `name`** is `visibleName` of its subject: the character's names when linked, its own when plain. It is no longer always the descriptive name (that was slice 5's placeholder, 6.1 "Names").
- **`encountered`** is per player and is recorded when a token enters that player's view (main.recordEncounters, before the ack, NORMAL durability like explored): one row per `(player, token)` holding the names that player knows *at that moment*, `grey` = the token is not in that player's view now (moved, removed, or `gm_only`) and never deletes it. **One rewrite path** (`characters.rewriteEncountered`) updates the SQLite row and the live in-memory entry together for `character.update`, a plain-token rename, a link change and an owner change, applying the 8 name rule per player, so the wire and a post-restart reload cannot disagree (#30). `name.reveal` rewrites exactly the revealed player's snapshot and `name.reveal_all` every player's (#27). On a diff the message carries only the entries that changed plus a `del` list (the only way an entry disappears is `encountered.remove`); on connect/resync it is `full:true`.
- **`roster`** is sent on connect (first, 6.3), after `player.setname`/`player.rename`, and after `key.create`/`key.replace`/`player.remove`: the full list every time, `connected` = that player has a live connection. Players receive named players only (6.1 leak note 4); the GM receives every player with `name:null` for an unused key.
- **`player.setname`** is a normalise-then-store intent (trim, then 6.5): `invalid` for a name that is empty or has a control character or exceeds 32 code points, `name-taken` regardless of case ("GM" included: it is an ordinary name in the `player` table), `not-allowed` for the GM, for a player that is already named, or for an unknown player. On success every connection of that player gets `hello` again with `me.name`, then the full resync, and everyone gets `roster`.
- **`player.rename`** (G) takes `id` + `name` and answers `invalid`, `not-found`, `name-taken`; the whole table is in 6.1. **`key.show`** (G) answers `{key}` with the stored plaintext secret (Q11) and refuses the GM's own key with `not-allowed` (CLI only, 3.2).
**Token payload rules [FIXED (owner-delegated), #20 and #22]** (6.1 was silent on these; slices 5 and 7 build them):
- `token.create` requires `kind`, `pos`, `descriptive_name` and `actual_name` for a plain token, and accepts `radius` (px > 0; null or absent = the scene default) and `props` (the three buckets, validated below) from slice 7 on. `character_id` is a *known* field no slice can honour yet: it answers `invalid` (silently dropping a GM's field would lose data), and `token.update` does the same for it. The character link lands in slice 8.
- A token's effective `radius` is its own `radius` when set, else the scene's `token_radius_default` (5.6). Both the wire `radius` and the move rules use the effective value, so a resize changes the escape/capsule/push geometry immediately (`worldmap.ruleToken`).
- `token.update` does not take `radius` or `props`: `token.resize` and `prop.set`/`prop.unset` own them (6.1's field list), so both are unknown fields there and are ignored (6.2).
**Status payload rules [FIXED (owner-delegated, 2026-11-15, #22)]** (slice 7):
- A token holds a set of `(status, source)` entries: status `stuck`|`squeezed`, source `walls`|`GM` (5.5). Stored order is by status (`stuck` before `squeezed`) then source (`walls` before `GM`), so the frames are deterministic and the diff never churns.
- `statuses:[{status, source}]` to the GM; `statuses:[{status}]` to everyone else, controller included (6.1 leak note 6). `status.set {id, status}` adds `(status, GM)`; adding an existing entry is `ok` and changes nothing. `status.clear {id, status, source}` removes exactly that entry: a missing token **or a missing entry** is `not-found` (6.1). After clearing the `walls` source the player escape rule of 5.5 applies unchanged, so no extra intent is needed.
- `source` is a stored wire word, not an enum index: `walls` and `GM` verbatim (`GM` is capitalised in the catalogue, so the check is exact).
**Property payload rules [FIXED (owner-delegated, 2026-11-15, #22)]** (6.1 delegated the numbers to #11, #22 fixes them; module `server/props.nim`):
- Buckets `public`|`owner`|`gm`; caps **64 keys per bucket**, key **1..64 code points** trimmed with no control characters (the name rule of 6.5), value **serialized JSON <= 8 KB**; a `null` value is not a value. Caps are per bucket: a full `public` bucket still leaves `owner` and `gm` writable.
- `prop.set {target, id, bucket, key, value}` / `prop.unset {target, id, bucket, key}`; `target` is `token` or `character`; a bad target, bucket, key, value or cap is `invalid`, a missing token is `not-found`; `prop.unset` of an absent key is `ok`. `target:"character"` is `not-found` in M3 because characters do not exist before slice 8.
- The **property-schema registry** (8, 9) is `key -> PropSchema{kind, bucket}` plus a fallback rule, shipped **empty with a permissive fallback** (`pkAny`, any bucket) — **[amended 2026-11-15, #41]**: no longer empty, its first two keys are `height` and `eye_height` (`number`, `gm`, 5.7), which the core sight rules read; every other key still falls back to `pkAny`. DESIGN 8 said the server never interprets props in v1 (narrowed by #41: only the registered keys the core sight rules use are interpreted), so an unregistered key is accepted in any bucket; a key the rules module registers is enforced (JSON kind, bucket), and a write that disagrees is `invalid`. **[FIXED, owner decision 2026-11-15, #22]** (owner-confirmed as specified): keep the permissive fallback in v1; strict mode (every key must be registered) comes with the FFF seam, post-v1. Flipping the fallback to strict is a one-line change when FFF lands.
- Egress: the `public` bucket to everyone who sees the token, `owner` additionally to the controller, all three to the GM (6.1). The filter lives in the typed view: `PlayerTokenView` has no field for the `gm` bucket, so a later frame change cannot leak it.
**Grow push and squeeze [FIXED (owner-delegated, 2026-11-15, #22)]** (5.6's tie-break, now decided):
- `token.resize {id, radius: number>0 | null}`; `radius` is required (absent is `invalid`), `null` returns the token to the scene default. The resize and its position/status outcome are one `FULL` transaction.
- Shrink never pushes and clears the `walls`-sourced entries only when the overlap actually ends.
- Grow: if the circle overlaps no blocking wall, nothing moves. Otherwise the server displaces the centre by a **deterministic greedy relaxation**: repeat at most 16 times "take the first blocking wall (scene order) the circle overlaps and move radially away from its closest point by the distance that ends at `r + 1e-6`", stopping as soon as the circle is clear and in bounds; a centre exactly on a wall takes the wall normal on the side of `prev` (no history: the left normal of `a->b`), and a second pass tries the flipped side once. A step whose own centre path crosses a blocking wall is refused, so the push never carries a token through a wall; if neither pass ends clear the token stays where it was and gets `squeezed` (source `walls`). The gate is one transaction: size, position and statuses.
- `token.resize` is GM-only (5.6: only the GM sets a size); the ack is `{}` with `not-found`/`invalid`.
- Names: both names are stored, the wire `name` of a `token` frame is always the descriptive name; the actual name has no egress path to a player until slice 8 provides the reveal rules. `token.update` on the names is a rename and reaches whoever may see the token.
- `controller` is a player id, or `null` = the GM. The GM's own player id is stored as GM-controlled, so `controller: null` is the only GM spelling on the wire. In a patch, `controller: null` and `vision_radius: null` are real patch fields (they mean "the GM" and "the scene default"); an absent field means "keep the stored value".
- `flags` carries the `vision` flag (DESIGN 8); `vision_radius` is the token's own range and the player step cap (5.5).
- `token` frame contents: a player gets `statuses: []` (no `source`), `props` with the `public` bucket and `owner` for the controller, `vision_radius` only for the controller (the step cap), and never `kind`, `controller`, `gm_only`, `flags`, `radius_own` or either raw name. The GM gets all of those plus `descriptive_name`/`actual_name` and `props` with all three buckets. `vision` polygons are integer px (6.4). `explored` on connect/resync is `{full:true, rle:[[cy, x0, len, ...], ...]}`; afterwards `{full:false, cells:[[cx,cy],...]}` with the cells that mutation added.
- A token that a recipient may no longer see is withdrawn with one `token_gone`; a recipient never gets `token_gone` for a token it was never shown.
**Tokens, statuses, props (9)**
| t | fields | who | ack ok / extra codes | effects and recipients |
|---|---|---|---|---|
| `token.create` | `scene, kind, pos`; plain token (no `character_id`): `descriptive_name, actual_name` required; linked: `character_id` and **no** names; optional `controller` (player id or null = GM; default: the character's owner if linked, else GM), `radius` (px > 0), `vision_radius`, `gm_only`, `flags`, `props` | G | `{id}`; `invalid`, `not-found` (scene, character or controller) | `token` to the GM and to each recipient who sees it (the controller always); vision recompute; GM placement ignores walls, `stuck` if it overlaps one (5.5); a new `encountered` entry for a player who sees it (diff) |
| `token.update` | `id`; any of `kind, descriptive_name, actual_name, character_id (string = link, null = unlink), controller (player id or null), gm_only, flags, vision_radius (number or null)` | G | `{}`; `not-found`, `invalid` (links with names; unlinking without both names) | `token` per view. Controller change: `mine` flips, the old controller loses the token unless it is in their LOS (`token_gone` by diff), vision recomputed for both; **never** changes the character owner. `gm_only` set: players lose it (`token_gone`); their `encountered` entry stays, greyed (8) |
| `token.move` | `id, pos` | P (controlled) / G (any) | `{pos}` (accepted position); P refused: uniform `{ok:false, pos:old}` (5.5); non-controlled or unknown id for P: `not-allowed` (one code for both, no existence oracle); G unknown id: `not-found`; G out of bounds: uniform nack | `token` per view; vision for the mover's player; `explored` fresh cells; pushes/status changes as server-originated `token` updates |
| `token.resize` | `id, radius:number>0 or null` (null = back to the scene default) | G | `{}`; `not-found`, `invalid` | `token` per view (effective `radius`); grow pushes or sets `squeezed`, shrink may clear `walls`-sourced entries (5.6) |
| `token.remove` | `id` | G | `{}`; `not-found` | `token_gone` to every recipient who knew it; its `encountered` entries stay and turn grey (never auto-removed, 8) |
| `status.set` | `id, status:"stuck"|"squeezed"` | G | `{}`; `not-found`, `invalid` | adds entry `(status, source GM)`; `token` per view (#4) |
| `status.clear` | `id, status, source:"walls"|"GM"` | G | `{}`; `not-found` (token or entry) | removes that single entry; `token` per view; then the escape rule (5.5) |
| `prop.set` | `target:"token"|"character", id, bucket:"public"|"owner"|"gm", key, value` | G (v1; owner-bucket writes by players come with FFF actions, 9) | `{}`; `not-found`, `invalid` | token target: `token` per view (bucket filtered). Character target: `character` to GM and to the owner (public/owner buckets only), and `token` updates (`cprops`, public bucket) to recipients who see a token of that character |
| `prop.unset` | `target, id, bucket, key` | G | `{}`; `not-found`, `invalid` | as `prop.set`; unsetting an absent key is ok |
**Characters, names, encountered (7)**
| t | fields | who | ack ok / extra codes | effects and recipients |
|---|---|---|---|---|
| `character.create` | `descriptive_name, actual_name, owner?:player id (default: the GM), props?` | G | `{id}`; `invalid`, `not-found` (owner) | `character` to GM and to the owner |
| `character.update` | `id`; any of `descriptive_name, actual_name` (props go through `prop.set`) | G | `{}`; `not-found`, `invalid` | `character` to GM and owner; `token` names per view for its tokens; `encountered` upserts for players who met it |
| `character.remove` | `id` | G | `{}`; `not-found`, `in-use` (any token still links it; GM removes or unlinks the tokens first) | `character_gone` to GM and owner |
| `character.reassign` | `id, owner:player id` | G | `{}`; `not-found`, `invalid` | `character` to GM and the new owner, `character_gone` to the old owner; **no** token controller changes (3.1); reveals kept [PROPOSED, 8]; `token` per view (`character_id` and actual name visibility follow the owner) |
| `name.reveal` | `subject:"character"|"token", id, player` (the player's id) | G | `{}`; `not-found`, `invalid` (a token that has a character: reveal through the character) | to that player only: `token`, `character`, `encountered` updated with the actual name; to GM: the updated `revealed` list. Reveals never revoke (8); there is no un-reveal intent in M3 |
| `name.reveal_all` | `subject, id` | G | `{}`; `not-found`, `invalid` | sets `reveal_all`; as `name.reveal` for every player. Idempotent |
| `encountered.remove` | `player, id` (token id) | G | `{}`; `not-found` (player or entry) | `encountered {del:[id]}` to that player, same to GM |
Count: 29 intents (2 + 6 + 5 + 9 + 7).
#### Server -> client
All are built per recipient at egress (single egress rule, 2). "Sent" always means: only when that recipient's view changed. Fields marked (GM) go to GM connections only; (P) to player connections only.
| t | content | recipient |
|---|---|---|
| `hello` | `proto:int, role:"gm"|"player", me:{id, name|null}`; unless the player is unnamed: `scene:{id, name, w, h, tile_size, cell, grid_size, vision_radius_default, token_radius_default, art_version}` plus `extra` (GM). No counts, no wall data, no owned ids (`mine` is on `token`) | the connecting connection, first frame; again on `scene.set` (all connections) and after `player.setname` (that player's connections). The client resets all state on receipt. An unnamed player gets only `proto, role, me` and nothing else until named |
| `ack` | see Conventions | sender connection only |
| `error` | `code` (`malformed` or `rate-limited`; 6.5) | sender connection only; only for frames that cannot be acked |
| `roster` | `players:[{id, name, role, colour, connected}]`, always the full list | everyone (Q9). Players receive named players only (an unused key is not visible); GM receives all, `name:null` for unnamed |
| `walls` | `scene, walls:[{id, a, b, kind, blocks_sight, blocks_movement, sight_dir, door, open, secret, locked, flags}]`; `kind` is the derived 5.8 label | GM, on connect and resync (6.3) |
| `wall` | `scene, id, a, b, kind, blocks_sight, blocks_movement, sight_dir, door, open, secret, locked, flags` (upsert; doors included; this replaces the old `door` message) | GM only |
| `wall_gone` | `scene, id` | GM only |
| `vision` | `polys:[{id:<token id>, pts:[[x,y],...]}]` integer px, the full set for this player's controlled tokens with `vision` | player only; never GM |
| `explored` | `full:true, rle:[[cy, x0, len, x0, len, ...], ...]` on connect and resync; `full:false, cells:[[cx,cy],...]` afterwards (fresh cells) [format PROPOSED, 6.4] | player only; never GM |
| `token` | `id, scene, name, pos, radius, mine, statuses:[{status}], props`; `name` = the one name this recipient may see (8), no reveal state; `radius` = effective px; `props` = only the buckets this recipient may read (public; plus owner for the controller; all three for GM). More for specific recipients: `statuses[].source` (GM only); `character_id` (GM, and a player who owns that character); `cprops:{public:{}}` the character's public props (player who does not own the character; `{}` for a plain token); `kind, controller (id or null), gm_only, flags, vision_radius, radius_own (number or null)` (GM); `vision_radius` also for the controller (the step cap, 5.5); plain tokens, GM: `descriptive_name, actual_name, reveal_all, revealed:[player ids]` | GM: all tokens; player: tokens they control, plus tokens inside own LOS and not `gm_only` (3.1). Whole view of one token per message |
| `token_gone` | `id` | a recipient who had it in their `known` table and no longer may see it (left LOS, removed, `gm_only` set, controller lost it). Never sent for a token the recipient never saw |
| `character` | GM: `id, owner, descriptive_name, actual_name, reveal_all, revealed:[player ids], props:{public,owner,gm}`. Owner (P): `id, descriptive_name, actual_name, props:{public,owner}`; the owner is never sent `reveal_all` or `revealed` | GM: every character; player: only the characters they own. No other player ever gets a character record (no browsable list, T16) |
| `character_gone` | `id` | GM; and the previous owner on reassign |
| `encountered` | `full:bool, set:[{id:<token id>, name, grey:bool}], del:[id]`; `full:true` replaces the whole list (on connect, resync); (GM) adds `player:<id>` | player: own list only; GM: one message per player and list. `name` = the name that recipient's player knows (8); `grey` = no longer in that player's view ("met before, whereabouts unknown"); no position, no `character_id` for players |
| `closing` | `reason` (one of the static strings of 6.5: `revoked`, `evicted`, `proto-mismatch`, `malformed-flood`) and `code` (the 6.5 close code: 4001, 4002, 4003, 1008) | sender connection only; the last frame a server-initiated close sends, immediately before the close frame (FIXED #18, 6.5). No other frame follows it |
Count: 15 server messages. Reserved, not built: `event` (9).
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.
### 6.2 Versioning [PROPOSED]
- `proto` is an integer compiled into both client and server; M3 ships `proto = 1`. The client announces it in the upgrade request (`/ws?proto=N`), and the parameter is required: absent or not a plain integer is HTTP 400, no upgrade (6.5 row 3). Any mismatch, older or newer, is refused (6.5 row 5): the upgrade completes and the server sends `closing {reason:"proto-mismatch", code:4003}` and closes, because a browser `WebSocket` cannot read an HTTP status, only a close code (and the code itself cannot be sent at the mummy pin, 3.2). The client then shows "reload" (assets are content-hashed by Vite, so a reload fetches the matching client). No `hello` and no state are sent on a mismatch. `hello.proto` is checked again on receipt as a backstop.
- Within one proto version: additive only (new optional fields, new message types). The client ignores unknown server message types and unknown fields; the server ignores unknown fields in intents and answers an unknown `t` with `ack {ok:false, code:"unknown-type"}` (or `error {code:"malformed"}` if there is no `reqId`).
- Breaking change -> bump `proto`, document in `docs/` changelog.
### 6.3 Reconnect and resync
- Reconnect = full resync. After `hello` the server sends, in this order: `roster`; GM: `walls`, `character` for all, `encountered` per player (full), then `token` for all; player: `character` for owned, `encountered` (full), `vision`, `explored` (full), then `token` for all visible and controlled. Slice 4 sends the `walls` part: one frame to every GM connection immediately after `hello` (players never get one). Slice 5 sends the token half of the sequence: the GM's `token` for every token, and for a named player `vision`, `explored` (full) then `token` for every token it may see or control. Slice 6 built the explored restore, and slice 8 (#23) completes the sequence: `roster`, `character` and `encountered` are sent in the order above, and a sighting is recorded before the list is built, so a token that walked into an offline player's sight is in their `encountered` list on the next connect. An unnamed player gets only `hello` until `player.setname` succeeds, which triggers the same sequence on that connection. The client reducer resets everything on `hello` (reconnect-reset bug fixed in prototype, test in `client/src/state.test.ts`, 4/4 pass) [MEASURED]. Clients must tolerate any order after `hello`.
- No gap detection and no `resume(since)`: WS over TCP is ordered and lossless while connected, and a reconnect restarts from a full snapshot. Full resync on every reconnect [FIXED, Q15]. Revisit if a measured snapshot exceeds ~100 KB.
- Client reconnect: exponential backoff with jitter, cap ~10 s (prototype: fixed 2 s). Pending `reqId`s are dropped with the old connection (client-side, M4); a `hello` on a live connection (`scene.set`, first name) does **not** drop them: their acks still arrive. Assets (tiles) are kept across reconnect because explored only grows [MEASURED prototype behaviour].
- Same player on two connections: both synced; each has its own `known` table. Multiple devices per player allowed (Q10, FIXED), up to 4 (4.3).
### 6.4 Deltas and size
- Tokens: `token` only when the recipient's view of it changed; `token_gone` on leaving view; per-connection `known` table gives correct enter/leave [MEASURED, leak test (c)]. The stored diff base is the frame **before** the per-connection `n` is stamped: `protocol.withN` deep-copies, so stamping cannot make the next comparison see a different frame and re-send unchanged state (this was a live bug until slice 8; the leak checker now sees a genuinely sparse stream).
- Bytes [MEASURED, `results/concurrency-final1-server.log`]: monster move 145 B to a seeing player, 244 B to GM; player move: mover 3359-3653 B (worst 4.9 KB, dominated by the full `vision` polygon + `explored` diff), GM 145 B; door toggle 45 B (prototype `door` message; the M3 `wall` upsert is a little larger).
- v1 decisions [FIXED, Q16]: full vision polygon, integer px (halves the text size [INFERRED]), owner only, sent only on change; deltas/binary post-v1. Explored on connect as run-length rows, later diffs as cell lists [PROPOSED].
- Move rate [FIXED (owner-delegated, 2026-11-14, #15)]: client sends at most ~20 Hz while dragging (prototype 50 ms) plus a final position. Server: token bucket per connection, 30 intents/s sustained, burst 100, same for GM and players. Excess intents are refused with `ack {ok:false, code:"rate-limited"}`; no rollback: each intent is atomic (accepted ones stay, rejected ones are never applied); the connection stays open. Reconciling refused optimistic edits is client behaviour (M4).
- Max inbound WS message [FIXED (owner-delegated, 2026-11-14, #15)]: 64 KB = mummy 0.4.8 default `maxMessageLen` (inbound only, cumulative across fragments). The server passes it explicitly (`protocol.MaxInboundBytes`), so a mummy default change cannot move the limit silently. Over the limit mummy closes TCP without a close frame (mummy.nim :658-660). No config; outbound unaffected.
- Per-connection `n` counts **server frames only**, starting at 1 with `hello`; a Ping/Pong (4.3) is a control frame and does not consume a number. There is no global counter on the wire (H25).
- Server Ping [FIXED (owner-delegated), #18]: one immediately after `hello`, then one every 20 s on every connection (`protocol.PingIntervalMs`); payload = the sequence number the client echoes in its Pong. Sending, recording and the interval are slice 3; lag measurement and the stop-feeding rule are M5 (4.3).
### 6.5 Refusals, errors and connection outcomes [FIXED (owner-delegated, 2026-11-14, #11)]
**Intent pipeline (order of checks).** The first failing step decides the reply; nothing is applied on any failure.
1. Frame over 64 KB: mummy closes TCP, no reply (6.4).
2. Not a UTF-8 text frame holding a JSON object with string `t` and integer `reqId` in range: `error {code:"malformed"}`, and it counts toward the malformed flood limit.
3. Rate limit (token bucket, 6.4): empty bucket -> `ack rate-limited` (or `error rate-limited` if step 2 failed).
4. Unknown `t` -> `ack unknown-type`.
5. P sender without a name, other than `conn.ping` and `player.setname` -> `not-allowed`.
6. Role: a G-only intent from a player -> `not-allowed`.
7. Field types and ranges -> `invalid`.
8. Target lookup. Player senders: a target that is not theirs or does not exist is one and the same `not-allowed` (no existence oracle, T9). GM senders: missing target -> `not-found`.
9. Semantic validation (GM: `invalid`; player move: the uniform nack, 5.5).
**Ack codes (static strings, never carry state).**
| code | meaning |
|---|---|
| `rate-limited` | token bucket empty (6.4); nothing applied |
| `unknown-type` | `t` is not in 6.1 |
| `not-allowed` | wrong role, not the controller, unknown or not-theirs target (players), unnamed player, GM key via the wire, `player.setname` when already named |
| `not-found` | GM-only: scene, wall, token, character, player or entry does not exist |
| `invalid` | missing or mistyped field, out of bounds, bad geometry, names/links inconsistent, bad name text |
| `name-taken` | player name already used (case-insensitive, includes `GM`) |
| `cap-reached` | `key.create` would exceed 6 players (3.2) |
| `in-use` | `character.remove` while a token links the character |
| `no-rules` | `act.do` (reserved, 9) |
Player name text: trimmed, NFC, 1 to 32 code points, no control characters. Deviation [FIXED (owner-delegated), #23]: Nim 2.2.12's stdlib has no Unicode normalisation (it lives in a package the pinned dependency set does not include) and adding one is out of slice scope, so a player name is trimmed and compared case-insensitively but stored as typed; two visually identical names written with precomposed vs combining accents would be different names. Nothing else changes. Character and plain-token names: 1 to 64 code points, same rules. All are rendered with `textContent` (T13).
**`error` frame (no `reqId`).** Codes `malformed`, `rate-limited` only; connection stays open unless the flood rule fires.
**Connection-level outcomes.** Order of checks on a `GET /ws` request, then on the open socket:
| # | condition | outcome | stage |
|---|---|---|---|
| 1 | `Origin` header missing or not equal to the configured public origin (T7) | HTTP 403, no upgrade | before upgrade |
| 2 | no session cookie, or its hash is unknown or revoked | HTTP 401, no upgrade | before upgrade |
| 3 | `proto` query missing or not an integer; request is not a WebSocket upgrade | HTTP 400 | before upgrade |
| 4 | total connections would exceed 16 after the player's own oldest is evicted (#15): the 17th | HTTP 503 with `Retry-After: 5`, no upgrade | before upgrade |
| 5 | `proto` differs from the server's (6.2) | upgrade completes, then WS close **4003** `proto-mismatch`; no `hello`, no state | open |
| 6 | the player already has 4 connections (#15): the 5th | the oldest of that player stops receiving at once and is closed with WS **4002** `evicted` (the close frame queues behind its backlog, 4.3); the new one proceeds | open |
| 7 | key replaced, player removed, or GM key rotated: the session is revoked (3.2) | WS **4001** `revoked` on every affected connection (client must not auto-reconnect: it goes to the sign-in page) | open |
| 8 | 10 `malformed` frames within any 10 s on one connection [numbers delegated, #11] | WS **1008** `malformed-flood` | open |
| 9 | inbound message over 64 KB, bad opcode/rsv, unmasked or oversized control frame | mummy closes TCP with **no close frame** (client sees 1006); not catchable by app code | open |
| 10 | server shutdown (SIGTERM) | WS **1001** (going away) [M5, 4.4 handler] | M5 |
**How the outcome reaches the client [FIXED, owner decision #18, 2026-11-15: option A].** At the mummy 0.4.8 pin `close(ws)` emits an **empty** close frame, so a browser reports **1005** and none of the codes above can be sent; mummy is neither patched nor forked. Instead, every server-initiated close (rows 5-8) is sent as **two frames**: one final application message `closing {reason, code}` (6.1 `closing`), then the close frame. `reason` is the bold static string of the row; `code` is the row's numeric code (4001, 4002, 4003, 1008); `closing` also carries the connection's `n`. The client's rule: on 1005, the reason is the `reason` field of the last message it received. A close with no preceding `closing` is a transport failure (row 9 or a dead peer), not an application outcome. Rows 1-4 refuse before the upgrade, so they are plain HTTP statuses with no frame; row 10 (M5) is the same two-step shape with `reason:"server-shutdown"`, `code:1001`, and is not built yet.
Why not the alternatives: patching/forking mummy is fallback only (4.3), and a client-side heuristic on 1005 alone cannot tell eviction from revocation from a proto mismatch. Consequence for tests: every close assertion is "the last message is `closing` with this reason and code, then the close event reports 1005".
WS close reasons are the static strings in bold above. Close codes 4001-4003 are the app's range; 1008 and 1001 are the RFC 6455 standard codes. Lagging clients (M5, 4.3) get no close and no frame: they are not fed until resync, and nginx closes dead peers (M5).
### 6.6 HTTP surface in M3
- `POST /join` (the sign-in page; HTTP, not WS; 3.2). Body `application/x-www-form-urlencoded`, one field `key`, at most 1 KB (the server answers `400` above that; mummy closes far above it). Key comparison ignores case, dashes and spaces and is constant-time. Valid key (player or GM): `303` to `/` with `Set-Cookie: fff_session=<random>; HttpOnly; Secure; SameSite=Strict; Path=/` and `Referrer-Policy: no-referrer`; the session token is a fresh 32-byte hex value and only its SHA-256 is stored (3.2). Invalid key: `401`, no body detail, no cookie. Wrong method `405`; missing `key` or wrong content type `400`. No rate limit (owner, #6). The body is never logged (T6). Cookie name `fff_session` [FIXED (owner-delegated, 2026-11-14, #17)].
- `GET /ws`: 6.5 (rows 1-4).
- `GET /tiles/<scene>/v<art_version>/<x>_<y>.png`: 3.3 (`200` with `X-Accel-Redirect`, `403` unexplored, `404` malformed/out of range). Slice 9 (#24) pins the full status split in 3.3: `404` also for another scene or a stale art version, `403` also for a missing or unknown session (one response with "unexplored"), and `Cache-Control: private`.
- `GET /healthz`: 200 `{"status":"ok"}` from M3 slice 1 [FIXED (owner-delegated, 2026-11-14, #16)]; M5 makes it report whether the global lock can be acquired within a bound (11.3).
---
## 7. Client
### 7.1 Layers (bottom to top, one Pixi stage under a world container with pan/zoom)
1. **Map tiles**: sprites per tile, loaded lazily for tiles the server allows.
2. **Grid**: one `TilingSprite` over a small cell texture, toggleable [MEASURED technique, `prototype-pixi-perf/README.md` Techniques].
3. **Entities/tokens**: pooled containers, shared `GraphicsContext` per colour, `BitmapText` labels.
4. **Fog (players)**: explored dim layer + vision cut-out (7.3).
5. **GM overlay (GM only)**: walls/doors Graphics, wall editor handles; hidden from players by never receiving the data.
6. **DOM overlay**: toolbars, token panel, player keys dialog, connection status; plain HTML on top of the canvas (no framework) [FIXED].
### 7.2 Rendering techniques kept from the perf prototype [MEASURED, `prototype-pixi-perf/README.md`]
- Verdict: Pixi v8 renders a VTT scene at 60 fps on Radeon 780M (WebGL and WebGPU) and Galaxy Note 10 (WebGL) up to 1000 tokens (Note 10 js ~14 ms, 2000 tokens -> 32-36 fps, CPU-bound; laptop js 9-12 ms at 2000). Only per-frame token JS scales; a table needs tens of tokens.
- **Update only changed entities**, never all per frame (chaos worst case is not a workload here).
- **BitmapText** with a pre-installed `BitmapFont` for labels (no raster/upload on change); limit: single font size blurs on zoom. Decision [FIXED, Q17]: names via BitmapText; glyph set = Latin incl. accented characters + Nerd Font icon glyphs. No non-Latin or emoji requirement, so no HTMLText/Text fallback in v1.
- **Shared GraphicsContext** per colour, tessellated once; pooled tokens.
- **Culling**: map tiles/baked sprites `cullable`; tokens fixed `cullArea`.
- **Map larger than max texture -> tiles**; WebGPU maxTex 8192 vs WebGL 16384 on the same GPU; phone maxTex 4096. A single 16384 texture ~1 GB VRAM: never upload big single textures, always tiles.
- **Baked strokes** (live Graphics chunks <= 48 pts, bake on pointer up) are available if drawing arrives post-v1; 200 strokes cost nothing on real HW [MEASURED], SwiftShader result was an artifact.
- **Input**: hand-rolled DOM pointer events for pan/zoom/pinch (pixi-viewport declared v8-compatible but custom token drag/pinch needed anyway); Pixi federated events off; O(N) hit test on press only.
- Fixed per-frame overhead on phone ~3 ms at 50 tokens vs 0.4 ms laptop [MEASURED, cause hypothesised overlay/culling]: keep the DOM overlay and per-frame work minimal.
- Unverified (carry as risks): iOS/Safari, WebGPU on mobile, tablets, HP-churn timing.
### 7.3 Fog rendering (new design; prototype's approach is explicitly not kept)
Prototype `client/src/main.ts`: explored rects appended to a `Graphics` mask forever (re-tessellated, flagged shortcut), one `Text` per token (heavy), unverified in a browser [HANDOFF.md]. Both replaced.
- Fog is a presentation of two server facts: `explored` cells and `vision` polygons. It is **cosmetic**: hidden tokens are never sent, so no client clip is needed for security.
- Three states per point: unexplored (opaque black), explored not visible (dim, ~0.6 alpha black), visible (clear).
- **Explored layer [PROPOSED]**: keep explored as a bitmap/RenderTexture at cell resolution (map/cell, e.g. 128x128 for 4096/32), updated by writing new cells; display scaled with smoothing. Memory fixed regardless of exploration; no unbounded Graphics. Exact Pixi mechanism (RenderTexture draw vs Uint8 texture resource) to be chosen in M4 with the pixijs skills; acceptance criterion is below.
- **Vision layer [PROPOSED]**: polygons (few, ~64-300 vertices each) drawn into a mask only when a `vision` message arrives; cut-out through a mask/erase blend.
- Soft edges: optional blur filter on the fog texture at cell scale; measure on Note 10 before enabling.
- GM view: fog disabled by default; optional "preview as player X" is a GM-side toggle that must not require extra data (GM client would need the player's polygons: it can request them as GM-only message `view.player` computed server-side) [PROPOSED, later].
- Browser rendering of fog/drag/reconnect is unverified in prototype (no browser in build env). M4 adds a headless-browser pixel check.
### 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]: click-click segments, snap to grid/endpoints optional, delete, undo of last edit [PROPOSED]; submits `wall.*` intents; server is the validator. A preset row (`wall` (default), `door`, `secret door`, `locked door`, `terrain`, `one-way wall`) sets the switches for a one-drag default; an **advanced** toggle exposes the raw switches (`blocks_sight`, `blocks_movement`, `sight_dir`, `door`, `open`, `secret`, `locked`) for a custom wall. The editor draws `kind` (the derived label) only; no preset is a stored kind. Thickness and height controls arrive with #45 and M4.
- 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).
### 7.5 Prediction and rollback for own moves
- Players do **not** know the walls, so the client cannot predict collisions [INFERRED, consequence of strict model]. Prediction = optimistic placement of the dragged sprite, send `token.move` with `reqId` at <= 20 Hz, and a final send on release.
- While dragging, incoming authoritative positions for that token are ignored (prototype behaviour) so the sprite does not fight the pointer.
- `ack{ok:true,pos}` -> nothing to do (server pos == requested). `ack{ok:false,pos}` (no `code`) -> snap to `pos` if not dragging; if dragging, snap on release (do not teleport under the finger).
- Rollback visual: short tween back to `pos` (cosmetic).
- Pending request map keyed by `reqId`; dropped when the connection closes (6.3).
- Others' tokens: render the latest `token` message; interpolate between updates (client-side only, <= 100 ms) [PROPOSED].
---
## 8. Data model
All ids are server-assigned. **Walls [FIXED, owner decision 2026-11-10, #3]**: per-scene ids, each scene counts from 1. Removal never renumbers; ids are never reused. Each scene stores `next_wall_id` (monotonic, never decreases, even if the newest wall is deleted). The column lives on the `scene` row created by migration step 3 (4.4), and the wire rules for the four wall intents are in 6.1. Wall identity = `(scene, id)` in DB, server and wire. Wall ids are GM-only in v1. **Tokens/entities [FIXED, owner decision 2026-11-10, #3]**: random opaque id, 12 chars from `[A-Za-z0-9_-]`, from a CSPRNG; server checks collision on create. Unique game-wide (not per-scene), so a token may later change scene keeping its id (cross-scene move not in M3). Counted ids would leak hidden tokens through gaps. **Doors are walls** and use wall ids; toggling is GM-only in v1, so any door-id exposure later leaks at most about the wall count (accepted). Rejected: dense ids with renumber broadcast (in-flight intents hit the wrong wall); game-wide wall counter (per-scene ids keep scene copy/export stable).
- **Scene** (exactly one in v1, Q3): `id, name, w, h` (px), `tile_size` (32 default = `explored_cell` [FIXED, Q4]; 64 is the per-scene fallback), `explored_cell` (32 default; `tile_size % cell == 0` required, prototype assumes it silently), `grid_size`, `vision_radius_default`, `token_radius_default` (px, > 0, no upper cap [FIXED, #4]), `art_version`, `active`, free-form `extra`.
- **Wall [FIXED, owner decision 2026-11-15, #42]**: `scene, id` (per-scene, see above), `a:[x,y], b:[x,y]`, the switches `blocks_sight, blocks_movement, sight_dir ('both'|'left'|'right')`, the door settings `door, open, secret, locked`, and the free `flags`. Behaviour comes from the switches (5.8); `kind` is only a derived output label (`wall`, `door`, `secret_door`, `locked_door`, `terrain`, `one_way`, else `custom`) and is never stored. `blocks = blocks_movement and not (door and open)`; a `terrain` wall is absent from the sight input. GM-only everywhere. **Height [FIXED, 2026-11-15, #41]**: an optional height in metres on the wall record (> 0, <= 100 m); absent = full height, which blocks sight for every viewer (5.7). Existing walls carry none and are unchanged. Thickness and the low-wall rules are #44/#45; the wire fields and the migration are #49. Rejected: a stored `kind` enum, and a `window` kind before #47 gives it a rule (in v1 "sees over, does not pass" is `terrain`).
- **Entity (token and anything else) [PROPOSED, FFF seam]**:
- `id` (random text, see above), `scene, kind` (free string: `pc`, `npc`, `item`...), `character_id` (NULL = plain token, e.g. monster or item; else the character it figures), `descriptive_name`, `actual_name` (plain tokens only; a character's tokens use the character's names), `pos`, `radius` (px, > 0, no upper cap; NULL = use scene `token_radius_default`; GM-only to set [FIXED, #4]; 5.6), `owner` = token controller (player id or null = GM-controlled; independent of the character's owner, 8), `gm_only`, `flags` (`vision`, `blocks_move`...), `vision_radius` (optional; per-entity numeric with scene default, Q7 FIXED; also the player step cap, 5.5), `statuses` (set of `(status, source)` entries; status `stuck`|`squeezed`, source `walls`|`GM`; locked while any entry exists; Q14, 5.5, #4).
- `props`: three JSON objects by visibility bucket: `public` (anyone who sees the entity), `owner` (token controller + GM), `gm` (GM only). Keys are strings, values JSON scalars/arrays/objects with a size cap. No hidden state beyond these buckets and `gm_only` in v1 [FIXED, Q19]. **`height` and `eye_height` (5.7) are the first two registered keys**, both in the `gm` bucket and both `number`: on a plain token they are its own values, on a linked token the token's values are a temporary override of the character's base (5.7) [FIXED, 2026-11-15, #41].
- The server interprets only registered keys used by core sight rules: `height` and `eye_height` (5.7) are read by them and enforced as numbers in the `gm` bucket; every other key is stored and never interpreted (FFF later). Interpretation beyond that arrives only through a registered property schema (`{kind, bucket}`), which is also the validation table; before #41 this bullet said "the server never interprets props in v1". Property writes are GM-only in v1 (6.1, #11); the writable-by role and a default value are deferred to the FFF seam (9, post-v1), not part of this registry.
- **Character [FIXED, owner decision 2026-11-10, #14]**: own record, separate from tokens. Fields (indicative): `id` (random, same format as token ids), `owner` (exactly one player id; the GM is a player, so GM ownership = the GM's player id; the GM reassigns), `descriptive_name`, `actual_name` (names rule below), `reveal_all`, `props` (three buckets, identity/base values; `height` and `eye_height` are the base values of 5.7, `gm` bucket). A character has any number of tokens in any scene. A new token for a character starts controlled by the character's owner; the GM may change it. Changing a character's owner never changes its tokens' controllers (GM adjusts by hand). Rejected: token controller derived from character; auto-follow on reassignment; all data on the token (duplicated stats); all data on the character.
- **Character props vs token props [FIXED, #14]**: the character holds who the figure is (identity, base values); the token holds what is happening to that figure (damage, conditions, scene effects). Plain tokens (monsters, items) keep their own data. Both use the three buckets: `owner` for a character = character owner + GM; for a token = token controller + GM. The server stores both and, apart from the registered sight keys `height`/`eye_height` (5.7), never interprets them; FFF decides the rest of the split (9). The character's `height`/`eye_height` are the base values; a token's are an on-map override that leaves the character alone (5.7) [FIXED, 2026-11-15, #41]. A recipient's view of a token is built from its own props and its character's props, each under its own bucket rule [PROPOSED].
- **Names [FIXED, #14]**: every character and every plain token has a `descriptive_name` (e.g. "a grumpy man") and an `actual_name` (e.g. "Lord Vex"). Players see the descriptive name until the GM reveals the actual name to that player; the GM can also reveal to all at once (`reveal_all`). The owner of a character always sees its actual name. A character's tokens use the character's names, so one reveal covers all of them. Applies to player characters too (introductions). A reveal cannot be undone in v1 (no un-reveal intent). Reveals are not revoked when ownership changes [PROPOSED]. Built in slice 8 (#23): a reveal is one `(player, subject)` row, and the subject is a character id **or a plain token id** — the two share one id namespace (4.4), so no column distinguishes them. `reveal_all` is a flag on the subject, not a fan-out of rows, so a player who joins later is covered. The one rule that turns a reveal, an owner or a flag into the name a recipient sees is `characters.knowsActual`/`visibleName`; no frame builder re-derives it.
- **Encountered list [FIXED, #14]**: per player, every token that the player's controlled tokens have ever seen, shown under the name that player knows. Out of sight: greyed ("met before, whereabouts unknown"). `gm_only` tokens never enter it; a token that becomes `gm_only` after a player met it keeps its entry (greyed). Entries are never removed automatically (not on token removal, scene change or a `gm_only` flip); only the GM removes an entry for a player. Server tracks and persists it. Built in slice 8 (#23): each entry is a *snapshot* of the names the player knew when it was first sighted (plus the character link, so a rename and a later reveal can follow it), `grey` is computed at frame time, and an entry is recorded on every mutation that could show the token, before the ack. No browsable list of all characters for players. Not the player roster (Q9 lists players only).
- **Player**: `id, name (NULL until first sign-in; unique among players), role (gm|player), colour`. Exactly one GM. A player is a real person who signs in with a player key; not a character. A player may own several characters. Max 6 players; unused keys count toward the cap. GM can rename. Remove: see 3.2 [FIXED, #6].
- **Player key**: `player_id, secret (plaintext, re-showable by GM, Q11 FIXED), created`; one current key per player; replace overwrites. Format: 20 symbols in 5 groups of 4 with dashes, alphabet without look-alikes, CSPRNG (~99 bits) [FIXED, #6; implementation detail #17 in 3.2]. The GM's key is the GM player's key (3.2). Not a session [FIXED, #6].
- **Session**: `id, player_id, token_hash (SHA-256 hex of a 32-byte CSPRNG token; the token itself is never stored), created, last_seen`; never expires (Q10 FIXED).
- **Explored grid**: per `(player, scene)`, strictly per player (Q9 FIXED): bitset over `ceil(w/cell) x ceil(h/cell)` cells; persisted as chunked bitmaps (4.4). Only grows. Players with no vision-enabled entity have an empty grid.
- **Vision polygons**: runtime only, never persisted (recomputed at start).
- **Connection (runtime)**: id, player, `known` map, last vision ver, counter.
Prototype entity (for mapping): `Tok{id,name,kind,pos,gmOnly}` + `tokenRadius` global in scene (`prototype-server-vision/data/scene.json`: 4096 px world, 256 px tiles, radius 400, token radius 20, cell 32, 60 walls, 8 tokens).
---
## 9. FFF integration seam (design only, not built)
Principle: v1 has no rules, but every state change already flows through a validated mutation with a recipient-aware view, and entities already carry bucketed properties. FFF later adds **interpretation**, not new plumbing.
- **Characters and tokens with properties**: FFF characters are character records (8); monsters and items are plain tokens. Both carry `props` in the three buckets. FFF decides which keys live where (token state vs character identity and base values); the VTT enforces the bucket on egress and interprets nothing except the registered sight keys `height`/`eye_height` (5.7, #41).
- **Action hook** (server side): the reserved `act` intent carries `actor, action, args`. Handling = `rules.handle(world, actor, action, args) -> list of mutations | error`. Mutations are the same primitive set the pipeline already validates (set prop, move, create/remove entity, emit event). Hook output is validated like any client intent; FFF cannot bypass the egress filter.
- **Events**: `event{kind, data}` server->client messages with per-recipient filtering (e.g. roll results visible to all, GM-only whispers). Not implemented in v1; message type name reserved.
- **Schema registry**: `property schema` (key, `{kind, bucket}`) registered by the rules module; v1 ships it with the two keys the core sight rules read, `height` and `eye_height` (`number`, `gm`, 5.7), and a permissive fallback for every other key (6.1). The server interprets only registered keys used by core sight rules, which is the one narrowing of "no interpretation in v1" (#41, 8); everything else is stored unread until FFF registers it. A writable-by role and a default value are not part of it: prop writes are GM-only in v1, and which role may write which key, plus any default, belongs to the FFF seam (post-v1).
- **Where does FFF run?** Undecided. Q19 answered only the hidden-state question (no state beyond the buckets and `gm_only`, FIXED); engine language, runtime and location are not answered. Revisit when FFF starts (schema change accepted then). Options: (a) compile-time Nim module linked into the server (simplest, fastest, requires FFF in Nim or a Nim port); (b) out-of-process sidecar speaking a small request/response protocol over a Unix socket (language-agnostic, adds latency and a failure mode inside the global lock; must run outside the lock or be time-bounded); (c) WASM. No decision made.
- Client side: a generic property panel driven by the schema registry; FFF-specific UI later as additional DOM panels (plain HTML overlay [FIXED] keeps this simple).
- Non-goal now: any assumption about dice, turns, or stat names.
---
## 10. Testing strategy
Principles carried from the prototype: the checker must be independent of the code under test where possible, and every check needs a negative control that proves it can fail.
### 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 (6.4); spread walkers across connections (4 per player, 16 total; 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"; completeness check is kept (assert (b)).
### 10.3 New
- **Fault classes** for new data: `GMONLY_TOKEN`, `OWNER_PROP`, `GM_PROP`, `GLOBAL_COUNTER` (gseq side channel), `WALL_DELTA` (wall.add reaches player), `KEY_IN_LOG`, `CHAR_OWNER_PROP`, `ACTUAL_NAME`, `CHAR_LIST`, `CONTROLLER_CHANGE` (#14). Each with an injected fault and exact-class assertion, same as existing. **Slice 5 built** the classes that exist at this slice: `HIDDEN_TOKEN`, `GMONLY_TOKEN`, `WALLDATA`, `WITHHELD`, `NO_REMOVE`, `OWN_VIEW`, `OTHER_PLAYER`, `EXPLORED` (`-d:leakfault` + `LEAK_FAULT=<name>`, `tools/fault.test.mjs`, exact class set per fault, and the shipped binary asserted to contain no `LEAK_FAULT`). `OWNER_PROP`, `GM_PROP` and the new `STATUS_SOURCE` arrive with slice 7 (#22): the leak scenario writes props into all three buckets and sets a GM-sourced status on a token the subject can see, and `tools/leakcheck.nim` refuses the `gm` bucket, the `owner` bucket on a non-controller and any `source` on a player status entry. `ACTUAL_NAME`, `CHAR_LIST`, `CONTROLLER_CHANGE` and `CHAR_OWNER_PROP` **arrive with slice 8 (#23)**: the leak scenario creates a character, puts a token of it next to the subject, writes the character's three prop buckets, renames it, reveals it to one player and to all, reassigns it twice, reveals a plain token, flips a `gm_only` token that the subject had met, removes a token the subject had met and removes one encountered entry. `tools/leakcheck.nim` adds the four classes: an actual name a player may not see in a `token` or an `encountered` frame (`ACTUAL_NAME`), plus `STALE_NAME` (v0.20, #30: an encountered entry whose name is neither the actual nor the descriptive name that player knows, e.g. a snapshot a rename failed to update); another player's `character` record, a `character_id` on somebody else's token, or an encountered entry the subject never saw (`CHAR_LIST`); a token controller that moved in a group whose intents asked for no controller change — the transcript logs every intent, so `token.create`/`token.update{controller}`/`player.remove` are the only allowed causes (`CONTROLLER_CHANGE`); a `cprops` object carrying anything but the character's `public` bucket (`CHAR_OWNER_PROP`). Two consequences worth recording: the `hidden` and `gmOnly` faults now also produce `NO_REMOVE`, because a leaked token whose frame never changes leaves the client holding it with no message to correct it, which is indistinguishable from a withheld `token_gone` at the client (both invariants really are broken, so both classes are asserted); and the tile gate is HTTP-plane, so it is proven by `tools/tiles.test.mjs` against the test nginx (10.3 Tiles), not by the WS transcript checker. `GLOBAL_COUNTER` is already structurally impossible (per-connection `n`).
- **Characters and names (#14)**: tests for reveal per player and reveal to all; owner sees own actual name; character owner change leaves token controllers unchanged; encountered entries survive token removal and scene change and are removed only by the GM; `gm_only` tokens never enter an encountered list. Fault classes: `ACTUAL_NAME` = unrevealed actual name sent to a player; `CHAR_LIST` = another player's character or encountered entry sent; `CONTROLLER_CHANGE` = owner change altering controllers; `CHAR_OWNER_PROP` = character owner-bucket prop sent to a non-owner. **Built in slice 8** as the `tools/characters.test.mjs` group, which also carries the two checks 10.3 was missing: "a status source is not shown to a non-GM" (the controller included) and "an encountered entry survives a `gm_only` flip and a token removal" (greyed, never deleted).
- **Tiles (#24)**: `tools/tiles.test.mjs` is the group's leak check (d) and the smoke tile-steal checks, through the real binary and a test nginx (`tools/nginx.mjs`, nginx from devbox; config generated per run in the state dir). An **independent explored oracle** (born in 10.2) recomputes visibility per cell from the GM's walls and the token's vision radius with its own clear-segment maths (inscribed 64-gon radius - 0.5 px for "sure", radius + 0.5 px and proper crossings for "maybe"): a `200` must be oracle-maybe (no invented disclosure) and oracle-sure must be `200` (no withheld tile). The 32x32-tile sweep is 1024 requests; slice 9's scene allows 283, all 283 oracle-sure, 0 maybe-refused. Also checked: a player with no sight state gets `403`; another player gets `403` on a tile its neighbour sees; direct `/_tiles/` is `404` (the file exists) for every identity; malformed/canonical/out-of-range/stale-version/scene paths are `404` (with and without a session, including the GM); traversal and encoded shapes never reach a file; the direct-from-Nim answer carries `X-Accel-Redirect: /_tiles/1/v1/<x>_<y>.png`, `Cache-Control: private` and an empty body. Fixture tiles are 32 px PNGs written by `tools/tilefixture.mjs` under the state dir at test time; the test asserts the repo tracks no `.png` at all.
- **Probing test (T8)**: M2, in-process against the move-rules module (5.5): arbitrary far moves; assertion: facts about walls/doors beyond LOS recoverable from replies <= a bounded amount (step cap), and uniform nack shape. M3: same test over WS with a hostile client (moved from M2).
- **Auth tests**: key replace (old key invalid, sessions revoked, live connections closed), remove player (key invalid, characters and tokens pass to GM), one key reused on several devices (Q10 FIXED), Origin mismatch rejected, cookie flags present.
- **Protocol tests** (#18, `tools/protocol.test.mjs`): proto missing/non-integer (HTTP 400) and mismatch (`closing` 4003, no `hello`); unknown intent type (`unknown-type`) with unknown fields ignored; exactly one `ack` per `reqId` (reqId 0 and 2^31-1 included); `hello` first with `n = 1` and a per-connection `n` thereafter; `error malformed` for unreadable frames; the malformed flood (nine tolerated, the tenth closes 1008); the intent bucket (burst then `rate-limited`, connection stays open, a refused intent applies nothing, `error rate-limited` for an unreadable frame on an empty bucket); the 64 KB inbound boundary (exactly 64 KB is a message, 64 KB + 1 drops the TCP connection with no close frame); unmasked and bad-opcode frames; the server Ping and the Pong answer to a client Ping; the connection cap (503 + `Retry-After: 5`); and every server-initiated close as `closing` then 1005.
- **Persistence**: migration tests (old DB -> new), chunked explored round trip, restart test extended to wall CRUD and entity props. **Slice 6 built** the explored half: `tests/texplored.nim` (chunk layout pinned, whole-chunk encoding, upsert replacement, per-player keying, restore, write cost) and `tools/persistence.test.mjs` (round trip through a fresh resync, per-player isolation, SIGTERM and SIGKILL restart equality, a wall removal's revealed cells after the wall returns, chunk rows decoded independently, move-ack timing, and a fixture schema-4 DB migrated by the real binary).
- **Restart (#25)**: `tools/restart.test.mjs` is the "restart" accept group. It builds one world that exercises every CRUD path (walls and an open door, plain/monster/player/linked tokens, a resize and a GM status, props in three buckets with a `prop.unset`, a character with props, a per-player reveal and a token `reveal_all`, a sighting in the encountered list, players and a name) and compares the complete 6.3 resync of a fresh GM connection and a fresh player connection before and after the restart: hello scene block, roster, walls, characters, tokens, encountered, vision and the full explored RLE, all normalized (only the per-connection `n` is dropped) and deep-equal. Both SIGTERM and SIGKILL are checked, because every ack follows its COMMIT (4.2).
- **Logs (#25)**: `tools/logs.test.mjs` is the "logs" accept group. It records every GM key (the CLI key, a `--new` rotation, an old key after rotation), every player key (`key.create`, `key.show`, `key.replace`), every session cookie from `/join` (several devices) and its SHA-256 hash, plus a wrong key, a refused tile, a proto mismatch and a malformed frame, across two server runs on the same state dir, then greps the whole `server.log` for every value: none may appear. The second test is the negative control: a `-d:leakfault` build with `LEAK_FAULT=keylog` writes a raw key to stdout past `eventlog`, and the same grep must find it (so a log that was never captured cannot pass).
- **Slow client** (Q13, 4.3): a client that stops reading; outbox stays under cap, no further state is queued to it, RSS flat, full resync on recovery equals a fresh connection; nginx closes the dead `/ws` socket within its configured timeout.
- **Browser e2e (new, none in prototype)**: headless Chromium via playwright-core (the perf prototype already drives devbox chromium, `prototype-pixi-perf/bench.mjs`; SwiftShader is fine for correctness, not for perf). Checks: join -> canvas renders; pixel probe shows unexplored area black, visible area map-coloured, dimmed explored area; GM sees walls, player DOM/network contains none; reconnect restores view; drag moves token and rollback works.
- **Independent traffic audit in e2e**: record all WS frames and HTTP responses seen by a player browser and run the leak checker's (a)(e) assertions over them.
- **Load/perf regression gate**: `bench` + concurrency numbers (section 5.3 and 4.3) compared with committed baselines; fail on > 2x regression [PROPOSED].
- **Wall-count scaling bench**: 5k-wall synthetic scene (section 5.3; PROPOSED test target, Q2).
- Timings from the prototype are single machine loopback power-save CPU; no real network, no client render [MEASURED caveat]. A real-network run (laptop over the intended HTTPS path, phone on LAN) is an M7 item.
### 10.4 Test tools [FIXED, owner decision 2026-11-14, #9]
- Black-box (outside) WS/HTTP harnesses: Node 26 only, repo-root `tools/`, ported from `prototype-server-vision/tools/` (`smoke.mjs`, `leak.mjs`, `restart.mjs`, `concurrency.mjs`, `lib.mjs`, `withserver.sh` incl. the M3 test nginx). No Nim rewrite. Reason: Node is already required for the client (Vite/TS, playwright-core e2e, reducer tests); a harness in another language from the server cannot share its protocol bugs; zero deps; already measured. Fix the stale "Node 22" note in `lib.mjs` on port. The port lives in `tools/withserver.mjs`, and slice 9 (#24) added the test nginx as `tools/nginx.mjs`.
- Harness tooling: built-ins only, no npm deps. Global `WebSocket` with `{headers}` for Cookie/Origin; `node:net` for raw and malformed frames (oversize, bad opcode/rsv, unmasked, flood); `node:test` as runner. Node 26 header behaviour [MEASURED, 2026-11-14, #16, node v26.11.1]: `{headers}` still puts `Cookie` and `Origin` on the wire, and without `{headers}` no `Origin` is sent; pinned by `tools/wsheaders.test.mjs` so a Node upgrade that drops the option fails loudly (#8 had verified v24 only; the prototype's "Node 22" note is stale).
- Root `devbox.json` pins `nodejs` 26 (port step) and, since slice 9 (#24), the `nginx` used only by the test harness (DESIGN 11.1); no global tooling.
- `devbox run test` = Nim tests first, then Node harnesses.
- The nine M3 accept groups and their proving harness tests are mapped in `tools/groups.mjs`; `tools/groups.test.mjs` fails if a group file or its named evidence test disappears, so the checklist of 14 (#12) cannot silently go stale. Slice-level harnesses that are not an accept group (`smoke`, `walls`, `tokens`, `details`, `scene`, `wsheaders`) run in the same pass.
- In-process tests stay Nim (`nimble test`, unchanged).
- Browser e2e details: M4, not decided here.
---
## 11. Ops
### 11.1 Deployment on NixOS [PROPOSED]
- **Service** [FIXED, Q20; research: `docs/research/q20-nix-packaging.md`]: NixOS module `services.fffVtt` in `nix/module.nix`, defining: package from `nix/package.nix` (`buildNimPackage`; dependencies from committed `nix/lock.json` generated by `nim_lk`; mummy tag `0.4.8`; nixpkgs input pinned to match devbox Nim 2.2.12; fallback: vendored deps via `nimFlags --path:`), a systemd unit, state dir, options for `publicOrigin`, `port`. Imported from the owner's server NixOS config, like `foundryvtt.nix`.
- Config keys [FIXED (owner-delegated, 2026-11-14, #16)]: `--public-origin` / `FFF_VTT_PUBLIC_ORIGIN`, `--port` / `FFF_VTT_PORT`, `--state-dir` / `FFF_VTT_STATE_DIR`. Flag wins over env wins over default; defaults `http://localhost:8080`, `9000`, `run`. The origin is canonicalised (lowercase scheme/host, no trailing slash) because it is compared byte for byte with the browser's `Origin` (3.2). The listen address is not a key: the binary always binds `127.0.0.1`.
- Unit hardening: `DynamicUser` or dedicated user, `StateDirectory=fff-vtt`, `ProtectSystem=strict`, `ProtectHome`, `NoNewPrivileges`, `PrivateTmp`, `RestrictAddressFamilies=AF_INET AF_INET6`, `MemoryMax`. Add `AF_UNIX` only if the FFF sidecar (section 9, option b) is chosen; revisit at Q19. Listen on `127.0.0.1:<port>` only [MEASURED prototype binds 127.0.0.1].
- `fff-vtt gm-key` (3.2) must run as the service user (e.g. `sudo -u <service user> fff-vtt gm-key`, or a wrapper in the module), so the DB and its WAL files stay owned by that user; with `DynamicUser` the module needs a fixed user name or a wrapper. [FIXED, owner-delegated, 2026-11-14, #13]
- The server takes the state-dir lock at startup and the CLI honours it (3.2): an `fcntl` write lock on `<stateDir>/instance.lock`; `gm-key --new` exits 3 while the server runs. [FIXED, owner-delegated, 2026-11-14, #17]
- `Restart=on-failure`; `TimeoutStopSec` short; SIGTERM handler flushes (4.4).
- **Client build**: Vite `dist/` produced by Nix (or CI), served by nginx from the store path. Hashed assets, long cache; `index.html` no-cache.
- **nginx** (shape of the vhost, adapt to the existing server config; reference only, I did not read the owner's NixOS repo for this doc):
- `location /` -> static client `dist`, SPA fallback to `index.html`.
- `location = /ws` (prototype uses `/ws`) -> `proxy_pass` to backend, `proxy_http_version 1.1`, `Upgrade`/`Connection` via the `$http_upgrade` -> `$conn_up` map as in the prototype, `proxy_read_timeout` long (prototype 1 h; app-level ping makes this robust), `proxy_buffering off`. The map must be declared at `http{}` level.
- `location = /join` -> proxy, **`access_log off`**, `add_header Referrer-Policy no-referrer`.
- `location /tiles/` -> proxy (Nim decides, returns `X-Accel-Redirect`).
- `location /_tiles/` -> `internal; alias <state dir>/tiles/;` `Cache-Control private`. Must be readable by the nginx user (group read on the tiles dir) [INFERRED NixOS gotcha]; do not expose the state dir otherwise. [FIXED (owner-delegated), #24] The `Cache-Control: private` on a served tile comes from the Nim gate (3.3) and nginx passes it through the internal redirect; the location adds no header of its own, so the header is not duplicated.
- Test nginx [FIXED (owner-delegated), #24]: `tools/nginx.mjs` starts the devbox `nginx` package on a free loopback port in front of the harness server, with a config generated per run under the server's state dir (ports and state paths never committed). It mirrors this vhost shape: `/join` (`access_log off`), `/tiles/` proxy, `/ws` upgrade, `/healthz` readiness, and `location /_tiles/ { internal; alias <state>/tiles/; }`. Tile bytes are 32 px fixture PNGs from `tools/tilefixture.mjs`, written under `<state>/tiles/`; none is committed.
- Response headers: HSTS, CSP (no inline scripts, `connect-src 'self'` wss), `X-Content-Type-Options`, `Referrer-Policy`.
- No `limit_req` on `/join` (owner, #6: no rate limit on key entry; ~100-bit key space).
- Prototype nginx config (`prototype-server-vision/nginx/nginx.conf`) is the functional reference; its `listen` has no address (binds all) and its temp/log paths are dev-only.
- Map import: offline CLI that slices an image into `tile_size` PNG/WebP tiles into `<state>/tiles/<scene>/v<art_version>/` and registers/updates the scene (prototype: `tools/genmap.mjs`, deterministic, hand-authored, not reusable as the importer). Browser upload is post-v1; CLI-only import in v1 (Q5 FIXED).
### 11.2 Backups [PROPOSED]
- SQLite: systemd timer running an online backup (`.backup` or `VACUUM INTO`) to a dated file in a backup folder the server creates under its data root (Q21 FIXED), keep N; WAL means a plain file copy is unsafe.
- Tiles: immutable after import, include in the normal file backup, or regenerate from source art (keep the source image).
- Restore drill documented and tested once (M6): restore into a temp dir, start server, run the restart-equivalence assertions.
- Off-box copy: out of v1 scope (Q21 FIXED).
### 11.3 Logging and metrics (bounded, outside the lock) [PROPOSED]
- Prototype's instrumentation is prototype-only: it appends every sample to unbounded arrays, and `printStats` copies and sorts all of them inside `finish()` under the global lock; **do not port** [MEASURED/HANDOFF].
- Real: under the lock only O(1) updates: a fixed-size ring buffer or fixed-bucket histogram per metric (lock_wait, vision, sqlite, send, total) and atomic counters (mutations, errors, nacks, connections, bytes). A separate timer thread (not holding the lock) snapshots and computes percentiles every N s and logs one line.
- Keep the `SLOW` line (total > `SLOW_MS`, default 50) with breakdown `lock_wait / vision / sqlite / send / other` and intent type: it is what diagnosed the SQLite COMMIT tail [MEASURED, `results/spike/investigation.md`]. Formatting of the line happens after releasing the lock; at most O(1) rate-limited lines per second.
- Log to stdout -> journald; levels; never log player key/session secrets, token positions of hidden entities are fine in server logs (server is trusted) but logs are GM-readable only (file perms).
- Redaction mechanism [FIXED (owner-delegated, 2026-11-14, #16)]: the logger (`server/eventlog.nim`) keeps a registry of secret *values* (`addSecret`, refuses anything shorter than 8 chars) and replaces each occurrence with `[redacted]` on every line, wherever it appears; independently, a field whose *name* is in the sensitive set (`key`, `player_key`, `gm_key`, `secret`, `session`, `session_token`, `cookie`, `set-cookie`, `token_hash`, `authorization`) is masked even when its value was never registered. Call sites still must not pass secrets; the registry is the safety net behind them.
- Metrics exposure: journald lines only in v1, no `/metrics` endpoint (Q22 FIXED).
- Health: `GET /healthz` internal-only returning 200 when the lock can be acquired within a bound. `/healthz` stays (Q22 FIXED).
---
## 12. HANDOFF items -> decisions / open questions
Source: `prototype-server-vision/HANDOFF.md` (and README/NOTES worries).
| # | Item | Decision / open | Milestone |
|---|---|---|---|
| H1 | Port geometry + tests as-is | Decision: port `geometry.nim`, `tgeometry.nim`, mutation check, leak harness first | M1 |
| H2 | Token on a wall can't leave (inclusive `segsCross`); closing a door or editing a wall on a token | Decision [FIXED, Q14; door case revised by owner 2026-11-08]: wall add/edit on a token gives it `stuck` (player moves refused, GM moves allowed); a door closing on a token pushes it aside instead (5.5; `squeezed` only if no side is valid; status names per #4, was `blocked`). Set/Keep/Clear per 5.5: stays while any blocking wall overlaps; clears on wall removal or door open only if no other wall overlaps, on a GM move to a free spot, or on GM clear; GM placements/moves onto a wall set it. Trigger = circle overlap [FIXED, owner]; escape + capsule rule [FIXED, accepted default]; both in 5.5. Pin tests replaced in M2. | M2 |
| H3 | O(rays x walls) vision | Decision: radius-bbox cull now; uniform spatial grid over walls only if the 5k-wall bench misses target (5.5) | M2 |
| H4 | `cellsTouched` ~12x polygon | Decision: scanline rasterization, differential test vs ported version | M2 |
| H5 | Shared-endpoint test gap | Decision: port with a test that fails if either arm is removed; new mutation (d) | M1 |
| H6 | Single machine, loopback, power-save timings | Decision: keep as baseline only; real-network run required | M7 |
| H7 | Boundary epsilon ambiguity | Decision: keep `RayEps`, 0.5 px tolerance in checkers; documented | M1 |
| H8 | Tile leak: whole 256 px tile | Decision [FIXED, Q4]: `tile_size` = explored cell = 32 px; residual leak <= one cell, never revoked; no server masking; M4 gates (headless mobile-emulation + phone run); fallback 64 px per-scene config | M4 |
| H9 | Prototype secret = cookie = permanent bearer, no expiry, binds 0.0.0.0, needs HTTPS | Decision: session != key, key replace (GM, live), remove player, log redaction, bind 127.0.0.1, HTTPS via nginx. Sessions never expire; one player key usable across devices (Q10 FIXED); keys plaintext (Q11 FIXED); no key-entry rate limit (owner, #6) | M3 |
| H10 | Move collision: centre path + dest circle, not swept circle | Decision: capsule (swept-circle) check + escape rule, 5.5; step cap = effective vision radius, 5.5 (T8) | M2 |
| H11 | Leak test explored/tile checks self-consistent | Decision: add independent explored oracle | M2 |
| H12 | Full vision polygon (~3 KB) per player move | Decision [FIXED, Q16]: full polygon, integer px, only on change; delta/binary post-v1 | M3 |
| H13 | Explored sent whole + one SQLite row per cell | Decision: chunked bitmaps in DB; RLE on connect | M3 |
| H14 | No SIGTERM handler | Decision: add; durability independent of it | M5 |
| H15 | `synchronous=NORMAL` vs FULL | Decision [FIXED, Q12]: NORMAL; FULL around GM authoring transactions | M3 |
| H16 | Timing instrumentation unbounded and under lock | Decision: do not port; ring buffer/histogram, snapshot outside lock | M5 |
| H17 | 583 ms spike unexplained | Open: not reproduced; production SLOW logging to catch recurrence | M5/M7 |
| H18 | mummy: unbounded send queue, no backpressure | Decision [FIXED (owner decision), Q13]: app-level bounded per-client outbox, coalescing, WS Ping(seq)/Pong lag tracking, stop feeding + full resync; no mummy patch; fork is fallback only (4.3) | M5 |
| H19 | `WebSocket` keyed by raw bytes | Decision: app `connId` table (not raw bytes; `WebSocket` has field-wise `==`/hash at pin, Q13 research) + layout test | M3 |
| H20 | Fog masks Graphics grow unbounded | Decision: fixed-size baked fog texture (7.3) | M4 |
| H21 | Pixi `Text` per token heavy | Decision: BitmapText; glyph set Latin incl. accents + Nerd Font icons (Q17 FIXED) | M4 |
| H22 | Browser rendering never verified | Decision: headless browser e2e | M4 |
| H23 | Tiles don't update on door change | Decision: by design (static art); doors never part of art | -- |
| H24 | Prototype `gmOnly` unused (my finding, not in HANDOFF) | Decision: enforce + fault class | M3 |
| H25 | Player-visible `gseq` side channel (my finding) | Decision: per-connection counter | M3 |
| H26 | Move-validation wall-probing oracle (my finding) | Decision: step cap + rate limit + uniform nack + test (in-process M2, over WS M3; 5.5) | M2/M3 |
---
## 13. Milestones
Each is small, ends with a green gate, and no milestone depends on browser UI before M4.
- **M1 - Port geometry + tests.**
- Scope: new repo layout (`server/`, `tools/`, `tests/`), devbox config, `geometry.nim` + `tgeometry.nim`, mutation script, add mutation (d) and the shared-endpoint arm test.
- Accept: `nimble test` green: M1 port baseline 33 test blocks / 98 checks, none dropped (plus new tests on top; current count in `results/nimble-test.log`); mutations a-d each fail >= 1 test (M1; M2 adds e-o in `tools/mutation.sh`), control passes; repo builds with devbox only.
- **M2 - Vision engine v2 and move rules** (decisions in 5.5, recorded 2026-11-08).
- Scope: scanline `cellsTouched`, differential + independent explored oracle tests, radius-bbox wall cull (spatial grid only if the 5k bench misses), capsule/swept move check and token-on-wall escape (5.5), step cap = effective vision radius (5.5), `blocked` flag with circle-overlap trigger and Set/Keep/Clear policy (5.5), GM moves ignore walls and step cap (and set/clear `blocked`), bench harness incl. 5k-wall scene, pure in-process move-rules module with unit tests. The WS/hostile-client harness is M3, not M2.
- Accept: `visibilityPolygon` and `cellsTouched` equal the old implementation on the corpus (5.5); `moveBlocked` excluded (its results change on purpose); polygon+cells bench <= prototype (0.451 ms) on the prototype scene and polygon < 1 ms on the 5k-wall scene [targets PROPOSED]; in-process probing test passes; escape and capsule positive and negative unit tests pass; door-push tests pass (each side, centre on the line uses the previous side, other-side fallback for a blocking wall and for out of bounds, both invalid -> blocked and opening frees it, GM-owned token pushed, wall add still sticks); `blocked` tests pass (every Set/Keep/Clear rule of 5.5: overlap trigger, doorway, two overlapping walls, GM drop/move sets and clears, GM clear then escape, unrelated change does not re-block); mutations k (no Keep), l (GM moves do not set blocked), m (push to the wrong side), n (push skips the validity check) and o (previous side ignored) each fail >= 1 test; over-cap move gives the same nack as a blocked move; thresholds documented in the module header; oracle tolerance 0.5 px. The KNOWN LIMITATION test and the Q14 pin test are replaced with positive assertions and `blocked`-policy tests.
- **M3 - Server core.**
- Scope: entities with bucketed props, characters with names, name reveal and encountered list (8, #14), players, player keys/sessions, scenes, chunked explored persistence, typed per-recipient views and single egress, per-connection counters, proto versioning, the wire catalogue of 6 (29 intents, 15 server messages), wall/token/character CRUD intents, Origin check, plaintext player keys and non-expiring sessions (Q10, Q11), SQLite schema + migrations. `scene.set` is the one scene-writing intent (6.1 payload rules) and completes the 29-intent catalogue (#25). Tile gate `/tiles/` (3.3), fixture tiles at 32 px generated at test time by a helper (not committed), minimal local test nginx with internal `/_tiles/` (production vhost and tile import CLI stay M6) [FIXED, owner decision 2026-11-14, #7]. Black-box harnesses ported to `tools/` on Node 26; `devbox run test` runs Nim then Node (10.4) [FIXED, owner decision 2026-11-14, #9].
- Accept: `devbox run test` green on a clean checkout, and that run includes the nine named groups below; details live at the § refs, not here. Out of M3 accept: concurrency (M5), 127.0.0.1 bind check (M6 deploy) [FIXED, owner decision 2026-11-14, #12].
1. **leak+fault**: ported leak test A and B; fault test catches every class with exact class sets, incl. characters and names; clean build passes (10.1, 10.3).
2. **tiles**: Tile gate: leak test (d) and smoke tile-steal checks pass through the test nginx; gate decisions match the independent explored oracle (10.2); direct `/_tiles/` fetch -> 404; malformed or out-of-range path -> 404; unexplored -> 403 [FIXED, owner decision 2026-11-14, #7]. **Built by slice 9 (#24):** `tools/tiles.test.mjs` (three tests: the oracle sweep of 1024 tile requests through the test nginx, the full refusal/path matrix plus direct `/_tiles/`, and the generated-fixture/no-committed-PNG check), with `tools/nginx.mjs` and `tools/tilefixture.mjs`; the decided URL grammar and status split are in 3.3.
3. **probing**: M2 in-process probing test (T8, H26) re-run over WS with a hostile client (10.3, 5.5).
4. **protocol**: proto mismatch refused, unknown type rejected, oversized frame rejected, malformed flood closed, rate limit hit, connection cap enforced (10.3, T10, 6.2, 6.5; codes and close codes in 6.5; limits and numbers in 4.3 (connections) and 6.4 (frame, intent rate) [FIXED, owner-delegated, #15]).
5. **auth**: key create; key replace (old sessions and live connections closed); remove player; one key on several devices; Origin mismatch rejected; cookie flags present (T7, H9, 3.2, 10.3).
6. **characters and names**: as #14 (10.3). Built by slice 8 (#23): `tools/characters.test.mjs` (ten tests: `player.setname` + `roster`, `player.rename` + `key.show`, `character.create`, reveal per player and `reveal_all`, a plain token's own names and `cprops`, `reassign` leaving controllers alone, `update`/`remove` with `in-use`, the encountered list and `encountered.remove`, the status source, and a restart), plus the four new fault classes in group 1.
7. **restart**: identical state after restart, incl. CRUD (10.1). **Built by slice 10 (#25):** `tools/restart.test.mjs` (two tests: full-state equality over SIGTERM and over SIGKILL, every CRUD path in one world; details in 10.3).
8. **persistence**: explored chunks round trip; old DB migrates to new (H13, 4.4, 10.3; migrations are PROPOSED in 4.4).
9. **logs**: no secret in any log; the test greps the logs for every key and session value it used (T6, 11.3 PROPOSED). **Built by slice 10 (#25):** `tools/logs.test.mjs` (two runs incl. a GM-key rotation, keys/sessions/hashes, and a `keylog` leak-fault negative control; details in 10.3).
- **M4 - Client v1.**
- Scope: new `client/` dir (first real client build): Vite + TS + Pixi v8 client: layers, tiles, grid, tokens (BitmapText), character list, encountered list (greyed), reveal buttons (#14 UI; server side in M3), fog textures, wall editor with presets (5.8), token drag with prediction/rollback, DOM overlay, reconnect backoff, reducer tests; after the client port, archive `prototype-*` dirs (Q24).
- Accept: headless e2e: fog pixel checks, player traffic audit clean, reconnect restores; manual run on laptop and Note 10 at 60 fps with 50 tokens, 16384 px map (tiled; PROPOSED test target, Q2), fog active.
- Tile-size gates [FIXED, Q4]: (a) automated headless-Chromium test with mobile emulation (viewport, dpr, CPU + network throttle) against the real server path (nginx HTTP/2 + caching): viewport fills in < 1 s at zoom 1; (b) one manual run on the owner's 5-year-old Android phone (worst-case reference). If either fails: `tile_size` 64 px (per-scene config, no code change). The 2026-11-08 prototype phone run (`prototype-tile-leak/README.md`) is evidence, not the gate: HTTP/1.1, no-store, zoom 0.5 only, first cold load up to 3.3 s.
- **M5 - Robustness and observability.**
- Scope: SIGTERM handler, bounded metrics + SLOW lines, connection cap, frame/rate limits, per-client bounded outbox with coalescing and Ping(seq)/Pong lag tracking (Q13, 4.3), verify `/ws` goes through nginx and its timeouts, healthz.
- Accept: concurrency 60 s x3 pass with p99 <= prototype (4.98 ms) +50%; slow-client test: client that stops reading -> outbox stays under cap, RSS flat, no further state queued to it, full resync on recovery equals a fresh connection; nginx closes a dead `/ws` within its configured timeout (measured); stats computation shown outside the lock (lock hold time unchanged with metrics on, measured).
- **M6 - NixOS deployment.**
- Scope: `nix/` dir per Q20: un-ignore `nix/` in `.gitignore`; `lock.json` (nim_lk), `package.nix` (buildNimPackage, nixpkgs pinned to devbox Nim 2.2.12, mummy tag 0.4.8), `module.nix` (`services.fffVtt`); declare a nimble `bin` in `fff_vtt.nimble` (nim_builder builds only `bin` entries, so the package is empty without it); client build; nginx vhost; systemd hardening; backups timer (Q21), restore drill, import CLI for maps (slices at `tile_size`, Q4).
- Accept: deployed behind HTTPS on the owner's server; `/_tiles/` 404 directly; WS upgrade works; player key sign-in works from phone; access log has no secret; backup + restore drill passes.
- **M7 - Real-world pass.**
- Scope: real-network latency/throughput run, iOS/Safari check (if available), one real session with the owner's table, collect SLOW lines.
- Accept: documented numbers; defects triaged to issues; go/no-go for v1.
- **M3 build slices** [FIXED, owner decision 2026-11-14, #13]: vertical slices, each runnable end-to-end with its own test. Order and blocking: each slice blocked by the previous, except 9 (blocked by 5 only) and 10 (blocked by 1-9). Open technical details (DDL, property-schema registry format, config keys, redaction mechanism) are decided by the builder inside the slice that needs them and recorded here as FIXED (owner-delegated).
1. Bare server (#16) 2. Getting in (#17) 3. Talking safely (#18) 4. Walls and doors (#19) 5. Tokens and sight (#20) 6. Explored persistence (#21) 7. Token details (#22) 8. Characters and names (#23, done) 9. Map tiles (#24, done) 10. Finish line (#25, done).
- **Post-v1 candidates**: FFF seam implementation (section 9), drawings/pings/ruler, chat/dice (order decided at M7, Q8), light sources, browser upload UI (Q5), multi-scene (Q3), vision deltas/binary protocol (Q16).
---
## 14. Open questions for the owner
1. Q1 - Table size and device mix: how many players max, and which devices (phones, tablets, iOS)? Drives iOS testing priority and token/message budgets. **RESOLVED [FIXED (owner decision), 2026-11-08]:** devices are phones, tablets and laptops. Max players: 6 [FIXED, owner decision 2026-11-08] (section 1). Connection cap 8 (6 players + GM + headroom) stays [PROPOSED] (sections 4.3, 13).
2. Q2 - Largest map you plan to use (px), and typical wall count per scene? Drives tile size, spatial grid priority and explored chunking. **DEFERRED [FIXED (owner decision), 2026-11-08]:** owner does not know yet. 16384 px map and 5k walls stay [PROPOSED] test targets; revisit with real maps.
3. Q3 - Multiple scenes in v1 (GM switches the active scene, per-scene explored grids), or exactly one scene per table to start? **RESOLVED [FIXED (owner decision), 2026-11-08]:** exactly one scene in v1; schema may stay `scene_id`-keyed.
4. Q4 - Tile-edge leak: accept as documented, or reduce it (smaller tiles = more requests; gate tiles only when explored cells cover a minimum fraction; or server-side masked tiles at the cost of image processing in Nim)? What detail do you paint in map art that must stay secret? **RESOLVED [FIXED (owner decision), 2026-11-08]:** `tile_size` = explored cell size = 32 px. Residual leak is at most one cell, never revoked; no server-side masking. Authoring rule shrinks from ~256 px to ~32 px. M4 acceptance: (a) headless mobile-emulation test on the real server path, (b) one manual phone run; fallback 64 px (per-scene config). Evidence: `prototype-tile-leak/README.md`. Applied in 3.3, 3.4 (T5), 8, 12 (H8), 13 (M4, M6).
5. Q5 - Map import: CLI-only for v1, or upload + tiling from the browser (GM) from the start? **RESOLVED [FIXED (owner decision), 2026-11-08]:** map import is CLI-only in v1; browser upload is post-v1.
6. Q6 - Wall/door authoring: is an in-browser GM wall editor required in v1 (no generator feeds in), or is hand-edited/imported wall data acceptable at first? What other wall kinds are needed soon (windows, one-way, secret doors, locked doors)? **RESOLVED [FIXED (owner decision), 2026-11-08]:** in-browser GM wall editor in v1; wall kinds `wall` and `door` only. **Kind set SUPERSEDED [FIXED (owner decision), 2026-11-15, #42]** by 5.8: a wall's behaviour is independent switches and named kinds are presets; v1 presets are `wall`, `door`, `secret door`, `locked door`, `terrain` and `one-way wall`, with no `window` preset until #47 gives windows a rule. The editor requirement is unchanged.
7. Q7 - Vision model: single radius per token or per-token property from day one? Is any "darkvision/light" concept needed before FFF? **RESOLVED [FIXED (owner decision), 2026-11-08]:** per-entity numeric `vision_radius` plus scene default; no light sources or darkvision.
8. Q8 - Which "table convenience" features come first after v1, if any: freehand drawing (exists in the perf prototype), pings, ruler, chat, dice, token images/portraits, initiative tracker? **DEFERRED [FIXED (owner decision), 2026-11-08]:** decided at M7.
9. Q9 - Should players see each other's names/presence, and should party members share vision (shared explored/LOS) or is it strictly per player? **RESOLVED [FIXED (owner decision), 2026-11-08]:** vision and explored strictly per player; player names visible to all.
10. Q10 - Session lifetime and invite policy: session expiry, how often invites rotate, single-use vs reusable invite links, can one player use multiple devices at once? **RESOLVED [FIXED (owner decision), 2026-11-08]:** sessions never expire; one player key is usable on multiple devices (wording amended #6: was invite link).
11. Q11 - Invite secrets: stored hashed (shown once, GM regenerates to re-share) or stored plaintext so the GM can re-copy a link? **RESOLVED [FIXED (owner decision), 2026-11-08]:** player and GM key secrets stored plaintext so the GM can re-show them (wording amended #6: was invite secrets).
12. Q12 - Durability: is `synchronous=NORMAL` (can lose the last few commits on power loss/OS crash, never corrupts) acceptable, or should it be FULL for some or all writes? **RESOLVED [FIXED (owner decision), 2026-11-08]:** `synchronous=NORMAL`; `FULL` around GM authoring transactions.
13. Q13 - Slow/dead client policy: acceptable to disconnect clients that fall behind? Willing to patch/fork the pinned mummy commit if per-socket queue depth cannot be read from outside? **RESOLVED [FIXED (owner decision), 2026-11-08]:** option A: app-level bounded per-client outbox, latest-state-wins coalescing per key (MQTT-retained-like), diff at flush time, server Ping(seq)/Pong ack tracking for lag, stop feeding lagging clients + full resync on recovery; no mummy patch. Dead/stuck peers closed by nginx proxy timeouts (mechanism PROPOSED; verify WS goes through nginx in M5). Fork of mummy (option B) is fallback only, not planned. Research: `docs/research/q13-mummy-slow-clients.md`; detail in 4.3.
14. Q14 - Moving tokens when walls change: what should happen if the GM closes a door (or edits a wall) on top of a token? Allow the token to walk out, auto-nudge it, or refuse the edit? **RESOLVED [FIXED (owner decision), 2026-11-08]:** a GM edit that lands on a token gives it status `blocked`: server refuses that token's player moves; GM can still move it; status clears when the wall is removed or the door opened, or when the GM clears it. **Door case revised [FIXED (owner decision), 2026-11-08]:** spell walls and wall edits stay stuck; a door closing on a token pushes the token aside (5.5), stuck only if neither side is valid. Status names superseded by #4 (2026-11-10): `blocked` is now `stuck`/`squeezed` (5.5); door-push failure is `squeezed`.
15. Q15 - Reconnect: is a full resync on every reconnect fine up to what explored/state size, or do you want `resume since N` later? **RESOLVED [FIXED (owner decision), 2026-11-08]:** full resync on every reconnect; revisit if a measured snapshot exceeds ~100 KB.
16. Q16 - Vision payload: OK with full polygon per move (~3.4-3.7 KB per mover delivery, measured on loopback) for v1, or do you want deltas/binary earlier (e.g. for mobile data plans)? **RESOLVED [FIXED (owner decision), 2026-11-08]:** full vision polygon, integer px, sent only on change; deltas post-v1.
17. Q17 - Names/labels: which character sets must labels support (Latin only, accents, non-Latin, emoji)? Affects BitmapText glyph atlas vs Text/HTMLText. **RESOLVED [FIXED (owner decision), 2026-11-08]:** labels in Latin incl. accented characters plus Nerd Font icon glyphs.
18. Q18 - Grid and movement: snap to grid on drop? Any server-side speed/distance limit per move, given there are no rules yet? **RESOLVED [FIXED (owner decision), 2026-11-08]:** grid snap off by default (client option); server step cap = token vision radius.
19. Q19 - FFF engine: implementation language/runtime, current maturity, and whether it should run inside the VTT server process, as a sidecar, or in the browser for display only? Does it need hidden/secret state beyond the three property buckets (public / owner / GM)? **RESOLVED for hidden state [FIXED (owner decision), 2026-11-08]:** no hidden state beyond the `public`/`owner`/`gm` buckets and `gm_only` flag in v1; revisit when FFF starts (schema change accepted then). Engine language, runtime and location: **DEFERRED** to FFF start (section 9 options a/b/c; no decision now).
20. Q20 - Nix packaging: how do you want the Nim server built (nimble lock + `buildNimPackage` or a vendored deps approach), and which repo hosts the NixOS module (this repo or your nixos-configuration repo)? **RESOLVED [FIXED (owner decision), 2026-11-08]:** `buildNimPackage` with a committed `nix/lock.json` (`nim_lk` JSON lock). `nix/package.nix` and `nix/module.nix` (`services.fffVtt`) live in this repo and are imported from the owner's server NixOS config, like `foundryvtt.nix`. nixpkgs input pinned to match devbox Nim (2.2.12). Fallback: vendored deps if `nim_lk` cannot resolve the mummy pin. `nix/` un-ignored in `.gitignore` when M6 starts, not now. mummy pinned to tag `0.4.8` (same `src/` as `01deb1ff`). Research: `docs/research/q20-nix-packaging.md`; detail in 11.1.
21. Q21 - Backups: where should off-box backups go (existing mechanism on the server?), and how many dated copies to keep? **RESOLVED [FIXED (owner decision), 2026-11-08]:** v1 backups go to a backup folder the server creates under its data root; off-box backups out of v1 scope.
22. Q22 - Observability: journald lines only, or also an internal metrics endpoint scraped by something you run? **RESOLVED [FIXED (owner decision), 2026-11-08]:** journald lines only; `/healthz` stays.
23. Q23 - Public exposure: reachable from the internet (domain, rate-limiting, fail2ban expectations) or LAN/VPN only? **RESOLVED [FIXED (owner decision), 2026-11-08]:** network exposure and access are out of project scope (owner handles reachability). Built-in protections stay (127.0.0.1 bind, connection cap, frame/rate limits, Origin check); internet-only hardening (fail2ban etc.) not in scope.
24. Q24 - Repo conventions: should this design live in `docs/DESIGN.md` plus ADRs under `docs/adr/` and a `GLOSSARY.md` (AGENTS.md references both, neither exists yet)? Should prototypes remain in-tree or move to an archive branch once ported? **RESOLVED [FIXED (owner decision), 2026-11-08]:** `GLOSSARY.md` and `docs/adr/` per AGENTS.md; prototypes stay in-tree until the M4 client port, then archived.
Owner also decided 2026-11-08 [FIXED (owner decision)]: restore drill belongs in M6 (sections 11.2, 13).
Owner also decided 2026-11-08 (M2): move rules, `blocked` trigger and GM move bypass are recorded in 5.5; M2 scope and accept criteria in 13.
Owner also decided 2026-11-10 [FIXED (owner decision), #14]: characters are separate records from tokens (one owner: a player or the GM; a token may link to one character; token controller is independent of the character owner); character holds identity, token holds the state of the figure; descriptive and actual names, revealed per player or to all; per-player encountered list, persisted, removed only by the GM; storage on the server only (SQLite). Character export/import as a file is future, not M3. See 3.1, 4.4, 8.
Owner also decided 2026-11-10 [FIXED (owner decision), #6]: one shared site link (alone it shows only the sign-in page); each player has a personal player key, generated by the GM with no name, identifying the player and granting access to their data. The player types their display name at first sign-in; names are unique among players; the GM can rename. The GM signs in the same way with a GM key printed by `fff-vtt gm-key` (replaces `gm-link`, #5; rest of #5 unchanged). The GM can replace a player's key at any time while the server runs: old key invalid, all that player's sessions revoked, live connections closed; identity, characters and encountered list kept; no name re-prompt. Removing a player: key invalid, sessions revoked, connections closed; their characters and controlled tokens pass to the GM; name and slot freed; encountered list deleted. Defaults accepted: one key on many devices; sessions never expire; keys stored plaintext; 20-character key in groups of 4 with dashes, no look-alikes, CSPRNG (~100 bits); 6-player cap counts unused keys; sign-in sets the session cookie as in 3.2. No rate limit or lockout on key entry (owner rejected guessing protection). Rejected: per-person invite links; GM types the name at key creation; delete-and-reinvite only; deleting characters with the player; shared-link visit creates a player; separate GM link path. Terms: "player key" and "GM key"; "token" stays reserved for map figures. Message names: #11.
Owner also decided 2026-11-14 [FIXED (owner decision), #7]: map tiles in M3. The tile gate (`/tiles/`, Nim, `X-Accel-Redirect`) and a minimal local test nginx with generated 32 px fixture tiles are M3 scope; tile import CLI and the production nginx vhost stay M6. Tile URLs carry `art_version` from M3 (always 1 in M3); responses are `Cache-Control: private`; malformed or out-of-range paths get 404, unexplored tiles 403. The gate reuses the server's explored-area logic, checked against the independent oracle (10.2). On-disk layout `<state>/tiles/<scene>/v<art_version>/` fixed in M3. See 3.3, 11.1, 13.
Owner also decided 2026-11-14 [FIXED (owner decision), #9]: test tools. Black-box WS/HTTP harnesses are Node 26 only (repo-root `tools/`, built-ins and `node:net` for raw frames, `node:test`, no npm deps), ported from the prototype; no Nim rewrite. In-process tests stay Nim. Root devbox pins nodejs 26; `devbox run test` runs Nim then Node. Browser e2e details stay open (M4). See 2, 10.4, 13.
Owner also decided 2026-11-14 [FIXED (owner decision), #12]: what M3 done means. Done = `devbox run test` green on a clean checkout, with the nine named groups in 13 (M3 Accept), each pointing to its details in 10.3, 3.4, 5.5 and 6. Concurrency moves to M5 and the 127.0.0.1 bind check to M6 deploy. Protocol limits (frame size, intent rate, connection caps) are a separate open card, "M3 limits", not decided here. See 10.3, 13.
Owner also decided 2026-11-14 [FIXED (owner-delegated, 2026-11-14, #15)]: M3 limits. The owner delegated the numbers to the agent and accepted the set. Max inbound WS message 64 KB (mummy default; inbound only; no config). Intent rate: token bucket per connection, 30/s sustained, burst 100, same for GM and players; excess refused with `rate limited`, no rollback (each intent atomic), connection stays open. Connections: 4 per player (a 5th closes the oldest), 16 total (the 17th is refused); replaces the PROPOSED cap of 8. Consequence: the M5 concurrency port spreads load across connections (10.1). See 4.3, 6.4, 10.1, 13.
Owner also decided 2026-11-14 [FIXED (owner-delegated, 2026-11-14, #11)]: M3 message list. The owner delegated the wire shapes; the set is the complete M3 catalogue in 6 (29 client intents, 14 server messages, 15 with #18's `closing`). Client `t` is `<noun>.<verb>` (GLOSSARY nouns: `token`, never "entity"), server `t` is a dotless state noun, so they never collide. Every intent carries `reqId` and gets exactly one `ack` (`ok`, new `id`, `pos` for moves); a refused player move stays the uniform nack (old position, no code), every other refusal has a static code (`rate-limited`, `not-allowed`, `not-found`, `invalid`, `name-taken`, `cap-reached`, `in-use`, `no-rules`, `unknown-type`); frames without a readable `reqId` get `error` (`malformed`, `rate-limited`). `invite.*`, `gmClearBlocked` and `blocked` are retired: `key.*`/`player.*` for player keys and players, `status.set`/`status.clear` and `token.resize` for #4. Connection outcomes: HTTP 403 (Origin), 401 (no session), 400, 503 (17th connection); WS close 4001 revoked, 4002 evicted (5th connection), 4003 proto mismatch, 1008 malformed flood; oversize closes TCP with no frame. `POST /join` is HTTP (6.6). Server `door` is folded into `wall`; `presence` into `roster`; `pong` into the ping `ack`. See 3.1, 3.2, 3.4, 4.2, 4.3, 5.5, 5.6, 6, 7.5, 13.
Owner also decided 2026-11-14 (review of #11 flags) [FIXED (owner decision)]: (1) players cannot create or edit characters or props in v1 (GM only); opening that later is a permission change on the existing intents, not a redesign (1). (2) A revealed name cannot be un-revealed: no un-reveal intent (8, 6.1). (3) `character.remove` is refused with `in-use` while tokens link the character (6.1, 6.5). (4) Encountered stays encountered: a `gm_only` flip leaves the entry, greyed (8, 6.1). (5) Status markers do not reveal their cause to non-GM viewers: `statuses[].source` goes to the GM only (3.1, 5.5, 6.1; amends #4). The controlling owner is not given `source` either, as the doc has no owner-view rule for statuses; revisit if wanted.
Owner also decided 2026-11-14 [FIXED (owner-delegated, 2026-11-14, #17)]: M3 slice 2 ("getting in"). Storage is migration step 2 (`auth`): `player`, `player_key`, `session`, a single-GM partial unique index, cascading deletes (4.4). Players/keys/sessions: 3.2 and 8. Cookie `fff_session`, `POST /join` as in 6.6. `fff-vtt gm-key [--new]` and the `<stateDir>/instance.lock` fcntl lock with exit 3 are recorded in 3.2/11.1. Slice 2 implements only the three GM intents auth needs (`key.create`, `key.replace`, `player.remove`) with the 6.1 ack shape; the rest of the envelope, error frames, rate limits and unknown-type answers stay slice 3 (#18). The application close codes of 6.5 are not expressible at the mummy pin (3.2); slice 3 decides. See 3.2, 4.4, 6.5, 6.6, 8, 11.1, 13.
Owner also decided 2026-11-15 [FIXED (owner decision), #18]: close codes at the mummy pin, option A. Mummy 0.4.8 cannot send an application close code (`close(ws)` -> an empty close frame -> the browser sees 1005); mummy is not forked or patched for it. Every server-initiated close is preceded by exactly one `closing {reason, code}` message carrying the reason of 6.5, then the close frame; a client treats 1005 plus that last message as the reason. `closing` is a catalogue message (server -> client, dotless noun) and the catalogue count is 15. Slice 2's eviction and revocation paths send it. Also recorded FIXED here: the server Ping interval (20 s, plus one right after `hello`; lag enforcement stays M5), the per-connection `n` rule (server frames only, no number for Ping/Pong, no global counter), the own `maxMessageLen` (64 KB) rather than mummy's default, and the slice-3 rollout note that catalogue intents whose slice has not landed answer `unknown-type`. See 3.2, 4.3, 6, 6.1, 6.2, 6.4, 6.5, 10.3.
Owner also decided 2026-11-15 [FIXED (owner-delegated, 2026-11-15, #19)]: walls and doors (M3 slice 4). Schema is migration step 3 (`world`): `scene` and `wall`, with the single v1 scene seeded at `id 1` (4096x4096, tile 32 = cell 32, no grid, vision 400, token radius 20, art_version 1, `next_wall_id` 1) (4.4). Wall ids are per scene from `next_wall_id`, monotonic and never reused across removal or restart (#3). The four intents `wall.add`/`wall.update`/`wall.remove`/`door.set` are GM-only and answer the 6.1 acks; the payload rules 6.1 left open are fixed there: integer `scene` (else `not-found`), `a`/`b` finite and in bounds with `a != b`, `open` boolean and never true on a plain wall, `flags` an object (default `{}`), `wall.update` patches only `a`/`b`/`kind`/`flags` and needs at least one, `door.set` on a non-door is `invalid`, fields before lookup. Effects: `wall`/`wall_gone` to every GM connection only, and a `walls` snapshot right after `hello` on a GM connection; players never receive wall data in any message (3.1, T2). Every wall write is one transaction with `synchronous=FULL` (Q12) and memory follows COMMIT, so a restart reloads exactly what was acked. See 4.4, 6.1, 6.3, 8, 10.3.
Owner also decided 2026-11-14 [FIXED (owner-delegated, 2026-11-14, #16)]: M3 slice 1 groundwork ("bare server"). Config keys, defaults, precedence and the canonical origin: 11.1. Migration history DDL, the agreement/contiguity rule and one-transaction-per-step: 4.4. Secret redaction (value registry plus sensitive field names, minimum secret length 8): 11.3. `GET /healthz` answers `200 {"status":"ok"}` from slice 1; the lock-bounded health check stays M5: 6.6, 11.3. `devbox run test` runs `nimble test` first and only then `node --test tools/*.test.mjs` (10.4); both logs land in `results/`. The server's listen address is the constant `config.BindAddress` = `127.0.0.1`, not a config key (T15). Dependencies: `fff_vtt.nimble` requires `mummy == 0.4.8` and `db_connector == 0.1.0`; devbox adds nodejs 26 and sqlite (`out`+`bin`, with `LD_LIBRARY_PATH=$DEVBOX_PACKAGES_DIR/lib` for the dlopen). Node 26 `{headers}` re-check: 10.4.
Owner also decided 2026-11-15 [FIXED (owner-delegated, 2026-11-15, #20)]: tokens and sight (M3 slice 5). Schema is migration step 4 (`tokens`): `entity` as listed in 4.4, no `radius`/props/`character_id` columns yet (slices 7-8 add them, `entity_status` with slice 7, `explored_chunk` with slice 6). Token ids are 12 random characters from `[A-Za-z0-9_-]` (a 64-symbol alphabet, so 6 uniform bits per character, 72 bits) from `std/sysrand`, collision-checked against every loaded token. The token payload rules 6.1 left open are fixed in 6.1 ("Token payload rules"); the load-bearing ones are: plain tokens only, `radius`/`props`/`character_id` refused `invalid` rather than dropped, effective radius = the scene default, the wire `name` is always the descriptive name, `controller: null` is the only GM spelling, and `explored` on connect is RLE rows. **Modules**: `server/tokens.nim` (records, validation, write-through persistence with FULL for GM authoring and NORMAL for moves), `server/vision.nim` (per-player polygons, explored set, the one copy of the visibility rule), `server/views.nim` (the single egress: typed `GmView`/`PlayerView`, then frames, then the per-connection diff), `server/worldmap.nim` (records -> geometry/move-rule inputs), `server/faults.nim` (test-only hook). `main.nim` holds the state (`tokens`, `visions` per player, `known` per connection keyed by app connId) and never builds a state frame itself, so raw world state has no path to a socket outside the egress (2, 10.1). **Egress timing**: a mutation's ack and its per-recipient diffs are enqueued under the global lock, in that order, and every frame is built from the state at enqueue time (mummy's `send` only appends to its deque, 4.3). Exact per-connection ordering between two concurrent mutations, and the coalescing that keeps that cheap, stay the M5 outbox. **Runtime rules**: polygons exist only for tokens a player controls that carry the `vision` flag, with the token's `vision_radius` or the scene default; only their token centres count for visibility; explored is the union of `cellsTouched` over history, only grows, drops cells outside the world, and the `fresh` set is cleared after one egress fan-out. A door closing pushes tokens aside (5.5) and persists the new positions; `stuck`/`squeezed` are slice 7's status model, so a failed push leaves the token overlapped and unflagged for now. `token.move` maps the move rules to the wire exactly: `ack {pos}`, the uniform nack for locked/over-cap/collision and for an out-of-bounds GM move, and `not-allowed` (players, one code for unknown and not-yours) or `not-found` (GM) before any geometry runs; accepted moves are persisted with NORMAL durability. `hello` carries the scene block for every named recipient and `extra` for the GM; an unnamed player still gets only `proto, role, me` and is not fed any state at all (6.3), so slice 5's player-side acceptance is reached through a harness fixture that writes the name into the DB before connecting: `player.setname` is slice 8 (#23) and the unnamed gate itself is pinned by `tools/tokens.test.mjs`. **Tests** (10.1, 10.3): `tools/leak.mjs` builds a 27-group scene over the real wire (enter/leave by movement, a closed door, create/remove, `gm_only`, a controller hand-over, another player walking in and out, a wall added and removed, a door push) and records every frame; `tools/leakcheck.nim` replays it with the GM socket as truth, recomputes polygons from `geometry.nim`, and checks explored against both that recomputation and an independent clear-segment sampler; A and B both pass with zero failures. `tools/fault.test.mjs` catches `hidden`, `gmOnly`, `walls`, `withhold`, `otherOwner`, `otherVision`, `otherExplored`, `noremove` and `explored` under their exact class sets and asserts the shipped binary contains no `LEAK_FAULT` string. `tools/probing.test.mjs` re-runs T8/H26 over WS: over-cap probes give the one uniform nack, two scenes differing only beyond cap + token radius produce identical reply sequences over 90 hostile probes inside the 6.4 burst, and a wall inside that bound does change the replies. Nim units: `tests/ttokens.nim`, `tests/tvision.nim`, `tests/tviews.nim`. Mutations aa-af pin the view rule, the egress `token_gone`, the absence of GM-only fields in a player frame and the "explored only grows" rule.
Owner also decided 2026-11-15 [FIXED (owner-delegated, 2026-11-15, #22)]: token details (M3 slice 7). Schema is migration step 6 (`token details`): the three prop buckets on `entity` and `entity_status` (4.4). Intents: `token.resize`, `status.set`, `status.clear`, `prop.set`, `prop.unset`, all GM-only in v1 (6.1; owner-bucket writes by players come with FFF actions, 9, and are a permission change, not a redesign). The payload rules 6.1 left open are fixed in 6.1: the status set and its `source`, the three-bucket caps (64 keys, 1..64-char keys, 8 KB values, per bucket), the property-schema registry (empty at start with a permissive fallback, so v1 accepts any key in any bucket because 8 says the server never interprets props; a registered key is enforced) and the grow-push search. **Modules**: `server/props.nim` (buckets, caps, registry, parsing), `server/moverules.nim` (the status model replaces the M2 `blocked` bool: `stuckWalls`/`squeezedWalls` are the `walls` source, `locked` is the caller's "any entry" bit, per-token radius everywhere, `resizeToken` with the grow search, `placeToken` for GM placement/move), `server/text.nim` (the one copy of the 6.5 text rule, shared by names and prop keys), `server/tokens.nim` (statuses and props on the record and in the row), `server/worldmap.nim` (`ruleToken`/`ruleWall`/`applyOutcome`/`wallsStatuses`: the bridge between the record's entry set and the rules' two booleans), `server/views.nim` (typed per-recipient statuses and buckets). **One rule, one place**: every wall/door edit and every resize runs the pure rules on a snapshot taken *before* the write, then the write, then `applyRuleOutcome` (positions and `walls` statuses in one `NORMAL` transaction, memory after COMMIT); `token.create` computes the placement status before writing the row, so a new token is born with `stuck` if it lands on a wall. Status sources are owned by different layers on purpose: the rules never see `GM` entries, the record never derives `walls` entries. **Tests** (10.1, 10.3): `tests/tprops.nim` (caps, key/value rules, registry enforcement, set/unset, clone isolation), `tests/ttokens.nim` (radius, buckets, statuses round trip, the FK cascade), `tests/tmoverules.nim` (per-token radius, shrink/grow/squeeze, the no-crossing rule, the source independence), `tests/tviews.nim` (bucket and source filtering, one `token` frame per change), `tools/details.test.mjs` (the five intents' acks and codes, grow push and squeeze, stuck/clear, prop caps, who reads which bucket, restart equality), plus the leak scenario's prop/status groups and the `OWNER_PROP`, `GM_PROP`, `STATUS_SOURCE` faults. Mutations am-au pin the bucket filter, the per-bucket cap, the status set/clear, the shrink/grow rules and the push. See 4.4, 5.5, 5.6, 6.1, 8, 10.3.
Owner also decided 2026-11-15 [FIXED (owner decision), #22]: the property-schema registry of 6.1 is confirmed as the agent specified it — v1 ships the registry **empty with a permissive fallback** (`pkAny`), so any key is accepted in any bucket and only a registered key is enforced, which matches 8's "the server never interprets props in v1". **Strict mode comes with the FFF seam (post-v1)**, where the rules module registers every key it uses; flipping the fallback is a one-line change and no v1 payload, wire shape or test changes. **[amended 2026-11-15, #41: the v1 registry is no longer empty — `height` and `eye_height` are registered (`number`, `gm`, 5.7); the rest of this entry stands]**. The rest of the #22 token-details decisions stay owner-delegated.
Owner also decided 2026-11-15 [FIXED (owner-delegated, 2026-11-15, #23)]: characters and names (M3 slice 8). Schema is migration step 7 (`characters`, 4.4): `character`, `name_reveal`, `encountered`, plus `entity.character_id` and `entity.reveal_all`. The decisions 4.4 leaves open are recorded there and the wire rules in 6.1 ("Character and name payload rules"): one id namespace for tokens and characters, an owner that never dangles (`player.remove` transfers to the GM first), an encountered entry with no FK that outlives everything, a linked token that stores `''` names, and `character_id`/`cprops` on the token frame with the ownership rules of 6.1 leak notes 2-3. **Modules**: `server/characters.nim` (records, the name rule, the reveal set, the encountered snapshots, their rows), `server/views.nim` (the typed character and encountered views plus the token-frame additions), `server/tokens.nim` (`characterId`/`revealAll`, the linked-token validation and `sqlLitId`), `server/text.nim` (`normalizedPlayerName`, `validPlayerName`, `sameName`), `server/auth.nim` (`allPlayers`, `nameTaken`, `setName`, `renamePlayer`), `server/main.nim` (`recordEncounters` in every mutation path before the ack, the roster fan-out, `sendHello`/`resync` for `player.setname`). Also fixed here: `protocol.withN` deep-copies before stamping `n`, because the stored diff base was being mutated and every state frame was re-sent on every mutation. **Tests** (10.1, 10.3): `tests/tcharacters.nim` (the name rule, the reveal set, the encounter snapshot, validation, persistence incl. the GM transfer and the `in-use` count), `tests/tviews.nim` (character frames, the owner/non-owner split, `cprops`, `character_gone`, the encountered diff), `tools/characters.test.mjs` (the acceptance group of 13), the leak scenario's ten character/name/encountered groups and the `ACTUAL_NAME`, `CHAR_LIST`, `CONTROLLER_CHANGE`, `CHAR_OWNER_PROP` faults. Mutations av-b4 pin the name rule, the encountered snapshot, the linked-token validation, `in-use`, the GM transfer, the snapshot rename and the `cprops` bucket. See 3.1, 4.1, 4.4, 6.1, 6.3, 6.4, 6.5, 8, 10.3, 13.
Owner also decided 2026-11-15 [FIXED (owner-delegated, 2026-11-15, #21)]: explored persistence (M3 slice 6). Schema is migration step 5 (`explored`): `explored_chunk` keyed by `(player_id, scene_id, cx, cy)` with a 512-byte blob, both FKs cascading (4.4). Chunk format and size are fixed at 64x64 cells = 512 B, row-major LSB-first bits, `(cx, cy)` = chunk coordinates; the layout is pinned by tests and re-read independently by the Node harness. **Write timing**: a mutation writes only the chunks its refresh dirtied, each encoded from the whole explored set, with `NORMAL` durability; a move writes position and chunks in one transaction, a GM authoring write adds a second `NORMAL` chunk transaction under the same lock, both before the ack — the two commits are deliberately not atomic with each other, and the only loss they can cause after a crash is cells no client was acked about, which the next refresh re-adds. Measured: 0.015 ms avg / 0.035 ms p99 per chunk write, 0.7 ms avg / 1-2 ms p99 per move ack (4.3's budget is untouched). **Load**: `explored.restore` fills every player's set at startup from the chunk rows and logs `explored_loaded players= chunks=`; polygons stay recomputed (8). **Tests** (10.1, 10.3): `tests/texplored.nim` (format, whole-chunk encoding, upsert replacement, per-player keying, restore, cost) and `tools/persistence.test.mjs` (fresh-resync round trip, per-player isolation, SIGTERM and SIGKILL restart equality, wall-removal cells surviving after the wall returns, chunk rows decoded independently, move-ack timing, and a schema-4 fixture DB migrated by the real binary). Mutations ag-al pin the bit layout, the chunk coordinate, the restore, the per-player key, the upsert and the dirty-chunk dedupe. See 4.4, 8, 10.3.
Owner also decided 2026-11-15 [FIXED (owner-delegated, 2026-11-15, #27-#31)]: five M3 correctness and cost fixes found by review, all owner-authorized to land on `main` with a regression test each. (1) **`name.reveal` is per player on disk too** (#27): the persisted snapshot write took only the subject, so every player who had met the subject got the actual name in their `encountered` row and saw it only after a restart; the write is now scoped by `player_id` and a reveal to one player changes exactly one row. `name.reveal_all` keeps all-players scope through the same helper. (2) **`token.update {character_id}` links a plain token** (#29): the link patch now drops the token's own two names, so the candidate satisfies `validToken`; names supplied *with* a link stay `invalid`, unlinking still needs both names (6.1). (3) **One encountered rewrite path** (#30): `characters.rewriteEncountered` takes the subject's `SubjectNames` plus the reveal set and rewrites every matching snapshot in SQLite *and* in `app.encountered` from the 8 name rule, so a rename, a link change and an owner change reach the live list immediately and the DB never disagrees with the wire. The old DB-only `renameEncountered*`/`revealEncountered*` helpers are gone, which is what let the two stores drift. (4) **Egress borrows the world** (#28): `views.Context` now holds six pointers (`contextOf`/`borrow`) instead of owning copies of `scene`, `tokens`, `characters`, `reveals`, `encountered` and `visions`, `playerView`/`gmView` read a `ptr PlayerVision` instead of `getOrDefault`, and a view computes each player's visible-id set once per frame so `grey` is a set test rather than a token scan plus a `PlayerVision` copy per encountered entry. Measured on this build's types (debug, 6 players, 40 encountered entries, 40 world tokens): context construction 0.227 ms / 4.87 ms at 16384 / 262144 explored cells before, 0.008 us after; one `getOrDefault` of a `PlayerVision` 28.8 us / 591 us before (gone); a GM egress pass 8.0 ms / 142.8 ms before, 0.79 ms / 0.80 ms after; a player pass 1.45 ms / 25.7 ms before, 0.32 ms after. Behaviour is unchanged and pinned by `tests/tviews.nim` (identity: a borrow sees a later in-place mutation; six pointers, no container; both sizes inside the M5 7.5 ms budget) plus the unchanged leak/fault suites. (5) **One scene read per request** (#31): `tileGate` reads `app.scene` once under `dbLock` and uses that local for the URL parse, the explored check and the redirect; `checkScene` reads the scene id under the lock; `scene.set` patches under the lock; the wall/door handlers capture `sceneId` inside their lock for the log and the effect frame. `tests/ttiles.nim` pins that one record gives one whole answer, and `tools/tiles.test.mjs` pins the handler shape (source scan) and interleaves 20 `scene.set` + wall edits with 200 tile fetches (only whole tiles, no crash). **Tests added**: `tests/tcharacters.nim` (per-player reveal row, one rewrite path, link handover), `tests/ttokens.nim`-style `patched` unit (in `tcharacters.nim`), `tools/characters.test.mjs` (link via update end to end), `tools/restart.test.mjs` (three named players + per-player reveals across SIGTERM/SIGKILL, with a direct `encountered` row assertion and a name oracle; a mid-session rename for a plain token and a character), `tools/leak.mjs`/`leakcheck.nim` (a second player meets the same subject; `STALE_NAME` pins each entry's expected name), `tests/tviews.nim` and `tests/ttiles.nim` as above. Mutations e1-e3 and the repointed b2 pin the reveal scope, the live snapshot update and the link handover.
Owner also decided 2026-11-15 [FIXED (owner-delegated, 2026-11-15, #25)]: the M3 finish line. `scene.set` is built as the 29th and last catalogue intent; its payload rules are in 6.1 ("Scene payload rules"), with the decision that `hello` also resets the server-side per-connection diff base (otherwise a resync after `hello` would skip state the client just reset). The two missing accept groups are built: **restart** = `tools/restart.test.mjs` (full 6.3 resync equality over SIGTERM and SIGKILL, every CRUD path) and **logs** = `tools/logs.test.mjs` (every key, session cookie and session hash absent from both runs' log, with a `LEAK_FAULT=keylog` negative control). `tools/groups.mjs` + `tools/groups.test.mjs` map the nine groups of 13 to their named proving tests, so the checklist cannot silently go stale. Fixture clean-up (acceptance 5): `tests/fixtures/scene.json` loses the stale `tileSize: 256`, the scene-wide `tokenRadius` (now a fixture constant, the server has per-token radius, #4) and its index token ids (`A`/`M1`); the geometry/corpus fixture keeps its walls, radii and positions. The `blocked` boolean is already gone from code (`stuck`/`squeezed`, #4). **M3 acceptance checklist (all nine groups, `devbox run test`, measured on the final tree):**
| # | group (13 M3 Accept) | proving test | status |
|---|---|---|---|
| 1 | leak+fault | `tools/leak.test.mjs` (leak A/B), `tools/fault.test.mjs` (exact class sets incl. `ACTUAL_NAME`, `CHAR_LIST`, `CONTROLLER_CHANGE`, `CHAR_OWNER_PROP`) | pass |
| 2 | tiles | `tools/tiles.test.mjs` (oracle sweep through the test nginx, refusal/path matrix, no committed PNG) | pass |
| 3 | probing | `tools/probing.test.mjs` (hostile client over WS, bounded replies) | pass |
| 4 | protocol | `tools/protocol.test.mjs` (proto, unknown type, envelope, flood, rate limit, 64 KB, cap, closing) | pass |
| 5 | auth | `tools/auth.test.mjs` (cookie flags, Origin, devices, key replace, remove, gm-key) | pass |
| 6 | characters and names | `tools/characters.test.mjs` (names, reveals, reassign, in-use, encountered, status source) | pass |
| 7 | restart | `tools/restart.test.mjs` (full state, all CRUD, SIGTERM and SIGKILL) | pass |
| 8 | persistence | `tools/persistence.test.mjs` (chunk round trip, migration, restart, write cost) | pass |
| 9 | logs | `tools/logs.test.mjs` (keys/sessions/hashes across two runs, `keylog` control) | pass |
Out of M3 accept, unchanged: concurrency (M5) and the 127.0.0.1 bind check (M6 deploy) [FIXED, #12]. **Measured 2026-11-15 on the final tree:** `devbox run test` exit 0 (Nim suite all pass; 103 Node harness tests, 0 fail) and `devbox run mutation` exit 0 (control passes, all 63 mutations fail >= 1 expected test, the new `d3` included; log `results/mutation.log`). See 6.1, 10.3, 10.4, 13.
Owner also decided 2026-11-15 [FIXED (owner decision), 2026-11-15, #41]: the height model. Heights are metres, decimal; map distances stay px and no map scale is introduced, because see-over compares heights with heights (research #39 3.3). `height` and `eye_height` are properties, not fields: a character carries the base value, a plain token must carry its own (`token.create` without one is refused), a linked token uses the character's value and may carry a temporary on-map override that never writes the character. Effective token height = token override, else character, else the plain token's own. Eye height follows the same pattern; if nobody set one by hand anywhere it is 93% of the effective token height and follows changes live [93% FIXED (owner-delegated)]. A wall is full height (nobody sees over it) unless the GM gives it one in metres; existing walls are unchanged. Both keys live in the `gm` bucket, so players see only the outcome, their sight. They are the first two keys of the property-schema registry (`number`, `gm`), so "the server never interprets props in v1" becomes "the server interprets only registered keys used by core sight rules". Limits [FIXED (owner-delegated)]: all heights > 0; `height` <= 100 m; `eye_height` <= 100 m and may exceed `height`; a wall's height > 0 and <= 100 m. Deferred: the target's height in see-over (#44) and the height existing tokens and characters get at migration (#49); wall kinds were settled afterwards by #42 (5.8, v0.22), while thickness (#45) and what a low wall hides (#44) stay with map #38. See 5.7, 6.1, 8, 9.
Owner also decided 2026-11-15 [FIXED (owner decision), 2026-11-15, #42]: the wall model. A wall's behaviour is **independent switches**, and a named kind is only a **preset** over them: never a fixed kind enum in the record, and never client-interpreted free flags (the client may send a preset name; the server expands and validates it). v1 switches are `blocks_sight` and `blocks_movement` plus the door settings `door`, `open`, `secret`, `locked` and one direction field `sight_dir` (`both|left|right`); no light or sound axis. Direction is **sight only**: movement is two-way governed by its switch. A door is a wall with `door` set and independent `open`/`secret`/`locked` settings, not a separate kind or a state enum, and `door.set` keeps working as "set `open`". The switches describe the closed wall: an open door blocks neither sight nor movement. A secret door is always closed and two-way (`open:true` or `sight_dir != both` on it is `invalid`), so it can look exactly like a solid wall. `secret` and `locked` are GM-only and never observable to a player in any form; the obligations are byte-identical player frames and refusals for a closed secret door against a solid wall, and one uniform move nack. v1 presets (one-drag editor defaults and the GM's label) are `wall` (default), `door`, `secret door`, `locked door`, `terrain` (blocks movement, not sight: railing, bushes) and `one-way wall`; there is no `window` preset until #47 gives windows a rule, and "blocks nothing" is not a preset. The record stores the switches; `kind` survives on the wire as a derived read-only label (exact preset match, else `custom`), never an input and never the authority [FIXED (owner-delegated)]. The switches are typed validated fields on the record and in the payloads, not entries in the never-interpreted `flags`; columns vs one validated object, and the existing-row migration, are #49's [FIXED (owner-delegated)]. The GM editor has a preset row plus an **advanced** toggle that exposes the raw switches [FIXED (owner decision)]. Thickness and height compose through the switches (a wall with `blocks_sight=false` never reaches the sight predicate) and are decided in #45 and #44. See 1, 3.1, 5.1, 5.5, 5.8, 6.1, 7.4, 8, 14.
+49
View File
@@ -0,0 +1,49 @@
# Handoff: start of M3 session
Written 2026-11-08 at main 809f219. Paste the "Prompt" section into a new agent session.
## Prompt
### Context
FFF_vtt: browser VTT. Nim 2.x authoritative server (per-player line-of-sight,
players never receive hidden info) + TypeScript/PixiJS v8 client.
Root: /home/davide/Projects/GDR/FFF_vtt, branch main (local, ahead of
origin, NOT pushed — do not push).
State:
- M1 (geometry port) and M2 (move rules, blocked/stuck policy, door push,
scanline cells, bench, mutation a–o) DONE. See git log, results/.
- All DESIGN.md §14 questions answered or deferred (owner decisions 2026-11-08,
tagged FIXED). docs/DESIGN.md = source of truth; §5.5 = move rules.
- Research notes: docs/research/. Prototypes (prototype-*/) read-only.
### Your job
Implement M3 exactly as defined in DESIGN.md §13. First read M3 + every section
it references; list only genuinely open points (where two reasonable
implementers would build different things and it matters), propose defaults for
obvious ones, and ask the owner before coding.
### Owner preferences
- Ask only important things; propose defaults for obvious ones.
- Plain language when talking to the owner.
- Small, clearly described commits on main. No push. No new long-lived branches.
- DESIGN.md may be edited to record owner decisions (tag FIXED, dated).
### Tooling and lessons
- NixOS + devbox only: `devbox run test | mutation | bench`. Nothing global.
- `devbox run mutation` ~80 s (parallel); run it once at the end, not per edit.
- Never wait with one long foreground timeout (laptop suspend froze a session
for 6 h); poll in short steps. Never `git stash` while tests run.
- Check library APIs (mummy pinned to tag 0.4.8, db_connector, PixiJS v8)
against source/docs, not memory.
### Known open items carried into M3+
- Wall ids shift on removal; §8 wants stable ids → fix in M3.
- GM "clear blocked" wire message to define in M3 (§6.1).
- Probing test over WebSocket (hostile client) = M3.
- M5: ordering rule for coalesced outbox messages (e.g. remove vs token update);
verify nginx actually proxies WS and which timeout closes dead peers.
- Untested edge: zero-length door push; centre-on-line push with no usable
previous position (falls back to left side).
- Old /tmp/tmp.* dirs from killed mutation runs may remain (harmless).
- Gitea still has prototype/* branches; local ones deleted.
+12 -8
View File
@@ -1,14 +1,18 @@
# Triage Labels
The skills speak in terms of five canonical triage roles. This file maps those roles to the actual label strings used in this repo's issue tracker.
The skills speak in terms of two category roles and five state roles. This file maps those roles to the actual label strings used in this repo's issue tracker.
| Label in mattpocock/skills | Label in our tracker | Meaning |
| -------------------------- | -------------------- | ---------------------------------------- |
| `needs-triage` | `needs-triage` | Maintainer needs to evaluate this issue |
| `needs-info` | `needs-info` | Waiting on reporter for more information |
| `ready-for-agent` | `ready-for-agent` | Fully specified, ready for an AFK agent |
| `ready-for-human` | `ready-for-human` | Requires human implementation |
| `wontfix` | `wontfix` | Will not be actioned |
Every triaged issue carries exactly one category label and one state label.
| Label in mattpocock/skills | Label in our tracker | Kind | Meaning |
| -------------------------- | -------------------- | -------- | ---------------------------------------- |
| `bug` | `bug` | category | Something is broken |
| `enhancement` | `enhancement` | category | New feature or improvement |
| `needs-triage` | `needs-triage` | state | Maintainer needs to evaluate this issue |
| `needs-info` | `needs-info` | state | Waiting on reporter for more information |
| `ready-for-agent` | `ready-for-agent` | state | Fully specified, ready for an AFK agent |
| `ready-for-human` | `ready-for-human` | state | Requires human implementation |
| `wontfix` | `wontfix` | state | Will not be actioned |
When a skill mentions a role (e.g. "apply the AFK-ready triage label"), use the corresponding label string from this table.
+123
View File
@@ -0,0 +1,123 @@
# M3 research: mummy 0.4.8 and db_connector API facts (#10)
Date: 2026-11-10. Parent: map #2. Scope: facts + source refs only. No decisions.
## Sources read (primary)
- **mummy tag 0.4.8** = commit `77a7563e87a1045e4e407a3a68731e299fa3507e` (GitHub API `refs/tags/0.4.8`). Repo is **`guzba/mummy`**, not `treeform/mummy` as the ticket says (nimble `url` = github.com/guzba/mummy). Files fetched raw from that commit: `src/mummy.nim` (1561 L), `src/mummy/{common,internal,routers,multipart}.nim`. Link base: `https://github.com/guzba/mummy/blob/77a7563e87a1045e4e407a3a68731e299fa3507e/`. Refs below are `src/mummy.nim:N` unless noted.
- **mummy at main `01deb1ff`** (devbox cache): `mummy.nim` is 54023 B, same size as the tag copy. q20 doc says only `.github/workflows` differ. Not re-diffed here.
- **webby 0.2.1** (`treeformwebby`), local pkgcache `/home/davide/.nimble/pkgcache/githubcom_treeformwebby_021/src/webby/`: `httpheaders.nim`, `queryparams.nim`. Upstream tag not fetched.
- **db_connector** commit `29450a2063970712422e1ab857695c12d80112a6` (nimble `specialVersions` 0.1.0; `srcDir = "src"`). Read from local cache `prototype-server-vision/.devbox/nimble/pkgs2/db_connector-0.1.0-4f2e67d0e4b61af9ac5575509305660b473f01a4/db_connector/` (`db_sqlite.nim`, `db_common.nim`, `sqlite3.nim`). Upstream file path inferred as `src/db_connector/db_sqlite.nim`. Not fetched from GitHub.
- **Nim stdlib** `hashes.nim` (devbox Nim 2.2.12): `/nix/store/274jzpwhdklcga24bd9cxywba9apvpic-nim-unwrapped-2.2.12/nim/lib/pure/hashes.nim`.
- Repo: `prototype-server-vision/src/server.nim`, `docs/DESIGN.md` §3.2, §4.2–4.4, §6.2, `docs/research/q20-nix-packaging.md`.
## mummy 0.4.8: facts
### Build / config
- Compile guards: `--mm:arc|orc|atomicArc` and `--threads:on` required, else `{.error.}` (`src/mummy.nim:1-6`).
- `newServer(handler, websocketHandler, logHandler, workerThreads = max(countProcessors()*10,1), maxHeadersLen = 8 KB, maxBodyLen = 1 MB, maxMessageLen = 64 KB, ...)` (`:1472-1479`).
- `serve(port, address = "localhost")` (`:1414`). `close(server)`: in-flight handler calls finish, queued ones not dispatched (`:1405-1412`).
### Threading model
- `RequestHandler = proc(request: Request) {.gcsafe.}`; `Request = ptr RequestObj` (`:45-61`, `:78`).
- Handlers and WS handler run on a worker pool (`workerProc`, `:464`). Docstring: "Calls to the HTTP, WebSocket and log handlers are made from worker threads" (`:1484`). HTTP handler calls run concurrently across requests.
- WS events for one socket are serialized (per-socket `websocketClaimed` flag, `:483-500`). Different sockets run concurrently.
- Single IO thread: `loopForever` (`:1150`).
- Handler exception: logged; `respond(500)` if not yet responded (`:471-478`).
- The `Request` is freed after the handler returns: `` `=destroy`(task.request[]) `` + `deallocShared` (`:479-480`). Do not retain a `Request` past the handler.
- `responded` flag is handler-thread only (docstring `:1540-1543`). 1xx responses do not set it.
### HTTP request access
- `RequestObj` fields: `httpVersion, httpMethod, uri, path` (decoded), `queryParams: QueryParams`, `pathParams`, `headers: HttpHeaders`, `body`, `remoteAddress` (`:46-58`).
- `path`/`queryParams` set from `parseUrl(uri)` (`:847-849`); copied in `popRequest` (`:754-776`).
- `HttpHeaders` = `distinct seq[(string,string)]`. `[]` is case-insensitive and returns the **first** match, `""` if absent (`webby httpheaders.nim:24-29`).
- `QueryParams[key]` returns first match, `""` if absent (`webby queryparams.nim:44-46`).
- No header-name or Origin/Cookie logic in mummy. Grep for `Origin`/`Cookie`: none.
### Response
- `respond(request, statusCode, headers: sink HttpHeaders, body)` (`:313-411`). Queues under `responseQueueLock`. Adds `Content-Length` if absent. Honors `Connection` header. Gzip/deflate-compresses bodies >860 B when `Accept-Encoding` matches and no `Content-Encoding` set.
- Set-Cookie / multi-value: `HttpHeaders[]=` **replaces the first match** or appends (`webby httpheaders.nim:30-38`). `encodeHeaders` emits every pair (`src/mummy/internal.nim:39-70`). Two `Set-Cookie` lines need a direct append to the underlying seq (`toBase`, `httpheaders.nim:5`). Not tested empirically.
- Redirect: no helper; `respond(302, headers with Location)`. Prototype does this (`server.nim:281-285`).
- `X-Accel-Redirect`: no special handling, plain header passthrough. Prototype uses it (`server.nim:301-304`).
- Limits: headers over `maxHeadersLen` → connection closed, no HTTP status (`:799-806`). Body over `maxBodyLen` → connection closed, no 413 (`:1004-1006`, `:1041-1043`). Data received while a request is outstanding is logged and not parsed (`:783-784`).
### Routing (`src/mummy/routers.nim`)
- `Router` with `get/post/put/delete/head/options/patch` and `addRoute(method, route, handler)` (`:23`, `:80-134`).
- Named path params (`pathParams`) and partial wildcards `*foo`, `foo*` (`:160-170`).
- `toHandler` (`:199`). Default 404 and 405 bodies are HTML (`:136-158`).
### WebSocket upgrade
- No upgrade hook. The HTTP handler decides: read headers, then either `upgradeToWebSocket(request)` or `respond(4xx)`. Prototype refuses with `respond(403)` (`server.nim:287-288`).
- `upgradeToWebSocket` raises `MummyError` if: `Connection` lacks `Upgrade`, `Upgrade` lacks `websocket`, `Sec-WebSocket-Key` empty, `Sec-WebSocket-Version != "13"` (`:412-438`). It returns a `WebSocket` and queues the 101 (`:455-461`). Origin is not checked.
- `send()` before the 101 is flushed is queued (`sendsWaitingForUpgrade`, `:1217-1223`). `OpenEvent` is posted after the 101 is queued (`:1213`). If the client is gone before the 101, no `OpenEvent` (docstring `:418-420`).
### WebSocket identity
- `WebSocket = object` with **private** fields `server`, `clientSocket: SocketHandle`, `clientId: uint64` (`:63-66`).
- `clientId = server.rand.next()` per accepted socket (`:1312`).
- No explicit `hash`/`==` in mummy. `hash` is the generic `hash[T: tuple | object]` in Nim stdlib, which hashes all fields (`hashes.nim:667-669`). `$websocket` uses it (`:178-179`). Mummy keys its own tables by `WebSocket` (`websocketClaimed`, `websocketQueues`, `:107-108`).
- `==`: no explicit proc in mummy; relies on Nim's built-in structural equality. Not checked in source.
### WebSocket send / close / events
- `WebSocketEvent = OpenEvent | MessageEvent | ErrorEvent | CloseEvent` (`:72-73`).
- `MessageKind = TextMessage | BinaryMessage | Ping | Pong` (`:75-76`). Inbound Ping/Pong are delivered to the handler as messages (`:734-737`). No auto-Pong reply in source.
- `send(ws, data, kind = TextMessage)`: enqueues one frame under `sendQueueLock`, triggers the IO thread (`:262-291`). Thread-safe by lock.
- `close(ws)`: enqueues a close frame behind already-queued messages (`:293-311`). Does not discard the queue.
- Sends to a disconnected or already-closed socket are dropped with a debug log, no error returned (`loopForever` `:1186-1250`; "Dropped message after WebSocket close").
- Peer close: mummy replies with a close frame and closes (`:725-733`). If our close frame is sent and no reply in 10 s, force-close (`:596-598`).
- Errors and close: `ErrorEvent` is posted only if no close frame was sent, then `CloseEvent` (`:1399-1404`).
- `maxMessageLen` (default 64 KB) is checked on **inbound** frames only, cumulative across fragments (`:658-660`). Violation closes the TCP connection with no close frame. Outbound sends are not capped by it.
- Control frames: fragmented or >125 B payload → close (`:650-655`). Unmasked frame → close (`:618-619`).
## db_connector (db_sqlite) at 29450a2: facts
- **Handle**: `DbConn* = PSqlite3` (raw `sqlite3*`) (`db_sqlite.nim:183`). No lock, no thread-ownership check. Module never calls `sqlite3_threadsafe` or `sqlite3_busy_timeout` (grep). Busy handling is left to the caller; `SQLITE_BUSY` surfaces as `DbError`.
- **Library**: `libsqlite3.so(|.0)` dynlib, or static with `-d:staticSqlite` (`sqlite3.nim:22-31`).
- **Open / close**: `open(connection, user, password, database)`. Only `connection` is used. Raises on failure (`:784-805`). `close(db)` (`:774-782`).
- **Errors**: `DbError* = object of IOError` (`db_common.nim:17`). `dbError(db)` raises `ref DbError` with `sqlite3_errmsg` text only; no error code exposed (`:198-211`).
- **exec**: `exec(db, sql"...", args...)` with `?` placeholders. Args are `$`-stringified and escaped by `dbQuote` (`:267-285`). Raises on failure.
- **tryExec**: returns `bool`; accepts `SQLITE_ROW` as success (`:235-256`). So `exec(sql"PRAGMA journal_mode=WAL")` works (prototype used `getAllRows` for it, `server.nim:330`).
- **Transactions**: no API. No begin/commit/rollback proc. Manual `db.exec(sql"BEGIN")` / `COMMIT` (doc example `:83`; prototype `server.nim:203-206`). No auto-rollback on exception.
- **Prepared statements**: `prepare(db, q): SqlPrepared` (`:229-233`; finalizes and raises on failure). `SqlPrepared = distinct PStmt` (`:188`). `bindParams(ps, args...)` macro (`:287-299`). Template `exec(db, stmt, args...)` does reset + clear_bindings + bind + step (`:301-309`). `finalize(stmt)` (`:819-820`) is manual; the type has no destructor.
- **Bind overloads**: `int32/int64/int/float64`, `bindNull`, `string` (`bind_text`, copy → `SQLITE_TRANSIENT`, `:857-861`), `openArray[byte]` (`bind_blob`, `:863-869`). A string binds TEXT, not BLOB.
- **Read**: `getValue(db, query)` returns `string` and copies BLOB bytes raw (`:618-656`, BLOB branch `:648-650`). `Row = seq[string]`: NULL → `""` (`:183-185`). `setRow` copies BLOB via `column_bytes` (`:325-335`). `InstantRow[]` returns `string` (`:499-505`).
- **Insert id / counts**: `insertID`/`tryInsertID` (`:675-716`); `execAffectedRows` (`:745-772`).
- **user_version**: no API. Read with `getValue(db, sql"PRAGMA user_version")`; write with `exec` of a literal. SQLite does not accept bound `?` for PRAGMA values. That last point is from SQLite docs, not checked in source here.
- **Thread safety**: none in the module. Caller must serialize access to one `DbConn`. Threading mode of the system `libsqlite3` is not checked here.
## Gotchas for our design
### DESIGN §3.2 (auth, origin, cookies)
- Origin is not checked by mummy. Read `request.headers["Origin"]` before `upgradeToWebSocket`. Missing header returns `""`, so compare for equality with the configured origin and refuse on mismatch. Refusal is `respond(403)`, not an exception. `upgradeToWebSocket` raises only on malformed upgrade headers.
- Cookie: `headers["Cookie"]` returns only the first `Cookie` header. Iterate all pairs as prototype does (`server.nim:267-272`).
- Setting a session cookie plus a clear/other cookie on one response requires appending to the header seq (see Set-Cookie above). `[]=` silently replaces.
- `Secure`/`HttpOnly`/`SameSite` are plain strings. mummy adds nothing.
### DESIGN §4.2–4.3 (pipeline, threading, outbox)
- `send()` is a short lock-and-enqueue; safe to call under our global lock.
- Outbound frames are unbounded in mummy. `maxMessageLen` is inbound only (`:658`). Matches DESIGN §4.3 (no depth API, bounded outbox needed app-side).
- `send` after `close` or after disconnect is silently dropped. Do not rely on send success for correctness.
- Inbound Ping/Pong reach the handler as `MessageEvent` with kind `Ping`/`Pong` (`:734-737`). Server-side Ping is `send(ws, payload, kind = Ping)`. Our payload must be ≤125 B.
- Oversize inbound message → abrupt TCP close, no close frame, no 1009 (`:658-660`). Client sees a drop, not an error code.
- No inbound rate limiting in mummy (grep). DESIGN §4.3 plans it in `websocketHandler`.
- Prototype runs 8 workers (`server.nim:363`). Each handler call holds the global lock while doing I/O, so workers block behind it. No backpressure in mummy.
- `WebSocket` fields are private. `clientId` is a random uint64 per accepted socket (`:1312`). Keying by `WebSocket` works via generic hash (`hashes.nim:667-669`), but DESIGN §4.3 already plans an app `connId`.
- `Request` pointer is freed after handler returns (`:479-480`). Never store it past the handler.
- `respond()` from another thread: queue is locked, but `request.responded` is not. Only call from the handler thread.
### DESIGN §4.4 (persistence)
- Single raw `DbConn` under the global lock matches the module (no internal lock).
- No `busy_timeout` set. Any second connection (e.g. an external tool on the same WAL file) can make `exec` raise `DbError` with a busy message. Set `PRAGMA busy_timeout` via `exec` if needed.
- Transactions are manual. An exception between `BEGIN` and `COMMIT` leaves the transaction open on the single connection. Need explicit `ROLLBACK` in the error path.
- BLOB write: `bindParams(stmt, bytesSeq)` with `openArray[byte]`. Passing a `string` writes TEXT. Read via `getValue` returns a `string` of raw bytes; convert as needed.
- `PRAGMA synchronous=NORMAL` and `journal_mode=WAL` via `exec` (prototype `server.nim:330-331`).
### DESIGN §6.2 (versioning)
- `/ws?proto=N`: `request.queryParams["proto"]` returns `""` if absent or not parsed. Query is percent-decoded by webby. Parse the int and check.
- `user_version` read/write is `getValue`/`exec` (see above). Enforce "refuse newer DB" in app code.
## Open / unverified
- `==` for `WebSocket`: Nim built-in structural equality assumed, not read from source.
- SQLite threading mode of the system `libsqlite3`: not checked.
- `PRAGMA user_version` with bound parameter: SQLite docs, not verified in source.
- Upstream db_connector path (`src/db_connector/db_sqlite.nim`) inferred from nimble `srcDir`.
- Two `Set-Cookie` lines on the wire: not tested with a running server.
+114
View File
@@ -0,0 +1,114 @@
# M3: test harness WebSocket options (#8 "Test tools check")
Date: 2026-11-10. Scope: facts and tradeoffs only; no decision, no repo code changed. Part of #2 (map). Question: what can the test harnesses use to speak WebSocket with control of Cookie + Origin headers, raw oversized frames, and floods, inside devbox.
Pins used below: treeform/ws `c9c0c7b` (v0.6.0), guzba/whisky `494fb10`, status-im/nim-websock `703f8f4` (v0.5.0), guzba/mummy `01deb1f` (repo pin). Local Nim 2.2.4 (system), devbox lock nim 2.2.12.
## 1. Summary
1. Current prototype WS harnesses are plain Node `.mjs` using only Node built-ins plus the global `WebSocket`. No npm `ws` package, no `package.json` for tools. 302 lines of WS-touching code.
2. Node global `WebSocket` accepts a non-standard `{headers}` 2nd arg. Verified locally: `Cookie` and `Origin` both reach the wire (node v24.22.1). Cannot send raw/malformed frames.
3. Main repo `devbox.json` has no node. Prototype `devbox.json` uses `nodejs: latest`, which the lock resolves to nodejs_26 26.11.1. `lib.mjs` comment says "Node 22" (stale vs lock). Node 26 not tested.
4. Nim 2.2.4 stdlib has no WebSocket module. `httpclient.getSocket` exists, so a hand-rolled handshake is possible.
5. treeform/ws (Nim 2.x compatible, active): no header injection API; `WebSocket.tcpSocket*` is exported, so raw bytes can be written after handshake. Type-checks on Nim 2.2.4.
6. nim-websock (active): header control via `Hook` (Cookie/Origin possible); 20 MB frame cap; but internal write procs are not exported (no raw frames) and it needs nim >= 2.2.14, above both pinned Nim versions.
7. whisky: archived, blocking, no header API. Not a fit for floods or header control.
8. Raw `node:net` gives full control (any bytes, any header) with zero deps. Nim rewrite = hand-rolled handshake + frame codec (roughly 150-250 lines, estimate).
9. Server side: mummy default `maxMessageLen` = 64 KB (server.nim does not override), so oversized-frame tests have a concrete server limit to probe.
## 2. Prototype harnesses (a)
| file | lines | WS? | deps |
|---|---|---|---|
| tools/leak.mjs | 65 | yes (via lib.mjs) | node:fs, lib.mjs |
| tools/lib.mjs | 17 | yes: `new WebSocket(url, {headers:{Cookie}})` | node:fs; global fetch/WebSocket |
| tools/smoke.mjs | 53 | yes: `{headers: {Cookie}}`, bad/absent cookie checks | node:fs |
| tools/restart.mjs | 85 | yes (via lib.mjs) | node:fs, node:child_process |
| tools/concurrency.mjs | 82 | yes (via lib.mjs) | lib.mjs |
| tools/genmap.mjs | 106 | no (map gen) | node:fs, node:zlib |
| tools/leakcheck.nim | 154 | no: replays JSONL transcript | std/[json,tables,sets,strutils,os,math], geometry |
| tools/faulttest.sh | 36 | no: shell; runs leak.mjs under withserver.sh | sh, nim, node |
| tools/withserver.sh / leaktest.sh | 17 / 11 | no: shell orchestration | sh, nginx |
- lib.mjs comment: "Node 22 WebSocket (undici) accepts {headers}" [L1].
- Only `package.json` in prototype is `client/package.json` (pixi.js, vite, typescript, @types/node). Tools do not import it.
- `ws` npm package: not used and not evaluated.
Sources: [P1] `/home/davide/Projects/GDR/FFF_vtt/prototype-server-vision/tools/lib.mjs`; [P2] `.../tools/smoke.mjs` L9; [P3] `.../tools/leak.mjs`, `.../tools/leakcheck.nim` (under `prototype-server-vision/tools/`); [P4] `prototype-server-vision/devbox.json`; [P5] `prototype-server-vision/client/package.json`.
## 3. Node availability and deps (b)
- Main `devbox.json` packages: nim 2, nimble, coreutils, gnused, diffutils, gnugrep. No node, no nginx. [M1] `/home/davide/Projects/GDR/FFF_vtt/devbox.json`
- Prototype `devbox.json`: `nodejs: "latest"`, `nginx`, `sqlite`. [P4]
- Prototype `devbox.lock` L300-303: `nodejs@latest` resolved to `nixpkgs 8edc0c7#nodejs_26`, version 26.11.1. [P6] `prototype-server-vision/devbox.lock`
- System node (outside devbox): v24.22.1, `/run/current-system/sw/bin/node`. Not the devbox version.
- Node `WebSocket` header option: tested by capturing raw upgrade on a local `net` server. Wire request contained `Cookie: sid=abc` and `Origin: https://evil.example`. Test script: `<scratchpad>/nodetest/hdr.mjs`. Node docs for the `headers` option were not checked; behavior is observed, not documented.
- Browser-standard WebSocket has no headers arg; this path depends on Node/undici.
- Deps reproducibility: tools use only built-ins, so no `npm install` step. Pin comes from devbox.lock.
## 4. Nim WebSocket client options (c)
Nim 2.2.4 stdlib: no WebSocket module (grep of `lib/pure` for "websocket" is empty). `httpclient`/`asynchttpclient` expose `getSocket` [S-httpclient]. treeform/ws uses that exact trick for the handshake [T-ws-connect].
| lib | commit / date | async | header control (Cookie/Origin) | raw/malformed frames | oversize | Nim 2.2.4 |
|---|---|---|---|---|---|---|
| treeform/ws | c9c0c7b, v0.6.0, pushed 2026-05-25, MIT | async only (asyncdispatch) | no: `newWebSocket(url, protocols)`; fixed headers | `tcpSocket*` exported, so raw writes possible after handshake; `send` always masks on client, no rsv/len override | no client-side cap; `receivePacket` accumulates fragments unbounded; 64-bit len reads only bytes 4-7 (ok < 4 GB) | `nim check` rc=0 (warnings only) |
| status-im/nim-websock | 703f8f4, v0.5.0, pushed 2026-10-29, Apache/MIT | chronos async | yes: `connect(..., hooks)`; `Hook.append(headers var HttpTable)` | no: `writeMessage`/`writeControl` not exported | `WSMaxMessageSize` 20 MB hard cap (frame.nim); `frameSize` 1 MB chunking | not compatible: `requires nim >= 2.2.14`, plus bearssl, chronicles, chronos 4.4-4.6, httputils, nimcrypto, results, stew, zlib |
| guzba/whisky | 494fb10, archived per GitHub API | blocking only | no: `newWebSocket(url)` | not reviewed beyond framing | no cap seen in `receiveFrame` | `nim check` rc=0 |
| niv/websocket.nim | last push 2022-12-04, license NOASSERTION | - | - | - | - | not evaluated (stale; treeform derives from it) |
| mummy | 01deb1f (repo pin) | server only | - | - | - | n/a (server, not client) |
Key source facts:
- treeform/ws: `newWebSocket` builds headers only from WS fields plus optional `Sec-WebSocket-Protocol` [T-ws-connect]. `WebSocket` object has `tcpSocket*`, `masked*` fields [T-ws-type]. Receive path rejects rsv bits and mask mismatch [T-ws-recv].
- nim-websock: `connect` takes `hooks: seq[Hook]`, calls `hp.append(hp, headers)` before the upgrade request [NW-connect]. `frame.nim` L200 raises above `WSMaxMessageSize` (20 MB) [NW-frame]. `types.nim` L26-27 defines `WSDefaultFrameSize` (1 MB) and `WSMaxMessageSize` (20 MB) [NW-types].
- Nim version drift: devbox pins nim 2.2.12; system nim is 2.2.4. nim-websock would need >= 2.2.14. Upgrading the pin is a separate decision.
- Hand-rolled Nim client: handshake via stdlib `asyncnet`/`httpclient` (or raw `asyncnet` sending the upgrade request, which gives full header control) plus frame encode/decode. Size is an estimate: 150-250 lines.
## 5. Node raw sockets vs global WebSocket (what each can do)
| need | global WebSocket (Node 24 tested) | `node:net` + hand-rolled frames | npm `ws` |
|---|---|---|---|
| Cookie + Origin | yes (`{headers}`, observed) | yes (raw handshake) | not evaluated |
| floods | yes (send loop; existing concurrency.mjs does it) | yes | not evaluated |
| oversized frame (>64 KB) | sends big strings; fragments per undici | yes (set any length) | not evaluated |
| malformed frames (rsv, unmasked, bad len, bad opcode) | no | yes | not evaluated |
| extra deps | none | none | would need lock file |
## 6. Effort: port .mjs vs rewrite in Nim (d)
Rough estimates, not measured.
- Port as-is to main repo: add `nodejs` to root `devbox.json` (one package line, lock regen). Copy `tools/lib.mjs` + the 4 WS scripts (~300 lines). Still need the prototype's run layout (`run/invites.txt`, nginx conf via `withserver.sh`, ports 18088/19000). Low effort, but the harnesses are tied to the prototype's layout and env.
- Rewrite in Nim: needs a WS client. Options: (i) hand-rolled client on stdlib (~150-250 lines, full control, no dep); (ii) treeform/ws + patch for headers (header patch on a fork, plus raw frames via `tcpSocket`); (iii) nim-websock (hooks and cap ok, but requires Nim upgrade). Floods and async fine in all Nim options.
- Hybrid: keep Node for the scenario drivers, Nim for the checker (leakcheck.nim already Nim, reads transcript, no WS). Adds no WS dep to Nim.
## 7. Open facts not yet verified
- Node 26 (devbox pin) header behavior: not tested.
- Node `WebSocket` headers option in official docs: not checked.
- treeform/ws and whisky runtime behavior: only `nim check`, not run against a server.
- niv/websocket.nim: not evaluated.
- npm `ws` package: not evaluated.
## Sources
Pinned upstream (commit links):
- [T-ws-readme] https://github.com/treeform/ws/blob/c9c0c7b51e2e83cc9305a895a0b144a297b4bea8/README.md
- [T-ws-connect] https://github.com/treeform/ws/blob/c9c0c7b51e2e83cc9305a895a0b144a297b4bea8/src/ws.nim (L72-185 handshake and newWebSocket)
- [T-ws-type] same file, `WebSocket* = ref object` (tcpSocket*, masked*) in the type block near the top
- [T-ws-recv] same file, recvFrame L321-400; receivePacket L402-413
- [T-ws-send] same file, send L291-320 (1 MB chunked writes)
- [NW-connect] https://github.com/status-im/nim-websock/blob/703f8f40c129699b703d7ef72f6897c05ab50f44/websock/websock.nim (connect L90-160, hooks L140-150)
- [NW-frame] https://github.com/status-im/nim-websock/blob/703f8f40c129699b703d7ef72f6897c05ab50f44/websock/frame.nim (L190-215)
- [NW-types] https://github.com/status-im/nim-websock/blob/703f8f40c129699b703d7ef72f6897c05ab50f44/websock/types.nim (L24-27, L95, hook type ~L147)
- [NW-session] https://github.com/status-im/nim-websock/blob/703f8f40c129699b703d7ef72f6897c05ab50f44/websock/session.nim (writeMessage L32, writeControl L64 not exported)
- [NW-nimble] https://github.com/status-im/nim-websock/blob/703f8f40c129699b703d7ef72f6897c05ab50f44/websock.nimble (`nim >= 2.2.14`)
- [WH-src] https://github.com/guzba/whisky/blob/494fb1046f5a563defc87ac36b8c62846ee7ea2c/src/whisky.nim (newWebSocket L156, receiveFrame L28)
- [WH-readme] https://github.com/guzba/whisky/blob/494fb1046f5a563defc87ac36b8c62846ee7ea2c/README.md
- [MUM-default] https://github.com/guzba/mummy/blob/01deb1ff694988635c7bf0f24f6088a0bdf6db5d/mummy.nim (newServer defaults L1476-1481: maxMessageLen = 64 KB; enforced L658)
- [SRV-newserver] local `/home/davide/Projects/GDR/FFF_vtt/prototype-server-vision/src/server.nim` L363 (`newServer(handler, wsHandler, workerThreads = 8)`, no maxMessageLen)
- [S-httpclient] local `/nix/store/3y9syv0p41rdaqzddashmdl475l0rbv0-nim-unwrapped-2.2.4/nim/lib/pure/httpclient.nim` L711-724 (getSocket)
- [P1..P6] local files cited in sections 2-3.
- [M1] `/home/davide/Projects/GDR/FFF_vtt/devbox.json`
- Node header test: `<scratchpad>/nodetest/hdr.mjs` (scratch, not committed).
- nimble index (names/URLs only): `/home/davide/Projects/GDR/FFF_vtt/prototype-server-vision/.devbox/nimble/packages_official.json`
- GitHub API metadata: `gh api repos/treeform/ws`, `repos/guzba/whisky`, `repos/status-im/nim-websock`, `repos/niv/websocket.nim` (pushed dates, archived flag).
+138
View File
@@ -0,0 +1,138 @@
# Q13: mummy slow WebSocket clients (pin 01deb1f)
Question (docs/DESIGN.md §4.3, Q13): how mummy queues WebSocket sends per connection; whether app code can see queue depth, get backpressure, close slow clients; ping/pong and timeouts; thread model; hooks; what later mummy commits change; feasibility of an app-level bounded per-client outbox with coalescing vs patching mummy vs other. Also checks the HANDOFF "mummy: unbounded send queue" note.
Pin: `guzba/mummy` `01deb1ff694988635c7bf0f24f6088a0bdf6db5d` (2026-04-29, "Revert ..."). Read from a fresh clone of `https://github.com/guzba/mummy` at that commit. All line numbers below refer to that commit. Base link: `https://github.com/guzba/mummy/blob/01deb1ff694988635c7bf0f24f6088a0bdf6db5d/`. Local copy: `/tmp/claude-1000/-home-davide-Projects-GDR-FFF-vtt/fb922d93-7ea6-4746-9a92-5070f98248eb/scratchpad/mummy/pin/src/mummy.nim`. Nim 2.2.12 stdlib used to check `==`/`hash` and epoll error mapping.
## TL;DR
1. Send path: `WebSocket.send` appends to one server-wide `sendQueue` (`src/mummy.nim` L262-291, L105). The IO thread drains that whole deque in one step into a per-socket `DataEntry.outgoingBuffers` (L1230-1250, L133). That per-socket deque is unbounded and is where backlog actually accumulates.
2. App code cannot read per-socket queue depth or bytes pending. The exported API is `send`, `close(ws)`, `respond`, `upgradeToWebSocket`, `serve`, `close(server)`, `newServer`, `waitUntilReady`, `responded`, and nothing else (grep of `^proc .*\*`).
3. No backpressure. `send` never blocks or fails. Nothing reports writable state to the handler (PR 146 adds this only for response streams, not WebSockets).
4. Slow clients cannot force-close. `close(ws)` only appends a Close frame to the same per-socket FIFO (L293-311, L1248), so a stuck client never receives it. The socket closes only on: peer Close reply, EOF/send error/`Error` event (L1317, L1336, L1358-1362), or a 10 s "close timeout" check that runs only when the socket receives data (L596-597).
5. Slow clients do not block other clients. Writes are non-blocking, one `send()` per writable event per socket in a single select loop (L1340-1362). The cost of a slow client is its own memory.
6. Ping/pong: mummy never sends a Ping and never auto-replies to one. Ping/Pong arrive at the app as `MessageEvent` with `kind` Ping/Pong (L734-736, L752). `send(..., kind = Ping/Pong)` exists (L262-281). There are no timers, idle timeouts, or connection caps. `maxMessageLen` = 64 KB (L1479) is the only size bound on inbound frames.
7. Thread model: one IO thread runs `loopForever` (L1150, select at L1164, `-1` timeout). Workers number `countProcessors()*10` (L1476, L1534). WebSocket events are serialized per connection by `websocketClaimed` (L107, L464-520). The inbound per-socket event queue is also unbounded (L108, L551-573).
8. Hooks: `handler`, `websocketHandler`, `logHandler` (L1472-1480). No per-socket hooks, no metrics, no close-reason callback. `CloseEvent` fires on every socket teardown (L1393-1404), which is enough to count connections.
9. Later commits: none on `master` after the pin (origin/master = 01deb1f, 2026-04-29). `src/` is byte-identical to tag `0.4.8`. Open PR #146 (2026-05-19) adds response-stream writable backpressure and explicitly leaves WebSocket internals alone. Issue #141 (Slowloris) was closed as "non-issue ... used behind a reverse proxy".
10. Feasible without patching mummy: an app-level, per-connection outbox that caps bytes in flight. Use server-solicited Ping(seq) and client Pong echoes (RFC 6455 §5.5.2/5.5.3, WHATWG "Ping and Pong frames") as acks, coalesce latest state per key, and stop feeding a lagging client. Not achievable without a patch: a deterministic forced disconnect, or a visible per-socket queue depth. The HANDOFF note is correct in substance but overstated in location (see Corrections).
## Findings with sources (pin 01deb1f)
### A. Data structures
- `WebSocket` = `{server: Server, clientSocket: SocketHandle, clientId: uint64}` (L63-66). Identity is (ptr, fd, random id).
- `clientId = server.rand.next()` per accepted socket (L1312). Fd reuse is guarded by comparing `clientId` (L1193, L1242).
- `ServerObj`: `sendQueue: Deque[OutgoingBuffer]` + `sendQueueLock` (L105-106); `websocketClaimed`, `websocketQueues: Table[WebSocket, Deque[WebSocketUpdate]]`, `websocketQueuesLock` (L107-109).
- `DataEntry` (per socket, IO-thread owned): `outgoingBuffers: Deque[OutgoingBuffer]` (L133), `sendsWaitingForUpgrade: seq[OutgoingBuffer]` (L136), `closeFrameQueuedAt: float64`, `closeFrameSent`, `upgradedToWebSocket` (L120-137).
- `OutgoingBuffer` = header + payload string + `bytesSent` (L157-162).
- Hashing: `WebSocket` is a Table key (L107-108) and is hashed in `$` (L179). Nim 2.2 `std/hashes` provides a generic `hash[T: tuple|object]` (`nim/lib/pure/hashes.nim` L666) and `system.==` is generic for objects (`nim/lib/system.nim` L1981). So the pinned type hashes and compares field-wise. This contradicts the HANDOFF/README/DESIGN claim "no ==/hash, keyed by raw bytes" (see Corrections).
### B. Send path (app -> wire)
- `send*` builds the frame (Text/Binary/Ping/Pong opcode, L268-280) and does `addLast` on the global `sendQueue` under `sendQueueLock`. It triggers the IO select event only when the queue was empty (L285-291). No size check, no return value, no failure mode.
- `close*(ws)` appends a Close frame to the same queue (L293-311). Messages queued before it are not discarded.
- IO loop drain: `if sendQueuedTriggered` moves every frame from `sendQueue` into the target socket's `outgoingBuffers` (L1230-1250). Frames for a socket that is not upgraded yet go to `sendsWaitingForUpgrade` (L1257). Frames for a socket that already sent a Close go to "Dropped message after WebSocket close" (L1246, `closeFrameQueuedAt > 0`).
- Write path: on `Write` readiness, one `send()` of the head buffer (buffer1 then buffer2) per select iteration (L1340-1362). `bytesSent > 0` is required; otherwise the socket is marked for closing (L1358-1362). Interest is `{Read, Write}` while buffers exist and `{Read}` otherwise (L1109).
- `afterSend` pops fully-sent buffers (L1091-1110). Its `isCloseFrame` branch sets `closeFrameSent`.
- Reads are never paused. Interest for upgraded sockets is always `Read` (L1315, L1109).
Conclusion: the "one server-wide deque" in HANDOFF/README is only the entry point. The IO thread empties it every iteration, so backlog grows in per-socket `outgoingBuffers` (L1248), which app code cannot see.
### C. Backpressure and slow-client control
- None to the app. `send` cannot block, fail, or report depth. No writable callback for WebSockets. No API to drop by key or cap bytes.
- `close(ws)` is not forced. It queues a Close frame behind the backlog (L1248 / L1220). The socket is closed only when:
- the client's Close reply arrives while `closeFrameQueuedAt > 0` (`afterRecvWebSocket`, opcode 0x8 branch, L729-730);
- recv returns 0 or send returns <= 0, or the selector reports `Error` (EPOLLERR/EPOLLHUP, nim stdlib `ioselectors_epoll.nim` L400-411) (L1317-1318, L1336-1337, L1358-1362);
- a frame arrives more than 10 s after the Close was queued (L596-597). This check runs only when the socket receives data.
- Consequence: a client that stops reading and stops sending keeps its socket and its whole backlog until the kernel reports a TCP error. Nothing in mummy times this out. Upstream explicitly declines to add timeouts (issue #141, below).
- Connection cap: none. `clientSockets` is only tracked (L1309, L1392). An app-level counter is needed (count `OpenEvent` L1213 and `CloseEvent` L1402).
- Inbound: `postWebSocketUpdate` appends every decoded message to an unbounded per-socket deque (L551-573, L108). Frame size is capped by `maxMessageLen` = 64 KB (L658, L1479). Message count is not capped, so a flooding client grows server memory on the inbound side too.
### D. Ping/pong and timeouts
- No automatic Pong reply and no server-initiated Ping. Ping/Pong frames are decoded and delivered to the app as `MessageEvent` (L734-736, L752). The app must reply to client Pings itself.
- Control-frame payload > 125 bytes is rejected on receive (L654). `send(kind=Ping)` does not check the 125-byte limit, so the app must keep ping payloads <= 125 bytes (RFC 6455 §5.5).
- Pong from peer is a normal message with `kind == Pong` and the echoed payload. Usable as an ack, see Options.
- No idle, read, header, body, or keep-alive timeouts (issue #141 confirms; maintainer closed it as non-issue because mummy sits behind a reverse proxy).
- `waitUntilReady` only waits for startup (L1546-1560). No timer facility exists anywhere in the module.
### E. Thread model
- One IO thread: `serve()` runs `loopForever` on the calling thread (L1414-1470, L1150). All socket IO, accept, framing decode, and the `sendQueue` drain happen there. Upstream README says the same (`README.md` L35 at pin).
- Worker threads: `countProcessors()*10` by default (L1476, L1534-1535). They run HTTP handlers and WebSocket handlers (L464-545). WebSocket handlers for one connection never run concurrently (`websocketClaimed`, L481-495, L508).
- `send`, `close(ws)` and `respond` are safe from any thread: they take a lock and call `trigger` (L286-291, L306-311). An app timer thread can call `send(kind=Ping)` directly.
- Sends to a closed connection are silently dropped (L1260-1262 "Dropped message to disconnected client", debug log only).
### F. Hooks
- `newServer(handler, websocketHandler, logHandler, workerThreads, maxHeadersLen=8 KB, maxBodyLen=1 MB, maxMessageLen=64 KB, tcpNoDelay=true)` (L1472-1480).
- Events: `OpenEvent` after the 101 is queued (L1213), `MessageEvent`, `ErrorEvent` (only if no Close was sent, L1399-1400), `CloseEvent` (L1402).
- `logHandler` receives debug messages such as "Dropped message after WebSocket close" and "Dropped message to disconnected client" (L1218, L1260-1262). Usable as a crude drop signal, not a metric.
- No per-socket hooks, no queue metrics, no write-ready callback.
## Later commits and related upstream work
- Upstream `master` tip = `01deb1f` (2026-04-29). There are 0 commits on `master` after the pin. The 7 commits between tag `0.4.8` (`77a7563`) and the pin are "whatever / noise / revert" and do not change `src/`. `git diff 0.4.8 01deb1f -- src` is empty.
- Tags `0.4.6`, `0.4.7`, `0.4.8` exist upstream. `docs/DESIGN.md` L48 says "no upstream tags", which is wrong. The pin's `src/` equals tag `0.4.8`.
- Experiment branches `experiments1/2/4` (Nov-Dec 2022, pre-0.4) are not relevant to current code. Checked by subject line only.
- PR #146 (open, not merged, head `be6bbfa9de9ff6033845ee6fd8b52ef29696a490`, 2026-05-19) https://github.com/guzba/mummy/pull/146 adds response streaming with "writable-event backpressure" (`StreamWritable`, one chunk in flight). Its body says WebSocket internals are "intentionally left close to upstream". `send`/`close(ws)` are unchanged in its diff. It does not give WebSocket backpressure.
- Issue #141 https://github.com/guzba/mummy/issues/141 (Slowloris, closed 2026-03-10). Maintainer comment (guzba, 2026-03-10): "Non-issue. Mummy is used behind a reverse proxy for TLS termination which is concerned with the above." Implies upstream expects timeouts from a proxy.
- Issue #142 (pipelined HTTP responses out of order) is closed and HTTP-only; not relevant.
## Standards (for the design)
- RFC 6455 §5.5.2: "Upon receipt of a Ping frame, an endpoint MUST send a Pong frame in response"; §5.5.3: the Pong must echo the Ping's application data. https://www.rfc-editor.org/rfc/rfc6455#section-5.5.2 (text checked at `https://www.rfc-editor.org/rfc/rfc6455.txt` L2036-2062).
- WHATWG WebSocket Standard, "Ping and Pong frames": pings/pongs "are not currently exposed in the API"; "servers will solicit pongs whenever appropriate for the server's needs". https://websockets.spec.whatwg.org/#ping-and-pong-frames
- WHATWG exposes `WebSocket.bufferedAmount` in the browser (client side only). It gives the client no server-side signal. https://websockets.spec.whatwg.org/#dom-websocket-bufferedamount
Consequence: browsers answer server Pings with Pongs in the network stack, without JS. A server-solicited Ping/Pong echo is a valid ack channel for current browsers without any client code change.
## Corrections to repo docs
- `prototype-server-vision/HANDOFF.md` L29 and `prototype-server-vision/README.md` L110-114: "one unbounded server-wide deque" is the entry point only. The backlog is per socket (`outgoingBuffers`, pin L133, L1248). The "no ==/hash, keyed by raw bytes" caveat is stale at this pin (generic field-wise `hash`/`==` apply).
- `docs/DESIGN.md` L48: "no upstream tags" is wrong. Tags `0.4.6`-`0.4.8` exist, and the pin's `src/` equals `0.4.8`.
- `docs/DESIGN.md` L192 and H18 (L500): the mitigation "close when sent - acked-by-pong exceeds a bound" cannot be executed as an immediate close at this pin. `close(ws)` queues behind the backlog. The workable action is to stop feeding the client and close once the peer responds or sends data.
- `docs/DESIGN.md` L192: "per-connection byte counter we maintain ourselves" is fine, but acks must come from server-solicited Pings. WHATWG says user agents must not use pings or unsolicited pongs to aid the server, so the server must solicit every Pong it relies on. JS cannot send or observe Pongs.
## Options
Each option is judged on the owner's requirements: bounded per-client memory, latest-state-wins for vision/positions, no slow client hurting others, and the ability to disconnect. Effort figures are rough estimates, not measured.
### Option A: app-level bounded outbox + ping-acked send window (no mummy patch)
Design:
- Per connection (app-assigned `connId` at upgrade; app table keyed by `connId`, not by `WebSocket`): `inFlightBytes`, a FIFO `mustQueue` of bytes-capped messages, and a `latest: Table[key, state]` map for state messages.
- Send window: call `ws.send` only while `inFlightBytes < W` (e.g. 64 KB). Timer thread sends `Ping(seq)` (<= 125 B payload) every T (e.g. 250 ms to 1 s). On `Pong(seq)` from the peer, subtract the bytes sent before that ping. Mummy's per-socket FIFO makes this exact.
- Coalescing: vision, position and fog state are keyed by (player, token). Keep only the latest per key. The prototype's current diff-at-send-time (`known` map) must change to diff-at-flush-time against last-delivered state. Otherwise dropping a queued delta silently diverges the client.
- Overflow: if `mustQueue` exceeds its cap, or no Pong for X s, stop feeding that client (keep the connection). On recovery send a full snapshot. The prototype already resets on `hello`.
- Disconnect: call `close(ws)`. It takes effect only when the peer reads or sends data. A dead peer that also sends nothing keeps its FD until the kernel reports a TCP error (not measured here).
- Connection cap: count OpenEvent/CloseEvent; reject at upgrade.
- Inbound: app must rate-limit messages per connection in `websocketHandler` (count on enqueue). Mummy's inbound queue is unbounded.
Trade-offs: no mummy patch, no fork; the thread-safety contract holds (`send` is locked, L286-291). Costs: an ack timer thread, ~2-byte-plus overhead per ping, and no forced disconnect (FD may linger). Works with unmodified browsers. Non-browser clients that ignore Pings just get throttled (safe default). Estimate: ~150-250 lines plus tests. Does not add visibility into mummy's real queue (the app's window bounds it instead).
### Option B: fork mummy at the pin and add a small hook set
Needed changes (all in `src/mummy.nim`):
- Per-socket pending-bytes counter, updated on enqueue (L286-291, L306-311) and on fully-sent in `afterSend` (L1091-1110). Expose `pendingBytes(ws)`.
- `send` returns `bool` or drops above `maxPendingBytes`.
- `forceClose(ws)`: enqueue an IO-thread event (same pattern as `sendQueued`) that sets `needClosing` for that socket. CloseEvent already fires from the teardown path (L1393-1404).
- Optional: inbound cap per socket (L551-573).
Trade-offs: fixes the real gaps (forced close, visible depth, hard cap). Costs: changes the IO loop (L1150-1410), the riskiest code in the library; fork maintenance and a nimble URL pin in place of a bare commit; a regression surface for everything mummy does. Upstream PR #146 shows writable-backpressure is acceptable upstream for streams, but WebSockets were left out on purpose, so upstream acceptance is uncertain. Estimate: ~100-200 lines plus tests. Use Option A's `connId`/outbox API so the patch can be swapped in later.
### Option C: rely on a front proxy for slow-client enforcement
Upstream's position (issue #141) assumes a reverse proxy handles timeouts. A proxy with per-client write/send timeouts could close stuck clients. Not evaluated here: no nginx WebSocket config was read, and whether the WS path goes through nginx is an open question (DESIGN has nginx for static and tiles only). Needs its own research.
### Option D: switch WebSocket library
Not evaluated. Would need a separate research pass against each candidate's pinned source. Not recommended before A is tried, because A removes the risk that motivates the switch.
### Option E: caps only (DESIGN v1 mitigations, no slow-client logic)
Connection cap, size limits, pong timeout detection without enforcement. Memory per stuck client grows until the process restarts or the kernel errors the socket. Illustrative arithmetic only: the prototype's ~3.4-3.7 KB per vision delivery (`prototype-server-vision/HANDOFF.md`, README) at an assumed 10 deliveries/s is ~2 MB per minute per stuck client. The 10/s is an assumption, not measured.
## Recommendation
Option A for M5, with a `connId` + outbox module behind a narrow interface. Move to Option B only if forced disconnect or visible depth proves necessary in load tests (the prototype's leak harness can measure `outgoingBuffers` growth via RSS). Update DESIGN H18/L192 and the HANDOFF/README wording per Corrections. Do not patch mummy before measuring A.
## Not verified / open
- No code was compiled or run against mummy. Claims come from reading the pinned source, the Nim 2.2.12 stdlib, and the RFC/WHATWG text.
- Browser behaviour (automatic Pong) is taken from RFC 6455 and the WHATWG text, not tested in a browser.
- TCP error timing for dead peers (kernel retransmit limits) not measured.
- Option C (nginx) and D (other libraries) not researched.
- Upstream issues/PRs were searched via `gh api` for "backpressure", "slow client", "ping", "send queue", "timeout websocket". Results listed above; not exhaustive.
- Not committed, not pushed, DESIGN.md not edited.
+143
View File
@@ -0,0 +1,143 @@
# Q20: Nix packaging of the Nim server + NixOS module
Date: 2026-11-08. Scope: research only. No repo code changed. Refs: `docs/DESIGN.md` Q20 (line 563) and §11.1 (line 445).
Source pins:
- NP = nixpkgs `c56a87d8e41ce69bd2af57eb35dcc117a9dfca33` (26.05.20261105). This is the owner's system nixpkgs (`nixos-version --json`). Links below use this commit. Local store copy: `/nix/store/qyccs9pc22b3fvl2lxia3jagcg97dn48-source` (nim 2.2.4).
- MUM = mummy commit `01deb1ff694988635c7bf0f24f6088a0bdf6db5d`.
- DEV = `devbox.lock` (local, `/home/davide/Projects/GDR/FFF_vtt/devbox.lock`): nixpkgs `55ba7f49ef2962b42cbd126522b7df5f95037679`, nim 2.2.12, nimble 0.24.1.
## 1. Summary
1. nixpkgs has a documented Nim builder: `buildNimPackage` plus a JSON `lockFile`, generated by `nim_lk`. The owner's system nixpkgs (NP) has it. [S1][S2]
2. Lock entries carry the source fetch: `method` `fetchzip` (tarball) or `git` (`url`, `rev`, `sha256`, `srcDir`, `fetchSubmodules`). The builder turns each into a fixed-output fetch plus `--path:` flag. Git-commit deps are fetched with `fetchgit` at the exact `rev`. [S1][S7][S8]
3. nim_builder ignores `requires` in the .nimble. Deps come only from the lock. The lock must list the full transitive closure. [S5][S1]
4. Not in nixpkgs: `mummy`, `db_connector`, `zippy`, `webby`, `crunchy`, `nimsimd` (no `by-name` entry, no `nimPackages`). They enter via the lock. [checked NP tree]
5. Nim 2.2.4 stdlib has no `db_*` module. `db_connector` must be a separate lock entry. [local stdlib]
6. Upstream now HAS tag `0.4.8` on mummy. DESIGN says "no tags" (stale). Tag `0.4.8` = `77a7563e`. MUM is 7 commits ahead; only `.github/workflows/*` differ. Library code is identical. [S13][S14]
7. nim_builder builds only nimble `bin` entries. Root `fff_vtt.nimble` has none and `server/` has no entrypoint yet (only `geometry.nim`). The Nix build would produce an empty package until a `bin` is declared. [S5][local]
8. Devbox pins nim 2.2.12. NP's nim-2_2 is 2.2.4. Version drift must be handled by pinning the nixpkgs input, not by hoping. [DEV][S10]
9. `.gitignore` already excludes `nix/`. DESIGN M6 plans `nix/`. Either remove that line or use another dir name before committing packaging. [local `.gitignore`]
10. Recommended: `buildNimPackage` + committed `nix/lock.json` (from `nim_lk`) + `nix/module.nix` modeled on nitter's systemd unit. Devbox stays the dev shell and is untouched.
## 2. Findings with sources
### 2.1 buildNimPackage (NP)
- Builder: `pkgs/build-support/build-nim-package.nix`. Phases delegate to `nim_builder --phase:{configure,build,check,install}`. `doCheck = true` by default. [S1]
- `lockFile` is read with `builtins.fromJSON`. Each `depends` entry becomes `--path:"<fod>/<srcDir>"` in `nimFlags`. Methods: `fetchzip` -> `fetchzip {url,sha256}`; `git` -> `fetchgit {url,rev,sha256,fetchSubmodules,leaveDotGit}`. `path` in the lock is ignored. [S1]
- `nimOverrides` maps a dep name to a function of (lockAttrs, prevAttrs) to add buildInputs etc. Mummy needs none (pure Nim). [S3][S2]
- `overrideNimAttrs` exists to change `src`/`lockFile` before lock flags are generated. [S2][S1]
- Nim: `nim2 = nim-2_2` (NP `pkgs/top-level/all-packages.nix` L4248). Nim 2.2.4 in NP. [S10][all-packages]
- Doc for the example and lock regeneration: `nix run -f . nim_lk ./result | jq --sort-keys > pkgs/by-name/.../lock.json`. The doc says run `nim_lk` on the source directory. [S2]
### 2.2 nim_builder behavior that matters
- `configurePhase`: writes `config.nims` (backend, nimcache, `-d:release`, `nimDefines`). It also adds `path` switches from `NIX_NIM_BUILD_INPUTS` *nimble files*, not from `requires`. [S5]
- `buildPhase`: `nim compile <nimFlags> --outdir:$out/bin <srcDir>/<bin>` for each `bin` in the root .nimble. No `bin` = nothing built. [S5]
- `checkPhase`: `nim r <nimFlags> tests/t*.nim` (top-level `tests/` only). Root has `tests/tgeometry.nim`, which matches. [S5][local]
- Root `nim.cfg` has `--mm:orc` and `--path:"server"`; no `--threads:on`. Nim 2.2 stdlib config defaults `threads:on` (local `.../nim/config/nim.cfg` L23). Mummy needs threads on. Keep it explicit in `nimFlags` anyway. [local stdlib][MUM README]
### 2.3 Lock file format (NP)
- Generator: `nim_lk` (sourcehut `~ehmry/nim_lk`; NP `pkgs/by-name/ni/nim_lk/package.nix`). It reads Nimble metadata and emits `{"depends":[...]}`. [S4][S2]
- Entry fields seen: `method`, `packages`, `path`, `ref`, `rev`, `sha256`, `srcDir`, `url`; git entries also `subDir`, `fetchSubmodules`, `leaveDotGit`. [S7][S8]
- Example git entry: `pkgs/by-name/ni/nimlangserver/lock.json`. Example fetchzip entry: `pkgs/by-name/ni/nimdow/lock.json`. [S7][S8]
- nim_lk README: sourcehut is bot-walled from my environment. I could NOT read the README. Whether `nim_lk` accepts `requires "pkg#<commit>"` and whether it reads `nimble.lock` is UNVERIFIED. Test it.
### 2.4 Dependency graph and revisions
Pinned in the owner's devbox nimble cache (`prototype-server-vision/.devbox/nimble/pkgs2/*/nimblemeta.json`, `vcsRevision`). Use as the first lock target, then compare with nim_lk output.
| dep | constraint in mummy/registry | devbox-resolved vcsRevision | upstream tag check |
|---|---|---|---|
| mummy | `requires "mummy#01deb1ff..."` (servervision.nimble) | `01deb1ff694988635c7bf0f24f6088a0bdf6db5d` | tag `0.4.8` = `77a7563e` [S13][S14] |
| zippy | mummy: `>= 0.10.9` | `cd562ba43ae8904a4d1ba55611b8a521ef4a179e` (0.10.20) | tag exists [API] |
| webby | mummy: `>= 0.2.1` | `325d6ade0970562bee7d7d53961a2c3287f0c4bc` (0.2.1); repo `treeform/webby` | no tags via API |
| crunchy | mummy: `>= 0.1.11` | `98eb6526982bb8aae8eec6e8781f4539fa19e049` (0.1.11) | tag exists [API] |
| nimsimd | crunchy dep | `3f6b2668ffb0867d0bf786a658b817763e611350` (1.3.2) | tag exists [API] |
| db_connector | fff: `requires "db_connector"` (unpinned) | `29450a2063970712422e1ab857695c12d80112a6` (0.1.0) | no tags via API [S15] |
- mummy nimble (at MUM): `requires nim >= 1.6.8`, `zippy >= 0.10.9`, `webby >= 0.2.1`, `crunchy >= 0.1.11`. [S12]
- db_connector nimble: `requires nim >= 1.7.3`, no other deps. [S15]
- Mummy commit diff vs tag 0.4.8: only `.github/workflows/build.yml` and `docs.yml`. [S13]
- Mummy README: needs `--threads:on` and `--mm:orc` or `--mm:arc`. [MUM README]
### 2.5 Are the deps in nixpkgs?
- Checked NP tree: `pkgs/by-name` has no `mummy`, `db_connector`, `zippy`, `webby`, `crunchy`, `nimsimd` directories. Grep of `pkgs/` for `mummy|db_connector` only hits unrelated files. No Nim package set (`nimPackages` is empty). [NP tree]
- Conclusion: all deps go through the lock. No nixpkgs package to reuse.
### 2.6 Alternatives
- **nimble.lock (Nimble native)**: `nimble.lock`, version 2, fields `vcsRevision`, `url`, `downloadMethod`, `checksums.sha1`. Written by `src/nimblepkg/lockfile.nim`. No nixpkgs builder consumes it. Converting it would be a custom script. [S18]
- **atlas**: documents `atlas.lock` via `pin` / `rep` commands. nixpkgs `nim-atlas` is pinned to `unstable-2023-09-22` (`ab22f997`). No nixpkgs builder reads `atlas.lock`. [S17][S11]
- **Vendored deps** (no lock tool): drop `lockFile`, commit deps (or `fetchFromGitHub` each) and pass `nimFlags = ["--path:..." ...]`. `buildNimPackage` makes `lockFile` optional (`optionalAttrs (hasAttr "lockFile")`). Simplest, zero tooling, but every bump is manual. [S1]
### 2.7 NixOS module precedent
- nitter: `nixos/modules/services/misc/nitter.nix` at NP, lines ~369-420. Unit: `DynamicUser`, `StateDirectory`, `LoadCredential`, `ProtectSystem`-style hardening block: `ProtectHome`, `PrivateDevices`, `ProtectKernel*`, `RestrictAddressFamilies = [AF_INET AF_INET6]`, `SystemCallFilter`, `UMask = 0077`. [S9]
- Nitter package: `pkgs/by-name/ni/nitter/package.nix`, `lockFile = ./lock.json`, `nixosTests`. [S-nitter-pkg]
- Note: nitter's `RestrictAddressFamilies` excludes `AF_UNIX`. DESIGN §11.1 includes `AF_UNIX`; keep it only if the FFF sidecar (Q18/Q19 option b) is chosen. [DESIGN L447]
### 2.8 Owner's host config
- `/home/davide/Projects/server_nixos_configuration/configuration.nix`: channel-style (`<agenix/modules/age.nix>`), not flake. Imports per-service files (`gitea.nix`, `foundryvtt.nix`). [local]
- Precedent for a service module file imported from `imports = [...]`. [local `configuration.nix` L13-23]
### 2.9 Devbox coexistence
- `devbox.json`: `nim: "2"`, `nimble: "latest"`, `NIMBLE_DIR=$DEVBOX_PROJECT_ROOT/.devbox/nimble`; scripts `test` = `nimble test`, `mutation`. [local devbox.json]
- `devbox.lock` resolves nim `2.2.12` (nixpkgs `55ba7f49`), nimble `0.24.1`. [DEV]
- Nix build uses NP nim `2.2.4` unless the flake pins a nixpkgs with 2.2.12. Mismatch risk.
- `nimble test` resolves deps from `requires` (registry + `#commit` pin). The Nix build resolves from the lock. Two resolution paths. Keep revs equal; check `vcsRevision` values above after lock generation.
- `.devbox/` is gitignored; Nix never sees it. No interference, provided the Nix package source does not depend on `.devbox/`.
## 3. Recommendation
Use `buildNimPackage` + committed `lock.json` generated by `nim_lk`, pinned to the same nixpkgs as devbox (or a nixpkgs with nim 2.2.12). Package and module live in-repo under `nix/`. Devbox stays the dev shell only.
Steps (sketch, no files written):
1. Un-ignore the packaging dir: remove `nix/` from `.gitignore` (or name it `packaging/nix/`). [local]
2. Declare a `bin` in `fff_vtt.nimble` once the entrypoint exists (for example `bin = @["main"]`, `srcDir` `server`). Until then the package is empty. Alternative: override `buildPhase`. [S5]
3. Decide mummy ref: keep `01deb1ff` (identical code to 0.4.8 except CI) or move both nimble and Nix to tag `0.4.8`. Fix the DESIGN "no tags" note either way. [S13]
4. Add `db_connector` pin to the lock (no tags upstream; pin the devbox `vcsRevision`). [S15]
5. Generate lock: `nix run <nixpkgs-with-nim_lk>#nim_lk -- <src> | jq --sort-keys > nix/lock.json`. Diff `rev`s against the devbox table in §2.4. [S2]
6. `nix/package.nix`: `buildNimPackage (finalAttrs: { pname = "fff-vtt-server"; version; src = lib.cleanSource ../.; lockFile = ./lock.json; nimFlags = ["--threads:on" "--mm:orc"]; ... })`. Let doCheck run `tests/t*.nim`. [S1][S5]
7. `nix/module.nix`: `options.services.fffVtt = { enable; package; port (127.0.0.1 only); publicOrigin; stateDir }`. `systemd.services.fff-vtt`: `wantedBy multi-user.target`, `DynamicUser`, `StateDirectory`, `ExecStart = ${cfg.package}/bin/<bin>`, hardening copied from nitter (§2.7), `AF_UNIX` only with sidecar. [S9][DESIGN L447]
8. Host: add `nix/module.nix` to `imports` in `server_nixos_configuration/configuration.nix` (path import or `builtins.fetchGit` pinned to a commit). Mirror `foundryvtt.nix` pattern. [local]
9. Smoke check: `nix build` the package; `nix-build` runs `nim r tests/t*.nim` via doCheck. Optional `nixosTests` VM test as nitter does. [S1][S9]
Fallback if `nim_lk` cannot resolve `mummy#<commit>` or db_connector: vendored deps with `nimFlags --path:` (§2.6). Nothing else changes.
## 4. Not checked / risks
- nim_lk CLI and its handling of `#commit` requires: unverified (sourcehut blocked).
- No `nix build` run; no lock generated; no fetch hashes computed. Hashes will come from `nim_lk`.
- Devbox nim 2.2.12 vs NP 2.2.4: pinned nixpkgs revision for the build not chosen yet.
- webby tags: none found via API. Pinned rev `325d6ade` is what the devbox resolved; upstream version list not checked.
- `nim_builder`'s `bin` handling assumes the root .nimble lists binaries; checked only the code, not a built example.
- atlas `atlas.lock` format not read in full; only the doc summary.
## 5. Sources
NixOS/nixpkgs @ c56a87d8e41ce69bd2af57eb35dcc117a9dfca33 (owner's system nixpkgs):
- [S1] https://github.com/NixOS/nixpkgs/blob/c56a87d8e41ce69bd2af57eb35dcc117a9dfca33/pkgs/build-support/build-nim-package.nix
- [S2] https://github.com/NixOS/nixpkgs/blob/c56a87d8e41ce69bd2af57eb35dcc117a9dfca33/doc/languages-frameworks/nim.section.md
- [S3] https://github.com/NixOS/nixpkgs/blob/c56a87d8e41ce69bd2af57eb35dcc117a9dfca33/pkgs/top-level/nim-overrides.nix
- [S4] https://github.com/NixOS/nixpkgs/blob/c56a87d8e41ce69bd2af57eb35dcc117a9dfca33/pkgs/by-name/ni/nim_lk/package.nix
- [S5] https://github.com/NixOS/nixpkgs/blob/c56a87d8e41ce69bd2af57eb35dcc117a9dfca33/pkgs/by-name/ni/nim_builder/nim_builder.nim
- [S7] https://github.com/NixOS/nixpkgs/blob/c56a87d8e41ce69bd2af57eb35dcc117a9dfca33/pkgs/by-name/ni/nimdow/lock.json
- [S8] https://github.com/NixOS/nixpkgs/blob/c56a87d8e41ce69bd2af57eb35dcc117a9dfca33/pkgs/by-name/ni/nimlangserver/lock.json
- [S9] https://github.com/NixOS/nixpkgs/blob/c56a87d8e41ce69bd2af57eb35dcc117a9dfca33/nixos/modules/services/misc/nitter.nix
- [S-nitter-pkg] https://github.com/NixOS/nixpkgs/blob/c56a87d8e41ce69bd2af57eb35dcc117a9dfca33/pkgs/by-name/ni/nitter/package.nix
- [S10] https://github.com/NixOS/nixpkgs/blob/c56a87d8e41ce69bd2af57eb35dcc117a9dfca33/pkgs/by-name/ni/nim-2_2/package.nix
- [S11] https://github.com/NixOS/nixpkgs/blob/c56a87d8e41ce69bd2af57eb35dcc117a9dfca33/pkgs/by-name/ni/nim-atlas/package.nix
- [all-packages] https://github.com/NixOS/nixpkgs/blob/c56a87d8e41ce69bd2af57eb35dcc117a9dfca33/pkgs/top-level/all-packages.nix (L4246-4255: nim, nim1, nim2, buildNimPackage, nimOverrides)
Upstream:
- [S12] mummy nimble @ pin: https://github.com/guzba/mummy/blob/01deb1ff694988635c7bf0f24f6088a0bdf6db5d/mummy.nimble
- [MUM README] https://github.com/guzba/mummy/blob/01deb1ff694988635c7bf0f24f6088a0bdf6db5d/README.md
- [S13] tag compare: https://api.github.com/repos/guzba/mummy/compare/77a7563e87a1045e4e407a3a68731e299fa3507e...01deb1ff694988635c7bf0f24f6088a0bdf6db5d
- [S14] mummy tags: https://api.github.com/repos/guzba/mummy/tags
- [S15] db_connector nimble: https://github.com/nim-lang/db_connector/blob/master/db_connector.nimble
- [S17] atlas doc: https://github.com/nim-lang/atlas/blob/master/doc/atlas.md
- [S18] nimble lockfile impl: https://github.com/nim-lang/nimble/blob/master/src/nimblepkg/lockfile.nim
- [API] zippy/crunchy/nimsimd tags: https://api.github.com/repos/guzba/zippy/tags , https://api.github.com/repos/guzba/crunchy/tags , https://api.github.com/repos/guzba/nimsimd/tags
Local (read-only):
- devbox.json / devbox.lock: /home/davide/Projects/GDR/FFF_vtt/devbox.json, /home/davide/Projects/GDR/FFF_vtt/devbox.lock
- devbox nimble cache (vcsRevision): /home/davide/Projects/GDR/FFF_vtt/prototype-server-vision/.devbox/nimble/pkgs2/*/nimblemeta.json
- nim 2.2.4 stdlib (threads default, no db_* modules): /nix/store/aa4fgarndnvq417l50imvqx5fdrrx9sn-nim-unwrapped-2.2.4/nim/config/nim.cfg, /nix/store/aa4fgarndnvq417l50imvqx5fdrrx9sn-nim-unwrapped-2.2.4/nim/lib
- owner config: /home/davide/Projects/server_nixos_configuration/configuration.nix, foundryvtt.nix
- repo .gitignore: /home/davide/Projects/GDR/FFF_vtt/.gitignore
+181
View File
@@ -0,0 +1,181 @@
# How virtual tabletops model wall kinds
Date: 2026-11-15. Ticket: #40 (map #38). **Research only: no decision taken, nothing here is a proposal to copy a product's design.** The owner decides the model on #42.
Question: how do existing VTTs and map formats model wall kinds — independent restriction flags for sight/movement vs fixed kinds; windows, one-way, secret, locked, terrain — and what does each model imply for a server that alone decides what each player sees (DESIGN §1 goal, §3.1 view rule: players never receive wall data)?
Sources are first-party docs and published data models, read on 2026-11-15. Versions and pins are in [Sources](#sources).
## TL;DR
1. Two model families exist. **Independent restriction axes** (Foundry: `light`/`sight`/`sound`/`move`, each an enum; Fantasy Grounds: per-occluder `Allow Vision`/`Allow Movement`/`Shadows` toggles) and **kind taxonomies** (MapTool VBL types; UVTT portals with a single `closed` flag). Every product that ships a taxonomy also ships presets *on top of* axes (Foundry "Solid/Terrain/Invisible/Ethereal/Door/Secret/Window/Blank", FG Wall/Terrain/Door/Secret/Window/Illusionary/Pit/Shadow), so the presets are UI shortcuts, not the storage model. [S1][S2][S9][S12][S13]
2. Door is orthogonal to the barrier: a *door type* (`none`/`door`/`secret`) plus a *door state* (`closed`/`open`/`locked`). Foundry stores exactly that (`door`, `ds`); FG stores toggleable + hidden + open + locked; Roll20 makes doors/windows separate portal objects placed beside barrier lines. Secret and locked are never separate geometry kinds. [S1][S2][S6][S7][S9][S10][S11]
3. One-way is a **direction axis on the barrier**, not a kind: Foundry `dir` ∈ {both,left,right} "direction of effect"; FG `Single-Sided` plus point winding order to reverse the blocked side; Roll20 "One Way" barrier with a direction toggle. MapTool has no one-way vision blocking at all (stated limitation). [S1][S5][S9][S10][S12]
4. "Window" is modelled two incompatible ways: a **distance-limited sight barrier** (Foundry: blocks movement; sight/sound only beyond a distance) or a **see-through movable portal** (FG, Roll20: see through, cannot pass unless opened, can be locked). Neither is a plain "transparent wall". [S1][S9][S10][S11]
5. "Terrain" is a naming trap. Foundry *Terrain Wall* blocks movement and sound and lets sight pass only past the second such wall; FG *Terrain* lets you see into the area but not beyond; MapTool *hill/pit/cover* are area visibility types. **"Blocks movement, not sight"** is Foundry *Invisible Wall* and Roll20 *Transparent barrier*, not Foundry "Terrain Wall". [S1][S9][S10][S12]
6. Low-wall / see-over behaviour is expressed as: a **limited** sight rule where the first barrier is transparent and the second blocks (Foundry), **area semantics** where the far edge blocks (FG terrain, MapTool hill/pit), or **distance thresholds** (Foundry `threshold`/proximity). None of these is a boolean "low" flag. [S1][S2][S8][S9][S12]
7. The interop format is the weakest: UVTT 0.3 has sight-blocking line strings, sight-blocking object rings and portals that only carry `closed`; there is **no movement blocking, no door/secret/locked field, no window, no direction** in the schema. (A real `.dd2vtt` sample confirms the portal shape.) Importers must therefore default or use out-of-spec fields. [S13][S14][S10]
8. None of these products' docs promise data-level withholding from players; they promise UI-level hiding ("Players do not have the ability to create, view, edit, or delete Walls" — Foundry KB). Our rule is stronger: the wall row never leaves the server (DESIGN §3.1). So the only player-observable effects of a new kind in our system are the vision polygon, explored grid, tiles and token frames. [S1][S15]
## Findings with sources
### 1. Foundry Virtual Tabletop (v13 API, v14 KB)
Data model ([S2], API v13.350). A wall is one segment `c: [x0,y0,x1,y1]` plus independent restriction numbers and door metadata:
| field | meaning (verbatim summary of the API description) |
|---|---|
| `light` | "illumination restriction type" |
| `sight` | "visual restriction type" |
| `sound` | "auditory restriction type" |
| `move` | "movement restriction type" |
| `dir` | "direction of effect imposed by this wall" |
| `door` | "type of door which this wall contains, if any" |
| `ds` | "state of the door this wall contains" |
| `doorSound` | door sound asset |
| `threshold` | per-sense minimum distance for blocking + `attenuation` |
Enum values ([S3]–[S8]):
- senses: `NONE 0`, `LIMITED 10`, `NORMAL 20`, `PROXIMITY 30`, `DISTANCE 40`.
- movement: `NONE 0`, `NORMAL 20` — movement is the only all-or-nothing axis.
- directions: `BOTH 0`, `LEFT 1`, `RIGHT 2`.
- door types: `NONE 0`, `DOOR 1`, `SECRET 2`.
- door states: `CLOSED 0`, `OPEN 1`, `LOCKED 2`.
Semantics ([S1], KB "Walls", updated 2026-10-24, v14.369):
- "A Wall can 'restrict' any combination of light, sound, movement, and sensory perception… Each of these restrictions can be configured independently."
- Sense levels: None, Normal, Limited ("the first Wall with a Limited restriction… does not interfere at all, but the second… is fully blocking"), Proximity, Reverse Proximity. Limited is the mechanism behind the Terrain Wall preset.
- Presets: **Solid** (sight, sound, movement); **Terrain Wall** ("block movement and sound, and only block sight beyond the second wall… see an object but not see beyond it"); **Invisible Wall** ("block movement but allows sight and sounds"); **Ethereal Wall** ("allow movement but block sight and sounds"); **Door** (closed blocks movement/sight/sounds, open sets all restrictions to None, can be locked); **Secret Door** ("players are unable to interact with them, only GMs can"; icon never shown to players); **Window** ("block movement, and only block sight and sound beyond a certain distance… the closer a token moves, the more it can see and hear"); **Blank** (restricts nothing).
- Door rules: closed = behaves like any wall with its types/levels; open = "all temporarily set to None"; locked = closed, visible to players, cannot be opened, gives a rattle sound instead.
- Players: "do not have the ability to create, view, edit, or delete Walls" (a UI statement).
- Proximity levels are per-token distance checks with an optional attenuation; `threshold` in the data model is the same idea per light/sight/sound ([S8]).
Relevance to us: this is the flags model in its purest form plus a separate door type/state and a direction axis. Every named "kind" the owner listed (window, one-way, secret, locked, terrain) is expressible as a combination except secret/locked, which live on the door fields.
### 2. Fantasy Grounds Unity
Occluders are drawn per image in "Line of Sight Mode"; each occluder has a **mode** and a set of **advanced toggles** ([S9], FG wiki, updated 2026-10-14):
- Modes: **Wall** ("block line of sight and movement for players"); **Terrain** ("Players can see into the first terrain in their vision. The back edge of the terrain blocks line of sight much like a wall. Players inside of terrain can see out of it in all directions"); **Door** ("see the contents of a door, but not beyond it", open/close by hover, GM shift-click to lock); **Secret** ("act just like a wall to players. The GM, however, will have the option to open the secret door"); **Window** ("see through the window but not move through it unless it is opened first. Windows can be locked"); **Illusionary Wall** ("block line of sight just like a wall, but which do not restrict player movement"); **Pits** (block movement and vision when a token is inside; the GM can open/close); **Shadow Caster** (blocks light only).
- Advanced toggles apply to any occluder: **Is Toggleable**, **Hidden** (hide the toggle UI from players), **Open**, **Locked** ("Players will not be able to open or close this occluder. The hover UI will still be visible… unless the hidden option is also set"), **Single-Sided** ("only block vision in one direction. The dashed/dotted lines indicates the invisible side"), **Terrain**, **Pit**, **Allow Movement**, **Allow Vision**, **Closed Shape**, **Counter-Clockwise** ("switch the direction of single-sided occluders"), **Shadows**.
- Editing aids: **Split**, **Union**, **Trim Interior**, **Razor** (edit-only), **Peek** ("amount users can see past where the occluder is drawn").
Relevance: FG is also a flags model, but the flags are per-instance booleans layered over presets, and secret/hidden/locked are properties of "toggleable" occluders. Terrain and pit are **area** semantics, not line segments. "Illusionary Wall" is the inverse of our terrain: blocks sight, allows movement.
### 3. Roll20
Barrier layer ([S10], help article, updated 2026-07-16):
- Default barrier = "Walls": blocks vision/light from both sides.
- **Transparent** barrier: "allow light and vision to pass through while blocking movement"; drawn dashed; the article's example is bushes/stumps you can see over but not walk through.
- **One-Way** barrier: "allows light and vision to pass through from one side of the barrier but not the other"; triangles show the pass-through side, a button toggles direction.
- "Anything drawn or placed on this layer will block lighting or vision for Tokens on that page."
- The page setting **Restrict Movement** is separate from the barrier line; transparent/one-way and portals prompt to enable it.
Doors and windows are **separate portal objects**, not barrier segments ([S10][S11], updated 2025-10-27):
- Placed "beside barrier lines, not on barrier lines"; require Restrict Movement to work.
- One portal object with a **Door/Window** dropdown; toggles: **Secret** ("determines whether or not players can see your door"), **Locked** ("both GMs and players will be unable to open or close it"), **Opened** ("open doors cannot be locked").
- Window-specific: Locked, Opened, **Curtains** — "curtains on open windows will allow movement but block vision; and curtains on closed windows will block vision and movement."
- One-way barrier example: a balcony where those above can see below but not vice versa.
Relevance: barriers carry the axes; portals carry type + state. The same authoring surface exposes terrain ("transparent") and one-way without naming them kinds.
### 4. MapTool
Vision is blocked by a **Vision Blocking Layer** (VBL) of drawn topology, plus a **Movement Blocking Layer** (MBL) that never affects vision ([S12], RPTools wiki, rev 37400, edited 2026-07-08):
- VBL **types**: **wall** (opaque; "blocks any vision on its border and inside its area and therefore overrides the more sophisticated options of pit and hill VBLs"), **hill** ("Tokens outside… have vision into the area but not beyond. Tokens within the area have vision in the area and beyond"), **pit** ("Tokens outside… have vision in the area and beyond, but tokens within… only have vision within its confines"), **cover** ("can be seen out of, and within, but tokens outside the area cannot see into it"). Hill/pit/cover require solid area drawing tools.
- MBL: "does not affect vision, but the calculation for the path a token would take."
- Doors have **no type**: the article suggests erasing VBL at the doorway, rotating a door token, or using token VBL.
- Explicit limitations (as of 1.11.5): "Vision Blocking is Binary… no 'partially transparent' or 'one way' VBL"; blocks all forms of vision; "has no Elevation… it stretches to infinity"; no VBL explorer.
Relevance: the pure-kind model, with terrain-like semantics only in closed areas and no door/secret/locked/one-way support. It shows what a taxonomy without axes cannot express.
### 5. Universal VTT (map interchange format)
UVTT 0.3 schema ([S13], `kwvanderlinde/uvtt` master, JSON Schema 2020-12):
- Required: `format` (const 0.3), `resolution` (`map_origin`, `map_size`, `pixels_per_grid`), `environment` (`baked_lighting`, optional `ambient_light`), `image` (base64 PNG/WebP).
- `line_of_sight`: arrays of points, "a connected string of line segments. Each segment blocks line-of-sight."
- `objects_line_of_sight`: closed rings, same meaning for objects.
- `portals`: each has `position`, `bounds` (segment string), `rotation`, `closed` ("If true, the bounds of this portal blocks line-of-sight"), `freestanding` ("not associated with a wall"). **No door type, no secret, no locked, no movement flag, no direction, no window, no distance threshold.**
- A real `.dd2vtt` sample (`format: 0.3`) has a portal with only `{position, rotation, closed: true, freestanding: false}` and `environment: {baked_lighting, ambient_light}` — no extra kind fields ([S14]).
Consequence: a format-only import (M6 CLI) can express "blocks sight" and "open/closed portal". Terrain, windows, one-way, secret and locked have to come from defaults or non-spec extensions. Roll20's UVTT article nevertheless says "UVTT map files place walls, doors, windows, and lights automatically" ([S10]) — exporters add fields the 0.3 schema does not define; treat those as vendor extensions, not format guarantees.
### 6. Comparison
| | Foundry | Fantasy Grounds | Roll20 | MapTool | UVTT 0.3 |
|---|---|---|---|---|---|
| storage | flags (`light/sight/sound/move` enums) + door type/state + `dir` | presets + per-occluder booleans | barrier kind (wall/transparent/one-way) + portal objects | VBL type (wall/hill/pit/cover) + MBL | sight line strings + portals with `closed` |
| sight | enum incl. limited/proximity | mode/area + allow-vision toggle | barrier passes or not; portals see-through | type-dependent, binary | yes/no |
| movement | `move` enum | allow-movement toggle | page "Restrict movement" + transparent barrier | MBL separate | not expressible |
| sound | enum | (not in LOS page) | — | — | — |
| light | enum | shadow casters | light blocked with vision | — | baked or ambient only |
| one-way | `dir` | single-sided + winding | one-way barrier + direction | none (stated) | none |
| secret | door type `SECRET` | secret mode / hidden toggle | portal `Secret` | none | none |
| locked | door state `LOCKED` | `Locked` toggle | portal `Locked` | none | none |
| window | distance-limited sight preset | see-through lockable portal | see-through portal w/ curtains | none | none |
| terrain meaning | "Terrain Wall" = block move+sound, sight past 2nd; "Invisible Wall" = block move only | see into area, not past | transparent = block move, pass sight | hill/pit/cover areas | none |
### 7. Name collisions to keep straight
- **terrain**: Foundry *Terrain Wall* is not "blocks movement only"; that is Foundry *Invisible Wall*, Roll20 *Transparent*, FG *Allow Vision*. FG *Terrain* and MapTool *hill/pit* are area visibility rules. Our map's "terrain (blocks movement, not sight)" matches the second group, not the first.
- **window**: Foundry = distance-limited wall; FG/Roll20 = see-through, openable, lockable portal. "Window" does not imply "always transparent".
- **secret** and **locked** are attributes of a door, never geometry. In FG and Roll20 the locked UI stays visible unless separately hidden; in Foundry a locked door is visible to players by design.
- **one-way** is always a direction on the sight (or light) restriction, never a separate kind.
### 8. What our server must hide, per kind
Design constraints used here: the server alone decides what each player sees (§1); players never receive walls or doors, geometry or open/closed, over WS or HTTP, and vision polygons, explored grid, tiles and token frames are the only carrier of what they know (§3.1, §6.1). Every wall row (`kind`, `flags`, ids) is GM-only, and wall intent acks go to the GM only.
Because the data is withheld, the security question per kind is not "which field do we omit" but **"is any player-visible output different in a way that reveals the kind, beyond what the kind is supposed to do?"**
| kind | intended player-observable effect | must not be observable |
|---|---|---|
| plain wall | LOS polygon stops at it | nothing extra |
| window | sight passes within the window's rule (distance-limited, or see-through while closed) | the wall row, the threshold value, the fact that a *portal* exists vs a gap; do not send a door/window flag for rendering |
| one-way | one observer sees through, the other does not | a shared "wall blocks/does not block" bit; direction must be evaluated per viewer, never broadcast as state |
| secret door (closed) | byte-identical to a plain wall in vision, explored, tiles, tokens and refusal codes | its existence, id, kind, icon, door sound. If players ever push doors, the refusal for a secret door must equal the refusal for a solid wall |
| locked door | closed = like a wall; lock state is GM-only in v1 (GM-only `door.set`) | the lock state; and later, refusals must not distinguish locked / secret / solid |
| terrain (block move, not sight) | identical vision to no wall; movement stops or is refused | any vision difference (a terrain wall must be absent from the sight predicate), and any refusal text/code that names the cause |
| door open/closed | LOS changes, which is the point | door frames/ids/count; open state must reach players only through recomputed vision/explored/token views |
Additional consequences:
- These five kinds need no new player-facing wire field. They change the server's sight and move predicates and, for doors, the GM-only state. That keeps the §3.1 rule intact.
- A per-wall "visible/hidden" flag like Foundry's secret or FG's hidden is unnecessary here: nothing is sent, so a secret door is hidden for free. The only design work is rule equivalence and refusal indistinguishability.
- Wall counts already leak through timing/id gaps today (`wall.add` ack is GM-only, but vision changes are visible); §3.1 already forbids `hello` carrying wall counts. New kinds do not add a channel, as long as acks and refusal reasons stay kind-neutral.
- If a later kind is *not* fully hidden (e.g. a window that renders), that is a deliberate change to §3.1 and belongs to the owner, not to this research.
## Fog this research makes specifiable (tickets, not decisions)
These are candidate tickets for the map; none is created here and none decides #42's answer.
1. **Secret-door equivalence oracle**: for a closed secret door, every player-bound frame and every refusal must equal the same scene with a plain wall (vision polygon, explored diff, tiles, token frames, error codes), and no frame may carry a door/secret marker.
2. **Terrain oracle**: vision polygon and explored grid identical with and without a terrain wall; move rules treat it as a blocker; refusal codes identical to a solid wall.
3. **One-way oracle**: A sees B and B does not see A across the same wall, evaluated per observer; no shared wall state on the wire.
4. **Window semantics test**: distance threshold value (owner-delegated number) and the oracle "sees through within N, blocked beyond", with no window metadata in any player frame.
5. **Door-state indistinguishability** (depends on whether players ever interact with doors, already fog): locked vs secret vs solid must share one refusal.
6. **UVTT import gap** (#49 input): the format cannot express movement blocking, secret, locked or one-way; the M6 importer needs a documented default plus a sidecar/extension mapping.
7. **Flags-vs-kinds storage** (#42 input): the facts above give the axes (sight rule, move rule, direction, door type/state, distance threshold) that any storage choice must be able to hold; this is evidence for that ticket, not an answer.
## Not covered
- Sound blocking (out of scope for the map).
- Foundry's Levels/Regions and FG's lighting model beyond wall interaction.
- Any product's internal code; only published docs and data models were read (Foundry and FG are closed source).
- Behaviour of modules/extensions that add kinds (e.g. Foundry wall modules); not first-party.
## Sources
- [S1] Foundry VTT Knowledge Base, "Walls", updated 2026-10-24, v14.369 — https://foundryvtt.com/article/walls/
- [S2] Foundry API v13.350, `WallData` interface — https://foundryvtt.com/api/v13/interfaces/foundry.documents.types.WallData.html
- [S3] Foundry API, `CONST.WALL_SENSE_TYPES` — https://foundryvtt.com/api/v13/variables/CONST.WALL_SENSE_TYPES.html
- [S4] Foundry API, `CONST.WALL_MOVEMENT_TYPES` — https://foundryvtt.com/api/v13/variables/CONST.WALL_MOVEMENT_TYPES.html
- [S5] Foundry API, `CONST.WALL_DIRECTIONS` — https://foundryvtt.com/api/v13/variables/CONST.WALL_DIRECTIONS.html
- [S6] Foundry API, `CONST.WALL_DOOR_TYPES` — https://foundryvtt.com/api/v13/variables/CONST.WALL_DOOR_TYPES.html
- [S7] Foundry API, `CONST.WALL_DOOR_STATES` — https://foundryvtt.com/api/v13/variables/CONST.WALL_DOOR_STATES.html
- [S8] Foundry API, `WallThresholdData` — https://foundryvtt.com/api/v13/interfaces/foundry.documents.types.WallThresholdData.html
- [S9] Fantasy Grounds Unity wiki, "Line of Sight Mode - Image Control", updated 2026-10-14 — https://fantasygroundsunity.atlassian.net/wiki/spaces/FGCP/pages/4350115897
- [S10] Roll20 Help Center, "Creating Light, Windows, and Barriers", updated 2026-07-16 — https://help.roll20.net/hc/en-us/articles/360051768974-Creating-Light-Windows-and-Barriers
- [S11] Roll20 Help Center, "Placing Doors & Windows", updated 2025-10-27 — https://help.roll20.net/hc/en-us/articles/11462645998999-Placing-Doors-Windows
- [S12] RPTools wiki, "Introduction to Vision Blocking", rev 37400, edited 2026-07-08 — https://wiki.rptools.info/index.php/Introduction_to_Vision_Blocking
- [S13] UVTT JSON Schema 0.3, `kwvanderlinde/uvtt` master — https://github.com/kwvanderlinde/uvtt/blob/master/0.3.schema.json
- [S14] Sample `test.dd2vtt` (format 0.3), `oganm/dd2vtt_importer` main — https://github.com/oganm/dd2vtt_importer/blob/main/test.dd2vtt
- [S15] Local: `docs/DESIGN.md` §1 goal, §3.1 view rule, §6.1 wall payloads, §8 wall/door record — https://git.fossellini.top/SirStone/FFF_vtt/src/branch/main/docs/DESIGN.md (repo `main`, 2026-11-15)
+321
View File
@@ -0,0 +1,321 @@
# Sight with thick and low walls
Research for ticket [#39](https://git.fossellini.top/SirStone/FFF_vtt/issues/39), map [#38](https://git.fossellini.top/SirStone/FFF_vtt/issues/38).
Scope: how 2D top-down sight systems handle **wall thickness** and **wall height (see-over)**, and what each option costs
against our sight budget (polygon < 1 ms, 5k-wall scene, per-move recompute). Facts and trade-offs only:
the decisions belong to the owner on the later cards (#41 height model, #44 low walls, #45 thick walls).
Everything marked **[MEASURED, #39]** was measured for this ticket on scratch copies of our own code under
`/tmp/opencode/thickbench/` (method in §5); nothing in the repo was modified to measure. Pre-existing numbers marked
`results/bench.log` are the committed bench. **[DERIVED]** is elementary geometry worked out here. **[INFERRED]** is a
conclusion from cited facts that nobody measured.
## TL;DR
1. **Thickness in the ray fan is a 4–10× polygon cost, not a 4× one.** A rectangular wall (4 segments) turns 6 rays per
wall into 24 and 1 segment into 4: measured **0.257 ms** on the 5k sparse scene (15.6 walls in the vision box, still
inside the 1 ms target) and **12.8 ms** on the 5k dense one (206.9 walls in the box, 9.9× over). Cheaper variants
exist: 2 offset faces = 3.8 ms dense (3.0×), 1 near face = same cost as today's thin wall [MEASURED, #39].
2. **Thickness barely changes the explored set on a realistic map, and a lot on a pathological one:** cells that flip
from visible to hidden against a 10 px wall are 4.6 % of the polygon on the prototype scene, 10 % on 5k sparse,
53 % on 5k dense [MEASURED, #39]. Thick polygons are always a *subset* of thin ones (0 cells gained, measured).
3. **Height cannot be expressed by one 2D polygon.** The region behind a low wall that is hidden is a *band* whose depth
depends on the viewer's distance to the wall (`d_floor = s · h_eye / (h_eye − h_wall)`), so the shadow boundary is a
curve, and a ray fan can only shorten rays, never restart them [DERIVED]. Every engine surveyed therefore does height
as a per-token or per-ray *predicate*, not as occlusion geometry.
4. **The cheapest see-over that is expressible in our raycaster is a distance threshold per ray** (one float compare per
candidate hit): measured **within noise of today** (0.088 vs 0.084 ms sparse; 1.18 vs 1.28 ms dense) and it is exactly
Foundry's "Proximity / Reverse Proximity" restriction. Per-target 3D LOS on top of the polygon costs **0.55–0.60 ms per
40 targets** at 5k walls without a wall index (0.10 ms with the candidate walls precomputed) [MEASURED, #39].
5. **Nothing about the explored format, the wire polygon shape or the tile gate changes**: explored chunks stay 64×64 =
512 B, the wire stays a full integer-px polygon (Q16), the gate stays one cell = one tile. What changes is the vertex
count (2.5–3.7× [MEASURED, #39]) and the independent leak-checker oracle, which is currently zero-width.
## 1. Our baseline, exactly
- One wall record, one predicate: `Wall{a, b, door, open}` and `blocks = not (door and open)` (`server/geometry.nim:18-26`).
Anything that blocks is a **zero-width segment**; there is no width or height field anywhere in the model
(`DESIGN` §8 "Wall/Door": `blocks = not (door and open)`, later kinds are extra `kind`/`flags` values and "v1 geometry
treats any non-open blocker identically").
- The polygon (`server/geometry.nim:41-69`): rays at ±`RayEps` = 1e-4 rad around every wall endpoint (3 rays per
endpoint), plus an inscribed 64-gon of the vision radius; each ray takes the **nearest** hit among all segments + the
64-gon; bbox cull against the radius box (`:52-56`). Cost is `O(rays × segments)`, and both numbers grow with the wall
count in the box (`DESIGN` §5.3, §5.4).
- Cells: `cellsTouched` is a scanline over the polygon (`server/geometry.nim:100-141`); `vision.refresh` unions the
result into the player's explored set and hands the delta to egress (`server/vision.nim:58-74`). Explored is stored as
64×64-cell chunks of 512 B (`server/explored.nim:26-30`), and the tile gate unlocks a 32 px tile iff its cell is
explored (`DESIGN` §3.3, Q4).
- Wire: the full polygon, integer px, only on change (`DESIGN` Q16, `server/vision.nim:20-21`); client fog draws the
polygon into a mask and the explored bitmap separately (`DESIGN` §7.3).
- Movements: `dist(c, W) < r` for stuck/overlap and the capsule test in `pathClear` (`server/moverules.nim:137-149`,
`:157-159`); both are distance-to-*segment* computations.
- Baseline numbers (`results/bench.log`, prototype scene 60 walls / radius 400 / cell 32): 1 polygon 0.037 ms, polygon +
cells 0.048 ms, 6 polygons + cells 0.267 ms, server recompute per move 1.18 ms avg / 4.55 ms worst; 5k sparse polygon
0.083 ms, 5k dense polygon 1.282 ms (dense = stress reference, ~207 walls in the vision box).
- Interim rule in force from #26: a zero-width wall hides exactly what is behind it on the line (`GLOSSARY.md` `Wall`;
map #38 Notes).
## 2. Thick walls
### 2.1 What thickness does to a sight polygon
A wall with thickness `t` is a body, so three things change [DERIVED, confirmed by the spot checks in §5]:
- the **wall body itself is hidden** (previously a zero-area line, now a strip of width `t`);
- the **shadow boundary moves out by `t/2`** on the far side, and the shadow of the two ends widens by `t/2` each, so the
shadow is a slightly wider wedge; at a distance `s` behind the wall the lateral error of the thin model is about
`(t/2)(1 + s/d_wall)` — 10 px of a 10 px wall at 400 px range behind a wall 400 px away;
- **joints stop leaking**: two rectangles meeting at an angle overlap, where two zero-width segments leave a sliver at the
shared vertex (the same class of artefact our boundary `RayEps` ambiguity already covers, `DESIGN` §5.4);
- a **door opening becomes a slot of depth `t`**, and the door as an object has a leaf rectangle rather than a line.
Because a thick wall's polygon is the union of its body and a widened shadow, the thick polygon is a **subset** of the
thin one. Sampling 50–200 origins per scene, cells gained by thickness were **0** in every scene; cells lost
[MEASURED, #39]:
| scene | explored cells per polygon (thin) | thin-only | thick-only | share lost |
|---|---|---|---|---|
| prototype (60 walls, 4096 px, rooms ≈ 500 px) | 390 | 18 | 0 | 4.6 % |
| 5k sparse (16.4k px, 15.6 walls/box) | 216 | 21 | 0 | 9.7 % |
| 5k dense (4.1k px, 206.9 walls/box, rooms ≈ 82 px) | 59 | 31 | 0 | 53 % |
Read: thickness costs explored area in proportion to `t / room size`. In the dense stress layout the "rooms" are 2.5
cells wide, so a 10 px wall eats half of what a token can see; on the prototype-scale map it is one cell border here and
there — inside the one-cell residual leak of Q4/§3.3.
### 2.2 Four representations, and the measured price
A thick wall is a polygon obstacle; there is no way to keep one segment and be exact. The four implementations differ only
in how many extra segments and vertices they add to the same ray fan:
| variant | segments per wall | endpoints (rays) per wall | prototype 60 walls | 5k sparse (15.6/box) | 5k dense (206.9/box) |
|---|---|---|---|---|---|
| thin, today | 1 | 2 (6 rays) | 0.038 ms | 0.084 ms | 1.284 ms |
| 1 near face, offset `t/2` toward the viewer | 1 | 2 (6 rays) | 0.034 ms | 0.174 ms\* | 1.328 ms\* |
| 2 offset faces (no caps) | 2 | 4 (12 rays) | 0.052 ms | 0.136 ms | 3.760 ms |
| 4-edge quad (exact) | 4 | 8 (24 rays) | 0.079 ms | 0.257 ms | 12.779 ms |
[MEASURED, #39], same harness and machine class as `results/bench.log` (thin numbers reproduce: 0.038 vs 0.037 committed,
1.284 vs 1.282). \*The near-face row includes building 5000 offset segments *inside* the timed call: that expansion alone
costs ~0.09 ms per 5000 walls; hoisted (as for the other rows) it is the same work as thin. The quad/face rows exclude
their one-time expansion (`DESIGN`-style: once per wall edit, not per query).
Why not 4×: rays and segments both grow, so the raw work is ~16× per wall; measured 9.9× dense, 3.1× sparse, because the
fixed 64-gon and the sort dominate at low wall counts.
Side effects of each variant:
- **Near face only** hides everything behind the near face, i.e. the wall body plus its shadow, which is what a *solid*
wall should do; what it gets wrong is the far half: an object *inside* the far half of the wall band is treated as
visible-ish, and the shadow boundary sits at `t/2` in front of where the exact model puts it. Cost: zero.
- **2 faces** is the same approximation with a more honest boundary (the near face blocks, then the far face is
unreachable); it buys nothing over the near face in the polygon (`⊂`), for 1.6–3.0× the cost.
- **4-edge quad** is exact for a rectangular wall (modulo the `±RayEps` ambiguity at its 8 vertices).
### 2.3 Against the budget
The M2 target is "polygon < 1 ms on the 5k-wall scene" (`DESIGN` §5.3, `results/bench.log`), and the per-move server
recompute budget in play is ~1.2 ms avg / 4.55 ms worst (`DESIGN` §5.3).
- **5k sparse (realistic density for a 16k px map): quads pass** at 0.257 ms; 2 faces 0.136 ms; near face ≈ thin.
- **5k dense (stress): all exact variants miss.** Quads 12.8 ms (12.8× the target), 2 faces 3.8 ms, near face 1.33 ms.
- **A 6-token party in one recompute** (dense): 6 thick polygons = 75.6 ms vs 7.7 ms thin [MEASURED, #39]. That is the
number that matters if a real map ever reaches ~200 walls in an 800×800 vision box.
- Wire: thickness adds vertices to the polygon that is sent on every change — 2.5× (sparse) to 3.7× (dense) more
vertices than today (158→398, 1303→4866 average) [MEASURED, #39]. Q16 measured 3.4–3.7 KB per mover delivery for the
thin polygon; the thick one would be ~2.5–3.7× that [INFERRED].
- `cellsTouched` on a thick polygon: 0.281 vs 0.257 ms sparse, 12.82 vs 12.78 ms dense — i.e. ~+3 %, because the
scanline cost is dominated by rows spanned, not by vertices [MEASURED, #39].
- Move checks: `pathClear` over 4 edges per wall = 0.030 ms vs 0.010 ms dense (3.0×), 0.034 vs 0.010 sparse
[MEASURED, #39] — irrelevant next to the 0.7 ms move-ack cost (`DESIGN` #21 decision).
**The asymptotics are the real limit.** A spatial index (`DESIGN` §5.5 "Wall index", H3) does not help: the bbox cull
already restricts the work to walls in the vision box, and thickness multiplies the work *per wall in the box*. Only a
different algorithm changes that: a rotational sweep is `O(n log n)` (Asano 1985; CGAL `Visibility_2`, measured 50×
faster than the naive fan in Red Blob's reading), and Bungiu et al. 2014 give a linear-time-per-query method after
preprocessing. Both are a rewrite of `visibilityPolygon`, not a wall-model change.
### 2.4 Precedent for representing thickness
- **Polygon obstacles are the standard formulation.** Red Blob's visibility article covers segments and has a companion
page for polygon obstacles; a thick wall is simply a convex polygon in that model.
- **The interchange format agrees.** Universal VTT (Dungeondraft / Dungeon Alchemist / Arkenforge / DungeonFog export;
imported by Foundry via a module, and natively by Roll20 and Fantasy Grounds) separates two lists: `line_of_sight`
(arrays of points — thin walls) and `objects_line_of_sight` (arrays of points per object — thick obstacles), plus
`portals` (doors/windows with `bounds` and `closed`). Thickness lives in the polygon list, not in the wall list.
- **Roll20's barrier layer is polygon drawing**: rectangles and shapes on the Dynamic Lighting layer block light, and a
"thick wall" is drawn as a shape rather than a line.
## 3. Low walls: what "see over" can mean in a 2D top-down view
### 3.1 Two different questions
A low wall splits into two questions that our pipeline answers in two different places:
1. **What does the fog/explored set cover?** — driven by the visibility polygon (§1). Binary per point.
2. **Is a token hidden behind it?** — driven by `insideAny(poly)` today (`server/vision.nim:95-101`), i.e. also binary.
A height model that only changes (2) leaves the explored set conservative (the ground behind a low wall stays fogged
until something else reveals it); one that changes (1) rewrites the polygon and therefore the explored set and the tile
gate.
### 3.2 What the engines actually do
- **Foundry VTT** (KB "Walls", updated 2026-10-24, v14.369): each wall has four independent restrictions (movement,
light, sight/senses, sound) with levels **None / Normal / Limited / Proximity / Reverse Proximity**:
- *Limited* ("Terrain Wall" preset): "the first Wall with a Limited restriction in the way does not interfere at all,
but the second Limited wall is fully blocking" — you see the bush or the building, not through it.
- *Proximity*: "blocking, but only for tokens that are far enough away"; *Reverse Proximity*: "only for tokens that are
close enough", applied at a configured distance from the wall in grid units, with optional **attenuation** that lets
"a small but increasing radius of … vision … pass through the wall".
- Presets: Solid, Terrain, Invisible (blocks movement only), Ethereal (blocks sight/sound only), Door, Secret Door,
**Window** ("only block sight and sound beyond a certain distance. The closer a token moves, the more it can see").
- **No wall height in core**: the maintainer, answering the eight-year request for a height property, wrote "As part of
working on Scene Levels we have intentionally chosen *not* to make this change. Walls are treated as infinite height,
but only apply within the Level that they belong to" (foundryvtt/foundryvtt#1829, 2026-02-20).
- **The "Wall Height" module** (schultzcole/FVTT-Wall-Height, GPL, archived) is the reference implementation of height
*without* touching the fog polygon: each wall gets `wallHeightTop` / `wallHeightBottom` flags (default `+∞`/`−∞`), and
the module wraps the collision predicate `WallsLayer.testWall(ray, wall)` to return "no hit" unless the observer
token's `elevation` lies inside `[bottom, top)`. So see-over is a **binary per wall, per observer** decision inside the
raycast — the polygon is unchanged, and a low wall is fully transparent or fully blocking for a given token.
- **Fantasy Grounds Unity**: the LOS layer has occluder *types* Wall, Terrain, Door, Secret; terrain behaves as a region:
"If players are outside of a terrain section, they will be able to see the entire contents of the first terrain that
their vision reveals. They will not be able to see past it. If players are inside of a terrain section, they will be
able to see out of it in every direction" (Map Line of Sight Style Guide, 2022). Same idiom as Foundry's *Limited*.
- **Roll20**: barriers on the Dynamic Lighting layer block vision and light; **Transparent** barriers block movement but
not vision ("players can see over the bushes but can not walk through the thicker areas"); **One Way** barriers pass
vision "from one side of the barrier but not the other", and the documented use is elevation ("anyone on the balcony
above the stairwell can see everything happening below them but anyone below is unable to see onto the balcony")
(Help Center, updated 2026-07-16).
Pattern: **no surveyed engine puts height into the sight polygon.** They all model "see over" as a predicate — a
per-restriction distance threshold, a region flag, or a per-token elevation gate — and keep the occluder geometry 2D.
### 3.3 Why height cannot go into one polygon [DERIVED]
Eye at height `h_e`, wall top at `h_w < h_e`, wall at horizontal distance `s`, target on the floor at distance `d > s`.
The sight line's height where it crosses the wall is `h_e · (1 − s/d)`. The target is hidden iff
```
h_e · (1 − s/d) < h_w ⇔ d < s · h_e / (h_e − h_w) =: d_floor
```
So a low wall hides a **band** immediately behind it, of depth `d_floor − s = s · h_w / (h_e − h_w)`, and the floor
beyond `d_floor` is visible again. Two consequences:
- The boundary between hidden and visible behind a low wall is a **curve** whose position depends on the *viewer's*
distance to that wall, not only on the wall's geometry.
- A visibility polygon is "the nearest hit along each ray". A ray can be shortened, never resumed: geometry added behind
a wall only hides more. Therefore a single 2D polygon cannot represent "hidden for 100 px, then visible again" — the
representation has to become a predicate (per point, per cell, or per ray) or a binary collapse.
Worked numbers for a human eye at 1.6 m (5 ft ≈ 1.6 m; the unit choice is #41's, not this ticket's): a 0.9 m wall at 5 m
hides floor out to `5 · 1.6 / (1.6 − 0.9) = 11.4 m` (band 6.4 m); the same wall at 20 m hides out to 45.7 m. Near the wall
you see almost nothing over it; far from it you see well over it. (Foundry's *Reverse Proximity* documents this same
asymmetry: "When a token is immediately next to the Wall, the restriction is fully blocking. As the token moves away, the
restriction is gradually eased".)
### 3.4 Four implementable families, with measured cost
| family | semantics | fog/explored | cost against today (sparse / dense) |
|---|---|---|---|
| **A. flag**: low walls do not block sight | see-over always, at any distance | polygon loses the low wall entirely; explored grows | 0 (predicate already exists) |
| **B. per-ray distance threshold** ("horizon circle") | a low wall blocks only hits farther than `R_h = R·(1 − h_w/h_e)` from the eye; one radius per wall height | polygon correct in the *far* field, no near-field band; explored grows near the wall | **0.088 / 1.18 ms** vs 0.084 / 1.28 — free [MEASURED, #39] |
| **C. per-target 3D LOS** on top of the 2D polygon | exact `d < d_floor` test per token (the Wall Height model, with a real comparison instead of an elevation band) | polygon unchanged (conservative) | **0.55–0.60 ms per 40 targets** at 5k walls unindexed; **0.10 ms** with candidate walls precomputed; today's `insideAny` for 40 targets is 0.004 / 0.025 ms [MEASURED, #39] |
| **D. two polygons**: strict (low walls block) + permissive (they do not) | fog = strict, token visibility = permissive, GM sees where they differ | no new geometry, 2× polygon cost (or 1× if the permissive one is only recomputed on wall edits) | +1 polygon per token = +0.084 / +1.28 ms [MEASURED, #39] |
Notes on B: the threshold is exactly Foundry's Proximity/Reverse-Proximity machinery expressed in our geometry, and it is
the only variant that keeps the *polygon* (and therefore the fog and the tile gate) responsive to height at near-zero
cost. It is also the least faithful: it cannot show the near-field band, and all low walls of one height produce shadows
starting at one circle. Attenuation (Foundry's partial pass-through) has no analogue in a nearest-hit ray fan without
turning each low wall into a graded occluder — out of scope of anything measured here.
Notes on C: without a spatial index the 40-target pass costs 0.45 ms just scanning 5000 wall bboxes; that is the number to
compare with the 1.2 ms per-move budget, not the 0.10 ms candidate number. `pathClear` (0.010 ms) is the closest existing
piece of code and is the natural place for such a predicate.
## 4. What this means for our pipeline (concrete, per file)
| place | what thickness/height touches | fact |
|---|---|---|
| `server/geometry.nim:18-20` `Wall` | + `thickness`, + `height`/kind bits | the record is copied into `geometryWalls` (`server/worldmap.nim:20-24`) and into every test fixture |
| `visibilityPolygon` | 1→4 segments per thick wall; low-wall predicate per hit | §2.2 table; not an interface change if thickness is expanded before the call |
| `cellsTouched`, `server/vision.nim` | unchanged code | cells follow the polygon; thick polygons are subsets (§2.1) |
| `server/explored.nim` | **no change** | chunks stay 64×64 cells = 512 B, bit layout pinned (#21) |
| wire `vision` (Q16) | full polygon, integer px | only the vertex count changes: 2.5–3.7× [MEASURED, #39] |
| tile gate (`DESIGN` §3.3) | no mechanism change | a tile is unlocked iff its cell is explored; thickness/height changes *which* cells, and the 32 px residual (Q4) already covers sub-cell wall widths |
| `server/moverules.nim:137-149,157-159` | `dist(c, W)` must become distance-to-rectangle; `pathClear` 3.0× | 0.010 → 0.030 ms dense [MEASURED, #39]; door push is perpendicular-to-segment and needs the leaf geometry |
| `tools/leakcheck.nim:192-197` `clearLine` | zero-width by construction | an independent oracle for thickness needs the same 4 edges (or a rectangle distance test) and a tolerance statement; the GEOMETRY check (`:644-660`) samples 64 angles × 3 radii and would need re-baselining |
| `tools/bench.nim` | 5k scenes already exist | a thick/low variant is a new arm in the same harness; numbers in §2.2/§3.4 are what to expect |
| `DESIGN` §5.3 table | needs a re-baseline | this doc supplies the delta (thin 1.28 → quad 12.8 ms dense; 0.084 → 0.257 sparse) |
Thresholds worth stating before #44/#45 decide anything: the decision between "thickness in the polygon" and "thickness
only in movement + the wall body" turns on whether real maps look like the sparse layout (16 walls per 800 px box → quads
cost 0.26 ms, affordable) or approach the dense one (207 → 12.8 ms, not).
## 5. Measurement method
- Scratch tree `/tmp/opencode/thickbench/`: `geometry.nim` copied verbatim from `server/geometry.nim`; `testutil.nim`,
`scenegen.nim`, `moverules.nim`, `tests/fixtures/scene.json` copied verbatim (imports flattened); `thickgeom.nim` is
`visibilityPolygon` re-expressed over an explicit segment list (with an optional per-segment top height) and the three
wall expansions (`expandQuads`, `expandFaces`, `expandNearFace`); `bench2.nim` mirrors `tools/bench.nim` (50 warm-up
iterations, O(1) accumulators, avg + worst, `-d:release`).
- The re-expressed fan reproduces the shipped one exactly: on 200 origins of the prototype scene (jittered starts,
`geometry.visibilityPolygon` vs `polyFromSegs` over the same segments) both polygons have the same length and every
vertex agrees to < 1e-6 px — 200/200 identical, 0 different. It times slightly faster (0.033 vs 0.038 ms), a codegen
difference between the two module layouts, not an algorithmic one.
- Correctness spot checks in the harness (a vertical wall at x=100, eye at (0,100), radius 400): the thin polygon hides
(102,100) and (350,100); the 10 px quad hides its own body (98,100) and still hides (350,100) — i.e. thickness only
shifts the boundary; with a wall top at half the eye height, (350,100) is visible over a wall at x=50 and hidden behind
one at x=300, and the per-target predicate agrees (`false` / `true`).
- Caveats: single machine, power-save class, same class as `results/bench.log` (thin numbers match); the 5k dense layout
is a stress reference, not a real map (`DESIGN` §5.3); client fog rendering, network bytes and a wall spatial index are
**not** measured here.
## 6. Sources
- Our code and design: `server/geometry.nim`, `server/vision.nim`, `server/explored.nim`, `server/moverules.nim`,
`server/worldmap.nim`, `tools/bench.nim`, `tools/leakcheck.nim`, `tests/fixtures/scene.json`, `results/bench.log`;
`docs/DESIGN.md` §3.3, §5.1, §5.3, §5.4, §5.5, §6.1, §7.3, §8, §10.2, §10.3, Q4, Q16, H3; `GLOSSARY.md` `Wall`.
- Foundry VTT, *Walls* (Knowledge Base, updated 2026-10-24, v14.369) — restriction types, restriction levels
(None/Normal/Limited/Proximity/Reverse Proximity), attenuation, presets (Terrain, Invisible, Ethereal, Door, Secret
Door, Window) — <https://foundryvtt.com/article/walls/>
- Foundry VTT issue #1829, "Support a height property for Wall objects…" (opened 2019, closed not planned 2026-02-20,
including the maintainer's statement that walls are infinite height and bounded by their Scene Level) —
<https://github.com/foundryvtt/foundryvtt/issues/1829>
- `schultzcole/FVTT-Wall-Height` (GPL-3.0, archived): `scripts/utils.js`, `scripts/patches.js` (wraps
`WallsLayer.testWall` with a `wallHeightTop`/`wallHeightBottom` vs token `elevation` test) —
<https://github.com/schultzcole/FVTT-Wall-Height>
- Fantasy Grounds Unity, *Map Line of Sight Style Guide* (2022): Wall/Terrain/Door/Secret occluders; terrain "see the
first terrain, not past it" —
<https://fantasygroundsunity.atlassian.net/wiki/spaces/FGCP/pages/996640584/Map+Line+of+Sight+Style+Guide>
- Roll20 Help Center, *Creating Light, Windows, and Barriers* (updated 2026-07-16): barrier layer, Transparent and
One-Way barriers with the balcony (elevation) example, doors/windows — <https://help.roll20.net/hc/en-us/articles/360051768974-Creating-Light-Windows-and-Barriers>
- Red Blob Games, *2D Visibility* (2012, rev. 2020): the ray-to-each-endpoint algorithm, the rotational sweep, and the
performance note that CGAL's linear-time algorithm is ~50× faster than the sweep; plus the subtractive/shadow-quad
alternative — <https://www.redblobgames.com/articles/visibility/>
- Red Blob Games, *Thin wall field of view* (2021, unpublished notes): FOV when walls are line segments on cell edges
rather than cells, and the symmetry problems that follow — <https://www.redblobgames.com/x/2128-thin-wall-fov/>
- Universal VTT format (`line_of_sight` polylines, `objects_line_of_sight` polygons, `portals`) as documented by Arkenforge
— <https://arkenforge.com/universal-vtt-files/>; Roll20's import support —
<https://help.roll20.net/hc/en-us/articles/41643201127831-Universal-Virtual-Tabletop-UVTT-Support>
- F. Bungiu, M. Hemmer, J. Hershberger, K. Huang, A. Kröller, *Efficient Computation of Visibility Polygons*,
arXiv:1403.3905 (2014) — <https://arxiv.org/abs/1403.3905>
- T. Asano, *An efficient algorithm for finding the visibility polygon for a polygonal region with holes*, IEICE
Transactions 68(9), 1985 (cited via Red Blob's reference list; the paper itself is not online).
## 7. What this research does not decide (inputs for #41, #44, #45)
- **Height model**: what `h_e`, `h_w` and the target height are, in what units, and whether height is a per-wall number,
a per-kind default (low wall / window), or a per-token elevation (#41). §3.3 needs all three to produce a number.
- **Which of families A–D feeds the fog** (#44). They differ in cost (A zero, B zero, C +0.1…0.6 ms, D +1 polygon) *and*
in what players remember: only A/B/D change the explored set, so only they change what a tile unlocks.
- **Thickness in the polygon or only in movement** (#45). Quads pass the 1 ms target at 15.6 walls/box and miss it by 12×
at 207; the near face costs nothing but puts the shadow boundary at `t/2` and needs a "solid vs see-through band"
answer anyway (it is where a low wall's thickness and height meet).
- **Door geometry**: a thick door is a leaf in a deep opening; #46's locked/secret semantics and the existing push rule
(`DESIGN` §5.5) both assume a zero-width segment today.
- **One-way walls** (#47): Roll20's documented one-way use is elevation (balcony), so one-way and low walls may be the
same mechanism seen from different sides — worth deciding together.
- **Oracle and gate work**: the leak checker's zero-width `clearLine` and 64×3 sample grid, the tile-gate oracle, and the
bench baseline all need a decided model before they can be extended (no ticket on the map covers this yet).
+8
View File
@@ -0,0 +1,8 @@
version = "0.1.0"
author = "SirStone"
description = "FFF_vtt: server-authoritative vision VTT"
license = "MIT"
srcDir = "server"
requires "nim >= 2.0"
requires "mummy == 0.4.8", "db_connector == 0.1.0"
+2
View File
@@ -0,0 +1,2 @@
--path:"server"
--mm:orc
+9
View File
@@ -0,0 +1,9 @@
.devbox/
nimbledeps/
data/tiles/
nimble.paths
tests/t[a-z]*
!tests/*.nim
server
run/
results/*-15s*
+33
View File
@@ -0,0 +1,33 @@
# Handoff: server-authoritative vision prototype -> real VTT
Each item verified against code at the commit named in README. Pointers = where to look.
## Port as-is
- Vision/geometry: `src/geometry.nim` (visibilityPolygon, cellsTouched, inside, moveBlocked) + `tests/tgeometry.nim` (corner tests, run `nimble test`; mutation check `devbox run mutation`, `tools/mutation.sh`). Leak harness (`tools/leak.mjs`, `tools/leakcheck.nim`, `tools/faulttest.sh`) is the acceptance test for any port.
- Limits: token exactly on a wall cannot move off it (`moveBlocked`, inclusive `segsCross`, `geometry.nim:59-85`); vision is O(rays x walls) per token, bbox cull only (`geometry.nim` visibilityPolygon); cellsTouched ~12x the polygon cost (`results/bench.log`).
- Test gap: "shared endpoint: no leak at the vertex" (`tests/tgeometry.nim:29`) still passes with the horizontal arm removed (verified); shared-vertex coverage is only indirect via `hasVertex`. Port a test that fails if either arm is missing.
## Caveats
- All timings are single machine, loopback, power-save CPU; no real network, no client render. Not production numbers (`results/bench.log`, `results/concurrency-final*.log`).
- Boundary epsilon (`RayEps` 1e-4 rad, `geometry.nim:12`; inclusive tests): a token exactly on a vision boundary is ambiguous. Leak checker uses a 0.5 px neighbourhood (`tools/leakcheck.nim:17-20`).
## Leaks / security
- Tile leak: a revealed tile exposes all 256 px, not just explored cells; door changes never affect tiles (static art). `src/server.nim` tile handler, `data/tiles/`.
- Invite links = permanent bearer secrets, cookie `sid` IS the secret, no expiry/rotation (`server.nim` ~L270-290, L346). Needs expiry/rotation + HTTPS. `nginx/nginx.conf` `listen NGX_PORT` has no address => binds 0.0.0.0.
- Move collision checks only the centre path (a->b) and the destination circle (`moveBlocked`, `server.nim:194`), not the swept circle: corner clipping possible.
- Leak test explored/tile checks use the server's own `cellsTouched` (self-consistency, not an independent oracle); see README.
## Protocol / scale
- Full vision polygon (~3 KB) resent on every player move (`bytes/delivery`, `results/concurrency-final1-server.log`) -> send deltas or coarser polygons.
- Explored grid sent whole on connect, one SQLite row per cell (`server.nim` persistCells/loadState) -> bitmap/RLE + per-tile summaries.
## Ops / robustness
- No SIGTERM handler: only `setControlCHook` (SIGINT) prints stats (`server.nim:359`); shutdown = hard kill. Durability rests on WAL commit before ack (`results/final-restart.log`).
- `PRAGMA synchronous=NORMAL` (`server.nim:331`): process kill loses nothing, OS crash/power loss may drop last commits (never corrupts). Tail (~20 ms server worst) unchanged by it: `results/spike/investigation.md`. Real project must choose NORMAL vs FULL deliberately (NORMAL cut avg commit 0.60 -> 0.17 ms, bought no tail).
- Timing instrumentation in `server.nim` (`tm` samples L52, appended per mutation L178; `printStats` L69-80 copies+sorts all samples, called at L174 inside `finish` under the global `lk`) is prototype-only: DO NOT PORT. Real build needs bounded metrics (histogram/ring buffer) computed outside the lock.
- 583 ms intent->ack spike: not reproduced (base worst 73.1/21.8/18.1 ms, fixed 21.3/20.8/21.0), cause undetermined (host-wide stall or node harness pause; original run was ~3.5x slower on average). Server tail >50 ms = SQLite COMMIT stall + lock_wait queued behind it. `results/spike/investigation.md`.
- mummy: send queue is one unbounded server-wide deque, no backpressure for slow clients; `WebSocket` keyed in `conns` by its raw bytes (no hash/==) (`server.nim` Conn/conns, README "mummy suitability").
## Client
- Fog masks are Graphics that grow unbounded (`client/src/main.ts` ~L98, shortcut comment) -> bake to RenderTexture. One Pixi `Text` per token (`main.ts:55`) is heavy -> BitmapText.
- Browser rendering never verified (no browser in build env): only reducer (`client/src/state.test.ts`, `results/client-tests.log`) and HTTP/WS paths are tested.
+32
View File
@@ -0,0 +1,32 @@
# Notes (feeds README Findings)
## Geometry edge-case log
- BROKE: `cellsTouched` returned nothing for a polygon wholly inside one cell (no edge crosses the cell, no cell corner inside poly). FIX: also hit if a polygon vertex lies in the cell.
- Test bug (not code): "shared endpoint" case asserted a point hugging a wall the token stands on line with was hidden; it is legitimately visible. Removed. RESTORED with the correct expectation (token on the arm line: point 5 px below visible, 5 px above hidden); weak corner-case tests (box corner, collinear, T-junction, token at endpoint, free-standing wall, behind-viewer fan) got visible+hidden probes, no geometry bug found.
- Design choices that avoided bugs (all pass first run): rays to each endpoint at -eps/0/+eps (1e-4 rad); ray/segment u-range inclusive with 1e-9 tolerance so no cracks at shared vertices / T-junctions; parallel (collinear) rays skipped since neighbouring +-eps rays cover them; token on an endpoint: that endpoint skipped for ray generation and hits at t<=1e-9 ignored.
- Moves: inclusive intersection (touching = blocked) so no squeezing through shared vertices. Limit: token standing exactly on a wall can't move off it; server must keep tokens off walls.
- Vision circle = inscribed 64-gon (max error r*(1-cos(pi/64)) ~ 0.12% of r).
## Layout
- Hand-authored (no RNG): reproducible by construction. 6 rooms, 7 corridors, 1 pillar (R1), T-junction (partition at x=3000 in R3 ends mid south wall), collinear split (R3 north wall at x=3200), long thin corridor (R2-R5, 1024x64), doors: R2 west (closed), R5 north (open).
## Phase 2a (server)
- Port 8080 was taken on dev box (docker puma): `PORT=8088 devbox run server|nginx` (sed into run/nginx.conf; server prints invite origin from PORT). Default 8080.
- Verified: WS path tricks rejected (webby 400 on %2f/%00); `/_tiles/` 404 when hit directly.
- Non-owned move => `error` (not moveAck: server pos of an unseen token would leak).
- `by` = "gm"|"A"|"B" (conn role name).
- Smoke: `devbox run smoke` (isolated via tools/withserver.sh: server+nginx on 19000/18088, run/test/invites.txt written by server).
## Phase 3
- BUG (client): reconnect did not reset state (stale tokens/explored/sprites); server already resends hello+state on every connect. FIX: reducer resets on `hello`, main.ts clears sprites/masks/doors/pending (tiles kept). Reducer test added.
- BUG (client): door click `if (d)` would ignore door id 0. FIX: `!== null`.
- Leak scenario bugs were scenario bugs (diagonal steps through walls), not server bugs; server answered `ok:false` as designed.
- Leak checker B-string check initially flagged legit `remove{id:"B"}`; exempted token/remove.
- Perf finding: cellsTouched (~0.46 ms) is ~12x the visibility polygon (~0.04 ms) (results/bench.log); per-move vision_ms is dominated by explored-cell computation.
## Post-phase-3 manual-test bug
- BUG (server, geometry.nim): `visibilityPolygon` sorted circle-segment angles in [0,2pi) together with wall-endpoint atan2 angles in (-pi,pi] -> fan vertices out of angular order -> bow-tie polygon, even-odd `inside`/`cellsTouched` dropped regions (tokens in plain LOS not shown, explored/tiles missing). Position dependent. FIX: wrap circle angles with atan2(sin,cos).
- Why tests missed it: leakcheck recomputed its oracle with the same `visibilityPolygon` (only checked "nothing extra leaks", never "everything visible shows"), and only subject A was checked. Now: independent clear-LOS (segment test) oracle, `SUBJECT=A|B`, geometry regression test.
## Token radius bug
- BUG (server): move validation treated tokens as points; client drew radius 20, so tokens stopped half inside walls/pillar/doors. FIX: `moveBlocked(..., r)` also requires dest circle clear (point-segment dist >= r); `tokenRadius` in scene.json + `hello`. 64 px corridors/doorways leave 12 px slack each side of the centreline. Leak scenario steps adjusted to stop >= r from the closed door/wall.
+123
View File
@@ -0,0 +1,123 @@
# Server-authoritative vision prototype (throwaway)
Question: can the server alone decide what each player sees (tokens, fog, map tiles) so a modified client learns nothing hidden? Stack: Nim + mummy (WS/HTTP), SQLite, nginx (static + `X-Accel-Redirect` tiles), Vite + TS + Pixi v8 client.
## Run (everything through devbox)
```
devbox run gen # data/scene.json + data/tiles/*.png (deterministic, hand-authored layout)
devbox run client # npm install, reducer test, tsc + vite build -> client/dist
PORT=8088 devbox run server # :9000 backend, prints invite links, writes run/invites.txt
PORT=8088 devbox run nginx # public port; separate terminal
```
`PORT` (default 8080) is only the public nginx port and the origin printed in invite links. On the dev box 8080 is taken by unrelated docker, hence 8088 in all examples.
Open the 3 invite links (gm, A, B) each in a **separate browser or profile**. The link sets cookie `sid=<secret>` (HttpOnly, SameSite=Strict) and redirects to `/`; the WS and tile requests authenticate by that cookie. One cookie jar = one identity, so two links in the same profile overwrite each other. Same cookie in two tabs = same player (shared vision, both connections synced).
Browser rendering was NOT verified (no browser in the build environment): only HTTP/WS behaviour is scripted-tested (served `/`, JS bundle 200, join -> cookie, WS through nginx, tiles).
## Tests
| cmd | what |
|---|---|
| `devbox run test` | regen map + `nimble test` (geometry), smoke, leaktest, faulttest, restart, concurrency (DUR=15; its log `results/concurrency-15s*` is gitignored) |
| `devbox run clienttest` | client reducer tests (`client/src/state.test.ts` via `npm run check`, incl. reconnect reset) -> `results/client-tests.log`; `devbox run client` also runs them |
| `devbox run smoke` | fresh DB, server+nginx, auth/cookie/tile/steal/garbage checks |
| `devbox run leaktest` | runs twice (SUBJECT=A, SUBJECT=B), fresh DB each; subject walks ~240 steps through rooms, corridor, open/closed doors while GM + B act; Nim checker (`tools/leakcheck.nim`) replays the transcript. Output per subject: `results/leak-A.log`, `results/leak-B.log` (committed), transcripts `results/leak-{A,B}.jsonl` (1.1-1.3 MB each, 2.4 MB total, committed) |
| `devbox run faulttest` | deliberate leaks: builds the server with `-d:leakfault` (hook absent from the normal build, asserted by grepping the clean binary for `LEAK_FAULT`), injects 8 faults one at a time (`LEAK_FAULT=`): hidden token sent (`hidden`), wall data to player (`walls`), unexplored tile 200 (`tile`), visible token withheld (`withhold`), B's vision / explored / ownership sent to A (`other-vision`, `other-explored`, `other-owner`), missing `remove` (`noremove`). Passes only if the checker fails each with exactly the expected failure-class set (classes: HIDDEN_TOKEN WALLDATA TILE WITHHELD OTHER_PLAYER NO_REMOVE, plus collateral OWN_VIEW / EXPLORED) and the clean build still passes. Details in `results/faults.log` (committed), summary `results/final-faulttest.log` |
| `devbox run restart` | isolated server, moves A/B/monsters, toggles doors, A explores a new area; stops with SIGTERM then (second round of changes) SIGKILL, restarts on the same DB; asserts invite secrets, token positions, doors, vision, explored grids per role and the full hello+state a reconnecting client receives are identical (gseq excluded: in-memory). Note: the server has no SIGTERM handler, so SIGTERM is as abrupt as SIGKILL; durability rests on the SQLite WAL commit before ack (`synchronous=NORMAL`: survives process kill, may lose the last commits on OS crash/power loss; see `results/spike/investigation.md`) |
| `devbox run concurrency` | 60 s (`DUR=` secs) A, B, GM(6 monsters + doors) at 20-50 ms per token; logs `results/concurrency-<TAG>.log` + `...-server.log` (server STATS; TAG defaults to `<DUR>s`; final runs use `TAG=final1..3`) |
| `devbox run mutation` | geometry mutation check on a temp copy (`tools/mutation.sh`): (a) no ±RayEps rays, (b) upper segment end exclusive, (c) lower end exclusive; control must pass, each mutation must fail a corner test. Logs `results/mutation-{a,b,c}.log` |
| `devbox run bench` | vision microbench, log `results/bench.log` |
Other saved outputs: `results/nimble-test.log` (`nimble test`), `results/mutation-summary.log`, `results/final-{leaktest,faulttest,restart}.log`, `results/smoke.log`, `results/final-rc.txt` (exit code of every final-run step), `results/spike/` (historical 583 ms investigation, earlier commits, see its `investigation.md`).
Tests are isolated: `tools/withserver.sh` uses `run/test/` (own DB, invites, nginx conf/logs) and ports 18088 (nginx) / 19000 (server), overridable via `TEST_PORT`/`TEST_BACKEND_PORT`; the live session on 8088/9000 and `run/` are never touched. Server stats print on stop into `run/test/server.log`.
### Leak test asserts
Ground truth = GM socket (tokens + doors per gseq). A's expected vision/explored is recomputed with `geometry.nim`, never from A's own messages. Per gseq:
- (a) A receives only hello/vision/explored/token/remove/moveAck; no wall-like keys (walls, door, open, a, b, segments...) anywhere.
- (b) every token A is sent is inside the independently computed polygon (0.5 px boundary tolerance); every token inside it IS in A's view (completeness); view positions == truth; A's `vision` polygon equals the recomputed one (1e-6); A's explored set == recomputed set.
- (c) `remove` arrives when a token leaves; scenario must show M1, M2, M5, B and >= 3 removes.
- (d) 256 tiles requested per sweep (A: 39 sweeps = 9984 requests, B: 29 = 7424; incl. unexplored): 200 iff an explored cell touches the tile at that gseq, else 403.
- (e) A never gets B-bound info: no B string outside token/remove, no `by:B` on others' tokens, hello tokens == ["A"], no error msgs.
**Caveat (self-consistency, not an independent oracle):** the explored-set check in (b) and the tile 200/403 check in (d) recompute the expected values with the server's own `geometry.nim` (`visibilityPolygon` + `cellsTouched`). They prove the server sends/gates exactly what its own geometry says and that nothing else leaks, not that `cellsTouched` is geometrically right. Only the token-visibility checks (clear-LOS segment oracle + polygon containment) are independent of the explored-cell computation.
Negative control: automated, `devbox run faulttest` (above).
Run 2026-11-07, AMD Ryzen 7 7840U (16 threads), 60.6 GiB RAM, NixOS 26.05 (kernel 6.18.55), CPU power mode: power-save, capped (governor `powersave`, deliberately not changed). Code commit tested: `18c9884`.
Result (`results/leak-A.log`): PASS (218 gseq groups, 467 A msgs, 4 other tokens seen, 4 removes, tiles 1709 x 200 / 8275 x 403, 2142 explored cells, 0 failures). Fault test: 8/8 faults caught with the exact class set + clean build passes (`results/final-faulttest.log`).
Result (`results/leak-B.log`): PASS (218 gseq groups, 217 B msgs, 3 other tokens seen, 3 removes, tiles 686 x 200 / 6738 x 403, 1114 explored cells, 0 failures).
### Concurrency result (60 s x3, all PASS; `results/concurrency-final{1,2,3}.log`, server side `...-server.log`)
Run 2026-11-07, AMD Ryzen 7 7840U (16 threads), 60.6 GiB RAM, NixOS 26.05 (kernel 6.18.55), CPU power mode: power-save, capped (governor `powersave`, deliberately not changed). Code commit tested: `18c9884`.
Load ~223 intents/s (final1: A 28, B 28, 6 monsters 167/s) + door toggles every 1-3 s. final1: 13748 mutations (10286 monster + 3400 player moves + 62 doors, `results/concurrency-final1-server.log`, = final gseq), no crash, 0 errors, gseq never went backwards at any client, every intent acked (sent == acks for all 3 clients; nacks = blocked random-walk moves, final1: GM 13, A 26, B 0), and after quiesce each client's tokens/doors/vision/explored == a fresh connection's snapshot (the script asserts this; PASS line).
| run | intent->ack avg | p99 | worst | source |
|---|---|---|---|---|
| final1 | 1.40 ms | 4.58 ms | 20.31 ms | `concurrency-final1.log` |
| final2 | 1.50 ms | 4.98 ms | 21.73 ms | `concurrency-final2.log` |
| final3 | 1.43 ms | 4.75 ms | 24.72 ms | `concurrency-final3.log` |
No `SLOW` (>50 ms) line in any final run. The 583 ms outlier seen once in an earlier, differently-built run did not reproduce and has no known cause (`results/spike/investigation.md`).
### Other final-run results (all PASS; exit codes in `results/final-rc.txt`)
Run 2026-11-07, AMD Ryzen 7 7840U (16 threads), 60.6 GiB RAM, NixOS 26.05 (kernel 6.18.55), CPU power mode: power-save, capped (governor `powersave`, deliberately not changed). Code commit tested: `18c9884`.
All results in `results/` were produced at code commit `18c9884` (last code/test-script commit; later commits are docs/results only).
| step | result | file |
|---|---|---|
| `nimble test` | 33 checks OK | `results/nimble-test.log` |
| `devbox run mutation` | control passes; a, b, c each fail >= 1 corner test (1, 2, 2) | `results/mutation-summary.log`, `results/mutation-{a,b,c}.log` |
| faulttest | 8/8 faults caught, clean build passes | `results/final-faulttest.log`, `results/faults.log` |
| restart | PASS | `results/final-restart.log` |
| smoke | PASS | `results/smoke.log` |
| client tests | 4/4 pass | `results/client-tests.log` |
## Measurements (laptop, release build, localhost)
Run 2026-11-07, AMD Ryzen 7 7840U (16 threads), 60.6 GiB RAM, NixOS 26.05 (kernel 6.18.55), CPU power mode: power-save, capped (governor `powersave`, deliberately not changed). Code commit tested: `18c9884`.
Sources: C = `results/concurrency-final1.log`, S = `results/concurrency-final1-server.log` (server STATS), B = `results/bench.log`.
| metric | avg | p95 | worst | source |
|---|---|---|---|---|
| vision recompute per player move (server, incl. cellsTouched + diff) | 1.18 ms | - | 4.55 ms | S `vision_ms move-player` |
| vision recompute per monster move | 0.000 ms (no vision) | - | 0.024 ms | S `vision_ms move-monster` |
| door toggle (2 roles) | 0.20 ms | - | 0.30 ms | S `vision_ms door` |
| server total per mutation (lock wait + vision + sqlite + send) | 0.70 ms | - (p99 3.71) | 19.63 ms | S `timing_ms total` |
| bench: 1 visibility polygon | 0.038 ms | - | 0.18 ms | B |
| bench: 6 polygons | 0.205 ms | - | 0.29 ms | B |
| bench: 1 poly + cellsTouched | 0.451 ms | - | 0.98 ms | B |
| bench: 6 polys + cellsTouched | 2.95 ms | - | 3.73 ms | B |
| latency intent -> ack (sender, via nginx) | 1.40 ms | 2.99 ms | 20.31 ms | C |
| latency intent -> arrival at other clients | 2.04 ms | 3.66 ms | 18.94 ms | C |
Bytes per delivery (only recipients that got something; S `bytes/delivery`):
| mutation | recipient | avg B |
|---|---|---|
| monster move | GM | 243.5 |
| monster move | player who sees it | 145.5 (B) - 146.0 (A) |
| player move | the mover (ack + token + new `vision` + `explored` diff) | 3359 (B) - 3653 (A) (worst 4.9 KB) |
| player move | GM | 144.6 |
| door toggle | GM | 44.8 |
"6 moving tokens" with vision: monsters have none in this design, so the 6-token case is the bench (a 6-token party in one role = 6 polys per recompute: 0.205 ms polys, 2.95 ms with cell marking; B). Concurrency exercised 6 simultaneously moving monsters (no vision cost) + 2 players.
## Findings
**Worked**
- Server-only filtering is simple under one global lock: validate -> mutate -> recompute -> persist -> per-connection diff -> send. Players never receive walls/doors/other tokens; leak test finds nothing.
- Per-connection `known` map gives correct enter/leave (`token`/`remove`) and a fresh connection gets full state; clients reset on `hello`.
- Token radius `tokenRadius` (20 px, data/scene.json via tools/genmap.mjs) is server-authoritative and sent in `hello` (client falls back to 20 if absent). A move is accepted only if the centre path crosses no blocking wall AND the destination circle is >= r from every blocking wall (open doors ignored). Only the destination is checked, so a token already overlapping a wall (closed door, legacy DB) can leave. Vision origin stays the token centre.
- Tile gating via nginx `internal` + `X-Accel-Redirect` after Nim checks explored cells; `/_tiles/` unreachable directly.
- Moves: inclusive segment test blocks squeezing through shared vertices; non-owned/malformed moves get `error` (not an ack, an ack would echo the position of an unseen token).
**Edge cases that broke (see NOTES.md)**: `cellsTouched` missed polygons wholly inside one cell (fix: vertex-in-cell test); client did not reset on reconnect (fix: reset on `hello`); door id 0 falsy check; leak scenario steps crossing walls diagonally (scenario bug, server correctly refused).
**mummy suitability**
- Send is thread-safe by construction: `WebSocket.send` appends the encoded frame to one server-wide deque under `sendQueueLock` and triggers the IO thread (mummy.nim ~L262-311); the IO thread drains it. Per-socket events are serialized by mummy. Because we also send while holding our own lock, per-socket order == gseq order, so no separate broadcaster was needed. 60 s of mixed 3-client load, 13748 mutations, ~36k messages (C: 24054 + 6093 + 6035 recv, final1): no crash, no reorder, no loss, consistent final views.
- Caveats: `WebSocket` has no `==`/hash, we key a table by its raw bytes (shortcut, works while it is one pointer-sized ref). Everything is serialized by one lock, so throughput is single-core bound (fine here: ~1.18 ms/player move, S). Sending under the lock is cheap (queue push) but a slow client cannot block it; there is no backpressure/limit on a slow client's queue (memory grows).
- Pinned to an exact commit (no tags upstream).
**Worries for a real VTT**
- Vision is O(rays x walls) per token (culled only by bbox); needs a spatial grid for big maps. cellsTouched (O(bbox cells x poly edges)) is ~12x costlier than the polygon itself (0.451 vs 0.038 ms, B) and dominates.
- Explored grid: 128x128 cells here; explored set sent whole on connect, kept in memory + one SQLite row per cell. Larger maps need run-length/bitmap + per-tile summaries.
- Full `vision` polygon resent on each player move (most of the ~3.4-3.7 KB per mover delivery); needs deltas or lower-res polygons.
- Cookie = the secret (bearer, no rotation/expiry); invite links in logs/URLs are credentials. HTTPS needed beyond localhost.
- Tiles do not update when a door changes (static art; only fog changes); a revealed tile stays visible forever and leaks the whole tile (256 px), not just the explored cells; tile granularity vs exploredCell is a leak/size tradeoff.
- Polygon boundary epsilon: ray nudges (1e-4 rad) and inclusive tolerances; tokens right on the boundary are ambiguous (tests use a 0.5 px tolerance). A token standing exactly on a wall cannot move off it; server must keep tokens off walls.
- Fog masks are Graphics that grow unbounded (explored rects re-tessellated); needs baking to a RenderTexture. Pixi `Text` per token is heavy vs `BitmapText` at scale.
- Browser rendering (fog masks, drag, reconnect visuals) is unverified: only the reducer and HTTP/WS paths were tested.
- Timing trusts a single machine/loopback; latencies exclude real network and client render.
@@ -0,0 +1,2 @@
node_modules/
dist/
@@ -0,0 +1,6 @@
<!doctype html>
<meta charset="utf-8"><title>servervision</title>
<style>html,body{margin:0;height:100%;overflow:hidden;background:#000}
#bar{position:fixed;top:0;left:0;right:0;padding:2px 8px;font:12px monospace;color:#0f0;background:#000a;z-index:1;pointer-events:none}</style>
<div id="bar"></div>
<script type="module" src="/src/main.ts"></script>
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,12 @@
{
"name": "servervision-client",
"private": true,
"type": "module",
"scripts": {
"dev": "vite",
"build": "tsc && vite build",
"check": "node --test src/state.test.ts"
},
"dependencies": { "pixi.js": "^8.0.0" },
"devDependencies": { "typescript": "^5.6.0", "vite": "^6.0.0", "@types/node": "^22.0.0" }
}
+174
View File
@@ -0,0 +1,174 @@
import { Application, Container, Graphics, Sprite, Text, Texture } from 'pixi.js';
import { apply, newState, tilesOfCells, type Tok, type V2 } from './state.ts';
const s = newState();
const bar = document.getElementById('bar')!;
let conn = 'connecting';
// identity from hello.tokens: a player owns only the token whose id is their slot ("A"/"B")
const who = () => (s.role === 'player' ? `player ${s.owned[0] ?? '?'}` : s.role ?? '?');
const status = () => (bar.textContent = `${who()} conn=${conn} gseq=${s.gseq}${s.lastError ? ' err=' + s.lastError : ''}`);
const app = new Application();
await app.init({ resizeTo: window, background: 0x000000, antialias: true });
document.body.appendChild(app.canvas);
const world = new Container();
const tilesL = new Container();
const doorsG = new Graphics();
const tokensL = new Container();
// Fog: dim = everywhere except current vision; black = everywhere except explored. Inverse stencil masks.
const dim = new Graphics();
const black = new Graphics();
const visionM = new Graphics();
const exploredM = new Graphics();
dim.addChild(visionM); dim.setMask({ mask: visionM, inverse: true });
black.addChild(exploredM); black.setMask({ mask: exploredM, inverse: true });
world.addChild(tilesL, dim, black, doorsG, tokensL);
app.stage.addChild(world);
// ---- tiles ----
const tileState = new Map<string, 'loading' | 'ok' | 'fail'>();
function loadTile(key: string) {
if (tileState.has(key) && tileState.get(key) !== 'fail') return;
tileState.set(key, 'loading');
fetch(`/tiles/${key}.png`)
.then((r) => (r.ok ? r.blob() : Promise.reject(r.status))) // 403 = not available (yet)
.then((b) => createImageBitmap(b))
.then((bmp) => {
const [x, y] = key.split('_').map(Number);
const sp = new Sprite(Texture.from(bmp));
sp.position.set(x * s.tileSize, y * s.tileSize);
tilesL.addChild(sp);
tileState.set(key, 'ok');
})
.catch(() => tileState.set(key, 'fail'));
}
// ---- tokens ----
const sprites = new Map<string, Container>();
const dragging = new Map<string, true>();
function drawToken(t: Tok) {
let c = sprites.get(t.id);
if (!c) {
c = new Container();
const g = new Graphics().circle(0, 0, s.tokenR).fill(t.mine ? 0x3a9d3a : 0xb03030).stroke({ width: 3, color: 0xffffff });
const l = new Text({ text: t.name, style: { fontSize: 14, fill: 0xffffff, stroke: { color: 0, width: 3 } } });
l.anchor.set(0.5, 0); l.y = s.tokenR + 2;
c.addChild(g, l);
tokensL.addChild(c); sprites.set(t.id, c);
}
if (!dragging.has(t.id)) c.position.set(t.pos[0], t.pos[1]); // incoming pos ignored while locally dragging
}
const canDrag = (t: Tok) => s.role === 'gm' || t.mine;
// ---- ws ----
let ws: WebSocket;
const send = (o: object) => ws.readyState === 1 && ws.send(JSON.stringify(o));
let reqId = 0;
const pending = new Map<number, string>();
function onMsg(m: any) {
if (m.t === 'moveAck') {
const id = pending.get(m.reqId); pending.delete(m.reqId);
if (!m.ok && id && !dragging.has(id)) { // snap to server pos
const t = s.tokens.get(id), c = sprites.get(id);
if (t) t.pos = m.pos;
c?.position.set(m.pos[0], m.pos[1]);
}
s.gseq = m.gseq;
return;
}
const fresh = apply(s, m);
switch (m.t) {
case 'hello':
for (const c of sprites.values()) c.destroy({ children: true });
sprites.clear(); pending.clear(); visionM.clear(); exploredM.clear(); doorsG.clear(); // tiles kept: explored only grows
fit();
if (s.role === 'gm') { dim.visible = black.visible = false; const n = Math.ceil(s.w / s.tileSize), k = Math.ceil(s.h / s.tileSize); for (let y = 0; y < k; y++) for (let x = 0; x < n; x++) loadTile(x + '_' + y); }
else { for (const g of [dim, black]) g.clear().rect(0, 0, s.w, s.h).fill(0x000000); dim.alpha = 0.6; }
break;
case 'walls': case 'door': drawDoors(); break;
case 'vision':
visionM.clear();
for (const p of s.polys) visionM.poly(p.flat()).fill(0xffffff);
break;
case 'explored':
if (fresh!.length) {
for (const [cx, cy] of fresh!) exploredM.rect(cx * s.cell, cy * s.cell, s.cell, s.cell);
exploredM.fill(0xffffff); // shortcut: Graphics grows unbounded, re-tessellates; bake to RenderTexture when cells >~50k
// retry failed/unrequested tiles under newly explored cells
for (const k of tilesOfCells(fresh!, s)) loadTile(k);
}
break;
case 'token': drawToken(s.tokens.get(m.id)!); break;
case 'remove': sprites.get(m.id)?.destroy({ children: true }); sprites.delete(m.id); break;
}
}
function connect() {
ws = new WebSocket(`${location.protocol === 'https:' ? 'wss' : 'ws'}://${location.host}/ws`);
ws.onopen = () => { conn = 'open'; status(); };
ws.onclose = () => { conn = 'closed (retry 2s)'; status(); setTimeout(connect, 2000); }; // state reset on hello; server resends everything
ws.onmessage = (e) => { onMsg(JSON.parse(e.data)); status(); };
}
// ---- walls (GM only) ----
function drawDoors() {
doorsG.clear();
for (const w of s.walls.values()) {
doorsG.moveTo(...w.a).lineTo(...w.b).stroke({ width: w.door ? 6 : 3, color: w.door ? (w.open ? 0x40ff40 : 0xff4040) : 0xffff00 });
}
}
function pickDoor(p: V2): string | null {
const tol = 10 / world.scale.x;
for (const w of s.walls.values()) {
if (!w.door) continue;
const [ax, ay] = w.a, [bx, by] = w.b, dx = bx - ax, dy = by - ay;
const u = Math.max(0, Math.min(1, ((p[0] - ax) * dx + (p[1] - ay) * dy) / (dx * dx + dy * dy || 1)));
if (Math.hypot(p[0] - (ax + u * dx), p[1] - (ay + u * dy)) < tol) return w.id;
}
return null;
}
// ---- camera + input ----
function fit() { const k = Math.min(innerWidth / s.w, innerHeight / s.h); world.scale.set(k); world.position.set(0, 0); }
const toWorld = (e: PointerEvent | WheelEvent): V2 => [(e.clientX - world.x) / world.scale.x, (e.clientY - world.y) / world.scale.x];
let pan: { x: number; y: number } | null = null;
let drag: { id: string; dx: number; dy: number; last: number } | null = null;
const moveTok = (id: string, pos: V2) => { const r = ++reqId; pending.set(r, id); send({ t: 'move', reqId: r, id, pos }); };
const cv = app.canvas;
cv.addEventListener('pointerdown', (e) => {
cv.setPointerCapture(e.pointerId);
const p = toWorld(e);
for (const [id, c] of [...sprites].reverse()) { // O(N) hit test on press
const t = s.tokens.get(id)!;
if (canDrag(t) && Math.hypot(p[0] - c.x, p[1] - c.y) <= s.tokenR) { drag = { id, dx: c.x - p[0], dy: c.y - p[1], last: 0 }; dragging.set(id, true); return; }
}
if (s.role === 'gm') { const d = pickDoor(p); if (d !== null) { send({ t: 'door', id: d, open: !s.walls.get(d)!.open }); return; } }
pan = { x: e.clientX - world.x, y: e.clientY - world.y };
});
cv.addEventListener('pointermove', (e) => {
if (drag) {
const p = toWorld(e), pos: V2 = [p[0] + drag.dx, p[1] + drag.dy];
sprites.get(drag.id)!.position.set(pos[0], pos[1]); // optimistic
const now = performance.now();
if (now - drag.last >= 50) { drag.last = now; moveTok(drag.id, pos); }
} else if (pan) world.position.set(e.clientX - pan.x, e.clientY - pan.y);
});
const up = () => {
if (drag) {
const c = sprites.get(drag.id)!, pos: V2 = [c.x, c.y];
moveTok(drag.id, pos); // final
const t = s.tokens.get(drag.id); if (t) t.pos = pos;
dragging.delete(drag.id); drag = null;
}
pan = null;
};
cv.addEventListener('pointerup', up); cv.addEventListener('pointercancel', up);
cv.addEventListener('wheel', (e) => {
e.preventDefault();
const p = toWorld(e), k = Math.max(0.05, Math.min(8, world.scale.x * Math.exp(-e.deltaY * 0.001)));
world.scale.set(k); world.position.set(e.clientX - p[0] * k, e.clientY - p[1] * k);
}, { passive: false });
status();
connect();
@@ -0,0 +1,47 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import { apply, newState, tilesOfCells } from './state.ts';
test('protocol reducer: fake server script', () => {
const s = newState();
apply(s, { t: 'hello', gseq: 1, role: 'player', tokens: ['a'], world: { w: 4096, h: 4096 }, tileSize: 512, exploredCell: 64 });
assert.equal(s.role, 'player');
assert.equal(s.walls.size, 0); // players never get walls
assert.deepEqual(apply(s, { t: 'explored', gseq: 2, cells: [[0, 0], [1, 0]] }), [[0, 0], [1, 0]]);
assert.deepEqual(apply(s, { t: 'explored', gseq: 3, cells: [[1, 0], [2, 0]] }), [[2, 0]]); // diff accumulates
assert.equal(s.explored.size, 3);
apply(s, { t: 'vision', gseq: 4, polys: [[[0, 0], [1, 0], [1, 1]]] });
apply(s, { t: 'vision', gseq: 5, polys: [] });
assert.equal(s.polys.length, 0); // full replacement
apply(s, { t: 'token', gseq: 6, id: 'a', name: 'A', kind: 'pc', pos: [5, 6], mine: true });
apply(s, { t: 'token', gseq: 7, id: 'a', name: 'A', kind: 'pc', pos: [7, 8], mine: true });
assert.deepEqual(s.tokens.get('a')!.pos, [7, 8]);
apply(s, { t: 'remove', gseq: 8, id: 'a' });
assert.equal(s.tokens.size, 0);
assert.equal(s.gseq, 8);
});
test('gm walls + door', () => {
const s = newState();
apply(s, { t: 'walls', gseq: 1, walls: [{ id: 'd1', a: [0, 0], b: [10, 0], door: true, open: false }] });
apply(s, { t: 'door', gseq: 2, id: 'd1', open: true });
assert.equal(s.walls.get('d1')!.open, true);
});
test('tilesOfCells', () => {
const g = { w: 4096, h: 4096, tileSize: 512, cell: 64 };
assert.deepEqual([...tilesOfCells([[0, 0], [7, 7]], g)], ['0_0']);
assert.deepEqual([...tilesOfCells([[8, 0]], g)], ['1_0']);
assert.deepEqual([...tilesOfCells([[0, 0]], { ...g, cell: 1024 })].length, 4); // cell spans 2x2 tiles
});
test('hello resets state (reconnect)', () => {
const s = newState();
apply(s, { t: 'hello', gseq: 1, role: 'player', tokens: ['a'], world: { w: 4096, h: 4096 }, tileSize: 512, exploredCell: 64 });
apply(s, { t: 'token', gseq: 2, id: 'a', name: 'A', kind: 'pc', pos: [5, 6], mine: true });
apply(s, { t: 'explored', gseq: 3, cells: [[0, 0]] });
apply(s, { t: 'hello', gseq: 9, role: 'player', tokens: ['a'], world: { w: 4096, h: 4096 }, tileSize: 512, exploredCell: 64 });
assert.equal(s.tokens.size, 0);
assert.equal(s.explored.size, 0);
assert.equal(s.gseq, 9);
});
@@ -0,0 +1,71 @@
// Pure protocol state + reducer (no Pixi) so it can be checked without a server.
export type V2 = [number, number];
export type Tok = { id: string; name: string; kind: string; pos: V2; mine: boolean };
export type Wall = { id: string; a: V2; b: V2; door: boolean; open: boolean };
export type Msg = { t: string; gseq: number; [k: string]: any };
export type State = {
role: 'gm' | 'player' | null;
owned: string[];
w: number; h: number; tileSize: number; cell: number; tokenR: number;
walls: Map<string, Wall>;
polys: V2[][];
explored: Set<string>;
tokens: Map<string, Tok>;
gseq: number;
lastError: string;
};
export const newState = (): State => ({
role: null, owned: [], w: 0, h: 0, tileSize: 512, cell: 32, tokenR: 20,
walls: new Map(), polys: [], explored: new Set(), tokens: new Map(), gseq: 0, lastError: '',
});
// Returns newly-added explored cells (only for t=explored), else undefined.
export function apply(s: State, m: Msg): V2[] | undefined {
s.gseq = m.gseq;
switch (m.t) {
case 'hello': // server resends full state after hello: start clean (reconnect)
Object.assign(s, newState(), { gseq: m.gseq });
s.role = m.role; s.owned = m.tokens; s.w = m.world.w; s.h = m.world.h;
s.tileSize = m.tileSize; s.cell = m.exploredCell; s.tokenR = m.tokenRadius ?? s.tokenR; // ?? : older server omits it
break;
case 'walls':
s.walls = new Map((m.walls as Wall[]).map((w) => [w.id, w]));
break;
case 'door': {
const w = s.walls.get(m.id);
if (w) w.open = m.open;
break;
}
case 'vision': s.polys = m.polys; break;
case 'explored': {
const fresh: V2[] = [];
for (const c of m.cells as V2[]) {
const k = c[0] + ',' + c[1];
if (!s.explored.has(k)) { s.explored.add(k); fresh.push(c); }
}
return fresh;
}
case 'token':
s.tokens.set(m.id, { id: m.id, name: m.name, kind: m.kind, pos: m.pos, mine: !!m.mine });
break;
case 'remove': s.tokens.delete(m.id); break;
case 'error': s.lastError = m.msg; break;
// moveAck handled by the view (needs pending/drag state)
}
return undefined;
}
// Tile keys "x_y" overlapped by the given explored cells.
export function tilesOfCells(cells: V2[], s: Pick<State, 'w' | 'h' | 'tileSize' | 'cell'>): Set<string> {
const out = new Set<string>();
const maxX = Math.ceil(s.w / s.tileSize) - 1, maxY = Math.ceil(s.h / s.tileSize) - 1;
for (const [cx, cy] of cells) {
const x0 = Math.floor((cx * s.cell) / s.tileSize), x1 = Math.floor(((cx + 1) * s.cell - 1) / s.tileSize);
const y0 = Math.floor((cy * s.cell) / s.tileSize), y1 = Math.floor(((cy + 1) * s.cell - 1) / s.tileSize);
for (let y = Math.max(0, y0); y <= Math.min(maxY, y1); y++)
for (let x = Math.max(0, x0); x <= Math.min(maxX, x1); x++) out.add(x + '_' + y);
}
return out;
}
@@ -0,0 +1,8 @@
{
"compilerOptions": {
"target": "ES2022", "module": "ESNext", "moduleResolution": "bundler",
"lib": ["ES2022", "DOM"], "strict": true, "noEmit": true, "skipLibCheck": true,
"allowImportingTsExtensions": true, "erasableSyntaxOnly": true, "types": ["node"]
},
"include": ["src"]
}
@@ -0,0 +1 @@
export default { base: './', build: { target: 'es2022' } };
+954
View File
@@ -0,0 +1,954 @@
{
"world": {
"w": 4096,
"h": 4096
},
"tileSize": 256,
"visionRadius": 400,
"tokenRadius": 20,
"exploredCell": 32,
"walls": [
{
"id": 0,
"a": [
256,
256
],
"b": [
1024,
256
],
"door": false,
"open": false
},
{
"id": 1,
"a": [
256,
1024
],
"b": [
608,
1024
],
"door": false,
"open": false
},
{
"id": 2,
"a": [
672,
1024
],
"b": [
1024,
1024
],
"door": false,
"open": false
},
{
"id": 3,
"a": [
256,
256
],
"b": [
256,
1024
],
"door": false,
"open": false
},
{
"id": 4,
"a": [
1024,
256
],
"b": [
1024,
608
],
"door": false,
"open": false
},
{
"id": 5,
"a": [
1024,
672
],
"b": [
1024,
1024
],
"door": false,
"open": false
},
{
"id": 6,
"a": [
1536,
256
],
"b": [
2304,
256
],
"door": false,
"open": false
},
{
"id": 7,
"a": [
1536,
1024
],
"b": [
1888,
1024
],
"door": false,
"open": false
},
{
"id": 8,
"a": [
1952,
1024
],
"b": [
2304,
1024
],
"door": false,
"open": false
},
{
"id": 9,
"a": [
1536,
256
],
"b": [
1536,
608
],
"door": false,
"open": false
},
{
"id": 10,
"a": [
1536,
608
],
"b": [
1536,
672
],
"door": true,
"open": false
},
{
"id": 11,
"a": [
1536,
672
],
"b": [
1536,
1024
],
"door": false,
"open": false
},
{
"id": 12,
"a": [
2304,
256
],
"b": [
2304,
608
],
"door": false,
"open": false
},
{
"id": 13,
"a": [
2304,
672
],
"b": [
2304,
1024
],
"door": false,
"open": false
},
{
"id": 14,
"a": [
2816,
256
],
"b": [
3200,
256
],
"door": false,
"open": false
},
{
"id": 15,
"a": [
2816,
1024
],
"b": [
3168,
1024
],
"door": false,
"open": false
},
{
"id": 16,
"a": [
3232,
1024
],
"b": [
3584,
1024
],
"door": false,
"open": false
},
{
"id": 17,
"a": [
2816,
256
],
"b": [
2816,
608
],
"door": false,
"open": false
},
{
"id": 18,
"a": [
2816,
672
],
"b": [
2816,
1024
],
"door": false,
"open": false
},
{
"id": 19,
"a": [
3584,
256
],
"b": [
3584,
1024
],
"door": false,
"open": false
},
{
"id": 20,
"a": [
256,
2048
],
"b": [
608,
2048
],
"door": false,
"open": false
},
{
"id": 21,
"a": [
672,
2048
],
"b": [
1024,
2048
],
"door": false,
"open": false
},
{
"id": 22,
"a": [
256,
2816
],
"b": [
1024,
2816
],
"door": false,
"open": false
},
{
"id": 23,
"a": [
256,
2048
],
"b": [
256,
2816
],
"door": false,
"open": false
},
{
"id": 24,
"a": [
1024,
2048
],
"b": [
1024,
2400
],
"door": false,
"open": false
},
{
"id": 25,
"a": [
1024,
2464
],
"b": [
1024,
2816
],
"door": false,
"open": false
},
{
"id": 26,
"a": [
1536,
2048
],
"b": [
1888,
2048
],
"door": false,
"open": false
},
{
"id": 27,
"a": [
1888,
2048
],
"b": [
1952,
2048
],
"door": true,
"open": true
},
{
"id": 28,
"a": [
1952,
2048
],
"b": [
2304,
2048
],
"door": false,
"open": false
},
{
"id": 29,
"a": [
1536,
2816
],
"b": [
2304,
2816
],
"door": false,
"open": false
},
{
"id": 30,
"a": [
1536,
2048
],
"b": [
1536,
2400
],
"door": false,
"open": false
},
{
"id": 31,
"a": [
1536,
2464
],
"b": [
1536,
2816
],
"door": false,
"open": false
},
{
"id": 32,
"a": [
2304,
2048
],
"b": [
2304,
2400
],
"door": false,
"open": false
},
{
"id": 33,
"a": [
2304,
2464
],
"b": [
2304,
2816
],
"door": false,
"open": false
},
{
"id": 34,
"a": [
2816,
2048
],
"b": [
3168,
2048
],
"door": false,
"open": false
},
{
"id": 35,
"a": [
3232,
2048
],
"b": [
3584,
2048
],
"door": false,
"open": false
},
{
"id": 36,
"a": [
2816,
2816
],
"b": [
3584,
2816
],
"door": false,
"open": false
},
{
"id": 37,
"a": [
2816,
2048
],
"b": [
2816,
2400
],
"door": false,
"open": false
},
{
"id": 38,
"a": [
2816,
2464
],
"b": [
2816,
2816
],
"door": false,
"open": false
},
{
"id": 39,
"a": [
3584,
2048
],
"b": [
3584,
2816
],
"door": false,
"open": false
},
{
"id": 40,
"a": [
3200,
256
],
"b": [
3584,
256
],
"door": false,
"open": false
},
{
"id": 41,
"a": [
1024,
608
],
"b": [
1536,
608
],
"door": false,
"open": false
},
{
"id": 42,
"a": [
1024,
672
],
"b": [
1536,
672
],
"door": false,
"open": false
},
{
"id": 43,
"a": [
2304,
608
],
"b": [
2816,
608
],
"door": false,
"open": false
},
{
"id": 44,
"a": [
2304,
672
],
"b": [
2816,
672
],
"door": false,
"open": false
},
{
"id": 45,
"a": [
1024,
2400
],
"b": [
1536,
2400
],
"door": false,
"open": false
},
{
"id": 46,
"a": [
1024,
2464
],
"b": [
1536,
2464
],
"door": false,
"open": false
},
{
"id": 47,
"a": [
2304,
2400
],
"b": [
2816,
2400
],
"door": false,
"open": false
},
{
"id": 48,
"a": [
2304,
2464
],
"b": [
2816,
2464
],
"door": false,
"open": false
},
{
"id": 49,
"a": [
1888,
1024
],
"b": [
1888,
2048
],
"door": false,
"open": false
},
{
"id": 50,
"a": [
1952,
1024
],
"b": [
1952,
2048
],
"door": false,
"open": false
},
{
"id": 51,
"a": [
3168,
1024
],
"b": [
3168,
2048
],
"door": false,
"open": false
},
{
"id": 52,
"a": [
3232,
1024
],
"b": [
3232,
2048
],
"door": false,
"open": false
},
{
"id": 53,
"a": [
608,
1024
],
"b": [
608,
2048
],
"door": false,
"open": false
},
{
"id": 54,
"a": [
672,
1024
],
"b": [
672,
2048
],
"door": false,
"open": false
},
{
"id": 55,
"a": [
600,
600
],
"b": [
680,
600
],
"door": false,
"open": false
},
{
"id": 56,
"a": [
600,
680
],
"b": [
680,
680
],
"door": false,
"open": false
},
{
"id": 57,
"a": [
600,
600
],
"b": [
600,
680
],
"door": false,
"open": false
},
{
"id": 58,
"a": [
680,
600
],
"b": [
680,
680
],
"door": false,
"open": false
},
{
"id": 59,
"a": [
3000,
700
],
"b": [
3000,
1024
],
"door": false,
"open": false
}
],
"floors": [
[
256,
256,
1024,
1024
],
[
1536,
256,
2304,
1024
],
[
2816,
256,
3584,
1024
],
[
256,
2048,
1024,
2816
],
[
1536,
2048,
2304,
2816
],
[
2816,
2048,
3584,
2816
],
[
1024,
608,
1536,
672
],
[
2304,
608,
2816,
672
],
[
1024,
2400,
1536,
2464
],
[
2304,
2400,
2816,
2464
],
[
1888,
1024,
1952,
2048
],
[
3168,
1024,
3232,
2048
],
[
608,
1024,
672,
2048
]
],
"tokens": [
{
"id": "A",
"kind": "player",
"name": "Player A",
"pos": [
400,
400
],
"gmOnly": false
},
{
"id": "B",
"kind": "player",
"name": "Player B",
"pos": [
400,
2200
],
"gmOnly": false
},
{
"id": "M1",
"kind": "monster",
"name": "Monster 1",
"pos": [
900,
900
],
"gmOnly": true
},
{
"id": "M2",
"kind": "monster",
"name": "Monster 2",
"pos": [
1920,
640
],
"gmOnly": true
},
{
"id": "M3",
"kind": "monster",
"name": "Monster 3",
"pos": [
3400,
500
],
"gmOnly": true
},
{
"id": "M4",
"kind": "monster",
"name": "Monster 4",
"pos": [
900,
2700
],
"gmOnly": true
},
{
"id": "M5",
"kind": "monster",
"name": "Monster 5",
"pos": [
1920,
2400
],
"gmOnly": true
},
{
"id": "M6",
"kind": "monster",
"name": "Monster 6",
"pos": [
3200,
2400
],
"gmOnly": true
}
]
}
+73
View File
@@ -0,0 +1,73 @@
{
"$schema": "https://raw.githubusercontent.com/jetify-com/devbox/0.17.2/.schema/devbox.schema.json",
"packages": {
"nim": "2",
"nimble": "latest",
"nginx": "latest",
"nodejs": "latest",
"sqlite": {
"version": "latest",
"outputs": [
"out",
"bin"
]
}
},
"shell": {
"init_hook": [],
"scripts": {
"gen": [
"node tools/genmap.mjs"
],
"client": [
"cd client && npm install --silent && npm run check && npm run build"
],
"test": [
"node tools/genmap.mjs",
"nimble test",
"devbox run smoke",
"devbox run leaktest",
"devbox run faulttest",
"devbox run restart",
"DUR=15 devbox run concurrency"
],
"server": [
"nimble build -d:release -y",
"mkdir -p run",
"./server"
],
"nginx": [
"mkdir -p run/temp client/dist",
"sed \"s/NGX_PORT/${PORT:-8080}/;s/NGX_BACKEND/${BACKEND_PORT:-9000}/\" nginx/nginx.conf > run/nginx.conf",
"nginx -p \"$PWD/\" -c run/nginx.conf -e run/error.log"
],
"leaktest": [
"tools/leaktest.sh"
],
"concurrency": [
"mkdir -p results; D=${DUR:-60}; N=${TAG:-${D}s}; tools/withserver.sh node tools/concurrency.mjs > results/concurrency-$N.log 2>&1; rc=$?; cat results/concurrency-$N.log; grep STATS run/test/server.log | awk '{k=$0; sub(/ n=.*/, \"\", k); a[k]=$0} END{for (k in a) print a[k]}' | sort > results/concurrency-$N-server.log; { grep SLOW run/test/server.log >> results/concurrency-$N-server.log || true; }; exit $rc"
],
"faulttest": [
"tools/faulttest.sh"
],
"restart": [
"NOSERVE=1 tools/withserver.sh node tools/restart.mjs"
],
"smoke": [
"tools/withserver.sh node tools/smoke.mjs"
],
"mutation": [
"tools/mutation.sh"
],
"clienttest": [
"mkdir -p results; (cd client && npm run check) > results/client-tests.log 2>&1; rc=$?; cat results/client-tests.log; exit $rc"
],
"bench": [
"mkdir -p results; nim c -d:release --hints:off -r -o:run/bench tools/bench.nim | tee results/bench.log"
]
}
},
"env": {
"NIMBLE_DIR": "$DEVBOX_PROJECT_ROOT/.devbox/nimble"
}
}
+437
View File
@@ -0,0 +1,437 @@
{
"lockfile_version": "1",
"packages": {
"gawk@latest": {
"last_modified": "2026-10-02T22:55:44Z",
"resolved": "github:NixOS/nixpkgs/55ba7f49ef2962b42cbd126522b7df5f95037679#gawk",
"source": "devbox-search",
"version": "5.4.1",
"systems": {
"aarch64-darwin": {
"outputs": [
{
"name": "out",
"path": "/nix/store/49jhcfya6jlc7p2hibbl2y5sfz132j3i-gawk-5.4.1",
"default": true
},
{
"name": "man",
"path": "/nix/store/1sclicd2js7iipqnw4vn1rmy3scjg72v-gawk-5.4.1-man",
"default": true
},
{
"name": "info",
"path": "/nix/store/n8gfvirxjm8z5zq7cx30qrmhn40w7jrb-gawk-5.4.1-info"
}
],
"store_path": "/nix/store/49jhcfya6jlc7p2hibbl2y5sfz132j3i-gawk-5.4.1"
},
"aarch64-linux": {
"outputs": [
{
"name": "out",
"path": "/nix/store/2bwpli20ff4f7hg5ck477p8s57kj857w-gawk-5.4.1",
"default": true
},
{
"name": "man",
"path": "/nix/store/wfnxkfk386wl2plrhqx7lwfj4z84r493-gawk-5.4.1-man",
"default": true
},
{
"name": "info",
"path": "/nix/store/l6wddbkc3rxavhbxyl48gn47rw8fq0pd-gawk-5.4.1-info"
}
],
"store_path": "/nix/store/2bwpli20ff4f7hg5ck477p8s57kj857w-gawk-5.4.1"
},
"x86_64-linux": {
"outputs": [
{
"name": "out",
"path": "/nix/store/63g104xwbzfpcq0h7c99w19m6j9ly3p1-gawk-5.4.1",
"default": true
},
{
"name": "man",
"path": "/nix/store/0azvqykndxs3clnj974q99cjfnmpprjv-gawk-5.4.1-man",
"default": true
},
{
"name": "info",
"path": "/nix/store/l4pwpdc6hrgy8n3diy24n389k53jqqjk-gawk-5.4.1-info"
}
],
"store_path": "/nix/store/63g104xwbzfpcq0h7c99w19m6j9ly3p1-gawk-5.4.1"
}
}
},
"gettext@latest": {
"last_modified": "2026-10-02T22:55:44Z",
"resolved": "github:NixOS/nixpkgs/55ba7f49ef2962b42cbd126522b7df5f95037679#gettext",
"source": "devbox-search",
"version": "1.0",
"systems": {
"aarch64-darwin": {
"outputs": [
{
"name": "out",
"path": "/nix/store/d73j7348argskpyvj28wq8n65mj6yg9x-gettext-1.0",
"default": true
},
{
"name": "man",
"path": "/nix/store/arv8546qvpn8cr2bsgvzbzzzypmdv1kp-gettext-1.0-man",
"default": true
},
{
"name": "doc",
"path": "/nix/store/4myr9gbsxvryjnwanyyhnnpqrdh56d5n-gettext-1.0-doc"
},
{
"name": "info",
"path": "/nix/store/b4d4imijjkkzr49zh5mq4gz2j9m2s047-gettext-1.0-info"
}
],
"store_path": "/nix/store/d73j7348argskpyvj28wq8n65mj6yg9x-gettext-1.0"
},
"aarch64-linux": {
"outputs": [
{
"name": "out",
"path": "/nix/store/8aimx510wyy0rzy7mllcjad5299jd17a-gettext-1.0",
"default": true
},
{
"name": "man",
"path": "/nix/store/qllbgswyx416d7r7kqkyxvafpfbasmr8-gettext-1.0-man",
"default": true
},
{
"name": "doc",
"path": "/nix/store/r2d6saacyqv8m9d8bvaidv4x2raqjb7z-gettext-1.0-doc"
},
{
"name": "info",
"path": "/nix/store/hsrnhwfpvrs4x4a5807cprpyz4qclgxy-gettext-1.0-info"
}
],
"store_path": "/nix/store/8aimx510wyy0rzy7mllcjad5299jd17a-gettext-1.0"
},
"x86_64-darwin": {
"outputs": [
{
"name": "out",
"path": "/nix/store/9mxzw5vwn99vx2b74ipjzk8x4b784fjy-gettext-1.0",
"default": true
},
{
"name": "man",
"path": "/nix/store/r87hlf9pn8q3a8rnplzhy9lbgaadqcr8-gettext-1.0-man",
"default": true
},
{
"name": "doc",
"path": "/nix/store/xmssbi5i2w3fv67hrv6c29wdiv8gxywi-gettext-1.0-doc"
},
{
"name": "info",
"path": "/nix/store/j4lz4zqicd1mw2l5c272ialxhl0nkc0b-gettext-1.0-info"
}
],
"store_path": "/nix/store/9mxzw5vwn99vx2b74ipjzk8x4b784fjy-gettext-1.0"
},
"x86_64-linux": {
"outputs": [
{
"name": "out",
"path": "/nix/store/gfkkr23q11kvyz6xxyxz3qbsp1msxdcv-gettext-1.0",
"default": true
},
{
"name": "man",
"path": "/nix/store/njdszjnrb0n7c6m6jzmx5539ac0ybn9g-gettext-1.0-man",
"default": true
},
{
"name": "doc",
"path": "/nix/store/z2p7kr1a45gz9m9g3s6rary2avk3gs9x-gettext-1.0-doc"
},
{
"name": "info",
"path": "/nix/store/8vqnaf3h4vlb8q5w9z9kscqld7m5rdif-gettext-1.0-info"
}
],
"store_path": "/nix/store/gfkkr23q11kvyz6xxyxz3qbsp1msxdcv-gettext-1.0"
}
}
},
"github:NixOS/nixpkgs/nixpkgs-unstable": {
"last_modified": "2026-10-20T14:23:57Z",
"resolved": "github:NixOS/nixpkgs/5adc50831c259f87faeb09ddf930d43597197473?lastModified=1792506237&narHash=sha256-Q%2F8KLB6jNfpaUN1HAedE%2Fu%2FEt9feE%2FzYSsutBLKrCFk%3D"
},
"nginx@latest": {
"last_modified": "2026-10-02T22:55:44Z",
"plugin_version": "0.0.4",
"resolved": "github:NixOS/nixpkgs/55ba7f49ef2962b42cbd126522b7df5f95037679#nginx",
"source": "devbox-search",
"version": "1.30.5",
"systems": {
"aarch64-darwin": {
"outputs": [
{
"name": "out",
"path": "/nix/store/81a75xq2ilmn8dnrb1b7m8siyprmaq94-nginx-1.30.5",
"default": true
},
{
"name": "doc",
"path": "/nix/store/s9zq3wyd2bdfwb58rk2648yf2wsryvhj-nginx-1.30.5-doc"
}
],
"store_path": "/nix/store/81a75xq2ilmn8dnrb1b7m8siyprmaq94-nginx-1.30.5"
},
"aarch64-linux": {
"outputs": [
{
"name": "out",
"path": "/nix/store/7yvpd3svx846fybmc2d5ddxq3jxf94qm-nginx-1.30.5",
"default": true
},
{
"name": "doc",
"path": "/nix/store/skp8nki2v0li5h44zyp1gp8s2ahz3g4j-nginx-1.30.5-doc"
}
],
"store_path": "/nix/store/7yvpd3svx846fybmc2d5ddxq3jxf94qm-nginx-1.30.5"
},
"x86_64-linux": {
"outputs": [
{
"name": "out",
"path": "/nix/store/6k4rgdzx05z7yk2l98r28p6wrbnlv63z-nginx-1.30.5",
"default": true
},
{
"name": "doc",
"path": "/nix/store/d8v365rflmpicpcnxjqfxbbzlpk0q844-nginx-1.30.5-doc"
}
],
"store_path": "/nix/store/6k4rgdzx05z7yk2l98r28p6wrbnlv63z-nginx-1.30.5"
}
}
},
"nim@2": {
"last_modified": "2026-10-02T22:55:44Z",
"resolved": "github:NixOS/nixpkgs/55ba7f49ef2962b42cbd126522b7df5f95037679#nim",
"source": "devbox-search",
"version": "2.2.12",
"systems": {
"aarch64-darwin": {
"outputs": [
{
"name": "out",
"path": "/nix/store/h055h3lxxsm8kql0mannw3706x740x7f-arm64-apple-darwin-nim-wrapper-2.2.12",
"default": true
}
],
"store_path": "/nix/store/h055h3lxxsm8kql0mannw3706x740x7f-arm64-apple-darwin-nim-wrapper-2.2.12"
},
"aarch64-linux": {
"outputs": [
{
"name": "out",
"path": "/nix/store/2fh7rg634j8969c1r394llrsjmmhaip7-aarch64-unknown-linux-gnu-nim-wrapper-2.2.12",
"default": true
}
],
"store_path": "/nix/store/2fh7rg634j8969c1r394llrsjmmhaip7-aarch64-unknown-linux-gnu-nim-wrapper-2.2.12"
},
"x86_64-linux": {
"outputs": [
{
"name": "out",
"path": "/nix/store/0cbdz34lsakfirycixckf6ypsd8hazhg-x86_64-unknown-linux-gnu-nim-wrapper-2.2.12",
"default": true
}
],
"store_path": "/nix/store/0cbdz34lsakfirycixckf6ypsd8hazhg-x86_64-unknown-linux-gnu-nim-wrapper-2.2.12"
}
}
},
"nimble@latest": {
"last_modified": "2026-10-02T22:55:44Z",
"resolved": "github:NixOS/nixpkgs/55ba7f49ef2962b42cbd126522b7df5f95037679#nimble",
"source": "devbox-search",
"version": "0.24.1",
"systems": {
"aarch64-darwin": {
"outputs": [
{
"name": "out",
"path": "/nix/store/clxsxdsqjfcc43rfd7rad733nd0ndrkf-nimble-0.24.1",
"default": true
}
],
"store_path": "/nix/store/clxsxdsqjfcc43rfd7rad733nd0ndrkf-nimble-0.24.1"
},
"aarch64-linux": {
"outputs": [
{
"name": "out",
"path": "/nix/store/c5d0r4a8qi1vqs8q82pr3c652q8d6jv7-nimble-0.24.1",
"default": true
}
],
"store_path": "/nix/store/c5d0r4a8qi1vqs8q82pr3c652q8d6jv7-nimble-0.24.1"
},
"x86_64-linux": {
"outputs": [
{
"name": "out",
"path": "/nix/store/8f5wx2s80gnw0lkmdpbl63n1xlilcfxi-nimble-0.24.1",
"default": true
}
],
"store_path": "/nix/store/8f5wx2s80gnw0lkmdpbl63n1xlilcfxi-nimble-0.24.1"
}
}
},
"nodejs@latest": {
"last_modified": "2026-10-08T19:21:32Z",
"plugin_version": "0.0.2",
"resolved": "github:NixOS/nixpkgs/8edc0c72e3a38faf5434e40d1f19431125fe4b30#nodejs_26",
"source": "devbox-search",
"version": "26.11.1",
"systems": {
"aarch64-darwin": {
"outputs": [
{
"name": "out",
"path": "/nix/store/42hvw959dvc16w7p79xns4p4sgfx2wiv-nodejs-26.11.1",
"default": true
}
],
"store_path": "/nix/store/42hvw959dvc16w7p79xns4p4sgfx2wiv-nodejs-26.11.1"
},
"aarch64-linux": {
"outputs": [
{
"name": "out",
"path": "/nix/store/zzx8zal1hmjkamrp8y9k6mjim08pzwz8-nodejs-26.11.1",
"default": true
}
],
"store_path": "/nix/store/zzx8zal1hmjkamrp8y9k6mjim08pzwz8-nodejs-26.11.1"
},
"x86_64-linux": {
"outputs": [
{
"name": "out",
"path": "/nix/store/m7vfpzl1rjwjpwlcsqs166jn3lywzpq1-nodejs-26.11.1",
"default": true
}
],
"store_path": "/nix/store/m7vfpzl1rjwjpwlcsqs166jn3lywzpq1-nodejs-26.11.1"
}
}
},
"sqlite@latest": {
"last_modified": "2026-10-08T19:21:32Z",
"resolved": "github:NixOS/nixpkgs/8edc0c72e3a38faf5434e40d1f19431125fe4b30#sqlite",
"source": "devbox-search",
"version": "3.53.3",
"systems": {
"aarch64-darwin": {
"outputs": [
{
"name": "bin",
"path": "/nix/store/9miwmq08y0pg4m97ws8b2gcqxrbr8d2c-sqlite-3.53.3-bin",
"default": true
},
{
"name": "man",
"path": "/nix/store/wlwc2gz7r5884rdmfjnqjk38lwv94qsy-sqlite-3.53.3-man",
"default": true
},
{
"name": "doc",
"path": "/nix/store/p6bsmbp6a5dz55isxvfr7941wbfjmjvf-sqlite-3.53.3-doc"
},
{
"name": "out",
"path": "/nix/store/0k4r9hnfbnyngn5f3j31siddfs0iglwl-sqlite-3.53.3"
},
{
"name": "dev",
"path": "/nix/store/r9cljv2bvqi3ci3n6m0z0wi3ldpvlyzq-sqlite-3.53.3-dev"
}
],
"store_path": "/nix/store/9miwmq08y0pg4m97ws8b2gcqxrbr8d2c-sqlite-3.53.3-bin"
},
"aarch64-linux": {
"outputs": [
{
"name": "bin",
"path": "/nix/store/kw0mkd9znldi5l0s4jygygdh4p9sms8r-sqlite-3.53.3-bin",
"default": true
},
{
"name": "man",
"path": "/nix/store/9q84sy842rw7k4z4jdsb4hkbiapr7pm0-sqlite-3.53.3-man",
"default": true
},
{
"name": "debug",
"path": "/nix/store/q39crs8z0dafx19dv0l2y4jxc8ahvy03-sqlite-3.53.3-debug"
},
{
"name": "dev",
"path": "/nix/store/74r7ps7mmjw10fl23xsgcp7ss09jrkjr-sqlite-3.53.3-dev"
},
{
"name": "doc",
"path": "/nix/store/g4f5y9laa7l7lbriv8x05clyi9x7w14z-sqlite-3.53.3-doc"
},
{
"name": "out",
"path": "/nix/store/2lyx0wc6ccabpdwpviksww3x5xhsmnvk-sqlite-3.53.3"
}
],
"store_path": "/nix/store/kw0mkd9znldi5l0s4jygygdh4p9sms8r-sqlite-3.53.3-bin"
},
"x86_64-linux": {
"outputs": [
{
"name": "bin",
"path": "/nix/store/iy2zkfn4l0w24xabv6ryi0vh7bpjvqm6-sqlite-3.53.3-bin",
"default": true
},
{
"name": "man",
"path": "/nix/store/is1ld1bxvwqqjwv89kl6vcnlpypbkg5r-sqlite-3.53.3-man",
"default": true
},
{
"name": "doc",
"path": "/nix/store/l778wamidjdrjyahinx63c7n50fwh0il-sqlite-3.53.3-doc"
},
{
"name": "out",
"path": "/nix/store/9x0m6s73sg89fv5awb95vsac2mbns8n0-sqlite-3.53.3"
},
{
"name": "debug",
"path": "/nix/store/1vbdchnss15n90chl72l80z16shxjp7l-sqlite-3.53.3-debug"
},
{
"name": "dev",
"path": "/nix/store/xrcjl59yi7zswbv0vzm8cmvw4vplsbgj-sqlite-3.53.3-dev"
}
],
"store_path": "/nix/store/iy2zkfn4l0w24xabv6ryi0vh7bpjvqm6-sqlite-3.53.3-bin"
}
}
}
}
}
+99
View File
@@ -0,0 +1,99 @@
types {
text/html html htm shtml;
text/css css;
text/xml xml;
image/gif gif;
image/jpeg jpeg jpg;
application/javascript js;
application/atom+xml atom;
application/rss+xml rss;
text/mathml mml;
text/plain txt;
text/vnd.sun.j2me.app-descriptor jad;
text/vnd.wap.wml wml;
text/x-component htc;
image/avif avif;
image/png png;
image/svg+xml svg svgz;
image/tiff tif tiff;
image/vnd.wap.wbmp wbmp;
image/webp webp;
image/x-icon ico;
image/x-jng jng;
image/x-ms-bmp bmp;
font/woff woff;
font/woff2 woff2;
application/java-archive jar war ear;
application/json json;
application/mac-binhex40 hqx;
application/msword doc;
application/pdf pdf;
application/postscript ps eps ai;
application/rtf rtf;
application/vnd.apple.mpegurl m3u8;
application/vnd.google-earth.kml+xml kml;
application/vnd.google-earth.kmz kmz;
application/vnd.ms-excel xls;
application/vnd.ms-fontobject eot;
application/vnd.ms-powerpoint ppt;
application/vnd.oasis.opendocument.graphics odg;
application/vnd.oasis.opendocument.presentation odp;
application/vnd.oasis.opendocument.spreadsheet ods;
application/vnd.oasis.opendocument.text odt;
application/vnd.openxmlformats-officedocument.presentationml.presentation
pptx;
application/vnd.openxmlformats-officedocument.spreadsheetml.sheet
xlsx;
application/vnd.openxmlformats-officedocument.wordprocessingml.document
docx;
application/vnd.wap.wmlc wmlc;
application/wasm wasm;
application/x-7z-compressed 7z;
application/x-cocoa cco;
application/x-java-archive-diff jardiff;
application/x-java-jnlp-file jnlp;
application/x-makeself run;
application/x-perl pl pm;
application/x-pilot prc pdb;
application/x-rar-compressed rar;
application/x-redhat-package-manager rpm;
application/x-sea sea;
application/x-shockwave-flash swf;
application/x-stuffit sit;
application/x-tcl tcl tk;
application/x-x509-ca-cert der pem crt;
application/x-xpinstall xpi;
application/xhtml+xml xhtml;
application/xspf+xml xspf;
application/zip zip;
application/octet-stream bin exe dll;
application/octet-stream deb;
application/octet-stream dmg;
application/octet-stream iso img;
application/octet-stream msi msp msm;
audio/midi mid midi kar;
audio/mpeg mp3;
audio/ogg ogg;
audio/x-m4a m4a;
audio/x-realaudio ra;
video/3gpp 3gpp 3gp;
video/mp2t ts;
video/mp4 mp4;
video/mpeg mpeg mpg;
video/quicktime mov;
video/webm webm;
video/x-flv flv;
video/x-m4v m4v;
video/x-mng mng;
video/x-ms-asf asx asf;
video/x-ms-wmv wmv;
video/x-msvideo avi;
}
+33
View File
@@ -0,0 +1,33 @@
# run via `devbox run nginx`; prefix = project root, all temp/log paths in run/
daemon off;
pid run/nginx.pid;
error_log run/error.log warn;
events {}
http {
access_log run/access.log;
client_body_temp_path run/temp/client_body;
proxy_temp_path run/temp/proxy;
fastcgi_temp_path run/temp/fastcgi;
uwsgi_temp_path run/temp/uwsgi;
scgi_temp_path run/temp/scgi;
server_tokens off;
include ../nginx/mime.types; # relative to the generated run/nginx.conf
map $http_upgrade $conn_up { default upgrade; '' close; }
server {
listen NGX_PORT; # sed-substituted from $PORT (default 8080); NGX_BACKEND from $BACKEND_PORT (default 9000)
server_name localhost;
root client/dist;
index index.html;
location /join/ { proxy_pass http://127.0.0.1:NGX_BACKEND; }
location /tiles/ { proxy_pass http://127.0.0.1:NGX_BACKEND; }
location /ws {
proxy_pass http://127.0.0.1:NGX_BACKEND;
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection $conn_up;
proxy_read_timeout 1h;
}
# only reachable via X-Accel-Redirect from Nim after its access check
location /_tiles/ { internal; alias data/tiles/; add_header Cache-Control "private, no-cache"; }
}
}
+3
View File
@@ -0,0 +1,3 @@
--path:"src"
--threads:on
--mm:orc
@@ -0,0 +1,5 @@
1 poly (jittered start positions): n=2000 avg=0.038ms worst=0.180ms
6 polys (one 6-token party): n=500 avg=0.205ms worst=0.291ms
1 poly + cellsTouched: n=2000 avg=0.451ms worst=0.980ms
6 polys + cellsTouched: n=300 avg=2.947ms worst=3.727ms
(sink 2063860)
@@ -0,0 +1,16 @@
> check
> node --test src/state.test.ts
✔ protocol reducer: fake server script (1.456001ms)
✔ gm walls + door (0.181201ms)
✔ tilesOfCells (0.268275ms)
✔ hello resets state (reconnect) (0.211899ms)
ℹ tests 4
ℹ suites 0
ℹ pass 4
ℹ fail 0
ℹ cancelled 0
ℹ skipped 0
ℹ todo 0
ℹ duration_ms 132.877698
@@ -0,0 +1,15 @@
STATS bytes/delivery door gm: n=62 avg=44.8 worst=46.
STATS bytes/delivery move-monster A: n=843 avg=146.0 worst=154.
STATS bytes/delivery move-monster B: n=754 avg=145.5 worst=154.
STATS bytes/delivery move-monster gm: n=10286 avg=243.5 worst=252.
STATS bytes/delivery move-player A: n=1689 avg=3652.8 worst=4887.
STATS bytes/delivery move-player B: n=1711 avg=3358.9 worst=4433.
STATS bytes/delivery move-player gm: n=3400 avg=144.6 worst=149.
STATS timing_ms lock_wait: n=13748 avg=0.119 p50=0.000 p99=2.181 worst=16.860
STATS timing_ms send: n=13748 avg=0.061 p50=0.040 p99=0.187 worst=0.335
STATS timing_ms sqlite: n=13748 avg=0.167 p50=0.139 p99=0.307 worst=17.568
STATS timing_ms total: n=13748 avg=0.701 p50=0.286 p99=3.714 worst=19.634
STATS timing_ms vision: n=13748 avg=0.293 p50=0.000 p99=2.491 worst=4.549
STATS vision_ms door: n=62 avg=0.204 worst=0.297
STATS vision_ms move-monster: n=10286 avg=0.000 worst=0.024
STATS vision_ms move-player: n=3400 avg=1.181 worst=4.549
@@ -0,0 +1,6 @@
gm: sent 10299 moves (167/s), acks 10299 (nack 13), recv 24054 msgs 2935 KiB, final gseq 13748, tokens in view 8
A: sent 1715 moves (28/s), acks 1715 (nack 26), recv 6093 msgs 6153 KiB, final gseq 13745, tokens in view 2
B: sent 1711 moves (28/s), acks 1711 (nack 0), recv 6035 msgs 5725 KiB, final gseq 13742, tokens in view 1
latency intent->ack (sender): n=13725 avg=1.40ms p95=2.99ms p99=4.58ms worst=20.31ms
latency intent->arrival at other clients: n=4926 avg=2.04ms p95=3.66ms p99=5.17ms worst=18.94ms
concurrency: PASS
@@ -0,0 +1,15 @@
STATS bytes/delivery door gm: n=58 avg=44.8 worst=46.
STATS bytes/delivery move-monster A: n=1393 avg=149.0 worst=154.
STATS bytes/delivery move-monster B: n=850 avg=147.4 worst=154.
STATS bytes/delivery move-monster gm: n=10222 avg=243.6 worst=252.
STATS bytes/delivery move-player A: n=1699 avg=3903.2 worst=4949.
STATS bytes/delivery move-player B: n=1716 avg=3341.6 worst=4514.
STATS bytes/delivery move-player gm: n=3414 avg=144.6 worst=148.
STATS timing_ms lock_wait: n=13695 avg=0.146 p50=0.000 p99=2.640 worst=19.868
STATS timing_ms send: n=13695 avg=0.064 p50=0.041 p99=0.199 worst=0.486
STATS timing_ms sqlite: n=13695 avg=0.169 p50=0.142 p99=0.301 worst=19.760
STATS timing_ms total: n=13695 avg=0.789 p50=0.293 p99=4.092 worst=21.321
STATS timing_ms vision: n=13695 avg=0.347 p50=0.000 p99=3.059 worst=4.930
STATS vision_ms door: n=58 avg=0.224 worst=0.328
STATS vision_ms move-monster: n=10222 avg=0.000 worst=0.022
STATS vision_ms move-player: n=3415 avg=1.387 worst=4.930
@@ -0,0 +1,6 @@
gm: sent 10271 moves (166/s), acks 10271 (nack 49), recv 23971 msgs 2926 KiB, final gseq 13695, tokens in view 8
A: sent 1709 moves (28/s), acks 1709 (nack 10), recv 6617 msgs 6685 KiB, final gseq 13693, tokens in view 2
B: sent 1716 moves (28/s), acks 1716 (nack 0), recv 6148 msgs 5728 KiB, final gseq 13690, tokens in view 2
latency intent->ack (sender): n=13696 avg=1.50ms p95=3.39ms p99=4.98ms worst=21.73ms
latency intent->arrival at other clients: n=5610 avg=2.10ms p95=4.11ms p99=5.47ms worst=21.78ms
concurrency: PASS
@@ -0,0 +1,15 @@
STATS bytes/delivery door gm: n=64 avg=44.8 worst=46.
STATS bytes/delivery move-monster A: n=912 avg=146.8 worst=154.
STATS bytes/delivery move-monster B: n=739 avg=143.6 worst=154.
STATS bytes/delivery move-monster gm: n=10278 avg=243.4 worst=252.
STATS bytes/delivery move-player A: n=1709 avg=3639.5 worst=4978.
STATS bytes/delivery move-player B: n=1707 avg=3280.8 worst=4489.
STATS bytes/delivery move-player gm: n=3413 avg=144.7 worst=149.
STATS timing_ms lock_wait: n=13758 avg=0.128 p50=0.000 p99=2.341 worst=21.024
STATS timing_ms send: n=13758 avg=0.061 p50=0.039 p99=0.184 worst=0.336
STATS timing_ms sqlite: n=13758 avg=0.170 p50=0.141 p99=0.297 worst=23.209
STATS timing_ms total: n=13758 avg=0.719 p50=0.288 p99=3.874 worst=24.258
STATS timing_ms vision: n=13758 avg=0.297 p50=0.000 p99=2.874 worst=4.548
STATS vision_ms door: n=64 avg=0.209 worst=0.288
STATS vision_ms move-monster: n=10278 avg=0.000 worst=0.026
STATS vision_ms move-player: n=3416 avg=1.191 worst=4.548
@@ -0,0 +1,6 @@
gm: sent 10302 moves (163/s), acks 10302 (nack 24), recv 24064 msgs 2936 KiB, final gseq 13758, tokens in view 8
A: sent 1724 moves (27/s), acks 1724 (nack 15), recv 6214 msgs 6212 KiB, final gseq 13748, tokens in view 1
B: sent 1707 moves (27/s), acks 1707 (nack 0), recv 6065 msgs 5578 KiB, final gseq 13756, tokens in view 2
latency intent->ack (sender): n=13733 avg=1.43ms p95=3.15ms p99=4.75ms worst=24.72ms
latency intent->arrival at other clients: n=4987 avg=2.04ms p95=3.90ms p99=5.41ms worst=24.80ms
concurrency: PASS
+148
View File
@@ -0,0 +1,148 @@
== fault hidden
FAIL [HIDDEN_TOKEN] LEAK token M5 outside A vision at g=0
FAIL [HIDDEN_TOKEN] view mismatch M5 want=false at g=0
FAIL [HIDDEN_TOKEN] view mismatch M5 want=false at g=1
FAIL [HIDDEN_TOKEN] view mismatch M5 want=false at g=2
FAIL [HIDDEN_TOKEN] view mismatch M5 want=false at g=3
FAIL [HIDDEN_TOKEN] view mismatch M5 want=false at g=4
FAIL [HIDDEN_TOKEN] view mismatch M5 want=false at g=5
FAIL [HIDDEN_TOKEN] view mismatch M5 want=false at g=6
FAIL [HIDDEN_TOKEN] view mismatch M5 want=false at g=7
FAIL [HIDDEN_TOKEN] view mismatch M5 want=false at g=8
FAIL [HIDDEN_TOKEN] view mismatch M5 want=false at g=9
FAIL [HIDDEN_TOKEN] view mismatch M5 want=false at g=10
FAIL [HIDDEN_TOKEN] view mismatch M5 want=false at g=11
FAIL [HIDDEN_TOKEN] view mismatch M5 want=false at g=12
FAIL [HIDDEN_TOKEN] view mismatch M5 want=false at g=13
FAIL [HIDDEN_TOKEN] view mismatch M5 want=false at g=14
FAIL [HIDDEN_TOKEN] view mismatch M5 want=false at g=15
FAIL [HIDDEN_TOKEN] view mismatch M5 want=false at g=16
FAIL [HIDDEN_TOKEN] view mismatch M5 want=false at g=17
FAIL [HIDDEN_TOKEN] view mismatch M5 want=false at g=18
FAILCLASS HIDDEN_TOKEN 144
leakcheck: 218 gseq groups, subject msgs 466, tokens seen 4 others, removes 3, tiles 9984 (200:1709 403:8275 other:0), explored cells 2142, failures 144
== fault walls
FAIL [WALLDATA] A got forbidden type walls
FAILCLASS WALLDATA 1
leakcheck: 218 gseq groups, subject msgs 468, tokens seen 4 others, removes 4, tiles 9984 (200:1709 403:8275 other:0), explored cells 2142, failures 1
== fault tile
FAIL [TILE] tile 3_0 g=0 (start) status 200 expected 403
FAIL [TILE] tile 4_0 g=0 (start) status 200 expected 403
FAIL [TILE] tile 5_0 g=0 (start) status 200 expected 403
FAIL [TILE] tile 6_0 g=0 (start) status 200 expected 403
FAIL [TILE] tile 7_0 g=0 (start) status 200 expected 403
FAIL [TILE] tile 8_0 g=0 (start) status 200 expected 403
FAIL [TILE] tile 9_0 g=0 (start) status 200 expected 403
FAIL [TILE] tile 10_0 g=0 (start) status 200 expected 403
FAIL [TILE] tile 11_0 g=0 (start) status 200 expected 403
FAIL [TILE] tile 12_0 g=0 (start) status 200 expected 403
FAIL [TILE] tile 13_0 g=0 (start) status 200 expected 403
FAIL [TILE] tile 14_0 g=0 (start) status 200 expected 403
FAIL [TILE] tile 15_0 g=0 (start) status 200 expected 403
FAIL [TILE] tile 4_1 g=0 (start) status 200 expected 403
FAIL [TILE] tile 5_1 g=0 (start) status 200 expected 403
FAIL [TILE] tile 6_1 g=0 (start) status 200 expected 403
FAIL [TILE] tile 7_1 g=0 (start) status 200 expected 403
FAIL [TILE] tile 8_1 g=0 (start) status 200 expected 403
FAIL [TILE] tile 9_1 g=0 (start) status 200 expected 403
FAIL [TILE] tile 10_1 g=0 (start) status 200 expected 403
FAILCLASS TILE 8275
leakcheck: 218 gseq groups, subject msgs 467, tokens seen 4 others, removes 4, tiles 9984 (200:9984 403:0 other:0), explored cells 2142, failures 8275
== fault withhold
FAIL [WITHHELD] view mismatch M1 want=true at g=21
FAIL [WITHHELD] view mismatch M1 want=true at g=22
FAIL [WITHHELD] view mismatch M1 want=true at g=23
FAIL [WITHHELD] view mismatch M1 want=true at g=24
FAIL [WITHHELD] view mismatch M1 want=true at g=25
FAIL [WITHHELD] view mismatch M1 want=true at g=26
FAIL [WITHHELD] view mismatch M1 want=true at g=27
FAIL [WITHHELD] view mismatch M1 want=true at g=28
FAIL [WITHHELD] view mismatch M1 want=true at g=29
FAIL [WITHHELD] view mismatch M1 want=true at g=30
FAIL [WITHHELD] view mismatch M1 want=true at g=31
FAIL [WITHHELD] view mismatch M1 want=true at g=32
FAIL [WITHHELD] view mismatch M1 want=true at g=33
FAIL [WITHHELD] view mismatch M1 want=true at g=34
FAIL [WITHHELD] view mismatch M1 want=true at g=35
FAIL [WITHHELD] view mismatch M1 want=true at g=36
FAIL [WITHHELD] view mismatch M1 want=true at g=37
FAIL [WITHHELD] view mismatch M1 want=true at g=38
FAIL [WITHHELD] scenario never showed subject token M1
FAILCLASS WITHHELD 19
leakcheck: 218 gseq groups, subject msgs 465, tokens seen 3 others, removes 3, tiles 9984 (200:1709 403:8275 other:0), explored cells 2142, failures 19
== fault other-vision
FAIL [OTHER_PLAYER] vision carries B's polygon at g=0
FAIL [OWN_VIEW] vision shape at g=0
FAIL [OTHER_PLAYER] vision carries B's polygon at g=1
FAIL [OWN_VIEW] vision shape at g=1
FAIL [OTHER_PLAYER] vision carries B's polygon at g=2
FAIL [OWN_VIEW] vision shape at g=2
FAIL [OTHER_PLAYER] vision carries B's polygon at g=3
FAIL [OWN_VIEW] vision shape at g=3
FAIL [OTHER_PLAYER] vision carries B's polygon at g=4
FAIL [OWN_VIEW] vision shape at g=4
FAIL [OTHER_PLAYER] vision carries B's polygon at g=5
FAIL [OWN_VIEW] vision shape at g=5
FAIL [OTHER_PLAYER] vision carries B's polygon at g=6
FAIL [OWN_VIEW] vision shape at g=6
FAIL [OTHER_PLAYER] vision carries B's polygon at g=7
FAIL [OWN_VIEW] vision shape at g=7
FAIL [OTHER_PLAYER] vision carries B's polygon at g=8
FAIL [OWN_VIEW] vision shape at g=8
FAIL [OTHER_PLAYER] vision carries B's polygon at g=9
FAIL [OWN_VIEW] vision shape at g=9
FAILCLASS OTHER_PLAYER 218
FAILCLASS OWN_VIEW 218
leakcheck: 218 gseq groups, subject msgs 574, tokens seen 4 others, removes 4, tiles 9984 (200:1709 403:8275 other:0), explored cells 2142, failures 436
== fault other-explored
FAIL [OTHER_PLAYER] LEAK explored cell not yet explored [7,65]
FAIL [OTHER_PLAYER] LEAK explored cell not yet explored [24,68]
FAIL [OTHER_PLAYER] LEAK explored cell not yet explored [11,64]
FAIL [OTHER_PLAYER] LEAK explored cell not yet explored [14,81]
FAIL [OTHER_PLAYER] LEAK explored cell not yet explored [7,72]
FAIL [OTHER_PLAYER] LEAK explored cell not yet explored [11,79]
FAIL [OTHER_PLAYER] LEAK explored cell not yet explored [8,68]
FAIL [OTHER_PLAYER] LEAK explored cell not yet explored [21,75]
FAIL [OTHER_PLAYER] LEAK explored cell not yet explored [18,64]
FAIL [OTHER_PLAYER] LEAK explored cell not yet explored [15,69]
FAIL [OTHER_PLAYER] LEAK explored cell not yet explored [15,66]
FAIL [OTHER_PLAYER] LEAK explored cell not yet explored [10,73]
FAIL [OTHER_PLAYER] LEAK explored cell not yet explored [8,72]
FAIL [OTHER_PLAYER] LEAK explored cell not yet explored [18,74]
FAIL [OTHER_PLAYER] LEAK explored cell not yet explored [11,75]
FAIL [OTHER_PLAYER] LEAK explored cell not yet explored [21,66]
FAIL [OTHER_PLAYER] LEAK explored cell not yet explored [16,72]
FAIL [OTHER_PLAYER] LEAK explored cell not yet explored [23,64]
FAIL [OTHER_PLAYER] LEAK explored cell not yet explored [10,77]
FAIL [OTHER_PLAYER] LEAK explored cell not yet explored [12,77]
FAILCLASS OTHER_PLAYER 786
FAILCLASS EXPLORED 218
leakcheck: 218 gseq groups, subject msgs 505, tokens seen 4 others, removes 4, tiles 9984 (200:1709 403:8275 other:0), explored cells 2142, failures 1004
== fault other-owner
FAIL [OTHER_PLAYER] B mentioned in {"role":"player","tokens":["A","B"],"world":{"w":4096,"h":4096},"tileSize":256,"exploredCell":32,"tokenRadius":20,"t":"hello","gseq":0}
FAIL [OTHER_PLAYER] hello tokens ["A","B"]
FAILCLASS OTHER_PLAYER 2
leakcheck: 218 gseq groups, subject msgs 467, tokens seen 4 others, removes 4, tiles 9984 (200:1709 403:8275 other:0), explored cells 2142, failures 2
== fault noremove
FAIL [NO_REMOVE] view mismatch M1 want=false at g=39
FAIL [NO_REMOVE] view mismatch M1 want=false at g=40
FAIL [NO_REMOVE] view mismatch M1 want=false at g=41
FAIL [NO_REMOVE] view mismatch M1 want=false at g=42
FAIL [NO_REMOVE] view mismatch M1 want=false at g=43
FAIL [NO_REMOVE] view mismatch M1 want=false at g=44
FAIL [NO_REMOVE] view mismatch M1 want=false at g=45
FAIL [NO_REMOVE] view mismatch M1 want=false at g=46
FAIL [NO_REMOVE] view mismatch M1 want=false at g=47
FAIL [NO_REMOVE] view mismatch M1 want=false at g=48
FAIL [NO_REMOVE] view mismatch M1 want=false at g=49
FAIL [NO_REMOVE] view mismatch M1 want=false at g=50
FAIL [NO_REMOVE] view mismatch M1 want=false at g=51
FAIL [NO_REMOVE] view mismatch M1 want=false at g=52
FAIL [NO_REMOVE] view mismatch M1 want=false at g=53
FAIL [NO_REMOVE] view mismatch M1 want=false at g=54
FAIL [NO_REMOVE] view mismatch M1 want=false at g=55
FAIL [NO_REMOVE] view mismatch M1 want=false at g=56
FAIL [NO_REMOVE] view mismatch M1 want=false at g=57
FAIL [NO_REMOVE] view mismatch M1 want=false at g=58
FAILCLASS NO_REMOVE 356
leakcheck: 218 gseq groups, subject msgs 463, tokens seen 4 others, removes 0, tiles 9984 (200:1709 403:8275 other:0), explored cells 2142, failures 356
@@ -0,0 +1,11 @@
Info: Running script "faulttest" on /home/davide/Projects/GDR/FFF_vtt/prototype-server-vision
PASS run/test/server-clean has no fault hook
PASS fault hidden caught as: HIDDEN_TOKEN
PASS fault walls caught as: WALLDATA
PASS fault tile caught as: TILE
PASS fault withhold caught as: WITHHELD
PASS fault other-vision caught as: OTHER_PLAYER OWN_VIEW
PASS fault other-explored caught as: EXPLORED OTHER_PLAYER
PASS fault other-owner caught as: OTHER_PLAYER
PASS fault noremove caught as: NO_REMOVE
PASS clean build passes
@@ -0,0 +1,7 @@
Info: Running script "leaktest" on /home/davide/Projects/GDR/FFF_vtt/prototype-server-vision
== SUBJECT=A
driver done: 237 actions, 0 unexpected acks, final gseq 217
leakcheck: 218 gseq groups, subject msgs 467, tokens seen 4 others, removes 4, tiles 9984 (200:1709 403:8275 other:0), explored cells 2142, failures 0
== SUBJECT=B
driver done: 237 actions, 0 unexpected acks, final gseq 217
leakcheck: 218 gseq groups, subject msgs 217, tokens seen 3 others, removes 3, tiles 7424 (200:686 403:6738 other:0), explored cells 1114, failures 0
@@ -0,0 +1,12 @@
nimble-test 0
mutation 0
leaktest 0
faulttest 0
restart 0
smoke 0
bench 0
client-tests 0
concurrency-final1 0
concurrency-final2 0
concurrency-final3 0
DONE
@@ -0,0 +1,28 @@
Info: Running script "restart" on /home/davide/Projects/GDR/FFF_vtt/prototype-server-vision
PASS move A -> 400,800
PASS move A -> 800,800
PASS move A -> 800,640
PASS move A -> 1000,640
PASS move A -> 1510,640
PASS move B -> 700,2300
PASS move M1 -> 900,640
PASS move M2 -> 2200,300
PASS move A -> 1700,640
PASS cycle1: invite secrets identical
PASS cycle1: gm state identical after SIGTERM restart
PASS cycle1: A state identical after SIGTERM restart
PASS cycle1: B state identical after SIGTERM restart
PASS A explored new area (292 -> 1145)
PASS cycle1: token positions are the moved ones
PASS cycle1: door states are the toggled ones
PASS cycle1: doors differ from initial (test is not vacuous)
PASS move A -> 1900,640
PASS move B -> 1000,2300
PASS move M1 -> 1200,640
PASS cycle2: invite secrets identical
PASS cycle2: gm state identical after SIGKILL restart
PASS cycle2: A state identical after SIGKILL restart
PASS cycle2: B state identical after SIGKILL restart
PASS cycle2: A explored more before kill -9
PASS cycle2: B explored more before kill -9
restart: PASS
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,2 @@
driver done: 237 actions, 0 unexpected acks, final gseq 217
leakcheck: 218 gseq groups, subject msgs 467, tokens seen 4 others, removes 4, tiles 9984 (200:1709 403:8275 other:0), explored cells 2142, failures 0
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,2 @@
driver done: 237 actions, 0 unexpected acks, final gseq 217
leakcheck: 218 gseq groups, subject msgs 217, tokens seen 3 others, removes 3, tiles 7424 (200:686 403:6738 other:0), explored cells 1114, failures 0
@@ -0,0 +1,57 @@
# mutation a: remove the +-RayEps rays
# run on a temp copy; diff orig -> mutated src/geometry.nim:
# 50,51d49
# < angles.add ang - RayEps
# < angles.add ang + RayEps
[Suite] visibility
[OK] open space is a circle
[OK] wall blocks
[OK] shared endpoint: no leak at the vertex
[OK] '<' apex: ray through the shared tip must not leak
[OK] every segment endpoint is a polygon vertex (lower and upper end inclusive)
/tmp/tmp.JzjWCOxzvp/w/tests/tgeometry.nim(65, 14): Check failed: sees(w, (0.0, 7.4), (100.0, -6.0))
/tmp/tmp.JzjWCOxzvp/w/tests/tgeometry.nim(69, 14): Check failed: sees(m, (0.0, -7.4), (100.0, 6.0))
/tmp/tmp.JzjWCOxzvp/w/tests/tgeometry.nim(73, 14): Check failed: sees(b, (0.0, -24.0), (200.0, 130.0))
[FAILED] rays nudged past a corner: area just beyond a wall end is visible
[OK] shared endpoint: closed corner of box has no crack
[OK] collinear walls act as one
[OK] collinear walls with a gap let light through
[OK] T-junction: no leak and correct shadow
[OK] pillar mid-room casts a shadow, sides visible
[OK] closed door blocks, open door passes
[OK] token exactly at wall endpoint
[OK] token at endpoint of free-standing wall sees along it
[OK] long thin corridor
[OK] wall endpoints behind the viewer: fan stays angularly ordered
[OK] radius clips
[Suite] moves
[OK] crossing blocked, parallel ok
[OK] grazing an endpoint is blocked
[OK] no leak through shared vertex
[OK] diagonal squeeze through corner vertex of L
[OK] moving along a collinear wall is blocked
[OK] doors
[OK] zero-length move
[Suite] cells
[OK] square polygon
[OK] tiny polygon inside one cell
[OK] polygon spanning a cell with no vertex in it
[OK] big polygon includes fully covered interior cells
[Suite] seed
[OK] every token in seed sees itself and is not walled in
[Suite] token clearance (r=20)
[OK] near pillar: circle overlapping blocked, clear ok
[OK] near closed door blocks, open door passes
[OK] 64px corridor and doorway passable on centerline
[OK] legacy overlap can escape, not stay overlapped
Error: execution of an external program failed: '/tmp/tmp.JzjWCOxzvp/w/tests/tgeometry'
# test exit=1
# NEW tests failed:
[FAILED] rays nudged past a corner: area just beyond a wall end is visible
@@ -0,0 +1,63 @@
# mutation b: upper segment end exclusive
# run on a temp copy; diff orig -> mutated src/geometry.nim:
# 27c27
# < if t > Eps and u >= -Eps and u <= 1 + Eps: t else: Inf
# ---
# > if t > Eps and u >= -Eps and u < 1 - Eps: t else: Inf
[Suite] visibility
[OK] open space is a circle
[OK] wall blocks
[OK] shared endpoint: no leak at the vertex
/tmp/tmp.JzjWCOxzvp/w/tests/tgeometry.nim(45, 59): Check failed: visibilityPolygon((0.0, 0.0), w, 500).hasVertex((100.0, 0.0))
/tmp/tmp.JzjWCOxzvp/w/tests/tgeometry.nim(46, 12): Check failed: not sees(w, (0.0, 0.0), (150.0, 0.0))
sees(w, (0.0, 0.0), (150.0, 0.0)) was true
/tmp/tmp.JzjWCOxzvp/w/tests/tgeometry.nim(47, 12): Check failed: not sees(w, (0.0, 0.0), (300.0, 0.0))
sees(w, (0.0, 0.0), (300.0, 0.0)) was true
[FAILED] '<' apex: ray through the shared tip must not leak
/tmp/tmp.JzjWCOxzvp/w/tests/tgeometry.nim(55, 24): Check failed: poly.hasVertex((80.0, 10.0))
/tmp/tmp.JzjWCOxzvp/w/tests/tgeometry.nim(58, 22): Check failed: pr.hasVertex((50.0, -30.0))
[FAILED] every segment endpoint is a polygon vertex (lower and upper end inclusive)
[OK] rays nudged past a corner: area just beyond a wall end is visible
[OK] shared endpoint: closed corner of box has no crack
[OK] collinear walls act as one
[OK] collinear walls with a gap let light through
[OK] T-junction: no leak and correct shadow
[OK] pillar mid-room casts a shadow, sides visible
[OK] closed door blocks, open door passes
[OK] token exactly at wall endpoint
[OK] token at endpoint of free-standing wall sees along it
[OK] long thin corridor
[OK] wall endpoints behind the viewer: fan stays angularly ordered
[OK] radius clips
[Suite] moves
[OK] crossing blocked, parallel ok
[OK] grazing an endpoint is blocked
[OK] no leak through shared vertex
[OK] diagonal squeeze through corner vertex of L
[OK] moving along a collinear wall is blocked
[OK] doors
[OK] zero-length move
[Suite] cells
[OK] square polygon
[OK] tiny polygon inside one cell
[OK] polygon spanning a cell with no vertex in it
[OK] big polygon includes fully covered interior cells
[Suite] seed
[OK] every token in seed sees itself and is not walled in
[Suite] token clearance (r=20)
[OK] near pillar: circle overlapping blocked, clear ok
[OK] near closed door blocks, open door passes
[OK] 64px corridor and doorway passable on centerline
[OK] legacy overlap can escape, not stay overlapped
Error: execution of an external program failed: '/tmp/tmp.JzjWCOxzvp/w/tests/tgeometry'
# test exit=1
# NEW tests failed:
[FAILED] '<' apex: ray through the shared tip must not leak
[FAILED] every segment endpoint is a polygon vertex (lower and upper end inclusive)
@@ -0,0 +1,63 @@
# mutation c: lower segment end exclusive
# run on a temp copy; diff orig -> mutated src/geometry.nim:
# 27c27
# < if t > Eps and u >= -Eps and u <= 1 + Eps: t else: Inf
# ---
# > if t > Eps and u > Eps and u <= 1 + Eps: t else: Inf
[Suite] visibility
[OK] open space is a circle
[OK] wall blocks
[OK] shared endpoint: no leak at the vertex
/tmp/tmp.JzjWCOxzvp/w/tests/tgeometry.nim(45, 59): Check failed: visibilityPolygon((0.0, 0.0), w, 500).hasVertex((100.0, 0.0))
/tmp/tmp.JzjWCOxzvp/w/tests/tgeometry.nim(46, 12): Check failed: not sees(w, (0.0, 0.0), (150.0, 0.0))
sees(w, (0.0, 0.0), (150.0, 0.0)) was true
/tmp/tmp.JzjWCOxzvp/w/tests/tgeometry.nim(47, 12): Check failed: not sees(w, (0.0, 0.0), (300.0, 0.0))
sees(w, (0.0, 0.0), (300.0, 0.0)) was true
[FAILED] '<' apex: ray through the shared tip must not leak
/tmp/tmp.JzjWCOxzvp/w/tests/tgeometry.nim(54, 24): Check failed: poly.hasVertex((50.0, -30.0))
/tmp/tmp.JzjWCOxzvp/w/tests/tgeometry.nim(59, 22): Check failed: pr.hasVertex((80.0, 10.0))
[FAILED] every segment endpoint is a polygon vertex (lower and upper end inclusive)
[OK] rays nudged past a corner: area just beyond a wall end is visible
[OK] shared endpoint: closed corner of box has no crack
[OK] collinear walls act as one
[OK] collinear walls with a gap let light through
[OK] T-junction: no leak and correct shadow
[OK] pillar mid-room casts a shadow, sides visible
[OK] closed door blocks, open door passes
[OK] token exactly at wall endpoint
[OK] token at endpoint of free-standing wall sees along it
[OK] long thin corridor
[OK] wall endpoints behind the viewer: fan stays angularly ordered
[OK] radius clips
[Suite] moves
[OK] crossing blocked, parallel ok
[OK] grazing an endpoint is blocked
[OK] no leak through shared vertex
[OK] diagonal squeeze through corner vertex of L
[OK] moving along a collinear wall is blocked
[OK] doors
[OK] zero-length move
[Suite] cells
[OK] square polygon
[OK] tiny polygon inside one cell
[OK] polygon spanning a cell with no vertex in it
[OK] big polygon includes fully covered interior cells
[Suite] seed
[OK] every token in seed sees itself and is not walled in
[Suite] token clearance (r=20)
[OK] near pillar: circle overlapping blocked, clear ok
[OK] near closed door blocks, open door passes
[OK] 64px corridor and doorway passable on centerline
[OK] legacy overlap can escape, not stay overlapped
Error: execution of an external program failed: '/tmp/tmp.JzjWCOxzvp/w/tests/tgeometry'
# test exit=1
# NEW tests failed:
[FAILED] '<' apex: ray through the shared tip must not leak
[FAILED] every segment endpoint is a polygon vertex (lower and upper end inclusive)
@@ -0,0 +1,5 @@
Info: Running script "mutation" on /home/davide/Projects/GDR/FFF_vtt/prototype-server-vision
control: exit=0 newfailed=0
a: exit=1 newfailed=1
b: exit=1 newfailed=2
c: exit=1 newfailed=2
@@ -0,0 +1,45 @@
Info: Running script "nimble" on /home/davide/Projects/GDR/FFF_vtt/prototype-server-vision
Info: Ensuring packages are installed.
Info: Using the environment variable: NIMBLE_DIR='/home/davide/Projects/GDR/FFF_vtt/prototype-server-vision/.devbox/nimble'
Info: using /nix/store/0cbdz34lsakfirycixckf6ypsd8hazhg-x86_64-unknown-linux-gnu-nim-wrapper-2.2.12/bin/nim for compilation
Compiling /home/davide/Projects/GDR/FFF_vtt/prototype-server-vision/tests/tgeometry (from package servervision) using c backend
Nim Output [Suite] visibility
... [OK] open space is a circle
... [OK] wall blocks
... [OK] shared endpoint: no leak at the vertex
... [OK] '<' apex: ray through the shared tip must not leak
... [OK] every segment endpoint is a polygon vertex (lower and upper end inclusive)
... [OK] rays nudged past a corner: area just beyond a wall end is visible
... [OK] shared endpoint: closed corner of box has no crack
... [OK] collinear walls act as one
... [OK] collinear walls with a gap let light through
... [OK] T-junction: no leak and correct shadow
... [OK] pillar mid-room casts a shadow, sides visible
... [OK] closed door blocks, open door passes
... [OK] token exactly at wall endpoint
... [OK] token at endpoint of free-standing wall sees along it
... [OK] long thin corridor
... [OK] wall endpoints behind the viewer: fan stays angularly ordered
... [OK] radius clips
... [Suite] moves
... [OK] crossing blocked, parallel ok
... [OK] grazing an endpoint is blocked
... [OK] no leak through shared vertex
... [OK] diagonal squeeze through corner vertex of L
... [OK] moving along a collinear wall is blocked
... [OK] doors
... [OK] zero-length move
... [Suite] cells
... [OK] square polygon
... [OK] tiny polygon inside one cell
... [OK] polygon spanning a cell with no vertex in it
... [OK] big polygon includes fully covered interior cells
... [Suite] seed
... [OK] every token in seed sees itself and is not walled in
... [Suite] token clearance (r=20)
... [OK] near pillar: circle overlapping blocked, clear ok
... [OK] near closed door blocks, open door passes
... [OK] 64px corridor and doorway passable on centerline
... [OK] legacy overlap can escape, not stay overlapped
Success: Execution finished
Success: All tests passed
+20
View File
@@ -0,0 +1,20 @@
Info: Running script "smoke" on /home/davide/Projects/GDR/FFF_vtt/prototype-server-vision
PASS join A: 302 + HttpOnly SameSite cookie
PASS bad secret 403
PASS ws without cookie refused
PASS ws bad cookie refused
player A msgs: hello,vision,explored,token
PASS hello first, player owns A
PASS no walls/door to player
PASS vision + explored sent
PASS only own token visible
PASS explored tile 200, 767 bytes
PASS unexplored tile 403
PASS tile without cookie 403
PASS /_tiles not reachable directly
PASS path trick rejected
PASS GM gets any tile
PASS steal/door/garbage -> 3 errors
PASS move through wall rejected
PASS legal move acked
PASS GM: walls, all 8 tokens, no explored
@@ -0,0 +1,18 @@
STATS bytes/delivery door gm: n=56 avg=44.7 worst=46.
STATS bytes/delivery move-monster A: n=900 avg=147.5 worst=153.
STATS bytes/delivery move-monster B: n=544 avg=146.5 worst=154.
STATS bytes/delivery move-monster gm: n=10370 avg=243.2 worst=252.
STATS bytes/delivery move-player A: n=1691 avg=3746.9 worst=4959.
STATS bytes/delivery move-player B: n=1714 avg=2950.4 worst=4376.
STATS bytes/delivery move-player gm: n=3404 avg=144.7 worst=149.
STATS timing_ms lock_wait: n=13831 avg=0.162 p50=0.000 p99=2.567 worst=71.704
STATS timing_ms send: n=13831 avg=0.060 p50=0.040 p99=0.177 worst=0.467
STATS timing_ms sqlite: n=13831 avg=0.616 p50=0.604 p99=1.224 worst=62.928
STATS timing_ms total: n=13831 avg=1.143 p50=0.762 p99=4.450 worst=72.870
STATS timing_ms vision: n=13831 avg=0.242 p50=0.000 p99=2.875 worst=4.230
STATS vision_ms door: n=56 avg=0.207 worst=0.346
STATS vision_ms move-monster: n=10370 avg=0.000 worst=0.050
STATS vision_ms move-player: n=3405 avg=0.981 worst=4.230
SLOW gseq=136 move-player total=63.8 lock_wait=0.0 vision=0.7 sqlite=62.9 send=0.1 other=0.1
SLOW gseq=138 move-monster total=56.6 lock_wait=55.9 vision=0.0 sqlite=0.6 send=0.0 other=0.0
SLOW gseq=152 move-player total=72.9 lock_wait=71.7 vision=0.4 sqlite=0.7 send=0.1 other=0.0
@@ -0,0 +1,6 @@
gm: sent 10391 moves (169/s), acks 10391 (nack 21), recv 24222 msgs 2953 KiB, final gseq 13831, tokens in view 8
A: sent 1704 moves (28/s), acks 1704 (nack 13), recv 6125 msgs 6324 KiB, final gseq 13826, tokens in view 2
B: sent 1714 moves (28/s), acks 1714 (nack 0), recv 5792 msgs 5022 KiB, final gseq 13829, tokens in view 1
latency intent->ack (sender): n=13809 avg=1.84ms p95=3.53ms p99=5.17ms worst=73.08ms
latency intent->arrival at other clients: n=4809 avg=2.43ms p95=4.54ms p99=5.92ms worst=73.22ms
concurrency: PASS
@@ -0,0 +1,15 @@
STATS bytes/delivery door gm: n=60 avg=44.7 worst=46.
STATS bytes/delivery move-monster A: n=907 avg=147.0 worst=155.
STATS bytes/delivery move-monster B: n=862 avg=146.8 worst=154.
STATS bytes/delivery move-monster gm: n=10257 avg=242.7 worst=252.
STATS bytes/delivery move-player A: n=1724 avg=3812.4 worst=4998.
STATS bytes/delivery move-player B: n=1710 avg=3252.1 worst=4567.
STATS bytes/delivery move-player gm: n=3432 avg=144.5 worst=149.
STATS timing_ms lock_wait: n=13751 avg=0.177 p50=0.000 p99=3.061 worst=11.928
STATS timing_ms send: n=13751 avg=0.060 p50=0.040 p99=0.185 worst=0.570
STATS timing_ms sqlite: n=13751 avg=0.592 p50=0.591 p99=1.168 worst=21.248
STATS timing_ms total: n=13751 avg=1.207 p50=0.753 p99=4.874 worst=21.348
STATS timing_ms vision: n=13751 avg=0.317 p50=0.000 p99=3.258 worst=4.943
STATS vision_ms door: n=60 avg=0.202 worst=0.315
STATS vision_ms move-monster: n=10257 avg=0.000 worst=0.017
STATS vision_ms move-player: n=3434 avg=1.267 worst=4.943
@@ -0,0 +1,6 @@
gm: sent 10338 moves (165/s), acks 10338 (nack 81), recv 24090 msgs 2931 KiB, final gseq 13751, tokens in view 8
A: sent 1728 moves (28/s), acks 1728 (nack 4), recv 6241 msgs 6554 KiB, final gseq 13748, tokens in view 2
B: sent 1710 moves (27/s), acks 1710 (nack 0), recv 6158 msgs 5560 KiB, final gseq 13749, tokens in view 2
latency intent->ack (sender): n=13776 avg=1.84ms p95=4.03ms p99=5.48ms worst=21.83ms
latency intent->arrival at other clients: n=5145 avg=2.43ms p95=4.84ms p99=6.26ms worst=15.69ms
concurrency: PASS
@@ -0,0 +1,15 @@
STATS bytes/delivery door gm: n=56 avg=44.8 worst=46.
STATS bytes/delivery move-monster A: n=901 avg=148.9 worst=155.
STATS bytes/delivery move-monster B: n=1125 avg=146.8 worst=154.
STATS bytes/delivery move-monster gm: n=10370 avg=243.1 worst=252.
STATS bytes/delivery move-player A: n=1721 avg=3563.7 worst=4934.
STATS bytes/delivery move-player B: n=1737 avg=3242.3 worst=4524.
STATS bytes/delivery move-player gm: n=3456 avg=144.9 worst=149.
STATS timing_ms lock_wait: n=13884 avg=0.144 p50=0.000 p99=2.448 worst=13.060
STATS timing_ms send: n=13884 avg=0.061 p50=0.042 p99=0.179 worst=0.334
STATS timing_ms sqlite: n=13884 avg=0.609 p50=0.604 p99=1.192 worst=9.628
STATS timing_ms total: n=13884 avg=1.133 p50=0.758 p99=3.934 worst=14.178
STATS timing_ms vision: n=13884 avg=0.256 p50=0.000 p99=2.257 worst=3.514
STATS vision_ms door: n=56 avg=0.229 worst=0.699
STATS vision_ms move-monster: n=10370 avg=0.000 worst=0.069
STATS vision_ms move-player: n=3458 avg=1.023 worst=3.514
@@ -0,0 +1,6 @@
gm: sent 10385 moves (167/s), acks 10385 (nack 15), recv 24270 msgs 2960 KiB, final gseq 13884, tokens in view 8
A: sent 1723 moves (28/s), acks 1723 (nack 2), recv 6173 msgs 6126 KiB, final gseq 13881, tokens in view 2
B: sent 1737 moves (28/s), acks 1737 (nack 0), recv 6513 msgs 5666 KiB, final gseq 13874, tokens in view 1
latency intent->ack (sender): n=13845 avg=1.78ms p95=3.46ms p99=4.51ms worst=18.14ms
latency intent->arrival at other clients: n=5425 avg=2.26ms p95=3.98ms p99=4.97ms worst=14.13ms
concurrency: PASS
@@ -0,0 +1,15 @@
STATS bytes/delivery door gm: n=58 avg=44.9 worst=46.
STATS bytes/delivery move-monster A: n=754 avg=146.4 worst=154.
STATS bytes/delivery move-monster B: n=400 avg=137.6 worst=155.
STATS bytes/delivery move-monster gm: n=10266 avg=242.8 worst=252.
STATS bytes/delivery move-player A: n=1707 avg=3854.9 worst=5028.
STATS bytes/delivery move-player B: n=1710 avg=3394.4 worst=4724.
STATS bytes/delivery move-player gm: n=3409 avg=144.5 worst=149.
STATS timing_ms lock_wait: n=13741 avg=0.148 p50=0.000 p99=2.687 worst=16.594
STATS timing_ms send: n=13741 avg=0.063 p50=0.040 p99=0.199 worst=0.394
STATS timing_ms sqlite: n=13741 avg=0.167 p50=0.137 p99=0.314 worst=17.739
STATS timing_ms total: n=13741 avg=0.792 p50=0.288 p99=4.203 worst=21.053
STATS timing_ms vision: n=13741 avg=0.351 p50=0.000 p99=3.172 worst=6.325
STATS vision_ms door: n=58 avg=0.236 worst=0.344
STATS vision_ms move-monster: n=10266 avg=0.000 worst=0.081
STATS vision_ms move-player: n=3417 avg=1.405 worst=6.325
@@ -0,0 +1,6 @@
gm: sent 10281 moves (164/s), acks 10281 (nack 15), recv 24018 msgs 2925 KiB, final gseq 13741, tokens in view 8
A: sent 1715 moves (27/s), acks 1715 (nack 8), recv 6041 msgs 6540 KiB, final gseq 13738, tokens in view 1
B: sent 1710 moves (27/s), acks 1710 (nack 0), recv 5687 msgs 5727 KiB, final gseq 13737, tokens in view 1
latency intent->ack (sender): n=13706 avg=1.51ms p95=3.48ms p99=5.09ms worst=21.33ms
latency intent->arrival at other clients: n=4490 avg=2.33ms p95=4.37ms p99=5.79ms worst=21.36ms
concurrency: PASS
@@ -0,0 +1,15 @@
STATS bytes/delivery door gm: n=66 avg=44.7 worst=46.
STATS bytes/delivery move-monster A: n=649 avg=146.1 worst=153.
STATS bytes/delivery move-monster B: n=1210 avg=147.0 worst=154.
STATS bytes/delivery move-monster gm: n=10238 avg=242.6 worst=252.
STATS bytes/delivery move-player A: n=1691 avg=3626.7 worst=4956.
STATS bytes/delivery move-player B: n=1703 avg=3336.6 worst=4459.
STATS bytes/delivery move-player gm: n=3394 avg=144.9 worst=149.
STATS timing_ms lock_wait: n=13698 avg=0.123 p50=0.000 p99=2.178 worst=18.542
STATS timing_ms send: n=13698 avg=0.062 p50=0.040 p99=0.185 worst=0.480
STATS timing_ms sqlite: n=13698 avg=0.170 p50=0.138 p99=0.315 worst=18.178
STATS timing_ms total: n=13698 avg=0.715 p50=0.287 p99=3.432 worst=20.612
STATS timing_ms vision: n=13698 avg=0.295 p50=0.000 p99=2.385 worst=4.037
STATS vision_ms door: n=66 avg=0.222 worst=0.345
STATS vision_ms move-monster: n=10238 avg=0.000 worst=0.029
STATS vision_ms move-player: n=3394 avg=1.187 worst=4.037
@@ -0,0 +1,6 @@
gm: sent 10281 moves (166/s), acks 10281 (nack 43), recv 23979 msgs 2918 KiB, final gseq 13698, tokens in view 8
A: sent 1714 moves (28/s), acks 1714 (nack 23), recv 5871 msgs 6089 KiB, final gseq 13693, tokens in view 2
B: sent 1703 moves (28/s), acks 1703 (nack 0), recv 6444 msgs 5728 KiB, final gseq 13694, tokens in view 2
latency intent->ack (sender): n=13698 avg=1.43ms p95=3.04ms p99=4.28ms worst=20.83ms
latency intent->arrival at other clients: n=5194 avg=2.03ms p95=3.61ms p99=4.93ms worst=20.95ms
concurrency: PASS
@@ -0,0 +1,15 @@
STATS bytes/delivery door gm: n=64 avg=44.8 worst=46.
STATS bytes/delivery move-monster A: n=384 avg=142.5 worst=154.
STATS bytes/delivery move-monster B: n=1018 avg=148.1 worst=154.
STATS bytes/delivery move-monster gm: n=10300 avg=243.1 worst=252.
STATS bytes/delivery move-player A: n=1708 avg=3746.7 worst=4879.
STATS bytes/delivery move-player B: n=1725 avg=3242.8 worst=4766.
STATS bytes/delivery move-player gm: n=3429 avg=144.6 worst=149.
STATS timing_ms lock_wait: n=13797 avg=0.126 p50=0.000 p99=2.384 worst=18.662
STATS timing_ms send: n=13797 avg=0.061 p50=0.039 p99=0.185 worst=0.369
STATS timing_ms sqlite: n=13797 avg=0.169 p50=0.136 p99=0.312 worst=18.797
STATS timing_ms total: n=13797 avg=0.724 p50=0.282 p99=3.789 worst=19.906
STATS timing_ms vision: n=13797 avg=0.305 p50=0.000 p99=2.841 worst=4.198
STATS vision_ms door: n=64 avg=0.217 worst=0.304
STATS vision_ms move-monster: n=10300 avg=0.000 worst=0.039
STATS vision_ms move-player: n=3433 avg=1.221 worst=4.198
@@ -0,0 +1,6 @@
gm: sent 10311 moves (166/s), acks 10311 (nack 11), recv 24109 msgs 2939 KiB, final gseq 13797, tokens in view 8
A: sent 1715 moves (28/s), acks 1715 (nack 7), recv 5671 msgs 6309 KiB, final gseq 13793, tokens in view 2
B: sent 1725 moves (28/s), acks 1725 (nack 0), recv 6322 msgs 5615 KiB, final gseq 13792, tokens in view 2
latency intent->ack (sender): n=13751 avg=1.43ms p95=3.20ms p99=4.49ms worst=20.95ms
latency intent->arrival at other clients: n=4774 avg=2.10ms p95=3.91ms p99=4.78ms worst=21.13ms
concurrency: PASS
@@ -0,0 +1,34 @@
# 583 ms spike investigation (results/spike/original-60s.log: worst intent->ack 583.13 ms, avg 6.33 ms)
HISTORICAL: measured 2026-11-07 on AMD Ryzen 7 7840U, 60.6 GiB, NixOS 26.05, power-save (capped), at commits b202eb6 (baseline) and a337cec (fixed). Not the final-run data (see README).
Setup: DUR=60, isolated stack (run/test, :18088/:19000), CPU powersave governor untouched, runs strictly sequential.
Server now logs per mutation: lock_wait / vision / sqlite / send / total, `SLOW` line when total > `SLOW_MS` (default 50), percentiles in `STATS timing_ms` (end of run + every 5000 mutations).
Client p99 added to `tools/concurrency.mjs`. Logs: `results/spike/base{1,2,3}[-server].log` (baseline), `results/spike/fixed{1,2,3}[-server].log` (after fix).
## Runs (client intent->ack, ms | server total per mutation, ms)
| run | avg | p99 | worst | srv avg | srv p99 | srv worst | srv sqlite avg / worst | srv lock_wait worst |
|---|---|---|---|---|---|---|---|---|
| original (no timing) | 6.33 | n/a | 583.13 | - | - | - | - | - |
| base 1 | 1.84 | 5.17 | 73.08 | 1.143 | 4.450 | 72.870 | 0.616 / 62.928 | 71.704 |
| base 2 | 1.84 | 5.48 | 21.83 | 1.207 | 4.874 | 21.348 | 0.592 / 21.248 | 11.928 |
| base 3 | 1.78 | 4.51 | 18.14 | 1.133 | 3.934 | 14.178 | 0.609 / 9.628 | 13.060 |
| fixed 1 | 1.51 | 5.09 | 21.33 | 0.792 | 4.203 | 21.053 | 0.167 / 17.739 | 16.594 |
| fixed 2 | 1.43 | 4.28 | 20.83 | 0.715 | 3.432 | 20.612 | 0.170 / 18.178 | 18.542 |
| fixed 3 | 1.43 | 4.49 | 20.95 | 0.724 | 3.789 | 19.906 | 0.169 / 18.797 | 18.662 |
(base runs' sqlite worst: run 2 file shows 21.2, run 3 file 9.6; table taken per file.)
## Slowest mutations (baseline; three exceeded 50 ms, all in base run 1 (gseq 136, 138, 152), `SLOW` lines in `spike/base1-server.log`; none in base 2/3 or fixed runs)
- run1 gseq=136 move-player total=63.8: sqlite=62.9 (COMMIT), vision 0.7, send 0.1, lock_wait 0.
- run1 gseq=138 move-monster total=56.6: lock_wait=55.9 (queued behind gseq=136's commit).
- run1 gseq=152 move-player total=72.9: lock_wait=71.7 (queued behind another stalled holder), rest < 1.
- run2/3 worst 21 / 14 ms: also sqlite commit (21.2 / 9.6), others queue behind it as lock_wait (12 / 13).
Vision (worst 4-5 ms) and send enqueue (worst < 0.6 ms) never matter. The global lock turns every stalled COMMIT into lock_wait for the mutations queued behind it.
## Verdict
- 583 ms does NOT reproduce: worst 73 / 22 / 18 ms over 3 runs, avg 1.8 ms vs 6.33 ms in the original run (original run was ~3.5x slower on average too, i.e. the whole run was degraded, not one event; the original server had no timing, so its breakdown is unrecoverable). Most likely host-wide (power cap / scheduler / disk) or node harness stall at that time; client-side not excluded: the 583.13 (ack) and 583.22 (other clients) worst are the same event seen from the same node process, which fits either a server/nginx stall or a node event-loop/GC pause. Not proven either way.
- What the breakdown does show: server-side tail (>10 ms) is the SQLite COMMIT (fsync, synchronous=FULL in WAL) + lock queueing behind it. Compute (vision) and send are not the tail.
- Fix: `PRAGMA synchronous=NORMAL` (WAL), 1 line in `src/server.nim`. Effect (before -> after, mean of 3 runs): sqlite avg 0.60 -> 0.17 ms, p50 0.60 -> 0.14 ms, server total avg 1.16 -> 0.74 ms, client avg 1.82 -> 1.46 ms. Tail is NOT fixed: server worst stays ~20 ms (sqlite worst ~18 ms still, now likely WAL auto-checkpoint / OS scheduling rather than per-commit fsync), client p99 ~4.6-5.1 ms unchanged within noise. The 73 ms outlier of base run 1 did not recur in fixed runs, but n=3, not evidence.
- Tradeoff: with synchronous=NORMAL in WAL, a commit is not fsynced; process crash/SIGKILL loses nothing (restart test passes), OS crash / power loss may drop the last few committed mutations (never corrupts). Ack-before-durable on power loss. Not done: moving persist out of the lock (would break gseq order == send order / ack-after-commit).
- After the change leaktest, faulttest, restart re-run: all PASS (`results/spike/postfix-{leaktest,faulttest,restart}.log`; leak-A/B logs byte-identical to committed).
@@ -0,0 +1,10 @@
STATS bytes/delivery door gm: n=60 avg=44.8 worst=46.
STATS bytes/delivery move-monster A: n=747 avg=145.0 worst=153.
STATS bytes/delivery move-monster B: n=814 avg=147.5 worst=154.
STATS bytes/delivery move-monster gm: n=10300 avg=243.0 worst=252.
STATS bytes/delivery move-player A: n=1711 avg=3678.6 worst=4927.
STATS bytes/delivery move-player B: n=1710 avg=3180.6 worst=4851.
STATS bytes/delivery move-player gm: n=3417 avg=144.7 worst=149.
STATS vision_ms door: n=60 avg=0.192 worst=0.492
STATS vision_ms move-monster: n=10300 avg=0.000 worst=0.025
STATS vision_ms move-player: n=3421 avg=1.159 worst=14.023
@@ -0,0 +1,6 @@
gm: sent 10364 moves (167/s), acks 10364 (nack 64), recv 24144 msgs 2940 KiB, final gseq 13781, tokens in view 8
A: sent 1728 moves (28/s), acks 1728 (nack 17), recv 6039 msgs 6259 KiB, final gseq 13777, tokens in view 2
B: sent 1710 moves (28/s), acks 1710 (nack 0), recv 6079 msgs 5434 KiB, final gseq 13772, tokens in view 1
latency intent->ack (sender): n=13802 avg=6.33ms p95=11.58ms worst=583.13ms
latency intent->arrival at other clients: n=4917 avg=7.22ms p95=12.89ms worst=583.22ms
concurrency: PASS
@@ -0,0 +1,11 @@
Info: Running script "faulttest" on /home/davide/Projects/GDR/FFF_vtt/prototype-server-vision
PASS run/test/server-clean has no fault hook
PASS fault hidden caught as: HIDDEN_TOKEN
PASS fault walls caught as: WALLDATA
PASS fault tile caught as: TILE
PASS fault withhold caught as: WITHHELD
PASS fault other-vision caught as: OTHER_PLAYER OWN_VIEW
PASS fault other-explored caught as: EXPLORED OTHER_PLAYER
PASS fault other-owner caught as: OTHER_PLAYER
PASS fault noremove caught as: NO_REMOVE
PASS clean build passes
@@ -0,0 +1,7 @@
Info: Running script "leaktest" on /home/davide/Projects/GDR/FFF_vtt/prototype-server-vision
== SUBJECT=A
driver done: 237 actions, 0 unexpected acks, final gseq 217
leakcheck: 218 gseq groups, subject msgs 467, tokens seen 4 others, removes 4, tiles 9984 (200:1709 403:8275 other:0), explored cells 2142, failures 0
== SUBJECT=B
driver done: 237 actions, 0 unexpected acks, final gseq 217
leakcheck: 218 gseq groups, subject msgs 217, tokens seen 3 others, removes 3, tiles 7424 (200:686 403:6738 other:0), explored cells 1114, failures 0
@@ -0,0 +1,28 @@
Info: Running script "restart" on /home/davide/Projects/GDR/FFF_vtt/prototype-server-vision
PASS move A -> 400,800
PASS move A -> 800,800
PASS move A -> 800,640
PASS move A -> 1000,640
PASS move A -> 1510,640
PASS move B -> 700,2300
PASS move M1 -> 900,640
PASS move M2 -> 2200,300
PASS move A -> 1700,640
PASS cycle1: invite secrets identical
PASS cycle1: gm state identical after SIGTERM restart
PASS cycle1: A state identical after SIGTERM restart
PASS cycle1: B state identical after SIGTERM restart
PASS A explored new area (292 -> 1145)
PASS cycle1: token positions are the moved ones
PASS cycle1: door states are the toggled ones
PASS cycle1: doors differ from initial (test is not vacuous)
PASS move A -> 1900,640
PASS move B -> 1000,2300
PASS move M1 -> 1200,640
PASS cycle2: invite secrets identical
PASS cycle2: gm state identical after SIGKILL restart
PASS cycle2: A state identical after SIGKILL restart
PASS cycle2: B state identical after SIGKILL restart
PASS cycle2: A explored more before kill -9
PASS cycle2: B explored more before kill -9
restart: PASS
@@ -0,0 +1,11 @@
version = "0.1.0"
author = "proto"
description = "Throwaway: server-authoritative vision prototype"
license = "MIT"
srcDir = "src"
bin = @["server"]
requires "nim >= 2.0"
# no tags upstream: pin exact commit
requires "mummy#01deb1ff694988635c7bf0f24f6088a0bdf6db5d"
requires "db_connector"
+116
View File
@@ -0,0 +1,116 @@
## 2D vision geometry. Pure, no deps.
import std/[math, algorithm]
type
Vec* = tuple[x, y: float]
Wall* = object
a*, b*: Vec
door*, open*: bool
const
Eps = 1e-9 # geometric tolerance (px)
RayEps = 1e-4 # angular nudge past endpoints (rad)
proc blocks*(w: Wall): bool = not (w.door and w.open)
proc cross(a, b: Vec): float = a.x * b.y - a.y * b.x
proc `-`(a, b: Vec): Vec = (a.x - b.x, a.y - b.y)
proc rayHit(o, d: Vec, a, b: Vec): float =
## smallest t > Eps where o + t*d hits segment ab (end-inclusive), else Inf
let e = b - a
let den = cross(d, e)
if abs(den) < 1e-12: return Inf # parallel/collinear: grazing, other rays cover it
let ao = a - o
let t = cross(ao, e) / den
let u = cross(ao, d) / den
if t > Eps and u >= -Eps and u <= 1 + Eps: t else: Inf
proc visibilityPolygon*(o: Vec, walls: openArray[Wall], radius: float,
circleSegs = 64): seq[Vec] =
## CCW polygon of what `o` sees, bounded by an inscribed circleSegs-gon of `radius`.
var segs: seq[(Vec, Vec)]
var angles: seq[float]
for i in 0 ..< circleSegs:
let a0 = 2 * PI * i.float / circleSegs.float
let a1 = 2 * PI * (i + 1).float / circleSegs.float
segs.add(((o.x + radius * cos a0, o.y + radius * sin a0),
(o.x + radius * cos a1, o.y + radius * sin a1)))
angles.add arctan2(sin a0, cos a0) # same (-pi,pi] range as the wall angles, else the sort scrambles the fan
for w in walls:
if not w.blocks: continue
# shortcut: walls beyond the circle are only culled by ray clipping, O(rays*walls); upgrade: spatial grid
if max(w.a.x, w.b.x) < o.x - radius or min(w.a.x, w.b.x) > o.x + radius or
max(w.a.y, w.b.y) < o.y - radius or min(w.a.y, w.b.y) > o.y + radius: continue
segs.add((w.a, w.b))
for p in [w.a, w.b]:
if abs(p.x - o.x) < Eps and abs(p.y - o.y) < Eps: continue # token on endpoint
let ang = arctan2(p.y - o.y, p.x - o.x)
angles.add ang
angles.add ang - RayEps
angles.add ang + RayEps
angles.sort
for ang in angles:
let d: Vec = (cos ang, sin ang)
var best = Inf
for s in segs: best = min(best, rayHit(o, d, s[0], s[1]))
if best < Inf: result.add((o.x + d.x * best, o.y + d.y * best))
proc segsCross(p, q, a, b: Vec): bool =
## inclusive segment intersection (touching and collinear overlap count)
proc orient(a, b, c: Vec): int =
let v = cross(b - a, c - a)
if v > Eps: 1 elif v < -Eps: -1 else: 0
proc onSeg(a, b, c: Vec): bool = # c collinear with ab: within bbox?
c.x >= min(a.x, b.x) - Eps and c.x <= max(a.x, b.x) + Eps and
c.y >= min(a.y, b.y) - Eps and c.y <= max(a.y, b.y) + Eps
let o1 = orient(p, q, a); let o2 = orient(p, q, b)
let o3 = orient(a, b, p); let o4 = orient(a, b, q)
if o1 != o2 and o3 != o4: return true
(o1 == 0 and onSeg(p, q, a)) or (o2 == 0 and onSeg(p, q, b)) or
(o3 == 0 and onSeg(a, b, p)) or (o4 == 0 and onSeg(a, b, q))
proc segDist(p, a, b: Vec): float =
let e = b - a
let l2 = e.x * e.x + e.y * e.y
let t = if l2 < Eps: 0.0 else: clamp(((p.x - a.x) * e.x + (p.y - a.y) * e.y) / l2, 0.0, 1.0)
hypot(p.x - a.x - t * e.x, p.y - a.y - t * e.y)
proc moveBlocked*(walls: openArray[Wall], a, b: Vec, r = 0.0): bool =
## true if travelling a->b touches any blocking wall (touching counts: no leaking through shared vertices)
## or the token circle (radius r) at b overlaps one. Only b is checked for clearance, so a token
## already overlapping (legacy position, door closed on it) can still leave to a clear spot.
## shortcut: a token standing exactly on a wall can't move off it; server must keep tokens off walls.
for w in walls:
if w.blocks and (segsCross(a, b, w.a, w.b) or segDist(b, w.a, w.b) < r): return true
proc inside*(poly: openArray[Vec], p: Vec): bool =
## even-odd point-in-polygon (boundary ambiguous)
var j = poly.len - 1
for i in 0 ..< poly.len:
if (poly[i].y > p.y) != (poly[j].y > p.y) and
p.x < (poly[j].x - poly[i].x) * (p.y - poly[i].y) / (poly[j].y - poly[i].y) + poly[i].x:
result = not result
j = i
proc cellsTouched*(poly: openArray[Vec], cell: float): seq[(int, int)] =
## grid cells (ix, iy) overlapped by the polygon (area overlap, boundary touch included), sorted.
if poly.len < 3: return
var x0, y0 = Inf
var x1, y1 = -Inf
for p in poly:
x0 = min(x0, p.x); x1 = max(x1, p.x); y0 = min(y0, p.y); y1 = max(y1, p.y)
for iy in int(floor(y0 / cell)) .. int(floor(y1 / cell)):
for ix in int(floor(x0 / cell)) .. int(floor(x1 / cell)):
let (cx0, cy0, cx1, cy1) = (ix.float * cell, iy.float * cell, (ix + 1).float * cell, (iy + 1).float * cell)
let c = [(cx0, cy0), (cx1, cy0), (cx1, cy1), (cx0, cy1)]
# no edge crosses => cell wholly inside poly (a corner decides) or poly wholly inside cell (a vertex decides) or disjoint
var hit = inside(poly, c[0]) or
(poly[0].x >= cx0 and poly[0].x <= cx1 and poly[0].y >= cy0 and poly[0].y <= cy1)
if not hit:
for i in 0 ..< poly.len:
let p = poly[i]; let q = poly[(i + 1) mod poly.len]
for k in 0 .. 3:
if segsCross(p, q, c[k], c[(k + 1) mod 4]): hit = true; break
if hit: break
if hit: result.add (ix, iy)
+366
View File
@@ -0,0 +1,366 @@
## Server-authoritative vision. Players are untrusted: only what is in their vision reaches them.
## One global Lock: validate -> mutate -> recompute vision -> persist -> send, so gseq order == send order.
import std/[json, tables, sets, locks, os, monotimes, times, strutils, sysrand, strformat, algorithm]
import mummy, db_connector/db_sqlite
import geometry
type
Tok = object
id, name, kind: string
pos: Vec
gmOnly: bool
Role = ref object # per player: shared by all that player's connections
polys: seq[seq[Vec]]
ver: int # bumped when polys change
explored: HashSet[int]
fresh: seq[int] # cells added by the current mutation
Conn = ref object
ws: WebSocket
role: string # "gm" | "A" | "B"
ver: int
known: Table[string, Vec] # tokens this client currently has
bytes: int
Ev = object # what the current mutation was
door: int
doorOpen: bool
moved, by: string
reqId: int
Stat = object
n: int
sum, worst: float
# nginx public port; 8080 per spec, PORT overrides when taken
let origin = "http://localhost:" & getEnv("PORT", "8080")
# RUN_DIR: db/invites dir (tools/withserver.sh sets run/test); BACKEND_PORT: mummy listen port (nginx proxies to it)
let runDir = getEnv("RUN_DIR", "run")
let backendPort = parseInt(getEnv("BACKEND_PORT", "9000"))
var
lk: Lock
db: DbConn
walls: seq[Wall] # index == wall id
toks: seq[Tok]
worldW, worldH, tileSize, cell, cw: int
radius, tokRadius: float
roles: Table[string, Role]
secrets: Table[string, string] # secret -> "gm"|"A"|"B"
conns: Table[string, Conn]
gseq: int
vstat, bstat: Table[string, Stat]
nMut: int
# per-mutation timing (ms), all set under lk: tLock = lock acquired, tSql = sqlite phase, tSend = send phase start
lockWaitMs, sqlMs: float
tLock, tSend: MonoTime
tm: array[5, seq[float]] # wait, vision, sql, send, total; one entry per mutation
let slowMs = parseFloat(getEnv("SLOW_MS", "50")) # mutations over this get a SLOW line with the breakdown
const tmNames = ["lock_wait", "vision", "sqlite", "send", "total"]
proc msSince(t: MonoTime): float = (getMonoTime() - t).inNanoseconds.float / 1e6
lk.initLock
# TEST BUILD ONLY (-d:leakfault, tools/faulttest.sh): deliberate leaks picked at run time by env LEAK_FAULT.
# Without the define fault() is a constant false and neither this code nor the env name is compiled in.
when defined(leakfault):
let faultName = getEnv("LEAK_FAULT")
template fault(n: string): bool =
when defined(leakfault): faultName == n else: false
proc add(s: var Stat, v: float) = inc s.n; s.sum += v; s.worst = max(s.worst, v)
proc printStats() =
for k, s in vstat: echo &"STATS vision_ms {k}: n={s.n} avg={s.sum / s.n.float:.3f} worst={s.worst:.3f}"
for k, s in bstat: echo &"STATS bytes/delivery {k}: n={s.n} avg={s.sum / s.n.float:.1f} worst={s.worst:.0f}"
for i, n in tmNames:
var a = tm[i]
if a.len == 0: continue
a.sort
var sum = 0.0
for v in a: sum += v
echo &"STATS timing_ms {n}: n={a.len} avg={sum / a.len.float:.3f} p50={a[a.len div 2]:.3f} p99={a[min(a.len - 1, a.len * 99 div 100)]:.3f} worst={a[^1]:.3f}"
stdout.flushFile
# shortcut: WebSocket has no ==/hash and private fields; key by raw bytes, fine while the layout is plain POD
proc key(ws: WebSocket): string =
result = newString(sizeof(ws)); copyMem(addr result[0], unsafeAddr ws, sizeof(ws))
proc owns(role, id: string): bool = role == "gm" or role == id
proc pt(v: Vec): JsonNode = %[%v.x, %v.y]
proc tokIdx(id: string): int =
for i, t in toks:
if t.id == id: return i
-1
proc send(c: Conn, t: string, j: JsonNode) =
j["t"] = %t; j["gseq"] = %gseq
let s = $j
c.bytes += s.len
c.ws.send(s)
proc err(c: Conn, msg: string) = c.send("error", %*{"msg": msg})
proc recompute(rn: string) =
let r = roles[rn]
var np: seq[seq[Vec]]
for t in toks:
if owns(rn, t.id): np.add visibilityPolygon(t.pos, walls, radius)
if np == r.polys: return
r.polys = np; inc r.ver
for p in np:
for (ix, iy) in cellsTouched(p, cell.float):
if ix >= 0 and iy >= 0 and ix < cw and iy < cw:
let k = iy * cw + ix
if not r.explored.containsOrIncl(k): r.fresh.add k
proc persistCells(rn: string) =
for k in roles[rn].fresh: db.exec(sql"INSERT OR IGNORE INTO exp VALUES (?,?)", rn, k)
proc sync(c: Conn, ev: Ev, initial: bool) =
## bring one client up to date; diff against what it already has
let player = c.role != "gm"
var r: Role
if player:
r = roles[c.role]
if c.ver != r.ver or (fault("other-vision") and c.role == "A"):
c.ver = r.ver
var ps = newJArray()
for p in (if fault("other-vision") and c.role == "A": r.polys & roles["B"].polys else: r.polys):
var a = newJArray()
for v in p: a.add pt(v)
ps.add a
c.send("vision", %*{"polys": ps})
var cells = newJArray()
let leakB = fault("other-explored") and c.role == "A"
if initial:
for k in r.explored: cells.add %[k mod cw, k div cw]
if leakB:
for k in roles["B"].explored: cells.add %[k mod cw, k div cw]
else:
for k in r.fresh: cells.add %[k mod cw, k div cw]
if leakB:
for k in roles["B"].fresh: cells.add %[k mod cw, k div cw]
if cells.len > 0: c.send("explored", %*{"cells": cells})
elif ev.door >= 0:
c.send("door", %*{"id": ev.door, "open": ev.doorOpen})
for t in toks:
var vis = c.role == "gm" or t.id == c.role
if not vis:
for p in r.polys:
if inside(p, t.pos): vis = true; break
if player and ((fault("hidden") and t.id == "M5") or (fault("withhold") and t.id == "M1")):
vis = t.id == "M5"
if vis:
if c.known.getOrDefault(t.id, (-1.0, -1.0)) != t.pos or initial:
c.known[t.id] = t.pos
let j = %*{"id": t.id, "name": t.name, "kind": t.kind, "pos": pt(t.pos), "mine": owns(c.role, t.id)}
if t.id == ev.moved and ev.reqId >= 0: j["by"] = %ev.by; j["reqId"] = %ev.reqId
c.send("token", j)
elif c.known.hasKey(t.id):
c.known.del t.id
if not (fault("noremove") and player): c.send("remove", %*{"id": t.id})
proc finish(ev: Ev, kind: string, visMs: float, mover: Conn = nil) =
## send phase of a mutation (caller holds lk, DB already committed)
for c in conns.values:
if c != mover: c.bytes = 0
sync(c, ev, false)
for r in roles.values: r.fresh.setLen 0
let sendMs = tSend.msSince
vstat.mgetOrPut(kind, Stat()).add visMs
var line = &"MUT gseq={gseq} {kind} vision_ms={visMs:.3f}"
for c in conns.values:
if c.bytes > 0: bstat.mgetOrPut(kind & " " & c.role, Stat()).add c.bytes.float # only recipients that got something
line.add &" {c.role}:{c.bytes}B"
echo line
inc nMut
if nMut mod 5000 == 0: printStats()
stdout.flushFile
# total = lock wait + everything under the lock (incl. the MUT line write); SLOW line is written after, not counted
let tot = lockWaitMs + tLock.msSince
for i, v in [lockWaitMs, visMs, sqlMs, sendMs, tot]: tm[i].add v
if tot > slowMs:
echo &"SLOW gseq={gseq} {kind} total={tot:.1f} lock_wait={lockWaitMs:.1f} vision={visMs:.1f} sqlite={sqlMs:.1f} send={sendMs:.1f} other={tot - lockWaitMs - visMs - sqlMs - sendMs:.1f}"
stdout.flushFile
proc handleMove(c: Conn, m: JsonNode) =
let p = m{"pos"}
if m{"reqId"}.isNil or m["reqId"].kind != JInt or m{"id"}.isNil or m["id"].kind != JString or
p.isNil or p.kind != JArray or p.len != 2 or p[0].kind notin {JInt, JFloat} or p[1].kind notin {JInt, JFloat}:
c.err("bad move"); return
let id = m["id"].getStr
let ti = tokIdx(id)
if ti < 0 or not owns(c.role, id): c.err("not yours"); return # no pos echoed: could leak unseen tokens
let reqId = m["reqId"].getInt
let np: Vec = (p[0].getFloat, p[1].getFloat)
let old = toks[ti].pos
if np.x < 0 or np.y < 0 or np.x > worldW.float or np.y > worldH.float or moveBlocked(walls, old, np, tokRadius):
c.send("moveAck", %*{"reqId": reqId, "ok": false, "pos": pt(old)}); return
toks[ti].pos = np
inc gseq
for x in conns.values: x.bytes = 0
let t0 = getMonoTime()
if roles.hasKey(id): recompute(id)
let visMs = (getMonoTime() - t0).inNanoseconds.float / 1e6
let t1 = getMonoTime()
db.exec(sql"BEGIN")
db.exec(sql"INSERT OR REPLACE INTO tok VALUES (?,?,?)", id, np.x, np.y)
if roles.hasKey(id): persistCells(id)
db.exec(sql"COMMIT")
sqlMs = t1.msSince; tSend = getMonoTime()
c.send("moveAck", %*{"reqId": reqId, "ok": true, "pos": pt(np)})
finish(Ev(door: -1, moved: id, by: c.role, reqId: reqId), (if roles.hasKey(id): "move-player" else: "move-monster"), visMs, c)
proc handleDoor(c: Conn, m: JsonNode) =
if c.role != "gm": c.err("gm only"); return
if m{"id"}.isNil or m["id"].kind != JInt or m{"open"}.isNil or m["open"].kind != JBool:
c.err("bad door"); return
let id = m["id"].getInt
if id < 0 or id >= walls.len or not walls[id].door: c.err("not a door"); return
let open = m["open"].getBool
if walls[id].open == open: return
walls[id].open = open
inc gseq
for x in conns.values: x.bytes = 0
let t0 = getMonoTime()
for rn in roles.keys: recompute(rn)
let visMs = (getMonoTime() - t0).inNanoseconds.float / 1e6
let t1 = getMonoTime()
db.exec(sql"BEGIN")
db.exec(sql"INSERT OR REPLACE INTO door VALUES (?,?)", id, ord(open))
for rn in roles.keys: persistCells(rn)
db.exec(sql"COMMIT")
sqlMs = t1.msSince; tSend = getMonoTime()
finish(Ev(door: id, doorOpen: open, moved: "", reqId: -1), "door", visMs, c)
proc openConn(ws: WebSocket, role: string) =
let c = Conn(ws: ws, role: role, ver: -1)
conns[key(ws)] = c
let ids = newJArray()
for t in toks:
if owns(role, t.id) or (fault("other-owner") and role == "A" and t.id == "B"): ids.add %t.id
c.send("hello", %*{"role": (if role == "gm": "gm" else: "player"), "tokens": ids,
"world": {"w": worldW, "h": worldH}, "tileSize": tileSize, "exploredCell": cell, "tokenRadius": tokRadius})
if role == "gm" or fault("walls"):
var ws = newJArray()
for i, w in walls: ws.add %*{"id": i, "a": pt(w.a), "b": pt(w.b), "door": w.door, "open": w.open}
c.send("walls", %*{"walls": ws})
sync(c, Ev(door: -1, reqId: -1), true)
proc wsHandler(ws: WebSocket, event: WebSocketEvent, message: Message) {.gcsafe.} =
{.gcsafe.}:
let tq = getMonoTime()
withLock lk:
lockWaitMs = tq.msSince; tLock = getMonoTime()
case event
of MessageEvent:
let c = conns.getOrDefault(key(ws))
if c.isNil or message.kind != TextMessage: return
try:
let m = parseJson(message.data)
case m{"t"}.getStr
of "move": handleMove(c, m)
of "door": handleDoor(c, m)
else: c.err("unknown type")
except CatchableError:
c.err("malformed")
of CloseEvent, ErrorEvent: conns.del key(ws)
else: discard
proc cookieSecret(request: Request): string =
for (k, v) in request.headers:
if k.toLowerAscii == "cookie":
for part in v.split(';'):
let p = part.strip
if p.startsWith("sid="): return p[4 .. ^1]
proc handler(request: Request) {.gcsafe.} =
{.gcsafe.}:
let path = request.path
if path.startsWith("/join/") and request.httpMethod == "GET":
let s = path[6 .. ^1]
withLock lk:
if s notin secrets: request.respond(403); return
var h: HttpHeaders
h["Location"] = "/"
h["Set-Cookie"] = &"sid={s}; Path=/; HttpOnly; SameSite=Strict"
request.respond(302, h)
elif path == "/ws":
withLock lk:
let s = cookieSecret(request)
if s notin secrets: request.respond(403); return
openConn(request.upgradeToWebSocket(), secrets[s])
elif path.startsWith("/tiles/") and path.endsWith(".png"):
let parts = path[7 .. ^5].split('_')
if parts.len != 2 or parts[0].len notin 1..3 or parts[1].len notin 1..3 or
not parts[0].allCharsInSet(Digits) or not parts[1].allCharsInSet(Digits):
request.respond(404); return
let (tx, ty) = (parseInt(parts[0]), parseInt(parts[1]))
if tx >= worldW div tileSize or ty >= worldH div tileSize: request.respond(404); return
var ok = false
withLock lk:
let s = cookieSecret(request)
if s in secrets:
let rn = secrets[s]
ok = rn == "gm" or fault("tile")
if not ok:
let per = tileSize div cell # shortcut: assumes tileSize % exploredCell == 0
for cy in ty * per ..< (ty + 1) * per:
for cx in tx * per ..< (tx + 1) * per:
if (cy * cw + cx) in roles[rn].explored: ok = true
if ok:
var h: HttpHeaders
h["X-Accel-Redirect"] = &"/_tiles/{tx}_{ty}.png"
request.respond(200, h)
else: request.respond(403)
else: request.respond(404)
proc loadState() =
let sc = parseFile("data/scene.json")
worldW = sc["world"]["w"].getInt; worldH = sc["world"]["h"].getInt
tileSize = sc["tileSize"].getInt; cell = sc["exploredCell"].getInt
radius = sc["visionRadius"].getFloat
tokRadius = sc["tokenRadius"].getFloat
cw = (worldW + cell - 1) div cell
for w in sc["walls"]:
walls.add Wall(a: (w["a"][0].getFloat, w["a"][1].getFloat), b: (w["b"][0].getFloat, w["b"][1].getFloat),
door: w["door"].getBool, open: w["open"].getBool)
for t in sc["tokens"]:
toks.add Tok(id: t["id"].getStr, name: t["name"].getStr, kind: t["kind"].getStr,
pos: (t["pos"][0].getFloat, t["pos"][1].getFloat), gmOnly: t["gmOnly"].getBool)
createDir runDir
db = open(runDir / "state.db", "", "", "")
discard db.getAllRows(sql"PRAGMA journal_mode=WAL")
db.exec(sql"PRAGMA synchronous=NORMAL") # WAL: commit no longer fsyncs (power loss may drop the last commits, never corrupts; process kill loses nothing)
for s in ["CREATE TABLE IF NOT EXISTS meta (k TEXT PRIMARY KEY, v TEXT)",
"CREATE TABLE IF NOT EXISTS tok (id TEXT PRIMARY KEY, x REAL, y REAL)",
"CREATE TABLE IF NOT EXISTS door (id INTEGER PRIMARY KEY, open INTEGER)",
"CREATE TABLE IF NOT EXISTS exp (role TEXT, c INTEGER, PRIMARY KEY (role, c))"]:
db.exec(sql(s))
for r in db.getAllRows(sql"SELECT id,x,y FROM tok"):
toks[tokIdx(r[0])].pos = (parseFloat(r[1]), parseFloat(r[2]))
for r in db.getAllRows(sql"SELECT id,open FROM door"): walls[parseInt(r[0])].open = r[1] == "1"
var invites = ""
for rn in ["gm", "A", "B"]:
var s = db.getValue(sql"SELECT v FROM meta WHERE k=?", rn)
if s == "":
for b in urandom(16): s.add toHex(b.int, 2).toLowerAscii
db.exec(sql"INSERT INTO meta VALUES (?,?)", rn, s)
secrets[s] = rn
invites.add &"{rn} {origin}/join/{s}\n"
if rn != "gm":
roles[rn] = Role(ver: 0)
for r in db.getAllRows(sql"SELECT c FROM exp WHERE role=?", rn): roles[rn].explored.incl parseInt(r[0])
echo invites
writeFile(runDir / "invites.txt", invites)
db.exec(sql"BEGIN")
for rn in roles.keys:
recompute(rn); persistCells(rn); roles[rn].fresh.setLen 0
db.exec(sql"COMMIT")
loadState()
setControlCHook(proc() {.noconv.} =
{.gcsafe.}:
printStats() # shortcut: reads stats without the lock; fine at exit
quit 0)
let server = newServer(handler, wsHandler, workerThreads = 8)
echo "listening 127.0.0.1:" & $backendPort
stdout.flushFile
server.serve(Port(backendPort), "127.0.0.1")
+238
View File
@@ -0,0 +1,238 @@
import std/[unittest, json, os]
import geometry
proc W(ax, ay, bx, by: float, door = false, open = false): Wall =
Wall(a: (ax, ay), b: (bx, by), door: door, open: open)
proc box(x0, y0, x1, y1: float): seq[Wall] =
@[W(x0, y0, x1, y0), W(x1, y0, x1, y1), W(x1, y1, x0, y1), W(x0, y1, x0, y0)]
proc sees(walls: openArray[Wall], o, p: Vec, r = 500.0): bool =
visibilityPolygon(o, walls, r).inside(p)
proc hasVertex(poly: openArray[Vec], p: Vec): bool =
for v in poly:
if abs(v.x - p.x) < 1e-6 and abs(v.y - p.y) < 1e-6: return true
suite "visibility":
test "open space is a circle":
let poly = visibilityPolygon((0.0, 0.0), @[], 100)
check poly.inside((60.0, 0.0))
check not poly.inside((101.0, 0.0))
check poly.inside((0.0, -95.0))
test "wall blocks":
let w = @[W(50, -50, 50, 50)]
check not sees(w, (0.0, 0.0), (80.0, 0.0))
check sees(w, (0.0, 0.0), (40.0, 0.0))
test "shared endpoint: no leak at the vertex":
# L corner at (50,0): vertical arm (50,-50)-(50,0), horizontal arm (50,0)-(100,0)
let w = @[W(50, -50, 50, 0), W(50, 0, 100, 0)]
# viewer on the diagonal through the shared vertex: the ray touches both arms' endpoint
let v: Vec = (0.0, -25.0)
check visibilityPolygon(v, w, 500).hasVertex((50.0, 0.0))
check not sees(w, v, (70.0, 9.0)) # just below the ray through the vertex (y=10 at x=70): vertical arm shadows it
check sees(w, v, (70.0, 11.0)) # just above the ray: past the vertex, the corner is not a crack
# token on the line of the horizontal arm: a point just above the line is visible past the arm's end-on
# edge, just below it is shadowed by the vertical arm
check sees(w, (0.0, 0.0), (70.0, 5.0))
check not sees(w, (0.0, 0.0), (70.0, -5.0))
test "'<' apex: ray through the shared tip must not leak":
for flip in [false, true]: # each wall in both directions: the tip is an upper end of one and a lower end of the other
let w = if flip: @[W(100, 0, 50, -40), W(100, 0, 50, 40)] else: @[W(50, -40, 100, 0), W(50, 40, 100, 0)]
check visibilityPolygon((0.0, 0.0), w, 500).hasVertex((100.0, 0.0))
check not sees(w, (0.0, 0.0), (150.0, 0.0))
check not sees(w, (0.0, 0.0), (300.0, 0.0))
check sees(w, (0.0, 0.0), (90.0, 0.0))
test "every segment endpoint is a polygon vertex (lower and upper end inclusive)":
# free-standing wall, nothing else shares the endpoints: an exclusive end would drop the exact-endpoint ray
let w = @[W(50, -30, 80, 10)]
let poly = visibilityPolygon((0.0, 0.0), w, 500)
check poly.hasVertex((50.0, -30.0)) # lower end (u = 0)
check poly.hasVertex((80.0, 10.0)) # upper end (u = 1)
let r = @[W(80, 10, 50, -30)] # same wall, ends swapped
let pr = visibilityPolygon((0.0, 0.0), r, 500)
check pr.hasVertex((50.0, -30.0))
check pr.hasVertex((80.0, 10.0))
test "rays nudged past a corner: area just beyond a wall end is visible":
# viewer heights are chosen so the corner ray sits mid-way between two circle rays: no other ray can mask a missing nudge ray
# wall (50,-50)-(50,0) seen from (0,7.4): the ray through the end (50,0) continues to (100,-7.4)
let w = @[W(50, -50, 50, 0)]
check sees(w, (0.0, 7.4), (100.0, -6.0)) # lit side of that ray
check not sees(w, (0.0, 7.4), (100.0, -9.0)) # shadow side
# mirror: wall (50,0)-(50,50) seen from (0,-7.4)
let m = @[W(50, 0, 50, 50)]
check sees(m, (0.0, -7.4), (100.0, 6.0))
check not sees(m, (0.0, -7.4), (100.0, 9.0))
# box (pillar) seen from (0,-24): the rays through corners (100,50) and (100,-50) continue to (200,124) and (200,-76)
let b = box(100, -50, 150, 50)
check sees(b, (0.0, -24.0), (200.0, 130.0))
check not sees(b, (0.0, -24.0), (200.0, 118.0))
check sees(b, (0.0, -24.0), (200.0, -85.0))
check not sees(b, (0.0, -24.0), (200.0, -70.0))
test "shared endpoint: closed corner of box has no crack":
let w = box(-100, -100, 100, 100)
check not sees(w, (0.0, 0.0), (130.0, 130.0), 1000)
check not sees(w, (-90.0, -90.0), (-130.0, -130.0), 1000)
check sees(w, (0.0, 0.0), (95.0, 95.0), 1000) # the corner itself is visible from inside
check sees(w, (-90.0, -90.0), (90.0, 90.0), 1000)
test "collinear walls act as one":
let w = @[W(50, -50, 50, 0), W(50, 0, 50, 50)]
check not sees(w, (0.0, 0.0), (80.0, 0.0)) # ray through the join
check not sees(w, (0.0, 30.0), (80.0, 30.0))
check sees(w, (0.0, 0.0), (40.0, 0.0)) # in front of the join
check sees(w, (0.0, 0.0), (-80.0, 0.0)) # behind the viewer
check sees(w, (0.0, 0.0), (80.0, 100.0)) # past the far end of the line
check not sees(w, (0.0, 0.0), (80.0, -30.0))
test "collinear walls with a gap let light through":
let w = @[W(50, -50, 50, -5), W(50, 5, 50, 50)]
check sees(w, (0.0, 0.0), (80.0, 0.0))
check not sees(w, (0.0, 0.0), (80.0, 30.0))
test "T-junction: no leak and correct shadow":
# horizontal y=0 from x=-100..100, vertical stem from (0,0) up to (0,-100)
let w = @[W(-100, 0, 100, 0), W(0, 0, 0, -100)]
check not sees(w, (-30.0, -30.0), (30.0, -30.0)) # stem blocks
check not sees(w, (-30.0, -30.0), (-30.0, 30.0)) # base blocks
check sees(w, (-30.0, -30.0), (-80.0, -60.0))
check not sees(w, (-30.0, -30.0), (10.0, -5.0), 500)
check sees(w, (-30.0, -30.0), (-10.0, -5.0)) # same side of the stem, above the base
check sees(w, (30.0, -30.0), (80.0, -60.0)) # mirror side
check not sees(w, (30.0, -30.0), (-10.0, -5.0))
test "pillar mid-room casts a shadow, sides visible":
var w = box(-200, -200, 200, 200)
w.add box(-10, -10, 10, 10)
check not sees(w, (-100.0, 0.0), (100.0, 0.0))
check sees(w, (-100.0, 0.0), (100.0, 50.0))
check sees(w, (-100.0, 0.0), (0.0, 50.0))
check not sees(w, (-100.0, 0.0), (50.0, 3.0))
test "closed door blocks, open door passes":
let closed = @[W(50, -50, 50, -10), W(50, -10, 50, 10, true, false), W(50, 10, 50, 50)]
var opened = closed
opened[1].open = true
check not sees(closed, (0.0, 0.0), (90.0, 0.0))
check sees(opened, (0.0, 0.0), (90.0, 0.0))
check not sees(opened, (0.0, 0.0), (90.0, 40.0))
test "token exactly at wall endpoint":
let w = @[W(0, 0, 100, 0), W(0, 0, 0, 100)] # corner, token on it
let poly = visibilityPolygon((0.0, 0.0), w, 200)
check poly.inside((-50.0, -50.0)) # open outward quadrant
check poly.inside((100.0, -30.0))
check poly.inside((50.0, 50.0)) # arms radiate from the token: the inner quadrant is open too
check poly.inside((-50.0, 50.0))
check not poly.inside((150.0, 150.0)) # beyond the radius (212 > 200)
check not poly.inside((0.0, 250.0))
test "token at endpoint of free-standing wall sees along it":
let w = @[W(0, 0, 100, 0)]
check sees(w, (0.0, 0.0), (50.0, -20.0))
check sees(w, (0.0, 0.0), (-50.0, 20.0))
check sees(w, (0.0, 0.0), (50.0, 20.0))
check not sees(w, (0.0, 0.0), (600.0, 0.0)) # beyond the 500 radius
test "long thin corridor":
# 1000 long, 20 wide, token at one end; radius 2000
let w = @[W(0, -10, 1000, -10), W(0, 10, 1000, 10), W(1000, -10, 1000, 10)]
check sees(w, (5.0, 0.0), (990.0, 0.0), 2000)
check not sees(w, (5.0, 0.0), (500.0, 15.0), 2000)
check not sees(w, (5.0, 0.0), (1010.0, 0.0), 2000)
check sees(w, (5.0, 0.0), (900.0, 8.0), 2000)
test "wall endpoints behind the viewer: fan stays angularly ordered":
# regression: circle angles in [0,2pi) were sorted against atan2 angles in (-pi,pi] -> bow-tie polygon
let w = box(600, 600, 680, 680) & @[W(1024, 256, 1024, 608)]
check sees(w, (908.66, 672.03), (789.36, 584.65), 400)
check sees(w, (789.36, 584.65), (908.66, 672.03), 400)
check not sees(w, (908.66, 672.03), (1100.0, 500.0), 400) # the x=1024 wall (y 256..608) is in the way
test "radius clips":
check not sees(@[], (0.0, 0.0), (300.0, 0.0), 200)
suite "moves":
let wall = W(0, -50, 0, 50)
test "crossing blocked, parallel ok":
check moveBlocked([wall], (-10.0, 0.0), (10.0, 0.0))
check not moveBlocked([wall], (-10.0, 0.0), (-10.0, 30.0))
check not moveBlocked([wall], (-10.0, 60.0), (10.0, 60.0)) # passes beyond the end
test "grazing an endpoint is blocked":
check moveBlocked([wall], (-10.0, 50.0), (10.0, 50.0))
check moveBlocked([wall], (-10.0, -60.0), (10.0, -40.0)) # crosses
test "no leak through shared vertex":
let w = [W(0, -50, 0, 0), W(0, 0, 0, 50)]
check moveBlocked(w, (-10.0, 0.0), (10.0, 0.0))
test "diagonal squeeze through corner vertex of L":
let w = [W(0, 0, 50, 0), W(0, 0, 0, 50)]
check moveBlocked(w, (10.0, -10.0), (-10.0, 10.0))
test "moving along a collinear wall is blocked":
check moveBlocked([wall], (0.0, -100.0), (0.0, 100.0))
test "doors":
var d = W(0, -10, 0, 10, true, false)
check moveBlocked([d], (-5.0, 0.0), (5.0, 0.0))
d.open = true
check not moveBlocked([d], (-5.0, 0.0), (5.0, 0.0))
test "zero-length move":
check not moveBlocked([wall], (-5.0, 0.0), (-5.0, 0.0))
suite "cells":
test "square polygon":
let sq = [(10.0, 10.0), (50.0, 10.0), (50.0, 50.0), (10.0, 50.0)]
check cellsTouched(sq, 32) == @[(0, 0), (1, 0), (0, 1), (1, 1)]
test "tiny polygon inside one cell":
check cellsTouched([(1.0, 1.0), (5.0, 1.0), (3.0, 5.0)], 32) == @[(0, 0)]
test "polygon spanning a cell with no vertex in it":
# thin horizontal strip crossing 3 cells
let strip = [(1.0, 10.0), (95.0, 10.0), (95.0, 12.0), (1.0, 12.0)]
check cellsTouched(strip, 32) == @[(0, 0), (1, 0), (2, 0)]
test "big polygon includes fully covered interior cells":
let big = [(0.0, 0.0), (200.0, 0.0), (200.0, 200.0), (0.0, 200.0)]
check (3, 3) in cellsTouched(big, 32)
suite "seed":
test "every token in seed sees itself and is not walled in":
let sp = currentSourcePath().parentDir / ".." / "data" / "scene.json"
if not fileExists(sp): skip()
else:
let j = parseFile(sp)
var walls: seq[Wall]
for w in j["walls"]:
walls.add Wall(a: (w["a"][0].getFloat, w["a"][1].getFloat), b: (w["b"][0].getFloat, w["b"][1].getFloat),
door: w{"door"}.getBool, open: w{"open"}.getBool)
for t in j["tokens"]:
let p: Vec = (t["pos"][0].getFloat, t["pos"][1].getFloat)
let poly = visibilityPolygon(p, walls, j["visionRadius"].getFloat)
check poly.len > 8
check cellsTouched(poly, j["exploredCell"].getFloat).len > 0
check not moveBlocked(walls, p, p, j["tokenRadius"].getFloat)
suite "token clearance (r=20)":
const r = 20.0
test "near pillar: circle overlapping blocked, clear ok":
let pil = box(600, 600, 680, 680)
check moveBlocked(pil, (500.0, 640.0), (585.0, 640.0), r) # center outside, circle inside wall
check not moveBlocked(pil, (500.0, 640.0), (570.0, 640.0), r) # 30 away
test "near closed door blocks, open door passes":
let cl = @[W(0, 0, 0, 64, door = true)]
check moveBlocked(cl, (-50.0, 32.0), (10.0, 32.0), r) # dest 10 from the wall
check moveBlocked(cl, (-50.0, 32.0), (-10.0, 32.0), r)
let op = @[W(0, 0, 0, 64, door = true, open = true)]
check not moveBlocked(op, (-50.0, 32.0), (50.0, 32.0), r)
test "64px corridor and doorway passable on centerline":
let c = @[W(0, 0, 500, 0), W(0, 64, 500, 64)]
check not moveBlocked(c, (10.0, 32.0), (490.0, 32.0), r)
check not moveBlocked(c, (10.0, 32.0), (11.0, 32.0), r)
let door = @[W(0, -200, 0, -32), W(0, 32, 0, 200)]
check not moveBlocked(door, (-30.0, 0.0), (30.0, 0.0), r)
test "legacy overlap can escape, not stay overlapped":
let w = @[W(0, 0, 100, 0)]
check not moveBlocked(w, (50.0, 5.0), (50.0, 40.0), r)
check moveBlocked(w, (50.0, 5.0), (50.0, 15.0), r)
+29
View File
@@ -0,0 +1,29 @@
## Vision microbench: nim c -d:release -r tools/bench.nim (devbox run bench)
import std/[json, monotimes, times, strformat]
import geometry
let j = parseFile("data/scene.json")
var walls: seq[Wall]
for w in j["walls"]:
walls.add Wall(a: (w["a"][0].getFloat, w["a"][1].getFloat), b: (w["b"][0].getFloat, w["b"][1].getFloat), door: w["door"].getBool, open: w["open"].getBool)
let r = j["visionRadius"].getFloat
var ps: seq[Vec]
for t in j["tokens"]: ps.add (t["pos"][0].getFloat, t["pos"][1].getFloat)
proc bench(name: string, n: int, f: proc(i: int)) =
var sum, worst = 0.0
for i in 0 ..< n:
let t0 = getMonoTime(); f(i)
let ms = (getMonoTime() - t0).inNanoseconds.float / 1e6
sum += ms; worst = max(worst, ms)
echo &"{name}: n={n} avg={sum / n.float:.3f}ms worst={worst:.3f}ms"
var sink = 0
bench("1 poly (jittered start positions)", 2000, proc(i: int) =
let p = ps[i mod 8]; sink += visibilityPolygon((p.x + float(i mod 50), p.y), walls, r).len)
bench("6 polys (one 6-token party)", 500, proc(i: int) =
for k in 0 ..< 6:
let p = ps[k + 2]; sink += visibilityPolygon((p.x + float(i mod 50), p.y), walls, r).len)
bench("1 poly + cellsTouched", 2000, proc(i: int) =
let p = ps[i mod 8]; sink += cellsTouched(visibilityPolygon((p.x + float(i mod 50), p.y), walls, r), 32).len)
bench("6 polys + cellsTouched", 300, proc(i: int) =
for k in 0 ..< 6:
let p = ps[k + 2]; sink += cellsTouched(visibilityPolygon((p.x + float(i mod 50), p.y), walls, r), 32).len)
echo "(sink ", sink, ")"
@@ -0,0 +1,82 @@
// A, B, GM hammer the server concurrently (moves every 20-50 ms per token, GM toggles doors), then compare views to fresh connections.
import { connect, sleep } from './lib.mjs'
const DUR = (process.env.DUR ?? 60) * 1000
const fails = []
const check = (c, m) => { if (!c) { fails.push(m); console.log('FAIL', m) } }
const sendT = new Map(), lat = { self: [], other: [] }
function mkState(name) {
const st = { name, toks: new Map(), doors: new Map(), explored: new Set(), poly: '[]', last: -1, backwards: 0, msgs: 0, bytes: 0, errors: 0, sent: 0, acks: 0, nack: 0, pending: new Set(), req: 0 }
st.on = (m, b) => {
st.msgs++; st.bytes += b
if (m.gseq < st.last) st.backwards++
st.last = m.gseq
switch (m.t) {
case 'hello': st.toks.clear(); st.explored.clear(); st.doors.clear(); st.poly = '[]'; break
case 'walls': for (const w of m.walls) if (w.door) st.doors.set(w.id, w.open); break
case 'door': st.doors.set(m.id, m.open); break
case 'vision': st.poly = JSON.stringify(m.polys); break
case 'explored': for (const c of m.cells) st.explored.add(c + ''); break
case 'token':
st.toks.set(m.id, m.pos + '')
if (m.reqId !== undefined) { const t0 = sendT.get(m.by + ':' + m.reqId); if (t0 && m.by !== st.name) lat.other.push(performance.now() - t0) }
break
case 'remove': st.toks.delete(m.id); break
case 'moveAck': st.acks++; st.pending.delete(m.reqId); if (!m.ok) st.nack++; st.onAck?.(m); break
case 'error': st.errors++; break
}
}
return st
}
const S = { gm: mkState('gm'), A: mkState('A'), B: mkState('B') }
const C = {}
for (const r of ['gm', 'A', 'B']) C[r] = await connect(r, S[r].on)
// random walkers: [client, token id, box]
const walkers = [['A', 'A', [300, 300, 980, 980], [400, 400]], ['B', 'B', [300, 2100, 980, 2780], [400, 2200]],
['gm', 'M1', [300, 300, 980, 980], [900, 900]], ['gm', 'M2', [1600, 300, 2250, 980], [1920, 640]], ['gm', 'M3', [2870, 300, 3530, 980], [3400, 500]],
['gm', 'M4', [300, 2100, 980, 2780], [900, 2700]], ['gm', 'M5', [1600, 2100, 2250, 2780], [1920, 2400]], ['gm', 'M6', [2870, 2100, 3530, 2780], [3200, 2400]]]
let running = true
const rnd = (a, b) => a + Math.random() * (b - a)
const loops = walkers.map(async ([who, id, [x0, y0, x1, y1], p]) => {
const st = S[who]
while (running) {
p = [Math.min(x1, Math.max(x0, p[0] + rnd(-40, 40))), Math.min(y1, Math.max(y0, p[1] + rnd(-40, 40)))]
const r = ++st.req; st.pending.add(r); st.sent++
sendT.set(who + ':' + r, performance.now())
st.onAck = m => { const t0 = sendT.get(who + ':' + m.reqId); if (t0) lat.self.push(performance.now() - t0); if (!m.ok) p = m.pos } // blocked: resync to server pos (shortcut: GM shares one onAck, only the last walker resyncs)
C[who].ws.send(JSON.stringify({ t: 'move', reqId: r, id, pos: p }))
await sleep(rnd(20, 50))
}
})
const doorLoop = (async () => { let o = true; while (running) { await sleep(rnd(1000, 3000)); o = !o; C.gm.ws.send(JSON.stringify({ t: 'door', id: 10, open: o })); C.gm.ws.send(JSON.stringify({ t: 'door', id: 27, open: !o })) } })()
const t0 = performance.now()
await sleep(DUR)
running = false
await Promise.all([...loops, doorLoop])
for (let i = 0; i < 100 && Object.values(S).some(s => s.pending.size); i++) await sleep(100)
await sleep(500)
// quiesced: compare against fresh connections
const F = {}
for (const r of ['gm', 'A', 'B']) { F[r] = mkState(r); await connect(r, F[r].on) }
const sig = m => JSON.stringify([...m].sort())
for (const r of ['gm', 'A', 'B']) {
const s = S[r], f = F[r]
check(s.pending.size === 0, `${r}: ${s.pending.size} moves never acked`)
check(s.sent === s.acks, `${r}: sent ${s.sent} acks ${s.acks}`)
check(s.backwards === 0, `${r}: gseq went backwards ${s.backwards}x`)
check(s.errors === 0, `${r}: ${s.errors} error msgs`)
check(sig(s.toks) === sig(f.toks), `${r}: token view != fresh snapshot`)
check(sig(s.doors) === sig(f.doors), `${r}: doors != fresh`)
check(s.poly === f.poly, `${r}: vision != fresh`)
check(sig(s.explored) === sig(f.explored), `${r}: explored != fresh (${s.explored.size} vs ${f.explored.size})`)
}
const q = (a, p) => a.length ? a.slice().sort((x, y) => x - y)[Math.min(a.length - 1, Math.floor(a.length * p))] : NaN
const st = a => `n=${a.length} avg=${(a.reduce((x, y) => x + y, 0) / a.length).toFixed(2)}ms p95=${q(a, 0.95).toFixed(2)}ms p99=${q(a, 0.99).toFixed(2)}ms worst=${Math.max(...a).toFixed(2)}ms`
const secs = (performance.now() - t0) / 1000
for (const r of ['gm', 'A', 'B']) console.log(`${r}: sent ${S[r].sent} moves (${(S[r].sent / secs).toFixed(0)}/s), acks ${S[r].acks} (nack ${S[r].nack}), recv ${S[r].msgs} msgs ${(S[r].bytes / 1024).toFixed(0)} KiB, final gseq ${S[r].last}, tokens in view ${S[r].toks.size}`)
console.log('latency intent->ack (sender):', st(lat.self))
console.log('latency intent->arrival at other clients:', st(lat.other))
console.log(fails.length ? `FAILED ${fails.length}` : 'concurrency: PASS')
process.exit(fails.length ? 1 : 0)
+36
View File
@@ -0,0 +1,36 @@
#!/bin/sh
# Deliberate-leak test: the checker must FAIL, under the right class, for every fault injected into a -d:leakfault server build.
# usage: tools/faulttest.sh (isolated via withserver.sh; also proves the normal build has no hook, and a clean build still passes)
cd "$(dirname "$0")/.." || exit 1
mkdir -p run/test results
nim c -d:release --hints:off -o:run/test/leakcheck tools/leakcheck.nim >/dev/null || exit 1
bad=0
# 1. normal build carries no hook
nim c -d:release --hints:off --nimblePath:"${NIMBLE_DIR:-.devbox/nimble}/pkgs2" --nimcache:run/test/nimcache-clean -o:run/test/server-clean src/server.nim >/dev/null || exit 1
for f in run/test/server-clean; do
[ -f $f ] || continue
if grep -aq LEAK_FAULT $f; then echo "FAIL $f contains the fault hook"; bad=1; else echo "PASS $f has no fault hook"; fi
done
# 2. each fault: "fault-name class" (class must appear as FAILCLASS in checker output, exit must be nonzero)
: > results/faults.log
while read -r fault cls extra; do
out=$(SERVER_FLAGS=-d:leakfault LEAK_FAULT=$fault SUBJECT=A tools/withserver.sh sh -c 'node tools/leak.mjs && run/test/leakcheck' 2>&1); rc=$?
{ echo "== fault $fault"; echo "$out" | grep -E '^(FAIL|leakcheck)'; } >> results/faults.log
got=$(echo "$out" | sed -n 's/^FAILCLASS \([A-Z_]*\) .*/\1/p' | sort | xargs)
want=$(echo "$cls $extra" | tr ' ' '\n' | sort | xargs)
# exact class set: the intended class fires and nothing unrelated does (a checker that flags everything would not prove anything)
if [ $rc -ne 0 ] && [ "$got" = "$want" ]; then echo "PASS fault $fault caught as: $got"
else echo "FAIL fault $fault (rc=$rc) classes [$got] expected [$want]"; echo "$out" | tail -5; bad=1; fi
done <<'LIST'
hidden HIDDEN_TOKEN
walls WALLDATA
tile TILE
withhold WITHHELD
other-vision OTHER_PLAYER OWN_VIEW
other-explored OTHER_PLAYER EXPLORED
other-owner OTHER_PLAYER
noremove NO_REMOVE
LIST
# 3. clean build still passes
if SUBJECT=A tools/withserver.sh sh -c 'node tools/leak.mjs && run/test/leakcheck' >/dev/null 2>&1; then echo "PASS clean build passes"; else echo "FAIL clean build rejected"; bad=1; fi
exit $bad
+106
View File
@@ -0,0 +1,106 @@
// One command: node tools/genmap.mjs -> data/scene.json (source of truth) + data/tiles/<x>_<y>.png
// `--from-seed` skips scene generation and re-renders tiles from the existing data/scene.json.
// Deterministic: layout is hand-authored (no RNG) so the seed edge cases are guaranteed.
import fs from 'node:fs'
import zlib from 'node:zlib'
const SIZE = 4096, TILE = 256, DIR = new URL('../data/', import.meta.url).pathname
const seedPath = DIR + 'scene.json'
function build() {
const walls = []
const add = (a, b, extra = {}) => walls.push({ id: walls.length, a, b, door: false, open: false, ...extra })
const H = (y, x0, x1, e) => add([x0, y], [x1, y], e)
const V = (x, y0, y1, e) => add([x, y0], [x, y1], e)
// split [lo,hi] by gaps [a,b,door?]; plain gap = opening, door gap = door segment
const side = (lo, hi, gaps, emit) => {
let c = lo
for (const [a, b, d] of [...gaps].sort((p, q) => p[0] - q[0])) {
if (a > c) emit(c, a)
if (d) emit(a, b, { door: true, open: d === 'open' })
c = b
}
if (c < hi) emit(c, hi)
}
const room = (x0, y0, x1, y1, g = {}) => {
side(x0, x1, g.n ?? [], (a, b, e) => H(y0, a, b, e))
side(x0, x1, g.s ?? [], (a, b, e) => H(y1, a, b, e))
side(y0, y1, g.w ?? [], (a, b, e) => V(x0, a, b, e))
side(y0, y1, g.e ?? [], (a, b, e) => V(x1, a, b, e))
}
const rooms = [
[256, 256, 1024, 1024, { e: [[608, 672]], s: [[608, 672]] }], // R1 (pillar)
[1536, 256, 2304, 1024, { w: [[608, 672, 'closed']], e: [[608, 672]], s: [[1888, 1952]] }], // R2: door 1
[2816, 256, 3584, 1024, { w: [[608, 672]], s: [[3168, 3232]] }], // R3 (T-junction, split north wall)
[256, 2048, 1024, 2816, { n: [[608, 672]], e: [[2400, 2464]] }], // R4
[1536, 2048, 2304, 2816, { n: [[1888, 1952, 'open']], w: [[2400, 2464]], e: [[2400, 2464]] }], // R5: door 2
[2816, 2048, 3584, 2816, { n: [[3168, 3232]], w: [[2400, 2464]] }], // R6
]
const floors = rooms.map(r => r.slice(0, 4))
rooms.forEach(r => room(...r))
// collinear: split R3's north wall into two touching pieces at x=3200
const n3 = walls.find(w => w.a[0] === 2816 && w.a[1] === 256 && w.b[0] === 3584 && w.b[1] === 256)
n3.b = [3200, 256]; H(256, 3200, 3584)
// corridors: two parallel walls + floor
const hc = (y0, y1, x0, x1) => { H(y0, x0, x1); H(y1, x0, x1); floors.push([x0, y0, x1, y1]) }
const vc = (x0, x1, y0, y1) => { V(x0, y0, y1); V(x1, y0, y1); floors.push([x0, y0, x1, y1]) }
hc(608, 672, 1024, 1536); hc(608, 672, 2304, 2816) // R1-R2 (door at R2 end), R2-R3
hc(2400, 2464, 1024, 1536); hc(2400, 2464, 2304, 2816) // R4-R5, R5-R6
vc(1888, 1952, 1024, 2048) // R2-R5: 1024 long, 64 wide (long thin)
vc(3168, 3232, 1024, 2048); vc(608, 672, 1024, 2048) // R3-R6, R1-R4
// pillar mid-room R1 (centre 640,640)
H(600, 600, 680); H(680, 600, 680); V(600, 600, 680); V(680, 600, 680)
// T-junction: partition ends mid-way on R3's south wall piece (2816..3168) at x=3000
V(3000, 700, 1024)
const tok = (id, kind, name, pos, gmOnly) => ({ id, kind, name, pos, gmOnly })
const tokens = [
tok('A', 'player', 'Player A', [400, 400], false),
tok('B', 'player', 'Player B', [400, 2200], false),
...[[900, 900], [1920, 640], [3400, 500], [900, 2700], [1920, 2400], [3200, 2400]]
.map((p, i) => tok(`M${i + 1}`, 'monster', `Monster ${i + 1}`, p, true)),
]
return { world: { w: SIZE, h: SIZE }, tileSize: TILE, visionRadius: 400, tokenRadius: 20, exploredCell: 32, walls, floors, tokens }
}
// --- raster ---
const crcT = Uint32Array.from({ length: 256 }, (_, n) => { let c = n; for (let k = 0; k < 8; k++) c = c & 1 ? 0xedb88320 ^ (c >>> 1) : c >>> 1; return c >>> 0 })
const crc = b => { let c = ~0; for (const x of b) c = crcT[(c ^ x) & 255] ^ (c >>> 8); return ~c >>> 0 }
const chunk = (t, d) => { const b = Buffer.alloc(12 + d.length); b.writeUInt32BE(d.length); b.write(t, 4); d.copy(b, 8); b.writeUInt32BE(crc(b.subarray(4, 8 + d.length)), 8 + d.length); return b }
function png(rgb, w, h) {
const raw = Buffer.alloc((w * 3 + 1) * h)
for (let y = 0; y < h; y++) rgb.copy(raw, y * (w * 3 + 1) + 1, y * w * 3, (y + 1) * w * 3)
const ihdr = Buffer.alloc(13); ihdr.writeUInt32BE(w); ihdr.writeUInt32BE(h, 4); ihdr[8] = 8; ihdr[9] = 2
return Buffer.concat([Buffer.from([137, 80, 78, 71, 13, 10, 26, 10]), chunk('IHDR', ihdr), chunk('IDAT', zlib.deflateSync(raw)), chunk('IEND', Buffer.alloc(0))])
}
function render(scene) {
const img = Buffer.alloc(SIZE * SIZE * 3)
const fill = (x0, y0, x1, y1, [r, g, b]) => {
for (let y = y0; y < y1; y++) for (let x = x0; x < x1; x++) { const i = (y * SIZE + x) * 3; img[i] = r; img[i + 1] = g; img[i + 2] = b }
}
fill(0, 0, SIZE, SIZE, [24, 22, 28])
for (const [x0, y0, x1, y1] of scene.floors) fill(x0, y0, x1, y1, [120, 112, 100])
const HALF = 4
for (const w of scene.walls) {
const [ax, ay] = w.a, [bx, by] = w.b
// door look is state-independent: tiles must not reveal or go stale on open/closed
const col = w.door ? [150, 80, 30] : [10, 10, 12]
const dx = bx - ax, dy = by - ay, L2 = dx * dx + dy * dy
for (let y = Math.max(0, Math.min(ay, by) - HALF); y <= Math.min(SIZE - 1, Math.max(ay, by) + HALF); y++)
for (let x = Math.max(0, Math.min(ax, bx) - HALF); x <= Math.min(SIZE - 1, Math.max(ax, bx) + HALF); x++) {
const t = Math.max(0, Math.min(1, ((x - ax) * dx + (y - ay) * dy) / L2))
if (Math.hypot(x - ax - t * dx, y - ay - t * dy) <= HALF) { const i = (y * SIZE + x) * 3; img[i] = col[0]; img[i + 1] = col[1]; img[i + 2] = col[2] }
}
}
fs.rmSync(DIR + 'tiles', { recursive: true, force: true }); fs.mkdirSync(DIR + 'tiles', { recursive: true })
const tile = Buffer.alloc(TILE * TILE * 3)
for (let ty = 0; ty < SIZE / TILE; ty++) for (let tx = 0; tx < SIZE / TILE; tx++) {
for (let y = 0; y < TILE; y++) img.copy(tile, y * TILE * 3, ((ty * TILE + y) * SIZE + tx * TILE) * 3, ((ty * TILE + y) * SIZE + (tx + 1) * TILE) * 3)
fs.writeFileSync(`${DIR}tiles/${tx}_${ty}.png`, png(tile, TILE, TILE))
}
}
fs.mkdirSync(DIR, { recursive: true })
if (!process.argv.includes('--from-seed')) fs.writeFileSync(seedPath, JSON.stringify(build(), null, 1))
render(JSON.parse(fs.readFileSync(seedPath, 'utf8')))
console.log('scene.json + 256 tiles ->', DIR)
+65
View File
@@ -0,0 +1,65 @@
// Leak test driver: scripted walk of A, GM + B as ground truth/noise. Writes run/leak-transcript.jsonl; tools/leakcheck.nim verifies it.
// SUBJECT=A|B (default A) is the player whose tile sweeps/view are checked (leakcheck reads the same env); the other walks as noise.
// Everything is sequential (one actor at a time) so every tile sweep sees a quiescent server at a known gseq.
import fs from 'node:fs'
import { O, RUN, connect, sleep } from './lib.mjs'
const out = fs.createWriteStream(`${RUN}/leak-transcript.jsonl`)
const log = o => out.write(JSON.stringify(o) + '\n')
let gmG = 0
const S = process.env.SUBJECT ?? 'A'
const acks = new Map(), req = { A: 0, B: 0, GM: 0 }
const mk = who => connect(who === 'GM' ? 'gm' : who, m => {
log({ k: 'msg', who, m })
if (who === 'GM') gmG = m.gseq
if (m.t === 'moveAck') acks.get(who + m.reqId)?.(m)
})
const [gm, A, B] = [await mk('GM'), await mk('A'), await mk('B')]
const cl = { GM: gm, A, B }
const pos = { A: [400, 400], B: [400, 2200], M1: [900, 900], M2: [1920, 640], M5: [1920, 2400] }
const owner = id => (id === 'A' || id === 'B' ? id : 'GM')
const mv = (id, p) => new Promise(res => { const w = owner(id), r = ++req[w]; acks.set(w + r, res); cl[w].ws.send(JSON.stringify({ t: 'move', reqId: r, id, pos: p })) })
const tiles = Object.keys(Array.from({ length: 256 })).map(i => [i % 16, Math.floor(i / 16)])
async function sweep(label) {
await sleep(40)
const g = gmG
for (let i = 0; i < tiles.length; i += 32)
await Promise.all(tiles.slice(i, i + 32).map(async ([x, y]) => {
const r = await fetch(`${O}/tiles/${x}_${y}.png`, { headers: { Cookie: cl[S].cookie } })
await r.arrayBuffer(); log({ k: 'tile', g, x, y, s: r.status, label })
}))
}
const acts = []
const cur = { ...pos }
const walk = (id, to, expectFail = false) => {
const [x, y] = cur[id], d = Math.hypot(to[0] - x, to[1] - y), n = Math.ceil(d / 40)
for (let i = 1; i <= n; i++) acts.push({ id, p: [x + (to[0] - x) * i / n, y + (to[1] - y) * i / n], fail: expectFail && i === n })
if (!expectFail) cur[id] = to
}
const door = (id, open) => acts.push({ door: [id, open] })
const sw = label => acts.push({ sweep: label })
sw('start')
walk('B', [700, 2300])
walk('A', [400, 800]); walk('A', [800, 800]); sw('M1 in view')
walk('A', [800, 640]); walk('A', [1000, 640]); walk('A', [1510, 640])
walk('A', [1540, 640], true); sw('closed door blocks')
walk('M2', [1700, 640]); sw('M2 behind closed door')
door(10, true); sw('door open'); walk('A', [1700, 640]); walk('M2', [1900, 700]); walk('A', [1900, 640]); sw('M2 close')
walk('M2', [2200, 300]); sw('M2 left'); walk('M1', [900, 640]); walk('M1', [1200, 640]); sw('M1 into corridor')
walk('A', [1920, 900]); walk('A', [1920, 1900]); sw('corridor')
door(27, false); sw('door 27 closed'); walk('A', [1920, 2020]); walk('A', [1920, 2060], true); sw('blocked'); door(27, true); sw('door 27 open')
walk('A', [1920, 2300]); sw('R5')
walk('B', [700, 2430]); walk('B', [1400, 2430]); walk('B', [1700, 2430]); sw('B visible?'); walk('B', [1000, 2430]); sw('B away')
walk('A', [1920, 2500]); sw('M5 in view'); walk('M5', [2200, 2700]); sw('M5 away'); walk('A', [1700, 2700]); sw('end')
let nA = 0, bad = 0
for (const a of acts) {
if (a.sweep) { await sweep(a.sweep); continue }
if (a.door) { cl.GM.ws.send(JSON.stringify({ t: 'door', id: a.door[0], open: a.door[1] })); await sleep(40); continue }
const m = await mv(a.id, a.p)
if (m.ok === !!a.fail) { bad++; console.log('unexpected ack', a, m) }
if (a.id === S && ++nA % 5 === 0) await sweep('walk'); else await sleep(15)
}
await sleep(200)
for (const c of [gm, A, B]) c.ws.close()
out.end()
console.log(`driver done: ${acts.length} actions, ${bad} unexpected acks, final gseq ${gmG}`)
process.exit(bad ? 1 : 0)
+154
View File
@@ -0,0 +1,154 @@
## Leak checker: replays run/leak-transcript.jsonl. Ground truth = GM socket (tokens+doors per gseq);
## subject (SUBJECT env, A|B)'s vision/explored are recomputed with geometry.nim, never taken from A's own messages.
import std/[json, tables, sets, strutils, os, math]
import geometry
let me = getEnv("SUBJECT", "A") # subject whose view is checked; the other player is noise
let other = if me == "A": "B" else: "A"
type Side = enum Out, Amb, In
# every failure carries a class (HIDDEN_TOKEN WALLDATA TILE WITHHELD OTHER_PLAYER NO_REMOVE | OWN_VIEW EXPLORED GEOMETRY PROTOCOL);
# tools/faulttest.sh asserts each injected server fault is reported under its class
var fails = 0
var classes: CountTable[string]
proc fail(cls, s: string) =
inc fails; classes.inc cls
if fails <= 20: echo "FAIL [", cls, "] ", s
# boundary is ambiguous in inside(): In/Out only if the point and its 0.5px neighbours agree
proc side(poly: seq[Vec], p: Vec): Side =
var n = 0
for d in [(0.0, 0.0), (0.5, 0.0), (-0.5, 0.0), (0.0, 0.5), (0.0, -0.5)]:
if poly.inside((p.x + d[0], p.y + d[1])): inc n
if n == 0: Out elif n == 5: In else: Amb
proc vec(j: JsonNode): Vec = (j[0].getFloat, j[1].getFloat)
const banned = ["walls", "door", "open", "a", "b", "segments", "segs", "wall"]
const allowed = ["hello", "vision", "explored", "token", "remove", "moveAck"]
proc scan(j: JsonNode, t: string) =
if j.kind == JObject:
for k, v in j:
if k in banned: fail "WALLDATA", "A msg " & t & " has wall-like key " & k
scan(v, t)
elif j.kind == JArray:
for v in j: scan(v, t)
var gm, am: seq[JsonNode]
var tiles: seq[JsonNode]
for line in lines(getEnv("RUN_DIR", "run") / "leak-transcript.jsonl"):
let j = parseJson(line)
if j["k"].getStr == "tile": tiles.add j
elif j["who"].getStr == "GM": gm.add j["m"]
elif j["who"].getStr == me: am.add j["m"]
# the other player's transcript is deliberately unused: it is only noise
let radius = parseFile("data/scene.json")["visionRadius"].getFloat
var walls: seq[Wall]
var truth: Table[string, Vec]
var tileSize, cell, cw: int
var firstG: Table[int, int] # explored cell -> gseq it first became explored (independent)
var view: Table[string, Vec] # what A has been told
var aExp: HashSet[int]
var oFirst: HashSet[int] # cells the OTHER player has explored so far (independent), to attribute leaks
var leaked: HashSet[string] # tokens already reported as HIDDEN_TOKEN (their stale view entry is not a missing remove)
var ai, removes, groups, expN: int
var seen: HashSet[string]
proc same(j: JsonNode, poly: seq[Vec]): bool =
if j.len != poly.len: return false
for i in 0 ..< poly.len:
if abs(j[i][0].getFloat - poly[i].x) > 1e-6 or abs(j[i][1].getFloat - poly[i].y) > 1e-6: return false
true
proc finalize(g: int) =
inc groups
let poly = visibilityPolygon(truth[me], walls, radius)
let polyO = visibilityPolygon(truth[other], walls, radius)
for (ix, iy) in cellsTouched(polyO, cell.float): oFirst.incl iy * cw + ix
# independent oracle (segment tests, not the ray fan): clear straight line to a point in range => point is in the polygon
for i in 0 ..< 64:
for k in [0.3, 0.6, 0.95]:
let o = truth[me]
let p: Vec = (o.x + k * radius * cos(2 * PI * i.float / 64), o.y + k * radius * sin(2 * PI * i.float / 64))
if not moveBlocked(walls, o, p) and side(poly, p) == Out: fail "GEOMETRY", "polygon misses clear-LOS point " & $p & " at g=" & $g
for (ix, iy) in cellsTouched(poly, cell.float):
if ix >= 0 and iy >= 0 and ix < cw and iy < cw and (iy * cw + ix) notin firstG:
firstG[iy * cw + ix] = g; inc expN
while ai < am.len and am[ai]["gseq"].getInt <= g:
let m = am[ai]; inc ai
let t = m["t"].getStr
if t == "error": fail "PROTOCOL", "A got error " & $m
if t notin allowed: fail (if t in ["walls", "door"]: "WALLDATA" else: "PROTOCOL"), "A got forbidden type " & t; continue
if t == "moveAck": continue
scan(m, t)
if m["gseq"].getInt != g: fail "PROTOCOL", "A msg gseq " & $m["gseq"] & " not in GM log (group " & $g & ")"
if t notin ["token", "remove"] and "\"" & other & "\"" in $m: fail "OTHER_PLAYER", other & " mentioned in " & $m
case t
of "hello": (if m["tokens"] != %[me]: fail "OTHER_PLAYER", "hello tokens " & $m["tokens"])
of "token":
let id = m["id"].getStr
if id notin truth: fail "HIDDEN_TOKEN", "unknown token " & id; continue
if vec(m["pos"]) != truth[id]: fail "OWN_VIEW", "token " & id & " pos != truth at g=" & $g
if m["mine"].getBool != (id == me): fail "OTHER_PLAYER", "mine flag " & id
if id != other and m{"by"}.getStr == other: fail "OTHER_PLAYER", other & " leak via by on " & id
if id != me and side(poly, truth[id]) == Out: leaked.incl id; fail "HIDDEN_TOKEN", "LEAK token " & id & " outside A vision at g=" & $g
view[id] = vec(m["pos"]); seen.incl id
of "remove":
let id = m["id"].getStr
if id notin view: fail "PROTOCOL", "remove of unknown " & id
if id in truth and side(poly, truth[id]) == In: fail "WITHHELD", "remove of token still visible " & id
view.del id; inc removes
of "vision":
let ps = m["polys"]
for q in ps:
if same(q, polyO): fail "OTHER_PLAYER", "vision carries " & other & "'s polygon at g=" & $g
if ps.len != 1 or ps[0].len != poly.len: fail "OWN_VIEW", "vision shape at g=" & $g; continue
if not same(ps[0], poly): fail "OWN_VIEW", "vision vertex differs at g=" & $g
of "explored":
for c in m["cells"]:
let k = c[1].getInt * cw + c[0].getInt
if firstG.getOrDefault(k, int.high) > g: fail (if k in oFirst: "OTHER_PLAYER" else: "EXPLORED"), "LEAK explored cell not yet explored " & $c
aExp.incl k
else: discard
if aExp.len != expN: fail "EXPLORED", "explored count at g=" & $g & ": A " & $aExp.len & " expected " & $expN
for id, p in truth:
let s = side(poly, p)
if s == Amb and id != me: continue
let want = id == me or s == In
if want != (id in view): fail (if want: "WITHHELD" elif id in leaked: "HIDDEN_TOKEN" else: "NO_REMOVE"), "view mismatch " & id & " want=" & $want & " at g=" & $g
elif want and view[id] != p: fail "OWN_VIEW", "view pos stale " & id & " at g=" & $g
var curG = -1
for m in gm:
let g = m["gseq"].getInt
if curG >= 0 and g != curG: finalize(curG)
curG = g
case m["t"].getStr
of "hello": tileSize = m["tileSize"].getInt; cell = m["exploredCell"].getInt; cw = (m["world"]["w"].getInt + cell - 1) div cell
of "walls":
for w in m["walls"]: walls.add Wall(a: vec(w["a"]), b: vec(w["b"]), door: w["door"].getBool, open: w["open"].getBool)
of "door": walls[m["id"].getInt].open = m["open"].getBool
of "token": truth[m["id"].getStr] = vec(m["pos"])
else: discard
finalize(curG)
if ai < am.len: fail "PROTOCOL", "A messages after last GM gseq: " & $am[ai]
var n200, n403, nOther: int
for t in tiles:
let g = t["g"].getInt
var exp = false
let per = tileSize div cell
for cy in t["y"].getInt * per ..< (t["y"].getInt + 1) * per:
for cx in t["x"].getInt * per ..< (t["x"].getInt + 1) * per:
if firstG.getOrDefault(cy * cw + cx, int.high) <= g: exp = true
let s = t["s"].getInt
if s == 200: inc n200 elif s == 403: inc n403 else: inc nOther
if s != (if exp: 200 else: 403): fail "TILE", "tile " & $t["x"] & "_" & $t["y"] & " g=" & $g & " (" & t["label"].getStr & ") status " & $s & " expected " & (if exp: "200" else: "403")
# coverage: the scripted path must actually exercise enter/leave
for id in (if me == "A": @["M1", "M2", "B", "M5"] else: @["A", "M5"]):
if id notin seen: fail "WITHHELD", "scenario never showed subject token " & id
if removes < (if me == "A": 3 else: 1): fail "NO_REMOVE", "only " & $removes & " removes"
for c, n in classes: echo "FAILCLASS ", c, " ", n
echo "leakcheck: ", groups, " gseq groups, subject msgs ", am.len, ", tokens seen ", seen.len - 1, " others, removes ", removes,
", tiles ", tiles.len, " (200:", n200, " 403:", n403, " other:", nOther, "), explored cells ", expN, ", failures ", fails
quit(if fails > 0: 1 else: 0)
+11
View File
@@ -0,0 +1,11 @@
#!/bin/sh
# usage: tools/leaktest.sh -> results/leak-{A,B}.log (driver + checker output) and .jsonl (transcript), one pair per subject
cd "$(dirname "$0")/.." || exit 1
mkdir -p results run/test
nim c -d:release --hints:off -o:run/test/leakcheck tools/leakcheck.nim >/dev/null || exit 1
for s in A B; do
SUBJECT=$s tools/withserver.sh sh -c 'node tools/leak.mjs && run/test/leakcheck' > results/leak-$s.log 2>&1; rc=$?
cp run/test/leak-transcript.jsonl results/leak-$s.jsonl
echo "== SUBJECT=$s"; cat results/leak-$s.log
[ $rc = 0 ] || exit 1
done
+17
View File
@@ -0,0 +1,17 @@
// shared by leak.mjs / concurrency.mjs. Node 22 WebSocket (undici) accepts {headers}.
import fs from 'node:fs'
export const RUN = process.env.RUN_DIR ?? 'run'
export const O = `http://localhost:${process.env.PORT ?? 8080}`
export const inv = Object.fromEntries(fs.readFileSync(`${RUN}/invites.txt`, 'utf8').trim().split('\n').map(l => l.split(' ')))
export const sleep = ms => new Promise(r => setTimeout(r, ms))
export const login = async role => (await fetch(inv[role], { redirect: 'manual' })).headers.get('set-cookie').split(';')[0]
// resolves once hello+initial state arrived (socket quiet for 300 ms)
export async function connect(role, onMsg) {
const cookie = await login(role)
const ws = new WebSocket(O.replace('http', 'ws') + '/ws', { headers: { Cookie: cookie } })
let last = Date.now()
ws.onmessage = e => { last = Date.now(); onMsg(JSON.parse(e.data), Buffer.byteLength(e.data)) }
await new Promise((res, rej) => { ws.onopen = res; ws.onerror = rej })
while (Date.now() - last < 300) await sleep(50)
return { ws, cookie }
}
+29
View File
@@ -0,0 +1,29 @@
#!/bin/sh
# usage: tools/mutation.sh mutation check of src/geometry.nim on a TEMP COPY (src/ is never touched).
# Control (unmutated copy) must pass; each mutation must fail >=1 of the corner tests in $NEW.
# Logs: results/mutation-{a,b,c}.log (a: no +-RayEps rays; b: upper segment end exclusive; c: lower end exclusive).
# Segment-end inclusion lives only in rayHit (visibility); moveBlocked's segsCross is a separate, intentionally inclusive test.
cd "$(dirname "$0")/.." || exit 1
mkdir -p results
NEW="shared endpoint: no leak at the vertex|'<' apex|every segment endpoint|rays nudged past a corner"
T=$(mktemp -d); trap 'rm -rf $T' EXIT
rc=0
run() { # $1 id $2 title $3 sed script ("" = control)
rm -rf $T/w; mkdir -p $T/w; cp -r src tests data nim.cfg $T/w/; rm -f $T/w/tests/tgeometry
[ -n "$3" ] && sed -i "$3" $T/w/src/geometry.nim
L=results/mutation-$1.log
{ echo "# mutation $1: $2"; echo "# run on a temp copy; diff orig -> mutated src/geometry.nim:"
diff src/geometry.nim $T/w/src/geometry.nim | sed 's/^/# /'; echo; } > $L
(cd $T/w && nim c -r --hints:off --nimcache:$T/nc tests/tgeometry.nim) >> $L 2>&1; r=$?
F=$(grep '\[FAILED\]' $L | grep -E "$NEW")
{ echo; echo "# test exit=$r"; echo "# NEW tests failed:"; echo "${F:-(none)}"; } >> $L
if [ -z "$3" ]; then [ $r -eq 0 ] || { echo "control FAILED"; rc=1; }
else [ -n "$F" ] || { echo "mutation $1 SURVIVED"; rc=1; }; fi
echo "$1: exit=$r newfailed=$(echo "$F" | grep -c .)"
}
run control "unmutated copy (must pass)" ""
run a "remove the +-RayEps rays" '/angles.add ang [-+] RayEps/d'
run b "upper segment end exclusive" 's/u <= 1 + Eps/u < 1 - Eps/'
run c "lower segment end exclusive" 's/u >= -Eps/u > Eps/'
rm -f results/mutation-control.log
exit $rc
+85
View File
@@ -0,0 +1,85 @@
// Restart durability: mutate, stop the server (SIGTERM, then SIGKILL), restart on the same DB, compare everything.
// Run via `NOSERVE=1 tools/withserver.sh node tools/restart.mjs` (withserver only builds run/test/server). Talks to the backend directly.
import fs from 'node:fs'
import { spawn } from 'node:child_process'
process.env.PORT = process.env.BACKEND_PORT // lib.mjs: origin = backend port (no nginx needed for ws/join)
const RUN = process.env.RUN_DIR
const sleep = ms => new Promise(r => setTimeout(r, ms))
let fails = 0
const check = (c, m) => { console.log(c ? 'PASS' : 'FAIL', m); if (!c) fails++ }
let proc
const start = async () => {
fs.writeFileSync(`${RUN}/server.log`, '', { flag: 'a' })
proc = spawn(`./${RUN}/server`, { env: process.env, stdio: ['ignore', fs.openSync(`${RUN}/server.log`, 'a'), 'inherit'] })
for (let i = 0; i < 100 && !fs.readFileSync(`${RUN}/server.log`, 'utf8').includes('listening'); i++) await sleep(100)
await sleep(200)
}
const stop = sig => new Promise(res => { proc.once('exit', res); proc.kill(sig) })
const invites = () => fs.readFileSync(`${RUN}/invites.txt`, 'utf8')
// reduce a connection's messages to comparable state (gseq is in-memory only, so it is not compared)
async function view(role, keep) {
const st = { toks: {}, doors: {}, explored: new Set(), poly: '[]', hello: null }
const c = await connect(role, m => {
switch (m.t) {
case 'hello': st.hello = JSON.stringify({ ...m, gseq: 0 }); break
case 'walls': for (const w of m.walls) if (w.door) st.doors[w.id] = w.open; break
case 'door': st.doors[m.id] = m.open; break
case 'vision': st.poly = JSON.stringify(m.polys); break
case 'explored': for (const x of m.cells) st.explored.add(x + ''); break
case 'token': st.toks[m.id] = m.pos + ''; break
case 'remove': delete st.toks[m.id]; break
}
})
if (!keep) c.ws.close()
return { st, c }
}
const norm = st => JSON.stringify({ ...st, explored: [...st.explored].sort(), toks: Object.entries(st.toks).sort(), doors: Object.entries(st.doors).sort() })
const snap = async () => { const o = {}; for (const r of ['gm', 'A', 'B']) o[r] = norm((await view(r)).st); return o }
let req = 0
async function mutate(steps) {
const C = {}, acks = new Map()
for (const r of ['gm', 'A', 'B']) C[r] = await connect(r, m => { if (m.t === 'moveAck') acks.get(m.reqId)?.(m) })
for (const [who, id, pos] of steps) {
if (who === 'door') { C.gm.ws.send(JSON.stringify({ t: 'door', id, open: pos })); await sleep(100); continue }
const r = ++req
const p = new Promise(res => acks.set(r, res)); C[who].ws.send(JSON.stringify({ t: 'move', reqId: r, id, pos }))
check((await p).ok, `move ${id} -> ${pos}`)
}
await sleep(200)
const live = {} // the long-lived clients' own accumulated view is not tracked; fresh views are the reference
for (const r of ['gm', 'A', 'B']) C[r].ws.close()
return live
}
async function cycle(label, steps, sig) {
await mutate(steps)
const before = await snap(), inv = invites()
await stop(sig)
await start()
const after = await snap()
check(invites() === inv, `${label}: invite secrets identical`)
for (const r of ['gm', 'A', 'B']) check(before[r] === after[r], `${label}: ${r} state identical after ${sig} restart`)
return after
}
await start()
const { connect } = await import('./lib.mjs') // lib reads invites.txt at import, so only after the first start
const s0 = await snap()
const a = JSON.parse(s0.A), g = JSON.parse(s0.gm)
const sA = await cycle('cycle1', [['A', 'A', [400, 800]], ['A', 'A', [800, 800]], ['A', 'A', [800, 640]], ['A', 'A', [1000, 640]], ['A', 'A', [1510, 640]],
['B', 'B', [700, 2300]], ['gm', 'M1', [900, 640]], ['gm', 'M2', [2200, 300]], ['door', 10, true], ['door', 27, false],
['A', 'A', [1700, 640]]], 'SIGTERM')
const a1 = JSON.parse(sA.A), g1 = JSON.parse(sA.gm)
check(a1.explored.length > a.explored.length, `A explored new area (${a.explored.length} -> ${a1.explored.length})`)
check(g1.toks.find(t => t[0] === 'A')[1] === '1700,640' && g1.toks.find(t => t[0] === 'B')[1] === '700,2300' && g1.toks.find(t => t[0] === 'M2')[1] === '2200,300', 'cycle1: token positions are the moved ones')
check(g1.doors.find(d => d[0] === '10')[1] === true && g1.doors.find(d => d[0] === '27')[1] === false, 'cycle1: door states are the toggled ones')
check(JSON.stringify(g.doors) !== JSON.stringify(g1.doors), 'cycle1: doors differ from initial (test is not vacuous)')
const sB = await cycle('cycle2', [['A', 'A', [1900, 640]], ['B', 'B', [1000, 2300]], ['gm', 'M1', [1200, 640]], ['door', 10, false], ['door', 27, true]], 'SIGKILL')
check(JSON.parse(sB.A).explored.length > a1.explored.length, 'cycle2: A explored more before kill -9')
check(JSON.parse(sB.B).explored.length > JSON.parse(sA.B).explored.length, 'cycle2: B explored more before kill -9')
await stop('SIGKILL')
console.log(fails ? `restart: FAILED ${fails}` : 'restart: PASS')
process.exit(fails ? 1 : 0)
+53
View File
@@ -0,0 +1,53 @@
// node tools/smoke.mjs [pos] -- needs server+nginx up. Node 22 WebSocket (undici) accepts {headers}.
import fs from 'node:fs'
const O = `http://localhost:${process.env.PORT ?? 8080}`
const RUN = process.env.RUN_DIR ?? 'run'
const inv = Object.fromEntries(fs.readFileSync(`${RUN}/invites.txt`, 'utf8').trim().split('\n').map(l => l.split(' ')))
const ok = (c, m) => { console.log(c ? 'PASS' : 'FAIL', m); if (!c) process.exitCode = 1 }
const join = async u => { const r = await fetch(u, { redirect: 'manual' }); return r }
const ws = (cookie, ms = 800) => new Promise(res => {
const msgs = [], s = new WebSocket(O.replace('http', 'ws') + '/ws', { headers: cookie ? { Cookie: cookie } : {} })
s.onmessage = e => msgs.push(JSON.parse(e.data))
s.onerror = () => res({ s, msgs, failed: true })
setTimeout(() => res({ s, msgs, failed: false }), ms)
})
const nextAck = (s, reqId) => new Promise(res => s.addEventListener('message', function f(e) { const m = JSON.parse(e.data); if (m.t === 'moveAck' && m.reqId === reqId) { s.removeEventListener('message', f); res(m) } }))
const r1 = await join(inv.A.replace('A ', ''))
const cookie = r1.headers.get('set-cookie')?.split(';')[0]
if (process.argv[2] === 'pos') {
const a = await ws(cookie); console.log('A pos', a.msgs.find(m => m.t === 'token' && m.id === 'A').pos); process.exit()
}
ok(r1.status === 302 && /HttpOnly/i.test(r1.headers.get('set-cookie')) && /SameSite=Strict/i.test(r1.headers.get('set-cookie')), 'join A: 302 + HttpOnly SameSite cookie')
ok((await join(`${O}/join/deadbeef`)).status === 403, 'bad secret 403')
ok((await ws(null)).failed, 'ws without cookie refused')
ok((await ws('sid=nope')).failed, 'ws bad cookie refused')
const a = await ws(cookie)
const types = a.msgs.map(m => m.t)
console.log('player A msgs:', types.join(','))
ok(types[0] === 'hello' && a.msgs[0].role === 'player' && a.msgs[0].tokens[0] === 'A', 'hello first, player owns A')
ok(!types.includes('walls') && !types.includes('door'), 'no walls/door to player')
ok(types.includes('vision') && types.includes('explored'), 'vision + explored sent')
const toks = a.msgs.filter(m => m.t === 'token')
ok(toks.length === 1 && toks[0].id === 'A' && toks[0].mine, 'only own token visible')
const get = (p, c = cookie) => fetch(O + p, { headers: { Cookie: c } })
const t1 = await get('/tiles/1_1.png'); const b1 = await t1.arrayBuffer()
ok(t1.status === 200 && b1.byteLength > 100 && !t1.headers.get('x-accel-redirect'), `explored tile 200, ${b1.byteLength} bytes`)
ok((await get('/tiles/15_15.png')).status === 403, 'unexplored tile 403')
ok((await fetch(`${O}/tiles/1_1.png`)).status === 403, 'tile without cookie 403')
ok((await fetch(`${O}/_tiles/1_1.png`, { headers: { Cookie: cookie } })).status === 404, '/_tiles not reachable directly')
ok([400, 404].includes((await get('/tiles/..%2f..%2fscene.json')).status), 'path trick rejected')
const gmc = (await join(inv.gm)).headers.get('set-cookie').split(';')[0]
ok((await get('/tiles/15_15.png', gmc)).status === 200, 'GM gets any tile')
a.s.send(JSON.stringify({ t: 'move', reqId: 1, id: 'B', pos: [1, 1] }))
a.s.send(JSON.stringify({ t: 'door', id: 10, open: true }))
a.s.send('garbage{')
await new Promise(r => setTimeout(r, 300))
ok(a.msgs.filter(m => m.t === 'error').length === 3, 'steal/door/garbage -> 3 errors')
let p = nextAck(a.s, 2); a.s.send(JSON.stringify({ t: 'move', reqId: 2, id: 'A', pos: [1100, 400] }))
ok(!(await p).ok, 'move through wall rejected')
p = nextAck(a.s, 3); a.s.send(JSON.stringify({ t: 'move', reqId: 3, id: 'A', pos: [500, 450] }))
const ack = await p; ok(ack.ok && ack.pos[0] === 500, 'legal move acked')
const g = await ws(gmc)
ok(g.msgs.some(m => m.t === 'walls') && !g.msgs.some(m => m.t === 'explored') && g.msgs.filter(m => m.t === 'token').length === 8, 'GM: walls, all 8 tokens, no explored')
process.exit()
+17
View File
@@ -0,0 +1,17 @@
#!/bin/sh
# usage: tools/withserver.sh cmd... isolated stack in run/test (own DB/invites/nginx conf+logs/binary), own ports TEST_PORT (nginx, 18088) + TEST_BACKEND_PORT (server, 19000); never touches live run/ or :8088/:9000. SIGINT => server prints STATS
cd "$(dirname "$0")/.." || exit 1
export RUN_DIR=run/test PORT=${TEST_PORT:-18088} BACKEND_PORT=${TEST_BACKEND_PORT:-19000}
R=$RUN_DIR
case "$PORT:$BACKEND_PORT" in 8088:*|*:9000|*:8088) echo "withserver: refusing live port (8088/9000)" >&2; exit 1;; esac
mkdir -p $R/temp client/dist
rm -f $R/state.db* $R/invites.txt
nim c -d:release $SERVER_FLAGS --nimcache:$R/nimcache$(echo $SERVER_FLAGS | tr -dc a-z) --hints:off --nimblePath:"${NIMBLE_DIR:-.devbox/nimble}/pkgs2" -o:$R/server src/server.nim >/dev/null || exit 1
sed -e "s/NGX_PORT/$PORT/" -e "s/NGX_BACKEND/$BACKEND_PORT/" -e "s#run/#$R/#g" -e "s#\.\./nginx/mime#$PWD/nginx/mime#" nginx/nginx.conf > $R/nginx.conf
if [ -z "$NOSERVE" ]; then # NOSERVE=1: build only, the command starts/stops the server itself (tools/restart.mjs)
./$R/server > $R/server.log 2>&1 & S=$!
nginx -p "$PWD/" -c $R/nginx.conf -e $R/error.log > $R/nginx.out 2>&1 & N=$!
trap 'kill -INT $S; sleep 1; kill $N 2>/dev/null' EXIT
for i in $(seq 50); do [ -s $R/invites.txt ] && curl -s -o /dev/null "localhost:$PORT/" && break; sleep 0.2; done
fi
"$@"
+10
View File
@@ -0,0 +1,10 @@
.devbox/
nimble.paths
data/
run/
bin/
nimble.develop
nimbledeps
devbox.d/
node_modules/
dist/
+170
View File
@@ -0,0 +1,170 @@
# prototype-tile-leak (throwaway): DESIGN.md Q4 / H8 / T5, tile-edge leak
## Question
DESIGN 3.3: a 256 px tile is served iff >=1 explored 32 px cell overlaps it, so up to 255x255 px of unexplored art reaches the browser (devtools). Which fix is cheapest: (A) server-side per-player masked 256 px tiles, or (B) tiles the size of an explored cell (32 px; 64 px for comparison) served as-is?
**Fact, not prototyped:** client-side fog, flattening or masking cannot fix this. The bytes are already in the browser (network tab, cache, decoded texture) before any client code runs. Only what the server sends counts.
## Method
- Art: procedural pure function of world coords (`src/art.nim`), so every tile size slices the same picture. Two noise levels bracket real art: `g6` (smooth, 256 px PNG ~83 KB) and `g40` (grainy, ~133 KB). **Synthetic: absolute sizes/ms depend on real art, ratios are what matter.**
- A: `src/maskbench.nim`. Decode PNG, set unexplored 32 px cells to opaque black (0,0,0,255), encode. Median of 200 runs, single thread, `-d:release`. Then replay of the real explored transcripts of `prototype-server-vision/results/leak-A.jsonl` (subjects A: 94 explored msgs, 2142 cells; B: 39 msgs, 1114 cells) on the 4096 px / 256 px-tile / 32 px-cell scene: every tile whose mask changed is re-masked for real.
- B: `src/gen.nim` slices the 4096 px map into 32/64/256 px PNG files, measures disk. `src/authsrv.nim` (mummy, same shape as the vision prototype tile route: strict path parse, cookie lookup, explored-cell range check under a lock, `X-Accel-Redirect`) behind nginx (4 workers, `internal` alias). Load by `h2load` (nghttp2) on loopback, `tools/netbench.sh`. Requests/step computed by replaying the same transcripts.
- Machine: AMD Ryzen 7 7840U, 16 threads, NixOS, kernel 6.18, governor left on `powersave` (as in the other prototypes). Page cache hot (cold disk not measured). Run-to-run noise on req/s is roughly +-30%.
- Lib check (pixie 6.1.0, nimPNG 0.3.6): APIs checked in source + context7 docs, not memory.
## Library choice (A)
| | pixie 6.1.0 | nimPNG 0.3.6 |
|---|---|---|
| dec+mask+enc, 1..63 of 64 cells explored | 1.6..10.9 ms | 9.3..26.5 ms |
| output size vs pixie | baseline | 5-25% smaller (auto palette/gray, MINSUM filter); all-black tile 88 B vs 853 B |
| deps | 7 pure-Nim pkgs (vmath chroma bumpy flatty zippy nimsimd crunchy), ~1.4 MB source | 0, ~0.24 MB source |
Pick **pixie**: 2-3x faster, `decodePng`/`encodePng` expose raw RGBA so masking is a plain loop; nimPNG only if bytes matter more than CPU. No C libs in either (devbox stays minimal). Pixie has no compression-level knob via `encodePng` (zippy default). [MEASURED `results/maskbench.log`]
## Numbers
### A. Masked 256 px tiles (MEASURED, `results/maskbench.log`)
Per tile, pixie, ms (out bytes), explored cells of 64:
| cells | g6 ms (B) | g40 ms (B) |
|---|---|---|
| 0 | 1.5 (853) | 1.8 (853) |
| 1 | 1.7 (3.2K) | 1.9 (4.0K) |
| 8 | 2.4 (12.7K) | 2.5 (19.7K) |
| 32 | 6.0 (43.6K) | 5.5 (69.0K) |
| 63 | 10.9 (82.2K) | 9.5 (131.5K) |
| 64 (all) | 0: serve the original file, no image work | 0 |
Decode alone 0.8-1.0 ms; encode dominates (8-10 ms for a full tile). Exact-polygon variant (naive per-pixel even-odd, 32-gon): 6.3-6.7 ms, an upper bound, a scanline fill would be about cell-mask cost.
Replay, subject A (B similar), 4096 px map, g6 / g40:
- tiles touched 71 (of 256); **366 re-masks in 94 steps = 3.9 tiles/step avg (max 13, the connect burst)**; CPU **20 ms/step avg, worst 70 ms**, per-step cost parallelisable over tiles, must run outside the state lock (vision recompute for comparison: 1.18 ms/move).
- Bytes to client: masked **13.1 / 20.7 MB** vs whole-tile 5.8 / 9.5 MB (each tile once) = **x2.0-2.2**, because every tile whose mask grows must be refetched (new URL/version per tile, client must be told which tiles changed: protocol + client change).
- Per-player cache of final masked tiles: A **2.9 / 4.6 MB** (71 tiles, ~41-65 KB each), B 1.5 / 2.4 MB (35 tiles). It scales with explored area, not map size. 16384 px map (4096 tiles) worst case if every tile were partial: <= the original art, 340-545 MB per player [INFERRED, = 4096 x tile size]. Old versions evictable.
- Re-mask when explored grows: only tiles whose cell set changed (above), results keyed (tile, mask-hash) so reconnects/other connections of the same player are free.
- Leak assert (MEASURED): for n in {0,1,8,32,63} cells, through pixie AND nimPNG, a 8x8 pure-red "secret" is planted in every unexplored cell; asserts: no red pixel in output, every unexplored pixel == (0,0,0,255), every explored pixel identical to source. Pass.
### B. Cell-size tiles
Tile counts [arithmetic]: 4096 px map: 32 px 16,384 / 64 px 4,096 / 256 px 256. 16384 px map: **262,144 / 65,536 / 4,096**.
Disk, 4096 px map, MEASURED (`results/disk4096.log`); 16384 px = x16 [INFERRED]. "on-disk" = 4 KiB filesystem blocks (ext4):
| tile | files | apparent g6 / g40 | on-disk g6 / g40 | 16384 px apparent g6/g40 | 16384 px on-disk g6/g40 |
|---|---|---|---|---|---|
| 256 | 256 | 21.1 / 34.1 MB | 21.2 / 33.8 MB | 337 / 545 MB | 339 / 541 MB |
| 64 | 4,096 | 24.6 / 38.6 MB (+17/+13%) | 32.9 / 49.3 MB | 393 / 618 MB | 526 / 788 MB |
| 32 | 16,384 | 28.4 / 43.5 MB (+35/+28%) | 66.0 / 66.0 MB | 454 / 696 MB | 1.06 GB (262k inodes) |
Small PNGs lose compression context and pay ~60 B header + one 4 KiB block each; no image work at serve time.
Requests per exploration step, MEASURED by transcript replay (`results/steps.log`), NEW tiles per step (a cell tile is fetched once, never again):
| | connect burst | steady median | p95 | max | total (A, 94 steps) |
|---|---|---|---|---|---|
| 32 px | 292 | 11 | 37 | 164 | 2142 |
| 64 px | 87 | 3 | 11 | 46 | 603 |
| 256 px whole (today) | 13 | 0 | 3 | 6 | 71 |
| 256 px masked (refetch on change) | - | - | - | 13 | 366 |
Bytes for A: 32 px 3.7 / 5.7 MB, 64 px 3.6 / 5.7 MB (count x avg tile bytes, g6 / g40) vs whole-256 5.8 / 9.5 MB vs masked-256 13.1 / 20.7 MB. Cell tiles send LESS than today, masking sends 2x more.
Serving, MEASURED (`results/netbench.log`), loopback, 20000 reqs, nginx -> Nim auth -> X-Accel-Redirect, upstream keepalive on:
| case | req/s | median / p99 |
|---|---|---|
| 32 px h1 c=1 (unloaded) | 10.4k | 90 us / 149 us |
| 256 px h1 c=1 (unloaded) | 7.2k | 132 us / 211 us |
| 32 px h1 c=6 (browser-like) | 46k | 122 us / 188 us |
| 64 px h1 c=6 | 45k | 127 us / 213 us |
| 256 px h1 c=6 | 19k | 296 us / 636 us (byte bound, ~83 KB each) |
| 32 px h1 c=32 | 54k | 480 us / 724 us |
| 32 px STATIC (no Nim, no auth) h1 c=32 | 87k | 332 us / 534 us |
| 32 px h2 c=1 m=100 | 18.6k | 5.1 ms / 8.9 ms (queued 100 deep) |
| 32 px h2 c=4 m=100 | 19.9k | 5.6 ms / 25 ms |
| burst 292 x 32 px, h1 c=6 | 7-16 ms wall (3 runs) | |
| burst 292 x 32 px, h2 c=1 m=100 | ~16-22 ms wall | |
| upstream keepalive off, 32 px h1 c=32 | 55k | same as on (loopback connect is cheap) |
- Nim auth hop costs ~35% throughput vs static nginx (54k vs 87k) and ~50 us unloaded, still 1000x the need (steady 11 req/step).
- HTTP/2 on loopback: **no gain** (one h2 connection is served by one nginx worker, ~20k req/s; h1 c=32 spreads over 4 workers). Loopback has RTT ~0, so the real h2 benefit (no 6-connection limit) is **not measurable here**. INFERRED: burst of 292 over h1 with 6 conns = ~49 round trips, ~2.4 s at 50 ms RTT, vs ~1-2 RTT + transfer on h2. TLS not measured. Needs h2 in the real nginx (HTTPS deploy gets it with `http2 on`). Note nginx default `keepalive_requests 1000` closes the h2 connection; h2load does not reconnect, hence `keepalive_requests 1000000` in the bench conf (a browser reconnects transparently).
- Not measured: client cost of 2142+ small Pixi sprites/textures (INFERRED fine with batching; the client can also blit received cell tiles into one RenderTexture per 256 px block).
### C. Leak bound demo (MEASURED, `devbox run netbench`, first section; asserts exit 1 on mismatch)
Explored = left half + one lone cell (64,3) just outside it; every tile of each size requested; allowed count must be half + 1 (PASS all three).
| tile | unexplored px revealed by the lone cell's tile |
|---|---|
| 32 px | **0** |
| 64 px | 3,072 (3 cells) |
| 256 px (today) | 64,512 (63 cells) |
Masked 256 px: 0 beyond explored cells, asserted pixel-exact in A (above).
## Comparison
| | 256 whole (today) | A masked 256 | B1 32 px tiles | B2 64 px tiles |
|---|---|---|---|---|
| leak beyond explored cells | up to 63 cells/tile | 0 | **0** | <= 3 cells/tile |
| server CPU | 0 | ~20 ms per step (avg), 70 ms burst, pixie | ~0.1 ms/req (auth) | same |
| bytes per run (A) | 5.8-9.5 MB | 13.1-20.7 MB | 3.7-5.7 MB | 3.6-5.7 MB |
| requests per step (median/burst) | 0 / 13 | ~4 / 13 refetch | 11 / 292 | 3 / 87 |
| storage 4096 px | 21-34 MB | + per-player cache 1.5-4.6 MB | 28-43 MB (66 MB on disk) | 25-39 MB (33-49 on disk) |
| storage 16384 px | 340-545 MB | + per-player <= 340-545 MB worst | 454-696 MB, 1.06 GB on disk, 262k files | 393-618 MB, 526-788 MB on disk, 65k files |
| deps / new code | none | pixie (7 pkgs), mask+cache+versioned URLs+refetch protocol | importer cuts 32 px tiles | importer cuts 64 px tiles |
| HTTP/2 needed | no | no | yes (INFERRED) | helpful |
| cacheability | immutable | per-version | immutable, never refetched | same |
## Recommendation
**B1: set `tile_size` = explored cell (32 px).** DESIGN already requires `tile_size % cell == 0`, so this is a scene-config change plus importer slicing; no image library in the server, no per-player state, rule "tile allowed iff its cell is explored" becomes exact (zero beyond-cell leak, MEASURED assert C). Total bytes to the client go DOWN vs today; masking doubles them and costs ~20 ms CPU/step plus a refetch protocol for the same residual leak. Fall back to **64 px** if 262k files / ~1 GB on-disk for a 16384 px map is unwelcome (leak <= 3 cells per allowed tile, 4x fewer files). Keep masking (pixie) only if tiles must stay large for another reason; do not build it for Q4 alone. Require h2 in the nginx config.
**Residual leak (all options, incl. masked):** granularity of fog = the explored cell. A cell the polygon only grazed is disclosed entirely (<= 32x32 px beyond what LOS actually saw), and once sent never revoked. Authoring rule shrinks from "~256 px around reachable areas" to "~32 px". Exact-polygon masking would close it but needs per-pixel explored state and ~same CPU as cell masking (6-7 ms/tile naive), not worth it. Also unchanged: static art only, doors not in tiles.
## Caveats
Synthetic art (real painted maps compress differently; ratios hold, absolutes move). Loopback only: no RTT, no TLS, no real browser; h2 benefit INFERRED. Hot page cache. Single laptop in powersave. 16384 px figures are x16 extrapolations. One scene/one player load; no concurrency mix with WS traffic.
## Run
```
cd prototype-tile-leak
devbox run setup # nimble setup (fetches pixie, nimPNG, mummy)
devbox run build # bin/maskbench bin/gen bin/authsrv
devbox run gen # data/g6, data/g40 tiles (~20 s, ~0.3 GB, gitignored) + results/disk4096.log
devbox run maskbench # results/maskbench.log (~30 s)
devbox run netbench # leak-bound demo + h2load matrix -> results/netbench.log
```
`results/steps.log`: `python3 tools/steps.py > results/steps.log` (replays `../prototype-server-vision/results/leak-A.jsonl`; first message = connect burst, excluded from steady stats).
## Phone test (client-side risk of 32 px tiles)
Question: does a Pixi v8 client cope with 32 px tiles (262,144 on a 16384 px map) vs 64 / 256 on a real phone? Unmeasured so far (Q4 "Not measured: client cost").
### Run
```
cd prototype-tile-leak
devbox run phone # first run: npm install + generates 16384 px tiles x {32,64,256} (g6 art, minutes, ~1.1 GB gitignored in data/phone) + builds; then serves
```
Prints `http://<LAN-IP>:8099/` (one line per interface; override with `PORT=`, `WORLD=`; changing WORLD regenerates tiles). Ctrl-C stops. Server: `src/phonesrv.nim`, plain static server (mummy; **no auth, no nginx, no X-Accel**: this tests the client, not the auth path, which `netbench` already covers), binds 0.0.0.0, rejects non-private peers (403), `Cache-Control: no-store` so every load is cold network. NixOS firewall: port 8099/tcp must be open (e.g. temporary `sudo iptables -I nixos-fw -p tcp --dport 8099 -j nixos-fw-accept`, removed with `-D`, or `networking.firewall.allowedTCPPorts`); not changed by this prototype.
`POST /results` (LAN only, JSON object <= 64 KB, whole file <= 2 MB per server run) appends one line per Send to `results/phone-<timestamp>.jsonl`.
### On the phone (~5 min)
1. Open the URL. Overlay top-left. Check `renderer` (webgl/webgpu), `dpr`, UA.
2. Tile size = **32**, **Open map** mode. Pan with one finger for 20 s (long drags, fast flicks), pinch zoom in/out for 10 s. Note moving fps.
3. **Reveal viewport (cold)**: drops all tiles, refetches everything in view; read `viewport loaded ms`. Press 3x, also at zoom 0.5 (worst case, ~1.3k tiles).
4. **Explore: start**: simulated connect burst (~290 cells, one disc) then a step every 400 ms (~11 new cells/step, leak-A median). Let it run 60 s; camera follows, you can still pan/pinch.
5. Pick **64**, repeat 2-4; pick **256**, repeat 2-4. (Switching size stores a snapshot of the previous size.)
6. **Send results** (also snapshots the current size). Check `results/phone-*.jsonl` on the laptop.
### What the numbers mean
- `fps(5s)`: all frames incl. idle (vsync cap: 60 or 120). `moving avg/p5/min`: only frames within 300 ms of a pan/pinch/sim step, accumulated per tile size since selecting it. **p5 = 1000/p95 frame time**, the figure to judge; min = worst single frame.
- `sprites`/`textures`: tile sprites on stage / loaded textures. Only tiles in view + 1 tile margin load; those beyond 2 tiles are released (sprite pooled, texture + source destroyed). Both must stay bounded (~ view area / tile^2) while panning, not grow: growth means a leak.
- `req inflight/done/failed`; cap 24 in flight (browser limits HTTP/1.1 to ~6 per host, so the server hop is HTTP/1.1; real deployment should use h2). `fetch+decode ms` = request to ImageBitmap ready.
- `viewport loaded ms` (ttvl): from click (cold reveal / size change / explore start) until every allowed tile in view is loaded. The explore start value is the connect burst.
- `heap`: only Chrome-based browsers (not iOS Safari). GPU memory is not visible; use `peakTextures` x tile^2 x 4 B as an estimate (32 px: 4 KB each).
- Fog mode: a tile loads iff it overlaps >= 1 revealed 32 px cell (same rule as the server auth), so 256 px mode also loads partly unexplored tiles.
### Proposed pass criteria (32 px, mid-range phone, Wi-Fi)
- moving p5 fps >= 30 while panning at zoom 1 (avg >= 45); no thermal collapse over the 60 s explore run.
- viewport load (cold) < 1 s at zoom 1; connect burst < 2 s.
- failed requests 0; sprites/textures bounded; heap not growing between size switches.
- 32 px not worse than ~1.5x of 64 px on the same metrics. If 32 fails but 64 passes: fall back to 64 px (README recommendation above).
Headless smoke check (server running): `devbox run -- node tools/headless.mjs` (software GL, not representative for fps).
## Phone run 2026-11-08
Device: Android 10, Chrome 157, dpr 2.625, 412x869 CSS px, WebGL. Source: `results/phone-20261108T113701.jsonl` (one line, 3 snaps, open-map mode). One run, 5-year-old phone (worst-case reference).
| tile | zoom | run s | moving fps avg / p5 / min | req done / failed | fetch+decode med / p95 ms | ttvl ms (as logged) | peak sprites | heap MB |
|---|---|---|---|---|---|---|---|---|
| 32 | 0.5 | 109 | 60 / 59.5 / 59.2 | 12094 / 0 | 46 / 75 | 1090, 2882, 3253, 148 | 1420 | ~10 |
| 64 | 0.5 | 37 | 60 / 59.5 / 58.8 | 4588 / 0 | 48 / 125 | 942, 389, 340, 1002, 1006 | 416 | ~10 |
| 256 | 0.6 | 28 | 59.8 / 59.5 / 20 | 404 / 0 | 118 / 220 | 453, 372, 390, 299 | 78 | ~10 |
- 32 px: 60 fps at all snaps, 1420 sprites/textures at zoom 0.5, heap ~10 MB, 0 failed of 12094 requests (17086 requests over all three sizes, 0 failed). Bounded, no growth seen.
- ttvl (cold reveal, size change, explore start; order as logged): 32 px first 1.1 s, worst 3.3 s at zoom 0.5. Transport was HTTP/1.1, `Cache-Control: no-store`, so this is pessimistic against the real path (h2, caching). Zoom 0.5 is the worst case (more tiles in view); the DESIGN gate is zoom 1 on the real path, not measured here.
- 256 px min moving frame 20 fps (single frame, p5 still 59.5): a one-off stall, not a sustained drop. Not investigated.
- Not recorded: zoom 1, explore run (60 s connect burst + steps). Still required by DESIGN 13 M4 (a) and (b).
- Conclusion: 32 px client cost is not the blocker on this phone. Cold viewport load at zoom 1 (< 1 s target) is still unproven.
+4
View File
@@ -0,0 +1,4 @@
# begin Nimble config (version 2)
when withDir(thisDir(), system.fileExists("nimble.paths")):
include "nimble.paths"
# end Nimble config
+41
View File
@@ -0,0 +1,41 @@
{
"$schema": "https://raw.githubusercontent.com/jetify-com/devbox/0.17.2/.schema/devbox.schema.json",
"packages": {
"nim": "2",
"nimble": "latest",
"nginx": "latest",
"nghttp2": "latest",
"curl": "latest",
"nodejs": "latest",
"chromium": "latest"
},
"env": {
"NIMBLE_DIR": "$DEVBOX_PROJECT_ROOT/.devbox/nimble"
},
"shell": {
"init_hook": [],
"scripts": {
"setup": [
"nimble setup -y",
"mkdir -p bin results"
],
"build": [
"for f in maskbench gen authsrv; do nim c -d:release --hints:off --warnings:off -o:bin/$f src/$f.nim || exit 1; done"
],
"gen": [
"bin/gen data/g6 6",
"bin/gen data/g40 40",
"for g in g6 g40; do for s in 256 64 32; do d=data/$g/tiles$s; echo \"$g $s files=$(ls $d | wc -l) apparent=$(du -sb $d | cut -f1) onDisk(4K blocks)=$(du -sk $d | cut -f1)KiB\"; done; done | tee results/disk4096.log"
],
"maskbench": [
"bin/maskbench ../prototype-server-vision/results/leak-A.jsonl | tee results/maskbench.log"
],
"netbench": [
"tools/netbench.sh | tee results/netbench.log"
],
"phone": [
"tools/phone.sh"
]
}
}
}
+589
View File
@@ -0,0 +1,589 @@
{
"lockfile_version": "1",
"packages": {
"chromium@latest": {
"last_modified": "2026-10-08T19:21:32Z",
"resolved": "github:NixOS/nixpkgs/8edc0c72e3a38faf5434e40d1f19431125fe4b30#chromium",
"source": "devbox-search",
"version": "155.0.8059.39",
"systems": {
"aarch64-linux": {
"outputs": [
{
"name": "out",
"path": "/nix/store/q56ri55nzhpwzhisgb2r0kilb61k4f5a-chromium-155.0.8059.39",
"default": true
},
{
"name": "sandbox",
"path": "/nix/store/a1w34yg08mvma03xps5dsy8vw5hrdy9w-chromium-155.0.8059.39-sandbox"
}
],
"store_path": "/nix/store/q56ri55nzhpwzhisgb2r0kilb61k4f5a-chromium-155.0.8059.39"
},
"x86_64-linux": {
"outputs": [
{
"name": "out",
"path": "/nix/store/ky199ji3a5drs6rm3wr5zidamx9dhz56-chromium-155.0.8059.39",
"default": true
},
{
"name": "sandbox",
"path": "/nix/store/5hpd396v5byrfp1vnw7zmpfscqd3b1zv-chromium-155.0.8059.39-sandbox"
}
],
"store_path": "/nix/store/ky199ji3a5drs6rm3wr5zidamx9dhz56-chromium-155.0.8059.39"
}
}
},
"curl@latest": {
"last_modified": "2025-12-05T15:03:55Z",
"resolved": "github:NixOS/nixpkgs/a672be65651c80d3f592a89b3945466584a22069#curl",
"source": "devbox-search",
"version": "8.17.0",
"systems": {
"aarch64-darwin": {
"outputs": [
{
"name": "bin",
"path": "/nix/store/qfwqcndy8bji6xww0gizclf2nqi2qpph-curl-8.17.0-bin",
"default": true
},
{
"name": "man",
"path": "/nix/store/rk815zvrhwzbi7c6d589v2mhxzyzb400-curl-8.17.0-man",
"default": true
},
{
"name": "dev",
"path": "/nix/store/ydp55g2mbd6rk6lfw0krkk3jwgdiqj5d-curl-8.17.0-dev"
},
{
"name": "devdoc",
"path": "/nix/store/8s884m82fmrbiyz8malglqc4sd632dkc-curl-8.17.0-devdoc"
},
{
"name": "out",
"path": "/nix/store/yxv8fxaz0fyhc31dv3rz89kc50zw5hgj-curl-8.17.0"
}
],
"store_path": "/nix/store/qfwqcndy8bji6xww0gizclf2nqi2qpph-curl-8.17.0-bin"
},
"aarch64-linux": {
"outputs": [
{
"name": "bin",
"path": "/nix/store/4x19j6zihdl6pya63xs8g360f2r614sx-curl-8.17.0-bin",
"default": true
},
{
"name": "man",
"path": "/nix/store/b29qbmbfvzkm34k0jnj8ykqg2gzj3rdy-curl-8.17.0-man",
"default": true
},
{
"name": "debug",
"path": "/nix/store/5hmbdk99knmbg8b0fzh96bv6bkcf6v5i-curl-8.17.0-debug"
},
{
"name": "dev",
"path": "/nix/store/iqs9mjscns3h5npgkrhgr5xa7qzwd0si-curl-8.17.0-dev"
},
{
"name": "devdoc",
"path": "/nix/store/1fwncv08c8g78k3hj3cj375vx92ndrp8-curl-8.17.0-devdoc"
},
{
"name": "out",
"path": "/nix/store/b0a6qc92vybjiggh0kg387cg0zp3kl6j-curl-8.17.0"
}
],
"store_path": "/nix/store/4x19j6zihdl6pya63xs8g360f2r614sx-curl-8.17.0-bin"
},
"x86_64-darwin": {
"outputs": [
{
"name": "bin",
"path": "/nix/store/w2336wv560g1n58cwashmmczdn3bfkq1-curl-8.17.0-bin",
"default": true
},
{
"name": "man",
"path": "/nix/store/i6xmhcan8g4abda7ivv20nvwxrsssjqj-curl-8.17.0-man",
"default": true
},
{
"name": "devdoc",
"path": "/nix/store/ipa7v9z7pjcnnv0fmdya1fldcxv0a28z-curl-8.17.0-devdoc"
},
{
"name": "out",
"path": "/nix/store/x9gyg634fi8mgcyay9mqa1ral7xg72fm-curl-8.17.0"
},
{
"name": "dev",
"path": "/nix/store/39zfdgq9kg3mb4sycf8pj4pdssrzki6c-curl-8.17.0-dev"
}
],
"store_path": "/nix/store/w2336wv560g1n58cwashmmczdn3bfkq1-curl-8.17.0-bin"
},
"x86_64-linux": {
"outputs": [
{
"name": "bin",
"path": "/nix/store/0rfz69vp1nl0q2hxzig20hc60sk72z62-curl-8.17.0-bin",
"default": true
},
{
"name": "man",
"path": "/nix/store/ijd0yybyzwm98d3q6x7a9cyixgxk0i5d-curl-8.17.0-man",
"default": true
},
{
"name": "debug",
"path": "/nix/store/h1fxw0xrifxvbhcp7b8hxsgirxxxfzav-curl-8.17.0-debug"
},
{
"name": "dev",
"path": "/nix/store/ikmdk37frjdblkba3wl3xws2wwgln17x-curl-8.17.0-dev"
},
{
"name": "devdoc",
"path": "/nix/store/jm6irg81cc0hqg43l39lkxr6pb0w2xk5-curl-8.17.0-devdoc"
},
{
"name": "out",
"path": "/nix/store/8idis3j5l13c3x74jl8xly0k4qyk9mx6-curl-8.17.0"
}
],
"store_path": "/nix/store/0rfz69vp1nl0q2hxzig20hc60sk72z62-curl-8.17.0-bin"
}
}
},
"gawk@latest": {
"last_modified": "2026-10-02T22:55:44Z",
"resolved": "github:NixOS/nixpkgs/55ba7f49ef2962b42cbd126522b7df5f95037679#gawk",
"source": "devbox-search",
"version": "5.4.1",
"systems": {
"aarch64-darwin": {
"outputs": [
{
"name": "out",
"path": "/nix/store/49jhcfya6jlc7p2hibbl2y5sfz132j3i-gawk-5.4.1",
"default": true
},
{
"name": "man",
"path": "/nix/store/1sclicd2js7iipqnw4vn1rmy3scjg72v-gawk-5.4.1-man",
"default": true
},
{
"name": "info",
"path": "/nix/store/n8gfvirxjm8z5zq7cx30qrmhn40w7jrb-gawk-5.4.1-info"
}
],
"store_path": "/nix/store/49jhcfya6jlc7p2hibbl2y5sfz132j3i-gawk-5.4.1"
},
"aarch64-linux": {
"outputs": [
{
"name": "out",
"path": "/nix/store/2bwpli20ff4f7hg5ck477p8s57kj857w-gawk-5.4.1",
"default": true
},
{
"name": "man",
"path": "/nix/store/wfnxkfk386wl2plrhqx7lwfj4z84r493-gawk-5.4.1-man",
"default": true
},
{
"name": "info",
"path": "/nix/store/l6wddbkc3rxavhbxyl48gn47rw8fq0pd-gawk-5.4.1-info"
}
],
"store_path": "/nix/store/2bwpli20ff4f7hg5ck477p8s57kj857w-gawk-5.4.1"
},
"x86_64-linux": {
"outputs": [
{
"name": "out",
"path": "/nix/store/63g104xwbzfpcq0h7c99w19m6j9ly3p1-gawk-5.4.1",
"default": true
},
{
"name": "man",
"path": "/nix/store/0azvqykndxs3clnj974q99cjfnmpprjv-gawk-5.4.1-man",
"default": true
},
{
"name": "info",
"path": "/nix/store/l4pwpdc6hrgy8n3diy24n389k53jqqjk-gawk-5.4.1-info"
}
],
"store_path": "/nix/store/63g104xwbzfpcq0h7c99w19m6j9ly3p1-gawk-5.4.1"
}
}
},
"gettext@latest": {
"last_modified": "2026-10-02T22:55:44Z",
"resolved": "github:NixOS/nixpkgs/55ba7f49ef2962b42cbd126522b7df5f95037679#gettext",
"source": "devbox-search",
"version": "1.0",
"systems": {
"aarch64-darwin": {
"outputs": [
{
"name": "out",
"path": "/nix/store/d73j7348argskpyvj28wq8n65mj6yg9x-gettext-1.0",
"default": true
},
{
"name": "man",
"path": "/nix/store/arv8546qvpn8cr2bsgvzbzzzypmdv1kp-gettext-1.0-man",
"default": true
},
{
"name": "doc",
"path": "/nix/store/4myr9gbsxvryjnwanyyhnnpqrdh56d5n-gettext-1.0-doc"
},
{
"name": "info",
"path": "/nix/store/b4d4imijjkkzr49zh5mq4gz2j9m2s047-gettext-1.0-info"
}
],
"store_path": "/nix/store/d73j7348argskpyvj28wq8n65mj6yg9x-gettext-1.0"
},
"aarch64-linux": {
"outputs": [
{
"name": "out",
"path": "/nix/store/8aimx510wyy0rzy7mllcjad5299jd17a-gettext-1.0",
"default": true
},
{
"name": "man",
"path": "/nix/store/qllbgswyx416d7r7kqkyxvafpfbasmr8-gettext-1.0-man",
"default": true
},
{
"name": "doc",
"path": "/nix/store/r2d6saacyqv8m9d8bvaidv4x2raqjb7z-gettext-1.0-doc"
},
{
"name": "info",
"path": "/nix/store/hsrnhwfpvrs4x4a5807cprpyz4qclgxy-gettext-1.0-info"
}
],
"store_path": "/nix/store/8aimx510wyy0rzy7mllcjad5299jd17a-gettext-1.0"
},
"x86_64-darwin": {
"outputs": [
{
"name": "out",
"path": "/nix/store/9mxzw5vwn99vx2b74ipjzk8x4b784fjy-gettext-1.0",
"default": true
},
{
"name": "man",
"path": "/nix/store/r87hlf9pn8q3a8rnplzhy9lbgaadqcr8-gettext-1.0-man",
"default": true
},
{
"name": "doc",
"path": "/nix/store/xmssbi5i2w3fv67hrv6c29wdiv8gxywi-gettext-1.0-doc"
},
{
"name": "info",
"path": "/nix/store/j4lz4zqicd1mw2l5c272ialxhl0nkc0b-gettext-1.0-info"
}
],
"store_path": "/nix/store/9mxzw5vwn99vx2b74ipjzk8x4b784fjy-gettext-1.0"
},
"x86_64-linux": {
"outputs": [
{
"name": "out",
"path": "/nix/store/gfkkr23q11kvyz6xxyxz3qbsp1msxdcv-gettext-1.0",
"default": true
},
{
"name": "man",
"path": "/nix/store/njdszjnrb0n7c6m6jzmx5539ac0ybn9g-gettext-1.0-man",
"default": true
},
{
"name": "doc",
"path": "/nix/store/z2p7kr1a45gz9m9g3s6rary2avk3gs9x-gettext-1.0-doc"
},
{
"name": "info",
"path": "/nix/store/8vqnaf3h4vlb8q5w9z9kscqld7m5rdif-gettext-1.0-info"
}
],
"store_path": "/nix/store/gfkkr23q11kvyz6xxyxz3qbsp1msxdcv-gettext-1.0"
}
}
},
"github:NixOS/nixpkgs/nixpkgs-unstable": {
"last_modified": "2026-10-20T14:23:57Z",
"resolved": "github:NixOS/nixpkgs/5adc50831c259f87faeb09ddf930d43597197473?lastModified=1792506237&narHash=sha256-Q%2F8KLB6jNfpaUN1HAedE%2Fu%2FEt9feE%2FzYSsutBLKrCFk%3D"
},
"nghttp2@latest": {
"last_modified": "2026-10-08T19:21:32Z",
"resolved": "github:NixOS/nixpkgs/8edc0c72e3a38faf5434e40d1f19431125fe4b30#nghttp2",
"source": "devbox-search",
"version": "1.70.0",
"systems": {
"aarch64-darwin": {
"outputs": [
{
"name": "out",
"path": "/nix/store/8p19fbn4slkvk18j3bvjjh4yhp0d32wf-nghttp2-1.70.0",
"default": true
},
{
"name": "man",
"path": "/nix/store/ijqj81fibram571b285bv0knwz5r3qki-nghttp2-1.70.0-man",
"default": true
},
{
"name": "dev",
"path": "/nix/store/idl71hpg6zlvwdm4flp2hr9pxmxw6ppr-nghttp2-1.70.0-dev"
},
{
"name": "doc",
"path": "/nix/store/r7dwv4hibaqkbkq0kr4g80ci6a9fdl2w-nghttp2-1.70.0-doc"
},
{
"name": "lib",
"path": "/nix/store/imwjr83lb0xlhz4ssq96kj8qbqk6qivs-nghttp2-1.70.0-lib"
}
],
"store_path": "/nix/store/8p19fbn4slkvk18j3bvjjh4yhp0d32wf-nghttp2-1.70.0"
},
"aarch64-linux": {
"outputs": [
{
"name": "out",
"path": "/nix/store/kgnsbgqd6wbfkk0w9ggsfmaphhfycdpw-nghttp2-1.70.0",
"default": true
},
{
"name": "man",
"path": "/nix/store/mf4xap4xwy757l2mn6z19c9vlwnsg9az-nghttp2-1.70.0-man",
"default": true
},
{
"name": "lib",
"path": "/nix/store/6pv315yv0ccxd5h26zhj0i6mgn7q3brj-nghttp2-1.70.0-lib"
},
{
"name": "dev",
"path": "/nix/store/bvf03id3xxgkpkw2ay29j5k6hcqivgk7-nghttp2-1.70.0-dev"
},
{
"name": "doc",
"path": "/nix/store/dg8m57h861pzxb4xml1rpxakvkkli1nn-nghttp2-1.70.0-doc"
}
],
"store_path": "/nix/store/kgnsbgqd6wbfkk0w9ggsfmaphhfycdpw-nghttp2-1.70.0"
},
"x86_64-linux": {
"outputs": [
{
"name": "out",
"path": "/nix/store/dpacn35xr3iajmgvcprb63hnxby21gpx-nghttp2-1.70.0",
"default": true
},
{
"name": "man",
"path": "/nix/store/rja4jsc58spfj44gscpaa6shnmqgijj7-nghttp2-1.70.0-man",
"default": true
},
{
"name": "dev",
"path": "/nix/store/9ia7882m3hhvdk6qi4p3p650pfhxg75r-nghttp2-1.70.0-dev"
},
{
"name": "doc",
"path": "/nix/store/w9fm1rnnl71p5m9wy6sn9hb11p35bf5p-nghttp2-1.70.0-doc"
},
{
"name": "lib",
"path": "/nix/store/sky8mslz50n51np0z4vhdq61jba12fh2-nghttp2-1.70.0-lib"
}
],
"store_path": "/nix/store/dpacn35xr3iajmgvcprb63hnxby21gpx-nghttp2-1.70.0"
}
}
},
"nginx@latest": {
"last_modified": "2026-10-02T22:55:44Z",
"plugin_version": "0.0.4",
"resolved": "github:NixOS/nixpkgs/55ba7f49ef2962b42cbd126522b7df5f95037679#nginx",
"source": "devbox-search",
"version": "1.30.5",
"systems": {
"aarch64-darwin": {
"outputs": [
{
"name": "out",
"path": "/nix/store/81a75xq2ilmn8dnrb1b7m8siyprmaq94-nginx-1.30.5",
"default": true
},
{
"name": "doc",
"path": "/nix/store/s9zq3wyd2bdfwb58rk2648yf2wsryvhj-nginx-1.30.5-doc"
}
],
"store_path": "/nix/store/81a75xq2ilmn8dnrb1b7m8siyprmaq94-nginx-1.30.5"
},
"aarch64-linux": {
"outputs": [
{
"name": "out",
"path": "/nix/store/7yvpd3svx846fybmc2d5ddxq3jxf94qm-nginx-1.30.5",
"default": true
},
{
"name": "doc",
"path": "/nix/store/skp8nki2v0li5h44zyp1gp8s2ahz3g4j-nginx-1.30.5-doc"
}
],
"store_path": "/nix/store/7yvpd3svx846fybmc2d5ddxq3jxf94qm-nginx-1.30.5"
},
"x86_64-linux": {
"outputs": [
{
"name": "out",
"path": "/nix/store/6k4rgdzx05z7yk2l98r28p6wrbnlv63z-nginx-1.30.5",
"default": true
},
{
"name": "doc",
"path": "/nix/store/d8v365rflmpicpcnxjqfxbbzlpk0q844-nginx-1.30.5-doc"
}
],
"store_path": "/nix/store/6k4rgdzx05z7yk2l98r28p6wrbnlv63z-nginx-1.30.5"
}
}
},
"nim@2": {
"last_modified": "2026-10-02T22:55:44Z",
"resolved": "github:NixOS/nixpkgs/55ba7f49ef2962b42cbd126522b7df5f95037679#nim",
"source": "devbox-search",
"version": "2.2.12",
"systems": {
"aarch64-darwin": {
"outputs": [
{
"name": "out",
"path": "/nix/store/h055h3lxxsm8kql0mannw3706x740x7f-arm64-apple-darwin-nim-wrapper-2.2.12",
"default": true
}
],
"store_path": "/nix/store/h055h3lxxsm8kql0mannw3706x740x7f-arm64-apple-darwin-nim-wrapper-2.2.12"
},
"aarch64-linux": {
"outputs": [
{
"name": "out",
"path": "/nix/store/2fh7rg634j8969c1r394llrsjmmhaip7-aarch64-unknown-linux-gnu-nim-wrapper-2.2.12",
"default": true
}
],
"store_path": "/nix/store/2fh7rg634j8969c1r394llrsjmmhaip7-aarch64-unknown-linux-gnu-nim-wrapper-2.2.12"
},
"x86_64-linux": {
"outputs": [
{
"name": "out",
"path": "/nix/store/0cbdz34lsakfirycixckf6ypsd8hazhg-x86_64-unknown-linux-gnu-nim-wrapper-2.2.12",
"default": true
}
],
"store_path": "/nix/store/0cbdz34lsakfirycixckf6ypsd8hazhg-x86_64-unknown-linux-gnu-nim-wrapper-2.2.12"
}
}
},
"nimble@latest": {
"last_modified": "2026-10-02T22:55:44Z",
"resolved": "github:NixOS/nixpkgs/55ba7f49ef2962b42cbd126522b7df5f95037679#nimble",
"source": "devbox-search",
"version": "0.24.1",
"systems": {
"aarch64-darwin": {
"outputs": [
{
"name": "out",
"path": "/nix/store/clxsxdsqjfcc43rfd7rad733nd0ndrkf-nimble-0.24.1",
"default": true
}
],
"store_path": "/nix/store/clxsxdsqjfcc43rfd7rad733nd0ndrkf-nimble-0.24.1"
},
"aarch64-linux": {
"outputs": [
{
"name": "out",
"path": "/nix/store/c5d0r4a8qi1vqs8q82pr3c652q8d6jv7-nimble-0.24.1",
"default": true
}
],
"store_path": "/nix/store/c5d0r4a8qi1vqs8q82pr3c652q8d6jv7-nimble-0.24.1"
},
"x86_64-linux": {
"outputs": [
{
"name": "out",
"path": "/nix/store/8f5wx2s80gnw0lkmdpbl63n1xlilcfxi-nimble-0.24.1",
"default": true
}
],
"store_path": "/nix/store/8f5wx2s80gnw0lkmdpbl63n1xlilcfxi-nimble-0.24.1"
}
}
},
"nodejs@latest": {
"last_modified": "2026-10-08T19:21:32Z",
"plugin_version": "0.0.2",
"resolved": "github:NixOS/nixpkgs/8edc0c72e3a38faf5434e40d1f19431125fe4b30#nodejs_26",
"source": "devbox-search",
"version": "26.11.1",
"systems": {
"aarch64-darwin": {
"outputs": [
{
"name": "out",
"path": "/nix/store/42hvw959dvc16w7p79xns4p4sgfx2wiv-nodejs-26.11.1",
"default": true
}
],
"store_path": "/nix/store/42hvw959dvc16w7p79xns4p4sgfx2wiv-nodejs-26.11.1"
},
"aarch64-linux": {
"outputs": [
{
"name": "out",
"path": "/nix/store/zzx8zal1hmjkamrp8y9k6mjim08pzwz8-nodejs-26.11.1",
"default": true
}
],
"store_path": "/nix/store/zzx8zal1hmjkamrp8y9k6mjim08pzwz8-nodejs-26.11.1"
},
"x86_64-linux": {
"outputs": [
{
"name": "out",
"path": "/nix/store/m7vfpzl1rjwjpwlcsqs166jn3lywzpq1-nodejs-26.11.1",
"default": true
}
],
"store_path": "/nix/store/m7vfpzl1rjwjpwlcsqs166jn3lywzpq1-nodejs-26.11.1"
}
}
}
}
}
+29
View File
@@ -0,0 +1,29 @@
<!doctype html>
<html>
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no" />
<title>Pixi v8 tile-size phone test (throwaway)</title>
<style>
html, body { margin: 0; height: 100%; overflow: hidden; background: #000; font: 11px monospace; color: #eee; overscroll-behavior: none; }
canvas { display: block; touch-action: none; }
.panel { position: fixed; background: rgba(0,0,0,.72); padding: 4px 6px; border-radius: 4px; }
#stats { top: 2px; left: 2px; white-space: pre; pointer-events: none; font-size: 10px; }
#ctl { bottom: 2px; left: 2px; right: 2px; display: flex; flex-wrap: wrap; gap: 4px; }
button, select { font: inherit; padding: 8px 6px; }
#msg { bottom: 110px; left: 2px; white-space: pre-wrap; pointer-events: none; }
</style>
</head>
<body>
<div id="stats" class="panel"></div>
<div id="msg" class="panel"></div>
<div id="ctl" class="panel">
<select id="size"><option>32</option><option>64</option><option>256</option></select>
<button id="explore">Explore: start</button>
<button id="open">Open map</button>
<button id="reveal">Reveal viewport (cold)</button>
<button id="send">Send results</button>
</div>
<script type="module" src="/web/main.ts"></script>
</body>
</html>
+3
View File
@@ -0,0 +1,3 @@
--path:"src"
--threads:on
--mm:orc

Some files were not shown because too many files have changed in this diff Show More