diff --git a/server/main.nim b/server/main.nim index cf30af3..06e670a 100644 --- a/server/main.nim +++ b/server/main.nim @@ -137,7 +137,15 @@ proc closeGone(conn: Conn, reason: string, code: int) = # views.egressFrames and never enter a PlayerView at all. proc wallObjectOf(w: WallRec): JsonNode = - wallObject(w.id, w.a, w.b, $w.kind, w.open, w.flags) + ## The GM's typed wall (DESIGN 6.1 proto 2): every stored field plus the derived shape label. + wallObject(WallView(id: w.id, a: w.a, b: w.b, thickness: w.thickness, position: $w.position, + blocksSight: w.blocksSight, blocksMovement: w.blocksMovement, + sightDir: $w.sightDir, playerMarker: w.playerMarker, door: w.door, + open: w.open, secret: w.secret, locked: w.locked, + height: (if w.height.isSome: w.height.get else: 0.0), + hasHeight: w.height.isSome, + label: (if w.label.isSome: w.label.get else: ""), + hasLabel: w.label.isSome, kind: derivedKind(w), flags: w.flags)) proc wallsSnapshot(sc: SceneRec): JsonNode = var walls: seq[JsonNode] @@ -484,6 +492,144 @@ proc declared(env: Envelope, key: string): bool = ## `vision_radius: null` means "the scene default" (6.1), so both are real patch fields. not env.node.isNil and env.node.hasKey(key) +# Wall payload fields (DESIGN 6.1, proto 2, #54). `kind` and (in an update) `open` are never read: +# they are unknown fields and ignored (6.2). Absent and JSON null are the same field-absent for +# every wall field except `height` and `label`, where an explicit null means "clear it". + +proc parseWallGeometry(env: Envelope, rec: var WallRec): bool = + ## thickness (px), position and height (metres); the ranges are checked by `validWall`. + if present(env, "thickness"): + let v = parseFinite(fieldOrNull(env.node, "thickness")) + if v.isNone: return false + rec.thickness = v.get + if present(env, "position"): + let node = env.node{"position"} + if node.kind != JString: return false + let p = parsePosition(node.getStr) + if p.isNone: return false + rec.position = p.get + if declared(env, "height"): + let node = env.node{"height"} + if node.kind == JNull: + rec.height = none(float) + else: + let v = parseFinite(node) + if v.isNone: return false + rec.height = v + true + +proc parseWallLabel(env: Envelope, rec: var WallRec): bool = + ## `label` absent leaves it alone on an update (the caller seeds `rec` from the stored row); + ## an explicit null clears it; anything but a string is `invalid`. The 6.5 text rule is #55, + ## but the schema's 1..64 bound is enforced by `validWall` so SQLite cannot raise. + if not declared(env, "label"): return true + let node = env.node{"label"} + if node.kind == JNull: + rec.label = none(string) + elif node.kind == JString: + rec.label = some(node.getStr) + else: + return false + true + +proc parseWallSwitch(env: Envelope, key: string, dest: var bool): bool = + ## One boolean switch: absent = leave `dest`; a non-boolean is `invalid`. + if not present(env, key): return true + boolField(env, key, dest) + +proc parseWallSwitches(env: Envelope, rec: var WallRec, allowOpen: bool): bool = + ## The raw 5.8 switches on a create: omitted switches keep the candidate's value (the `wall` + ## defaults), `open` is accepted here. A `sight_dir` outside the three words is `invalid`. + if not parseWallSwitch(env, "blocks_sight", rec.blocksSight): return false + if not parseWallSwitch(env, "blocks_movement", rec.blocksMovement): return false + if not parseWallSwitch(env, "player_marker", rec.playerMarker): return false + if not parseWallSwitch(env, "door", rec.door): return false + if allowOpen and not parseWallSwitch(env, "open", rec.open): return false + if not parseWallSwitch(env, "secret", rec.secret): return false + if not parseWallSwitch(env, "locked", rec.locked): return false + if present(env, "sight_dir"): + let node = env.node{"sight_dir"} + if node.kind != JString: return false + let d = parseSightDir(node.getStr) + if d.isNone: return false + rec.sightDir = d.get + true + +proc parseWallPatch(env: Envelope, patch: var WallPatch): bool = + ## `wall.update` names only the fields it patches. `open` and `kind` are unknown here and are + ## ignored: a door's open state changes only through `door.set` (DESIGN 6.1, #54). + if present(env, "a"): + let v = parseVec(env.node{"a"}) + if v.isNone: return false + patch.a = v + if present(env, "b"): + let v = parseVec(env.node{"b"}) + if v.isNone: return false + patch.b = v + if present(env, "thickness"): + let v = parseFinite(fieldOrNull(env.node, "thickness")) + if v.isNone: return false + patch.thickness = v + if present(env, "position"): + let node = env.node{"position"} + if node.kind != JString: return false + let p = parsePosition(node.getStr) + if p.isNone: return false + patch.position = p + if declared(env, "height"): + let node = env.node{"height"} + if node.kind == JNull: + patch.clearHeight = true + else: + let v = parseFinite(node) + if v.isNone: return false + patch.height = v + if declared(env, "label"): + let node = env.node{"label"} + if node.kind == JNull: + patch.clearLabel = true + elif node.kind == JString: + patch.label = some(node.getStr) + else: + return false + var bit: bool + if present(env, "blocks_sight"): + if not boolField(env, "blocks_sight", bit): return false + patch.blocksSight = some(bit) + if present(env, "blocks_movement"): + if not boolField(env, "blocks_movement", bit): return false + patch.blocksMovement = some(bit) + if present(env, "player_marker"): + if not boolField(env, "player_marker", bit): return false + patch.playerMarker = some(bit) + if present(env, "door"): + if not boolField(env, "door", bit): return false + patch.door = some(bit) + if present(env, "secret"): + if not boolField(env, "secret", bit): return false + patch.secret = some(bit) + if present(env, "locked"): + if not boolField(env, "locked", bit): return false + patch.locked = some(bit) + if present(env, "sight_dir"): + let node = env.node{"sight_dir"} + if node.kind != JString: return false + let d = parseSightDir(node.getStr) + if d.isNone: return false + patch.sightDir = d + if present(env, "flags"): + let f = parseFlags(env.node{"flags"}) + if f.isNone: return false + patch.flags = f + true + +proc wallPatchHasField(patch: WallPatch): bool = + patch.a.isSome or patch.b.isSome or patch.thickness.isSome or patch.position.isSome or + patch.height.isSome or patch.clearHeight or patch.label.isSome or patch.clearLabel or + patch.blocksSight.isSome or patch.blocksMovement.isSome or patch.sightDir.isSome or + patch.playerMarker.isSome or patch.door.isSome or patch.secret.isSome or patch.locked.isSome or + patch.flags.isSome + type ControllerCheck = enum ccOk @@ -1897,20 +2043,10 @@ proc dispatch(conn: Conn, env: Envelope) {.gcsafe.} = if a.isNone or b.isNone: ackErr(conn, env.reqId, CodeInvalid) return - let kindNode = env.node{"kind"} - if kindNode.isNil or kindNode.kind != JString: - ackErr(conn, env.reqId, CodeInvalid) - return - let kind = parseKind(kindNode.getStr) - if kind.isNone: - ackErr(conn, env.reqId, CodeInvalid) - return - let open = parseOpen(fieldOrNull(env.node, "open")) - if open.isNone: - ackErr(conn, env.reqId, CodeInvalid) - return - if kind.get == wkWall and open.get: - # A wall is never open; only a door has an open state (DESIGN 6.1, 8). + # The raw-switch create: omitted switches keep the `wall` preset's defaults (DESIGN 6.1, #54). + var candidate = defaultWall(a.get, b.get) + if not parseWallGeometry(env, candidate) or not parseWallSwitches(env, candidate, true) or + not parseWallLabel(env, candidate): ackErr(conn, env.reqId, CodeInvalid) return let flags = parseFlags(fieldOrNull(env.node, "flags")) @@ -1923,16 +2059,15 @@ proc dispatch(conn: Conn, env: Envelope) {.gcsafe.} = var ok = false withLock app.dbLock: sceneId = app.scene.id # the request's one read (#31) - # `candidate` is built here so its `flags` copy and its record copy both die under the lock; - # `detachedJson` keeps the stored object independent of `env` (ANALYSIS 4.1). - let candidate = WallRec(a: a.get, b: b.get, door: kind.get == wkDoor, - open: open.get, blocksSight: true, blocksMovement: true, - flags: detachedJson(flags.get)) + # The record is copied here so its `flags` object and the record copy both die under the + # lock; `detachedJson` keeps the stored object independent of `env` (ANALYSIS 4.1). + var stored = candidate + stored.flags = detachedJson(flags.get) # 5.5 SET: the new wall sticks every token its circle overlaps. The rules run on a snapshot # taken before the write (the id is assigned by the write), and their outcome is applied only # after it committed, so a failed write leaves every token untouched. var mr = moveScene(app.scene, app.tokens) - let id = addWall(app.db, app.scene, candidate) + let id = addWall(app.db, app.scene, stored) if id.isSome: let added = wallById(app.scene, id.get) discard moverules.addWall(mr, ruleWall(added.get)) @@ -1940,7 +2075,7 @@ proc dispatch(conn: Conn, env: Envelope) {.gcsafe.} = 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 addedId = added.get.id - addedKind = $added.get.kind + addedKind = derivedKind(added.get) # The wall frame references `added.flags`; build it and fan it out here, before the record # copy leaves scope, never after the lock is released (ANALYSIS 4.1). settleWorldLocked(conn, env.reqId, wallFrame(sceneId, wallObjectOf(added.get)), @@ -1960,41 +2095,12 @@ proc dispatch(conn: Conn, env: Envelope) {.gcsafe.} = ackErr(conn, env.reqId, CodeInvalid) return var patch: WallPatch - var anyField = false - if not fieldOrNull(env.node, "a").isNil: - let a = parseVec(env.node{"a"}) - if a.isNone: - ackErr(conn, env.reqId, CodeInvalid) - return - patch.a = a - anyField = true - if not fieldOrNull(env.node, "b").isNil: - let b = parseVec(env.node{"b"}) - if b.isNone: - ackErr(conn, env.reqId, CodeInvalid) - return - patch.b = b - anyField = true - if not fieldOrNull(env.node, "kind").isNil: - let node = env.node{"kind"} - if node.kind != JString: - ackErr(conn, env.reqId, CodeInvalid) - return - let kind = parseKind(node.getStr) - if kind.isNone: - ackErr(conn, env.reqId, CodeInvalid) - return - patch.kind = kind - anyField = true - if not fieldOrNull(env.node, "flags").isNil: - let flags = parseFlags(env.node{"flags"}) - if flags.isNone: - ackErr(conn, env.reqId, CodeInvalid) - return - patch.flags = flags - anyField = true - if not anyField: - # `wall.update` changes at least one of a, b, kind, flags (6.1). + if not parseWallPatch(env, patch): + ackErr(conn, env.reqId, CodeInvalid) + return + if not wallPatchHasField(patch): + # A fieldless update (or one naming only the ignored `open`/`kind`) is `invalid`, before the + # target lookup (6.1, 6.5 steps 7 then 8). ackErr(conn, env.reqId, CodeInvalid) return var outcome = waNotFound @@ -2020,7 +2126,7 @@ proc dispatch(conn: Conn, env: Envelope) {.gcsafe.} = discard applyRuleOutcome(mr) refreshAll() persistAllExplored() - updatedKind = $updated.get.kind + 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))) ok = true diff --git a/server/protocol.nim b/server/protocol.nim index 82a1fc6..61d6b9e 100644 --- a/server/protocol.nim +++ b/server/protocol.nim @@ -14,8 +14,10 @@ import std/[json, monotimes, unicode] import geometry const - ProtoVersion* = 1 - ## M3 ships proto 1 (DESIGN 6.2). The client announces it as `/ws?proto=N`. + ProtoVersion* = 2 + ## proto 2 is the wall-model build (DESIGN 6.2, ADR-0011, #54): the wall payloads carry the + ## typed geometry and switches, `kind` is output-only and the GM frames echo the full record. + ## The client announces it as `/ws?proto=N`. MaxInboundBytes* = 64 * 1024 ## DESIGN 6.4: mummy's `maxMessageLen`, inbound and cumulative across fragments. RatePerSecond* = 30 @@ -211,10 +213,39 @@ proc rosterEntry*(id: int, name: JsonNode, role: string, colour: string, # `n`: they are the only frames fanned out to several recipients at once (every GM connection), and # each recipient gets its own number, added by the sender with `withN` right before the send. -proc wallObject*(id: int, a, b: Vec, kind: string, open: bool, flags: JsonNode): JsonNode = +type + WallView* = object + ## One wall as the GM's `wall`/`walls` frames show it (DESIGN 6.1, proto 2, #54). The typed + ## record plus the derived shape label; `height` and `label` are always present and null when + ## unset (the frame is GM-only, so their presence marks nothing). This is the narrow wire shape, + ## kept out of `world.nim` so the protocol shell stays free of storage imports. + id*: int + a*, b*: Vec + thickness*: float + position*: string + blocksSight*, blocksMovement*: bool + sightDir*: string + playerMarker*, door*, open*, secret*, locked*: bool + height*: float + hasHeight*: bool ## false = full height (`height:null`) + label*: string + hasLabel*: bool ## false = no label (`label:null`) + kind*: string ## the derived 5.8 shape label, output only + flags*: JsonNode + +proc wallObject*(w: WallView): JsonNode = ## One wall as the wire shows it: the same shape inside `walls` and in a `wall` upsert. - %*{"id": id, "a": [a.x, a.y], "b": [b.x, b.y], "kind": kind, "open": open, - "flags": (if flags.isNil: newJObject() else: flags)} + %*{ + "id": w.id, "a": [w.a.x, w.a.y], "b": [w.b.x, w.b.y], + "thickness": w.thickness, "position": w.position, + "height": (if w.hasHeight: %w.height else: newJNull()), + "kind": w.kind, + "blocks_sight": w.blocksSight, "blocks_movement": w.blocksMovement, + "sight_dir": w.sightDir, "player_marker": w.playerMarker, + "door": w.door, "open": w.open, "secret": w.secret, "locked": w.locked, + "label": (if w.hasLabel: %w.label else: newJNull()), + "flags": (if w.flags.isNil: newJObject() else: w.flags) + } proc wallsFrame*(scene: int, walls: seq[JsonNode]): JsonNode = ## The GM snapshot of every wall in the scene (DESIGN 6.1 `walls`, 6.3: on connect and resync). diff --git a/server/views.nim b/server/views.nim index be789d9..7a86648 100644 --- a/server/views.nim +++ b/server/views.nim @@ -427,6 +427,9 @@ proc playerTokenFrame*(v: PlayerTokenView): JsonNode = buckets["gm"] = v.faultGmProps if faultActive("statusSource") and v.faultStatusEntries.len > 0: result["statuses"] = statusesJson(v.faultStatusEntries) + if faultActive("wallHeight"): + # WALLDATA positive control (#54): a wall field name (`height`) in a player token frame. + result["height"] = %1.8 proc tokenGoneFrame*(id: string): JsonNode = %*{"t": "token_gone", "id": id} diff --git a/server/world.nim b/server/world.nim index e39bae4..4a6c71c 100644 --- a/server/world.nim +++ b/server/world.nim @@ -4,9 +4,10 @@ ## ## Walls (DESIGN 8, FIXED #3): per-scene ids from `scene.next_wall_id`, monotonic and never reused ## (a removal leaves the counter alone). Identity is `(scene, id)` in the DB, in memory and on the -## wire. Doors are walls with `kind = door`; `blocks = not (kind == door and open)` comes from -## geometry.Wall when slice 5 feeds the vision code. `flags` is a free JSON object the server never -## interprets (M6/Beyond: window, one-way, secret door live there). +## wire. Today a wall's sight/movement behaviour is still `blocks = not (door and open)` in +## geometry.Wall; the stored switches (`blocks_sight`, `blocks_movement`, `sight_dir`) gain their +## behaviour in the window/one-way rounds (#57/#58). `flags` is a free JSON object the server never +## interprets. ## ## Wire payload shapes are DESIGN 6.1; the parts it leaves open are fixed here (recorded FIXED ## owner-delegated, #19, in DESIGN 6.1/14): @@ -15,11 +16,11 @@ ## - `scene.set` (slice 10, #25): the patch rules of 6.1 ("Scene payload rules"); `w`, `h`, ## `tile_size`, `cell` and `art_version` are not patch fields. `patched`/`writeSceneRow` are pure ## and transaction-free so main.nim can commit the scene row with the tokens it resized. -## - `wall.add`: `open` omitted = false; `open` on a `kind: "wall"` is `invalid` (a wall is never -## open), and the stored row normalizes it to false regardless. -## - `wall.update` patches `a`, `b`, `kind`, `flags` only (`open` belongs to `door.set`; an `open` -## field here is an unknown field and is ignored); at least one patch field is required, else -## `invalid`. Changing `kind` door -> wall closes the door. +## - `wall.add`: the geometry fields and the eight raw switches of 6.1; an omitted switch keeps +## the `wall` default, `open` omitted = false, and a non-door never stores door-only settings. +## - `wall.update` patches only what it names (geometry, the switches except `open`, `label`, +## `flags`); `open` belongs to `door.set`, so an `open` field here is an unknown field and is +## ignored, and at least one patch field is required, else `invalid`. ## - `a != b` (a zero-length wall is refused) and both endpoints inside `[0,w] x [0,h]`. ## - `flags` must be a JSON object; omitted = `{}`. Coordinates must be finite numbers. ## @@ -27,15 +28,11 @@ ## around it (Q12 FIXED: GM authoring is the expensive-to-lose data) and the in-memory state is ## updated only after COMMIT, so a failing write leaves memory and DB identical. This module does ## no locking: the caller holds the global lock (4.3). -import std/[json, math, options, strutils] +import std/[json, math, options, strutils, unicode] import db_connector/db_sqlite import geometry, text type - WallKind* = enum - wkWall = "wall" - wkDoor = "door" - WallPosition* = enum wpCenter = "center" wpLeft = "left" @@ -47,8 +44,8 @@ type sdRight = "right" WallRec* = object - ## The typed wall record of DESIGN 8. The wire still carries the legacy `kind`/`open` pair in - ## this round (#53); `kind` is derived from `door` and nothing else is exposed there yet (#54). + ## The typed wall record of DESIGN 8. Every field is a column; `kind` is never stored and is + ## derived from the switches (`derivedKind`) for the GM's frames (#54). id*: int a*, b*: Vec thickness*: float @@ -83,8 +80,19 @@ type WallPatch* = object ## The updatable fields of `wall.update` (DESIGN 6.1); none = the field keeps its value. + ## `open` is not here: it belongs to `door.set` and is an unknown field in a wall update (#54). + ## `height`/`label` use a separate `clear*` flag because an explicit JSON null is a real patch + ## ("clear it"), while an absent field keeps the stored value. a*, b*: Option[Vec] - kind*: Option[WallKind] + thickness*: Option[float] + position*: Option[WallPosition] + height*: Option[float] + clearHeight*: bool + label*: Option[string] + clearLabel*: bool + blocksSight*, blocksMovement*: Option[bool] + sightDir*: Option[SightDir] + playerMarker*, door*, secret*, locked*: Option[bool] flags*: Option[JsonNode] ScenePatch* = object @@ -104,36 +112,41 @@ type const DefaultSceneId* = 1 ## The seeded v1 scene (migration step 3). Exactly one scene exists in v1 (Q3). - WallKinds* = [wkWall, wkDoor] + WallPositions* = [wpCenter, wpLeft, wpRight] + SightDirs* = [sdBoth, sdLeft, sdRight] SceneNameMaxLen* = 64 ## `scene.set.name`: the 6.5 text rule, same 64-code-point bound as character names (#25). proc defaultWall*(a, b: Vec): WallRec = - ## The `wall` preset's switches: both blocks on, both-way sight, no marker, no door settings. - WallRec(a: a, b: b, blocksSight: true, blocksMovement: true, flags: newJObject()) + ## The `wall` preset's switches: both blocks on, both-way sight, no marker, no door settings, + ## zero thickness, centre placement and full height (DESIGN 5.8, 6.1). + WallRec(a: a, b: b, position: wpCenter, blocksSight: true, blocksMovement: true, + sightDir: sdBoth, flags: newJObject()) -proc kind*(w: WallRec): WallKind = - ## The legacy wire label for this round: only the door axis exists on it (#53). #54 replaces - ## this with the full derived shape label. - if w.door: wkDoor else: wkWall - -proc `kind=`*(w: var WallRec, k: WallKind) = - ## Legacy update path (`wall.update {kind}`): a wall is never open; clearing the door switch - ## also drops the door-only settings so the DB CHECK cannot see an impossible row. - if k == wkDoor: - w.door = true +proc derivedKind*(w: WallRec): string = + ## The GM-only shape label of DESIGN 5.8, derived in this order and never stored or accepted as + ## input: window, one_way, door, wall, else custom. `secret`/`locked` never change it. + if not w.blocksSight and w.blocksMovement: + "window" + elif w.blocksSight and w.sightDir != sdBoth: + "one_way" + elif w.blocksSight and w.blocksMovement and w.door: + "door" + elif w.blocksSight and w.blocksMovement and not w.door and w.sightDir == sdBoth: + "wall" else: - w.door = false - w.open = false - w.secret = false - w.locked = false + "custom" # --------------------------------------------------------------------------------------------------- # Field parsing (DESIGN 6.1 field notes: px floats, missing or wrongly typed -> `invalid`) -proc parseKind*(raw: string): Option[WallKind] = - for k in WallKinds: - if $k == raw: return some(k) +proc parsePosition*(raw: string): Option[WallPosition] = + for p in WallPositions: + if $p == raw: return some(p) + +proc parseSightDir*(raw: string): Option[SightDir] = + for d in SightDirs: + if $d == raw: return some(d) proc parseVec*(node: JsonNode): Option[Vec] = ## `a:[x,y]` / `b:[x,y]`: exactly two finite JSON numbers. @@ -155,19 +168,13 @@ proc parseFlags*(node: JsonNode): Option[JsonNode] = if node.kind != JObject: return none(JsonNode) some(node) -proc parseOpen*(node: JsonNode): Option[bool] = - ## `open?`: a boolean or absent (= false). - if node.isNil: return some(false) - if node.kind != JBool: return none(bool) - some(node.getBool) - proc fieldOrNull*(env: JsonNode, key: string): JsonNode = ## `undefined` and `null` are both "field absent" for the wall payloads. if env.isNil: return nil result = env{key} if not result.isNil and result.kind == JNull: result = nil -proc parseFinite(node: JsonNode): Option[float] = +proc parseFinite*(node: JsonNode): Option[float] = ## One finite JSON number (integers accepted; strings, booleans and null are not numbers). if node.isNil: return none(float) case node.kind @@ -233,13 +240,32 @@ proc patched*(sc: SceneRec, patch: ScenePatch): SceneRec = proc inBounds(sc: SceneRec, p: Vec): bool = p.x >= 0 and p.y >= 0 and p.x <= sc.w and p.y <= sc.h # written so NaN fails +proc storable*(rec: WallRec): bool = + ## The subset of the switch-set invariants the database CHECKs already enforce (db.nim step 8). + ## #54 accepts and stores the raw switches; this test keeps a payload the schema cannot store from + ## reaching SQLite and raising. The full expand-and-validate path, presets and the remaining + ## switch-set rules are #55. + if rec.open and not rec.door: return false + if rec.secret and not rec.door: return false + if rec.secret and (rec.open or not rec.blocksSight or not rec.blocksMovement or + rec.sightDir != sdBoth): return false + if rec.locked and not rec.door: return false + if rec.sightDir != sdBoth and not rec.blocksSight: return false + true + proc validWall*(sc: SceneRec, rec: WallRec): bool = - ## DESIGN 6.1 `wall.*` validation: `a != b`, both endpoints in bounds. `kind` and `flags` are - ## checked by the parsers, so a `WallRec` can only carry valid ones. - (rec.a.x != rec.b.x or rec.a.y != rec.b.y) and inBounds(sc, rec.a) and inBounds(sc, rec.b) + ## DESIGN 6.1 `wall.*` validation: `a != b`, both endpoints in bounds, the geometry ranges and a + ## switch set the schema can store. `flags` is checked by the parser, so a `WallRec` can only + ## carry a valid one. + (rec.a.x != rec.b.x or rec.a.y != rec.b.y) and inBounds(sc, rec.a) and inBounds(sc, rec.b) and + rec.thickness >= 0 and rec.thickness <= 256 and + (rec.height.isNone or (rec.height.get > 0 and rec.height.get <= 100)) and + (rec.label.isNone or (rec.label.get.runeLen >= 1 and rec.label.get.runeLen <= 64)) and + storable(rec) proc normalize*(rec: WallRec): WallRec = - ## A wall is never open; only a door can be, and a non-door stores no door-only settings. + ## A non-door stores no door-only settings (clearing `door` closes and de-secrets), and a missing + ## flags object becomes `{}` (DESIGN 6.1). result = rec if not result.door: result.open = false @@ -256,11 +282,25 @@ proc wallById*(sc: SceneRec, id: int): Option[WallRec] = if i.isSome: return some(sc.walls[i.get]) proc patched*(w: WallRec, patch: WallPatch): WallRec = - ## `wall.update` candidate: the stored row with the patch applied (open untouched). + ## `wall.update` candidate: the stored row with the patch applied. A patch is absolute and only + ## touches what it names; `open` is never here (door.set owns it). `clearHeight`/`clearLabel` are + ## an explicit null, distinct from an absent field. result = w if patch.a.isSome: result.a = patch.a.get if patch.b.isSome: result.b = patch.b.get - if patch.kind.isSome: result.kind = patch.kind.get + if patch.thickness.isSome: result.thickness = patch.thickness.get + if patch.position.isSome: result.position = patch.position.get + if patch.clearHeight: result.height = none(float) + elif patch.height.isSome: result.height = patch.height + if patch.clearLabel: result.label = none(string) + elif patch.label.isSome: result.label = patch.label + if patch.blocksSight.isSome: result.blocksSight = patch.blocksSight.get + if patch.blocksMovement.isSome: result.blocksMovement = patch.blocksMovement.get + if patch.sightDir.isSome: result.sightDir = patch.sightDir.get + if patch.playerMarker.isSome: result.playerMarker = patch.playerMarker.get + if patch.door.isSome: result.door = patch.door.get + if patch.secret.isSome: result.secret = patch.secret.get + if patch.locked.isSome: result.locked = patch.locked.get if patch.flags.isSome: result.flags = patch.flags.get result = normalize(result) @@ -355,7 +395,7 @@ proc addWall*(db: DbConn, sc: var SceneRec, rec: WallRec): Option[int] = proc updateWall*(db: DbConn, sc: var SceneRec, rec: WallRec): WallApply = ## `wall.update` = full replacement of the patched row (`remove + add` for the 5.5 status rules, - ## which slice 5 re-evaluates). A kind change door -> wall closes the door. + ## which slice 5 re-evaluates). Clearing the door switch closes and de-secrets the wall. let idx = wallIndex(sc, rec.id) if idx.isNone: return waNotFound let stored = normalize(rec) diff --git a/tests/tprotocol.nim b/tests/tprotocol.nim index 6dcaa29..49e8608 100644 --- a/tests/tprotocol.nim +++ b/tests/tprotocol.nim @@ -148,7 +148,7 @@ suite "server frames (6.1)": check not h.hasKey("scene") # an unnamed player gets proto, role, me only (6.1) check not h.hasKey("extra") check h["t"].getStr == "hello" - check h["proto"].getInt == 1 + check h["proto"].getInt == 2 check h["role"].getStr == "player" check h["me"]["id"].getInt == 4 check h["me"]["name"].kind == JNull @@ -211,25 +211,54 @@ suite "server frames (6.1)": ["revoked", "evicted", "proto-mismatch", "malformed-flood"] suite "wall frames (6.1 `walls`, `wall`, `wall_gone`; GM only)": - test "one wall carries id, a, b, kind, open and flags in the 6.1 shape": - let w = wallObject(7, (10.0, 20.5), (300.0, 20.5), "door", true, %*{"locked": false}) + test "one wall carries the typed record plus the derived kind in the proto-2 shape": + let w = wallObject(WallView(id: 7, a: (10.0, 20.5), b: (300.0, 20.5), thickness: 12.0, + position: "left", blocksSight: true, blocksMovement: true, + sightDir: "both", playerMarker: false, door: true, open: true, + secret: false, locked: true, height: 2.5, hasHeight: true, + label: "the king's window", hasLabel: true, kind: "door", + flags: %*{"locked": false})) check w["id"].getInt == 7 check w["a"][0].getFloat == 10.0 check w["a"][1].getFloat == 20.5 check w["b"][0].getFloat == 300.0 + check w["thickness"].getFloat == 12.0 + check w["position"].getStr == "left" + check w["height"].getFloat == 2.5 check w["kind"].getStr == "door" + check w["blocks_sight"].getBool + check w["blocks_movement"].getBool + check w["sight_dir"].getStr == "both" + check w["player_marker"].getBool == false + check w["door"].getBool check w["open"].getBool + check w["secret"].getBool == false + check w["locked"].getBool + check w["label"].getStr == "the king's window" check w["flags"]["locked"].getBool == false - # an absent flags object is still an object on the wire - check wallObject(1, (0.0, 0.0), (1.0, 0.0), "wall", false, nil)["flags"].kind == JObject + # unset height/label are present as JSON null, and an absent flags object is still an object + let plain = wallObject(WallView(id: 1, a: (0.0, 0.0), b: (1.0, 0.0), position: "center", + blocksSight: true, blocksMovement: true, sightDir: "both", + kind: "wall")) + check plain["height"].kind == JNull + check plain["label"].kind == JNull + check plain["flags"].kind == JObject test "`walls` is the full list plus the scene, `wall` is one upsert, `wall_gone` an id": - let snap = wallsFrame(1, @[wallObject(1, (0.0, 0.0), (9.0, 0.0), "wall", false, nil)]) + let plain = WallView(id: 1, a: (0.0, 0.0), b: (9.0, 0.0), position: "center", + blocksSight: true, blocksMovement: true, sightDir: "both", kind: "wall") + let snap = wallsFrame(1, @[wallObject(plain)]) check snap["t"].getStr == "walls" check snap["scene"].getInt == 1 check snap["walls"].len == 1 check snap["walls"][0]["id"].getInt == 1 - let one = wallFrame(1, wallObject(2, (0.0, 5.0), (9.0, 5.0), "door", false, nil)) + var doorView = plain + doorView.id = 2 + doorView.a = (0.0, 5.0) + doorView.b = (9.0, 5.0) + doorView.door = true + doorView.kind = "door" + let one = wallFrame(1, wallObject(doorView)) check one["t"].getStr == "wall" check one["scene"].getInt == 1 check one["id"].getInt == 2 @@ -240,7 +269,9 @@ suite "wall frames (6.1 `walls`, `wall`, `wall_gone`; GM only)": check gone["id"].getInt == 2 test "the fan-out frames carry no n: the sender stamps it per recipient": + let plain = WallView(id: 1, a: (0.0, 0.0), b: (1.0, 1.0), position: "center", + blocksSight: true, blocksMovement: true, sightDir: "both", kind: "wall") check not wallsFrame(1, @[]).hasKey("n") - check not wallFrame(1, wallObject(1, (0.0, 0.0), (1.0, 1.0), "wall", false, nil)).hasKey("n") + check not wallFrame(1, wallObject(plain)).hasKey("n") check not wallGoneFrame(1, 1).hasKey("n") check withN(wallGoneFrame(1, 1), 12)["n"].getInt == 12 diff --git a/tests/tvision.nim b/tests/tvision.nim index c4b4748..3c29ded 100644 --- a/tests/tvision.nim +++ b/tests/tvision.nim @@ -9,9 +9,9 @@ proc sceneWith(walls: seq[WallRec]): SceneRec = visionRadiusDefault: 400, tokenRadiusDefault: 20, artVersion: 1, nextWallId: 1, extra: newJObject(), walls: walls) -proc wall(ax, ay, bx, by: float, kind = wkWall, open = false): WallRec = +proc wall(ax, ay, bx, by: float, door = false, open = false): WallRec = result = defaultWall((ax, ay), (bx, by)) - result.kind = kind + result.door = door result.open = open proc tok(id: string, x, y: float, owner: int, visionFlag = true, gmOnly = false): TokenRec = @@ -55,8 +55,8 @@ suite "polygons (5.1: one per controlled token with the `vision` flag)": for p in pts: check hypot(p.x - 400, p.y - 400) <= 121 test "an open door does not block; closing it does (5.1, 5.5)": - let closed = sceneWith(@[wall(700, 0, 700, 4096, wkDoor, open = false)]) - let open = sceneWith(@[wall(700, 0, 700, 4096, wkDoor, open = true)]) + let closed = sceneWith(@[wall(700, 0, 700, 4096, door = true, open = false)]) + let open = sceneWith(@[wall(700, 0, 700, 4096, door = true, open = true)]) let tokens = @[tok("me", 400, 400, 2)] check computePolys(closed, tokens, 2)[0].pts.allIt(it.x <= 701) check computePolys(open, tokens, 2)[0].pts.anyIt(it.x > 790) @@ -90,7 +90,7 @@ suite "explored (5.1, 8: strictly per player, only grows)": check not pv.insideAny((400.0, 400.0)) test "a closed door hides the cells behind it; opening it adds them": - var sc = sceneWith(@[wall(700, 0, 700, 4096, wkDoor, open = false)]) + var sc = sceneWith(@[wall(700, 0, 700, 4096, door = true, open = false)]) var pv: PlayerVision pv.refresh(sc, @[tok("me", 400, 400, 2)], 2) let behind = sc.cellIndex(23, 12) # x ~ 750, past the closed door diff --git a/tests/tworld.nim b/tests/tworld.nim index 7485ba3..075d73e 100644 --- a/tests/tworld.nim +++ b/tests/tworld.nim @@ -12,9 +12,9 @@ proc tmpDir(): string = removeDir(result) createDir(result) -proc wall(ax, ay, bx, by: float, kind = wkWall, open = false): WallRec = +proc wall(ax, ay, bx, by: float, door = false, open = false): WallRec = result = defaultWall((ax, ay), (bx, by)) - result.kind = kind + result.door = door result.open = open proc freshScene(): tuple[db: DbConn, dir: string] = @@ -65,19 +65,37 @@ suite "field parsing (6.1 field notes)": check parseVec(newJNull()).isNone check parseVec(nil).isNone - test "kind, open and flags accept only their own shape": - check parseKind("wall").get == wkWall - check parseKind("door").get == wkDoor - check parseKind("window").isNone - check parseKind("").isNone - check parseKind("WALL").isNone - check parseOpen(nil).get == false # omitted = closed - check parseOpen(%true).get == true - check parseOpen(%1).isNone + test "position, sight_dir and flags accept only their own shape": + check parsePosition("center").get == wpCenter + check parsePosition("left").get == wpLeft + check parsePosition("right").get == wpRight + check parsePosition("middle").isNone + check parsePosition("").isNone + check parseSightDir("both").get == sdBoth + check parseSightDir("left").get == sdLeft + check parseSightDir("right").get == sdRight + check parseSightDir("any").isNone check parseFlags(nil).get.kind == JObject # omitted = {} check parseFlags(%*{"a": 1}).get["a"].getInt == 1 check parseFlags(%*[1]).isNone + test "kind is derived from the switches, never stored (5.8)": + check derivedKind(defaultWall((0.0, 0.0), (1.0, 0.0))) == "wall" + var door = defaultWall((0.0, 0.0), (1.0, 0.0)) + door.door = true + check derivedKind(door) == "door" + var window = defaultWall((0.0, 0.0), (1.0, 0.0)) + window.blocksSight = false + check derivedKind(window) == "window" + window.door = true + check derivedKind(window) == "window" # a fixed or opening window is still a window + var oneWay = defaultWall((0.0, 0.0), (1.0, 0.0)) + oneWay.sightDir = sdLeft + check derivedKind(oneWay) == "one_way" + var custom = defaultWall((0.0, 0.0), (1.0, 0.0)) + custom.blocksMovement = false + check derivedKind(custom) == "custom" + test "undefined and null are the same as an absent field": check fieldOrNull(%*{"open": true}, "open").getBool var withNull = newJObject() @@ -141,11 +159,11 @@ suite "persistence (write-through, restart-identical)": var north = defaultWall((0.0, 0.0), (4096.0, 0.0)) north.flags = %*{"note": "north"} let id1 = addWall(conn, sc, north).get - let id2 = addWall(conn, sc, wall(100, 25, 300, 25, wkDoor)).get + let id2 = addWall(conn, sc, wall(100, 25, 300, 25, door = true)).get check setDoor(conn, sc, id2, true) == waOk var changed = defaultWall((0.0, 0.0), (2000.0, 0.0)) changed.id = id1 - changed.kind = wkDoor + changed.door = true changed.flags = %*{"note": "north wall"} check updateWall(conn, sc, changed) == waOk @@ -155,11 +173,11 @@ suite "persistence (write-through, restart-identical)": check reloaded.walls[0].id == id1 check reloaded.walls[0].a == (0.0, 0.0) check reloaded.walls[0].b == (2000.0, 0.0) - check reloaded.walls[0].kind == wkDoor # kind is updatable + check reloaded.walls[0].door # the door switch is updatable check reloaded.walls[0].open == false check reloaded.walls[0].flags["note"].getStr == "north wall" check reloaded.walls[1].id == id2 - check reloaded.walls[1].kind == wkDoor + check reloaded.walls[1].door check reloaded.walls[1].open == true # an open door stays open check reloaded.walls[1].flags.kind == JObject # flags default to {} @@ -264,25 +282,25 @@ suite "validation (DESIGN 6.1 `wall.*`)": close(conn) removeDir(d) var sc = loadScene(conn).get - let id = addWall(conn, sc, wall(10, 10, 100, 10, wkWall, open = true)).get + let id = addWall(conn, sc, wall(10, 10, 100, 10, open = true)).get check wallById(sc, id).get.open == false check loadScene(conn).get.walls[0].open == false - test "update keeps the row's id and open flag unless the kind changes": + test "update keeps the row's id and open flag unless the door switch is cleared": let (conn, d) = freshScene() defer: close(conn) removeDir(d) var sc = loadScene(conn).get - let id = addWall(conn, sc, wall(10, 10, 100, 10, wkDoor)).get + let id = addWall(conn, sc, wall(10, 10, 100, 10, door = true)).get check setDoor(conn, sc, id, true) == waOk var w = wallById(sc, id).get w.a = (20.0, 20.0) check updateWall(conn, sc, w) == waOk check wallById(sc, id).get.open == true # untouched by update - # door -> wall closes it (a wall is never open) + # clearing the door switch closes it (a non-door stores no door settings) var back = wallById(sc, id).get - back.kind = wkWall + back.door = false check updateWall(conn, sc, back) == waOk check wallById(sc, id).get.open == false check loadScene(conn).get.walls[0].open == false @@ -298,7 +316,8 @@ suite "validation (DESIGN 6.1 `wall.*`)": let after = patched(before, WallPatch(b: some((300.0, 400.0)))) check after.a == before.a check after.b == (300.0, 400.0) - check after.kind == before.kind + check after.door == before.door + check after.thickness == before.thickness check after.flags.kind == JObject suite "lookup outcomes (main.nim's 6.5 mapping)": diff --git a/tools/details.test.mjs b/tools/details.test.mjs index 39448a4..97995d5 100644 --- a/tools/details.test.mjs +++ b/tools/details.test.mjs @@ -84,9 +84,8 @@ test('grow push and squeeze (5.6): pushed clear of a wall, or flagged squeezed w const gm = await gmConnect(s.origin, gmKey) const alice = await namedPlayer(s.origin, gm, 'Alice') // a 40 px corridor at x in [500, 540]: a token of r=15 fits, r=25 does not - const left = await gm.ws.request({ t: 'wall.add', scene: gm.sceneId, a: [500, 0], b: [500, 900], - kind: 'wall' }) - await gm.ws.request({ t: 'wall.add', scene: gm.sceneId, a: [540, 0], b: [540, 900], kind: 'wall' }) + const left = await gm.ws.request({ t: 'wall.add', scene: gm.sceneId, a: [500, 0], b: [500, 900] }) + await gm.ws.request({ t: 'wall.add', scene: gm.sceneId, a: [540, 0], b: [540, 900] }) // the token sits mid-corridor: r=15 fits between the walls, so it starts unlocked const pushee = await gm.ws.request({ t: 'token.create', scene: gm.sceneId, kind: 'pc', pos: [400, 400], descriptive_name: 'Alice', @@ -124,8 +123,7 @@ test('grow push and squeeze (5.6): pushed clear of a wall, or flagged squeezed w const free = await gm.ws.request({ t: 'token.create', scene: gm.sceneId, kind: 'pc', pos: [1000, 900], descriptive_name: 'Bob', actual_name: 'Bob', radius: 10 }) - await gm.ws.request({ t: 'wall.add', scene: gm.sceneId, a: [1010, 700], b: [1010, 1100], - kind: 'wall' }) + await gm.ws.request({ t: 'wall.add', scene: gm.sceneId, a: [1010, 700], b: [1010, 1100] }) const grown = await mutate(gm.ws, { t: 'token.resize', id: free.id, radius: 60 }) assert.equal(grown.ack.ok, true) const pushed = await grown.wait(m => m.t === 'token' && m.id === free.id && m.radius === 60) @@ -150,7 +148,7 @@ test('stuck from a wall and from a GM placement, cleared by the removal and by a // a wall added over the token gives it stuck(walls) (5.5 SET) const add = await mutate(gm.ws, { t: 'wall.add', scene: gm.sceneId, a: [990, 800], - b: [990, 1200], kind: 'wall' }) + b: [990, 1200] }) const wall = add.ack let frame = await add.wait(m => m.t === 'token' && m.id === tok.id && m.statuses.length > 0) assert.deepEqual(frame.statuses, [{ status: 'stuck', source: 'walls' }]) @@ -175,8 +173,7 @@ test('stuck from a wall and from a GM placement, cleared by the removal and by a assert.deepEqual(frameOf(gm.ws, tok.id).statuses, []) // a GM placement on a wall is stuck too (5.5 SET) - await gm.ws.request({ t: 'wall.add', scene: gm.sceneId, a: [990, 800], b: [990, 1200], - kind: 'wall' }) + await gm.ws.request({ t: 'wall.add', scene: gm.sceneId, a: [990, 800], b: [990, 1200] }) const placed = await gm.ws.request({ t: 'token.create', scene: gm.sceneId, kind: 'npc', pos: [990, 1000], descriptive_name: 'a guard', actual_name: 'Vex' }) diff --git a/tools/fault.test.mjs b/tools/fault.test.mjs index f258f81..a885c54 100644 --- a/tools/fault.test.mjs +++ b/tools/fault.test.mjs @@ -27,6 +27,7 @@ const FAULTS = { hidden: ['HIDDEN_TOKEN', 'NO_REMOVE'], gmOnly: ['GMONLY_TOKEN', 'NO_REMOVE'], walls: ['WALLDATA'], + wallHeight: ['WALLDATA'], withhold: ['WITHHELD'], otherOwner: ['OTHER_PLAYER'], otherVision: ['OTHER_PLAYER'], diff --git a/tools/leak.mjs b/tools/leak.mjs index c8fd074..2be6ffc 100644 --- a/tools/leak.mjs +++ b/tools/leak.mjs @@ -113,10 +113,10 @@ export async function runLeak({ origin, gmKey, stateDir, transcript, keepOpen = // --- the scene ------------------------------------------------------------------------------- // x = 500 is a wall with a door in the middle (y 400..700): the subject starts west of it. const wallsToAdd = [ - { a: [500, 0], b: [500, 400], kind: 'wall' }, - { a: [500, 400], b: [500, 700], kind: 'door', open: false }, - { a: [500, 700], b: [500, 1000], kind: 'wall' }, - { a: [1400, 400], b: [1400, 900], kind: 'wall' }, + { a: [500, 0], b: [500, 400] }, + { a: [500, 400], b: [500, 700], door: true, open: false }, + { a: [500, 700], b: [500, 1000] }, + { a: [1400, 400], b: [1400, 900] }, ] const wallIds = [] @@ -232,7 +232,7 @@ export async function runLeak({ origin, gmKey, stateDir, transcript, keepOpen = expectAck(await move(gm, ids.B, [420, 1500]), true) }) await group('GM adds a wall in the subject sight', async () => { - await addWall({ a: [400, 900], b: [900, 900], kind: 'wall' }) + await addWall({ a: [400, 900], b: [900, 900] }) }) await group('GM removes it again', async () => { const ack = await gm.request({ t: 'wall.remove', scene, id: wallIds[wallIds.length - 1] }) @@ -267,7 +267,7 @@ export async function runLeak({ origin, gmKey, stateDir, transcript, keepOpen = if (resized.ok !== true) throw new Error(`token.resize refused: ${JSON.stringify(resized)}`) }) await group('GM adds a wall over N2 (stuck, source walls)', async () => { - await addWall({ a: [700, 560], b: [700, 660], kind: 'wall' }) + await addWall({ a: [700, 560], b: [700, 660] }) }) await group('GM unsets the public prop of N2', async () => { const unset = await gm.request({ t: 'prop.unset', target: 'token', id: ids.N2, diff --git a/tools/leakcheck.nim b/tools/leakcheck.nim index 32d9143..071677a 100644 --- a/tools/leakcheck.nim +++ b/tools/leakcheck.nim @@ -36,7 +36,10 @@ const AllowedTypes = ["hello", "ack", "roster", "token", "token_gone", "vision", "explored", "character", "character_gone", "encountered"] BannedAlways = ["walls", "wall", "wall_gone", "a", "b", "open", "kind", "controller", "gm_only", - "flags", "radius_own", "extra"] + "flags", "radius_own", "extra", + # every wall field name (#54): geometry, switches, door settings, label + "thickness", "position", "height", "blocks_sight", "blocks_movement", "sight_dir", + "player_marker", "door", "secret", "locked", "label"] BannedToken = ["descriptive_name", "actual_name", "reveal_all", "revealed"] BannedCharacterTop = ["owner", "reveal_all", "revealed"] ## top-level only: `props.owner` is fine BannedEncountered = ["player", "character_id", "pos"] @@ -124,11 +127,11 @@ proc applyGmWalls(truth: var Truth, ids: var seq[int], m: JsonNode) = ids.setLen(0) for w in m["walls"]: truth.walls.add Wall(a: vec(w["a"]), b: vec(w["b"]), - door: w["kind"].getStr == "door", open: w["open"].getBool) + door: w["door"].getBool, open: w["open"].getBool) ids.add w["id"].getInt of "wall": let id = m["id"].getInt - let w = Wall(a: vec(m["a"]), b: vec(m["b"]), door: m["kind"].getStr == "door", + let w = Wall(a: vec(m["a"]), b: vec(m["b"]), door: m["door"].getBool, open: m["open"].getBool) var found = false for i in 0 ..< ids.len: diff --git a/tools/lib.mjs b/tools/lib.mjs index 6a17350..c7f7980 100644 --- a/tools/lib.mjs +++ b/tools/lib.mjs @@ -67,8 +67,8 @@ export function listeningSockets(port) { // Auth helpers (#17): sign-in, cookie/Ws clients, and a raw HTTP upgrade for status checks. // The proto query is required from slice 3 on (DESIGN 6.2: missing or non-integer -> HTTP 400). -// proto: null omits the query entirely (the 400 test). -export function wsUrl(origin, proto = 1) { +// proto: null omits the query entirely (the 400 test). The default is the build's proto (2, #54). +export function wsUrl(origin, proto = 2) { return origin.replace(/^http/, 'ws') + (proto === null ? '/ws' : `/ws?proto=${proto}`) } @@ -168,11 +168,11 @@ function wireOpen(ws, onOpen, onError) { // Raw HTTP upgrade attempt (node:net): lets a test read the status line before the 101. // originHeader: undefined = the server origin, null = omit the header, string = send it. -// proto: undefined = 1, null = omit the query parameter, else the value as given. +// proto: undefined = 2 (the build's proto), null = omit the query parameter, else as given. export async function rawUpgrade(origin, opts = {}) { const u = new URL(origin) const key = crypto.randomBytes(16).toString('base64') - const proto = opts.proto === undefined ? 1 : opts.proto + const proto = opts.proto === undefined ? 2 : opts.proto const path = proto === null ? '/ws' : `/ws?proto=${proto}` const lines = [`GET ${path} HTTP/1.1`, `Host: ${u.host}`, 'Upgrade: websocket', 'Connection: Upgrade', `Sec-WebSocket-Key: ${key}`, 'Sec-WebSocket-Version: 13'] @@ -280,7 +280,7 @@ function decodeFrames(buf) { export async function rawWs(origin, opts = {}) { const u = new URL(origin) - const proto = opts.proto === undefined ? 1 : opts.proto + const proto = opts.proto === undefined ? 2 : opts.proto const path = proto === null ? '/ws' : `/ws?proto=${proto}` const key = crypto.randomBytes(16).toString('base64') const lines = [`GET ${path} HTTP/1.1`, `Host: ${u.host}`, 'Upgrade: websocket', diff --git a/tools/logs.test.mjs b/tools/logs.test.mjs index 92f4123..35fa471 100644 --- a/tools/logs.test.mjs +++ b/tools/logs.test.mjs @@ -82,7 +82,7 @@ test('logs: no key, session cookie or session hash reaches the log', async () => assert.equal((await join(s.origin, wrongKey)).status, 401) const tile = await fetch(`${s.origin}/tiles/1/v1/0_0.png`) assert.equal(tile.status, 403) - const mismatch = await rawWs(s.origin, { cookie: a2.cookie, proto: 2 }) + const mismatch = await rawWs(s.origin, { cookie: a2.cookie, proto: 1 }) await mismatch.closed const g2 = await openAs(s.origin, gmKey1) g2.ws.sendText('this is not json') diff --git a/tools/persistence.test.mjs b/tools/persistence.test.mjs index e7132d7..c33e37c 100644 --- a/tools/persistence.test.mjs +++ b/tools/persistence.test.mjs @@ -9,6 +9,7 @@ import fs from 'node:fs' import { DatabaseSync } from 'node:sqlite' import { createPlayer, namePlayer, sleep } from './lib.mjs' import { gmKeyOf, makeStateDir, openAs, startServer, stopServer } from './withserver.mjs' +import { V7_DDL, V7_WALLS } from './schema7fixture.mjs' const CELL = 32 const cellOf = (x, y) => `${Math.floor(x / CELL)},${Math.floor(y / CELL)}` @@ -261,8 +262,7 @@ test('a wall removal\'s newly explored cells are persisted, even after the wall // A wall at x = 500 hides everything to the right of Alice (her circle reaches x = 600). // Endpoints stay off the exact 64-gon rays: a ray through a wall endpoint is the documented // boundary ambiguity of 5.4, not something this test is about. - const wall = await gm.ws.request({ t: 'wall.add', scene: gm.scene, a: [500, 50], b: [500, 4000], - kind: 'wall' }) + const wall = await gm.ws.request({ t: 'wall.add', scene: gm.scene, a: [500, 50], b: [500, 4000] }) assert.equal(wall.ok, true, JSON.stringify(wall)) const tok = await visionToken(gm, alice, [200, 200]) const p = await openAs(s.origin, alice.key) @@ -280,8 +280,7 @@ test('a wall removal\'s newly explored cells are persisted, even after the wall assert.ok(revealed.has(cellOf(590, 200)), 'removing the wall revealed and persisted the right side') // Put the wall back: the right side is out of sight again, so only the store can still have it. - assert.equal((await gm.ws.request({ t: 'wall.add', scene: gm.scene, a: [500, 50], b: [500, 4000], - kind: 'wall' })).ok, true) + assert.equal((await gm.ws.request({ t: 'wall.add', scene: gm.scene, a: [500, 50], b: [500, 4000] })).ok, true) await sleep(150) const afterReplace = await exploredSnapshot(s.origin, alice) assert.deepEqual(sorted(afterReplace), sorted(revealed)) @@ -457,55 +456,7 @@ test('migration: a schema-4 DB (fixture) migrates under the real binary to the l // empty props, a linked token with a hand-set height/eye_height, and two characters, one with a // hand-set height. Step 8 must rebuild `wall`, drop `kind`, add `marker_seen` and backfill only // the missing heights. -const V7_DDL = ` -CREATE TABLE schema_migration (version INTEGER PRIMARY KEY, name TEXT NOT NULL, applied_at TEXT NOT NULL); -CREATE TABLE meta (k TEXT PRIMARY KEY, v TEXT NOT NULL); -CREATE TABLE player (id INTEGER PRIMARY KEY, name TEXT UNIQUE, role TEXT NOT NULL CHECK (role IN ('gm', 'player')), colour TEXT NOT NULL, created_at TEXT NOT NULL); -CREATE UNIQUE INDEX player_single_gm ON player(role) WHERE role = 'gm'; -CREATE TABLE player_key (player_id INTEGER PRIMARY KEY REFERENCES player(id) ON DELETE CASCADE, secret TEXT NOT NULL, created_at TEXT NOT NULL); -CREATE TABLE session (id INTEGER PRIMARY KEY, player_id INTEGER NOT NULL REFERENCES player(id) ON DELETE CASCADE, token_hash TEXT NOT NULL UNIQUE, created_at TEXT NOT NULL, last_seen TEXT NOT NULL); -CREATE INDEX session_player ON session(player_id); -CREATE TABLE scene (id INTEGER PRIMARY KEY, name TEXT NOT NULL, w REAL NOT NULL, h REAL NOT NULL, tile_size INTEGER NOT NULL, cell INTEGER NOT NULL, grid_size REAL NOT NULL, vision_radius_default REAL NOT NULL, token_radius_default REAL NOT NULL, art_version INTEGER NOT NULL, active INTEGER NOT NULL DEFAULT 1, next_wall_id INTEGER NOT NULL DEFAULT 1, extra TEXT NOT NULL DEFAULT '{}'); -CREATE TABLE wall (scene_id INTEGER NOT NULL REFERENCES scene(id) ON DELETE CASCADE, id INTEGER NOT NULL, ax REAL NOT NULL, ay REAL NOT NULL, bx REAL NOT NULL, by REAL NOT NULL, kind TEXT NOT NULL CHECK (kind IN ('wall', 'door')), open INTEGER NOT NULL DEFAULT 0 CHECK (open IN (0, 1)), flags TEXT NOT NULL DEFAULT '{}', PRIMARY KEY (scene_id, id)); -CREATE TABLE entity (id TEXT PRIMARY KEY, scene_id INTEGER NOT NULL REFERENCES scene(id) ON DELETE CASCADE, kind TEXT NOT NULL, descriptive_name TEXT NOT NULL, actual_name TEXT NOT NULL, x REAL NOT NULL, y REAL NOT NULL, radius REAL, owner_player_id INTEGER REFERENCES player(id) ON DELETE SET NULL, gm_only INTEGER NOT NULL DEFAULT 0 CHECK (gm_only IN (0, 1)), vision_radius REAL, flags TEXT NOT NULL DEFAULT '{}', created_at TEXT NOT NULL, props_public TEXT NOT NULL DEFAULT '{}', props_owner TEXT NOT NULL DEFAULT '{}', props_gm TEXT NOT NULL DEFAULT '{}', character_id TEXT REFERENCES character(id), reveal_all INTEGER NOT NULL DEFAULT 0 CHECK (reveal_all IN (0, 1))); -CREATE TABLE explored_chunk (player_id INTEGER NOT NULL REFERENCES player(id) ON DELETE CASCADE, scene_id INTEGER NOT NULL REFERENCES scene(id) ON DELETE CASCADE, cx INTEGER NOT NULL, cy INTEGER NOT NULL, bits BLOB NOT NULL CHECK (length(bits) = 512), PRIMARY KEY (player_id, scene_id, cx, cy)); -CREATE TABLE entity_status (entity_id TEXT NOT NULL REFERENCES entity(id) ON DELETE CASCADE, status TEXT NOT NULL CHECK (status IN ('stuck', 'squeezed')), source TEXT NOT NULL CHECK (source IN ('walls', 'GM')), PRIMARY KEY (entity_id, status, source)); -CREATE TABLE character (id TEXT PRIMARY KEY, owner_player_id INTEGER NOT NULL REFERENCES player(id), descriptive_name TEXT NOT NULL, actual_name TEXT NOT NULL, reveal_all INTEGER NOT NULL DEFAULT 0 CHECK (reveal_all IN (0, 1)), props_public TEXT NOT NULL DEFAULT '{}', props_owner TEXT NOT NULL DEFAULT '{}', props_gm TEXT NOT NULL DEFAULT '{}', created_at TEXT NOT NULL); -CREATE INDEX character_owner ON character(owner_player_id); -CREATE TABLE name_reveal (player_id INTEGER NOT NULL REFERENCES player(id) ON DELETE CASCADE, subject_id TEXT NOT NULL, created_at TEXT NOT NULL, PRIMARY KEY (player_id, subject_id)); -CREATE TABLE encountered (player_id INTEGER NOT NULL REFERENCES player(id) ON DELETE CASCADE, entity_id TEXT NOT NULL, character_id TEXT, descriptive_name TEXT NOT NULL, actual_name TEXT, created_at TEXT NOT NULL, PRIMARY KEY (player_id, entity_id)); -CREATE INDEX encountered_character ON encountered(character_id); -INSERT INTO schema_migration VALUES (1, 'meta', '2026-11-15T00:00:00Z'), (2, 'auth', '2026-11-15T00:00:00Z'), (3, 'world', '2026-11-15T00:00:00Z'), (4, 'tokens', '2026-11-15T00:00:00Z'), (5, 'explored', '2026-11-15T00:00:00Z'), (6, 'token details', '2026-11-15T00:00:00Z'), (7, 'characters', '2026-11-15T00:00:00Z'); -INSERT INTO scene (id, name, w, h, tile_size, cell, grid_size, vision_radius_default, token_radius_default, art_version, active, next_wall_id, extra) VALUES (1, 'Scene', 4096, 4096, 32, 32, 0, 400, 20, 1, 1, 5, '{}'); -INSERT INTO player (id, name, role, colour, created_at) VALUES (1, 'GM', 'gm', '#6b7280', '2026-11-15T00:00:00Z'); -INSERT INTO player (id, name, role, colour, created_at) VALUES (2, 'Alice', 'player', '#2563eb', '2026-11-15T00:00:00Z'); -INSERT INTO player_key (player_id, secret, created_at) VALUES (2, 'ALIC-ALIC-ALIC-ALIC-ALIC', '2026-11-15T00:00:00Z'); -INSERT INTO wall (scene_id, id, ax, ay, bx, by, kind, open, flags) VALUES - (1, 1, 0, 0, 4096, 0, 'wall', 0, '{"note":"north"}'), - (1, 2, 10, 10, 100, 10, 'wall', 1, '{}'), - (1, 3, 100, 100, 400, 100, 'door', 1, '{"a":1}'), - (1, 4, 500, 500, 900, 500, 'door', 0, '{}'); -INSERT INTO character (id, owner_player_id, descriptive_name, actual_name, created_at, props_gm) VALUES - ('char000000001', 1, 'Alice', 'Alice', '2026-11-15T00:00:00Z', '{}'), - ('char000000002', 1, 'Bob', 'Bob', '2026-11-15T00:00:00Z', '{"height":1.5}'); -INSERT INTO entity (id, scene_id, kind, descriptive_name, actual_name, x, y, owner_player_id, flags, created_at, props_gm, character_id) VALUES - ('tok000000001', 1, 'pc', 'a wanderer', 'Wanderer', 400, 400, 2, '{"vision": true}', '2026-11-15T00:00:00Z', '{}', NULL), - ('tok000000002', 1, 'pc', '', '', 800, 800, 2, '{"vision": true}', '2026-11-15T00:00:00Z', '{"height":2.5,"eye_height":2.0}', 'char000000001'); -PRAGMA user_version = 7; -` -const V7_WALLS = [ - { id: 1, thickness: 0, position: 'center', blocks_sight: 1, blocks_movement: 1, sight_dir: 'both', - player_marker: 0, door: 0, open: 0, secret: 0, locked: 0, height: null, label: null, - flags: '{"note":"north"}' }, - { id: 2, thickness: 0, position: 'center', blocks_sight: 1, blocks_movement: 1, sight_dir: 'both', - player_marker: 0, door: 0, open: 0, secret: 0, locked: 0, height: null, label: null, flags: '{}' }, - { id: 3, thickness: 0, position: 'center', blocks_sight: 1, blocks_movement: 1, sight_dir: 'both', - player_marker: 0, door: 1, open: 1, secret: 0, locked: 0, height: null, label: null, - flags: '{"a":1}' }, - { id: 4, thickness: 0, position: 'center', blocks_sight: 1, blocks_movement: 1, sight_dir: 'both', - player_marker: 0, door: 1, open: 0, secret: 0, locked: 0, height: null, label: null, flags: '{}' }, -] function readWallRows(db) { return db.prepare(`SELECT id, thickness, position, blocks_sight, blocks_movement, sight_dir, diff --git a/tools/probing.test.mjs b/tools/probing.test.mjs index 6bcd640..4dbea42 100644 --- a/tools/probing.test.mjs +++ b/tools/probing.test.mjs @@ -107,16 +107,16 @@ async function probe(ctx) { } const farA = [ - { a: [3000, 1000], b: [3000, 3000], kind: 'wall' }, - { a: [3200, 1200], b: [3400, 2600], kind: 'door', open: false }, + { a: [3000, 1000], b: [3000, 3000] }, + { a: [3200, 1200], b: [3400, 2600], door: true, open: false }, ] const farB = [ - { a: [3050, 2400], b: [3600, 2400], kind: 'wall' }, - { a: [3100, 1500], b: [3100, 1900], kind: 'door', open: true }, - { a: [3800, 1000], b: [3900, 3900], kind: 'wall' }, + { a: [3050, 2400], b: [3600, 2400] }, + { a: [3100, 1500], b: [3100, 1900], door: true, open: true }, + { a: [3800, 1000], b: [3900, 3900] }, ] // Inside the bound relative to START: 150 px east. -const nearExtra = [{ a: [1150, 1900], b: [1150, 2100], kind: 'wall' }] +const nearExtra = [{ a: [1150, 1900], b: [1150, 2100] }] test('probing over WS: walls beyond cap + radius change no reply', async () => { fs.mkdirSync(path.join(projectRoot, 'results'), { recursive: true }) diff --git a/tools/protocol.test.mjs b/tools/protocol.test.mjs index 185ba48..d947fc8 100644 --- a/tools/protocol.test.mjs +++ b/tools/protocol.test.mjs @@ -24,7 +24,7 @@ test('hello is the first frame; n counts server frames per connection, never glo const hello = await gm.ws.waitText('hello') assert.deepEqual(gm.ws.messages[0], hello, 'hello is the first frame') assert.equal(hello.n, 1) // starts at 1 on the connection's first frame - assert.equal(hello.proto, 1) // M3 ships proto 1 (DESIGN 6.2) + assert.equal(hello.proto, 2) // proto 2 is the wall-model build (DESIGN 6.2) assert.equal(hello.role, 'gm') assert.deepEqual(hello.me, { id: 1, name: 'GM' }) // 6.3: the roster, then the GM wall snapshot (slice 4, DESIGN 6.1 `walls`) @@ -78,9 +78,9 @@ test('proto: absent or non-integer is HTTP 400; a different proto is 101 + closi assert.equal((await rawUpgrade(s.origin, { cookie, proto: null })).status, 400) assert.equal((await rawUpgrade(s.origin, { cookie, proto: 'x' })).status, 400) assert.equal((await rawUpgrade(s.origin, { cookie, proto: '1.0' })).status, 400) - assert.equal((await rawUpgrade(s.origin, { cookie, proto: 1 })).status, 101) + assert.equal((await rawUpgrade(s.origin, { cookie, proto: 2 })).status, 101) - const raw = await rawWs(s.origin, { cookie, proto: 2 }) + const raw = await rawWs(s.origin, { cookie, proto: 1 }) const closing = await raw.waitText('closing') assert.equal(closing.reason, 'proto-mismatch') assert.equal(closing.code, 4003) diff --git a/tools/restart.test.mjs b/tools/restart.test.mjs index 864f282..22519c1 100644 --- a/tools/restart.test.mjs +++ b/tools/restart.test.mjs @@ -50,9 +50,9 @@ async function buildWorld(origin, gmKey) { await createPlayer(gm.ws) // A wall and a door; the door is opened (door.set is its own write path). const wall = await gm.ws.request({ t: 'wall.add', scene: gm.sceneId, a: [700, 0], - b: [700, 900], kind: 'wall' }) + b: [700, 900] }) const door = await gm.ws.request({ t: 'wall.add', scene: gm.sceneId, a: [700, 1000], - b: [700, 1400], kind: 'door' }) + b: [700, 1400], door: true }) assert.equal(wall.ok, true, JSON.stringify(wall)) assert.equal(door.ok, true, JSON.stringify(door)) assert.equal((await gm.ws.request({ t: 'door.set', scene: gm.sceneId, id: door.id, diff --git a/tools/scene.test.mjs b/tools/scene.test.mjs index a32e4c8..81072bc 100644 --- a/tools/scene.test.mjs +++ b/tools/scene.test.mjs @@ -153,7 +153,7 @@ test('token_radius_default: a grow pushes default-radius tokens, an own radius n const gm = await gmConnect(s.origin, gmKey) // A wall 40 px above the token: clear at radius 20, overlapping at 50. assert.equal((await gm.ws.request({ t: 'wall.add', scene: gm.sceneId, a: [0, 440], - b: [1000, 440], kind: 'wall' })).ok, true) + b: [1000, 440] })).ok, true) const def = await gm.ws.request({ t: 'token.create', scene: gm.sceneId, kind: 'npc', pos: [400, 400], descriptive_name: 'a goblin', actual_name: 'Grib' }) @@ -191,9 +191,9 @@ test('token_radius_default: a grow with no room on either side squeezes', async const gm = await gmConnect(s.origin, gmKey) // A corridor 60 px wide: a radius-20 token fits centred, a radius-40 token cannot fit at all. assert.equal((await gm.ws.request({ t: 'wall.add', scene: gm.sceneId, a: [1000, 900], - b: [1000, 1100], kind: 'wall' })).ok, true) + b: [1000, 1100] })).ok, true) assert.equal((await gm.ws.request({ t: 'wall.add', scene: gm.sceneId, a: [1060, 900], - b: [1060, 1100], kind: 'wall' })).ok, true) + b: [1060, 1100] })).ok, true) const tok = await gm.ws.request({ t: 'token.create', scene: gm.sceneId, kind: 'npc', pos: [1030, 1000], descriptive_name: 'a rat', actual_name: 'Squeak' }) diff --git a/tools/schema7fixture.mjs b/tools/schema7fixture.mjs new file mode 100644 index 0000000..edad120 --- /dev/null +++ b/tools/schema7fixture.mjs @@ -0,0 +1,53 @@ +// The schema-7 fixture of the wall-record build (#54) and the migration tests (#53): a DB exactly +// as the schema-7 build (#23) left it. Shared by tools/persistence.test.mjs (migration mapping) and +// tools/wallbehaviour.test.mjs (behaviour preservation: migrated scene vs the same walls authored +// through the proto-2 wall intents). Test fixture only; never imported by the server. +export const V7_DDL = ` +CREATE TABLE schema_migration (version INTEGER PRIMARY KEY, name TEXT NOT NULL, applied_at TEXT NOT NULL); +CREATE TABLE meta (k TEXT PRIMARY KEY, v TEXT NOT NULL); +CREATE TABLE player (id INTEGER PRIMARY KEY, name TEXT UNIQUE, role TEXT NOT NULL CHECK (role IN ('gm', 'player')), colour TEXT NOT NULL, created_at TEXT NOT NULL); +CREATE UNIQUE INDEX player_single_gm ON player(role) WHERE role = 'gm'; +CREATE TABLE player_key (player_id INTEGER PRIMARY KEY REFERENCES player(id) ON DELETE CASCADE, secret TEXT NOT NULL, created_at TEXT NOT NULL); +CREATE TABLE session (id INTEGER PRIMARY KEY, player_id INTEGER NOT NULL REFERENCES player(id) ON DELETE CASCADE, token_hash TEXT NOT NULL UNIQUE, created_at TEXT NOT NULL, last_seen TEXT NOT NULL); +CREATE INDEX session_player ON session(player_id); +CREATE TABLE scene (id INTEGER PRIMARY KEY, name TEXT NOT NULL, w REAL NOT NULL, h REAL NOT NULL, tile_size INTEGER NOT NULL, cell INTEGER NOT NULL, grid_size REAL NOT NULL, vision_radius_default REAL NOT NULL, token_radius_default REAL NOT NULL, art_version INTEGER NOT NULL, active INTEGER NOT NULL DEFAULT 1, next_wall_id INTEGER NOT NULL DEFAULT 1, extra TEXT NOT NULL DEFAULT '{}'); +CREATE TABLE wall (scene_id INTEGER NOT NULL REFERENCES scene(id) ON DELETE CASCADE, id INTEGER NOT NULL, ax REAL NOT NULL, ay REAL NOT NULL, bx REAL NOT NULL, by REAL NOT NULL, kind TEXT NOT NULL CHECK (kind IN ('wall', 'door')), open INTEGER NOT NULL DEFAULT 0 CHECK (open IN (0, 1)), flags TEXT NOT NULL DEFAULT '{}', PRIMARY KEY (scene_id, id)); +CREATE TABLE entity (id TEXT PRIMARY KEY, scene_id INTEGER NOT NULL REFERENCES scene(id) ON DELETE CASCADE, kind TEXT NOT NULL, descriptive_name TEXT NOT NULL, actual_name TEXT NOT NULL, x REAL NOT NULL, y REAL NOT NULL, radius REAL, owner_player_id INTEGER REFERENCES player(id) ON DELETE SET NULL, gm_only INTEGER NOT NULL DEFAULT 0 CHECK (gm_only IN (0, 1)), vision_radius REAL, flags TEXT NOT NULL DEFAULT '{}', created_at TEXT NOT NULL, props_public TEXT NOT NULL DEFAULT '{}', props_owner TEXT NOT NULL DEFAULT '{}', props_gm TEXT NOT NULL DEFAULT '{}', character_id TEXT REFERENCES character(id), reveal_all INTEGER NOT NULL DEFAULT 0 CHECK (reveal_all IN (0, 1))); +CREATE TABLE explored_chunk (player_id INTEGER NOT NULL REFERENCES player(id) ON DELETE CASCADE, scene_id INTEGER NOT NULL REFERENCES scene(id) ON DELETE CASCADE, cx INTEGER NOT NULL, cy INTEGER NOT NULL, bits BLOB NOT NULL CHECK (length(bits) = 512), PRIMARY KEY (player_id, scene_id, cx, cy)); +CREATE TABLE entity_status (entity_id TEXT NOT NULL REFERENCES entity(id) ON DELETE CASCADE, status TEXT NOT NULL CHECK (status IN ('stuck', 'squeezed')), source TEXT NOT NULL CHECK (source IN ('walls', 'GM')), PRIMARY KEY (entity_id, status, source)); +CREATE TABLE character (id TEXT PRIMARY KEY, owner_player_id INTEGER NOT NULL REFERENCES player(id), descriptive_name TEXT NOT NULL, actual_name TEXT NOT NULL, reveal_all INTEGER NOT NULL DEFAULT 0 CHECK (reveal_all IN (0, 1)), props_public TEXT NOT NULL DEFAULT '{}', props_owner TEXT NOT NULL DEFAULT '{}', props_gm TEXT NOT NULL DEFAULT '{}', created_at TEXT NOT NULL); +CREATE INDEX character_owner ON character(owner_player_id); +CREATE TABLE name_reveal (player_id INTEGER NOT NULL REFERENCES player(id) ON DELETE CASCADE, subject_id TEXT NOT NULL, created_at TEXT NOT NULL, PRIMARY KEY (player_id, subject_id)); +CREATE TABLE encountered (player_id INTEGER NOT NULL REFERENCES player(id) ON DELETE CASCADE, entity_id TEXT NOT NULL, character_id TEXT, descriptive_name TEXT NOT NULL, actual_name TEXT, created_at TEXT NOT NULL, PRIMARY KEY (player_id, entity_id)); +CREATE INDEX encountered_character ON encountered(character_id); +INSERT INTO schema_migration VALUES (1, 'meta', '2026-11-15T00:00:00Z'), (2, 'auth', '2026-11-15T00:00:00Z'), (3, 'world', '2026-11-15T00:00:00Z'), (4, 'tokens', '2026-11-15T00:00:00Z'), (5, 'explored', '2026-11-15T00:00:00Z'), (6, 'token details', '2026-11-15T00:00:00Z'), (7, 'characters', '2026-11-15T00:00:00Z'); +INSERT INTO scene (id, name, w, h, tile_size, cell, grid_size, vision_radius_default, token_radius_default, art_version, active, next_wall_id, extra) VALUES (1, 'Scene', 4096, 4096, 32, 32, 0, 400, 20, 1, 1, 5, '{}'); +INSERT INTO player (id, name, role, colour, created_at) VALUES (1, 'GM', 'gm', '#6b7280', '2026-11-15T00:00:00Z'); +INSERT INTO player (id, name, role, colour, created_at) VALUES (2, 'Alice', 'player', '#2563eb', '2026-11-15T00:00:00Z'); +INSERT INTO player_key (player_id, secret, created_at) VALUES (2, 'ALIC-ALIC-ALIC-ALIC-ALIC', '2026-11-15T00:00:00Z'); +INSERT INTO wall (scene_id, id, ax, ay, bx, by, kind, open, flags) VALUES + (1, 1, 0, 0, 4096, 0, 'wall', 0, '{"note":"north"}'), + (1, 2, 10, 10, 100, 10, 'wall', 1, '{}'), + (1, 3, 100, 100, 400, 100, 'door', 1, '{"a":1}'), + (1, 4, 500, 500, 900, 500, 'door', 0, '{}'); +INSERT INTO character (id, owner_player_id, descriptive_name, actual_name, created_at, props_gm) VALUES + ('char000000001', 1, 'Alice', 'Alice', '2026-11-15T00:00:00Z', '{}'), + ('char000000002', 1, 'Bob', 'Bob', '2026-11-15T00:00:00Z', '{"height":1.5}'); +INSERT INTO entity (id, scene_id, kind, descriptive_name, actual_name, x, y, owner_player_id, flags, created_at, props_gm, character_id) VALUES + ('tok000000001', 1, 'pc', 'a wanderer', 'Wanderer', 400, 400, 2, '{"vision": true}', '2026-11-15T00:00:00Z', '{}', NULL), + ('tok000000002', 1, 'pc', '', '', 800, 800, 2, '{"vision": true}', '2026-11-15T00:00:00Z', '{"height":2.5,"eye_height":2.0}', 'char000000001'); +PRAGMA user_version = 7; +` + +export const V7_WALLS = [ + { id: 1, thickness: 0, position: 'center', blocks_sight: 1, blocks_movement: 1, sight_dir: 'both', + player_marker: 0, door: 0, open: 0, secret: 0, locked: 0, height: null, label: null, + flags: '{"note":"north"}' }, + { id: 2, thickness: 0, position: 'center', blocks_sight: 1, blocks_movement: 1, sight_dir: 'both', + player_marker: 0, door: 0, open: 0, secret: 0, locked: 0, height: null, label: null, flags: '{}' }, + { id: 3, thickness: 0, position: 'center', blocks_sight: 1, blocks_movement: 1, sight_dir: 'both', + player_marker: 0, door: 1, open: 1, secret: 0, locked: 0, height: null, label: null, + flags: '{"a":1}' }, + { id: 4, thickness: 0, position: 'center', blocks_sight: 1, blocks_movement: 1, sight_dir: 'both', + player_marker: 0, door: 1, open: 0, secret: 0, locked: 0, height: null, label: null, flags: '{}' }, +] diff --git a/tools/tiles.test.mjs b/tools/tiles.test.mjs index 1496f93..b54e711 100644 --- a/tools/tiles.test.mjs +++ b/tools/tiles.test.mjs @@ -60,7 +60,7 @@ async function sceneWithVision(s, gmKey, ngx) { const gm = await gmConnect(ngx.origin, gmKey) const player = await createPlayer(gm.ws) await namePlayer(ngx.origin, player.key, 'Alice') - const wall = await addWall(gm, { a: [400, 100], b: [400, 700], kind: 'wall' }) + const wall = await addWall(gm, { a: [400, 100], b: [400, 700] }) const created = await gm.ws.request({ t: 'token.create', scene: gm.scene, kind: 'pc', pos: [300, 300], flags: { vision: true }, vision_radius: 400, controller: player.id, @@ -112,8 +112,10 @@ function segGap(p, q, a, b) { } function blockingWalls(wallsFrame) { + // A wall blocks sight unless it is an open door (today's rule; the raw switches gain their + // behaviour in the window/one-way rounds, #57/#58). return wallsFrame.walls - .filter(w => w.kind === 'wall' || w.open === false) + .filter(w => !(w.door && w.open)) .map(w => ({ a: { x: w.a[0], y: w.a[1] }, b: { x: w.b[0], y: w.b[1] } })) } @@ -414,7 +416,7 @@ test('concurrent scene edits and tile requests answer whole tiles, never a mixtu assert.equal((await ctx.gm.ws.request({ t: 'scene.set', scene: scene.id, name: `Cave ${i}` })).ok, true) const w = await ctx.gm.ws.request({ t: 'wall.add', scene: scene.id, - a: [380, 200], b: [380, 420], kind: 'wall' }) + a: [380, 200], b: [380, 420] }) assert.equal(w.ok, true, JSON.stringify(w)) assert.equal((await ctx.gm.ws.request({ t: 'wall.remove', scene: scene.id, id: w.id })).ok, true) diff --git a/tools/tokens.test.mjs b/tools/tokens.test.mjs index ca323ba..908d0e9 100644 --- a/tools/tokens.test.mjs +++ b/tools/tokens.test.mjs @@ -319,7 +319,7 @@ test('door closing pushes an overlapped token aside (5.5), and the push is a nor const gm = await gmConnect(s.origin, gmKey) const alice = await namedPlayer(s.origin, gm, 'Alice') const door = await gm.ws.request({ t: 'wall.add', scene: gm.scene, a: [500, 400], b: [500, 700], - kind: 'door' }) + door: true }) const tok = await gm.ws.request({ t: 'token.create', scene: gm.scene, kind: 'pc', pos: [300, 550], descriptive_name: 'Alice', actual_name: 'Alice', controller: alice.id, diff --git a/tools/wallbehaviour.test.mjs b/tools/wallbehaviour.test.mjs new file mode 100644 index 0000000..05c8923 --- /dev/null +++ b/tools/wallbehaviour.test.mjs @@ -0,0 +1,187 @@ +// Behaviour preservation for the proto-2 wall record (#54, TESTING 10.3 "Wall fields, storage and +// migration"). One real server migrates the shared schema-7 fixture and keeps its legacy walls; a +// second server migrates the identical fixture and rebuilds the *same* walls through the proto-2 +// `wall.add` raw-switch path before any player connects. The same script then runs against both, +// and each player's complete frame sequence (including every ack/nack) and the per-tile HTTP status +// sweep must be byte-identical after canonicalisation. No normalisation: token ids, player ids and +// the per-connection `n` are identical because both runs start from the same fixture. +import test from 'node:test' +import assert from 'node:assert/strict' +import fs from 'node:fs' +import { DatabaseSync } from 'node:sqlite' +import { baseUrl, freePort, refuseLivePort } from './lib.mjs' +import { gmKeyOf, makeStateDir, openAs, startServer, stopServer } from './withserver.mjs' +import { startTestNginx, stopTestNginx } from './nginx.mjs' +import { writeTileGrid } from './tilefixture.mjs' +import { V7_DDL } from './schema7fixture.mjs' + +const ALICE = 'ALIC-ALIC-ALIC-ALIC-ALIC' + +// The four walls the schema-7 fixture holds, as the proto-2 raw-switch create spells them. +const AUTHORED_WALLS = [ + { a: [0, 0], b: [4096, 0], flags: { note: 'north' } }, + { a: [10, 10], b: [100, 10] }, + { a: [100, 100], b: [400, 100], door: true, open: true, flags: { a: 1 } }, + { a: [500, 500], b: [900, 500], door: true }, +] + +const canonical = value => { + if (Array.isArray(value)) return value.map(canonical) + if (value && typeof value === 'object') { + return Object.fromEntries(Object.keys(value).sort().map(k => [k, canonical(value[k])])) + } + return value +} + +function seededStateDir() { + const stateDir = makeStateDir() + const db = new DatabaseSync(`${stateDir}/state.db`) + try { db.exec(V7_DDL) } finally { db.close() } + return stateDir +} + +async function stack(stateDir) { + const gmKey = gmKeyOf(stateDir) + const nginxPort = await freePort() + refuseLivePort(nginxPort) + const server = await startServer({ stateDir, publicOrigin: baseUrl(nginxPort) }) + const nginx = await startTestNginx({ backendPort: server.port, stateDir, port: nginxPort }) + return { stateDir, gmKey, server, nginx, origin: nginx.origin } +} + +// Rebuild the migrated scene's walls through the wire, before any player connects. +async function authorWalls(gm, scene) { + const snap = await gm.ws.waitText('walls') + for (const w of snap.walls) { + assert.equal((await gm.ws.request({ t: 'wall.remove', scene, id: w.id })).ok, true) + } + for (const wall of AUTHORED_WALLS) { + const ack = await gm.ws.request({ t: 'wall.add', scene, ...wall }) + assert.equal(ack.ok, true, JSON.stringify(ack)) + await gm.ws.waitFor(m => m.t === 'wall' && m.id === ack.id) + } +} + +// The wall whose drawn segment is the given one, however its id was assigned in this run. +function wallBySegment(gm, a, b) { + const from = gm.ws.messages.filter(m => m.t === 'wall' && m.a[0] === a[0] && m.a[1] === a[1] && + m.b[0] === b[0] && m.b[1] === b[1]) + if (from.length > 0) return from[from.length - 1] + const snap = gm.ws.messages.filter(m => m.t === 'walls').pop() + const hit = snap.walls.find(w => w.a[0] === a[0] && w.a[1] === a[1] && + w.b[0] === b[0] && w.b[1] === b[1]) + assert.ok(hit, `no wall from ${a} to ${b}`) + return hit +} + +const TOKEN = 'tok000000001' + +async function position(gm, x, y) { + const before = gm.ws.messages.length + const ack = await gm.ws.request({ t: 'token.move', id: TOKEN, pos: [x, y] }) + assert.equal(ack.ok, true, JSON.stringify(ack)) + await gm.ws.waitFor((m, i) => i >= before && m.t === 'token' && m.id === TOKEN && + m.pos[0] === x && m.pos[1] === y) +} + +// One scripted sequence, identical in both stacks except for how the migrated walls got there. +async function runScript(ctx) { + const gm = await openAs(ctx.origin, ctx.gmKey) + await gm.ws.waitText('hello') + const scene = (await gm.ws.waitText('walls')).scene + if (ctx.author) await authorWalls(gm, scene) + + const door = wallBySegment(gm, [500, 500], [900, 500]) + assert.equal(door.kind, 'door') + + // The player connects only after the wall set exists in both runs, so the compared sequence starts + // from the same resync. + const player = await openAs(ctx.origin, ALICE) + await player.ws.waitText('hello') + await player.ws.waitFor(m => m.t === 'explored' && m.full === true) + + // Start 20 px above the closed door, then attempt to cross it: the uniform move nack (5.5). + await position(gm, 600, 480) + let ack = await player.ws.request({ t: 'token.move', id: TOKEN, pos: [600, 520] }) + assert.equal(ack.ok, false) + assert.deepEqual(ack.pos, [600, 480]) + ack = await player.ws.request({ t: 'token.move', id: TOKEN, pos: [600, 440] }) + assert.equal(ack.ok, true) + await player.ws.waitFor(m => m.t === 'token' && m.id === TOKEN && m.pos[1] === 440) + + // Open the door: the way is clear and the player crosses. + assert.equal((await gm.ws.request({ t: 'door.set', scene, id: door.id, open: true })).ok, true) + await gm.ws.waitFor(m => m.t === 'wall' && m.id === door.id && m.open === true) + await position(player, 600, 520) + assert.equal((await player.ws.request({ t: 'token.move', id: TOKEN, pos: [600, 440] })).ok, true) + + // Move clear, close the door, and the same crossing is refused again. + await position(gm, 600, 560) + assert.equal((await gm.ws.request({ t: 'door.set', scene, id: door.id, open: false })).ok, true) + await gm.ws.waitFor(m => m.t === 'wall' && m.id === door.id && m.open === false) + ack = await player.ws.request({ t: 'token.move', id: TOKEN, pos: [600, 480] }) + assert.equal(ack.ok, false) + // Two refusals of different shapes: over the step cap, and out of bounds. + ack = await player.ws.request({ t: 'token.move', id: TOKEN, pos: [2000, 560] }) + assert.equal(ack.ok, false) + assert.deepEqual(ack.pos, [600, 560]) + ack = await player.ws.request({ t: 'token.move', id: TOKEN, pos: [-10, 560] }) + assert.equal(ack.ok, false) + + await new Promise(r => setTimeout(r, 80)) + const frames = player.ws.messages.map(canonical) + const cookie = player.cookie + player.ws.close(); gm.ws.close() + await player.ws.closed + return { scene, frames, cookie } +} + +// Every tile of the checked rectangle, as a status string; the oracle is the server's own explored +// gate in both runs, so any difference is a real behaviour difference. +async function tileStatuses(ctx, scene, cookie) { + const statuses = [] + for (let y = 0; y <= 31; y++) { + for (let x = 0; x <= 31; x++) { + const r = await fetch(`${ctx.origin}/tiles/${scene}/v1/${x}_${y}.png`, + { headers: { Cookie: cookie } }) + statuses.push(`${x},${y}:${r.status}`) + await r.arrayBuffer() + } + } + return statuses +} + +test('behaviour preservation: a migrated schema-7 scene and the same scene authored via raw switches are byte-identical to a player', async () => { + const migratedDir = seededStateDir() + const authoredDir = seededStateDir() + let migrated + let authored + try { + migrated = await stack(migratedDir) + authored = await stack(authoredDir) + // Fixture tiles for both stacks: every tile the gate may allow has bytes behind the alias. + for (const dir of [migratedDir, authoredDir]) { + writeTileGrid(dir, { scene: 1, artVersion: 1, size: 32, x0: 0, x1: 31, y0: 0, y1: 31 }) + } + + const a = await runScript({ ...migrated, author: false }) + const b = await runScript({ ...authored, author: true }) + + assert.ok(a.frames.length > 20, 'the script produced real coverage') + assert.deepEqual(b.frames, a.frames, + 'the migrated scene and the same scene authored through wall.add must give identical player frames') + + const ta = await tileStatuses(migrated, a.scene, a.cookie) + const tb = await tileStatuses(authored, b.scene, b.cookie) + assert.deepEqual(tb, ta, 'per-tile statuses must be identical between the two scenes') + assert.ok(ta.some(s => s.endsWith(':200')), 'the sweep allowed some tiles') + assert.ok(ta.some(s => s.endsWith(':403')), 'the sweep refused some tiles') + } finally { + await stopTestNginx(authored?.nginx) + await stopTestNginx(migrated?.nginx) + await stopServer(authored?.server) + await stopServer(migrated?.server) + fs.rmSync(migratedDir, { recursive: true, force: true }) + fs.rmSync(authoredDir, { recursive: true, force: true }) + } +}) diff --git a/tools/walls.test.mjs b/tools/walls.test.mjs index 7d83293..4bde49e 100644 --- a/tools/walls.test.mjs +++ b/tools/walls.test.mjs @@ -1,15 +1,14 @@ -// M3 slice 4 (#19): walls and doors. Black-box through the real binary (withserver): the GM -// `walls` snapshot, wall.add/wall.update/wall.remove and door.set with their 6.5 acks and GM-only -// effects, the per-scene never-reused wall ids, the 6.1 validation table, "no wall data reaches a -// player" and a restart that leaves walls (and door state) identical (DESIGN 3.1, 6.1, 8, 10.1). +// M3 slice 4 (#19) walls and doors, rewritten for the proto-2 typed wall record (#54). Black-box +// through the real binary (withserver): the GM `walls` snapshot, wall.add/wall.update/wall.remove +// and door.set with their 6.5 acks and GM-only effects, the typed geometry and raw switches, the +// derived shape label, the per-scene never-reused wall ids, "no wall data reaches a player" and a +// restart that leaves walls (and door state) identical (DESIGN 3.1, 5.8, 6.1, 8, 10.1). import test from 'node:test' import assert from 'node:assert/strict' import fs from 'node:fs' import { gmKeyOf, makeStateDir, startServer, stopServer, withGmServer, openAs } from './withserver.mjs' import { createPlayer, sleep } from './lib.mjs' -const stripN = msg => { const { n, ...rest } = msg; return rest } - // The GM's first connection: hello, then the wall snapshot (DESIGN 6.1 `walls`, 6.3). async function gmConnect(origin, gmKey) { const conn = await openAs(origin, gmKey) @@ -28,47 +27,85 @@ async function wallEffect(ws, pred, timeoutMs = 5000) { return await ws.waitFor(m => (m.t === 'wall' || m.t === 'wall_gone') && pred(m), timeoutMs) } -test('wall.add: one ack with the id, then the wall to the GM with the 6.1 shape', async () => { +// The full proto-2 GM frame every wall must carry (5.8 + 6.1). +const WALL_FIELDS = ['id', 'a', 'b', 'thickness', 'position', 'height', 'kind', 'blocks_sight', + 'blocks_movement', 'sight_dir', 'player_marker', 'door', 'open', 'secret', 'locked', 'label', + 'flags'] + +function assertTypedWall(wall) { + // A `wall` frame also carries `t`/`scene`; a `walls` entry only the wall fields plus `n` on send. + for (const key of WALL_FIELDS) assert.ok(key in wall, `wall frame is missing ${key}`) +} + +test('wall.add: the typed record, raw-switch defaults and the derived kind', async () => { await withGmServer(async (s, gmKey) => { const gm = await gmConnect(s.origin, gmKey) assert.equal(gm.walls.t, 'walls') assert.equal(typeof gm.scene, 'number') assert.deepEqual(gm.walls.walls, [], 'a fresh scene has no walls') - const ack = await addWall(gm, { a: [100, 200.5], b: [400, 200.5], kind: 'wall' }) + const ack = await addWall(gm, { a: [100, 200.5], b: [400, 200.5] }) assert.equal(ack.ok, true) assert.equal(ack.id, 1) assert.equal(ack.code, undefined, 'an ok ack carries the result fields only') - assert.equal(typeof ack.n, 'number') - const wall = await wallEffect(gm.ws, m => m.t === 'wall' && m.id === 1) + assertTypedWall(wall) assert.equal(wall.scene, gm.scene) assert.deepEqual(wall.a, [100, 200.5]) assert.deepEqual(wall.b, [400, 200.5]) + assert.equal(wall.thickness, 0) + assert.equal(wall.position, 'center') + assert.equal(wall.height, null) assert.equal(wall.kind, 'wall') - assert.equal(wall.open, false) // omitted open = closed - assert.deepEqual(wall.flags, {}) // omitted flags = {} - assert.equal(typeof wall.n, 'number') + assert.equal(wall.blocks_sight, true) + assert.equal(wall.blocks_movement, true) + assert.equal(wall.sight_dir, 'both') + assert.equal(wall.player_marker, false) + assert.equal(wall.door, false) + assert.equal(wall.open, false) + assert.equal(wall.secret, false) + assert.equal(wall.locked, false) + assert.equal(wall.label, null) + assert.deepEqual(wall.flags, {}) assert.ok(gm.ws.messages.indexOf(ack) < gm.ws.messages.indexOf(wall), 'the ack is enqueued before the effect (DESIGN 4.2)') - // the flags object round-trips untouched; unknown intent fields are ignored (6.2) - const withFlags = await addWall(gm, { a: [10, 10], b: [10, 300], kind: 'door', - open: true, flags: { locked: false, note: 'side' }, - junk: { ignored: true } }) - assert.equal(withFlags.ok, true) - assert.equal(withFlags.id, 2) - const door = await wallEffect(gm.ws, m => m.t === 'wall' && m.id === 2) - assert.equal(door.kind, 'door') - assert.equal(door.open, true) - assert.deepEqual(door.flags, { locked: false, note: 'side' }) + // `kind` is output-only: an input kind is an unknown field and ignored (#54, 6.2) + const ignored = await addWall(gm, { a: [10, 10], b: [10, 300], kind: 'door', + flags: { note: 'side' }, junk: { ignored: true } }) + assert.equal(ignored.ok, true) + const plain = await wallEffect(gm.ws, m => m.t === 'wall' && m.id === ignored.id) + assert.equal(plain.kind, 'wall') + assert.equal(plain.door, false, 'an input kind never creates a door') + assert.deepEqual(plain.flags, { note: 'side' }) - // a second GM connection gets the snapshot of both walls, in id order + // geometry is accepted, stored and echoed; the switch set derives the shape label in 5.8 order + const shapes = [ + [{ blocks_sight: false }, 'window'], + [{ sight_dir: 'left' }, 'one_way'], + [{ door: true }, 'door'], + [{ door: true, blocks_sight: false }, 'window'], // a one-way check first: see-through wall + [{ blocks_movement: false }, 'custom'], + [{ secret: true, door: true }, 'door'], // secret never changes the label + ] + for (const [switches, kind] of shapes) { + const a = await addWall(gm, { a: [5, 5], b: [50, 50], thickness: 12, position: 'left', + height: 2.5, label: 'railing', ...switches }) + assert.equal(a.ok, true, JSON.stringify(switches)) + const frame = await wallEffect(gm.ws, m => m.t === 'wall' && m.id === a.id) + assert.equal(frame.kind, kind, JSON.stringify(switches)) + assert.equal(frame.thickness, 12) + assert.equal(frame.position, 'left') + assert.equal(frame.height, 2.5) + assert.equal(frame.label, 'railing') + } + + // a second GM connection gets the snapshot of every wall, in id order const gm2 = await openAs(s.origin, gmKey) await gm2.ws.waitText('hello') const snap = await gm2.ws.waitText('walls') - assert.deepEqual(snap.walls.map(w => w.id), [1, 2]) - assert.equal(snap.walls[1].open, true) + assert.deepEqual(snap.walls.map(w => w.id), [1, 2, 3, 4, 5, 6, 7, 8]) + for (const w of snap.walls) assertTypedWall(w) gm.ws.close(); gm2.ws.close() }) }) @@ -77,12 +114,12 @@ test('wall ids: monotonic per scene and never reused after removal', async () => await withGmServer(async (s, gmKey) => { const gm = await gmConnect(s.origin, gmKey) for (let i = 0; i < 3; i++) { - assert.equal((await addWall(gm, { a: [i * 10, 0], b: [i * 10 + 5, 0], kind: 'wall' })).id, i + 1) + assert.equal((await addWall(gm, { a: [i * 10, 0], b: [i * 10 + 5, 0] })).id, i + 1) } assert.equal((await gm.ws.request({ t: 'wall.remove', scene: gm.scene, id: 2 })).ok, true) await wallEffect(gm.ws, m => m.t === 'wall_gone' && m.id === 2) // the surviving ids do not renumber, and the next add does not reuse 2 - const next = await addWall(gm, { a: [0, 50], b: [50, 50], kind: 'wall' }) + const next = await addWall(gm, { a: [0, 50], b: [50, 50] }) assert.equal(next.id, 4) const gm2 = await openAs(s.origin, gmKey) await gm2.ws.waitText('hello') @@ -90,52 +127,97 @@ test('wall ids: monotonic per scene and never reused after removal', async () => assert.deepEqual(snap.walls.map(w => w.id), [1, 3, 4]) // remove the newest and add again: still no reuse assert.equal((await gm.ws.request({ t: 'wall.remove', scene: gm.scene, id: 4 })).ok, true) - assert.equal((await addWall(gm, { a: [0, 60], b: [50, 60], kind: 'wall' })).id, 5) + assert.equal((await addWall(gm, { a: [0, 60], b: [50, 60] })).id, 5) gm.ws.close(); gm2.ws.close() }) }) -test('wall.update: patches a, b, kind and flags; the id and open state stay', async () => { +test('wall.update: patches only what it names; open and kind are unknown fields', async () => { await withGmServer(async (s, gmKey) => { const gm = await gmConnect(s.origin, gmKey) - const { id } = await addWall(gm, { a: [100, 100], b: [200, 100], kind: 'door' }) + const { id } = await addWall(gm, { a: [100, 100], b: [200, 100], door: true }) await wallEffect(gm.ws, m => m.t === 'wall' && m.id === id) assert.equal((await gm.ws.request({ t: 'door.set', scene: gm.scene, id, open: true })).ok, true) await wallEffect(gm.ws, m => m.t === 'wall' && m.id === id && m.open === true) const ack = await gm.ws.request({ t: 'wall.update', scene: gm.scene, id, - a: [100, 100], b: [300, 400], flags: { kind: 'thin' } }) + a: [100, 100], b: [300, 400], thickness: 30, + position: 'right', height: 4, label: 'deep', + flags: { kind: 'thin' } }) assert.equal(ack.ok, true) const updated = await wallEffect(gm.ws, m => m.t === 'wall' && m.id === id && m.b[1] === 400) assert.deepEqual(updated.a, [100, 100]) assert.deepEqual(updated.b, [300, 400]) + assert.equal(updated.thickness, 30) + assert.equal(updated.position, 'right') + assert.equal(updated.height, 4) + assert.equal(updated.label, 'deep') assert.deepEqual(updated.flags, { kind: 'thin' }) assert.equal(updated.open, true, 'wall.update does not touch the open state') assert.equal(updated.kind, 'door') - // a partial patch keeps the other endpoint + // `open` in an update is an unknown field: it neither opens nor closes the door + const framesBefore = gm.ws.messages.filter(m => m.t === 'wall' && m.id === id).length + assert.equal((await gm.ws.request({ t: 'wall.update', scene: gm.scene, id, + open: false })).code, 'invalid', + 'an update naming only the ignored open has no patch field') + await sleep(50) + assert.equal(gm.ws.messages.filter(m => m.t === 'wall' && m.id === id).length, framesBefore, + 'the ignored open produced no frame') + + // a partial patch keeps the other fields; an explicit null clears height and label assert.equal((await gm.ws.request({ t: 'wall.update', scene: gm.scene, id, a: [0, 0] })).ok, true) const partial = await wallEffect(gm.ws, m => m.t === 'wall' && m.id === id && m.a[0] === 0) assert.deepEqual(partial.b, [300, 400]) - - // door -> wall closes it (a wall is never open) + assert.equal(partial.thickness, 30) assert.equal((await gm.ws.request({ t: 'wall.update', scene: gm.scene, id, - kind: 'wall' })).ok, true) - const asWall = await wallEffect(gm.ws, m => m.t === 'wall' && m.id === id && m.kind === 'wall') + height: null, label: null })).ok, true) + const cleared = await wallEffect(gm.ws, m => m.t === 'wall' && m.id === id && + m.height === null) + assert.equal(cleared.label, null) + + // clearing the door switch closes and de-secrets it (a non-door stores no door settings) + assert.equal((await gm.ws.request({ t: 'wall.update', scene: gm.scene, id, + door: false })).ok, true) + const asWall = await wallEffect(gm.ws, m => m.t === 'wall' && m.id === id && + m.door === false) assert.equal(asWall.open, false) + assert.equal(asWall.secret, false) + assert.equal(asWall.locked, false) + assert.equal(asWall.kind, 'wall') assert.equal((await gm.ws.request({ t: 'door.set', scene: gm.scene, id, open: true })).code, 'invalid', 'the row is a plain wall now') gm.ws.close() }) }) +test('wall.update {door:true} on a see-through fixed window yields a closed opening window', async () => { + await withGmServer(async (s, gmKey) => { + const gm = await gmConnect(s.origin, gmKey) + const { id } = await addWall(gm, { a: [100, 100], b: [200, 100], + blocks_sight: false, blocks_movement: true }) + const fixed = await wallEffect(gm.ws, m => m.t === 'wall' && m.id === id) + assert.equal(fixed.kind, 'window') + assert.equal(fixed.door, false) + assert.equal((await gm.ws.request({ t: 'wall.update', scene: gm.scene, id, + door: true })).ok, true) + const opening = await wallEffect(gm.ws, m => m.t === 'wall' && m.id === id && + m.door === true) + assert.equal(opening.kind, 'window') + assert.equal(opening.open, false, 'the new door is closed, never silently open') + assert.equal(opening.blocks_sight, false) + assert.equal(opening.blocks_movement, true) + gm.ws.close() + }) +}) + test('wall.remove and door.set: acks, GM effects, and the codes of 6.5', async () => { await withGmServer(async (s, gmKey) => { const gm = await gmConnect(s.origin, gmKey) - const { id: wallId } = await addWall(gm, { a: [0, 0], b: [100, 0], kind: 'wall' }) - const { id: doorId } = await addWall(gm, { a: [0, 100], b: [100, 100], kind: 'door' }) + const { id: wallId } = await addWall(gm, { a: [0, 0], b: [100, 0] }) + const { id: doorId } = await addWall(gm, { a: [0, 100], b: [100, 100], door: true }) await wallEffect(gm.ws, m => m.t === 'wall' && m.id === doorId) // door.set toggles only doors @@ -159,7 +241,7 @@ test('wall.remove and door.set: acks, GM effects, and the codes of 6.5', async ( const snap = await gm2.ws.waitText('walls') assert.deepEqual(snap.walls.map(w => w.id), [wallId]) - // door.set on a plain wall, an unknown id, and a missing open flag + // door.set on a plain wall, an unknown id, and bad open flags assert.equal((await gm.ws.request({ t: 'door.set', scene: gm.scene, id: wallId, open: true })).code, 'invalid') assert.equal((await gm.ws.request({ t: 'door.set', scene: gm.scene, id: 99, open: true })).code, @@ -171,26 +253,34 @@ test('wall.remove and door.set: acks, GM effects, and the codes of 6.5', async ( }) }) -test('field validation: invalid geometry and shapes are refused, nothing is applied', async () => { +test('field validation: geometry, switch shapes and impossible rows are refused', async () => { await withGmServer(async (s, gmKey) => { const gm = await gmConnect(s.origin, gmKey) const scene = gm.scene const invalid = [ - { a: [10, 10], b: [10, 10], kind: 'wall' }, // a == b - { a: [10, 10], kind: 'wall' }, // no b - { b: [10, 10], kind: 'wall' }, // no a - { a: [10, 10], b: [20, 20] }, // no kind - { a: [10, 10], b: [20, 20], kind: 'window' }, // kind outside wall|door - { a: [10, 10], b: [20, 20], kind: 'WALL' }, - { a: [-1, 10], b: [20, 20], kind: 'wall' }, // out of bounds - { a: [10, 10], b: [4097, 20], kind: 'wall' }, - { a: [10], b: [20, 20], kind: 'wall' }, // not a point - { a: [10, 10, 10], b: [20, 20], kind: 'wall' }, - { a: ['10', 10], b: [20, 20], kind: 'wall' }, - { a: [10, 10], b: [20, 20], kind: 'wall', open: 'yes' }, // open is not a boolean - { a: [10, 10], b: [20, 20], kind: 'wall', open: true }, // a wall is never open - { a: [10, 10], b: [20, 20], kind: 'door', flags: [1, 2] }, // flags is not an object - { a: [10, 10], b: [20, 20], kind: 'door', flags: 7 }, + { a: [10, 10], b: [10, 10] }, // a == b + { a: [10, 10] }, // no b + { b: [10, 10] }, // no a + { a: [-1, 10], b: [20, 20] }, // out of bounds + { a: [10, 10], b: [4097, 20] }, + { a: [10], b: [20, 20] }, // not a point + { a: [10, 10, 10], b: [20, 20] }, + { a: ['10', 10], b: [20, 20] }, + { a: [10, 10], b: [20, 20], thickness: -1 }, // ranges (5.10, 5.7) + { a: [10, 10], b: [20, 20], thickness: 257 }, + { a: [10, 10], b: [20, 20], thickness: 'thick' }, + { a: [10, 10], b: [20, 20], position: 'middle' }, + { a: [10, 10], b: [20, 20], height: 0 }, + { a: [10, 10], b: [20, 20], height: 101 }, + { a: [10, 10], b: [20, 20], height: 'tall' }, + { a: [10, 10], b: [20, 20], blocks_sight: 'yes' }, // switches are booleans + { a: [10, 10], b: [20, 20], open: 'yes' }, // open is a boolean on a create + { a: [10, 10], b: [20, 20], sight_dir: 'up' }, + { a: [10, 10], b: [20, 20], sight_dir: 'left', blocks_sight: false }, // direction needs sight + { a: [10, 10], b: [20, 20], door: true, secret: true, blocks_sight: false }, + { a: [10, 10], b: [20, 20], flags: [1, 2] }, // flags is not an object + { a: [10, 10], b: [20, 20], flags: 7 }, + { a: [10, 10], b: [20, 20], label: 7 }, ] for (const fields of invalid) { const ack = await gm.ws.request({ t: 'wall.add', scene, ...fields }) @@ -199,10 +289,10 @@ test('field validation: invalid geometry and shapes are refused, nothing is appl assert.equal(ack.id, undefined, 'a refusal carries no state') } // scene: a wrong id is not-found, a wrongly typed one is invalid - assert.equal((await gm.ws.request({ t: 'wall.add', scene: '1', a: [0, 0], b: [1, 1], - kind: 'wall' })).code, 'invalid') - assert.equal((await gm.ws.request({ t: 'wall.add', scene: scene + 1, a: [0, 0], b: [1, 1], - kind: 'wall' })).code, 'not-found') + assert.equal((await gm.ws.request({ t: 'wall.add', scene: '1', a: [0, 0], b: [1, 1] })).code, + 'invalid') + assert.equal((await gm.ws.request({ t: 'wall.add', scene: scene + 1, a: [0, 0], b: [1, 1] })).code, + 'not-found') // fields are checked before the lookup (6.5 steps 7 then 8): no patch field is `invalid`, // whatever the id assert.equal((await gm.ws.request({ t: 'wall.update', scene, id: 1 })).code, 'invalid') @@ -217,20 +307,25 @@ test('field validation: invalid geometry and shapes are refused, nothing is appl }) }) -test('wall.update refuses an empty patch, bad fields and bad geometry', async () => { +test('wall.update refuses an empty patch, ignored-only fields and bad values', async () => { await withGmServer(async (s, gmKey) => { const gm = await gmConnect(s.origin, gmKey) - const { id } = await addWall(gm, { a: [100, 100], b: [200, 100], kind: 'wall' }) + const { id } = await addWall(gm, { a: [100, 100], b: [200, 100] }) await wallEffect(gm.ws, m => m.t === 'wall' && m.id === id) const cases = [ [{}, 'invalid'], // no updatable field at all [{ id: 'x' }, 'invalid'], // id is not an integer [{ a: [1] }, 'invalid'], - [{ kind: 'window' }, 'invalid'], + [{ kind: 'window' }, 'invalid'], // output-only, so no patch field + [{ open: true }, 'invalid'], // door.set owns open, so no patch field [{ flags: 'no' }, 'invalid'], - [{ open: true }, 'invalid'], // `open` alone is not an update + [{ thickness: -1 }, 'invalid'], + [{ position: 'up' }, 'invalid'], + [{ height: -2 }, 'invalid'], + [{ blocks_movement: 0 }, 'invalid'], [{ a: [5, 5], b: [5, 5] }, 'invalid'], // degenerate [{ b: [9999, 5] }, 'invalid'], // out of bounds + [{ door: true, secret: true, blocks_sight: false }, 'invalid'], [{ id: 42, a: [0, 0] }, 'not-found'], ] for (const [fields, code] of cases) { @@ -253,7 +348,7 @@ test('players get no wall data at all, and every wall intent is refused to them' // a marker unique in the whole session: no number of the GM's walls may appear in a player frame const marker = [1234.5, 321.5] - const added = await addWall(gm, { a: marker, b: [2345.5, 321.5], kind: 'door' }) + const added = await addWall(gm, { a: marker, b: [2345.5, 321.5], door: true, height: 3.25 }) assert.equal(added.ok, true) await gm.ws.request({ t: 'door.set', scene: gm.scene, id: added.id, open: true }) await gm.ws.request({ t: 'wall.update', scene: gm.scene, id: added.id, b: [3456.5, 321.5] }) @@ -264,14 +359,22 @@ test('players get no wall data at all, and every wall intent is refused to them' for (const t of ['walls', 'wall', 'wall_gone']) { assert.equal(types.has(t), false, `a player received a ${t} frame`) } + // no wall field name may ride a player frame (DESIGN 3.1, 5.8; the leak checker bans them all) + const banned = ['thickness', 'position', 'height', 'blocks_sight', 'blocks_movement', + 'sight_dir', 'player_marker', 'door', 'secret', 'locked', 'label'] for (const m of p.ws.messages) { assert.ok(!JSON.stringify(m).includes('1234.5'), `wall coordinates leaked: ${JSON.stringify(m)}`) - assert.ok(!JSON.stringify(m).includes('321.5'), `wall coordinates leaked: ${JSON.stringify(m)}`) + for (const key of banned) { + const deepest = (node) => { + if (node === null || typeof node !== 'object') return false + if (Array.isArray(node)) return node.some(deepest) + return Object.keys(node).some(k => k === key || deepest(node[k])) + } + assert.equal(deepest(m), false, `wall field ${key} leaked: ${JSON.stringify(m)}`) + } } - // DESIGN 6.1 roles / 6.5 step 5-6: an unnamed non-GM connection is refused (the named-player - // role gate is the same `GmOnlyIntents` check, pinned by tests/tprotocol.nim until slice 8 - // brings naming). - for (const intent of [{ t: 'wall.add', scene: gm.scene, a: [0, 0], b: [1, 1], kind: 'wall' }, + // DESIGN 6.5 step 6: every wall intent is G-only, whatever the wall's settings + for (const intent of [{ t: 'wall.add', scene: gm.scene, a: [0, 0], b: [1, 1] }, { t: 'wall.update', scene: gm.scene, id: 1, a: [0, 0] }, { t: 'wall.remove', scene: gm.scene, id: 1 }, { t: 'door.set', scene: gm.scene, id: 1, open: true }]) { @@ -283,7 +386,7 @@ test('players get no wall data at all, and every wall intent is refused to them' }) }) -test('restart: walls, door state and the id counter are identical afterwards', async () => { +test('restart: the typed walls, door state and the id counter are identical afterwards', async () => { const stateDir = makeStateDir() try { const gmKey = gmKeyOf(stateDir) @@ -292,13 +395,14 @@ test('restart: walls, door state and the id counter are identical afterwards', a try { const gm = await gmConnect(s.origin, gmKey) scene = gm.scene - const w1 = await addWall(gm, { a: [0, 0], b: [4096, 0], kind: 'wall', flags: { side: 'north' } }) - const w2 = await addWall(gm, { a: [100, 100], b: [400, 100], kind: 'door' }) - const w3 = await addWall(gm, { a: [0, 500], b: [0, 900], kind: 'wall' }) + const w1 = await addWall(gm, { a: [0, 0], b: [4096, 0], flags: { side: 'north' }, + thickness: 20, position: 'left', height: 3 }) + const w2 = await addWall(gm, { a: [100, 100], b: [400, 100], door: true }) + const w3 = await addWall(gm, { a: [0, 500], b: [0, 900], blocks_sight: false }) assert.deepEqual([w1.id, w2.id, w3.id], [1, 2, 3]) assert.equal((await gm.ws.request({ t: 'door.set', scene, id: w2.id, open: true })).ok, true) assert.equal((await gm.ws.request({ t: 'wall.remove', scene, id: w3.id })).ok, true) - await gm.ws.request({ t: 'wall.update', scene, id: w1.id, b: [4000, 0] }) + await gm.ws.request({ t: 'wall.update', scene, id: w1.id, b: [4000, 0], label: 'north' }) await sleep(100) gm.ws.close() } finally { @@ -314,12 +418,18 @@ test('restart: walls, door state and the id counter are identical afterwards', a t: 'walls', scene, walls: [ - { id: 1, a: [0, 0], b: [4000, 0], kind: 'wall', open: false, flags: { side: 'north' } }, - { id: 2, a: [100, 100], b: [400, 100], kind: 'door', open: true, flags: {} }, + { id: 1, a: [0, 0], b: [4000, 0], thickness: 20, position: 'left', height: 3, + kind: 'wall', blocks_sight: true, blocks_movement: true, sight_dir: 'both', + player_marker: false, door: false, open: false, secret: false, locked: false, + label: 'north', flags: { side: 'north' } }, + { id: 2, a: [100, 100], b: [400, 100], thickness: 0, position: 'center', height: null, + kind: 'door', blocks_sight: true, blocks_movement: true, sight_dir: 'both', + player_marker: false, door: true, open: true, secret: false, locked: false, + label: null, flags: {} }, ], }) // the counter survived the removal of wall 3: the next id is 4, never 3 - assert.equal((await addWall(gm, { a: [10, 10], b: [20, 20], kind: 'wall' })).id, 4) + assert.equal((await addWall(gm, { a: [10, 10], b: [20, 20] })).id, 4) gm.ws.close() } finally { await stopServer(s)