diff --git a/docs/TESTING.md b/docs/TESTING.md index c16929b..dae3cb6 100644 --- a/docs/TESTING.md +++ b/docs/TESTING.md @@ -441,20 +441,22 @@ from the prototype, what was missing, what the M3 build added, and the tools it oracle-refused (a withheld proof cell still fails). Fault class `ONEWAY` (built) — the player-facing computation drops `sight_dir`, so the one-way wall becomes two-way — with its injected fault (`LEAK_FAULT=oneWay`) and exact-class assertion, shaped like the existing classes. -- **Player marker (#48; shape fixed by #49; planned: Walls r1 #59/#60).** Once planned Walls r1 #59 - lands, `leakcheck.nim` allows the `marker` type and, with its own code (never calling `vision.nim`), - checks that a marker exists for a player exactly when some - point of the wall's visible extent has entered that player's polygon **and** the wall is - `player_marker:true` and derives `window`, and that the frame carries only the opaque marker id and - the anchor: anything else is `WALLDATA`/`MARKER_EXTRA`. Positive control: a window in the open yields - exactly one marker once its anchor is seen; a wall behind a sight blocker, `player_marker:false`, or a - solid wall with the switch on yields none. Faults: `MARKER_EARLY`, `MARKER_EXTRA`, `MARKER_OFF`. - Retraction is checked GM-side: removing the wall, clearing the switch or moving the geometry retracts - the marker, never sends the new position early, and writes no explored cell or tile. +- **Player marker (#48; shape fixed by #49; emission/storage/oracle built #59; retraction and the + exact fault classes #60).** `leakcheck.nim` allows the `marker` type and, with its own code (never + calling `vision.nim`), checks that a marker exists for a player exactly when some point of the + wall's visible extent has entered that player's polygon **and** the wall is `player_marker:true` + and derives `window`, and that the frame carries only the opaque marker id and the anchor: anything + else is `WALLDATA`/`MARKER`. Positive control: a marked window the subject sees yields exactly one + marker at its drawn midpoint; a wall behind a sight blocker, `player_marker:false`, or a solid wall + with the switch on yields none. The oracle's expected set accumulates like explored memory, so + walking away, a door or lost sight never makes a sent marker wrong. Faults `MARKER_EARLY`, + `MARKER_EXTRA`, `MARKER_OFF` and retraction (removing the wall, clearing the switch, moving the + geometry retracts the marker, never sending the new position early and writing no explored cell or + tile) remain #60. - **Wall fields, storage and migration (#49).** Three gates. **Leak:** `BannedAlways` contains every wall field name (`thickness`, `position`, `height`, `blocks_sight`, `blocks_movement`, `sight_dir`, `player_marker`, `door`, `open`, `secret`, `locked`, `label`, `a`, `b`), so any of them in a player - frame is `WALLDATA`; `marker` is an allowed server type with its own oracle (planned: Walls r1 #59); + frame is `WALLDATA`; `marker` is an allowed server type with its own oracle (built #59); positive control: a wall `height` injected into a player `token` frame fails with exactly `WALLDATA`. **Migration:** a schema-7 fixture (both wall kinds, an open door, non-empty `flags`, tokens and a character with props) diff --git a/server/main.nim b/server/main.nim index cc84871..3e6c052 100644 --- a/server/main.nim +++ b/server/main.nim @@ -39,7 +39,7 @@ import std/typedthreads import db_connector/db_sqlite import mummy, mummy/routers import config, db, eventlog, crypto, auth, conns, instancelock, protocol, world, jsonbound -import characters, geometry, props, text, tiles, tokens, vision, views, explored, worldmap, faults, moverules +import characters, geometry, markers, props, text, tiles, tokens, vision, views, explored, worldmap, faults, moverules const CookieName* = "fff_session" @@ -191,9 +191,11 @@ proc refreshPlayer(pid: int) = ## Recompute one player's polygons and explored cells (4.2 step 5). Caller holds the lock. The ## sight state is created on first use, so a player who never connected still gets one the moment ## they do (nothing is stale from startup, 4.1). The table entry is passed by reference: reading it - ## into a `var` would copy it and the update would be lost. + ## into a `var` would copy it and the update would be lost. The same refresh mints the player's + ## markers (5.8): the polygon is the gate, so it must run after `refresh`. if pid == GmControlled: return app.visions.mgetOrPut(pid, PlayerVision()).refresh(app.scene, app.tokens, pid) + discard markers.syncMarkers(app.visions.mgetOrPut(pid, PlayerVision()), app.scene) proc refreshAll() = ## A wall or door changed: every player's sight changes (4.2 step 5). @@ -229,11 +231,11 @@ proc recordEncounters() = app.encountered.mgetOrPut(pid, initTable[string, characters.EncounteredEntry]())[e.entityId] = e # --------------------------------------------------------------------------------------------------- -# Explored persistence (DESIGN 4.2 step 6, 4.4; M3 slice 6 / #21). The grid lives in memory; this is -# the only place it reaches the DB. One rule: a mutation writes exactly the chunks its refresh -# dirtied, never the whole grid, and the write rides in the mutation's transaction so an ack cannot -# precede the cells it reports. NORMAL durability (Q12): explored is derived and monotone, not -# GM-authored content. +# Derived player memory persistence: explored cells and player markers (DESIGN 4.2 step 6, 4.4, 5.8; +# M3 slice 6 / #21, #59). Both live in memory and reach the DB only here. One rule: a mutation writes +# exactly the explored chunks its refresh dirtied and the markers it minted, never the whole state, +# and the write rides in the mutation's transaction so an ack cannot precede what it reports. NORMAL +# durability (Q12): both are derived and monotone (a marker only grows in r1), not GM-authored. proc dirtyExplored(pids: openArray[int]): seq[explored.Chunk] = ## The chunks the last refresh dirtied, for the named players. Caller holds the lock and has @@ -247,16 +249,27 @@ proc dirtyExplored(pids: openArray[int]): seq[explored.Chunk] = app.visions.mgetOrPut(pid, PlayerVision()).explored, fresh): result.add c -proc persistExplored(pids: openArray[int]) = - ## Writes the dirtied chunks. No transaction of its own: the caller wraps it together with the - ## mutation's own row writes (db.withTransaction). +proc persistMarkers(pids: openArray[int]) = + ## The marker half alone, for a connect where the explored grid must stay exactly as it was (a + ## schema-4/7 database rebuilds its grid on connect and stores nothing until a mutation): a marker + ## minted at the resync is still durable before it is sent (5.8, 4.2 step 6). + for pid in pids: + if pid == GmControlled: continue + discard markers.writeNew(app.db, app.scene.id, pid, + app.visions.mgetOrPut(pid, PlayerVision()).markerFresh) + +proc persistDerived(pids: openArray[int]) = + ## Writes the dirtied explored chunks and the markers the same refresh minted (5.8: a marker insert + ## is in the same derived-memory transaction as the explored chunks, after the wall row commits). + ## No transaction of its own: the caller wraps it together with the mutation's row writes. let chunks = dirtyExplored(pids) if chunks.len > 0: discard explored.writeChunks(app.db, app.scene.id, chunks) + persistMarkers(pids) -proc persistAllExplored() = - ## After `refreshAll` (a wall or door changed): every player whose grid grew, in one transaction. +proc persistAllDerived() = + ## After `refreshAll` (a wall or door changed): every player whose grid grew or markers changed. app.db.withTransaction: - persistExplored(app.visions.keys.toSeq) + persistDerived(app.visions.keys.toSeq) proc egressAll() = ## One pass over every live connection: build that recipient's view, diff it against what the @@ -331,7 +344,13 @@ proc resync(connId: int, named: bool, player: Player) = # This is the moment a connection starts receiving state, so the player's own sight is computed # here: a connection opened while unnamed never had a refresh, and `player.setname` resyncs on the # same socket (6.1). Idempotent: a refresh that changes nothing only costs the polygon pass. - if not isGm and named: refreshPlayer(player.id) + if not isGm and named: + refreshPlayer(player.id) + # A marker minted here (a window the player had not seen before connecting) must be durable like + # any other derived memory before the resync sends it (5.8, 4.2 step 6). Only markers: the + # explored grid keeps its own existing connect behaviour (nothing is stored here). + app.db.withTransaction: + persistMarkers(@[player.id]) # A token visible right now is a sighting: record it before the `encountered` list is built (the # player may have been offline while something walked into their sight). recordEncounters() @@ -1183,7 +1202,7 @@ proc dispatch(conn: Conn, env: Envelope) {.gcsafe.} = app.tokens.add created.token refreshPlayer(created.token.owner) app.db.withTransaction: - persistExplored(@[created.token.owner]) + persistDerived(@[created.token.owner]) # The record copy (`created`, and the world's own) must die under this lock, and so must # the ack's `id`: settle inside the critical section, then carry only fresh scalars out. createdId = detachedString(created.token.id) @@ -1319,7 +1338,7 @@ proc dispatch(conn: Conn, env: Envelope) {.gcsafe.} = refreshPlayer(oldOwner) refreshPlayer(candidate.owner) app.db.withTransaction: - persistExplored(@[oldOwner, candidate.owner]) + persistDerived(@[oldOwner, candidate.owner]) # A plain-token rename or a link change keeps every encountered snapshot of this token # in step with its subject - the descriptive name, the character link and the actual # name this player may know - in the DB and in memory at once (8; #29, #30). A linked @@ -1386,7 +1405,7 @@ proc dispatch(conn: Conn, env: Envelope) {.gcsafe.} = app.db.withTransaction: discard writePosition(app.db, app.tokens[idx.get]) writeStatuses(app.db, app.tokens[idx.get]) - persistExplored(@[app.tokens[idx.get].owner]) + persistDerived(@[app.tokens[idx.get].owner]) case kind of mkError: ackErr(conn, env.reqId, if conn.role == prGm: CodeNotFound else: CodeNotAllowed) @@ -1416,7 +1435,7 @@ proc dispatch(conn: Conn, env: Envelope) {.gcsafe.} = app.tokens.delete idx.get refreshPlayer(owner) app.db.withTransaction: - persistExplored(@[owner]) + persistDerived(@[owner]) if not removed: ackErr(conn, env.reqId, CodeNotFound) return @@ -1462,7 +1481,7 @@ proc dispatch(conn: Conn, env: Envelope) {.gcsafe.} = app.tokens[idx.get] = rec refreshPlayer(rec.owner) app.db.withTransaction: - persistExplored(@[rec.owner]) + persistDerived(@[rec.owner]) if outcome == toNotFound: ackErr(conn, env.reqId, CodeNotFound) return @@ -2018,7 +2037,7 @@ proc dispatch(conn: Conn, env: Envelope) {.gcsafe.} = app.scene = candidate for (i, rec) in tokenChanges: app.tokens[i] = rec refreshAll() - persistAllExplored() + persistAllDerived() recordEncounters() ackOk(conn, env.reqId) resyncEveryone() @@ -2074,7 +2093,7 @@ proc dispatch(conn: Conn, env: Envelope) {.gcsafe.} = discard moverules.addWall(mr, ruleWall(added.get)) discard applyRuleOutcome(mr) refreshAll() # 4.2 step 5: a wall change moves every player's sight - persistAllExplored() # step 6: the chunks the new wall revealed, before the ack + persistAllDerived() # step 6: the chunks the new wall revealed, before the ack addedId = added.get.id addedKind = derivedKind(added.get) # The wall frame references `added.flags`; build it and fan it out here, before the record @@ -2130,7 +2149,7 @@ proc dispatch(conn: Conn, env: Envelope) {.gcsafe.} = discard moverules.updateWall(mr, idx, ruleWall(updated.get)) discard applyRuleOutcome(mr) refreshAll() - persistAllExplored() + persistAllDerived() updatedKind = derivedKind(updated.get) # Frame and record copy both live and die inside this lock (ANALYSIS 4.1). settleWorldLocked(conn, env.reqId, wallFrame(sceneId, wallObjectOf(updated.get))) @@ -2164,7 +2183,7 @@ proc dispatch(conn: Conn, env: Envelope) {.gcsafe.} = discard moverules.removeWall(mr, idx.get) discard applyRuleOutcome(mr) refreshAll() - persistAllExplored() + persistAllDerived() if outcome == waNotFound: ackErr(conn, env.reqId, CodeNotFound) return @@ -2201,7 +2220,7 @@ proc dispatch(conn: Conn, env: Envelope) {.gcsafe.} = if idx.isSome: discard moverules.setDoor(mr, idx.get, open) discard applyRuleOutcome(mr) refreshAll() - persistAllExplored() + persistAllDerived() # Frame and record copy both live and die inside this lock (ANALYSIS 4.1). settleWorldLocked(conn, env.reqId, wallFrame(sceneId, wallObjectOf(updated.get))) ok = true @@ -2426,6 +2445,9 @@ proc runServer(cfg: Config): int = # 4.4 startup / slice 6: the players' explored grids come back from their chunk rows. Polygons are # never stored; the sight state is rebuilt from the loaded walls on the player's first refresh. state.visions = explored.restore(conn, state.scene) + # 5.8 (#59): the per-player marker memory comes back with the explored state, before the first + # connection, so a reconnecting player gets the full set they had. + markers.restore(conn, state.scene, state.visions) let gm = gmPlayer(conn) if gm.isSome: state.gmPlayerId = gm.get.id lg.log(lvInfo, "scene_loaded", [("scene", $state.scene.id), ("walls", $state.scene.walls.len), @@ -2433,7 +2455,8 @@ proc runServer(cfg: Config): int = ("characters", $state.characters.len), ("next_wall_id", $state.scene.nextWallId)]) lg.log(lvInfo, "explored_loaded", [("players", $state.visions.len), - ("chunks", $explored.chunkCount(conn, state.scene.id))]) + ("chunks", $explored.chunkCount(conn, state.scene.id)), + ("markers", $markers.markerCount(conn, state.scene.id))]) lg.log(lvInfo, "names_loaded", [("reveals", $state.reveals.pairs.len), ("encountered_players", $state.encountered.len)]) appHandle = cast[pointer](state) diff --git a/server/markers.nim b/server/markers.nim new file mode 100644 index 0000000..fec0a6a --- /dev/null +++ b/server/markers.nim @@ -0,0 +1,105 @@ +## Player marker emission and persistence (DESIGN 5.8, 6.1, 6.3, 8; ADR-0015, #59). +## +## A marker exists for a player exactly when a wall is both `player_marker:true` and derives +## `window`, and any point of the wall's visible extent has been inside one of that player's vision +## polygons. In this round the visible extent is the drawn segment (thickness is inert, 5.10), so the +## test is: an endpoint inside the polygon, or the segment crossing one of its edges. The gate is the +## player's own polygon, the same one that decides token visibility (5.1), so nothing behind a +## sight-blocking wall qualifies and the check never needs a second vision implementation. +## +## The marker is per-player memory like explored: it is minted once, gets that player's own opaque +## 12-character id (never the wall id), keeps the wall's drawn midpoint rounded once as its anchor, +## and is persisted in `marker_seen` as part of the same derived-memory transaction as the explored +## chunks (4.2 step 6). `vision.PlayerVision.markers` holds it in memory and `restore` loads it at +## startup, before the first connection (4.4). This round only adds: retraction (wall removed, switch +## off, no longer a window, geometry moved), re-earning a fresh id and the marker fault classes are +## #60; `sync` is the seam where that lifetime rule lands. +## +## No DB transaction control here: the caller owns it, exactly like explored.nim. +import std/[math, options, strutils, tables] +import db_connector/db_sqlite +import geometry, tokens, vision, world + +proc anchorOf*(w: WallRec): (int, int) = + ## The wall's drawn midpoint, rounded once to integer px and fixed for the wall (5.8, 6.1). + (int(round((w.a.x + w.b.x) / 2.0)), int(round((w.a.y + w.b.y) / 2.0))) + +proc extentSeen*(pv: PlayerVision, a, b: Vec): bool = + ## True when any point of the wall's visible extent (the segment in this round) is inside one of + ## the player's polygons: an endpoint inside, or the segment crossing a polygon edge. Boundary + ## contacts are inclusive, which is the generous side of "any point" and cannot admit anything + ## behind a sight blocker (the polygon itself stops there). + for poly in pv.polys: + if poly.pts.len < 3: continue + if inside(poly.pts, a) or inside(poly.pts, b): return true + for i in 0 ..< poly.pts.len: + if segsCross(a, b, poly.pts[i], poly.pts[(i + 1) mod poly.pts.len]): return true + +proc qualifies*(pv: PlayerVision, w: WallRec): bool = + ## The complete emission gate of 5.8: the switch on, the derived shape label a window, and part of + ## the visible extent seen. A solid wall with `player_marker:true` fails the kind gate. + w.playerMarker and derivedKind(w) == "window" and pv.extentSeen(w.a, w.b) + +proc markerIdTaken(pv: PlayerVision, id: string): bool = + for marker in pv.markers.values: + if marker.id == id: return true + +proc freshMarkerId(pv: PlayerVision): string = + result = newTokenId() + var tries = 0 + while markerIdTaken(pv, result) and tries < 64: + result = newTokenId() + inc tries + +proc syncMarkers*(pv: var PlayerVision, sc: SceneRec): int = + ## Adds one marker per wall that now qualifies and is not in this player's memory yet; returns how + ## many were minted. Add-only by design in this round (#59): a marker that stops qualifying stays, + ## so walking away, a door closing and lost sight never retract it. The retraction/re-earn rule is + ## #60 and belongs here, next to this loop. + for w in sc.walls: + if w.id in pv.markers: continue + if not pv.qualifies(w): continue + let (x, y) = anchorOf(w) + let marker = Marker(id: freshMarkerId(pv), x: x, y: y) + pv.markers[w.id] = marker + pv.markerFresh.add (w.id, marker) + inc result + +# --------------------------------------------------------------------------------------------------- +# Persistence (marker_seen, migration step 8; the caller owns the transaction) + +const InsertSql = """INSERT INTO marker_seen (player_id, scene_id, wall_id, marker_id) +VALUES (?, ?, ?, ?)""" + +proc writeNew*(db: DbConn, sceneId, playerId: int, fresh: var seq[(int, Marker)]): int = + ## Inserts the markers the last refresh minted for one player and clears the buffer. Called inside + ## the mutation's transaction, after the wall row (for a wall write) committed and before the ack: + ## a marker can never precede the wall that causes it (5.8, 4.2 step 6). + if fresh.len == 0: return 0 + let ps = db.prepare(InsertSql) + try: + for (wallId, marker) in fresh: + db.exec(ps, playerId, sceneId, wallId, marker.id) + inc result + finally: + finalize(ps) + fresh.setLen(0) + +proc restore*(db: DbConn, sc: SceneRec, visions: var Table[int, PlayerVision]) = + ## Startup (4.4): every `marker_seen` row back into its player's memory, before the first + ## connection, with the anchor recomputed from the loaded wall (the anchor is derived, not stored). + ## A row whose wall is missing cannot exist (the composite FK cascades); skipping one defensively + ## keeps a hand-edited DB from crashing startup. + for row in db.getAllRows(sql""" + SELECT player_id, wall_id, marker_id FROM marker_seen WHERE scene_id = ?""", sc.id): + let pid = parseInt(row[0]) + let wallId = parseInt(row[1]) + let wall = sc.wallById(wallId) + if wall.isNone: continue + let (x, y) = anchorOf(wall.get) + visions.mgetOrPut(pid, PlayerVision()).markers[wallId] = + Marker(id: row[2], x: x, y: y) + +proc markerCount*(db: DbConn, sceneId: int): int = + ## Scene-wide marker rows: an O(1) startup log number (11.3) and a test probe. + parseInt(db.getValue(sql"SELECT count(*) FROM marker_seen WHERE scene_id = ?", sceneId)) diff --git a/server/views.nim b/server/views.nim index 7a86648..b4bb662 100644 --- a/server/views.nim +++ b/server/views.nim @@ -104,6 +104,12 @@ type name*: string grey*: bool + MarkerView* = object + ## One player marker (DESIGN 5.8, 6.1): the player's own opaque id and the wall's drawn midpoint + ## in integer px. There is deliberately no wall id, kind, state, label or switch here. + id*: string + x*, y*: int + GmEncounteredView* = object player*: int entries*: seq[EncounteredView] @@ -117,6 +123,7 @@ type tokens*: seq[PlayerTokenView] characters*: seq[PlayerCharacterView] encountered*: seq[EncounteredView] + markers*: seq[MarkerView] polys*: seq[Poly] fresh*: seq[(int, int)] @@ -151,6 +158,7 @@ type tokens*: Table[string, JsonNode] characters*: Table[string, JsonNode] encountered*: Table[string, JsonNode] ## GM: "/"; player: "" + markers*: Table[string, JsonNode] ## player: marker id -> the `{id,pos}` entry sent vision*: string ## the last `vision` payload sent, "" = never visionSent*: bool @@ -291,8 +299,7 @@ proc playerView*(ctx: Context, playerId: int): PlayerView = result.encountered.add EncounteredView(id: eid, name: e.entryName, grey: eid notin visible) when defined(leakfault): # Negative controls (DESIGN 10.3): add what the honest rule just refused, so the harness proves - # it would notice. Never a second copy of the visibility rule. - # The two "add a token the honest rule refused" controls build the frame exactly as the honest + # it would notice. Never a second copy of the visibility rule. # The two "add a token the honest rule refused" controls build the frame exactly as the honest # path would, so the class they report stays the one they were built for (a bucket mismatch here # would add an OWNER_PROP/CHAR_OWNER_PROP class and blunt the assertion). proc leakedView(t: TokenRec): PlayerTokenView = @@ -367,6 +374,12 @@ proc playerView*(ctx: Context, playerId: int): PlayerView = if ch.isNone or ch.get.owner == playerId: continue for v in result.tokens.mitems: if v.id == t.id: v.cpropsPublic = objectOf(ch.get.props[pbOwner]) + result.markers = newSeqOfCap[MarkerView](pv[].markers.len) + for _, marker in pv[].markers.pairs: + result.markers.add MarkerView(id: marker.id, x: marker.x, y: marker.y) + # Deterministic order by the opaque id: the full set is compared byte-for-byte on resync, and the + # order must not reveal wall order or count (the ids are random, 5.8). + result.markers.sort(proc (a, b: MarkerView): int = cmp(a.id, b.id)) result.polys = pv[].polys result.fresh = pv[].fresh @@ -504,6 +517,22 @@ proc exploredFreshFrame*(cells: seq[(int, int)]): JsonNode = for (cx, cy) in cells: list.add %*[cx, cy] %*{"t": "explored", "full": false, "cells": list} +proc markerEntryJson(m: MarkerView): JsonNode = + ## One entry of a `marker` set: only the opaque id and the integer-px anchor (5.8, 6.1). + %*{"id": m.id, "pos": [m.x, m.y]} + +proc markerFrame*(entries: seq[MarkerView], full: bool, del: seq[string]): JsonNode = + ## `marker {full, set:[{id, pos}], del:[id]}` (DESIGN 6.1). `full:true` replaces the whole set on + ## connect/resync and carries no `del`; a diff carries additions in `set` and retractions in `del`, + ## never both for one id. Retraction emission is #60; this builder already has the shape. + var set: JsonNode = newJArray() + for m in entries: set.add markerEntryJson(m) + result = %*{"t": "marker", "full": full, "set": set} + if not full: + var removals = newJArray() + for id in del: removals.add %id + result["del"] = removals + proc sceneBlock*(sc: SceneRec): JsonNode = ## The `scene` object inside `hello` (DESIGN 6.1, 3.1: no counts, no wall data, no owned ids). %*{"id": sc.id, "name": sc.name, "w": sc.w, "h": sc.h, "tile_size": sc.tileSize, @@ -562,6 +591,27 @@ proc diffEncountered(known: var Known, key: string, entries: seq[EncounteredView del.sort() encounteredFrame(set, full, del, player) +proc diffMarkers(known: var Known, markers: seq[MarkerView], full: bool): JsonNode = + ## One `marker` message or nil (DESIGN 5.8, 6.1): on connect/resync `full:true` with the whole set + ## (after `explored`, 6.3); afterwards only new ids in `set`. The `del` path exists in the frame + ## shape but the r1 map is add-only: retraction is #60, so it stays empty here. + var seen = initHashSet[string]() + var set: seq[MarkerView] + var del: seq[string] + for m in markers: + seen.incl m.id + let frame = markerEntryJson(m) + if full or known.markers.getOrDefault(m.id) != frame: + known.markers[m.id] = frame + set.add m + for id in known.markers.keys.toSeq: + if id in seen: continue + known.markers.del id + if not full: del.add id + if full or set.len > 0 or del.len > 0: + del.sort() + return markerFrame(set, full, del) + proc egressFrames*(r: Recipient, ctx: Context, known: var Known, resync = false): seq[JsonNode] = ## Ordered like the 6.3 resync sequence: characters, encountered, then vision/explored and the ## tokens. Empty = nothing changed for this recipient, which is what keeps hidden mutations @@ -624,6 +674,12 @@ proc egressFrames*(r: Recipient, ctx: Context, known: var Known, resync = false) fresh.add other.exploredFull(ctx.scene) result.add exploredFreshFrame(fresh) + # 6.3: `marker` (full) sits after `explored` because it is the same kind of memory and the client + # draws it over the fog `explored` just rebuilt. A diff follows the explored diff for the same + # reason. The GM never reaches this branch (3.1, 5.8). + let markerMsg = diffMarkers(known, view.markers, resync) + if not markerMsg.isNil: result.add markerMsg + var seen = initHashSet[string]() for v in view.tokens: seen.incl v.id diff --git a/server/vision.nim b/server/vision.nim index 4cbbf54..9782dcb 100644 --- a/server/vision.nim +++ b/server/vision.nim @@ -20,7 +20,12 @@ ## ## Change tracking: `ver` counts polygon changes (the client gets `vision` only when it changes, 6.4) ## and `fresh` holds the cells this mutation added (4.2 step 8: cleared after egress). -import std/[algorithm, math, sets] +## +## Player markers (DESIGN 5.8, ADR-0015, #59) are per-player memory like explored: `markers` maps a +## wall id to that player's own opaque marker id and its fixed anchor (integer px). The map only grows +## in this round; retraction and re-earning are #60. `markerFresh` holds the markers minted by the +## current refresh so the mutation's transaction can persist them (server/markers.nim). +import std/[algorithm, math, sets, tables] import tokens, worldmap, geometry, world, faults type @@ -28,11 +33,19 @@ type tokenId*: string pts*: seq[Vec] + Marker* = object + ## One player's marker memory for one wall (DESIGN 5.8, 6.1). The id is opaque and per player; + ## the anchor is the wall's drawn midpoint, rounded once at mint time and never updated. + id*: string + x*, y*: int + PlayerVision* = object polys*: seq[Poly] explored*: HashSet[int] ## cell index cy * cols + cx ver*: int ## bumped when `polys` changes fresh*: seq[(int, int)] ## cells added by the current mutation (cx, cy), sorted + markers*: Table[int, Marker] ## wall id -> this player's marker (5.8, #59) + markerFresh*: seq[(int, Marker)] ## markers minted by the last refresh, awaiting the DB write proc cols*(sc: SceneRec): int = ## Cells across the scene (DESIGN 8: ceil(w / cell)). diff --git a/tests/tviews.nim b/tests/tviews.nim index 5b632b2..cbaccb1 100644 --- a/tests/tviews.nim +++ b/tests/tviews.nim @@ -141,7 +141,7 @@ suite "diff (6.4: only what changed)": var ctx = ctxOf(sceneWith(@[]), @[tok("mine", 400, 400, Pid)], @[Pid]) var known: Known let first = pass(ctx, known, resync = true) - check typesOf(first) == @["encountered", "vision", "explored", "token"] + check typesOf(first) == @["encountered", "vision", "explored", "marker", "token"] check first[0]["full"].getBool # 6.3: the whole list on connect/resync check first[0]["set"].len == 0 check first[2]["full"].getBool diff --git a/tools/leak.mjs b/tools/leak.mjs index d1c3fb4..fa87e75 100644 --- a/tools/leak.mjs +++ b/tools/leak.mjs @@ -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 () => { diff --git a/tools/leakcheck.nim b/tools/leakcheck.nim index 2d39bf4..780c306 100644 --- a/tools/leakcheck.nim +++ b/tools/leakcheck.nim @@ -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, ", diff --git a/tools/markers.test.mjs b/tools/markers.test.mjs new file mode 100644 index 0000000..292d87a --- /dev/null +++ b/tools/markers.test.mjs @@ -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() + }) + }) diff --git a/tools/protocol.test.mjs b/tools/protocol.test.mjs index d947fc8..ee2bc0f 100644 --- a/tools/protocol.test.mjs +++ b/tools/protocol.test.mjs @@ -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) => { diff --git a/tools/restart.test.mjs b/tools/restart.test.mjs index 22519c1..5d3eb57 100644 --- a/tools/restart.test.mjs +++ b/tools/restart.test.mjs @@ -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 }) }