Files
FFF_vtt_frozen/tools/leakcheck.nim
T
SirStone 77fa2dfe4c feat(walls): proto 2 typed wall record, inert geometry, derived kind (#54)
wall.add/wall.update take thickness, position, height and the eight raw
switches; kind is output-only and the GM wall frames echo the full typed
record. Geometry is stored but inert (0/full/centre behaviour), and the
legacy kind/open wire adapter is gone. proto is bumped to 2 with the
harness default, and BannedAlways gains every wall field name with a
WALLDATA positive control.

Tests: schema-7 migrated scene vs the same walls authored via raw switches
gives byte-identical player frames, refusals and per-tile statuses.
Nim 382 / Node 113 green.
2026-11-19 22:21:47 +01:00

675 lines
32 KiB
Nim

## Leak checker: replays a leak-transcript.jsonl written by tools/leak.mjs and verifies one player's
## whole view (DESIGN 10.1, 10.2, 10.3; M3 slice 5 / #20). Ground truth is the GM socket: the GM sees
## every token and every wall, so the checker never trusts the subject's own messages for *what is*.
##
## Independent oracles: the subject's visibility polygons and explored cells are recomputed from the
## GM's truth with geometry.nim, and the explored set is additionally probed with a clear-segment
## test (no ray fan), because the prototype's explored check was self-consistent only (10.2).
##
## Every failure carries a class, and tools/fault.test.mjs asserts the EXACT class set of each
## injected server fault:
## HIDDEN_TOKEN a token the subject may not see reached it
## GMONLY_TOKEN the same, for a `gm_only` token inside the subject's LOS
## WALLDATA a wall-ish key or frame reached the subject
## WITHHELD a token the subject may see was not sent (or was taken away while visible)
## NO_REMOVE a token that left the view was never withdrawn
## OWN_VIEW the subject's own token position or its vision polygon is wrong
## OTHER_PLAYER another player's polygon, `mine` flag, explored cells or presence leaked
## EXPLORED the explored set differs from the recomputation / the clear-segment oracle
## OWNER_PROP the `owner` property bucket reached someone who does not control the token
## GM_PROP the `gm` property bucket reached a player at all
## STATUS_SOURCE a player frame carried the `source` of a status (5.5, 6.1 note 6)
## ACTUAL_NAME an actual name the subject was never told reached it (8)
## STALE_NAME an encountered entry names a subject something other than the name that player
## knows (8): a stale snapshot the old "not the unrevealed actual" check let pass
## CHAR_LIST another player's character record or encountered entry reached the subject
## 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)
## GEOMETRY the recomputed polygon disagrees with the clear-segment oracle (sanity)
## PROTOCOL a frame the catalogue does not allow, a bad `n` sequence, a missing hello block
##
## usage: leakcheck <transcript.jsonl> <SUBJECT> exit 0 = clean
import std/[algorithm, json, math, options, os, sets, strutils, tables]
import geometry
const
AllowedTypes = ["hello", "ack", "roster", "token", "token_gone", "vision", "explored",
"character", "character_gone", "encountered"]
BannedAlways = ["walls", "wall", "wall_gone", "a", "b", "open", "kind", "controller", "gm_only",
"flags", "radius_own", "extra",
# every wall field name (#54): geometry, switches, door settings, label
"thickness", "position", "height", "blocks_sight", "blocks_movement", "sight_dir",
"player_marker", "door", "secret", "locked", "label"]
BannedToken = ["descriptive_name", "actual_name", "reveal_all", "revealed"]
BannedCharacterTop = ["owner", "reveal_all", "revealed"] ## top-level only: `props.owner` is fine
BannedEncountered = ["player", "character_id", "pos"]
type
TruthToken = object
pos: Vec
controller: int
gmOnly: bool
hasVision: bool
visionRadius: Option[float]
radius: float
props: JsonNode ## the GM's three buckets (the truth for every bucket question)
statuses: seq[string] ## the status names the GM sees, in order
characterId: string ## "" = a plain token (8)
descriptive, actual: string ## a plain token's own names ("" for a linked token)
revealAll: bool ## a plain token's reveal flag, "" names otherwise
revealed: seq[int] ## the players a plain token's actual name was revealed to
TruthCharacter = object
owner: int
descriptive, actual: string
revealAll: bool
revealed: seq[int]
props: JsonNode
Truth = object
walls: seq[Wall]
tokens: Table[string, TruthToken]
characters: Table[string, TruthCharacter]
Group = object
label: string
gmMsgs: seq[JsonNode]
subjMsgs: seq[JsonNode]
intents: seq[JsonNode] ## what the clients asked for in this group (see CONTROLLER_CHANGE)
var fails = 0
var classes: CountTable[string]
proc fail(cls, s: string) =
inc fails
classes.inc cls
if fails <= 25: echo "FAIL [", cls, "] ", s
proc vec(j: JsonNode): Vec = (j[0].getFloat, j[1].getFloat)
proc samePos(j: JsonNode, p: Vec): bool =
## JSON numbers lose their int/float spelling on the wire round trip: compare numerically.
j.kind == JArray and j.len == 2 and
abs(j[0].getFloat - p.x) < 1e-6 and abs(j[1].getFloat - p.y) < 1e-6
# ---------------------------------------------------------------------------------------------------
# Transcript
proc readGroups(path, subject: string): seq[Group] =
## One entry per group marker; every message belongs to the group that was open when it arrived.
var current = -1
var groups: seq[Group]
for line in lines(path):
if line.strip.len == 0: continue
let j = parseJson(line)
case j["k"].getStr
of "group":
groups.add Group(label: j["label"].getStr)
current = groups.high
of "msg":
if current < 0: continue
let who = j["who"].getStr
if who == "GM": groups[current].gmMsgs.add j["m"]
elif who == subject: groups[current].subjMsgs.add j["m"]
of "intent":
if current >= 0: groups[current].intents.add j
else: discard
groups
# ---------------------------------------------------------------------------------------------------
# Truth from the GM socket (walls and every token)
proc applyGmWalls(truth: var Truth, ids: var seq[int], m: JsonNode) =
## `wall` (upsert) and `wall_gone` need the id, which geometry.Wall does not carry.
case m["t"].getStr
of "walls":
truth.walls.setLen(0)
ids.setLen(0)
for w in m["walls"]:
truth.walls.add Wall(a: vec(w["a"]), b: vec(w["b"]),
door: w["door"].getBool, open: w["open"].getBool)
ids.add w["id"].getInt
of "wall":
let id = m["id"].getInt
let w = Wall(a: vec(m["a"]), b: vec(m["b"]), door: m["door"].getBool,
open: m["open"].getBool)
var found = false
for i in 0 ..< ids.len:
if ids[i] == id:
truth.walls[i] = w
found = true
if not found:
truth.walls.add w
ids.add id
of "wall_gone":
let id = m["id"].getInt
for i in 0 ..< ids.len:
if ids[i] == id:
truth.walls.delete i
ids.delete i
break
else: discard
proc applyGmTokens(truth: var Truth, m: JsonNode) =
case m["t"].getStr
of "token":
var t = TruthToken(pos: vec(m["pos"]), controller: (if m["controller"].kind == JNull: 0
else: m["controller"].getInt),
gmOnly: m["gm_only"].getBool,
hasVision: m["flags"].hasKey("vision") and
m["flags"]["vision"].kind == JBool and
m["flags"]["vision"].getBool,
radius: m["radius"].getFloat)
if m["vision_radius"].kind != JNull: t.visionRadius = some(m["vision_radius"].getFloat)
t.props = m["props"]
for st in m["statuses"]: t.statuses.add st["status"].getStr
# Slice 8 (#23): the GM frame always carries `character_id`, and a plain token carries its own
# names and reveal state (a linked token's live on the `character` record).
if m.hasKey("character_id") and m["character_id"].kind != JNull:
t.characterId = m["character_id"].getStr
if m.hasKey("descriptive_name"):
t.descriptive = m["descriptive_name"].getStr
t.actual = m["actual_name"].getStr
t.revealAll = m["reveal_all"].getBool
for p in m["revealed"]: t.revealed.add p.getInt
truth.tokens[m["id"].getStr] = t
of "token_gone":
truth.tokens.del m["id"].getStr
else: discard
proc applyGmCharacters(truth: var Truth, m: JsonNode) =
case m["t"].getStr
of "character":
var c = TruthCharacter(owner: m["owner"].getInt,
descriptive: m["descriptive_name"].getStr,
actual: m["actual_name"].getStr,
revealAll: m["reveal_all"].getBool, props: m["props"])
for p in m["revealed"]: c.revealed.add p.getInt
truth.characters[m["id"].getStr] = c
of "character_gone":
truth.characters.del m["id"].getStr
else: discard
# ---------------------------------------------------------------------------------------------------
# Independent oracles
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).
for w in walls:
if w.blocks and segsCross(o, p, w.a, w.b): return false
true
proc rangeOf(sceneDefault: float, t: TruthToken): float =
if t.hasVision and t.visionRadius.isSome and t.visionRadius.get > 0: t.visionRadius.get
else: sceneDefault
proc polygonsOf(truth: Truth, controller: int, sceneDefault: float): seq[(string, seq[Vec])] =
for id, t in truth.tokens:
if t.controller != controller or not t.hasVision: continue
result.add (id, visibilityPolygon(t.pos, truth.walls, rangeOf(sceneDefault, t)))
# 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]))
proc insideAny(polys: seq[(string, seq[Vec])], p: Vec): bool =
for (_, pts) in polys:
if inside(pts, p): return true
proc cellOf(sceneW: float, cell: int, ix, iy: int): (float, float) =
(float(ix * cell) + float(cell) / 2, float(iy * cell) + float(cell) / 2)
proc definitelySeen(walls: seq[Wall], polys: seq[(string, seq[Vec])], sceneW: float,
cell, cx, cy: int): bool =
## A cell is seen if any of its corners or its centre is in clear LOS inside a polygon. The
## tolerance for the opposite direction (explored but no sample in LOS) lives in the caller.
let (mx, my) = cellOf(sceneW, cell, cx, cy)
let pts = [(mx, my), (float(cx * cell), float(cy * cell)),
(float((cx + 1) * cell), float(cy * cell)),
(float((cx + 1) * cell), float((cy + 1) * cell)),
(float(cx * cell), float((cy + 1) * cell))]
for p in pts:
if insideAny(polys, p) and clearLine(walls, (mx, my), p): return true
false
proc keysDeep(node: JsonNode, into: var HashSet[string]) =
if node.kind == JObject:
for k, v in node:
into.incl k
keysDeep(v, into)
elif node.kind == JArray:
for v in node: keysDeep(v, into)
# ---------------------------------------------------------------------------------------------------
proc subjectKnewActual(truth: Truth, t: TruthToken, me: int): bool =
## DESIGN 8: a player is told a subject's actual name when they own the character it belongs to,
## when the GM revealed it to everyone, or when the GM revealed it to them.
if t.characterId.len > 0:
if not truth.characters.hasKey(t.characterId): return false
let c = truth.characters[t.characterId]
result = c.owner == me or c.revealAll or me in c.revealed
else:
result = t.revealAll or me in t.revealed
proc subjectNames(truth: Truth, t: TruthToken): (string, string) =
## The descriptive and actual name of what a token figures: the character's when linked (8).
if t.characterId.len > 0 and truth.characters.hasKey(t.characterId):
let c = truth.characters[t.characterId]
(c.descriptive, c.actual)
else:
(t.descriptive, t.actual)
proc checkArgs(): (string, string) =
if paramCount() < 2:
echo "usage: leakcheck <transcript.jsonl> <SUBJECT>"
quit 2
(paramStr(1), paramStr(2))
proc main() =
let (path, subject) = checkArgs()
let groups = readGroups(path, subject)
if groups.len == 0:
echo "leakcheck: no groups in ", path
quit 2
var truth: Truth
var wallIds: seq[int]
var me = 0
var other = 0
var sceneDefault = 400.0
var sceneW = 4096.0
var cell = 32
var haveHello = false
var expectedN = 1
# what the subject has been told
var view: Table[string, JsonNode] # token id -> last `token` frame
var leaked: Table[string, string] # token id -> the class it was first reported under
var exploredSent: HashSet[int]
var otherExplored: HashSet[int]
var removes = 0
var groupsSeen = 0
var recomputedSoFar: HashSet[int] # every cell the subject has ever seen, recomputed
var seenAny: HashSet[string] # token ids the subject was legitimately shown
var encounterable: HashSet[string] # token ids the subject may have met (independent oracle)
var viewCharacters: HashSet[string] # character ids the subject was sent
var prevController: Table[string, int] # controller of each token at the previous group
for g in groups:
inc groupsSeen
for m in g.gmMsgs:
applyGmWalls(truth, wallIds, m)
applyGmTokens(truth, m)
applyGmCharacters(truth, m)
# player ids: the subject from its hello, the other from any token it does not control
for m in g.subjMsgs:
if m["t"].getStr == "hello":
haveHello = true
me = m["me"]["id"].getInt
if m.hasKey("scene"):
sceneW = m["scene"]["w"].getFloat
cell = m["scene"]["cell"].getInt
sceneDefault = m["scene"]["vision_radius_default"].getFloat
else:
fail "PROTOCOL", "hello without a scene block for a named player"
for id, t in truth.tokens:
if me != 0 and t.controller != me and t.controller != 0 and
(other == 0 or t.controller < other):
other = t.controller
# Before the subject's hello there is no subject side to check: `me` is unknown, so "mine" and
# "visible to the subject" would both be meaningless. Always apply the GM truth first.
if me == 0: continue
let polys = polygonsOf(truth, me, sceneDefault)
let otherPolys = if other != 0: polygonsOf(truth, other, sceneDefault) else: @[]
# 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
# met. It only grows, exactly like the server's list (8).
var visibleNow = initHashSet[string]()
for id, actual in truth.tokens:
if actual.controller == me or (not actual.gmOnly and insideAny(polys, actual.pos)):
visibleNow.incl id
encounterable.incl id
# the other player's explored cells, independently (attribute leaks, 3.1 OTHER_PLAYER)
for (_, pts) in otherPolys:
for (cx, cy) in cellsTouched(pts, float(cell)):
if cx < 0 or cy < 0: continue
otherExplored.incl cy * int(ceil(sceneW / float(cell))) + cx
# --- the subject's frames of this group -----------------------------------------------------
for m in g.subjMsgs:
let t = m["t"].getStr
if not m.hasKey("n") or m["n"].getInt != expectedN:
fail "PROTOCOL", "n " & (if m.hasKey("n"): $m["n"].getInt else: "missing") &
" where " & $expectedN & " was expected (" & t & ")"
expectedN = (if m.hasKey("n"): m["n"].getInt else: expectedN) + 1
if t notin AllowedTypes:
fail (if t in ["walls", "wall", "wall_gone"]: "WALLDATA" else: "PROTOCOL"),
"frame type the catalogue forbids: " & t
continue
var keys = initHashSet[string]()
keysDeep(m, keys)
for k in keys:
if k == "source":
# 5.5 / 6.1 note 6: a viewer sees the status, never what caused it.
fail "STATUS_SOURCE", "player frame carries a status source"
elif k in BannedAlways:
fail "WALLDATA", "player frame has wall-ish/GM-only key " & k
if t == "token":
for k in BannedToken:
if k in keys: fail "WALLDATA", "a `token` frame for a player carries " & k
elif t == "character":
# An owner reads both names and its own `props.owner`; it must never learn `owner` (theirs),
# `reveal_all` or the list of players a name was revealed to.
for k, _ in m:
if k in BannedCharacterTop: fail "CHAR_LIST", "a `character` frame carries " & k
elif t == "encountered":
for k in BannedEncountered:
if k in keys: fail "CHAR_LIST", "an `encountered` frame carries " & k
case t
of "ack":
# only a bad shape is interesting here; the driver already checked the outcomes it expected
if m["ok"].getBool and m.hasKey("code"): fail "PROTOCOL", "ok ack with a code"
of "token":
let id = m["id"].getStr
if id notin truth.tokens:
fail "HIDDEN_TOKEN", "token " & id & " is not in the GM's truth"
continue
let actual = truth.tokens[id]
# props: the public bucket always, the owner bucket only for the controller, the gm bucket
# never (6.1 leak notes; the typed view has no field for it, so an injected fault shows here)
var buckets = initHashSet[string]()
if m.hasKey("props") and m["props"].kind == JObject:
for name, _ in m["props"]: buckets.incl name
if "gm" in buckets:
fail "GM_PROP", "token " & id & " carried the gm property bucket to a player"
# A frame that claims `mine` is the OTHER_PLAYER fault's shape: the bucket then matches the
# (wrong) claim, so the claim itself is what gets reported, not the bucket.
if "owner" in buckets and not (actual.controller == me) and not m["mine"].getBool:
fail "OWNER_PROP", "token " & id & " carried the owner bucket to a non-controller"
if actual.controller == me and "owner" notin buckets:
fail "OWNER_PROP", "the controller is missing the owner bucket of token " & id
if m.hasKey("props"):
for name in ["public", "owner"]:
if name notin buckets or not actual.props.hasKey(name): continue
if m["props"][name] != actual.props[name]:
fail (if name == "public": "OWN_VIEW" else: "OWNER_PROP"),
"token " & id & " has a " & name & " bucket that is not the truth"
# statuses: the names the GM sees, and nothing else on the entry
var gotStatuses: seq[string]
for st in m["statuses"]:
if st.len != 1: fail "STATUS_SOURCE", "a player status entry carries more than `status`"
gotStatuses.add st["status"].getStr
if gotStatuses != actual.statuses:
fail "OWN_VIEW", "token " & id & " statuses " & $gotStatuses & " != truth " &
$actual.statuses
if not samePos(m["pos"], actual.pos):
fail "OWN_VIEW", "token " & id & " position " & $m["pos"] & " != truth " &
$[actual.pos.x, actual.pos.y]
let wantMine = actual.controller == me
if m["mine"].getBool != wantMine:
fail (if wantMine: "OWN_VIEW" else: "OTHER_PLAYER"), "mine flag on " & id
# names (8): the one name this recipient may see, from the character when the token is linked
let (dname, aname) = subjectNames(truth, actual)
let knows = subjectKnewActual(truth, actual, me)
let wantName = if knows: aname else: dname
if m["name"].getStr != wantName:
if aname != dname and m["name"].getStr == aname:
fail "ACTUAL_NAME", "token " & id & " carries an actual name the subject was not told"
else:
fail "OWN_VIEW", "token " & id & " name " & m["name"].getStr & " != " & wantName
# `character_id` goes only to the GM and the character's owner (6.1 leak note 2): showing it
# to anyone else would link two tokens of one character (10.3 CHAR_LIST).
if m.hasKey("character_id"):
let owned = actual.characterId.len > 0 and truth.characters.hasKey(actual.characterId) and
truth.characters[actual.characterId].owner == me
if not owned or m["character_id"].getStr != actual.characterId:
fail "CHAR_LIST", "token " & id & " carries character_id to a non-owner"
# cprops: the character's `public` bucket and nothing else, `{}` when there is nothing to say
if m.hasKey("cprops"):
for name, _ in m["cprops"]:
if name != "public":
fail "CHAR_OWNER_PROP", "token " & id & " cprops carries the " & name & " bucket"
var want = newJObject()
if actual.characterId.len > 0 and truth.characters.hasKey(actual.characterId) and
truth.characters[actual.characterId].owner != me:
want = truth.characters[actual.characterId].props["public"]
let got = if m["cprops"].hasKey("public"): m["cprops"]["public"] else: newJObject()
if got != want:
fail "CHAR_OWNER_PROP", "token " & id & " cprops public bucket is not the truth"
view[id] = m
let visible = wantMine or (not actual.gmOnly and insideAny(polys, actual.pos))
if not visible:
let cls = if actual.gmOnly and insideAny(polys, actual.pos): "GMONLY_TOKEN"
else: "HIDDEN_TOKEN"
leaked[id] = cls
fail cls, "token " & id & " sent but not visible (group " & g.label & ")"
else:
seenAny.incl id
of "token_gone":
let id = m["id"].getStr
if id notin view:
fail "PROTOCOL", "token_gone for a token this player never had: " & id
else:
view.del id
inc removes
if id in truth.tokens:
let actual = truth.tokens[id]
if actual.controller == me or (not actual.gmOnly and insideAny(polys, actual.pos)):
fail "WITHHELD", "token_gone for a token still visible: " & id
of "character":
# 6.1: a player gets only the characters it owns, with both names and the public/owner
# buckets. Anything else is CHAR_LIST (10.3).
let id = m["id"].getStr
if not truth.characters.hasKey(id):
fail "CHAR_LIST", "a character record the GM's truth does not have: " & id
elif truth.characters[id].owner != me:
fail "CHAR_LIST", "another player's character record: " & id
else:
let c = truth.characters[id]
if m["descriptive_name"].getStr != c.descriptive or
m["actual_name"].getStr != c.actual:
fail "PROTOCOL", "character " & id & " names differ from the truth"
for name, value in m["props"]:
if not c.props.hasKey(name) or c.props[name] != value:
fail (if name == "public": "OWN_VIEW" else: "CHAR_OWNER_PROP"),
"character " & id & " has a " & name & " bucket that is not the truth"
viewCharacters.incl id
of "character_gone":
let id = m["id"].getStr
if id notin viewCharacters:
fail "PROTOCOL", "character_gone for a character this player never had: " & id
viewCharacters.excl id
of "encountered":
# 6.1: the subject's own list only; an entry names a token the subject really did see, under
# the name it knows (8). No position, no character link.
for e in m["set"]:
let id = e["id"].getStr
if id notin encounterable:
fail "CHAR_LIST", "encountered entry the subject never saw: " & id
elif truth.tokens.hasKey(id):
let (dname, aname) = subjectNames(truth, truth.tokens[id])
let knows = subjectKnewActual(truth, truth.tokens[id], me)
# The expected name, not merely "not the unrevealed actual": a stale snapshot that still
# carries an old descriptive name is a bug the old check could not see (#30).
let want = if knows: aname else: dname
let got = e["name"].getStr
if got != want:
if aname != dname and got == aname:
fail "ACTUAL_NAME", "encountered " & id & " carries an unrevealed actual name"
else:
fail "STALE_NAME", "encountered " & id & " has name " & got & " not " & want &
" (group " & g.label & ")"
if m.hasKey("del"):
for d in m["del"]:
if d.getStr notin encounterable:
fail "CHAR_LIST", "del for an entry the subject never had: " & d.getStr
of "roster":
# 6.1 leak note 4: players see named players only.
for pl in m["players"]:
if pl["name"].kind == JNull or pl["name"].getStr.len == 0:
fail "PROTOCOL", "the roster handed a player an unnamed entry"
of "vision":
var got: seq[(string, seq[Vec])]
for p in m["polys"]:
var pts: seq[Vec]
for q in p["pts"]: pts.add vec(q)
got.add (p["id"].getStr, pts)
let want = polys
var haveIds = initHashSet[string]()
for (id, pts) in got:
haveIds.incl id
var matched = false
for (wid, wpts) in want:
if wid != id: continue
matched = true
if pts.len != wpts.len:
fail "OWN_VIEW", "polygon " & id & " has " & $pts.len & " of " & $wpts.len & " vertices"
else:
for i in 0 ..< pts.len:
# integer px on the wire (6.4): 0.5 px is the documented tolerance
if abs(pts[i].x - wpts[i].x) > 0.5 + 1e-6 or abs(pts[i].y - wpts[i].y) > 0.5 + 1e-6:
fail "OWN_VIEW", "polygon " & id & " vertex " & $i & " is " & $pts[i] &
" not " & $wpts[i]
break
if not matched:
var theirs = false
for (oid, _) in otherPolys:
if oid == id: theirs = true
fail (if theirs: "OTHER_PLAYER" else: "PROTOCOL"),
"vision carries a polygon for a token this player does not control: " & id
for (id, _) in want:
if id notin haveIds: fail "OWN_VIEW", "vision is missing the polygon of " & id
of "explored":
if m["full"].getBool:
# a resync snapshot replaces the set; every cell must be one the recomputation has seen
var cells: seq[(int, int)]
let cols = int(ceil(sceneW / float(cell)))
for row in m["rle"]:
let cy = row[0].getInt
var i = 1
while i + 1 < row.len:
let x0 = row[i].getInt
let len = row[i + 1].getInt
for k in 0 ..< len: cells.add (x0 + k, cy)
i += 2
discard cols
exploredSent = initHashSet[int]()
for (cx, cy) in cells: exploredSent.incl cy * int(ceil(sceneW / float(cell))) + cx
else:
for c in m["cells"]:
let cx = c[0].getInt
let cy = c[1].getInt
let k = cy * int(ceil(sceneW / float(cell))) + cx
exploredSent.incl k
else: discard
# --- CONTROLLER_CHANGE (10.3) ----------------------------------------------------------------
# A token's controller may move only when an intent asked for it (`token.create` names one,
# `token.update` patches `controller`, `player.remove` hands them to the GM). A character edit
# that changed a controller would show up here (DESIGN 8: the controller is set on the token).
var controllerIntent = false
for it in g.intents:
let t = it["t"].getStr
if t == "token.create" or t == "player.remove": controllerIntent = true
elif t == "token.update" and it["f"].hasKey("controller"): controllerIntent = true
for id, actual in truth.tokens:
if prevController.hasKey(id) and prevController[id] != actual.controller and
not controllerIntent:
fail "CONTROLLER_CHANGE", "token " & id & " changed controller in group " & g.label
prevController[id] = actual.controller
# --- the set of tokens the subject should hold at the end of this group ---------------------
for id, actual in truth.tokens:
let want = id in visibleNow
let have = view.hasKey(id)
if want and not have:
fail "WITHHELD", "visible token never sent: " & id & " (group " & g.label & ")"
elif not want and have:
# A token that was never legitimately in view stays a leak under its first class; one that
# 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.
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):
fail "GMONLY_TOKEN", "gm_only token still in view: " & id
else: fail "NO_REMOVE", "token left the view and was never withdrawn: " & id &
" (group " & g.label & ")"
elif want and have:
if not samePos(view[id]["pos"], actual.pos):
fail "OWN_VIEW", "stale position for " & id
# --- the explored set ----------------------------------------------------------------------
var recomputed: HashSet[int]
let cols = int(ceil(sceneW / float(cell)))
let rows = int(ceil(sceneW / float(cell)))
for (_, pts) in polys:
for (cx, cy) in cellsTouched(pts, float(cell)):
# 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
recomputed.incl cy * cols + cx
for k in recomputed: recomputedSoFar.incl k
var suspect = initCountTable[string]()
for k in exploredSent:
# explored only grows (5.1): a cell seen in an earlier group is legitimately explored now
if k in recomputedSoFar: continue
let cx = k mod cols
let cy = k div cols
if definitelySeen(truth.walls, polys, sceneW, cell, cx, cy):
recomputed.incl k # grazed cell the sampler does see: fine either way
continue
# attribution: a cell only the other player has explored is a presence leak, not a bad cell
let cls = if k in otherExplored: "OTHER_PLAYER" else: "EXPLORED"
suspect.inc(cls)
if suspect[cls] <= 3:
fail cls, "explored cell (" & $cx & "," & $cy & ") is outside the subject's sight (group " &
g.label & ")"
for cls, n in suspect:
if n > 3: fail cls, $n & " explored cells the subject never saw (group " & g.label & ")"
# completeness: every cell the recomputation says is seen must have been sent
var missing = 0
for k in recomputed:
if k notin exploredSent:
inc missing
if missing <= 3: fail "EXPLORED", "recomputed explored cell never sent: " & $k
if missing > 3:
fail "EXPLORED", $missing & " recomputed explored cells were never sent"
if getEnv("LEAK_DEBUG") != "":
for (id, pts) in polys:
var cx0 = 100000; var cx1 = -1; var cy0 = 100000; var cy1 = -1
for (cx, cy) in cellsTouched(pts, float(cell)):
cx0 = min(cx0, cx); cx1 = max(cx1, cx); cy0 = min(cy0, cy); cy1 = max(cy1, cy)
echo " poly ", id, " verts ", pts.len, " cells x ", cx0, "..", cx1, " y ", cy0, "..", cy1,
" group ", g.label, " cell ", cell, " sceneW ", sceneW
# --- the clear-segment oracle on the polygon itself -----------------------------------------
for (id, pts) in polys:
if pts.len < 3: continue
var t: TruthToken
for tid, tt in truth.tokens:
if tid == id: t = tt
let o = t.pos
let r = rangeOf(sceneDefault, t)
for i in 0 ..< 64:
for k in [0.3, 0.6, 0.95]:
let p: Vec = (o.x + k * r * cos(2 * PI * i.float / 64),
o.y + k * r * sin(2 * PI * i.float / 64))
if p.x < 0 or p.y < 0 or p.x > sceneW or p.y > sceneW: continue
if clearLine(truth.walls, o, p) and not inside(pts, p):
fail "GEOMETRY", "polygon " & id & " misses a clear-LOS point " & $p
if not haveHello: fail "PROTOCOL", "no hello for the subject"
if me == 0: fail "PROTOCOL", "no player id in hello"
if removes == 0: fail "NO_REMOVE", "the scenario never withdrew a token (harness coverage)"
if seenAny.len < 3: fail "WITHHELD", "the scenario never showed the subject 3 tokens"
for cls, n in classes: echo "FAILCLASS ", cls, " ", n
echo "leakcheck: subject ", subject, " (player ", me, "), ", groupsSeen, " groups, ",
view.len, " tokens in view at the end, ", removes, " withdrawals, ", exploredSent.len,
" explored cells, ", fails, " failures"
quit(if fails > 0: 1 else: 0)
main()