feat(walls): player markers — emission, opaque ids, storage, resync (#59)

A wall that is player_marker:true and derives window sends a player one
anchor (the drawn midpoint, integer px) and an opaque per-player 12-char id
once any point of its segment enters that player's vision polygon. Markers
live in PlayerVision like explored, persist to marker_seen in the same
derived-memory transaction, load before the first connection and resync as a
full set after explored; the GM and other players never receive one.

- markers.nim: emission gate, visible-extent test, id mint, anchor, marker_seen I/O.
- views/main: PlayerView markers + full/diff frames, refresh sync, startup load.
- markers.test.mjs: window preset, switch off, solid wall, any-part anchor,
  walk-away/door/lost sight, full-after-explored, per-player privacy, GM none.
- leakcheck: marker allowed type + independent visible-extent oracle with a
  positive control (a marked window the subject sees).
- restart: marked window in the fixture; marker set and marker_seen rows
  identical before/after SIGTERM and SIGKILL.
- protocol/tviews: catalogue and frame order pin the 16th message.

Retraction, re-earning and MARKER_* faults are #60.

Ref #59
This commit is contained in:
2026-11-19 23:27:26 +01:00
parent e989100f50
commit edd4437f7e
11 changed files with 599 additions and 47 deletions
+7
View File
@@ -286,6 +286,13 @@ export async function runLeak({ origin, gmKey, stateDir, transcript, keepOpen =
id: wallIds[wallIds.length - 1] })
if (ack.ok !== true) throw new Error(`wall.remove refused: ${JSON.stringify(ack)}`)
})
// Walls r1 (#59): a marked window in the subject's sight. The window preset carries the marker,
// so the subject gets exactly one opaque-id anchor after the explored diff; the checker's own
// visible-extent oracle independently expects the drawn midpoint (520,800). It sits in the room,
// east of the x=500 walls and clear of every scripted path (x >= 560 or the door line).
await group('GM adds a marked window in the subject sight', async () => {
await addWall({ preset: 'window', a: [520, 700], b: [520, 900] })
})
// Slice 8 (#23): characters, names and the encountered list. Every group here is one the subject
// receives: A is in the room, and C1's token is placed next to A's own.
await group('GM creates a character owned by the other player', async () => {
+123 -1
View File
@@ -27,6 +27,9 @@
## 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)
## ONEWAY the subject's fan ignores `sight_dir` (the two-way fan; TESTING 10.3, #58)
## MARKER a marker frame disagrees with the independent visible-extent oracle, or its shape
## is wrong (the exact MARKER_EARLY/EXTRA/OFF classes are #60's fault builds; #59
## proves the allowed type and the oracle with a positive control)
## 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
@@ -41,7 +44,9 @@ import geometry
const
AllowedTypes = ["hello", "ack", "roster", "token", "token_gone", "vision", "explored",
"character", "character_gone", "encountered"]
"marker", "character", "character_gone", "encountered"]
MarkerIdLength = 12
MarkerIdAlphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789_-"
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
@@ -75,9 +80,19 @@ type
Truth = object
walls: seq[Wall]
markerWalls: seq[MarkerWall]
tokens: Table[string, TruthToken]
characters: Table[string, TruthCharacter]
MarkerWall = object
## A wall that should produce a marker (DESIGN 5.8): `player_marker:true` and the derived shape
## label `window` (`blocks_sight:false`, `blocks_movement:true`; a door either way). The checker
## keeps the geometry and the id from the GM's frames and does its own visible-extent test.
id: int
a, b: Vec
playerMarker: bool
isWindow: bool
Group = object
label: string
gmMsgs: seq[JsonNode]
@@ -134,11 +149,29 @@ proc readGroups(path, subject: string): seq[Group] =
# ---------------------------------------------------------------------------------------------------
# Truth from the GM socket (walls and every token)
proc markerWallOf(id: int, w: JsonNode): MarkerWall =
## The marker-relevant projection of a GM wall frame (5.8): the derived `window` gate and the switch.
MarkerWall(id: id, a: vec(w["a"]), b: vec(w["b"]),
playerMarker: w["player_marker"].getBool,
isWindow: not w["blocks_sight"].getBool and w["blocks_movement"].getBool)
proc isMarkerCandidate(m: MarkerWall): bool = m.playerMarker and m.isWindow
proc setMarkerWall(truth: var Truth, mw: MarkerWall) =
## Upsert by wall id, so a `wall` update replaces the marker projection in place.
for i in 0 ..< truth.markerWalls.len:
if truth.markerWalls[i].id == mw.id:
if mw.isMarkerCandidate: truth.markerWalls[i] = mw
else: truth.markerWalls.delete i
return
if mw.isMarkerCandidate: truth.markerWalls.add mw
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)
truth.markerWalls.setLen(0)
ids.setLen(0)
for w in m["walls"]:
truth.walls.add Wall(a: vec(w["a"]), b: vec(w["b"]),
@@ -147,6 +180,7 @@ proc applyGmWalls(truth: var Truth, ids: var seq[int], m: JsonNode) =
sightBarrier: w["blocks_sight"].getBool,
movementBarrier: w["blocks_movement"].getBool)
ids.add w["id"].getInt
truth.setMarkerWall markerWallOf(w["id"].getInt, w)
of "wall":
let id = m["id"].getInt
let w = Wall(a: vec(m["a"]), b: vec(m["b"]), door: m["door"].getBool,
@@ -161,6 +195,7 @@ proc applyGmWalls(truth: var Truth, ids: var seq[int], m: JsonNode) =
if not found:
truth.walls.add w
ids.add id
truth.setMarkerWall markerWallOf(id, m)
of "wall_gone":
let id = m["id"].getInt
for i in 0 ..< ids.len:
@@ -168,6 +203,10 @@ proc applyGmWalls(truth: var Truth, ids: var seq[int], m: JsonNode) =
truth.walls.delete i
ids.delete i
break
for i in 0 ..< truth.markerWalls.len:
if truth.markerWalls[i].id == id:
truth.markerWalls.delete i
break
else: discard
proc applyGmTokens(truth: var Truth, m: JsonNode) =
@@ -294,6 +333,40 @@ proc insideAny(polys: seq[(string, seq[Vec])], p: Vec): bool =
for (_, pts) in polys:
if inside(pts, p): return true
proc extentSeen(polys: seq[(string, seq[Vec])], a, b: Vec): bool =
## The checker's OWN visible-extent test (DESIGN 5.8, TESTING 10.3; never `vision.nim`): any point
## of the segment inside one of the subject's polygons means an endpoint is inside or the segment
## crosses a polygon edge. The polygons themselves are the GM-truth recomputation above.
for (_, pts) in polys:
if pts.len < 3: continue
if inside(pts, a) or inside(pts, b): return true
for i in 0 ..< pts.len:
if segsCross(a, b, pts[i], pts[(i + 1) mod pts.len]): return true
proc anchorOf(mw: MarkerWall): (int, int) =
## The drawn midpoint, rounded once to integer px (5.8, 6.1).
(int(round((mw.a.x + mw.b.x) / 2)), int(round((mw.a.y + mw.b.y) / 2)))
proc validMarkerId(id: string): bool =
if id.len != MarkerIdLength: return false
for c in id:
if c notin MarkerIdAlphabet: return false
true
proc markerShapeOk(m: JsonNode): bool =
## Only `{id, pos}` per entry, the id opaque and the anchor integer px (6.1). A wall id or any
## other field here is a shape failure, and `keysDeep` catches the banned wall names separately.
for e in m["set"]:
if e.kind != JObject or e.len != 2 or not e.hasKey("id") or not e.hasKey("pos"): return false
if e["id"].kind != JString or not validMarkerId(e["id"].getStr): return false
if e["pos"].kind != JArray or e["pos"].len != 2: return false
for q in e["pos"]:
if q.kind != JInt: return false
if m.hasKey("del"):
for d in m["del"]:
if d.kind != JString or not validMarkerId(d.getStr): return false
true
proc cellOf(sceneW: float, cell: int, ix, iy: int): (float, float) =
(float(ix * cell) + float(cell) / 2, float(iy * cell) + float(cell) / 2)
@@ -373,6 +446,9 @@ proc main() =
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
var markers: Table[string, (int, int)] # marker id -> anchor, what the subject was sent
var expectedMarkers: Table[int, (int, int)] # wall id -> anchor, accumulated memory (#59)
var markerPositive = false # the scenario exercised the oracle at least once
for g in groups:
inc groupsSeen
@@ -380,6 +456,8 @@ proc main() =
applyGmWalls(truth, wallIds, m)
applyGmTokens(truth, m)
applyGmCharacters(truth, m)
if m["t"].getStr == "marker":
fail "PROTOCOL", "the GM received a marker frame (5.8: player memory only)"
# player ids: the subject from its hello, the other from any token it does not control
for m in g.subjMsgs:
@@ -437,6 +515,7 @@ proc main() =
otherExplored.incl cy * int(ceil(sceneW / float(cell))) + cx
# --- the subject's frames of this group -----------------------------------------------------
var sawExploredFull = false
for m in g.subjMsgs:
let t = m["t"].getStr
if not m.hasKey("n") or m["n"].getInt != expectedN:
@@ -643,6 +722,7 @@ proc main() =
if id notin haveIds: fail "OWN_VIEW", "vision is missing the polygon of " & id
of "explored":
if m["full"].getBool:
sawExploredFull = true
# 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)))
@@ -663,8 +743,48 @@ proc main() =
let cy = c[1].getInt
let k = cy * int(ceil(sceneW / float(cell))) + cx
exploredSent.incl k
of "marker":
# DESIGN 5.8/6.1/6.3: the player's own opaque ids and integer-px anchors, nothing else.
# `full:true` is the resync set and must follow `explored` full (the client draws it over the
# fog just rebuilt); a diff adds ids in `set` and (from #60) retracts in `del`.
if not markerShapeOk(m):
fail "MARKER", "malformed marker frame (group " & g.label & ")"
elif m["full"].getBool and not sawExploredFull:
fail "PROTOCOL", "marker full before explored full (group " & g.label & ")"
else:
if m["full"].getBool: markers.clear()
for e in m["set"]:
let id = e["id"].getStr
if markers.hasKey(id):
fail "MARKER", "duplicate marker id " & id & " (group " & g.label & ")"
markers[id] = (e["pos"][0].getInt, e["pos"][1].getInt)
if m.hasKey("del"):
for d in m["del"]:
let id = d.getStr
if not markers.hasKey(id):
fail "MARKER", "del for a marker the subject never had: " & id
markers.del id
else: discard
# --- player markers (5.8, TESTING 10.3 #59) -------------------------------------------------
# The oracle's own memory: a marked window enters `expectedMarkers` once any part of its drawn
# extent is inside the subject's polygons, and stays (walking away, a door, lost sight never
# retract it). It never calls vision.nim: `polysChecks` is this file's recomputed fan.
for mw in truth.markerWalls:
if expectedMarkers.hasKey(mw.id): continue
if extentSeen(polysChecks, mw.a, mw.b): expectedMarkers[mw.id] = anchorOf(mw)
var wantPos: seq[(int, int)]
for _, pos in expectedMarkers: wantPos.add pos
var gotPos: seq[(int, int)]
for _, pos in markers: gotPos.add pos
wantPos.sort()
gotPos.sort()
if gotPos != wantPos:
fail "MARKER", "marker set " & $gotPos & " != visible-extent oracle " & $wantPos &
" (group " & g.label & ")"
elif wantPos.len > 0:
markerPositive = true
# --- 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
@@ -762,6 +882,8 @@ proc main() =
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"
if not markerPositive:
fail "MARKER", "the scenario never produced a marker the visible-extent oracle expects"
for cls, n in classes: echo "FAILCLASS ", cls, " ", n
echo "leakcheck: subject ", subject, " (player ", me, "), ", groupsSeen, " groups, ",
+182
View File
@@ -0,0 +1,182 @@
// Walls r1 (#59): player markers over the real wire. A marker exists only for a wall that is both
// `player_marker:true` and derives `window`; it carries one opaque per-player id and the drawn
// midpoint in integer px, nothing else. It is memory like explored: it survives walking away, a door
// closing and lost sight, the full set comes after explored on connect/resync, and a player never
// sees another player's marker (DESIGN 3.1, 5.8, 6.1, 6.3, 8; ADR-0015).
//
// Retraction, re-earning and the MARKER_* fault classes are #60 and are deliberately not asserted
// here: this group proves the emission gate, the anchor, storage/resync and privacy.
import test from 'node:test'
import assert from 'node:assert/strict'
import { withGmServer, openAs } from './withserver.mjs'
import { createPlayer, namePlayer, sleep } from './lib.mjs'
const ID_RE = /^[A-Za-z0-9_-]{12}$/
async function gmConnect(origin, gmKey) {
const conn = await openAs(origin, gmKey)
await conn.ws.waitText('hello')
const walls = await conn.ws.waitText('walls')
return { ...conn, scene: walls.scene }
}
async function addWall(gm, fields) {
const ack = await gm.ws.request({ t: 'wall.add', scene: gm.scene, ...fields })
assert.equal(ack.ok, true, JSON.stringify(ack))
return ack
}
async function namedPlayer(gm, origin, name) {
const player = await createPlayer(gm.ws)
await namePlayer(origin, player.key, name)
const conn = await openAs(origin, player.key)
await conn.ws.waitText('hello')
return { ...player, conn }
}
async function addSightToken(gm, player, pos) {
const ack = await gm.ws.request({ t: 'token.create', scene: gm.scene, kind: 'pc', pos,
descriptive_name: 'sight', actual_name: 'Sight',
controller: player.id, flags: { vision: true } })
assert.equal(ack.ok, true, JSON.stringify(ack))
return ack.id
}
const markerFrames = ws => ws.messages.filter(m => m && m.t === 'marker')
function assertMarkerShape(frame) {
const keys = frame.full ? ['full', 'n', 'set', 't'] : ['del', 'full', 'n', 'set', 't']
assert.deepEqual(Object.keys(frame).sort(), keys)
assert.equal(Array.isArray(frame.del ?? []), true)
for (const entry of frame.set) {
assert.deepEqual(Object.keys(entry).sort(), ['id', 'pos'], 'a marker carries only id and pos')
assert.match(entry.id, ID_RE, 'the marker id is 12 characters from the token alphabet')
assert.equal(entry.pos.length, 2)
assert.equal(Number.isInteger(entry.pos[0]) && Number.isInteger(entry.pos[1]), true,
'the anchor is integer px (6.1)')
}
}
const markersAfter = (ws, from) =>
ws.messages.filter((m, i) => i >= from && m && m.t === 'marker')
test('marker emission: only a marked window, exact anchor and count, no wall field (#59)', async () => {
await withGmServer(async (s, gmKey) => {
const gm = await gmConnect(s.origin, gmKey)
// The first window is in view of where the subject's token will stand: (200,600) midpoint.
await addWall(gm, { preset: 'window', a: [200, 500], b: [200, 700] })
const player = await namedPlayer(gm, s.origin, 'Marker One')
const tokenId = await addSightToken(gm, player, [300, 300])
const first = await player.conn.ws.waitFor(m => m.t === 'marker' && m.set.length > 0)
assert.equal(first.full, false, 'a mutation sends a diff, not a full set')
assertMarkerShape(first)
assert.equal(first.set.length, 1, 'the window preset emits exactly one marker')
assert.deepEqual(first.set[0].pos, [200, 600], 'the anchor is the drawn midpoint, integer px')
assert.match(first.set[0].id, ID_RE)
// The wall id (an integer) and any wall field are absent from the whole frame.
for (const banned of ['wall', 'walls', 'a', 'b', 'kind', 'player_marker', 'door']) {
assert.equal(JSON.stringify(first).includes(`"${banned}"`), false,
`a marker frame carries no wall field ${banned}`)
}
// A solid wall with the switch on stores the switch and sends nothing (5.8 gate).
let from = player.conn.ws.messages.length
await addWall(gm, { a: [100, 700], b: [400, 700], player_marker: true })
await sleep(120)
assert.equal(markersAfter(player.conn.ws, from).length, 0,
'a solid wall with player_marker:true emits no marker')
// The same see-through shape with the switch off is an invisible barrier.
from = player.conn.ws.messages.length
await addWall(gm, { blocks_sight: false, blocks_movement: true, door: true,
player_marker: false, a: [500, 500], b: [500, 700] })
await sleep(120)
assert.equal(markersAfter(player.conn.ws, from).length, 0,
'a window with its marker off emits nothing')
// Any part of the extent qualifies, and the anchor stays the midpoint even when the midpoint
// is outside the vision radius: (300,650) is 350 px from the token, the midpoint (300,950) 650.
from = player.conn.ws.messages.length
await addWall(gm, { preset: 'window', a: [300, 650], b: [300, 1250] })
const second = await player.conn.ws.waitFor(m => m.t === 'marker' &&
m.set.some(e => e.pos[0] === 300 && e.pos[1] === 950))
assertMarkerShape(second)
assert.equal(second.set.length, 1, 'one newly seen window yields exactly one marker')
assert.notEqual(second.set[0].id, first.set[0].id, 'each wall gets its own marker id')
const all = markerFrames(player.conn.ws).flatMap(m => m.set)
assert.equal(new Set(all.map(e => e.id)).size, 2, 'the player holds exactly two markers')
// The GM never receives a marker frame (5.8: a player's memory stays a player's).
assert.equal(markerFrames(gm.ws).length, 0)
gm.ws.close(); player.conn.ws.close()
})
})
test('marker lifetime and resync: survives walk-away and doors, full after explored, private (#59)',
async () => {
await withGmServer(async (s, gmKey) => {
const gm = await gmConnect(s.origin, gmKey)
const window = await addWall(gm, { preset: 'window', a: [200, 500], b: [200, 700] })
const alice = await namedPlayer(gm, s.origin, 'Marker Alice')
const aliceToken = await addSightToken(gm, alice, [300, 300])
const seen = await alice.conn.ws.waitFor(m => m.t === 'marker' && m.set.length > 0)
const aliceMarker = seen.set[0]
assert.equal(seen.set.length, 1)
// Walk away: the marker is memory, so no retraction and no new frame.
let from = alice.conn.ws.messages.length
assert.equal((await gm.ws.request({ t: 'token.move', id: aliceToken,
pos: [2000, 2000] })).ok, true)
await sleep(120)
assert.equal(markersAfter(alice.conn.ws, from).length, 0,
'walking away never retracts or re-sends a marker')
// A door closing is not a cause either (the window preset is an opening window).
for (const open of [true, false]) {
from = alice.conn.ws.messages.length
assert.equal((await gm.ws.request({ t: 'door.set', scene: gm.scene, id: window.id,
open })).ok, true)
await sleep(80)
assert.equal(markersAfter(alice.conn.ws, from).length, 0,
`door.set open:${open} leaves the marker alone`)
}
// A fresh connection gets the full set after the explored snapshot (6.3).
const again = await openAs(s.origin, alice.key)
await again.ws.waitText('hello')
const explored = await again.ws.waitFor(m => m.t === 'explored' && m.full === true)
const full = await again.ws.waitFor(m => m.t === 'marker' && m.full === true)
assertMarkerShape(full)
assert.ok(again.ws.messages.indexOf(explored) < again.ws.messages.indexOf(full),
'the marker full set comes after explored')
assert.equal(full.set.length, 1)
assert.equal(full.set[0].id, aliceMarker.id, 'the same opaque id survives the reconnect')
assert.deepEqual(full.set[0].pos, aliceMarker.pos)
// A second player sees the same window with their own, different id; neither receives the
// other's (5.8: never another player's marker).
const bob = await namedPlayer(gm, s.origin, 'Marker Bob')
await addSightToken(gm, bob, [350, 350])
const bobSeen = await bob.conn.ws.waitFor(m => m.t === 'marker' && m.set.length > 0)
const bobMarker = bobSeen.set[0]
assert.notEqual(bobMarker.id, aliceMarker.id, 'ids are per player')
assert.deepEqual(bobMarker.pos, aliceMarker.pos)
assert.equal(JSON.stringify(alice.conn.ws.messages).includes(bobMarker.id), false,
"Alice never receives Bob's marker id")
assert.equal(JSON.stringify(bob.conn.ws.messages).includes(aliceMarker.id), false,
"Bob never receives Alice's marker id")
// Turning the switch off makes the barrier invisible: a player who sees it now gets no marker.
assert.equal((await gm.ws.request({ t: 'wall.update', scene: gm.scene, id: window.id,
player_marker: false })).ok, true)
const carol = await namedPlayer(gm, s.origin, 'Marker Carol')
await addSightToken(gm, carol, [300, 300])
await sleep(150)
const carolMarkers = markerFrames(carol.conn.ws).flatMap(m => m.set)
assert.equal(carolMarkers.length, 0, 'a window with the switch off is an invisible barrier')
assert.equal(markerFrames(gm.ws).length, 0, 'the GM receives no marker')
gm.ws.close(); alice.conn.ws.close(); again.ws.close(); bob.conn.ws.close(); carol.conn.ws.close()
})
})
+5 -4
View File
@@ -49,11 +49,12 @@ test('hello is the first frame; n counts server frames per connection, never glo
})
})
// The 15 server message types of DESIGN 6.1. A client must ignore unknown server types (6.2), but
// the server itself never invents one: this pins the direction that is testable without a client.
// The 16 server message types of DESIGN 6.1 (15 M3 + `marker`, 6.2 proto 2). A client must ignore
// unknown server types (6.2), but the server itself never invents one: this pins the direction that
// is testable without a client.
const SERVER_TYPES = new Set(['hello', 'ack', 'error', 'roster', 'walls', 'wall', 'wall_gone',
'vision', 'explored', 'token', 'token_gone', 'character', 'character_gone', 'encountered',
'closing'])
'vision', 'explored', 'marker', 'token', 'token_gone', 'character', 'character_gone',
'encountered', 'closing'])
test('every server frame carries a catalogue type (nothing outside the wire catalogue)', async () => {
await withGmServer(async (s, gmKey) => {
+43 -2
View File
@@ -57,6 +57,11 @@ async function buildWorld(origin, gmKey) {
assert.equal(door.ok, true, JSON.stringify(door))
assert.equal((await gm.ws.request({ t: 'door.set', scene: gm.sceneId, id: door.id,
open: true })).ok, true)
// Walls r1 (#59): a marked window every sighted player starts in view of, so the restart
// compares a non-empty per-player marker set and the `marker_seen` rows behind it.
const window = await gm.ws.request({ t: 'wall.add', scene: gm.sceneId, preset: 'window',
a: [450, 300], b: [550, 300] })
assert.equal(window.ok, true, JSON.stringify(window))
// The player's own token: vision, explored cells and the encountered list come from it.
const pc = await gm.ws.request({ t: 'token.create', scene: gm.sceneId, kind: 'pc',
@@ -115,7 +120,7 @@ async function buildWorld(origin, gmKey) {
assert.equal((await gm.ws.request({ t: 'name.reveal_all', subject: 'token',
id: pc.id })).ok, true)
saved.ids = { ...saved.ids, pc: pc.id, monster: monster.id, character: character.id,
linked: linked.id, wall: wall.id, door: door.id }
linked: linked.id, wall: wall.id, door: door.id, window: window.id }
gm.ws.close()
} finally {
try { gm.ws.close() } catch {}
@@ -136,7 +141,7 @@ async function waitResync(client, expected) {
count(client, 'character') >= expected.characters &&
(expected.gm ? count(client, 'walls') >= 1
: count(client, 'encountered') >= 1 && count(client, 'vision') >= 1 &&
count(client, 'explored') >= 1)
count(client, 'explored') >= 1 && count(client, 'marker') >= 1)
if (ok) return
if (Date.now() > deadline) {
throw new Error(`resync incomplete: ${JSON.stringify(client.messages.map(m => m.t))}`)
@@ -162,6 +167,8 @@ async function snapshot(origin, key, expected, isGm) {
snap.walls = walls
snap.walls.walls.sort(by('id'))
snap.characters = pick('character').sort(by('id'))
assert.equal(c.ws.messages.some(m => m.t === 'marker'), false,
'the GM never receives a marker frame (5.8)')
snap.encountered = pick('encountered').map(e => {
e.set.sort(by('id'))
return e
@@ -174,6 +181,9 @@ async function snapshot(origin, key, expected, isGm) {
snap.vision.polys.sort(by('id'))
// explored RLE rows are already ordered by cy; keep the payload as the view, not a set.
snap.explored = pick('explored').pop()
// #59: the full marker set, after explored, with this player's own opaque ids.
snap.marker = pick('marker').pop()
snap.marker.set.sort(by('id'))
}
return snap
} finally {
@@ -219,6 +229,15 @@ async function compareAcross(origin, gmKey, players, ids, expected) {
}
assert.ok(snap.vision.polys.length >= 1, `${who} has sight`)
assert.ok(snap.explored.rle.length >= 1, `${who} explored something`)
// #59: the marked window is in every sighted player's full set, at its drawn midpoint, under
// an opaque 12-character id of that player's own (never the wall id).
assert.equal(snap.marker.full, true, `${who}'s marker set is a full resync set`)
assert.ok(snap.marker.set.length >= 1, `${who} saw the marked window`)
for (const entry of snap.marker.set) {
assert.deepEqual(entry.pos, [500, 300], `${who}'s marker anchor is the drawn midpoint`)
assert.match(entry.id, /^[A-Za-z0-9_-]{12}$/, `${who}'s marker id is opaque`)
assert.notEqual(entry.id, String(ids.window), `${who}'s marker id is never the wall id`)
}
}
return before
}
@@ -267,6 +286,16 @@ function dbEncounteredNames(stateDir, entityId) {
.map(line => { const [id, name] = line.split('='); return [id, name] }))
}
// #59: the persisted marker memory, player id -> marker id, for one wall.
function dbMarkerRows(stateDir, wallId) {
const r = spawnSync('sqlite3', [path.join(stateDir, 'state.db'),
`SELECT player_id || '=' || marker_id FROM marker_seen WHERE wall_id = ${wallId} ` +
`ORDER BY player_id`], { encoding: 'utf8' })
assert.equal(r.status, 0, r.stderr)
return Object.fromEntries(r.stdout.trim().split('\n').filter(Boolean)
.map(line => { const [id, markerId] = line.split('='); return [id, markerId] }))
}
const EXPECTED = { tokens: 5, characters: 1 }
async function restartGroup(hard) {
@@ -275,11 +304,21 @@ async function restartGroup(hard) {
const players = {}
let s = await startServer({ stateDir })
let saved
let markerRows
try {
saved = await buildWorld(s.origin, gmKey)
players.alice = saved.alice
players.bob = saved.bob
players.carol = saved.carol
// #59: one persisted marker row per player/wall that has seen the window, all distinct per
// player, each an opaque id that is never the wall id. The rows are the restart fixture.
markerRows = dbMarkerRows(stateDir, saved.ids.window)
assert.ok(Object.keys(markerRows).length >= 2,
`the marked window wrote marker_seen rows for the sighted players: ${JSON.stringify(markerRows)}`)
for (const markerId of Object.values(markerRows)) {
assert.match(markerId, /^[A-Za-z0-9_-]{12}$/, 'the persisted marker id is opaque')
assert.notEqual(markerId, String(saved.ids.window), 'the marker id is never the wall id')
}
// #27, asserted against the rows while the server is still up: the monster's actual name was
// revealed to Bob only, so exactly one of the three rows carries it.
const monsterRows = dbEncounteredNames(stateDir, saved.ids.monster)
@@ -297,6 +336,8 @@ async function restartGroup(hard) {
}
try {
await restartAndCompare(stateDir, gmKey, players, saved.ids, EXPECTED, hard)
assert.deepEqual(dbMarkerRows(stateDir, saved.ids.window), markerRows,
'the marker_seen rows (player and opaque id) survive the restart unchanged')
} finally {
fs.rmSync(stateDir, { recursive: true, force: true })
}