feat(walls): presets, label rule and one switch-set validation path (#55)

wall.add/wall.update now take a preset or raw switches, never both:
resolveWall expands the four 5.8 presets to switches before validating, so
a preset never touches geometry and preset+switch or preset+open is invalid.
A raw create starts from the wall defaults; a raw update patches only the
switches it names and {door:false} closes and de-secrets.

The switch-set invariants are enforced by that one path for add and update:
open/secret/locked without a door, a secret door that is open/one-way/not
opaque, open with secret or locked, and a direction with no sight to block
are all invalid. The DB gains the missing open+locked CHECK as the backstop,
and the now-redundant open/door parity test is gone from the server path.

A wall label is now the 6.5 text rule: trimmed, 1..64 code points, no control
characters, null clears, stored verbatim and GM-only. window/one_way presets
are accepted and expanded to their switch sets per DESIGN 5.8/6.1; their
player-facing behaviour stays with #57/#58.

Tests: WS black-box presets/patch semantics/every refusal/label round-trip;
Nim shape pins for expansion, invariants and the label rule.
Nim 385 / Node 117 green.
This commit is contained in:
2026-11-19 22:35:57 +01:00
parent 77fa2dfe4c
commit 484275e8bb
5 changed files with 504 additions and 107 deletions
+1
View File
@@ -230,6 +230,7 @@ CREATE TABLE wall (
CHECK (secret = 0 OR (door = 1 AND open = 0 AND blocks_sight = 1 AND blocks_movement = 1
AND sight_dir = 'both')),
CHECK (locked = 0 OR door = 1),
CHECK (open = 0 OR locked = 0),
CHECK (sight_dir = 'both' OR blocks_sight = 1)
)""", """
INSERT INTO wall (scene_id, id, ax, ay, bx, by, thickness, position, blocks_sight,
+66 -61
View File
@@ -520,8 +520,8 @@ proc parseWallGeometry(env: Envelope, rec: var WallRec): bool =
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.
## an explicit null clears it; anything but a string is `invalid`. The 6.5 text rule (trimmed,
## 1..64 code points, no control characters) is enforced by `validWall` before the write (#55).
if not declared(env, "label"): return true
let node = env.node{"label"}
if node.kind == JNull:
@@ -532,32 +532,47 @@ proc parseWallLabel(env: Envelope, rec: var WallRec): bool =
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 parseWallPreset(env: Envelope, dest: var Option[Preset]): bool =
## `preset` is a 5.8 name, never JSON null; anything else is `invalid`.
if not declared(env, "preset"): return true
let node = env.node{"preset"}
if node.kind != JString: return false
let p = parsePreset(node.getStr)
if p.isNone: return false
dest = p
true
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
proc parseWallSwitch(env: Envelope, key: string, dest: var Option[bool]): bool =
## One raw switch: absent = not patched; a non-boolean is `invalid`.
if not present(env, key): return true
var bit: bool
if not boolField(env, key, bit): return false
dest = some(bit)
true
proc parseWallSwitches(env: Envelope, sw: var WallSwitches, allowOpen: bool): bool =
## Collects the raw 5.8 switches the payload names. `open` is collected only on a create; in an
## update it is an unknown field and is ignored (`door.set` owns it, DESIGN 6.1).
if not parseWallSwitch(env, "blocks_sight", sw.blocksSight): return false
if not parseWallSwitch(env, "blocks_movement", sw.blocksMovement): return false
if not parseWallSwitch(env, "player_marker", sw.playerMarker): return false
if not parseWallSwitch(env, "door", sw.door): return false
if allowOpen and not parseWallSwitch(env, "open", sw.open): return false
if not parseWallSwitch(env, "secret", sw.secret): return false
if not parseWallSwitch(env, "locked", sw.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
sw.sightDir = d
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).
## ignored: a door's open state changes only through `door.set` (DESIGN 6.1, #54). A preset
## replaces the whole switch set and may not appear with any raw switch, `open` included (#55).
if not parseWallPreset(env, patch.preset): return false
if present(env, "a"):
let v = parseVec(env.node{"a"})
if v.isNone: return false
@@ -592,31 +607,11 @@ proc parseWallPatch(env: Envelope, patch: var WallPatch): bool =
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 not parseWallSwitches(env, patch.switches, false): return false
if patch.preset.isSome and (patch.switches.hasAnySwitch or declared(env, "open")):
# preset xor raw switches; an `open` field alongside a preset is `invalid` even though open is
# otherwise an ignored unknown field on an update (DESIGN 6.1, #55).
return false
if present(env, "flags"):
let f = parseFlags(env.node{"flags"})
if f.isNone: return false
@@ -626,9 +621,7 @@ proc parseWallPatch(env: Envelope, patch: var WallPatch): bool =
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
patch.preset.isSome or patch.switches.hasAnySwitch or patch.flags.isSome
type
ControllerCheck = enum
@@ -2043,12 +2036,20 @@ proc dispatch(conn: Conn, env: Envelope) {.gcsafe.} =
if a.isNone or b.isNone:
ackErr(conn, env.reqId, CodeInvalid)
return
# The raw-switch create: omitted switches keep the `wall` preset's defaults (DESIGN 6.1, #54).
# A raw-switch create starts from the `wall` defaults; a preset replaces the switch set. Both
# go through the same expand-and-validate path (DESIGN 6.1, #55).
var candidate = defaultWall(a.get, b.get)
if not parseWallGeometry(env, candidate) or not parseWallSwitches(env, candidate, true) or
not parseWallLabel(env, candidate):
var preset: Option[Preset]
var switches: WallSwitches
if not parseWallGeometry(env, candidate) or not parseWallPreset(env, preset) or
not parseWallSwitches(env, switches, true) or not parseWallLabel(env, candidate):
ackErr(conn, env.reqId, CodeInvalid)
return
let resolved = resolveWall(candidate, preset, switches)
if resolved.isNone:
ackErr(conn, env.reqId, CodeInvalid)
return
candidate = resolved.get
let flags = parseFlags(fieldOrNull(env.node, "flags"))
if flags.isNone:
ackErr(conn, env.reqId, CodeInvalid)
@@ -2118,18 +2119,22 @@ proc dispatch(conn: Conn, env: Envelope) {.gcsafe.} =
# `wall.update` = remove then add for the status rules (5.5): the rules run on the snapshot
# with the patched wall at the same index, so a move away clears and a move onto a token sticks.
let idx = wallIndex(app.scene, id).get
var mr = moveScene(app.scene, app.tokens)
outcome = updateWall(app.db, app.scene, patched(current.get, storedPatch))
if outcome == waOk:
let updated = wallById(app.scene, id)
discard moverules.updateWall(mr, idx, ruleWall(updated.get))
discard applyRuleOutcome(mr)
refreshAll()
persistAllExplored()
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
let candidate = patched(current.get, storedPatch)
if candidate.isNone:
outcome = waInvalid # an impossible resulting switch set (5.8)
else:
var mr = moveScene(app.scene, app.tokens)
outcome = updateWall(app.db, app.scene, candidate.get)
if outcome == waOk:
let updated = wallById(app.scene, id)
discard moverules.updateWall(mr, idx, ruleWall(updated.get))
discard applyRuleOutcome(mr)
refreshAll()
persistAllExplored()
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
if outcome == waNotFound:
ackErr(conn, env.reqId, CodeNotFound)
return
+134 -45
View File
@@ -16,8 +16,10 @@
## - `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`: 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.add`/`wall.update`: either a 5.8 preset or raw switches, never both; `resolveWall` is
## the one expand-and-validate path, so a preset never touches geometry and an impossible
## switch set is `invalid` at every entry point. A raw create starts from the `wall` defaults;
## a raw update patches only the switches it names; `{door:false}` closes and de-secrets.
## - `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`.
@@ -28,7 +30,7 @@
## 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, unicode]
import std/[json, math, options, strutils]
import db_connector/db_sqlite
import geometry, text
@@ -43,6 +45,23 @@ type
sdLeft = "left"
sdRight = "right"
Preset* = enum
## The four 5.8 presets. A preset is a named switch set, never storage: `expandPreset` turns it
## into switches before the one validation path runs (DESIGN 5.8, 6.1).
pwWall = "wall"
pwDoor = "door"
pwWindow = "window"
pwOneWay = "one_way"
WallSwitches* = object
## The raw switches a payload names. A field that is `none` is not patched, which is what makes
## a raw-switch `wall.update` patch-only and a raw-switch `wall.add` start from the `wall`
## defaults (DESIGN 6.1). `open` is collected only for `wall.add`; on an update it is an
## unknown field and `door.set` owns it.
blocksSight*, blocksMovement*, playerMarker*: Option[bool]
door*, open*, secret*, locked*: Option[bool]
sightDir*: Option[SightDir]
WallRec* = object
## 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).
@@ -90,9 +109,8 @@ type
clearHeight*: bool
label*: Option[string]
clearLabel*: bool
blocksSight*, blocksMovement*: Option[bool]
sightDir*: Option[SightDir]
playerMarker*, door*, secret*, locked*: Option[bool]
preset*: Option[Preset] ## replaces the whole switch set; never with a raw switch
switches*: WallSwitches ## the raw switches present; patches only those
flags*: Option[JsonNode]
ScenePatch* = object
@@ -114,8 +132,11 @@ const
## The seeded v1 scene (migration step 3). Exactly one scene exists in v1 (Q3).
WallPositions* = [wpCenter, wpLeft, wpRight]
SightDirs* = [sdBoth, sdLeft, sdRight]
Presets* = [pwWall, pwDoor, pwWindow, pwOneWay]
SceneNameMaxLen* = 64
## `scene.set.name`: the 6.5 text rule, same 64-code-point bound as character names (#25).
WallLabelMaxLen* = 64
## `wall.label`: the 6.5 text rule, 1..64 code points, trimmed, no control characters (#55).
proc defaultWall*(a, b: Vec): WallRec =
## The `wall` preset's switches: both blocks on, both-way sight, no marker, no door settings,
@@ -137,6 +158,87 @@ proc derivedKind*(w: WallRec): string =
else:
"custom"
# ---------------------------------------------------------------------------------------------------
# The one expand-and-validate path for wall writes (DESIGN 5.8, 6.1 FIXED #49/#55)
proc storable*(rec: WallRec): bool =
## The switch-set invariants of DESIGN 5.8, mirrored by the database CHECKs of db.nim step 8.
## The caller has already resolved presets and raw patches; this is the last semantic gate
## before SQLite (which stays the backstop for a write that bypasses the server).
# `open` without `door` cannot survive the resolve/normalize path (a named `open:true` is refused
# and a cleared `door` closes the row), so the parity rule lives in the DB CHECK alone.
if rec.secret and not rec.door: return false
if rec.locked 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.open and (rec.secret or rec.locked): return false
if rec.sightDir != sdBoth and not rec.blocksSight: return false
true
proc hasAnySwitch*(sw: WallSwitches): bool =
## True when the payload named any raw switch (a preset may not appear with one).
sw.blocksSight.isSome or sw.blocksMovement.isSome or sw.playerMarker.isSome or
sw.door.isSome or sw.open.isSome or sw.secret.isSome or sw.locked.isSome or
sw.sightDir.isSome
proc expandPreset*(base: WallRec, preset: Preset): WallRec =
## A preset replaces the whole switch set and touches nothing else: `a`, `b`, thickness,
## position, height, label and flags are the base's (DESIGN 5.8 table, 6.1). `window` is the
## opening window (door set, closed) with the marker on; the fixed window is `door` turned off.
result = base
case preset
of pwWall, pwDoor:
result.blocksSight = true
result.blocksMovement = true
result.sightDir = sdBoth
of pwWindow:
result.blocksSight = false
result.blocksMovement = true
result.sightDir = sdBoth
of pwOneWay:
result.blocksSight = true
result.blocksMovement = true
result.sightDir = sdLeft
result.playerMarker = preset == pwWindow
result.door = preset in {pwDoor, pwWindow}
result.open = false
result.secret = false
result.locked = false
proc applySwitches(base: WallRec, sw: WallSwitches): Option[WallRec] =
## A raw-switch write patches only the switches it names. A door-only switch set to true on a
## non-door is `invalid` (never silently dropped); when the write clears `door`, inherited
## door-only settings are closed and de-secreted (DESIGN 5.8, 6.1).
var r = base
if sw.blocksSight.isSome: r.blocksSight = sw.blocksSight.get
if sw.blocksMovement.isSome: r.blocksMovement = sw.blocksMovement.get
if sw.playerMarker.isSome: r.playerMarker = sw.playerMarker.get
if sw.door.isSome: r.door = sw.door.get
if sw.open.isSome: r.open = sw.open.get
if sw.secret.isSome: r.secret = sw.secret.get
if sw.locked.isSome: r.locked = sw.locked.get
if sw.sightDir.isSome: r.sightDir = sw.sightDir.get
if not r.door:
if sw.open == some(true) or sw.secret == some(true) or sw.locked == some(true):
return none(WallRec)
r.open = false
r.secret = false
r.locked = false
some(r)
proc resolveWall*(base: WallRec, preset: Option[Preset],
sw: WallSwitches): Option[WallRec] =
## THE single path shared by `wall.add`, `wall.update` and the future UVTT importer: a preset is
## expanded before validation and may not appear with any raw switch; raw switches patch the
## base; the resulting switch set is then checked by `storable`. Geometry, height and label are
## validated by `validWall`; a preset never touches them (DESIGN 5.8, 6.1 FIXED #49/#55).
if preset.isSome:
if sw.hasAnySwitch: return none(WallRec)
result = some(expandPreset(base, preset.get))
else:
result = applySwitches(base, sw)
if result.isSome and not storable(result.get): result = none(WallRec)
# ---------------------------------------------------------------------------------------------------
# Field parsing (DESIGN 6.1 field notes: px floats, missing or wrongly typed -> `invalid`)
@@ -148,6 +250,10 @@ proc parseSightDir*(raw: string): Option[SightDir] =
for d in SightDirs:
if $d == raw: return some(d)
proc parsePreset*(raw: string): Option[Preset] =
for p in Presets:
if $p == raw: return some(p)
proc parseVec*(node: JsonNode): Option[Vec] =
## `a:[x,y]` / `b:[x,y]`: exactly two finite JSON numbers.
if node.isNil or node.kind != JArray or node.len != 2: return none(Vec)
@@ -240,27 +346,14 @@ 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, 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.
## DESIGN 6.1 `wall.*` validation: `a != b`, both endpoints in bounds, the geometry ranges, the
## 6.5 text rule for `label` 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
(rec.label.isNone or validText(rec.label.get, WallLabelMaxLen)) and
storable(rec)
proc normalize*(rec: WallRec): WallRec =
@@ -281,28 +374,24 @@ proc wallById*(sc: SceneRec, id: int): Option[WallRec] =
let i = wallIndex(sc, id)
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. 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.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)
proc patched*(w: WallRec, patch: WallPatch): Option[WallRec] =
## `wall.update` candidate: the stored row with the patch applied and validated by the same path
## as `wall.add`. 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. `none` means the resulting switch set is forbidden (DESIGN 5.8, 6.1).
var base = w
if patch.a.isSome: base.a = patch.a.get
if patch.b.isSome: base.b = patch.b.get
if patch.thickness.isSome: base.thickness = patch.thickness.get
if patch.position.isSome: base.position = patch.position.get
if patch.clearHeight: base.height = none(float)
elif patch.height.isSome: base.height = patch.height
if patch.clearLabel: base.label = none(string)
elif patch.label.isSome: base.label = patch.label
if patch.flags.isSome: base.flags = patch.flags.get
result = resolveWall(base, patch.preset, patch.switches)
if result.isSome:
result = some(normalize(result.get))
# ---------------------------------------------------------------------------------------------------
# Persistence (write-through, synchronous=FULL around the transaction, Q12)