feat(walls): one-way sight per-viewer filter and ONEWAY fault (#58)

The vision fan blocks a sight-blocking one-way wall only for a viewer on
its blind side (sight_dir names it; left is the (-dy,dx) normal of a->b),
one sign test inline after the radius cull, so the hoisted wall list stays
viewer-independent. Movement never reads the direction: one-way walls block
both ways. Explored and tiles therefore differ by side and only ever grow.

- geometry: WallDir + Wall.sightDir + blindTo, filter in visibilityPolygon.
- worldmap: sight_dir mapping (movement mapping unchanged).
- vision: the ONEWAY leak-fault build drops sight_dir player-side.
- leakcheck: own side test for the fan and the clear-segment oracle; ONEWAY
  class detected against the sight_dir-dropped fan.
- leak scenario gains a one-way wall the subject sees across; fault test
  asserts exactly ONEWAY.
- oneway.test.mjs: both sides, tile sweep with its own oracle, flip with
  fixed endpoints, monotone explored/tiles, restart, two-way movement.
- docs: DESIGN 5.8 mechanism sentence corrected; TESTING #58 markers built.
- nginx harness: temp dirs created recursively (restart on one state dir).
This commit is contained in:
2026-11-19 22:57:39 +01:00
parent 0f3aa2300f
commit 9fcbe885c1
14 changed files with 649 additions and 78 deletions
+6 -4
View File
@@ -1115,16 +1115,18 @@ What a wall's behaviour is made of. Heights are 5.7; what a low wall does to sig
marker carries no type). marker carries no type).
- **What a one-way wall does to the floor [FIXED (owner decision), 2026-11-16, #47].** Explored - **What a one-way wall does to the floor [FIXED (owner decision), 2026-11-16, #47].** Explored
cells and tiles differ per side **by construction, not by a new mechanism**: each viewer's sight cells and tiles differ per side **by construction, not by a new mechanism**: each viewer's sight
wall list drops the one-way walls whose blind side that viewer stands on, so polygon, wall list drops every one-way wall the viewer sees across (the viewer is not on its blind side),
`cellsTouched`, explored and therefore tiles differ between the two sides with no extra state. so polygon, `cellsTouched`, explored and therefore tiles differ between the two sides with no
extra state.
Explored only grows (5.4), so flipping the direction or `a`/`b` never un-explores a cell and never Explored only grows (5.4), so flipping the direction or `a`/`b` never un-explores a cell and never
revokes a tile; a flip only widens what the newly-seeing side may explore next. Movement is revokes a tile; a flip only widens what the newly-seeing side may explore next. Movement is
two-way (above). With a low wall the direction filters first, then 5.9/5.10 evaluate every crossed two-way (above). With a low wall the direction filters first, then 5.9/5.10 evaluate every crossed
face of the walls that remain. face of the walls that remain.
- **Per-viewer filter [FIXED (owner-delegated), 2026-11-16, #47].** Nothing per-viewer is stored or - **Per-viewer filter [FIXED (owner-delegated), 2026-11-16, #47].** Nothing per-viewer is stored or
copied: the 5.10 quad faces stay hoisted and viewer-independent, and the fan skips a copied: the 5.10 quad faces stay hoisted and viewer-independent, and the fan skips a
sight-blocking wall inline when it is one-way and the viewer is on its blind side — one sign test sight-blocking one-way wall inline for a viewer on the seeing side (it blocks only a viewer on its
per **one-way** wall per viewer (cross product with `(-dy, dx)`), after the radius-bbox cull; blind side) — one sign test per **one-way** wall per viewer (cross product with `(-dy, dx)`),
after the radius-bbox cull;
two-way walls pay only a type check. Rejected: a per-viewer copy of the wall list (the prototype two-way walls pay only a type check. Rejected: a per-viewer copy of the wall list (the prototype
measured ~0.15 ms per viewer per frame for the copy, times tokens) and two prebuilt left/right measured ~0.15 ms per viewer per frame for the copy, times tokens) and two prebuilt left/right
lists (choosing between them needs the same per-viewer side test, and they duplicate the list). lists (choosing between them needs the same per-viewer side test, and they duplicate the list).
+19 -13
View File
@@ -226,6 +226,9 @@ How to run: `devbox run test` = Nim in-process tests first, then the Node black-
(§10.3, DESIGN §3.4 T17, #46). (§10.3, DESIGN §3.4 T17, #46).
- A wall `label` is in the leak checker's `BannedAlways` key scan (§10.3), so a player frame carrying - A wall `label` is in the leak checker's `BannedAlways` key scan (§10.3), so a player frame carrying
`label` is `WALLDATA`. `label` is `WALLDATA`.
- One-way sight (built, #58): the two sides, the direction flip, monotone explored/tiles and the
restart are proven by `tools/oneway.test.mjs`; the checker's own side test and the `ONEWAY` fault
are in §10.3.
### 5.9 Low walls: see-over ### 5.9 Low walls: see-over
@@ -347,10 +350,10 @@ from the prototype, what was missing, what the M3 build added, and the tools it
exact-class assertion; the shipped binary must contain no `LEAK_FAULT`. Built: `HIDDEN_TOKEN`, exact-class assertion; the shipped binary must contain no `LEAK_FAULT`. Built: `HIDDEN_TOKEN`,
`GMONLY_TOKEN`, `WALLDATA`, `WITHHELD`, `NO_REMOVE`, `OWN_VIEW`, `OTHER_PLAYER`, `EXPLORED`, `GMONLY_TOKEN`, `WALLDATA`, `WITHHELD`, `NO_REMOVE`, `OWN_VIEW`, `OTHER_PLAYER`, `EXPLORED`,
`OWNER_PROP`, `GM_PROP`, `STATUS_SOURCE`, `ACTUAL_NAME`, `STALE_NAME`, `CHAR_LIST`, `OWNER_PROP`, `GM_PROP`, `STATUS_SOURCE`, `ACTUAL_NAME`, `STALE_NAME`, `CHAR_LIST`,
`CONTROLLER_CHANGE`, `CHAR_OWNER_PROP`, `KEY_IN_LOG`. Walls r1 built: `secretgap` (#56), asserted `CONTROLLER_CHANGE`, `CHAR_OWNER_PROP`, `KEY_IN_LOG`, `ONEWAY` (#58). Walls r1 built: `secretgap`
as exactly `SECRETGAP` by `tools/doors.test.mjs` (the differential group, not the transcript (#56), asserted as exactly `SECRETGAP` by `tools/doors.test.mjs` (the differential group, not the
checker). Planned: Walls r1 — `ONEWAY` (#58), `MARKER_EARLY`/`MARKER_EXTRA`/`MARKER_OFF` transcript checker). Planned: Walls r1 — `MARKER_EARLY`/`MARKER_EXTRA`/`MARKER_OFF` (#59/#60).
(#59/#60). `tools/leakcheck.nim` `tools/leakcheck.nim`
refuses the `gm` bucket, the `owner` bucket on a refuses the `gm` bucket, the `owner` bucket on a
non-controller and any `source` on a player status entry. Two consequences: the `hidden` and non-controller and any `source` on a player status entry. Two consequences: the `hidden` and
`gmOnly` faults also produce `NO_REMOVE` (a leaked token whose frame never changes leaves the client `gmOnly` faults also produce `NO_REMOVE` (a leaked token whose frame never changes leaves the client
@@ -422,19 +425,22 @@ from the prototype, what was missing, what the M3 build added, and the tools it
thick locked door vs thick plain door), byte-identical. Also pinned: a fixed window and an open door thick locked door vs thick plain door), byte-identical. Also pinned: a fixed window and an open door
never push, and no wall edit pushes. **Mutations:** push from the drawn line; push ignoring the normal never push, and no wall edit pushes. **Mutations:** push from the drawn line; push ignoring the normal
span; ambiguous side ignoring `prev`; validity check on the door only — each fails at least one test. span; ambiguous side ignoring `prev`; validity check on the door only — each fails at least one test.
- **One-way direction (#47; planned: Walls r1 #58)**: `tools/leakcheck.nim` and the independent - **One-way direction (#47; built: Walls r1 #58)**: `tools/leakcheck.nim` and the independent
explored/tile oracle apply explored/tile oracle apply
**their own** side test — sign of the cross product of `viewer - a` with the `(-dy, dx)` normal of **their own** side test — sign of the cross product of `viewer - a` with the `(-dy, dx)` normal of
`a -> b`, positive = left — never by calling `vision.nim`: a sight-blocking one-way wall is dropped `a -> b`, positive = left — never by calling `vision.nim`: a sight-blocking one-way wall stays in
from the oracle's wall list for a viewer on its blind side, and a wall that is `blocks_sight:false` the oracle's wall list only for a viewer on its blind side (the side `sight_dir` names), and a
is dropped for everyone. Assertions: a token on the blind side gets no polygon point, explored cell wall that is `blocks_sight:false` is dropped for everyone. Assertions: a token on the blind side
or tile beyond the wall, and a token across it gives no `token` frame, no name and no encountered gets no polygon point, explored cell or tile beyond the wall, and a token across it gives no
entry; a viewer on the seeing side does see across (the positive control, so the oracle can fail). `token` frame, no name and no encountered entry; a viewer on the seeing side does see across (the
positive control, so the oracle can fail). `tools/oneway.test.mjs` runs the two sides, the
`sight_dir` flip with fixed endpoints, the monotone explored/tile set across flips and a restart,
and the per-tile sweep with the same own side test.
Tolerances as elsewhere: the 0.5 px boundary band along the blind side is oracle-*maybe* (a `200` Tolerances as elsewhere: the 0.5 px boundary band along the blind side is oracle-*maybe* (a `200`
there is legitimate, but never *sure*), and anything clearly behind the blind wall is there is legitimate, but never *sure*), and anything clearly behind the blind wall is
oracle-refused (a withheld proof cell still fails). New fault class `ONEWAY` — the player-facing oracle-refused (a withheld proof cell still fails). Fault class `ONEWAY` (built) — the
computation drops `sight_dir` and lets the blind side see across — with its injected fault and player-facing computation drops `sight_dir`, so the one-way wall becomes two-way — with its
exact-class assertion, shaped like the existing classes. injected fault (`LEAK_FAULT=oneWay`) and exact-class assertion, shaped like the existing classes.
- **Player marker (#48; shape fixed by #49; planned: Walls r1 #59/#60).** Once planned Walls r1 #59 - **Player marker (#48; shape fixed by #49; planned: Walls r1 #59/#60).** Once planned Walls r1 #59
lands, `leakcheck.nim` allows the `marker` type and, with its own code (never calling `vision.nim`), lands, `leakcheck.nim` allows the `marker` type and, with its own code (never calling `vision.nim`),
checks that a marker exists for a player exactly when some checks that a marker exists for a player exactly when some
+30
View File
@@ -3,6 +3,9 @@
## Fixed in M2 (DESIGN 5.5): token exactly on a wall can move off it (moverules escape rule); the move check is the ## Fixed in M2 (DESIGN 5.5): token exactly on a wall can move off it (moverules escape rule); the move check is the
## swept circle, not centre path + destination only; `moveBlocked` is gone from this module; cellsTouched is a scanline ## swept circle, not centre path + destination only; `moveBlocked` is gone from this module; cellsTouched is a scanline
## (prototype per-cell version kept test-only in tests/refold.nim, differential-tested). ## (prototype per-cell version kept test-only in tests/refold.nim, differential-tested).
## One-way sight (DESIGN 5.8, #58): `Wall.sightDir` names the blind side of `a -> b` (`left` = the `(-dy, dx)` normal)
## and `visibilityPolygon` blocks such a wall only for a viewer on that side; the other side casts rays past it.
## Movement never reads it: `moverules` gets the same wall and blocks both ways.
## Known limitations (DESIGN 5.4 / 12): ## Known limitations (DESIGN 5.4 / 12):
## - boundary epsilon ambiguity: RayEps 1e-4 rad, inclusive tests; token on a vision boundary is ambiguous ## - boundary epsilon ambiguity: RayEps 1e-4 rad, inclusive tests; token on a vision boundary is ambiguous
## (leak checker and explored oracle use a 0.5 px neighbourhood). ## (leak checker and explored oracle use a 0.5 px neighbourhood).
@@ -15,9 +18,19 @@ import std/[math, algorithm]
type type
Vec* = tuple[x, y: float] Vec* = tuple[x, y: float]
WallDir* = enum
## Which side of the drawn `a -> b` order cannot see across (DESIGN 5.8, #47/#58). `left` is
## the `(-dy, dx)` side, the same formula as `position` (5.10) and the door-push side (5.5).
## This is a sight-only field: movement is always two-way and never reads it.
wdBoth = "both"
wdLeft = "left"
wdRight = "right"
Wall* = object Wall* = object
a*, b*: Vec a*, b*: Vec
door*, open*: bool door*, open*: bool
sightDir*: WallDir
const const
Eps* = 1e-9 # geometric tolerance (px) Eps* = 1e-9 # geometric tolerance (px)
@@ -28,6 +41,19 @@ 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 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 `-`*(a, b: Vec): Vec = (a.x - b.x, a.y - b.y)
proc blindTo*(w: Wall, o: Vec): bool =
## DESIGN 5.8: true when `o` stands on the side the wall's `sight_dir` names blind. One sign test
## of the viewer against the `a -> b` left normal: cross(a->b, o - a) is the signed distance along
## `(-dy, dx)`, so positive is the left side. A viewer exactly on the drawn line (|s| <= Eps) is
## blind to either direction: the predicate is never ambiguous, even though the fan's own rays
## start on the segment and a token standing on a wall already sees along it (5.5).
if w.sightDir == wdBoth: return false
let s = cross(w.b - w.a, o - w.a)
case w.sightDir
of wdBoth: false
of wdLeft: s >= -Eps
of wdRight: s <= Eps
proc rayHit(o, d: Vec, a, b: Vec): float = proc rayHit(o, d: Vec, a, b: Vec): float =
## smallest t > Eps where o + t*d hits segment ab (end-inclusive), else Inf ## smallest t > Eps where o + t*d hits segment ab (end-inclusive), else Inf
let e = b - a let e = b - a
@@ -54,6 +80,10 @@ proc visibilityPolygon*(o: Vec, walls: openArray[Wall], radius: float,
# shortcut: walls beyond the circle are only culled by ray clipping, O(rays*walls); upgrade: spatial grid # 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 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 max(w.a.y, w.b.y) < o.y - radius or min(w.a.y, w.b.y) > o.y + radius: continue
# Per-viewer one-way filter (5.8, #58), inline and after the radius cull so the hoisted wall
# list stays viewer-independent: a sight-blocking one-way wall blocks only a viewer on its
# blind side; the other side sees across it. Two-way walls skip the test entirely.
if w.sightDir != wdBoth and not w.blindTo(o): continue
segs.add((w.a, w.b)) segs.add((w.a, w.b))
for p in [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 if abs(p.x - o.x) < Eps and abs(p.y - o.y) < Eps: continue # token on endpoint
+11 -3
View File
@@ -5,7 +5,8 @@
## Vision (5.1): one visibility polygon per token the player controls that carries the `vision` flag, ## Vision (5.1): one visibility polygon per token the player controls that carries the `vision` flag,
## cast from the token centre against the scene's blocking walls with the token's range (Q7: the ## cast from the token centre against the scene's blocking walls with the token's range (Q7: the
## token's `vision_radius` if it sets one, else the scene's `vision_radius_default`). Open doors do ## token's `vision_radius` if it sets one, else the scene's `vision_radius_default`). Open doors do
## not block; geometry.nim does the casting. ## not block; geometry.nim does the casting. A sight-blocking one-way wall blocks only a viewer on
## its blind side (the side `sight_dir` names), one sign test inline after the radius cull (#58).
## ##
## Explored (5.1, 8): the union of the cells every polygon ever overlapped, per player, strictly ## Explored (5.1, 8): the union of the cells every polygon ever overlapped, per player, strictly
## per player (Q9 FIXED). It only grows: a wall edit or a door closing never un-explores. `cells` ## per player (Q9 FIXED). It only grows: a wall edit or a door closing never un-explores. `cells`
@@ -20,7 +21,7 @@
## Change tracking: `ver` counts polygon changes (the client gets `vision` only when it changes, 6.4) ## Change tracking: `ver` counts polygon changes (the client gets `vision` only when it changes, 6.4)
## and `fresh` holds the cells this mutation added (4.2 step 8: cleared after egress). ## and `fresh` holds the cells this mutation added (4.2 step 8: cleared after egress).
import std/[algorithm, math, sets] import std/[algorithm, math, sets]
import tokens, worldmap, geometry, world import tokens, worldmap, geometry, world, faults
type type
Poly* = object Poly* = object
@@ -48,8 +49,15 @@ proc cellOf*(sc: SceneRec, idx: int): (int, int) =
proc computePolys*(sc: SceneRec, tokens: seq[TokenRec], playerId: int): seq[Poly] = proc computePolys*(sc: SceneRec, tokens: seq[TokenRec], playerId: int): seq[Poly] =
## One polygon per token of this player that has vision, in token order (a stable wire order). ## One polygon per token of this player that has vision, in token order (a stable wire order).
## The wall list is hoisted and viewer-independent: the one-way filter is inline in the ray fan
## (geometry.visibilityPolygon), one sign test per one-way wall per viewer (5.8, #58).
if playerId <= 0: return if playerId <= 0: return
let walls = geometryWalls(sc, forSight = true) var walls = geometryWalls(sc, forSight = true)
when defined(leakfault):
# Negative control (DESIGN 10.3, TESTING 10.3): the ONEWAY fault drops `sight_dir` from the
# player-facing computation, so a sight-blocking one-way wall blocks both sides.
if faultActive("oneWay"):
for w in walls.mitems: w.sightDir = wdBoth
for t in tokens: for t in tokens:
if t.owner != playerId or not t.hasVision: continue if t.owner != playerId or not t.hasVision: continue
result.add Poly(tokenId: t.id, result.add Poly(tokenId: t.id,
+4 -4
View File
@@ -4,10 +4,10 @@
## ##
## Walls (DESIGN 8, FIXED #3): per-scene ids from `scene.next_wall_id`, monotonic and never reused ## Walls (DESIGN 8, FIXED #3): per-scene ids from `scene.next_wall_id`, monotonic and never reused
## (a removal leaves the counter alone). Identity is `(scene, id)` in the DB, in memory and on the ## (a removal leaves the counter alone). Identity is `(scene, id)` in the DB, in memory and on the
## wire. Today a wall's sight/movement behaviour is still `blocks = not (door and open)` in ## wire. A wall's sight/movement behaviour is still `blocks = not (door and open)` in
## geometry.Wall; the stored switches (`blocks_sight`, `blocks_movement`, `sight_dir`) gain their ## geometry.Wall plus the per-viewer one-way filter (`sight_dir`, #58); `blocks_sight` and
## behaviour in the window/one-way rounds (#57/#58). `flags` is a free JSON object the server never ## `blocks_movement` gain their general behaviour in the window/movement round (#57). `flags` is a
## interprets. ## free JSON object the server never interprets.
## ##
## Wire payload shapes are DESIGN 6.1; the parts it leaves open are fixed here (recorded FIXED ## Wire payload shapes are DESIGN 6.1; the parts it leaves open are fixed here (recorded FIXED
## owner-delegated, #19, in DESIGN 6.1/14): ## owner-delegated, #19, in DESIGN 6.1/14):
+10 -3
View File
@@ -18,18 +18,25 @@ import std/options
import geometry, moverules, tokens, world, faults import geometry, moverules, tokens, world, faults
proc geometryWalls*(sc: SceneRec, forSight = false): seq[Wall] = proc geometryWalls*(sc: SceneRec, forSight = false): seq[Wall] =
## The scene's walls as the vision code sees them: an open door does not block (5.1). ## The scene's walls as the vision code sees them: an open door does not block (5.1), and a
## one-way wall carries the side that is blind (5.8, #58). Movement gets the same mapping and
## ignores `sightDir` (two-way).
## `forSight` is only the sight computation; `LEAK_FAULT=secretgap` (a -d:leakfault build only) ## `forSight` is only the sight computation; `LEAK_FAULT=secretgap` (a -d:leakfault build only)
## opens a secret door there, the negative control for the door-equivalence group (#56). ## opens a secret door there, the negative control for the door-equivalence group (#56).
result = newSeqOfCap[Wall](sc.walls.len) result = newSeqOfCap[Wall](sc.walls.len)
for w in sc.walls: for w in sc.walls:
var wall = Wall(a: w.a, b: w.b, door: w.door, open: w.open) let dir = case w.sightDir
of sdBoth: wdBoth
of sdLeft: wdLeft
of sdRight: wdRight
var wall = Wall(a: w.a, b: w.b, door: w.door, open: w.open, sightDir: dir)
if forSight and w.secret and faultActive("secretgap"): if forSight and w.secret and faultActive("secretgap"):
wall.open = true wall.open = true
result.add wall result.add wall
proc ruleWall*(w: WallRec): Wall = proc ruleWall*(w: WallRec): Wall =
## The same wall as the move rules see it (they need `door`/`open` to know what blocks). ## The same wall as the move rules see it (they need `door`/`open` to know what blocks; the
## one-way direction is sight-only and never read by the move rules, so it is not mapped).
Wall(a: w.a, b: w.b, door: w.door, open: w.open) Wall(a: w.a, b: w.b, door: w.door, open: w.open)
proc ruleToken*(sc: SceneRec, t: TokenRec): moverules.Token = proc ruleToken*(sc: SceneRec, t: TokenRec): moverules.Token =
+2 -2
View File
@@ -6,8 +6,8 @@ proc scaled*(n: int): int =
## FFF_MUTATION=1 (set only by tools/mutation.sh) divides random/oracle iteration counts by 10; normal runs use n. ## FFF_MUTATION=1 (set only by tools/mutation.sh) divides random/oracle iteration counts by 10; normal runs use n.
if getEnv("FFF_MUTATION") != "": max(1, n div 10) else: n if getEnv("FFF_MUTATION") != "": max(1, n div 10) else: n
proc W*(ax, ay, bx, by: float, door = false, open = false): Wall = proc W*(ax, ay, bx, by: float, door = false, open = false, sightDir = wdBoth): Wall =
Wall(a: (ax, ay), b: (bx, by), door: door, open: open) Wall(a: (ax, ay), b: (bx, by), door: door, open: open, sightDir: sightDir)
proc box*(x0, y0, x1, y1: float): seq[Wall] = 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)] @[W(x0, y0, x1, y0), W(x1, y0, x1, y1), W(x1, y1, x0, y1), W(x0, y1, x0, y0)]
+22
View File
@@ -131,6 +131,28 @@ suite "visibility":
check sees(opened, (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)) check not sees(opened, (0.0, 0.0), (90.0, 40.0))
test "one-way: sight_dir names the blind side (left is the (-dy, dx) normal)":
# a=(0,0) -> b=(0,100): the left normal (-dy, dx) = (-100, 0) points west.
let left = @[W(0, 0, 0, 100, sightDir = wdLeft)]
check not sees(left, (-50.0, 50.0), (50.0, 50.0)) # viewer on the blind (west) side
check sees(left, (50.0, 50.0), (-50.0, 50.0)) # positive control: the east side sees across
let right = @[W(0, 0, 0, 100, sightDir = wdRight)]
check sees(right, (-50.0, 50.0), (50.0, 50.0))
check not sees(right, (50.0, 50.0), (-50.0, 50.0))
test "one-way: flipping the direction swaps the blind side and moves nothing":
var w = @[W(0, 0, 0, 100, sightDir = wdLeft)]
check not sees(w, (-50.0, 50.0), (50.0, 50.0))
w[0].sightDir = wdRight
check (w[0].a, w[0].b) == ((0.0, 0.0), (0.0, 100.0))
check sees(w, (-50.0, 50.0), (50.0, 50.0))
check not sees(w, (50.0, 50.0), (-50.0, 50.0))
test "one-way: an open door blocks neither side whatever the direction says":
let door = @[W(0, 0, 0, 100, door = true, open = true, sightDir = wdLeft)]
check sees(door, (-50.0, 50.0), (50.0, 50.0))
check sees(door, (50.0, 50.0), (-50.0, 50.0))
test "token exactly at wall endpoint": test "token exactly at wall endpoint":
let w = @[W(0, 0, 100, 0), W(0, 0, 0, 100)] # corner, token on it 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) let poly = visibilityPolygon((0.0, 0.0), w, 200)
+3 -1
View File
@@ -5,7 +5,8 @@
// //
// Classes: HIDDEN_TOKEN, GMONLY_TOKEN, WALLDATA, WITHHELD, NO_REMOVE, OWN_VIEW, OTHER_PLAYER, // Classes: HIDDEN_TOKEN, GMONLY_TOKEN, WALLDATA, WITHHELD, NO_REMOVE, OWN_VIEW, OTHER_PLAYER,
// EXPLORED, from slice 7 (#22) OWNER_PROP, GM_PROP, STATUS_SOURCE, and from slice 8 (#23) // EXPLORED, from slice 7 (#22) OWNER_PROP, GM_PROP, STATUS_SOURCE, and from slice 8 (#23)
// ACTUAL_NAME, CHAR_LIST, CONTROLLER_CHANGE, CHAR_OWNER_PROP. (The tile class lands with slice 9.) // ACTUAL_NAME, CHAR_LIST, CONTROLLER_CHANGE, CHAR_OWNER_PROP, and from Walls r1 (#58) ONEWAY.
// (The tile class lands with slice 9.)
import test from 'node:test' import test from 'node:test'
import assert from 'node:assert/strict' import assert from 'node:assert/strict'
import fs from 'node:fs' import fs from 'node:fs'
@@ -28,6 +29,7 @@ const FAULTS = {
gmOnly: ['GMONLY_TOKEN', 'NO_REMOVE'], gmOnly: ['GMONLY_TOKEN', 'NO_REMOVE'],
walls: ['WALLDATA'], walls: ['WALLDATA'],
wallHeight: ['WALLDATA'], wallHeight: ['WALLDATA'],
oneWay: ['ONEWAY'],
withhold: ['WITHHELD'], withhold: ['WITHHELD'],
otherOwner: ['OTHER_PLAYER'], otherOwner: ['OTHER_PLAYER'],
otherVision: ['OTHER_PLAYER'], otherVision: ['OTHER_PLAYER'],
+3 -2
View File
@@ -12,8 +12,9 @@ export const GROUPS = {
], ],
}, },
tiles: { tiles: {
files: ['tiles.test.mjs'], files: ['tiles.test.mjs', 'oneway.test.mjs'],
evidence: [['tiles.test.mjs', 'tile gate: leak check (d) matches the independent explored oracle']], evidence: [['tiles.test.mjs', 'tile gate: leak check (d) matches the independent explored oracle'],
['oneway.test.mjs', 'one-way sight: the blind side sees nothing across, the seeing side does (#58)']],
}, },
probing: { probing: {
files: ['probing.test.mjs'], files: ['probing.test.mjs'],
+12
View File
@@ -22,6 +22,8 @@
// - slice 7 (#22): props written into all three buckets on a token the subject can see, a // - slice 7 (#22): props written into all three buckets on a token the subject can see, a
// GM-sourced status, a walls-sourced stuck from a new wall, a resize, and a prop.unset — every // GM-sourced status, a walls-sourced stuck from a new wall, a resize, and a prop.unset — every
// frame of the group is checked for the bucket and the `source` it must not carry // frame of the group is checked for the bucket and the `source` it must not carry
// - Walls r1 (#58): a one-way wall the subject sees across (`sight_dir` names the token's side
// blind), the ONEWAY fault's positive source and the blind-side oracle's control
import fs from 'node:fs' import fs from 'node:fs'
import path from 'node:path' import path from 'node:path'
import { spawnSync } from 'node:child_process' import { spawnSync } from 'node:child_process'
@@ -371,6 +373,16 @@ export async function runLeak({ origin, gmKey, stateDir, transcript, keepOpen =
await group('A walks further south', async () => { await group('A walks further south', async () => {
expectAck(await move(A, ids.A, [560, 1300]), true) expectAck(await move(A, ids.A, [560, 1300]), true)
}) })
// Walls r1 (#58): a one-way wall between the subject (west) and a token on its blind (east) side.
// `sight_dir:"right"` names the east side blind, so the subject sees across; the ONEWAY fault
// drops `sight_dir` and the same wall would hide E2 and shrink the subject's fan.
await group('GM adds a one-way wall east of the subject', async () => {
await addWall({ a: [700, 1200], b: [700, 1400], sight_dir: 'right' })
})
await group('GM puts a token behind the one-way wall (the subject sees across)', async () => {
await createToken('E2', { kind: 'npc', pos: [800, 1300], descriptive_name: 'a sentry',
actual_name: 'Sentry' })
})
await group('end', async () => { await sleep(0) }) await group('end', async () => { await sleep(0) })
// Let anything still queued arrive, then close politely. // Let anything still queued arrive, then close politely.
+112 -20
View File
@@ -26,8 +26,15 @@
## CONTROLLER_CHANGE a token changed controller in a group that asked for no such thing (8) ## CONTROLLER_CHANGE a token changed controller in a group that asked for no such thing (8)
## CHAR_OWNER_PROP a character's owner bucket reached a player who does not own it (8) ## CHAR_OWNER_PROP a character's owner bucket reached a player who does not own it (8)
## GEOMETRY the recomputed polygon disagrees with the clear-segment oracle (sanity) ## GEOMETRY the recomputed polygon disagrees with the clear-segment oracle (sanity)
## ONEWAY the subject's fan ignores `sight_dir` (the two-way fan; TESTING 10.3, #58)
## PROTOCOL a frame the catalogue does not allow, a bad `n` sequence, a missing hello block ## PROTOCOL a frame the catalogue does not allow, a bad `n` sequence, a missing hello block
## ##
## One-way sight (DESIGN 5.8, TESTING 10.3): the checker reads `sight_dir` from the GM's frames and
## applies its OWN side test (`blindTo`, the sign of the cross product with `(-dy, dx)`) to decide
## whether a one-way wall is in a viewer's fan. It never calls `server/vision.nim`. Once the
## subject's own `vision` frame proves the sight_dir-dropped fan (the ONEWAY fault), the oracles
## evaluate that two-way perspective so the fault is reported as exactly ONEWAY.
##
## usage: leakcheck <transcript.jsonl> <SUBJECT> exit 0 = clean ## usage: leakcheck <transcript.jsonl> <SUBJECT> exit 0 = clean
import std/[algorithm, json, math, options, os, sets, strutils, tables] import std/[algorithm, json, math, options, os, sets, strutils, tables]
import geometry import geometry
@@ -87,6 +94,14 @@ proc fail(cls, s: string) =
proc vec(j: JsonNode): Vec = (j[0].getFloat, j[1].getFloat) proc vec(j: JsonNode): Vec = (j[0].getFloat, j[1].getFloat)
proc wallDir(j: JsonNode): WallDir =
## The GM's wall frames carry `sight_dir` (proto 2, #54); the checker reads it as its own input.
if j.kind != JString: return wdBoth
case j.getStr
of "left": wdLeft
of "right": wdRight
else: wdBoth
proc samePos(j: JsonNode, p: Vec): bool = proc samePos(j: JsonNode, p: Vec): bool =
## JSON numbers lose their int/float spelling on the wire round trip: compare numerically. ## JSON numbers lose their int/float spelling on the wire round trip: compare numerically.
j.kind == JArray and j.len == 2 and j.kind == JArray and j.len == 2 and
@@ -127,12 +142,13 @@ proc applyGmWalls(truth: var Truth, ids: var seq[int], m: JsonNode) =
ids.setLen(0) ids.setLen(0)
for w in m["walls"]: for w in m["walls"]:
truth.walls.add Wall(a: vec(w["a"]), b: vec(w["b"]), truth.walls.add Wall(a: vec(w["a"]), b: vec(w["b"]),
door: w["door"].getBool, open: w["open"].getBool) door: w["door"].getBool, open: w["open"].getBool,
sightDir: wallDir(w["sight_dir"]))
ids.add w["id"].getInt ids.add w["id"].getInt
of "wall": of "wall":
let id = m["id"].getInt let id = m["id"].getInt
let w = Wall(a: vec(m["a"]), b: vec(m["b"]), door: m["door"].getBool, let w = Wall(a: vec(m["a"]), b: vec(m["b"]), door: m["door"].getBool,
open: m["open"].getBool) open: m["open"].getBool, sightDir: wallDir(m["sight_dir"]))
var found = false var found = false
for i in 0 ..< ids.len: for i in 0 ..< ids.len:
if ids[i] == id: if ids[i] == id:
@@ -193,9 +209,39 @@ proc applyGmCharacters(truth: var Truth, m: JsonNode) =
# --------------------------------------------------------------------------------------------------- # ---------------------------------------------------------------------------------------------------
# Independent oracles # Independent oracles
var checkDir = true
## False once the subject's own `vision` frame shows `sight_dir` dropped (the ONEWAY fault): from
## then on the oracles evaluate the faulty perspective so the fault is reported as exactly ONEWAY,
## not as a cascade of WITHHELD/OWN_VIEW/EXPLORED.
proc blindTo(w: Wall, o: Vec): bool =
## The checker's OWN copy of the 5.8 side test, never `vision.nim`: cross(a->b, o - a) is the
## signed distance along the `(-dy, dx)` normal of `a -> b`, positive = left. On the drawn line
## both directions answer blind, so the predicate is never ambiguous.
if w.sightDir == wdBoth: return false
let s = cross(w.b - w.a, o - w.a)
case w.sightDir
of wdBoth: false
of wdLeft: s >= -Eps
of wdRight: s <= Eps
proc wallsFor(truth: Truth, o: Vec, honourDir: bool): seq[Wall] =
## The wall list one viewer's fan gets. With `honourDir`, a sight-blocking one-way wall is kept
## only for a viewer on its blind side (the checker's own side test); otherwise every `sight_dir`
## is dropped, which is exactly the ONEWAY fault's two-way wall list.
if honourDir:
for w in truth.walls:
if w.sightDir != wdBoth and not w.blindTo(o): continue
result.add w
else:
result = truth.walls
for w in result.mitems: w.sightDir = wdBoth
proc clearLine(walls: seq[Wall], o, p: Vec): bool = proc clearLine(walls: seq[Wall], o, p: Vec): bool =
## The clear-segment oracle: no blocking wall between o and p (independent of the ray fan). ## The clear-segment oracle: no blocking wall between o and p (independent of the ray fan). The
## one-way filter is the checker's own side test, for the sample's viewer `o`.
for w in walls: for w in walls:
if checkDir and w.sightDir != wdBoth and not w.blindTo(o): continue
if w.blocks and segsCross(o, p, w.a, w.b): return false if w.blocks and segsCross(o, p, w.a, w.b): return false
true true
@@ -203,13 +249,41 @@ proc rangeOf(sceneDefault: float, t: TruthToken): float =
if t.hasVision and t.visionRadius.isSome and t.visionRadius.get > 0: t.visionRadius.get if t.hasVision and t.visionRadius.isSome and t.visionRadius.get > 0: t.visionRadius.get
else: sceneDefault else: sceneDefault
proc polygonsOf(truth: Truth, controller: int, sceneDefault: float): seq[(string, seq[Vec])] = proc polygonsOf(truth: Truth, controller: int, sceneDefault: float,
honourDir = true): seq[(string, seq[Vec])] =
for id, t in truth.tokens: for id, t in truth.tokens:
if t.controller != controller or not t.hasVision: continue if t.controller != controller or not t.hasVision: continue
result.add (id, visibilityPolygon(t.pos, truth.walls, rangeOf(sceneDefault, t))) result.add (id, visibilityPolygon(t.pos, wallsFor(truth, t.pos, honourDir),
rangeOf(sceneDefault, t)))
# deterministic order: by token id (the server keeps creation order; the checker sorts) # deterministic order: by token id (the server keeps creation order; the checker sorts)
result.sort(proc (a, b: (string, seq[Vec])): int = cmp(a[0], b[0])) result.sort(proc (a, b: (string, seq[Vec])): int = cmp(a[0], b[0]))
proc samePolySet(got, want: seq[(string, seq[Vec])], tol = 0.5): bool =
## Every polygon present with the same id, vertex count and vertices within `tol` px (the wire's
## integer rounding, 6.4). Used to tell the correct fan from the ONEWAY fault's two-way fan.
if got.len != want.len: return false
var used = newSeq[bool](want.len)
for (gid, gpts) in got:
var matched = false
for i in 0 ..< want.len:
if used[i] or want[i][0] != gid: continue
used[i] = true
matched = true
let wpts = want[i][1]
if gpts.len != wpts.len: return false
for k in 0 ..< gpts.len:
if abs(gpts[k].x - wpts[k].x) > tol + 1e-6 or
abs(gpts[k].y - wpts[k].y) > tol + 1e-6: return false
break
if not matched: return false
true
proc parsePolys(m: JsonNode): seq[(string, seq[Vec])] =
for p in m["polys"]:
var pts: seq[Vec]
for q in p["pts"]: pts.add vec(q)
result.add (p["id"].getStr, pts)
proc insideAny(polys: seq[(string, seq[Vec])], p: Vec): bool = proc insideAny(polys: seq[(string, seq[Vec])], p: Vec): bool =
for (_, pts) in polys: for (_, pts) in polys:
if inside(pts, p): return true if inside(pts, p): return true
@@ -322,14 +396,31 @@ proc main() =
if me == 0: continue if me == 0: continue
let polys = polygonsOf(truth, me, sceneDefault) let polys = polygonsOf(truth, me, sceneDefault)
let otherPolys = if other != 0: polygonsOf(truth, other, sceneDefault) else: @[] var anyOneWay = false
for w in truth.walls:
if w.sightDir != wdBoth: anyOneWay = true
# The fault's fan is only worth recomputing in a world that has a one-way wall at all.
let faultPolys = if anyOneWay: polygonsOf(truth, me, sceneDefault, honourDir = false)
else: polys
# The subject's own `vision` frame decides the perspective this group is checked against: if it
# matches the sight_dir-dropped fan and not the correct one, the ONEWAY fault is live. Then the
# oracles evaluate that perspective, so the fault surfaces as exactly ONEWAY instead of a
# cascade of WITHHELD/OWN_VIEW/EXPLORED.
if anyOneWay:
for m in g.subjMsgs:
if m["t"].getStr != "vision": continue
let got = parsePolys(m)
if not samePolySet(got, polys) and samePolySet(got, faultPolys): checkDir = false
let polysChecks = if checkDir: polys else: faultPolys
let otherPolys = if other != 0: polygonsOf(truth, other, sceneDefault, honourDir = checkDir)
else: @[]
# The encountered oracle, computed from the GM's truth and the subject's own polygons - never # The encountered oracle, computed from the GM's truth and the subject's own polygons - never
# from what the subject was sent: every token the subject can see right now is one it may have # from what the subject was sent: every token the subject can see right now is one it may have
# met. It only grows, exactly like the server's list (8). # met. It only grows, exactly like the server's list (8).
var visibleNow = initHashSet[string]() var visibleNow = initHashSet[string]()
for id, actual in truth.tokens: for id, actual in truth.tokens:
if actual.controller == me or (not actual.gmOnly and insideAny(polys, actual.pos)): if actual.controller == me or (not actual.gmOnly and insideAny(polysChecks, actual.pos)):
visibleNow.incl id visibleNow.incl id
encounterable.incl id encounterable.incl id
@@ -441,9 +532,9 @@ proc main() =
if got != want: if got != want:
fail "CHAR_OWNER_PROP", "token " & id & " cprops public bucket is not the truth" fail "CHAR_OWNER_PROP", "token " & id & " cprops public bucket is not the truth"
view[id] = m view[id] = m
let visible = wantMine or (not actual.gmOnly and insideAny(polys, actual.pos)) let visible = wantMine or (not actual.gmOnly and insideAny(polysChecks, actual.pos))
if not visible: if not visible:
let cls = if actual.gmOnly and insideAny(polys, actual.pos): "GMONLY_TOKEN" let cls = if actual.gmOnly and insideAny(polysChecks, actual.pos): "GMONLY_TOKEN"
else: "HIDDEN_TOKEN" else: "HIDDEN_TOKEN"
leaked[id] = cls leaked[id] = cls
fail cls, "token " & id & " sent but not visible (group " & g.label & ")" fail cls, "token " & id & " sent but not visible (group " & g.label & ")"
@@ -458,7 +549,7 @@ proc main() =
inc removes inc removes
if id in truth.tokens: if id in truth.tokens:
let actual = truth.tokens[id] let actual = truth.tokens[id]
if actual.controller == me or (not actual.gmOnly and insideAny(polys, actual.pos)): if actual.controller == me or (not actual.gmOnly and insideAny(polysChecks, actual.pos)):
fail "WITHHELD", "token_gone for a token still visible: " & id fail "WITHHELD", "token_gone for a token still visible: " & id
of "character": of "character":
# 6.1: a player gets only the characters it owns, with both names and the public/owner # 6.1: a player gets only the characters it owns, with both names and the public/owner
@@ -513,11 +604,12 @@ proc main() =
if pl["name"].kind == JNull or pl["name"].getStr.len == 0: if pl["name"].kind == JNull or pl["name"].getStr.len == 0:
fail "PROTOCOL", "the roster handed a player an unnamed entry" fail "PROTOCOL", "the roster handed a player an unnamed entry"
of "vision": of "vision":
var got: seq[(string, seq[Vec])] let got = parsePolys(m)
for p in m["polys"]: if not samePolySet(got, polys):
var pts: seq[Vec] if anyOneWay and samePolySet(got, faultPolys):
for q in p["pts"]: pts.add vec(q) # TESTING 10.3: the fan behaves as if `sight_dir` were dropped (a two-way wall).
got.add (p["id"].getStr, pts) fail "ONEWAY", "vision is the sight_dir-dropped fan (group " & g.label & ")"
else:
let want = polys let want = polys
var haveIds = initHashSet[string]() var haveIds = initHashSet[string]()
for (id, pts) in got: for (id, pts) in got:
@@ -593,7 +685,7 @@ proc main() =
# was legitimately seen and is now invisible is a missing withdrawal. `seenAny` decides, # was legitimately seen and is now invisible is a missing withdrawal. `seenAny` decides,
# so a `gm_only` flip after a legitimate sighting is not re-labelled as a gm_only leak. # so a `gm_only` flip after a legitimate sighting is not re-labelled as a gm_only leak.
if leaked.hasKey(id): fail leaked[id], "leaked token still in view: " & id if leaked.hasKey(id): fail leaked[id], "leaked token still in view: " & id
elif id notin seenAny and actual.gmOnly and insideAny(polys, actual.pos): elif id notin seenAny and actual.gmOnly and insideAny(polysChecks, actual.pos):
fail "GMONLY_TOKEN", "gm_only token still in view: " & id fail "GMONLY_TOKEN", "gm_only token still in view: " & id
else: fail "NO_REMOVE", "token left the view and was never withdrawn: " & id & else: fail "NO_REMOVE", "token left the view and was never withdrawn: " & id &
" (group " & g.label & ")" " (group " & g.label & ")"
@@ -605,7 +697,7 @@ proc main() =
var recomputed: HashSet[int] var recomputed: HashSet[int]
let cols = int(ceil(sceneW / float(cell))) let cols = int(ceil(sceneW / float(cell)))
let rows = int(ceil(sceneW / float(cell))) let rows = int(ceil(sceneW / float(cell)))
for (_, pts) in polys: for (_, pts) in polysChecks:
for (cx, cy) in cellsTouched(pts, float(cell)): for (cx, cy) in cellsTouched(pts, float(cell)):
# cells outside the world are not cells: the server drops them too (vision.refresh) # cells outside the world are not cells: the server drops them too (vision.refresh)
if cx < 0 or cy < 0 or cx >= cols or cy >= rows: continue if cx < 0 or cy < 0 or cx >= cols or cy >= rows: continue
@@ -617,7 +709,7 @@ proc main() =
if k in recomputedSoFar: continue if k in recomputedSoFar: continue
let cx = k mod cols let cx = k mod cols
let cy = k div cols let cy = k div cols
if definitelySeen(truth.walls, polys, sceneW, cell, cx, cy): if definitelySeen(truth.walls, polysChecks, sceneW, cell, cx, cy):
recomputed.incl k # grazed cell the sampler does see: fine either way recomputed.incl k # grazed cell the sampler does see: fine either way
continue continue
# attribution: a cell only the other player has explored is a presence leak, not a bad cell # attribution: a cell only the other player has explored is a presence leak, not a bad cell
@@ -637,7 +729,7 @@ proc main() =
if missing > 3: if missing > 3:
fail "EXPLORED", $missing & " recomputed explored cells were never sent" fail "EXPLORED", $missing & " recomputed explored cells were never sent"
if getEnv("LEAK_DEBUG") != "": if getEnv("LEAK_DEBUG") != "":
for (id, pts) in polys: for (id, pts) in polysChecks:
var cx0 = 100000; var cx1 = -1; var cy0 = 100000; var cy1 = -1 var cx0 = 100000; var cx1 = -1; var cy0 = 100000; var cy1 = -1
for (cx, cy) in cellsTouched(pts, float(cell)): for (cx, cy) in cellsTouched(pts, float(cell)):
cx0 = min(cx0, cx); cx1 = max(cx1, cx); cy0 = min(cy0, cy); cy1 = max(cy1, cy) cx0 = min(cx0, cx); cx1 = max(cx1, cx); cy0 = min(cy0, cy); cy1 = max(cy1, cy)
@@ -645,7 +737,7 @@ proc main() =
" group ", g.label, " cell ", cell, " sceneW ", sceneW " group ", g.label, " cell ", cell, " sceneW ", sceneW
# --- the clear-segment oracle on the polygon itself ----------------------------------------- # --- the clear-segment oracle on the polygon itself -----------------------------------------
for (id, pts) in polys: for (id, pts) in polysChecks:
if pts.len < 3: continue if pts.len < 3: continue
var t: TruthToken var t: TruthToken
for tid, tt in truth.tokens: for tid, tt in truth.tokens:
+3 -1
View File
@@ -93,7 +93,9 @@ export async function startTestNginx({ backendPort, stateDir, port }) {
if (!(await portIsFree(port))) throw new Error(`test nginx port ${port} is already in use`) if (!(await portIsFree(port))) throw new Error(`test nginx port ${port} is already in use`)
const prefix = path.join(stateDir, 'nginx') const prefix = path.join(stateDir, 'nginx')
fs.mkdirSync(prefix, { recursive: true }) fs.mkdirSync(prefix, { recursive: true })
for (const d of ['client_body', 'proxy', 'fastcgi', 'uwsgi', 'scgi']) fs.mkdirSync(path.join(prefix, d)) for (const d of ['client_body', 'proxy', 'fastcgi', 'uwsgi', 'scgi']) {
fs.mkdirSync(path.join(prefix, d), { recursive: true })
}
const confPath = path.join(prefix, 'nginx.conf') const confPath = path.join(prefix, 'nginx.conf')
fs.writeFileSync(confPath, config({ prefix, port, backendPort, stateDir })) fs.writeFileSync(confPath, config({ prefix, port, backendPort, stateDir }))
const logFd = fs.openSync(path.join(prefix, 'stderr.log'), 'a') const logFd = fs.openSync(path.join(prefix, 'stderr.log'), 'a')
+387
View File
@@ -0,0 +1,387 @@
// Walls r1 (#58, DESIGN 5.8, TESTING 10.3): one-way sight over the real binary and the test nginx.
// One scene, one full-height one-way wall and two players on its two sides:
// - the player on the blind side gets no token, explored cell or tile across the wall;
// - the player on the seeing side does (the positive control, so the oracle can fail);
// - flipping `sight_dir` swaps the blind side without moving the endpoints and with no
// normalisation: explored cells and allowed tiles only ever grow, never shrink;
// - after a restart the direction and the walls are identical and nothing is revoked.
// The oracle below is this file's OWN: it reads the GM's wall truth, applies its own side test
// (cross product with the (-dy, dx) normal of `a -> b`) and samples clear segments per cell. It
// never calls the server's vision or explored code.
import test from 'node:test'
import assert from 'node:assert/strict'
import fs from 'node:fs'
import { baseUrl, createPlayer, freePort, namePlayer, sleep } from './lib.mjs'
import { gmKeyOf, makeStateDir, openAs, startServer, stopServer } from './withserver.mjs'
import { startTestNginx, stopTestNginx } from './nginx.mjs'
import { writeTileGrid } from './tilefixture.mjs'
const ALICE = 'Alice'
const BOB = 'Bob'
const CELL = 32 // v1 pins tile_size = cell (Q4); the oracle and the tile sweep both use it
const WALL_X = 400
const WALL = { a: [WALL_X, 0], b: [WALL_X, 4096], preset: 'one_way' } // sight_dir defaults to left
// The first cell wholly east of the drawn line: the wall at x=400 sits inside cell 12.
const EAST_EDGE = Math.ceil(WALL_X / CELL) * CELL
const REGION = { x0: 5, x1: 17, y0: 5, y1: 12 }
const Tol = 0.5
// ---------------------------------------------------------------------------------------------
// A stack: real server + test nginx in front (the production shape of 11.1).
async function withOneWayStack(fn) {
const stateDir = makeStateDir()
const gmKey = gmKeyOf(stateDir)
const stack = { stateDir, gmKey }
const boot = async () => {
stack.nginxPort = await freePort()
stack.server = await startServer({ stateDir, publicOrigin: baseUrl(stack.nginxPort) })
stack.nginx = await startTestNginx({ backendPort: stack.server.port, stateDir,
port: stack.nginxPort })
stack.origin = stack.nginx.origin
}
const down = async () => {
await stopTestNginx(stack.nginx)
await stopServer(stack.server)
}
await boot()
const api = {
stateDir, gmKey, boot, down,
get origin() { return stack.origin },
}
try {
return await fn(api)
} finally {
await down()
fs.rmSync(stateDir, { recursive: true, force: true })
}
}
async function gmConnect(origin, gmKey) {
const conn = await openAs(origin, gmKey)
const hello = await conn.ws.waitText('hello')
const walls = await conn.ws.waitText('walls')
return { ...conn, scene: walls.scene, walls, art: hello.scene.art_version }
}
// ---------------------------------------------------------------------------------------------
// The independent oracle: the side test, the sight wall list and the per-cell clear-segment sample.
function blindTo(w, o) {
// DESIGN 5.8: `sight_dir` names the blind side of `a -> b`; `left` is the (-dy, dx) normal. The
// cross product of the a->b direction with (o - a) is the signed distance along that normal.
if (w.sight_dir !== 'left' && w.sight_dir !== 'right') return false
const dx = w.b[0] - w.a[0], dy = w.b[1] - w.a[1]
const s = dx * (o.y - w.a[1]) - dy * (o.x - w.a[0])
return w.sight_dir === 'left' ? s >= -1e-9 : s <= 1e-9
}
function sightBlocking(wallsFrame, viewer) {
// Today's blocking rule is `not (door and open)`, plus the one-way side test. A one-way wall is
// in the viewer's fan only while the viewer stands on the blind side (a wall it sees across is
// absent from the fan). This is the file's own copy, never server vision code.
return wallsFrame.walls
.filter(w => !(w.door && w.open) && !((w.sight_dir === 'left' || w.sight_dir === 'right') &&
!blindTo(w, viewer)))
.map(w => ({ a: { x: w.a[0], y: w.a[1] }, b: { x: w.b[0], y: w.b[1] } }))
}
function segDist(p, a, b) {
const ex = b.x - a.x
const ey = b.y - a.y
const l2 = ex * ex + ey * ey
const t = l2 === 0 ? 0 : Math.max(0, Math.min(1, ((p.x - a.x) * ex + (p.y - a.y) * ey) / l2))
return Math.hypot(p.x - a.x - t * ex, p.y - a.y - t * ey)
}
function orient(a, b, c) {
return (b.x - a.x) * (c.y - a.y) - (b.y - a.y) * (c.x - a.x)
}
function properCross(p, q, a, b) {
const d1 = orient(p, q, a), d2 = orient(p, q, b), d3 = orient(a, b, p), d4 = orient(a, b, q)
return d1 * d2 < 0 && d3 * d4 < 0
}
function segGap(p, q, a, b) {
if (properCross(p, q, a, b)) return 0
return Math.min(segDist(p, a, b), segDist(q, a, b), segDist(a, p, q), segDist(b, p, q))
}
// sure = a lattice point inside the inscribed 64-gon whose LOS is > Tol from every blocking wall;
// maybe = a point within radius + Tol whose LOS no blocking wall properly crosses.
function oracleCell({ o, radius, walls, cell, x, y }) {
const rin = radius * Math.cos(Math.PI / 64) - Tol
const x0 = x * cell, y0 = y * cell
let sure = false, maybe = false
const n = 16
for (let j = 0; j <= n && !(sure && maybe); j++) {
for (let i = 0; i <= n; i++) {
const p = { x: x0 + (cell * i) / n, y: y0 + (cell * j) / n }
const d = Math.hypot(p.x - o.x, p.y - o.y)
if (!maybe && d <= radius + Tol) {
let clear = true
for (const w of walls) if (properCross(o, p, w.a, w.b)) { clear = false; break }
if (clear) maybe = true
}
if (!sure && d <= rin) {
let clear = true
for (const w of walls) if (segGap(o, p, w.a, w.b) <= Tol) { clear = false; break }
if (clear) sure = true
}
if (sure && maybe) break
}
}
return { sure, maybe }
}
// ---------------------------------------------------------------------------------------------
function collectExplored(ws) {
const cells = new Set()
for (const m of ws.messages) {
if (m.t !== 'explored') continue
if (m.full) {
for (const row of m.rle) {
const cy = row[0]
for (let i = 1; i < row.length; i += 2) {
for (let k = 0; k < row[i + 1]; k++) cells.add(`${row[i] + k},${cy}`)
}
}
} else {
for (const [cx, cy] of m.cells) cells.add(`${cx},${cy}`)
}
}
return cells
}
function assertSuperset(after, before, what) {
for (const k of before) assert.ok(after.has(k), `${what} lost ${k} (explored/tiles never shrink)`)
}
async function sweepTiles({ origin, cookie, scene, art, wallsFrame, o, radius, cell,
strictMaybes = true }) {
const walls = sightBlocking(wallsFrame, o)
const allowed = new Set()
let sure = 0
for (let y = REGION.y0; y <= REGION.y1; y++) {
for (let x = REGION.x0; x <= REGION.x1; x++) {
const vis = oracleCell({ o, radius, walls, cell, x, y })
if (vis.sure) sure++
const r = await fetch(`${origin}/tiles/${scene}/v${art}/${x}_${y}.png`,
{ headers: { Cookie: cookie } })
const at = `tile ${x},${y} (sure=${vis.sure} maybe=${vis.maybe})`
if (r.status === 200) {
allowed.add(`${x},${y}`)
// Explored only grows: once a cell was seen, its tile stays allowed even when a later flip
// puts it on the blind side again. Only a fresh region may be checked for invented cells.
if (strictMaybes) {
assert.ok(vis.maybe, `${at}: allowed although the oracle cannot see any point in the cell`)
}
} else {
assert.equal(r.status, 403, `${at}: unexpected status ${r.status}`)
assert.ok(!vis.sure, `${at}: refused although the oracle is sure the cell is visible`)
}
}
}
return { allowed, sure }
}
function eastOfWall(cells) {
const out = []
for (const k of cells) {
const [cx, cy] = k.split(',').map(Number)
if (cx * CELL >= EAST_EDGE) out.push(k)
}
return out
}
// ---------------------------------------------------------------------------------------------
test('one-way sight: the blind side sees nothing across, the seeing side does (#58)', async () => {
await withOneWayStack(async ({ origin, gmKey, stateDir }) => {
const gm = await gmConnect(origin, gmKey)
const ack = await gm.ws.request({ t: 'wall.add', scene: gm.scene, ...WALL })
assert.equal(ack.ok, true, JSON.stringify(ack))
const wall = await gm.ws.waitFor(m => m.t === 'wall' && m.id === ack.id)
assert.equal(wall.sight_dir, 'left')
assert.equal(wall.kind, 'one_way')
assert.deepEqual(wall.a, WALL.a)
assert.deepEqual(wall.b, WALL.b)
const wallsFrame = { walls: [wall] }
const alice = await createPlayer(gm.ws)
const bob = await createPlayer(gm.ws)
await namePlayer(origin, alice.key, ALICE)
await namePlayer(origin, bob.key, BOB)
const mkToken = async (player, pos, name) => {
const a = await gm.ws.request({ t: 'token.create', scene: gm.scene, kind: 'pc', pos,
flags: { vision: true }, vision_radius: 400,
controller: player.id, descriptive_name: name,
actual_name: name })
assert.equal(a.ok, true, JSON.stringify(a))
return (await gm.ws.waitFor(m => m.t === 'token' && m.id === a.id)).id
}
const aliceToken = await mkToken(alice, [300, 300], ALICE) // west, the blind (left) side
const bobToken = await mkToken(bob, [500, 400], BOB) // east, the seeing side
const a = await openAs(origin, alice.key)
await a.ws.waitText('hello')
await a.ws.waitFor(m => m.t === 'explored' && m.full === true)
const b = await openAs(origin, bob.key)
await b.ws.waitText('hello')
await b.ws.waitFor(m => m.t === 'explored' && m.full === true)
await sleep(100)
// Blind side: no token frame, no encountered entry, and no explored cell east of the wall.
assert.equal(a.ws.messages.some(m => m.t === 'token' && m.id === bobToken), false,
'the blind side received a token across the one-way wall')
const encountered = a.ws.messages.filter(m => m.t === 'encountered')
.flatMap(m => (m.set ?? []).map(e => e.id))
assert.equal(encountered.includes(bobToken), false,
'the blind side encountered a token across the one-way wall')
const aliceExplored = collectExplored(a.ws)
assert.deepEqual(eastOfWall(aliceExplored), [],
'the blind side explored a cell east of the wall')
assert.ok(aliceExplored.has('9,9'), 'the blind side did not explore its own cell (control)')
// Seeing side (positive control): the same wall lets Bob see Alice's token and west cells.
assert.ok(b.ws.messages.some(m => m.t === 'token' && m.id === aliceToken),
'the seeing side did not receive the token across the one-way wall')
const bobExplored = collectExplored(b.ws)
assert.ok(bobExplored.has('9,9'), 'the seeing side did not explore a cell west of the wall')
// Direction is sight only: the wall blocks movement both ways (story 22).
const crossFromBlind = await a.ws.request({ t: 'token.move', id: aliceToken, pos: [450, 300] })
assert.equal(crossFromBlind.ok, false, 'the blind side walked through the one-way wall')
const crossFromSeeing = await b.ws.request({ t: 'token.move', id: bobToken, pos: [350, 400] })
assert.equal(crossFromSeeing.ok, false, 'the seeing side walked through the one-way wall')
// Tiles, blind side: every allowed tile is oracle-maybe, every oracle-sure tile is allowed, and
// the east shadow (full-height wall) is refused.
const scene = gm.scene
writeTileGrid(stateDir, { scene, artVersion: gm.art, size: CELL, ...REGION })
const blind = await sweepTiles({ origin, cookie: a.cookie, scene, art: gm.art, wallsFrame,
o: { x: 300, y: 300 }, radius: 400, cell: CELL })
assert.ok(blind.sure > 15, `the blind-side oracle sampled too little (sure=${blind.sure})`)
assert.ok(blind.allowed.size > 10, `the gate allowed too few blind-side tiles (${blind.allowed.size})`)
for (let y = REGION.y0; y <= REGION.y1; y++) {
for (let x = EAST_EDGE / CELL; x <= REGION.x1; x++) {
const shadow = oracleCell({ o: { x: 300, y: 300 }, radius: 400,
walls: sightBlocking(wallsFrame, { x: 300, y: 300 }),
cell: CELL, x, y })
assert.equal(shadow.maybe, false, `oracle says cell ${x},${y} east of the wall is visible`)
assert.equal(blind.allowed.has(`${x},${y}`), false,
`the blind side was allowed tile ${x},${y} behind the wall`)
}
}
// --- flip: same endpoints, other blind side ------------------------------------------------
const upd = await gm.ws.request({ t: 'wall.update', scene, id: wall.id, sight_dir: 'right' })
assert.equal(upd.ok, true, JSON.stringify(upd))
const flipped = await gm.ws.waitFor(m => m.t === 'wall' && m.id === wall.id &&
m.sight_dir === 'right')
assert.deepEqual(flipped.a, WALL.a, 'the flip moved endpoint a')
assert.deepEqual(flipped.b, WALL.b, 'the flip moved endpoint b')
assert.equal(flipped.kind, 'one_way')
await a.ws.waitFor(m => m.t === 'token' && m.id === bobToken)
await b.ws.waitFor(m => m.t === 'token_gone' && m.id === aliceToken)
const aliceSaw = await a.ws.waitFor(m => m.t === 'explored' && m.full === false)
assert.ok(aliceSaw.cells.length > 0, 'the newly seeing side explored no cell after the flip')
const aliceAfter = collectExplored(a.ws)
assertSuperset(aliceAfter, aliceExplored, 'the flipped side')
assert.ok(eastOfWall(aliceAfter).length > 0, 'the seeing side never explored across after the flip')
const bobAfter = collectExplored(b.ws)
assertSuperset(bobAfter, bobExplored, 'the side that lost sight')
const flippedFrame = { walls: [flipped] }
// Tiles after the flip: previously allowed blind-side tiles stay allowed (no revoke) and the
// newly seeing side gains at least one eastern tile (positive control).
const seen = await sweepTiles({ origin, cookie: a.cookie, scene, art: gm.art,
wallsFrame: flippedFrame, o: { x: 300, y: 300 }, radius: 400,
cell: CELL })
assertSuperset(seen.allowed, blind.allowed, 'tiles after the flip')
assert.ok([...seen.allowed].some(k => Number(k.split(',')[0]) >= 13),
'the seeing side gained no tile east of the wall after the flip')
// --- flip back: nothing is ever revoked ----------------------------------------------------
const back = await gm.ws.request({ t: 'wall.update', scene, id: wall.id, sight_dir: 'left' })
assert.equal(back.ok, true, JSON.stringify(back))
const again = await gm.ws.waitFor(m => m.t === 'wall' && m.id === wall.id &&
m.sight_dir === 'left')
assert.deepEqual(again.a, WALL.a)
assert.deepEqual(again.b, WALL.b)
const blindAgain = await sweepTiles({ origin, cookie: a.cookie, scene, art: gm.art,
wallsFrame: { walls: [again] }, o: { x: 300, y: 300 },
radius: 400, cell: CELL, strictMaybes: false })
assertSuperset(blindAgain.allowed, seen.allowed, 'tiles after the flip back')
assertSuperset(collectExplored(a.ws), aliceAfter, 'explored after the flip back')
a.ws.close(); b.ws.close(); gm.ws.close()
})
})
test('one-way sight: the direction and the walls survive a restart (#58)', async () => {
await withOneWayStack(async ctx => {
let origin = ctx.origin
const { gmKey, stateDir, boot, down } = ctx
let gm = await gmConnect(origin, gmKey)
const ack = await gm.ws.request({ t: 'wall.add', scene: gm.scene, ...WALL })
assert.equal(ack.ok, true, JSON.stringify(ack))
await gm.ws.waitFor(m => m.t === 'wall' && m.id === ack.id)
const alice = await createPlayer(gm.ws)
await namePlayer(origin, alice.key, ALICE)
const mk = await gm.ws.request({ t: 'token.create', scene: gm.scene, kind: 'pc', pos: [300, 300],
flags: { vision: true }, vision_radius: 400,
controller: alice.id, descriptive_name: ALICE,
actual_name: ALICE })
assert.equal(mk.ok, true, JSON.stringify(mk))
const bob = await gm.ws.request({ t: 'token.create', scene: gm.scene, kind: 'pc', pos: [500, 400],
flags: { vision: true }, vision_radius: 400,
descriptive_name: BOB, actual_name: BOB })
assert.equal(bob.ok, true, JSON.stringify(bob))
const scene = gm.scene
const art = gm.art
writeTileGrid(stateDir, { scene, artVersion: art, size: CELL, ...REGION })
const wallsFrame = { walls: [await gm.ws.waitFor(m => m.t === 'wall' && m.id === ack.id)] }
let a = await openAs(origin, alice.key)
await a.ws.waitText('hello')
await a.ws.waitFor(m => m.t === 'explored' && m.full === true)
await sleep(100)
assert.equal(a.ws.messages.some(m => m.t === 'token' && m.id === bob.id), false)
const before = collectExplored(a.ws)
const beforeTiles = await sweepTiles({ origin, cookie: a.cookie, scene, art, wallsFrame,
o: { x: 300, y: 300 }, radius: 400, cell: CELL })
assert.ok(beforeTiles.allowed.size > 10)
a.ws.close(); gm.ws.close()
// Restart in place: same state dir, real binary migrates/reopens, nothing is rebuilt by hand.
await down()
await boot()
origin = ctx.origin
gm = await gmConnect(origin, gmKey)
const snap = gm.walls
assert.equal(snap.walls.length, 1)
assert.equal(snap.walls[0].sight_dir, 'left')
assert.equal(snap.walls[0].kind, 'one_way')
assert.deepEqual(snap.walls[0].a, WALL.a)
assert.deepEqual(snap.walls[0].b, WALL.b)
a = await openAs(origin, alice.key)
await a.ws.waitText('hello')
await a.ws.waitFor(m => m.t === 'explored' && m.full === true)
await sleep(100)
assertSuperset(collectExplored(a.ws), before, 'explored across the restart')
assert.equal(a.ws.messages.some(m => m.t === 'token' && m.id === bob.id), false,
'the restarted server let the blind side see across')
const afterTiles = await sweepTiles({ origin, cookie: a.cookie, scene, art: art,
wallsFrame: { walls: snap.walls }, o: { x: 300, y: 300 },
radius: 400, cell: CELL, strictMaybes: false })
assertSuperset(afterTiles.allowed, beforeTiles.allowed, 'tiles across the restart')
a.ws.close(); gm.ws.close()
})
})