test(m4): finish audit, measurement and archive (#76)

- client/e2e/audit.test.mjs: independent player-browser traffic audit (own
  frame catalogue and banned-key list, never leakcheck.nim), with a
  -d:leakfault/otherVision negative control.
- client/e2e/fogbench.test.mjs + tools/fogbench.nim: 50 tokens on a
  16384 px map (server move path and headless SwiftShader cadence);
  results/m4-fog-bench.md records both honestly (SW is not the phone gate).
- Archive prototype-* under docs/archive/prototypes (Q24); DESIGN 13 M4
  done, TESTING 13 M4 accept result, HANDOFF-M4 close-out.
- mutation.sh c1/c2 patch the post-#65 tile-gate line again (they had
  silently become sed no-ops).
This commit is contained in:
2026-11-21 15:43:08 +01:00
parent fd711de152
commit fcd90529b6
142 changed files with 1111 additions and 242 deletions
+3 -2
View File
@@ -212,6 +212,7 @@ Still missing entirely:
| `devbox run e2e` | builds `client/dist`, then drives headless Chromium against the real server through the TLS/HTTP2 test nginx | | `devbox run e2e` | builds `client/dist`, then drives headless Chromium against the real server through the TLS/HTTP2 test nginx |
| `devbox run mutation` | mutation suite on a temp copy of `server/`, `tests/`, `tools/`: every seeded mutation must fail at least one test | | `devbox run mutation` | mutation suite on a temp copy of `server/`, `tests/`, `tools/`: every seeded mutation must fail at least one test |
| `devbox run bench` | release-build bench of the vision and egress paths, writing `results/bench.log` | | `devbox run bench` | release-build bench of the vision and egress paths, writing `results/bench.log` |
| `devbox run fogbench` | the 50-token / 16384 px server measurement, writing `results/m4-fog-bench.log`; the numbers live in `results/m4-fog-bench.md` |
| `devbox run -- nimble install -d -y` | install/refresh the pinned Nim dependencies | | `devbox run -- nimble install -d -y` | install/refresh the pinned Nim dependencies |
| `devbox run -- bash -c 'cd client && npm ci && npm run dev'` | Vite dev server on :5173 — the UI only, no server API behind it | | `devbox run -- bash -c 'cd client && npm ci && npm run dev'` | Vite dev server on :5173 — the UI only, no server API behind it |
@@ -227,9 +228,9 @@ you touch geometry, vision, move rules or egress.
| `tests/` | Nim in-process suites, one file per area (`tvision.nim`, `tmoverules.nim`, `tdb.nim`, …) plus fixtures | | `tests/` | Nim in-process suites, one file per area (`tvision.nim`, `tmoverules.nim`, `tdb.nim`, …) plus fixtures |
| `tools/` | Node black-box harnesses (WS/HTTP against the real binary), the test nginx, the tile and scene fixture writers, the bench and the mutation script | | `tools/` | Node black-box harnesses (WS/HTTP against the real binary), the test nginx, the tile and scene fixture writers, the bench and the mutation script |
| `docs/` | `DESIGN.md` (the spec), `TESTING.md` (how each rule is proven), `adr/` (decisions and why), `agents/` (agent workflow), `research/`, `DESIGN-history.md` | | `docs/` | `DESIGN.md` (the spec), `TESTING.md` (how each rule is proven), `adr/` (decisions and why), `agents/` (agent workflow), `research/`, `DESIGN-history.md` |
| `results/` | committed gate evidence (`bench.log`, `leak-*.log`, `mutation.log`, `nimble-test.log`, `probing.log`, `faults.log`); the per-run `node-test.log`, `e2e.log` and `client-test.log` are regenerated, not committed | | `results/` | committed gate evidence (`bench.log`, `leak-*.log`, `mutation.log`, `nimble-test.log`, `probing.log`, `faults.log`, `m4-fog-bench.*`); the per-run `node-test.log`, `e2e.log` and `client-test.log` are regenerated, not committed |
| `run/` | gitignored scratch: built binaries, nimcache, local state dirs | | `run/` | gitignored scratch: built binaries, nimcache, local state dirs |
| `prototype-*` | the three prototypes whose measurements the design cites; DESIGN §1 archives them once M4 accepts | | `docs/archive/prototypes/` | the three prototypes whose measurements the design cites, frozen at the M4 finish (#76); the maintained code is `server/` and `client/` |
`GLOSSARY.md` at the root defines the domain words (wall switch, preset, token, character, player `GLOSSARY.md` at the root defines the domain words (wall switch, preset, token, character, player
marker, stuck, squeezed, …). Use those words in code, tests and issues. marker, stuck, squeezed, …). Use those words in code, tests and issues.
+15
View File
@@ -73,6 +73,21 @@ change them only if a slice needs a new *core* event, and say so in the PR.
- No game data (and no Pixi `Application`) exists before a live `hello`; a visitor without a session - No game data (and no Pixi `Application`) exists before a live `hello`; a visitor without a session
only sees the sign-in page. only sees the sign-in page.
## Traffic audit and the M4 measurement (T13, #76)
- **Traffic audit** (`e2e/audit.test.mjs`) is the independent proof that the player browser cannot
become a leak. It records the page's own WebSocket frames and HTTP responses and applies its own
rules: only the 13 player frame types; no wall field and no GM-only token column at any depth; no
other player's id and no token outside the player's sight; vision polygons only for controlled
tokens; explored cells only inside a historical own-vision bbox; tiles only under `/tiles/`, only
200/403, every served tile covering an explored cell, and `/_tiles/` unreachable. The banned-key
list is written in the test, never imported from `tools/leakcheck.nim`, so the proof is independent
of the server's own list. A second test is the negative control: the same rules run against a
`-d:leakfault` build with `LEAK_FAULT=otherVision` and must catch the injected foreign polygon.
- **50-token measurement**: the server half is `tools/fogbench.nim` (`devbox run fogbench`, 16384 px,
50 tokens, ~5k walls); the headless half is `e2e/fogbench.test.mjs`. Numbers and the honest caveat
(SwiftShader is a floor, not a phone) are in `results/m4-fog-bench.md`. The real 60 fps run is #77.
## Name, badge and reconnect (T5, #68) ## Name, badge and reconnect (T5, #68)
- **First sign-in name prompt.** A live player with `me.name === null` gets the `#name` section - **First sign-in name prompt.** A live player with `me.name === null` gets the `#name` section
+406
View File
@@ -0,0 +1,406 @@
// T13 (#76, TESTING 10.3 "Independent traffic audit"): record every WebSocket frame and every HTTP
// response the *player browser* receives, then judge that recording with this file's own rules.
//
// Independence is the point: the banned-key list, the frame catalogue and the geometry checks below
// are written here and never imported from the server's `tools/leakcheck.nim` or `BannedAlways`. A
// server list that quietly loses an entry must not be able to weaken this proof.
//
// The scenario is a player who must see a lot of interesting state (own token, an NPC in sight, a
// window marker, fog, explored cells, tile requests including refused ones) while the GM authors
// every round-1 wall field. A second player and a `gm_only` token sit outside the audited player's
// sight; none of their ids may appear in its traffic.
import test from 'node:test'
import assert from 'node:assert/strict'
import { createPlayer, namePlayer, sleep } from '../../tools/lib.mjs'
import { openAs } from '../../tools/withserver.mjs'
import { writeTileGrid } from '../../tools/tilefixture.mjs'
import { launchBrowser, newPage, signIn, waitForVisible, withStack } from './stack.mjs'
const SCENE = { w: 4096, h: 4096, tile: 32, cell: 32 }
const OWN = [2048, 2048]
const OTHER = [3500, 3500]
/** DESIGN 6.1 server -> client rows a *player* may receive. GM-only rows are absent by design. */
const PLAYER_FRAMES = new Set([
'hello', 'ack', 'error', 'roster', 'vision', 'explored', 'token', 'token_gone',
'character', 'character_gone', 'encountered', 'closing', 'marker',
])
/**
* Fields a player must never receive. Own copy, deliberately broader than any server list: every
* wall geometry field, the GM-only wall and token columns, and the GM-only status cause.
*/
const BANNED_KEYS = new Set([
// wall rows and the GM-only wall frames
'wall', 'walls', 'wall_gone',
'a', 'b', 'thickness', 'position', 'height', 'kind',
'blocks_sight', 'blocks_movement', 'sight_dir', 'player_marker',
'door', 'open', 'secret', 'locked', 'label', 'flags',
// GM-only token columns
'controller', 'gm_only', 'descriptive_name', 'actual_name', 'reveal_all', 'revealed',
'seen_by', 'source',
])
/** Record the page's own WebSocket frames without changing what the app sees. */
async function recordSockets(page) {
await page.addInitScript(() => {
window.__audit = { sockets: 0, frames: [], closes: [] }
const Native = window.WebSocket
class RecordingSocket extends Native {
constructor(url, protocols) {
super(url, protocols)
this.opened = false
window.__audit.sockets += 1
this.addEventListener('open', () => { this.opened = true })
this.addEventListener('message', event => {
try {
window.__audit.frames.push(JSON.parse(event.data))
} catch {
window.__audit.frames.push({ t: '<unparsed>', raw: String(event.data).slice(0, 80) })
}
})
this.addEventListener('close', event => {
window.__audit.closes.push({ code: event.code, reason: event.reason, opened: this.opened })
})
}
}
window.WebSocket = RecordingSocket
})
}
const framesOf = page => page.evaluate(() => window.__audit.frames)
async function waitForFrames(page, predicate, timeout = 20000) {
await page.waitForFunction(predicate, null, { timeout })
}
function walkKeys(value, visit) {
if (Array.isArray(value)) {
for (const item of value) walkKeys(item, visit)
return
}
if (value === null || typeof value !== 'object') return
for (const [key, child] of Object.entries(value)) {
visit(key)
walkKeys(child, visit)
}
}
/** Every explored cell the player was ever told about, from full RLE snapshots and cell diffs. */
function exploredCells(frames) {
const cells = new Set()
for (const frame of frames) {
if (frame.t !== 'explored') continue
if (frame.full) {
for (const row of frame.rle ?? []) {
const cy = row[0]
for (let i = 1; i + 1 < row.length; i += 2) {
const x0 = row[i]
const len = row[i + 1]
for (let x = x0; x < x0 + len; x += 1) cells.add(`${x},${cy}`)
}
}
} else {
for (const [cx, cy] of frame.cells ?? []) cells.add(`${cx},${cy}`)
}
}
return cells
}
/** Bounding boxes (cell coordinates) of every vision polygon the player was ever sent. */
function visionBoxes(frames, cell) {
const boxes = []
for (const frame of frames) {
if (frame.t !== 'vision') continue
for (const poly of frame.polys ?? []) {
const pts = poly.pts ?? []
if (pts.length === 0) continue
const xs = pts.map(([x]) => x)
const ys = pts.map(([, y]) => y)
boxes.push({
id: poly.id,
x0: Math.floor(Math.min(...xs) / cell) - 1,
y0: Math.floor(Math.min(...ys) / cell) - 1,
x1: Math.ceil(Math.max(...xs) / cell) + 1,
y1: Math.ceil(Math.max(...ys) / cell) + 1,
})
}
}
return boxes
}
function insideAnyBox(cx, cy, boxes) {
return boxes.some(b => cx >= b.x0 && cx <= b.x1 && cy >= b.y0 && cy <= b.y1)
}
/** Judge the player's frame stream. Every rule below returns what it found, so the negative
* control can prove each rule can fail, not only that a clean run is empty. */
function frameViolations(frames, { foreignPlayerId = null, foreignTokenIds = [], cell = 32, near = null } = {}) {
const offCatalogue = frames.filter(frame => !PLAYER_FRAMES.has(frame.t))
const banned = []
for (const frame of frames) {
walkKeys(frame, key => {
if (BANNED_KEYS.has(key)) banned.push({ t: frame.t, key })
})
}
const ownIds = new Set(frames.filter(f => f.t === 'token' && f.mine === true).map(f => f.id))
const polyIds = new Set(frames.filter(f => f.t === 'vision').flatMap(f => (f.polys ?? []).map(p => p.id)))
const offSightPolys = [...polyIds].filter(id => !ownIds.has(id))
const withoutRoster = frames.filter(f => f.t !== 'roster')
const idFields = new Set(['id', 'player', 'owner', 'controller', 'seen_by'])
const foreignPlayers = []
if (foreignPlayerId !== null) {
const visitIdFields = value => {
if (Array.isArray(value)) return value.forEach(visitIdFields)
if (value === null || typeof value !== 'object') return
for (const [key, child] of Object.entries(value)) {
if (idFields.has(key)) {
const values = Array.isArray(child) ? child : [child]
if (values.includes(foreignPlayerId)) foreignPlayers.push({ key, value: child })
}
visitIdFields(child)
}
}
withoutRoster.forEach(visitIdFields)
}
const foreignTokens = foreignTokenIds.filter(id => withoutRoster.some(f => JSON.stringify(f).includes(id)))
const boxes = visionBoxes(frames, cell)
const explored = exploredCells(frames)
const exploredOutside = []
for (const key of explored) {
const [cx, cy] = key.split(',').map(Number)
if (!insideAnyBox(cx, cy, boxes)) exploredOutside.push([cx, cy])
}
const exploredNear = []
if (near) {
for (const key of explored) {
const [cx, cy] = key.split(',').map(Number)
if (Math.abs(cx * cell - near[0]) < 300 && Math.abs(cy * cell - near[1]) < 300) exploredNear.push([cx, cy])
}
}
return { offCatalogue, banned, ownIds, polyIds, offSightPolys, foreignPlayers, foreignTokens, boxes, explored, exploredOutside, exploredNear }
}
test('player browser traffic: catalogue-only frames, no wall data, no other player, allowed tiles', { timeout: 240000 }, async () => {
await withStack(async ({ origin, gmKey, stateDir }) => {
const gm = await openAs(origin, gmKey)
const hello = await gm.ws.waitText('hello')
const walls = await gm.ws.waitText('walls')
const scene = hello.scene ?? walls.scene
assert.deepEqual(walls.walls, [], 'the seeded scene starts without walls')
// The audited player and a second player whose room stays out of Ann's sight.
const ann = await createPlayer(gm.ws)
await namePlayer(origin, ann.key, 'Ann')
const bea = await createPlayer(gm.ws)
await namePlayer(origin, bea.key, 'Bea')
// Every round-1 wall field is authored around Ann *before* her token exists, so every explored
// cell derives from a polygon this page is actually sent (no pre-wall memory).
const authored = [
{ a: [1848, 2248], b: [2248, 2248], thickness: 20, position: 'left', height: 2.5, label: 'south wall' },
{ a: [1848, 1848], b: [1848, 2248], preset: 'door', thickness: 10 },
{ a: [2248, 1848], b: [2248, 2248], door: true, secret: true, blocks_sight: true, blocks_movement: true, label: 'hidden door' },
{ a: [1748, 1898], b: [1748, 2198], door: true, locked: true },
{ a: [1898, 1748], b: [2198, 1748], blocks_sight: true, blocks_movement: true, sight_dir: 'left', player_marker: true },
{ a: [1848, 1848], b: [2248, 1848], preset: 'window' },
{ a: [2648, 1848], b: [2648, 2248], flags: { note: 'opaque' } },
]
const ids = []
for (const payload of authored) {
const ack = await gm.ws.request({ t: 'wall.add', scene: scene.id, ...payload })
assert.equal(ack.ok, true, `wall.add ${JSON.stringify(payload)}: ${JSON.stringify(ack)}`)
ids.push(ack.id)
}
// One sighted token plus an NPC inside its sight, a second player and a GM-only token outside.
const own = await gm.ws.request({
t: 'token.create', scene: scene.id, kind: 'pc', pos: OWN,
descriptive_name: 'Ann', actual_name: 'Ann', controller: ann.id,
flags: { vision: true }, vision_radius: 300, radius: 20,
})
assert.equal(own.ok, true, JSON.stringify(own))
const npc = await gm.ws.request({
t: 'token.create', scene: scene.id, kind: 'npc', pos: [2128, 2048],
descriptive_name: 'Rat', actual_name: 'Giant Rat',
})
assert.equal(npc.ok, true, JSON.stringify(npc))
const other = await gm.ws.request({
t: 'token.create', scene: scene.id, kind: 'pc', pos: OTHER,
descriptive_name: 'Bea', actual_name: 'Bea', controller: bea.id,
flags: { vision: true }, vision_radius: 300, radius: 20,
})
assert.equal(other.ok, true, JSON.stringify(other))
const hidden = await gm.ws.request({
t: 'token.create', scene: scene.id, kind: 'npc', pos: [1968, 1978],
descriptive_name: 'Secret', actual_name: 'Secret', gm_only: true,
})
assert.equal(hidden.ok, true, JSON.stringify(hidden))
writeTileGrid(stateDir, {
scene: scene.id, artVersion: scene.art_version, size: scene.tile_size,
x0: 40, x1: 85, y0: 40, y1: 85,
})
const browser = await launchBrowser()
try {
const { page } = await newPage(browser)
const tileTraffic = []
const requests = []
page.on('request', request => requests.push(request.url()))
page.on('response', response => {
tileTraffic.push({ url: response.url(), status: response.status() })
})
await recordSockets(page)
await page.goto(`${origin}/`)
await waitForVisible(page, '#signin')
await signIn(page, ann.key)
await waitForVisible(page, '#stage canvas')
await page.waitForFunction(
() => document.querySelector('#stage canvas')?.dataset.tiles === 'ready',
null,
{ timeout: 30000 },
)
// The whole initial view has arrived (including the marker for the window Ann can see).
await waitForFrames(page, () => {
const seen = new Set(window.__audit.frames.map(frame => frame.t))
return ['hello', 'roster', 'token', 'vision', 'explored', 'marker', 'encountered']
.every(type => seen.has(type))
})
// GM activity while the page records: edits, a door, a removal, a move of Ann's own token
// (new vision + explored cells) and of the NPC (a token update), then an untouched settle.
assert.equal((await gm.ws.request({ t: 'wall.update', scene: scene.id, id: ids[0], height: 3 })).ok, true)
assert.equal((await gm.ws.request({ t: 'door.set', scene: scene.id, id: ids[1], open: true })).ok, true)
assert.equal((await gm.ws.request({ t: 'wall.remove', scene: scene.id, id: ids[6] })).ok, true)
assert.equal((await gm.ws.request({ t: 'token.move', id: own.id, pos: [2048, 2160] })).ok, true)
assert.equal((await gm.ws.request({ t: 'token.move', id: npc.id, pos: [2100, 2080] })).ok, true)
await sleep(500)
const frames = await framesOf(page)
assert.ok(frames.length > 10, `the audit recorded a real stream: ${frames.length} frames`)
const v = frameViolations(frames, {
foreignPlayerId: bea.id,
foreignTokenIds: [other.id, hidden.id],
cell: scene.cell,
near: OTHER,
})
// 1. Catalogue only: every frame type is a row a player may receive.
assert.deepEqual(v.offCatalogue, [], `off-catalogue frames: ${JSON.stringify(v.offCatalogue.slice(0, 3))}`)
// 2. No wall field and no GM-only column anywhere in the player's frames, at any depth.
assert.deepEqual(v.banned, [], `player frames carried forbidden keys: ${JSON.stringify(v.banned.slice(0, 5))}`)
// 3. Vision polygons belong to Ann's own controlled token and nothing else.
assert.ok(v.polyIds.size > 0, 'the player received its vision polygons')
assert.deepEqual(v.offSightPolys, [], 'a vision polygon for a token Ann does not control')
// 4. No other player's or hidden token's id anywhere except the roster's own player list.
// Player ids are small integers, so they are checked in id-shaped fields only (a `reqId`
// or a coordinate may legitimately equal one); token ids are opaque strings.
assert.deepEqual(v.foreignPlayers, [], `another player's id reached the player: ${JSON.stringify(v.foreignPlayers)}`)
assert.deepEqual(v.foreignTokens, [], `a token outside Ann's sight reached her: ${JSON.stringify(v.foreignTokens)}`)
// 5. Explored is this player's own memory: every cell lies in the bbox of a polygon Ann was
// sent, and no cell is anywhere near the other player's room.
assert.ok(v.boxes.length > 0, 'historical vision polygons were recorded')
assert.ok(v.explored.size > 100, `explored has real content: ${v.explored.size} cells`)
assert.deepEqual(v.exploredOutside.slice(0, 5), [], `explored cells outside Ann's own sight: ${v.exploredOutside.length}`)
assert.deepEqual(v.exploredNear, [], 'no explored cell near the other player')
const explored = v.explored
// 6. Tiles: only the product path, only 200/403, and every served tile overlaps a cell Ann
// has explored. `/_tiles/` is never reachable from the page.
const tileResponses = tileTraffic.filter(r => new URL(r.url).pathname.startsWith('/tiles/'))
assert.ok(tileResponses.length > 0, 'the page fetched map tiles')
for (const r of tileResponses) {
assert.ok([200, 403].includes(r.status), `unexpected tile status ${r.status} for ${r.url}`)
}
const served = tileResponses.filter(r => r.status === 200)
const refused = tileResponses.filter(r => r.status === 403)
assert.ok(served.length > 0 && refused.length > 0, 'the scenario has both allowed and refused tiles')
for (const r of served) {
const path = new URL(r.url).pathname
const match = /^\/tiles\/(\d+)\/v(\d+)\/(\d+)_(\d+)\.png$/.exec(path)
assert.ok(match, `tile URL not on the catalogue path: ${r.url}`)
const tx = Number(match[3])
const ty = Number(match[4])
assert.ok(
explored.has(`${tx},${ty}`),
`a served tile the player never explored: ${path} (${served.length} served)`,
)
}
for (const url of requests) {
assert.ok(!url.includes('/_tiles/'), `the page requested the internal tile alias: ${url}`)
if (url.includes('/tiles/')) {
assert.match(new URL(url).pathname, /^\/tiles\/\d+\/v\d+\/\d+_\d+\.png$/, `unexpected tile path ${url}`)
}
}
const direct = await page.evaluate(async () => {
const response = await fetch('/_tiles/1/v1/60_60.png')
return response.status
})
assert.equal(direct, 404, 'a direct /_tiles/ request from the page is refused')
// 7. The live socket never closed during the audit. The boot probe's 1006 (the client asks
// `/ws` with no session and lands on sign-in) is expected and never opened.
const closes = await page.evaluate(() => window.__audit.closes)
assert.deepEqual(
closes.filter(c => c.opened && c.code !== 1005),
[],
`the live player socket closed: ${JSON.stringify(closes)}`,
)
} finally {
await browser.close()
gm.ws.close()
}
})
})
// Negative control: the audit must fail on a build that really leaks. `-d:leakfault` with
// `LEAK_FAULT=otherVision` injects another player's vision polygon into this player's `vision`
// frame (the server's own fault hook, not a fixture). The rule that catches it is rule 3: a polygon
// for a token the player does not control.
test('audit rules catch a leaking build (negative control)', { timeout: 180000 }, async () => {
await withStack(async ({ origin, gmKey }) => {
const gm = await openAs(origin, gmKey)
const hello = await gm.ws.waitText('hello')
await gm.ws.waitText('walls')
const scene = hello.scene
const ann = await createPlayer(gm.ws)
await namePlayer(origin, ann.key, 'Ann')
const bea = await createPlayer(gm.ws)
await namePlayer(origin, bea.key, 'Bea')
for (const [player, pos, name] of [[ann, [1200, 1200], 'Ann'], [bea, [3000, 3000], 'Bea']]) {
const ack = await gm.ws.request({
t: 'token.create', scene: scene.id, kind: 'pc', pos,
descriptive_name: name, actual_name: name, controller: player.id,
flags: { vision: true }, vision_radius: 300, radius: 20,
})
assert.equal(ack.ok, true, JSON.stringify(ack))
}
const browser = await launchBrowser()
try {
const { page } = await newPage(browser)
await recordSockets(page)
await page.goto(`${origin}/`)
await waitForVisible(page, '#signin')
await signIn(page, ann.key)
await waitForVisible(page, '#stage canvas')
await waitForFrames(page, () =>
(window.__audit.frames ?? []).some(f => f.t === 'vision' && (f.polys ?? []).length >= 2))
const frames = await framesOf(page)
const v = frameViolations(frames)
assert.ok(v.offSightPolys.length > 0, 'the off-sight polygon rule fired on the leaking build')
} finally {
await browser.close()
gm.ws.close()
}
}, { server: { defines: ['leakfault'], env: { LEAK_FAULT: 'otherVision' } } })
})
+159
View File
@@ -0,0 +1,159 @@
// T13 (#76): the 50-token, 16384 px map measurement the finish ticket records in
// `results/m4-fog-bench.md`. This is NOT the phone gate: headless Chromium here renders with
// SwiftShader (software), so its frame cadence is a floor for correctness work, never a substitute
// for the Note 10 run (#77). The server half of the same measurement is `tools/fogbench.nim`.
//
// The scene is the real one, patched to 16384 px (only the importer owns w/h, so the harness writes
// the scene row before the server loads it). 50 tokens sit inside the player's sight; the fog
// texture is therefore 512x512 cells, the real M4 maximum.
import test from 'node:test'
import assert from 'node:assert/strict'
import { spawnSync } from 'node:child_process'
import path from 'node:path'
import { createPlayer, namePlayer } from '../../tools/lib.mjs'
import { openAs } from '../../tools/withserver.mjs'
import { writeTileGrid } from '../../tools/tilefixture.mjs'
import { launchBrowser, signIn, waitForVisible, withStack, sleep } from './stack.mjs'
const MOBILE = { viewport: { width: 412, height: 869 }, deviceScaleFactor: 2.625, isMobile: true, hasTouch: true }
const SIZE = 16384
const CENTRE = [SIZE / 2, SIZE / 2]
/** The scene row is the importer's (DESIGN 6.1: w/h are not wire fields); write it before boot. */
function setSceneSize(stateDir, size) {
const db = path.join(stateDir, 'state.db')
const r = spawnSync('sqlite3', [db, `UPDATE scene SET w=${size}, h=${size} WHERE id=1`], { encoding: 'utf8' })
assert.equal(r.status, 0, `set scene size: ${r.stderr}`)
}
async function gmWorld(origin, gmKey) {
const gm = await openAs(origin, gmKey)
const hello = await gm.ws.waitText('hello')
const walls = await gm.ws.waitText('walls')
return { ...gm, hello, scene: hello.scene ?? walls.scene }
}
/** 50 tokens: one controlled sighted token and 49 NPCs packed inside its radius. */
async function fiftyTokens(gm, scene, player) {
const own = await gm.ws.request({
t: 'token.create', scene: scene.id, kind: 'pc', pos: CENTRE,
descriptive_name: 'Ann', actual_name: 'Ann', controller: player.id,
flags: { vision: true }, vision_radius: 400, radius: 20,
})
assert.equal(own.ok, true, JSON.stringify(own))
for (let i = 0; i < 49; i += 1) {
const ack = await gm.ws.request({
t: 'token.create', scene: scene.id, kind: 'npc',
pos: [CENTRE[0] + ((i % 7) - 3) * 28, CENTRE[1] + (Math.floor(i / 7) - 3) * 28],
descriptive_name: `T${i}`, actual_name: `T${i}`,
})
assert.equal(ack.ok, true, JSON.stringify(ack))
}
}
/** rAF cadence over `count` frames, summarised the way the fog-cost test does. */
async function cadence(page, count) {
return page.evaluate(async frames => {
const samples = []
await new Promise(resolve => {
let last = performance.now()
let seen = 0
const step = () => {
const now = performance.now()
samples.push(now - last)
last = now
seen += 1
if (seen < frames) requestAnimationFrame(step)
else resolve()
}
requestAnimationFrame(step)
})
samples.sort((a, b) => a - b)
return {
samples: samples.length,
median: samples[Math.floor(samples.length / 2)],
p95: samples[Math.floor(samples.length * 0.95)],
}
}, count)
}
const fogState = page =>
page.evaluate(() => {
const data = document.querySelector('#stage canvas')?.dataset
if (!data) return null
return {
cells: Number(data.fogCells ?? -1),
polys: Number(data.fogPolys ?? -1),
fullMs: Number(data.fogFullMs ?? -1),
tokens: Number(data.tokens ?? -1),
}
})
test('50-token fog measurement on a 16384 px map (headless SwiftShader, not the phone gate)', { timeout: 180000 }, async () => {
await withStack(async ({ origin, gmKey, stateDir }) => {
const gm = await gmWorld(origin, gmKey)
const scene = gm.scene
assert.equal(scene.w, SIZE, 'the prepared scene is 16384 px')
const player = await createPlayer(gm.ws)
await namePlayer(origin, player.key, 'Ann')
await fiftyTokens(gm, scene, { id: player.id })
// Only the viewport's window needs fixture bytes; 16384 px would be 262144 files.
writeTileGrid(stateDir, {
scene: scene.id, artVersion: scene.art_version, size: scene.tile_size,
x0: 240, x1: 280, y0: 235, y1: 280,
})
const browser = await launchBrowser()
try {
const context = await browser.newContext({ ignoreHTTPSErrors: true, ...MOBILE })
const page = await context.newPage()
const cdp = await context.newCDPSession(page)
const errors = []
page.on('pageerror', error => errors.push(error.message))
page.on('console', message => {
if (message.type() === 'error' && !message.text().includes('WebSocket connection') &&
!message.text().includes('403') && !message.text().includes('net::ERR_')) {
errors.push(message.text())
}
})
await page.goto(`${origin}/`)
await waitForVisible(page, '#signin')
await signIn(page, player.key)
await waitForVisible(page, '#stage canvas')
await page.waitForFunction(
() => document.querySelector('#stage canvas')?.dataset.tiles === 'ready',
null,
{ timeout: 30000 },
)
await page.waitForFunction(
() => Number(document.querySelector('#stage canvas')?.dataset.fogPolys ?? 0) > 0,
null,
{ timeout: 30000 },
)
const initial = await fogState(page)
assert.equal(initial.tokens, 50, `the client draws 50 tokens: ${initial.tokens}`)
assert.ok(initial.cells > 400, `a 16384 px map explored cells: ${initial.cells}`)
assert.ok(initial.fullMs > 0, `the 512x512 fog snapshot was repainted: ${initial.fullMs}`)
const real = await cadence(page, 120)
await cdp.send('Emulation.setCPUThrottlingRate', { rate: 4 })
await sleep(200)
const throttled = await cadence(page, 90)
assert.deepEqual(errors, [])
console.log(
`fogbench (#76): 16384px map (512x512 cells), 50 tokens, 412x869 dpr2.625, ` +
`SwiftShader: fog snapshot=${initial.fullMs.toFixed(3)}ms exploredCells=${initial.cells} ` +
`frames real median=${real.median.toFixed(1)}ms p95=${real.p95.toFixed(1)}ms ` +
`4xCPU median=${throttled.median.toFixed(1)}ms p95=${throttled.p95.toFixed(1)}ms ` +
`(software rasteriser: floor only, not the phone number)`,
)
await context.close()
} finally {
await browser.close()
gm.ws.close()
}
}, { prepare: stateDir => setSceneSize(stateDir, SIZE) })
})
+3 -2
View File
@@ -25,12 +25,13 @@ export function assertClientBuild() {
) )
} }
export async function withStack(fn) { export async function withStack(fn, opts = {}) {
assertClientBuild() assertClientBuild()
const stateDir = makeStateDir() const stateDir = makeStateDir()
const gmKey = gmKeyOf(stateDir) const gmKey = gmKeyOf(stateDir)
if (opts.prepare) await opts.prepare(stateDir, gmKey)
const nginxPort = await freePort() const nginxPort = await freePort()
const server = await startServer({ stateDir, publicOrigin: httpsBaseUrl(nginxPort) }) const server = await startServer({ stateDir, publicOrigin: httpsBaseUrl(nginxPort), ...(opts.server ?? {}) })
let nginx let nginx
try { try {
nginx = await startTestNginx({ nginx = await startTestNginx({
+3
View File
@@ -36,6 +36,9 @@
], ],
"bench": [ "bench": [
"mkdir -p results; nim c -d:release --hints:off -r tools/bench.nim > results/bench.log 2>&1; rc=$?; cat results/bench.log; exit $rc" "mkdir -p results; nim c -d:release --hints:off -r tools/bench.nim > results/bench.log 2>&1; rc=$?; cat results/bench.log; exit $rc"
],
"fogbench": [
"mkdir -p results; nim c -d:release --hints:off -o:run/test/fogbench tools/fogbench.nim > results/m4-fog-bench.log 2>&1 && ./run/test/fogbench >> results/m4-fog-bench.log 2>&1; rc=$?; cat results/m4-fog-bench.log; exit $rc"
] ]
} }
}, },
+3 -3
View File
@@ -84,13 +84,13 @@ All of Q1-Q24 are RESOLVED or DEFERRED; none OPEN.
## B. HANDOFF traceability (old DESIGN §12) ## B. HANDOFF traceability (old DESIGN §12)
Source: `prototype-server-vision/HANDOFF.md` (and README/NOTES worries). Every Source: `docs/archive/prototypes/server-vision/HANDOFF.md` (and README/NOTES worries). Every
row is resolved; the current rules are in the sections each row names. row is resolved; the current rules are in the sections each row names.
<!-- BEGIN old section 12 verbatim --> <!-- BEGIN old section 12 verbatim -->
## 12. HANDOFF items -> decisions / open questions ## 12. HANDOFF items -> decisions / open questions
Source: `prototype-server-vision/HANDOFF.md` (and README/NOTES worries). Source: `docs/archive/prototypes/server-vision/HANDOFF.md` (and README/NOTES worries).
| # | Item | Decision / open | Milestone | | # | Item | Decision / open | Milestone |
|---|---|---|---| |---|---|---|---|
@@ -148,7 +148,7 @@ Source: `prototype-server-vision/HANDOFF.md` (and README/NOTES worries).
[FIXED (owner decision), 2026-11-08]:** `tile_size` = explored cell size = 32 px. Residual leak is [FIXED (owner decision), 2026-11-08]:** `tile_size` = explored cell size = 32 px. Residual leak is
at most one cell, never revoked; no server-side masking. Authoring rule shrinks from ~256 px to at most one cell, never revoked; no server-side masking. Authoring rule shrinks from ~256 px to
~32 px. M4 acceptance: (a) headless mobile-emulation test on the real server path, (b) one manual ~32 px. M4 acceptance: (a) headless mobile-emulation test on the real server path, (b) one manual
phone run; fallback 64 px (per-scene config). Evidence: `prototype-tile-leak/README.md`. Applied phone run; fallback 64 px (per-scene config). Evidence: `docs/archive/prototypes/tile-leak/README.md`. Applied
in 3.3, 3.4 (T5), 8, 12 (H8), 13 (M4, M6). in 3.3, 3.4 (T5), 8, 12 (H8), 13 (M4, M6).
5. Q5 - Map import: CLI-only for v1, or upload + tiling from the browser (GM) from the start? 5. Q5 - Map import: CLI-only for v1, or upload + tiling from the browser (GM) from the start?
**RESOLVED [FIXED (owner decision), 2026-11-08]:** map import is CLI-only in v1; browser upload is **RESOLVED [FIXED (owner decision), 2026-11-08]:** map import is CLI-only in v1; browser upload is
+31 -24
View File
@@ -19,15 +19,16 @@ Legend:
- **[PROPOSED]** design choice made in this doc; the owner may overturn it. - **[PROPOSED]** design choice made in this doc; the owner may overturn it.
Evidence roots (relative to repo root): Evidence roots (relative to repo root):
- `prototype-pixi-perf/` (client perf; README holds all tables) - `docs/archive/prototypes/pixi-perf/` (client perf; README holds all tables)
- `prototype-server-vision/` (server + vision; `README.md`, `HANDOFF.md`, `NOTES.md`, `results/`, - `docs/archive/prototypes/server-vision/` (server + vision; `README.md`, `HANDOFF.md`, `NOTES.md`, `results/`,
`results/spike/investigation.md`) `results/spike/investigation.md`)
- `prototype-tile-leak/` (tile size vs leak; `README.md` holds desktop tables and the 2026-11-08 - `docs/archive/prototypes/tile-leak/` (tile size vs leak; `README.md` holds desktop tables and the 2026-11-08
phone run; `results/phone-20261108T113701.jsonl`) phone run; `results/phone-20261108T113701.jsonl`)
- `docs/prototype.md` is only the original brief for the perf prototype. - `docs/prototype.md` is only the original brief for the perf prototype.
- No FFF engine notes exist in the repo. `GLOSSARY.md` and `docs/adr/` exist per AGENTS.md (Q24, - No FFF engine notes exist in the repo. `GLOSSARY.md` and `docs/adr/` exist per AGENTS.md (Q24,
FIXED). `prototype-*` dirs stay in-tree until the M4 client port, then are archived (Q24, FIXED). FIXED). `prototype-*` trees are archived at `docs/archive/prototypes/` from the M4 finish (#76;
Nothing here is FFF-specific beyond the seam in section 9. Q24, FIXED): frozen history, never built or maintained, with the maintained code in `/server` and
`/client`. Nothing here is FFF-specific beyond the seam in section 9.
--- ---
@@ -107,7 +108,7 @@ entitled to.
the official pixijs-skills (already in `.agents/skills/pixijs*`). the official pixijs-skills (already in `.agents/skills/pixijs*`).
- Server: Nim 2.x; `mummy` pinned to tag `0.4.8` (commit `77a7563e`; `src/` identical to the former - Server: Nim 2.x; `mummy` pinned to tag `0.4.8` (commit `77a7563e`; `src/` identical to the former
pin `01deb1ff694988635c7bf0f24f6088a0bdf6db5d`) [FIXED (owner decision), 2026-11-08; tags pin `01deb1ff694988635c7bf0f24f6088a0bdf6db5d`) [FIXED (owner decision), 2026-11-08; tags
0.4.6-0.4.8 exist]. `prototype-server-vision/servervision.nimble` still pins the commit until 0.4.6-0.4.8 exist]. `docs/archive/prototypes/server-vision/servervision.nimble` still pins the commit until
ported; `db_connector/db_sqlite`, WAL. No Nim in the browser. ported; `db_connector/db_sqlite`, WAL. No Nim in the browser.
- nginx (existing, HTTPS) in front: static client, reverse proxy for `/ws`, `/join`, `/tiles/`; - nginx (existing, HTTPS) in front: static client, reverse proxy for `/ws`, `/join`, `/tiles/`;
internal location for tile bytes. internal location for tile bytes.
@@ -157,7 +158,7 @@ entitled to.
- **Single egress rule [PROPOSED]:** all bytes to a player leave through one egress module that - **Single egress rule [PROPOSED]:** all bytes to a player leave through one egress module that
takes a recipient and a typed per-recipient view. Raw world state (walls, hidden entities, other takes a recipient and a typed per-recipient view. Raw world state (walls, hidden entities, other
players' explored grids) has no code path into that module. The prototype enforces this by players' explored grids) has no code path into that module. The prototype enforces this by
discipline in `sync()` (`prototype-server-vision/src/server.nim`); the real build should enforce discipline in `sync()` (`docs/archive/prototypes/server-vision/src/server.nim`); the real build should enforce
it by types (distinct `PlayerView` and `GmView` structures, no `JsonNode` of world state passed it by types (distinct `PlayerView` and `GmView` structures, no `JsonNode` of world state passed
around). around).
- Client-side fog is cosmetic. Security never depends on the client hiding anything (section 7). - Client-side fog is cosmetic. Security never depends on the client hiding anything (section 7).
@@ -420,7 +421,7 @@ server clamps nothing silently (clamping would leak the hit distance, T8).
### 4.3 Locking and threading ### 4.3 Locking and threading
- mummy: `WebSocket.send` appends the encoded frame to one server-wide deque under `sendQueueLock` - mummy: `WebSocket.send` appends the encoded frame to one server-wide deque under `sendQueueLock`
and wakes the IO thread; worker threads handle events; per-socket events are serialized [MEASURED and wakes the IO thread; worker threads handle events; per-socket events are serialized [MEASURED
reading, `prototype-server-vision/README.md` "mummy suitability", mummy.nim ~L262-311]. reading, `docs/archive/prototypes/server-vision/README.md` "mummy suitability", mummy.nim ~L262-311].
- **One global lock** around intent handling and outbox enqueue; network sends happen outside it - **One global lock** around intent handling and outbox enqueue; network sends happen outside it
(flush, see 4.2). [MEASURED] order, loss and final-view consistency over 3 x 60 s runs, and the (flush, see 4.2). [MEASURED] order, loss and final-view consistency over 3 x 60 s runs, and the
latency figures: TESTING §4.3. latency figures: TESTING §4.3.
@@ -691,7 +692,7 @@ explored_chunk(player_id, scene_id, cx, cy, bits BLOB, PRIMARY KEY(player_id, sc
## 5. Vision and explored ## 5. Vision and explored
### 5.1 Algorithm (ported from `prototype-server-vision/src/geometry.nim`) ### 5.1 Algorithm (ported from `docs/archive/prototypes/server-vision/src/geometry.nim`)
- **Visibility polygon** from token centre: cast rays to every blocking wall endpoint (for a thick - **Visibility polygon** from token centre: cast rays to every blocking wall endpoint (for a thick
wall, every corner of its body quad, 5.10) at angle -eps, 0, +eps (`RayEps` = 1e-4 rad), plus an wall, every corner of its body quad, 5.10) at angle -eps, 0, +eps (`RayEps` = 1e-4 rad), plus an
inscribed 64-gon of radius R as range limit; sort by angle; each ray returns nearest hit among inscribed 64-gon of radius R as range limit; sort by angle; each ray returns nearest hit among
@@ -1900,7 +1901,7 @@ they are not fed until resync, and nginx closes dead peers (M5).
### 7.1 Layers (bottom to top, one Pixi stage under a world container with pan/zoom) ### 7.1 Layers (bottom to top, one Pixi stage under a world container with pan/zoom)
1. **Map tiles**: sprites per tile, loaded lazily for tiles the server allows. 1. **Map tiles**: sprites per tile, loaded lazily for tiles the server allows.
2. **Grid**: one `TilingSprite` over a small cell texture, toggleable [MEASURED technique, 2. **Grid**: one `TilingSprite` over a small cell texture, toggleable [MEASURED technique,
`prototype-pixi-perf/README.md` Techniques]. `docs/archive/prototypes/pixi-perf/README.md` Techniques].
3. **Entities/tokens**: pooled containers, shared `GraphicsContext` per colour, `BitmapText` labels. 3. **Entities/tokens**: pooled containers, shared `GraphicsContext` per colour, `BitmapText` labels.
4. **Fog (players)**: explored dim layer + vision cut-out (7.3). 4. **Fog (players)**: explored dim layer + vision cut-out (7.3).
5. **GM overlay (GM only)**: walls/doors Graphics, wall editor handles; hidden from players by never 5. **GM overlay (GM only)**: walls/doors Graphics, wall editor handles; hidden from players by never
@@ -1911,7 +1912,7 @@ they are not fed until resync, and nginx closes dead peers (M5).
The module layout and the append-only extension rules (one reducer slice file, one render module The module layout and the append-only extension rules (one reducer slice file, one render module
file per feature; no shared registry edit) are written in `client/README.md` [T4, #67]. file per feature; no shared registry edit) are written in `client/README.md` [T4, #67].
### 7.2 Rendering techniques kept from the perf prototype [MEASURED, `prototype-pixi-perf/README.md`] ### 7.2 Rendering techniques kept from the perf prototype [MEASURED, `docs/archive/prototypes/pixi-perf/README.md`]
- Verdict: Pixi v8 renders a VTT scene at 60 fps on Radeon 780M (WebGL and WebGPU) and Galaxy Note - Verdict: Pixi v8 renders a VTT scene at 60 fps on Radeon 780M (WebGL and WebGPU) and Galaxy Note
10 (WebGL) up to 1000 tokens (Note 10 js ~14 ms, 2000 tokens -> 32-36 fps, CPU-bound; laptop js 10 (WebGL) up to 1000 tokens (Note 10 js ~14 ms, 2000 tokens -> 32-36 fps, CPU-bound; laptop js
9-12 ms at 2000). Only per-frame token JS scales; a table needs tens of tokens. 9-12 ms at 2000). Only per-frame token JS scales; a table needs tens of tokens.
@@ -2144,7 +2145,7 @@ copy/export stable).
- **Connection (runtime)**: id, player, `known` map, last vision ver, counter. - **Connection (runtime)**: id, player, `known` map, last vision ver, counter.
Prototype entity (for mapping): `Tok{id,name,kind,pos,gmOnly}` + `tokenRadius` global in scene Prototype entity (for mapping): `Tok{id,name,kind,pos,gmOnly}` + `tokenRadius` global in scene
(`prototype-server-vision/data/scene.json`: 4096 px world, 256 px tiles, radius 400, token radius (`docs/archive/prototypes/server-vision/data/scene.json`: 4096 px world, 256 px tiles, radius 400, token radius
20, cell 32, 60 walls, 8 tokens). 20, cell 32, 60 walls, 8 tokens).
--- ---
@@ -2256,7 +2257,7 @@ See TESTING §10.4 (Node 26 black-box harnesses, built-ins only, `devbox run tes
- Response headers: HSTS, CSP (no inline scripts, `connect-src 'self'` wss), - Response headers: HSTS, CSP (no inline scripts, `connect-src 'self'` wss),
`X-Content-Type-Options`, `Referrer-Policy`. `X-Content-Type-Options`, `Referrer-Policy`.
- No `limit_req` on `/join` (owner, #6: no rate limit on key entry; ~100-bit key space). - No `limit_req` on `/join` (owner, #6: no rate limit on key entry; ~100-bit key space).
- Prototype nginx config (`prototype-server-vision/nginx/nginx.conf`) is the functional reference; - Prototype nginx config (`docs/archive/prototypes/server-vision/nginx/nginx.conf`) is the functional reference;
its `listen` has no address (binds all) and its temp/log paths are dev-only. its `listen` has no address (binds all) and its temp/log paths are dev-only.
- Map import: offline CLI that slices an image into `tile_size` PNG/WebP tiles into - Map import: offline CLI that slices an image into `tile_size` PNG/WebP tiles into
`<state>/tiles/<scene>/v<art_version>/` and registers/updates the scene (prototype: `<state>/tiles/<scene>/v<art_version>/` and registers/updates the scene (prototype:
@@ -2327,18 +2328,24 @@ columns with today's defaults) lands complete now, so the later build needs no m
green on a clean checkout with the nine groups: leak+fault, tiles, probing, protocol, auth, green on a clean checkout with the nine groups: leak+fault, tiles, probing, protocol, auth,
characters and names, restart, persistence, logs. Gate mechanics and the measured result: TESTING characters and names, restart, persistence, logs. Gate mechanics and the measured result: TESTING
§13. Out of M3 accept: concurrency (M5), the 127.0.0.1 bind check (M6). §13. Out of M3 accept: concurrency (M5), the 127.0.0.1 bind check (M6).
- **M4 - Client v1.** Vite + TS + Pixi v8 client: layers, tiles, grid, tokens (BitmapText), - **M4 - Client v1.** Done (2026-11-21, #76). Vite + TS + Pixi v8 client: layers, tiles, grid,
character and encountered lists, reveal controls, fog textures, the wall editor (four presets, tokens (BitmapText), character and encountered lists, reveal controls, fog textures, the wall
switches, marker, label, one-way arrow and flips), token drag with prediction/rollback, DOM editor (four presets, switches, marker, label, one-way arrow and flips), token drag with
overlay, reconnect backoff, reducer tests; then archive `prototype-*` (Q24). Thickness and height prediction/rollback, DOM overlay, reconnect backoff, reducer tests; `prototype-*` archived under
controls are not in M4 (build order above; 5.7, 5.10). `docs/archive/prototypes/` (Q24). Thickness and height controls are not in M4 (build order above;
- Accept: headless e2e (fog pixel checks, player traffic audit clean, reconnect restores); manual 5.7, 5.10).
run on laptop and Note 10 at 60 fps with 50 tokens on a 16384 px tiled map (test target - Accept: headless e2e (fog pixel checks, player traffic audit clean, reconnect restores) - met by
PROPOSED, Q2), fog active. `devbox run e2e` including `client/e2e/audit.test.mjs`; the manual run on laptop and Note 10 at
60 fps with 50 tokens on a 16384 px tiled map (test target PROPOSED, Q2) with fog active is
#77, the one `ready-for-human` step, and remains open by design.
- Tile-size gates [FIXED, Q4]: (a) automated headless-Chromium test (mobile emulation, real server - Tile-size gates [FIXED, Q4]: (a) automated headless-Chromium test (mobile emulation, real server
path): viewport fills in < 1 s at zoom 1; (b) one manual run on the owner's 5-year-old Android path): viewport fills in < 1 s at zoom 1 - met in `client/e2e/map.test.mjs`; (b) one manual run
phone. If either fails: `tile_size` 64 px (per-scene config, no code change). Harness detail and on the owner's 5-year-old Android phone - #77. If either fails: `tile_size` 64 px (per-scene
the prototype-run caveat: TESTING §13. config, no code change). Harness detail and the prototype-run caveat: TESTING §13.
- Finish evidence (#76): `results/m4-fog-bench.md` (50 tokens / 16384 px: server move path
0.119 ms; headless SwiftShader cadence recorded, explicitly not a phone number),
`results/bench.log`, `results/mutation.log`, `results/nimble-test.log`, and the
`devbox run test | client-test | e2e` logs (regenerated, not committed).
- **M5 - Robustness and observability.** SIGTERM handler, bounded metrics and SLOW lines, per-client - **M5 - Robustness and observability.** SIGTERM handler, bounded metrics and SLOW lines, per-client
bounded outbox with coalescing and Ping/Pong lag tracking (4.3), verify `/ws` goes through nginx bounded outbox with coalescing and Ping/Pong lag tracking (4.3), verify `/ws` goes through nginx
and which timeout closes a dead peer, healthz lock check. Accept: concurrency 60 s x3 with p99 <= and which timeout closes a dead peer, healthz lock check. Accept: concurrency 60 s x3 with p99 <=
+43
View File
@@ -0,0 +1,43 @@
# Handoff: end of M4
**Current at 2026-11-21**, M4 finish (#76). M1-M4 are done; M5 is next. This is the close-out note
for the M4 run: what exists, what is proven, what is deliberately still open.
## State
- **Server:** `proto` 2, 29 intents / 16 server messages, one scene, thin walls with the 5.8
switches, doors/secret/locked, windows, one-way, player markers, characters/names, per-player
explored + vision, lock-free tile gate and session cache (#64, #65). `devbox run test` is the
server gate.
- **Client:** `/client` (Vite + TS + PixiJS v8, plain DOM overlay). Sign-in, name prompt, badge,
reconnect + full resync, tiles/grid/pan/zoom, three-state fog + markers, tokens/labels/statuses,
both lists, drag with prediction/rollback, GM wall editor, roster/keys/tokens panel, characters/
reveals/who-sees-it. Gates: `devbox run client-test`, `devbox run e2e`.
- **M4 accept:** `devbox run e2e` proves join, fog pixels, drag/rollback, reconnect and the
independent player-traffic audit; `results/m4-fog-bench.md` records 50 tokens on a 16384 px map
(server move path 0.12-0.14 ms; headless SwiftShader cadence recorded as a floor, not a phone
number). Thickness/height controls are **not** in M4 (ADR-0012); walls round 2 is #37/#45/#50/
#41/#44.
- **Archived:** the three `prototype-*` trees now live under `docs/archive/prototypes/` (frozen,
not built). One maintained client (`/client`), one server (`/server`).
## Still open
- **#77** - the human real-phone playtest: Note 10 + laptop, 16384 px map, 50 tokens, fog active,
LAN TLS/h2. Its comment is the checklist with commands, numbers to record and pass thresholds.
`#63` and `#62` close only after #77.
- **M5** - concurrency, bounded outbox/coalescing, lag tracking, SIGTERM, metrics, nginx dead-peer
timeout, stats outside the lock. `#34` heartbeat is M5.
- **Deferred:** `db_connector` -> thin sqlite3 binding (build item 13); per-token polygon cache and
incremental wall-edit refresh (items 3/4) are **not** needed by the M4 measurement.
## Notes for the next session
- `AGENTS.md` points at the issue tracker and the domain docs. Use the Gitea issues, not the docs,
for work state.
- Gates are sequential and real: `devbox run test`, `devbox run client-test`, `devbox run e2e`,
`devbox run mutation`, `devbox run bench`, and (for fog numbers) `devbox run fogbench`.
- `results/*.log` are evidence and committed; `results/node-test.log`, `results/e2e.log`,
`results/client-test.log` are gitignored scratch and regenerated.
- Browser e2e: `client/e2e/` owns `playwright-core`; `tools/` stays built-ins-only (TESTING §10.4).
The e2e stack is the real server through the TLS/HTTP2 test nginx, never a fixture.
+29 -10
View File
@@ -18,10 +18,10 @@ independent of the code under test where possible, and every check needs a negat
it can fail. it can fail.
Evidence roots (relative to repo root): Evidence roots (relative to repo root):
- `prototype-pixi-perf/` (client perf; README holds all tables) - `docs/archive/prototypes/pixi-perf/` (client perf; README holds all tables)
- `prototype-server-vision/` (server + vision; `README.md`, `HANDOFF.md`, `NOTES.md`, `results/`, - `docs/archive/prototypes/server-vision/` (server + vision; `README.md`, `HANDOFF.md`, `NOTES.md`, `results/`,
`results/spike/investigation.md`) `results/spike/investigation.md`)
- `prototype-tile-leak/` (tile size vs leak; README tables and the 2026-11-08 phone run) - `docs/archive/prototypes/tile-leak/` (tile size vs leak; README tables and the 2026-11-08 phone run)
How to run: `devbox run test` = Nim in-process tests first, then the Node black-box harnesses; How to run: `devbox run test` = Nim in-process tests first, then the Node black-box harnesses;
`devbox run mutation` = the mutation suite. Run everything from the repo root through `devbox run`. `devbox run mutation` = the mutation suite. Run everything from the repo root through `devbox run`.
@@ -46,11 +46,11 @@ built against glibc 2.44 while this host (NixOS) runs 2.42, so a 2.44-built `lib
**Rule:** DESIGN §3.3. **Rule:** DESIGN §3.3.
- Direct hits on `/_tiles/` give 404 [MEASURED: `prototype-server-vision/results/smoke.log`, README - Direct hits on `/_tiles/` give 404 [MEASURED: `docs/archive/prototypes/server-vision/results/smoke.log`, README
"Phase 2a"]. "Phase 2a"].
- A tile is allowed iff at least one explored cell of that player overlaps it [MEASURED semantics: leak - A tile is allowed iff at least one explored cell of that player overlaps it [MEASURED semantics: leak
test (d), 9984 + 7424 requests, 0 failures, `results/leak-A.log`, `results/leak-B.log`]. test (d), 9984 + 7424 requests, 0 failures, `results/leak-A.log`, `results/leak-B.log`].
- The residual 32 px edge leak's sizing evidence: `prototype-tile-leak/README.md` (desktop numbers; - The residual 32 px edge leak's sizing evidence: `docs/archive/prototypes/tile-leak/README.md` (desktop numbers;
phone run 2026-11-08). M4's tile-size gates are in §13 below. phone run 2026-11-08). M4's tile-size gates are in §13 below.
- `Cache-Control: private` is set by the Nim gate and rides through nginx's internal redirect - `Cache-Control: private` is set by the Nim gate and rides through nginx's internal redirect
unchanged; nginx adds nothing of its own there (the test vhost records this, §11.1). unchanged; nginx adds nothing of its own there (the test vhost records this, §11.1).
@@ -552,7 +552,7 @@ from the prototype, what was missing, what the M3 build added, and the tools it
state is queued to it, RSS flat, full resync on recovery equals a fresh connection; nginx closes the state is queued to it, RSS flat, full resync on recovery equals a fresh connection; nginx closes the
dead `/ws` socket within its configured timeout. dead `/ws` socket within its configured timeout.
- **Browser e2e (new, none in prototype)**: headless Chromium via playwright-core (the perf prototype - **Browser e2e (new, none in prototype)**: headless Chromium via playwright-core (the perf prototype
already drives devbox chromium, `prototype-pixi-perf/bench.mjs`; SwiftShader is fine for correctness, already drives devbox chromium, `docs/archive/prototypes/pixi-perf/bench.mjs`; SwiftShader is fine for correctness,
not for perf). Checks: join -> canvas renders; pixel probe shows unexplored area black, visible area not for perf). Checks: join -> canvas renders; pixel probe shows unexplored area black, visible area
map-coloured, dimmed explored area; GM sees walls, player DOM/network contains none; reconnect map-coloured, dimmed explored area; GM sees walls, player DOM/network contains none; reconnect
restores view; drag moves token and rollback works. The harness is `client/e2e/` (the client package restores view; drag moves token and rollback works. The harness is `client/e2e/` (the client package
@@ -571,13 +571,20 @@ from the prototype, what was missing, what the M3 build added, and the tools it
real Vite build (`client/e2e/run.sh` runs `npm run build` first): real Vite build (`client/e2e/run.sh` runs `npm run build` first):
`performance.getEntriesByType('navigation')[0].nextHopProtocol` is `h2` over TLS. The vhost group `performance.getEntriesByType('navigation')[0].nextHopProtocol` is `h2` over TLS. The vhost group
keeps a local stub dist because `devbox run test` must not depend on the client's npm install. keeps a local stub dist because `devbox run test` must not depend on the client's npm install.
- **Independent traffic audit in e2e**: record all WS frames and HTTP responses seen by a player - **Independent traffic audit in e2e**: `client/e2e/audit.test.mjs` records every WS frame and every
browser and run the leak checker's (a)(e) assertions over them. HTTP response the *player browser* receives and judges them with its own catalogue and banned-key
list (never importing `tools/leakcheck.nim`): only the 13 player frame types; no wall geometry or
GM-only column at any depth; vision polygons only for the player's own tokens; no other player's
id or out-of-sight token id; explored cells only inside a historical own-vision bbox and never near
the other player; tiles only on `/tiles/`, only 200/403, every 200 covering an explored cell, and
`/_tiles/` unreachable (direct fetch 404). It runs in `devbox run e2e` beside the fog, drag and
reconnect files. A negative control runs the same rules against a `-d:leakfault` build with
`LEAK_FAULT=otherVision`, so the rule that rejects a foreign vision polygon is proven able to fail.
### 10.4 Test tools [FIXED, owner decision 2026-11-14, #9] ### 10.4 Test tools [FIXED, owner decision 2026-11-14, #9]
- Black-box (outside) WS/HTTP harnesses: Node 26 only, repo-root `tools/`, ported from - Black-box (outside) WS/HTTP harnesses: Node 26 only, repo-root `tools/`, ported from
`prototype-server-vision/tools/` (`smoke.mjs`, `leak.mjs`, `restart.mjs`, `concurrency.mjs`, `docs/archive/prototypes/server-vision/tools/` (`smoke.mjs`, `leak.mjs`, `restart.mjs`, `concurrency.mjs`,
`lib.mjs`, `withserver.sh` incl. the M3 test nginx). No Nim rewrite. Reason: Node is already required `lib.mjs`, `withserver.sh` incl. the M3 test nginx). No Nim rewrite. Reason: Node is already required
for the client (Vite/TS, playwright-core e2e, reducer tests); a harness in another language from the for the client (Vite/TS, playwright-core e2e, reducer tests); a harness in another language from the
server cannot share its protocol bugs; zero deps; already measured. The harness lives in server cannot share its protocol bugs; zero deps; already measured. The harness lives in
@@ -594,7 +601,8 @@ from the prototype, what was missing, what the M3 build added, and the tools it
keeps holding. keeps holding.
- `devbox run test` = Nim tests first, then Node harnesses. `devbox run client-test` = the client's - `devbox run test` = Nim tests first, then Node harnesses. `devbox run client-test` = the client's
Vitest seam (pure reducer, protocol client, envelope); `devbox run e2e` = the built client through Vitest seam (pure reducer, protocol client, envelope); `devbox run e2e` = the built client through
the real server and vhost. The finish gate runs all three. the real server and vhost; `devbox run fogbench` = the 50-token 16384 px server measurement
(`results/m4-fog-bench.log`). The finish gate (#76) runs all of them plus `mutation` and `bench`.
- The nine M3 accept groups and their proving harness tests are mapped in `tools/groups.mjs`; - The nine M3 accept groups and their proving harness tests are mapped in `tools/groups.mjs`;
`tools/groups.test.mjs` fails if a group file or its named evidence test disappears, so the `tools/groups.test.mjs` fails if a group file or its named evidence test disappears, so the
acceptance checklist cannot silently go stale. Harnesses that are not an accept group (`smoke`, acceptance checklist cannot silently go stale. Harnesses that are not an accept group (`smoke`,
@@ -657,6 +665,17 @@ from the prototype, what was missing, what the M3 build added, and the tools it
registered test ran and passed. The restart group takes its baseline from the as-built state on the registered test ran and passed. The restart group takes its baseline from the as-built state on the
first server instance, before any restart, not from a state that has already been through one first server instance, before any restart, not from a state that has already been through one
(#36). (#36).
- **M4 accept result.** Measured 2026-11-21 at the finish commit (#76): `devbox run test` exit 0
(Nim suite all pass, 419 OK checks; 159 Node harness tests with the group evidence step),
`devbox run client-test` 164, `devbox run e2e` 27/27 (join, fog pixel probes, drag + rollback,
reconnect, the independent traffic audit and the 50-token measurement), `devbox run mutation`
control + 80 mutations each failing at least its expected test, `devbox run bench` PASS and
`devbox run fogbench` PASS. Evidence: `results/nimble-test.log`, `results/mutation.log`,
`results/bench.log`, `results/m4-fog-bench.md` (+ `.log`); the e2e/client logs are regenerated
per run and not committed. The manual Note 10 + laptop 60 fps run is **#77** and is the only
open M4 accept item. Mutation housekeeping found here: `c1`/`c2` still patched the pre-#65
tile-gate expression and had silently become `sed` no-ops; both now patch
`cy * sc.cols + cx in explored` and fail the tile gate group again.
- **M4 gate harness.** (a) automated headless-Chromium test with mobile emulation (viewport, dpr, CPU - **M4 gate harness.** (a) automated headless-Chromium test with mobile emulation (viewport, dpr, CPU
and network throttle) against the real server path (nginx HTTP/2 + caching); (b) one manual run on and network throttle) against the real server path (nginx HTTP/2 + caching); (b) one manual run on
the owner's 5-year-old Android phone. The 2026-11-08 prototype phone run is evidence, not the gate the owner's 5-year-old Android phone. The 2026-11-08 prototype phone run is evidence, not the gate
+13
View File
@@ -0,0 +1,13 @@
# Archived prototypes (M4 close-out, #76)
These three trees are the pre-M4 prototypes. They are **frozen history**: not built, not tested and
not maintained. The one maintained client is `/client`; the server is `/server`.
| Tree | What it proved | Where its numbers now live |
|---|---|---|
| [`pixi-perf/`](pixi-perf/) | PixiJS v8 can draw a VTT-sized scene on modest hardware; 2048-16384 px maps, 50-2000 tokens, fog and labels | `docs/DESIGN.md` §7.2, `results/m4-fog-bench.md` |
| [`server-vision/`](server-vision/) | The visibility polygon, scanline cells, explored, the leak transcripts and the move rules that `server/` ports at M1-M3 | `results/bench.log`, `docs/TESTING.md` §10 |
| [`tile-leak/`](tile-leak/) | Tile size vs the fog edge leak; the 2026-11-08 phone run (evidence, not a gate) | `docs/TESTING.md` §13 M4 gate harness |
They were moved here from the repo root in the M4 finish commit; `git log --follow <path>` shows
their last live revision. Do not revive them for a fix: change `/client` or `/server`.

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