// Leak test driver (DESIGN 10.1, 10.3; M3 slice 5 / #20; scenario rewrite Walls r1 #61). Builds a // known scene over the real wire, then plays a scripted narrative with ONE mutation per group and // writes every frame each socket received to a JSONL transcript. tools/leakcheck.nim replays it: the // GM socket is ground truth, the subject's own messages are only ever checked, never trusted. // // Groups: a marker line, one action, then "quiescent" (no frame for QUIET ms on any socket). That // is what lets the checker evaluate a group as one state: every mutation is its own group, so the // truth after the group is the truth the group's frames describe. // // THE WORLD (4096 px, 32 px cells, 400 px vision, token radius 20) is one coherent scene, not a list // of appendages. Every element is there to be sight-tested, and each carries exactly one obligation: // // - the room x 500..1400, entered through an opening door in the west wall; the subject // starts west of it, so "behind a closed door" and "through it" are both shown // - far wall x = 1400: solid, a secret door, solid, a locked door. N3 and N4 stand behind // them and are as invisible as a token behind solid wall (5.8, T17): the // checker recomputes from `blocks_sight` alone, never from `secret`/`locked` // - one-way screen the southern hall is split at x = 700 with `sight_dir:"right"` (east blind); // the subject, west of it, sees across to the sentry E2 (#58) // - markers a marked opening window in the room (seen: the positive control), the same // window's switch cleared and restored (the retraction/re-earn path, #60), a // marked solid wall in the room (switch on, no marker: MARKER_EXTRA control), // a marked window far outside every scripted position (never seen: MARKER_EARLY // control) and a marked window behind the far wall (occluded: "a wall behind a // sight blocker yields none", TESTING 5.8) // - the rest a token hidden behind the closed door and revealed by opening it, tokens // created/removed while watched, a `gm_only` token inside LOS, a controller // handed over and back, another player walking in and out, a wall added and // removed in sight, a door closing on a token (the 5.5 push), and the slice 7/8 // property, status, name and character groups // // Every pre-existing fault class keeps its witness here, so the rewrite traded no old obligation // for a new one; tools/fault.test.mjs asserts each class exactly. import fs from 'node:fs' import path from 'node:path' import { spawnSync } from 'node:child_process' import { createPlayer, namePlayer, openWs, sleep, projectRoot, isWindow, anchorOf } from './lib.mjs' import { signIn } from './withserver.mjs' const QUIET_MS = 60 // The far wall's x (the WORLD's `far-*` segments): east of it is behind a sight blocker at every // scripted subject position. Scenario coverage reads this to prove the occluded marker control. const FAR_WALL_X = 1400 const nimblePkgs = () => path.join(process.env.NIMBLE_DIR ?? path.join(projectRoot, '.devbox', 'nimble'), 'pkgs2') // The checker is compiled once per process (it imports server/geometry.nim through --path in nim.cfg). let checkerBin = null export function buildChecker() { if (checkerBin) return checkerBin const out = path.join(projectRoot, 'run', 'test', 'leakcheck') fs.mkdirSync(path.dirname(out), { recursive: true }) const r = spawnSync('nim', ['c', '--hints:off', '-d:release', `--nimblePath:${nimblePkgs()}`, `-o:${out}`, path.join('tools', 'leakcheck.nim')], { cwd: projectRoot, encoding: 'utf8' }) if (r.status !== 0) throw new Error(`nim c tools/leakcheck.nim failed:\n${r.stdout}\n${r.stderr}`) checkerBin = out return out } export function runChecker(transcript, subject) { const r = spawnSync(buildChecker(), [transcript, subject], { encoding: 'utf8' }) return { status: r.status, output: `${r.stdout ?? ''}${r.stderr ?? ''}` } } // One socket, its received frames, and where the transcript cursor is. Every intent a client sends // is logged too (`k:'intent'`): the checker needs it to tell an intended controller change from one // a character edit caused (the CONTROLLER_CHANGE class, DESIGN 10.3). async function connect(origin, key, who, log, group) { const { cookie } = await signIn(origin, key) const ws = await openWs(origin, cookie) return { who, ws, logged: 0, log, request(fields) { log({ k: 'intent', g: group(), who, t: fields.t, f: fields }) return ws.request(fields) }, } } // The world: one fixture per obligation. `role` is the handle later groups and the coverage // assertion use, so no group has to count positions in a list (the old `wallIds[1]` fragility). const WORLD = [ // West wall x = 500, y 0..1000 with an opening door (y 400..700). The subject starts west of it. { role: 'west-north', a: [500, 0], b: [500, 400] }, { role: 'west-door', a: [500, 400], b: [500, 700], door: true, open: false }, { role: 'west-south', a: [500, 700], b: [500, 1000] }, // Far wall x = 1400: solid, secret door, solid, locked door. `secret`/`locked` are ordinary // closed door switches; to a player the three blockers are indistinguishable (5.8, T17). { role: 'far-north', a: [1400, 400], b: [1400, 620] }, { role: 'far-secret', a: [1400, 620], b: [1400, 720], door: true, secret: true }, { role: 'far-middle', a: [1400, 720], b: [1400, 820] }, { role: 'far-locked', a: [1400, 820], b: [1400, 920], door: true, locked: true }, // One-way screen: the wall's right (east) side is blind, so a subject west of it sees across. { role: 'one-way-screen', a: [700, 1200], b: [700, 1400], sight_dir: 'right' }, // Marked window in the room, the positive marker control: anchor (520, 800) (#59). { role: 'marked-window', preset: 'window', a: [520, 700], b: [520, 900] }, // Marked solid wall in the room: the switch is on but the shape is a wall, so no marker may be // minted (the MARKER_EXTRA negative control, #60). { role: 'marked-solid', a: [620, 760], b: [720, 760], player_marker: true }, // Marked window far outside every scripted position: never seen, so never a marker (the // MARKER_EARLY negative control, #60). { role: 'marked-unseen', preset: 'window', a: [3500, 2000], b: [3500, 2200] }, // A marked window behind the far wall (east of FAR_WALL_X): truly occluded, so it must yield no // marker at all — TESTING 5.8 "a wall behind a sight blocker yields none". Unlike `marked-unseen` // this is not merely out of range; a sight-blocking wall stands between it and every subject // position, so even walking the whole room never earns it. { role: 'marked-occluded', preset: 'window', a: [1500, 700], b: [1500, 800] }, ] // The scenario's own coverage, read off the GM's wall frames and the subject's marker frames. The // acceptance contract of #61 is a world holding each of these elements, so the test proves the // scenario really has them instead of trusting the list above: a rewrite that silently drops the // locked door, the one-way wall or one side of the marker sight test fails loudly. export function scenarioCoverage(gmMsgs, subjMsgs) { const walls = new Map() for (const m of gmMsgs) { if (!m || typeof m.t !== 'string') continue if (m.t === 'walls') { walls.clear() for (const w of m.walls) walls.set(w.id, w) } else if (m.t === 'wall') walls.set(m.id, m) else if (m.t === 'wall_gone') walls.delete(m.id) } const all = [...walls.values()] const received = new Set() for (const m of subjMsgs) { if (!m || m.t !== 'marker') continue for (const e of m.set ?? []) received.add(e.pos.join(',')) } const marked = all.filter(w => w.player_marker) const windows = marked.filter(isWindow) const occluded = windows.filter(w => anchorOf(w)[0] > FAR_WALL_X) return { walls: all.length, oneWay: all.filter(w => w.sight_dir !== 'both').length, secretDoors: all.filter(w => w.secret).length, lockedDoors: all.filter(w => w.locked).length, markedWindows: windows.length, markedNonWindows: marked.filter(w => !isWindow(w)).length, // "both sides of the sight test": a marked window the subject earned and one it did not. markedWindowsSeen: windows.filter(w => received.has(anchorOf(w).join(','))).length, markedWindowsUnseen: windows.filter(w => !received.has(anchorOf(w).join(','))).length, // A marked window behind the far wall: occluded, never earned, however far the subject walks. markedWindowsOccluded: occluded.length, markedWindowsOccludedSeen: occluded.filter(w => received.has(anchorOf(w).join(','))).length, markers: received.size, } } export async function runLeak({ origin, gmKey, stateDir, transcript, keepOpen = false }) { // The transcript is written in group order; the checker needs nothing else. const lines = [] const log = obj => lines.push(JSON.stringify(obj)) const clients = [] const gm = await connect(origin, gmKey, 'GM', log, () => g) clients.push(gm) await gm.ws.waitText('hello') const walls = await gm.ws.waitText('walls') const scene = walls.scene let g = 0 let quiesceMs = QUIET_MS const flush = () => { // Only now, at a group boundary, do the frames a client received get attributed to the group. for (const c of clients) { for (; c.logged < c.ws.messages.length; c.logged++) { log({ k: 'msg', who: c.who, g, m: c.ws.messages[c.logged] }) } } } async function quiesce() { const deadline = Date.now() + 5000 let last = -1 let since = Date.now() for (;;) { const n = clients.reduce((a, c) => a + c.ws.messages.length, 0) if (n !== last) { last = n; since = Date.now() } if (Date.now() - since >= quiesceMs) return if (Date.now() > deadline) throw new Error('server never went quiet') await sleep(10) } } async function group(label, fn) { g++ log({ k: 'group', g, label }) await fn() await quiesce() flush() } const wallIds = {} // role -> id, so a later group never indexes into creation order const ids = {} const characters = {} const addWall = async spec => { const { role, ...fields } = spec const ack = await gm.request({ t: 'wall.add', scene, ...fields }) if (ack.ok !== true) throw new Error(`wall.add refused (${role ?? 'transient'}): ${JSON.stringify(ack)}`) if (role !== undefined) wallIds[role] = ack.id return ack.id } const createToken = async (id, fields) => { const ack = await gm.request({ t: 'token.create', scene, ...fields }) if (ack.ok !== true) throw new Error(`token.create refused: ${JSON.stringify(ack)}`) ids[id] = ack.id return ack.id } const move = async (client, id, pos) => client.request({ t: 'token.move', id, pos }) // Two named players: the naming is the fixture of lib.mjs (player.setname is slice 8). const playerA = await createPlayer(gm.ws) const playerB = await createPlayer(gm.ws) await namePlayer(origin, playerA.key, 'Subject A') await namePlayer(origin, playerB.key, 'Player B') // --- the world and its cast ---------------------------------------------------------------- await group('the world', async () => { for (const w of WORLD) await addWall(w) }) await group('the cast', async () => { await createToken('A', { kind: 'pc', pos: [300, 300], descriptive_name: 'A', actual_name: 'A', controller: playerA.id, flags: { vision: true } }) await createToken('B', { kind: 'pc', pos: [300, 3000], descriptive_name: 'B', actual_name: 'B', controller: playerB.id, flags: { vision: true } }) await createToken('M1', { kind: 'npc', pos: [400, 200], descriptive_name: 'a wolf', actual_name: 'Fang' }) await createToken('M2', { kind: 'npc', pos: [560, 550], descriptive_name: 'a guard', actual_name: 'Captain Vex' }) await createToken('M3', { kind: 'npc', pos: [350, 350], descriptive_name: 'a shadow', actual_name: 'The Hidden', gm_only: true }) await createToken('M4', { kind: 'item', pos: [3500, 3500], descriptive_name: 'a chest', actual_name: 'The Vault' }) // Behind the far wall's secret and locked doors: never visible, and never named. await createToken('N3', { kind: 'npc', pos: [1500, 670], descriptive_name: 'a scribe', actual_name: 'Brother Ivo' }) await createToken('N4', { kind: 'npc', pos: [1500, 870], descriptive_name: 'a jailer', actual_name: 'Warden Hale' }) }) const A = await connect(origin, playerA.key, 'A', log, () => g) clients.push(A) await A.ws.waitText('hello') await group('the subject connects', async () => { await sleep(0) }) const B = await connect(origin, playerB.key, 'B', log, () => g) clients.push(B) await B.ws.waitText('hello') await group('the other player connects', async () => { await sleep(0) }) // --- through the door ---------------------------------------------------------------------- // A walks from (300,300) to just west of the door; M2 waits behind it. await group('A walks up to the closed door', async () => { expectAck(await move(A, ids.A, [350, 600]), true) }) await group('A stands at the door', async () => { expectAck(await move(A, ids.A, [350, 620]), true) }) await group('M2 is hidden behind the closed door', async () => { await sleep(0) }) await group('GM opens the door', async () => { const ack = await gm.request({ t: 'door.set', scene, id: wallIds['west-door'], open: true }) if (ack.ok !== true) throw new Error(`door.set refused: ${JSON.stringify(ack)}`) }) // In the room the subject also first sees the marked window: its marker is earned here. await group('A steps through the door', async () => { expectAck(await move(A, ids.A, [560, 600]), true) }) await group('A steps into the room', async () => { expectAck(await move(A, ids.A, [600, 640]), true) }) // --- sight, hiding and seeing --------------------------------------------------------------- await group('GM moves M1 into the room', async () => { expectAck(await move(gm, ids.M1, [700, 700]), true) }) await group('GM creates a token in view', async () => { await createToken('N1', { kind: 'item', pos: [520, 700], descriptive_name: 'a lamp', actual_name: 'Lantern' }) }) await group('GM removes it', async () => { const ack = await gm.request({ t: 'token.remove', id: ids.N1 }) if (ack.ok !== true) throw new Error(`token.remove refused: ${JSON.stringify(ack)}`) }) await group('GM hides M1', async () => { const ack = await gm.request({ t: 'token.update', id: ids.M1, gm_only: true }) if (ack.ok !== true) throw new Error(`token.update refused: ${JSON.stringify(ack)}`) }) await group('GM unhides M1', async () => { const ack = await gm.request({ t: 'token.update', id: ids.M1, gm_only: false }) if (ack.ok !== true) throw new Error(`token.update refused: ${JSON.stringify(ack)}`) }) await group('GM hands M1 to the subject', async () => { const ack = await gm.request({ t: 'token.update', id: ids.M1, controller: playerA.id }) if (ack.ok !== true) throw new Error(`token.update refused: ${JSON.stringify(ack)}`) }) await group('GM moves the subject-owned token far away', async () => { expectAck(await move(gm, ids.M1, [3000, 3000]), true) }) await group('GM hands M1 back to the GM', async () => { const ack = await gm.request({ t: 'token.update', id: ids.M1, controller: null }) if (ack.ok !== true) throw new Error(`token.update refused: ${JSON.stringify(ack)}`) }) await group('GM walks the other player in', async () => { expectAck(await move(gm, ids.B, [420, 640]), true) }) await group('GM walks the other player out', async () => { expectAck(await move(gm, ids.B, [420, 1500]), true) }) await group('GM adds a plain wall in the subject sight', async () => { await addWall({ role: 'transient-wall', a: [400, 910], b: [900, 910] }) }) await group('GM removes it again', async () => { const ack = await gm.request({ t: 'wall.remove', scene, id: wallIds['transient-wall'] }) if (ack.ok !== true) throw new Error(`wall.remove refused: ${JSON.stringify(ack)}`) }) await group('GM puts M2 on the door line', async () => { expectAck(await move(gm, ids.M2, [500, 600]), true) }) await group('GM closes the door: the server pushes M2 aside', async () => { const ack = await gm.request({ t: 'door.set', scene, id: wallIds['west-door'], open: false }) if (ack.ok !== true) throw new Error(`door.set refused: ${JSON.stringify(ack)}`) }) // --- properties, statuses and shapes (slice 7, #22) ------------------------------------------ // N2 sits near A, so every frame of these groups is one the subject receives. await group('GM creates N2 in view', async () => { await createToken('N2', { kind: 'item', pos: [660, 600], descriptive_name: 'a rune', actual_name: 'The Rune' }) }) for (const [bucket, value] of [['public', 'cold'], ['owner', 3], ['gm', 'the duke']]) { await group(`GM writes the ${bucket} prop of N2`, async () => { const ack = await gm.request({ t: 'prop.set', target: 'token', id: ids.N2, bucket, key: 'aura', value }) if (ack.ok !== true) throw new Error(`prop.set refused: ${JSON.stringify(ack)}`) }) } await group('GM sets a GM-sourced status on N2', async () => { const ack = await gm.request({ t: 'status.set', id: ids.N2, status: 'squeezed' }) if (ack.ok !== true) throw new Error(`status.set refused: ${JSON.stringify(ack)}`) }) await group('GM resizes N2', async () => { const resized = await gm.request({ t: 'token.resize', id: ids.N2, radius: 45 }) if (resized.ok !== true) throw new Error(`token.resize refused: ${JSON.stringify(resized)}`) }) await group('GM adds a wall over N2 (stuck, source walls)', async () => { await addWall({ role: 'over-n2', a: [700, 560], b: [700, 660] }) }) await group('GM unsets the public prop of N2', async () => { const unset = await gm.request({ t: 'prop.unset', target: 'token', id: ids.N2, bucket: 'public', key: 'aura' }) if (unset.ok !== true) throw new Error(`prop.unset refused: ${JSON.stringify(unset)}`) }) await group('GM clears the GM-sourced status of N2', async () => { const cleared = await gm.request({ t: 'status.clear', id: ids.N2, status: 'squeezed', source: 'GM' }) if (cleared.ok !== true) throw new Error(`status.clear refused: ${JSON.stringify(cleared)}`) }) await group('GM removes the wall over N2', async () => { const ack = await gm.request({ t: 'wall.remove', scene, id: wallIds['over-n2'] }) if (ack.ok !== true) throw new Error(`wall.remove refused: ${JSON.stringify(ack)}`) }) // --- characters, names and the encountered list (slice 8, #23) ------------------------------ await group('GM creates a character owned by the other player', async () => { const ack = await gm.request({ t: 'character.create', descriptive_name: 'a cloaked figure', actual_name: 'Lady Vex', owner: playerB.id }) if (ack.ok !== true) throw new Error(`character.create refused: ${JSON.stringify(ack)}`) characters.C1 = ack.id }) await group('GM puts a token of the character in the subject sight', async () => { const ack = await gm.request({ t: 'token.create', scene, kind: 'pc', pos: [600, 560], character_id: characters.C1 }) if (ack.ok !== true) throw new Error(`token.create refused: ${JSON.stringify(ack)}`) ids.C1 = ack.id }) // #27/#30: a second player meets the same token of the same character, so the transcript carries // two encountered lists whose names can be compared independently (leakcheck runs once per // subject). The later rename and reveals must reach this player's snapshot too, and a reveal to // the *other* player must not. await group('GM walks the other player into the room again', async () => { expectAck(await move(gm, ids.B, [650, 700]), true) }) // One mutation per group (the driver's contract): the checker evaluates a group as one state, so // two prop writes in one group would compare an intermediate frame against the final truth. for (const [bucket, value] of [['public', 'noble'], ['owner', 4], ['gm', 'the duke']]) { await group(`GM writes the ${bucket} prop of the character`, async () => { const ack = await gm.request({ t: 'prop.set', target: 'character', id: characters.C1, bucket, key: 'rank', value }) if (ack.ok !== true) throw new Error(`prop.set refused: ${JSON.stringify(ack)}`) }) } await group('GM renames the character', async () => { const ack = await gm.request({ t: 'character.update', id: characters.C1, descriptive_name: 'a tall stranger' }) if (ack.ok !== true) throw new Error(`character.update refused: ${JSON.stringify(ack)}`) }) await group('GM reveals the actual name to the subject only', async () => { const ack = await gm.request({ t: 'name.reveal', subject: 'character', id: characters.C1, player: playerA.id }) if (ack.ok !== true) throw new Error(`name.reveal refused: ${JSON.stringify(ack)}`) }) await group('GM reveals the actual name to everyone', async () => { const ack = await gm.request({ t: 'name.reveal_all', subject: 'character', id: characters.C1 }) if (ack.ok !== true) throw new Error(`name.reveal_all refused: ${JSON.stringify(ack)}`) }) await group('GM hands the character to the subject (controllers must not move)', async () => { const ack = await gm.request({ t: 'character.reassign', id: characters.C1, owner: playerA.id }) if (ack.ok !== true) throw new Error(`character.reassign refused: ${JSON.stringify(ack)}`) }) await group('GM gives the character back to the other player', async () => { const ack = await gm.request({ t: 'character.reassign', id: characters.C1, owner: playerB.id }) if (ack.ok !== true) throw new Error(`character.reassign refused: ${JSON.stringify(ack)}`) }) await group('GM reveals a plain token actual name to the subject', async () => { const ack = await gm.request({ t: 'name.reveal', subject: 'token', id: ids.N2, player: playerA.id }) if (ack.ok !== true) throw new Error(`name.reveal refused: ${JSON.stringify(ack)}`) }) await group('GM reveals that plain token to everyone', async () => { const ack = await gm.request({ t: 'name.reveal_all', subject: 'token', id: ids.N2 }) if (ack.ok !== true) throw new Error(`name.reveal_all refused: ${JSON.stringify(ack)}`) }) await group('GM walks the other player out again', async () => { expectAck(await move(gm, ids.B, [420, 1500]), true) }) await group('GM hides the character token (the encountered entry stays, greyed)', async () => { const ack = await gm.request({ t: 'token.update', id: ids.C1, gm_only: true }) if (ack.ok !== true) throw new Error(`token.update refused: ${JSON.stringify(ack)}`) }) await group('GM shows it again', async () => { const ack = await gm.request({ t: 'token.update', id: ids.C1, gm_only: false }) if (ack.ok !== true) throw new Error(`token.update refused: ${JSON.stringify(ack)}`) }) await group('GM removes the character token (the entry stays, greyed)', async () => { const ack = await gm.request({ t: 'token.remove', id: ids.C1 }) if (ack.ok !== true) throw new Error(`token.remove refused: ${JSON.stringify(ack)}`) }) await group('GM removes one encountered entry of the subject', async () => { const ack = await gm.request({ t: 'encountered.remove', player: playerA.id, id: ids.N2 }) if (ack.ok !== true) throw new Error(`encountered.remove refused: ${JSON.stringify(ack)}`) }) // --- marker memory: retract and re-earn (#60) ----------------------------------------------- // A still sees the marked window from the room. Clearing the switch retracts its marker (a `del` // only, never a new anchor); restoring it re-earns one with a fresh id, because the old id died. // The checker's oracle mirrors the rule from the GM's wall frames, so both directions are checked // against its own memory, not against what the server sent. await group('GM clears the marked window player marker', async () => { const ack = await gm.request({ t: 'wall.update', scene, id: wallIds['marked-window'], player_marker: false }) if (ack.ok !== true) throw new Error(`wall.update refused: ${JSON.stringify(ack)}`) }) await group('GM turns the marker back on', async () => { const ack = await gm.request({ t: 'wall.update', scene, id: wallIds['marked-window'], player_marker: true }) if (ack.ok !== true) throw new Error(`wall.update refused: ${JSON.stringify(ack)}`) }) // --- the far wall: a secret and a locked door (5.8, T17) ------------------------------------ // A walks up to the far wall. N3 and N4 are 200 px away behind the two doors, well inside sight: // with any of the three blockers missing they would be in the polygon, so their absence here is // the leak-checker's proof that a secret or locked door is a solid wall to this player. The walk // is in step-cap legs (a player's move is capped at its vision radius, 5.5). await group('A walks east across the room', async () => { expectAck(await move(A, ids.A, [950, 645]), true) }) await group('A walks up to the far wall', async () => { expectAck(await move(A, ids.A, [1300, 650]), true) }) await group('the secret and locked doors are solid wall to the subject', async () => { await sleep(0) }) // --- the southern hall and the one-way screen (#58) ----------------------------------------- await group('A walks away from the far wall', async () => { expectAck(await move(A, ids.A, [930, 800]), true) }) await group('A walks back towards the door', async () => { expectAck(await move(A, ids.A, [560, 950]), true) }) await group('A walks further south', async () => { expectAck(await move(A, ids.A, [560, 1300]), true) }) // `sight_dir:"right"` names the east side blind, so the subject west of the screen sees across; // the ONEWAY fault drops `sight_dir` and the same wall would hide E2 and shrink the fan. await group('GM puts a sentry behind the one-way screen (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) }) // Let anything still queued arrive, then close politely. await sleep(100) flush() if (!keepOpen) for (const c of clients) c.ws.close() fs.mkdirSync(path.dirname(transcript), { recursive: true }) fs.writeFileSync(transcript, lines.join('\n') + '\n') const coverage = scenarioCoverage(gm.ws.messages, A.ws.messages) return { transcript, groups: g, walls: wallIds, tokens: ids, characters, coverage } } function expectAck(ack, ok) { const got = ack.ok === true if (got !== ok) throw new Error(`unexpected ack: ${JSON.stringify(ack)}`) return ack }