test: tie group evidence to passing tests and baseline restart on the as-built server (#36)

- tools/groups.mjs evidence entries now name the exact test, a minimum assertion
  count and the calls its body must keep; groups.test.mjs checks all three.
- tools/evidence.mjs parses the spec reporter log and fails the gate unless every
  registered evidence test ran and passed; test.sh runs it after the Node suite.
- restart.test.mjs snapshots the live as-built world on the first server, then
  compares it to the post-SIGTERM/SIGKILL state (players connect before the GM, so
  the GM's derived encountered grey is computed on both sides).
- Negative controls: a hollowed auth test fails the new evidence check; a planted
  first-load drop of a token's gm prop bucket fails the new restart baseline while
  the old restart-to-restart test passed.
- Refresh the gate evidence (control + 73 mutations incl. s1-s7, 142 node tests).
This commit is contained in:
2026-11-20 21:55:50 +01:00
parent b0e1633aa9
commit 1f11779658
10 changed files with 816 additions and 216 deletions
+101
View File
@@ -0,0 +1,101 @@
// #36: the evidence half of the M3 group map. `GROUPS` (tools/groups.mjs) names, per acceptance
// group, the exact test that proves it plus the assertions/calls its body must keep. This module
// turns that claim into something checkable in two places:
//
// * `findTestBody` (static, used by tools/groups.test.mjs): the declaration exists exactly once,
// its body still holds at least `minAsserts` assertions and every required snippet;
// * this file's CLI (run by tools/test.sh AFTER the Node suite): the reporter output shows every
// registered test actually ran and passed, and none of them was skipped. A title substring in a
// comment, an emptied test body, or a registration that never runs cannot satisfy it.
import fs from 'node:fs'
import path from 'node:path'
import { fileURLToPath } from 'node:url'
import { GROUPS } from './groups.mjs'
const escapeRe = s => s.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')
// A test title as written in the source, with `${...}` standing for the case it is built for.
export function titleToRegExp(title) {
const parts = String(title).split(/\$\{[^}]*\}/g).map(escapeRe)
return new RegExp(`^${parts.join('.*?')}$`)
}
// The source text of one test declaration: located by its exact title literal, bounded by the
// matching close of the `test(` call at the declaration's own indentation.
export function findTestBody(fileText, title) {
const needles = ['`', "'", '"'].map(q => `test(${q}${title}${q}`)
const hits = needles.map(n => fileText.indexOf(n)).filter(i => i >= 0)
if (hits.length !== 1) return null // absent, or declared under more than one quoting/title
const start = fileText.lastIndexOf('\n', hits[0]) + 1
const indent = fileText.slice(start, hits[0])
if (/\S/.test(indent)) return null
const closer = new RegExp(`^${escapeRe(indent)}\\}\\)\\s*$`, 'm')
const rest = fileText.slice(start)
const m = closer.exec(rest)
if (!m) return null
return { start, end: start + m.index, body: rest.slice(0, m.index) }
}
const GLYPH = /^\s*(✔|✖|﹣)\s+(.+?)\s+\((?:<1|\d+(?:\.\d+)?)ms\)(?:\s+#\s+(SKIP|TODO))?\s*$/
// The spec reporter's per-test lines, as `devbox run test` records them in results/node-test.log.
export function parseReporter(text) {
const out = []
for (const line of text.split('\n')) {
const m = GLYPH.exec(line)
if (!m) continue
const [, glyph, name, skipped] = m
const status = glyph === '✖' ? 'fail' : (skipped || glyph === '﹣') ? 'skipped' : 'pass'
out.push({ name, status })
}
return out
}
export function checkLog(logText, groups = GROUPS) {
const ran = parseReporter(logText)
const errors = []
let checked = 0
for (const [group, spec] of Object.entries(groups)) {
for (const ev of spec.evidence) {
checked += 1
const rx = titleToRegExp(ev.test)
const hits = ran.filter(t => rx.test(t.name))
const passed = hits.filter(t => t.status === 'pass').length
const failed = hits.filter(t => t.status === 'fail').length
const skipped = hits.filter(t => t.status === 'skipped').length
const want = ev.minTests ?? 1
const where = `${group}: ${ev.file} "${ev.test}"`
if (passed < want) {
errors.push(`${where}: ${passed} passing run(s), expected at least ${want}` +
(hits.length ? ` (saw ${JSON.stringify(hits.slice(0, 4))})` : ' (never ran)'))
}
if (failed > 0) errors.push(`${where}: ${failed} failing run(s)`)
if (skipped > 0) errors.push(`${where}: ${skipped} skipped run(s)`)
}
}
return { checked, errors }
}
function main(argv) {
const root = path.dirname(fileURLToPath(import.meta.url))
const logPath = argv[2] ?? path.join(root, '..', 'results', 'node-test.log')
let text
try {
text = fs.readFileSync(logPath, 'utf8')
} catch (e) {
console.error(`evidence: cannot read ${logPath}: ${e.message}`)
return 1
}
const { checked, errors } = checkLog(text)
if (errors.length) {
console.error(`evidence: ${errors.length} group evidence problem(s) in ${logPath}:`)
for (const e of errors) console.error(` - ${e}`)
return 1
}
console.log(`evidence: ${checked} registered group evidence test(s) ran and passed (${logPath})`)
return 0
}
if (process.argv[1] && path.resolve(process.argv[1]) === fileURLToPath(import.meta.url)) {
process.exitCode = main(process.argv)
}
+75 -19
View File
@@ -1,8 +1,14 @@
// The nine M3 acceptance groups of DESIGN 13 (FIXED by owner decision #12) and the test that proves
// each one. `devbox run test` runs every `tools/*.test.mjs`; this map is the checklist the finish
// line (#25) records in DESIGN 14, and tools/groups.test.mjs fails if a group's file or its named
// evidence test disappears. Slice-level test files that are not an accept group (smoke, walls,
// tokens, details, scene, wsheaders) still run; they are not listed here.
// line (#25) records in DESIGN 14.
//
// #36: an evidence entry is not a title substring. It names the test's exact title (a `${...}`
// placeholder marks a title the file builds per case), the minimum number of `assert.*` calls its
// body must keep, and any distinctive call the body must keep executing. `tools/groups.test.mjs`
// checks those against the source statically; the final step of `tools/test.sh` parses the Node
// test runner's reporter output and fails unless every registered title actually ran and passed
// (tools/evidence.mjs). A test hollowed out to its title, or one that is registered but never runs,
// therefore fails the gate.
export const GROUPS = {
'leak+fault': {
// The transcript checker and its negative controls, plus the two Walls r1 harnesses whose
@@ -10,50 +16,100 @@ export const GROUPS = {
// #56) and the player marker group (#59/#60). #61's scenario rewrite keeps all of them green.
files: ['leak.test.mjs', 'fault.test.mjs', 'doors.test.mjs', 'markers.test.mjs'],
evidence: [
['leak.test.mjs', 'leak test ${subject}: the subject\'s whole view matches the GM\'s truth'],
['fault.test.mjs', 'caught as exactly'],
['doors.test.mjs', 'fault secretgap: the equivalence group fails as exactly SECRETGAP'],
['markers.test.mjs', 'retraction: every cause sends del only, a re-earned marker gets a fresh id (#60)'],
{ file: 'leak.test.mjs',
test: "leak test ${subject}: the subject's whole view matches the GM's truth",
minTests: 2, minAsserts: 8, requires: ['runChecker(transcript, subject)'] },
{ file: 'fault.test.mjs',
test: "fault ${fault}: caught as exactly ${expected.join(' ')}",
minAsserts: 2, requires: ['classesOf(check.output)'] },
{ file: 'doors.test.mjs',
test: 'fault secretgap: the equivalence group fails as exactly SECRETGAP',
minAsserts: 1, requires: ["equivalenceClasses(a, b), ['SECRETGAP']"] },
{ file: 'markers.test.mjs',
test: 'retraction: every cause sends del only, a re-earned marker gets a fresh id (#60)',
minAsserts: 12, requires: ['assertMarkerShape(seen)'] },
],
},
tiles: {
files: ['tiles.test.mjs', 'oneway.test.mjs'],
evidence: [['tiles.test.mjs', 'tile gate: leak check (d) matches the independent explored oracle'],
['oneway.test.mjs', 'one-way sight: the blind side sees nothing across, the seeing side does (#58)']],
evidence: [
{ file: 'tiles.test.mjs',
test: 'tile gate: leak check (d) matches the independent explored oracle',
minAsserts: 6, requires: ['oracle'] },
{ file: 'oneway.test.mjs',
test: 'one-way sight: the blind side sees nothing across, the seeing side does (#58)',
minAsserts: 12, requires: ['withOneWayStack'] },
],
},
probing: {
files: ['probing.test.mjs'],
evidence: [['probing.test.mjs', 'probing over WS: walls beyond cap + radius change no reply']],
evidence: [
{ file: 'probing.test.mjs',
test: 'probing over WS: walls beyond cap + radius change no reply',
minAsserts: 3, requires: ['assert.deepEqual(shape(ra), shape(rb)'] },
],
},
protocol: {
files: ['protocol.test.mjs'],
evidence: [['protocol.test.mjs', 'an unknown type is refused, unknown fields are ignored']],
evidence: [
{ file: 'protocol.test.mjs',
test: 'an unknown type is refused, unknown fields are ignored, and every intent gets one ack',
minAsserts: 6, requires: ['assert.equal'] },
],
},
auth: {
files: ['auth.test.mjs'],
evidence: [['auth.test.mjs', 'key.replace: old key and old sessions die']],
evidence: [
{ file: 'auth.test.mjs',
test: 'key.replace: old key and old sessions die, live connections close, the new key works',
minAsserts: 6, requires: ['assert.notEqual'] },
],
},
'characters and names': {
files: ['characters.test.mjs'],
evidence: [['characters.test.mjs', 'encountered: a sighting is kept under the name the player knows']],
evidence: [
{ file: 'characters.test.mjs',
test: 'encountered: a sighting is kept under the name the player knows, and survives everything',
minAsserts: 8, requires: ['encountered'] },
],
},
restart: {
files: ['restart.test.mjs'],
evidence: [['restart.test.mjs', 'restart: full state, all CRUD, before and after SIGTERM'],
['restart.test.mjs', 'restart: full state, all CRUD, before and after SIGKILL']],
evidence: [
// #36: both variants take the baseline from the first (as-built) server, before the signal;
// the thin wrappers must keep calling the only code path that can prove it.
{ file: 'restart.test.mjs',
test: 'restart: full state, all CRUD, before and after SIGTERM',
minAsserts: 0, requires: ['restartGroup(false)'] },
{ file: 'restart.test.mjs',
test: 'restart: full state, all CRUD, before and after SIGKILL',
minAsserts: 0, requires: ['restartGroup(true)'] },
],
},
persistence: {
// The schema-7 fixture driven through the real binary (migration mapping, explored round trip)
// plus the behaviour-preservation pair: migrated walls vs the same walls authored through
// `wall.add`, byte-identical to a player (stories 29/30/77, #52).
files: ['persistence.test.mjs', 'wallbehaviour.test.mjs'],
evidence: [['persistence.test.mjs', 'explored round trip: a fresh connection gets the whole grid'],
['persistence.test.mjs', 'migration: a schema-4 DB (fixture) migrates under the real binary'],
['wallbehaviour.test.mjs', 'behaviour preservation: a migrated schema-7 scene and the same scene authored via raw switches are byte-identical to a player']],
evidence: [
{ file: 'persistence.test.mjs',
test: 'explored round trip: a fresh connection gets the whole grid the server accumulated',
minAsserts: 3, requires: ['exploredSnapshot(s.origin, alice)'] },
{ file: 'persistence.test.mjs',
test: 'migration: a schema-4 DB (fixture) migrates under the real binary to the latest schema',
minAsserts: 6, requires: ['assert.equal'] },
{ file: 'wallbehaviour.test.mjs',
test: 'behaviour preservation: a migrated schema-7 scene and the same scene authored via raw switches are byte-identical to a player',
minAsserts: 2, requires: ['assert.deepEqual'] },
],
},
logs: {
files: ['logs.test.mjs'],
evidence: [['logs.test.mjs', 'logs: no key, session cookie or session hash reaches the log']],
evidence: [
{ file: 'logs.test.mjs',
test: 'logs: no key, session cookie or session hash reaches the log',
minAsserts: 8, requires: ['assert.equal'] },
],
},
}
+22 -6
View File
@@ -1,12 +1,14 @@
// The M3 acceptance checklist as a test: the nine groups of DESIGN 13 exist, each points at a real
// harness in tools/, and each carries the named test that proves it (DESIGN 14, #12 / #25). This
// fails if someone renames a group test or deletes a group file, so `devbox run test` cannot go
// green with a group silently unproven.
// harness in tools/, and each carries the exact test that proves it (DESIGN 14, #12 / #25). #36:
// "proves it" is not a substring — the declaration and its body must still hold the assertions and
// the call the group claims, and `tools/test.sh` separately requires the reporter to show every one
// of these tests passing (tools/evidence.mjs), so a hollowed or unrun test cannot count.
import test from 'node:test'
import assert from 'node:assert/strict'
import fs from 'node:fs'
import path from 'node:path'
import { GROUP_COUNT, GROUPS } from './groups.mjs'
import { findTestBody } from './evidence.mjs'
import { projectRoot } from './lib.mjs'
const tools = path.join(projectRoot, 'tools')
@@ -24,9 +26,23 @@ test('M3 accept: the nine groups of DESIGN 13 are mapped to named harness tests'
assert.ok(fs.statSync(full).size > 0, `${group}: ${file} is not empty`)
}
assert.ok(spec.evidence.length >= 1, `${group}: names its proving test`)
for (const [file, needle] of spec.evidence) {
const text = fs.readFileSync(path.join(tools, file), 'utf8')
assert.ok(text.includes(needle), `${group}: ${file} contains the test "${needle}"`)
for (const ev of spec.evidence) {
assert.ok(spec.files.includes(ev.file), `${group}: evidence file ${ev.file} is one of the group files`)
assert.equal(typeof ev.test, 'string', `${group}: evidence names an exact test title`)
assert.ok(!ev.test.includes('*'), `${group}: the evidence title is exact, not a glob`)
const text = fs.readFileSync(path.join(tools, ev.file), 'utf8')
const found = findTestBody(text, ev.test)
assert.ok(found,
`${group}: ${ev.file} declares exactly one test with the title "${ev.test}" ` +
'(a renamed, duplicated or absent evidence test fails the group)')
const asserts = (found.body.match(/\bassert\.[A-Za-z]+/g) ?? []).length
const min = ev.minAsserts ?? 1
assert.ok(asserts >= min,
`${group}: "${ev.test}" keeps its assertions (${asserts} found, at least ${min} required)`)
for (const needle of ev.requires ?? []) {
assert.ok(found.body.includes(needle),
`${group}: "${ev.test}" still executes \`${needle}\``)
}
}
}
// Every *group* harness is run by `tools/test.sh` (one glob over tools/*.test.mjs).
+35 -20
View File
@@ -201,15 +201,24 @@ function expectedEncounteredName(who, ids) {
[ids.linked]: 'a cloaked figure', [ids.pc]: 'Wanderer' }
}
// The full before/after comparison: one fresh GM connection and one fresh connection per player.
async function compareAcross(origin, gmKey, players, ids, expected) {
const beforeGm = await snapshot(origin, gmKey, expected, true)
const before = { gm: beforeGm }
// The full before/after comparison: one fresh connection per player and one fresh GM connection.
// #36: players connect first, so their live sight state is computed before the GM's per-player
// `encountered` lists (whose `grey` is a live sight test, not stored state) are read. Connecting
// them only after the GM would compare a refreshed restarted server against an unrefreshed one.
async function snapshotAll(origin, gmKey, players, expected) {
const all = {}
for (const [who, p] of Object.entries(players)) {
// Only the character's owner is sent a `character` record (6.1).
before[who] = await snapshot(origin, p.key,
{ ...expected, characters: who === 'alice' ? 1 : 0 }, false)
all[who] = await snapshot(origin, p.key,
{ ...expected, characters: who === 'alice' ? 1 : 0 }, false)
}
all.gm = await snapshot(origin, gmKey, expected, true)
return all
}
async function compareAcross(origin, gmKey, players, ids, expected) {
const before = await snapshotAll(origin, gmKey, players, expected)
const beforeGm = before.gm
// The CRUD inventory is not empty: a restart test over an empty world would prove nothing.
assert.ok(beforeGm.walls.walls.length >= 2, 'the wall and the door are there')
assert.equal(beforeGm.walls.walls.find(w => w.id === ids.door).open, true, 'the door is open')
@@ -242,11 +251,10 @@ async function compareAcross(origin, gmKey, players, ids, expected) {
return before
}
async function restartAndCompare(stateDir, gmKey, players, ids, expected, hard) {
let s = await startServer({ stateDir })
const before = await compareAcross(s.origin, gmKey, players, ids, expected)
// Kill the server that holds the as-built world. SIGKILL is deliberate for the hard variant: every
// ack is sent after COMMIT (4.2), so a hard kill cannot lose an acked mutation.
async function stopWithSignal(s, hard) {
if (hard) {
// Every ack is sent after COMMIT (4.2), so a hard kill cannot lose an acked mutation.
s.child.kill('SIGKILL')
const deadline = Date.now() + 5000
while (s.child.signalCode === null && s.child.exitCode === null && Date.now() < deadline) {
@@ -254,19 +262,22 @@ async function restartAndCompare(stateDir, gmKey, players, ids, expected, hard)
}
}
await stopServer(s)
}
s = await startServer({ stateDir })
// #36: `before` is the snapshot of the *as-built* world on the first server instance, taken after
// the CRUD and before any restart. The old version took it after a restart, so a field silently
// dropped on the first load was missing from both sides and the deepEqual held.
async function restartAndCompare(stateDir, before, gmKey, players, ids, expected) {
let s = await startServer({ stateDir })
try {
const afterGm = await snapshot(s.origin, gmKey, expected, true)
assert.deepEqual(afterGm, before.gm, 'the GM resync after the restart is identical')
for (const [who, p] of Object.entries(players)) {
const after = await snapshot(s.origin, p.key,
{ ...expected, characters: who === 'alice' ? 1 : 0 }, false)
assert.deepEqual(after, before[who],
const after = await snapshotAll(s.origin, gmKey, players, expected)
assert.deepEqual(after.gm, before.gm, 'the GM resync after the restart is identical')
for (const who of Object.keys(players)) {
assert.deepEqual(after[who], before[who],
`${who}'s resync after the restart is identical`)
// ... and the absolute truth, so two equally wrong snapshots cannot pass (#27).
for (const [id, name] of Object.entries(expectedEncounteredName(who, ids))) {
assert.equal(after.encountered.set.find(e => e.id === id)?.name, name,
assert.equal(after[who].encountered.set.find(e => e.id === id)?.name, name,
`${who}'s encountered entry for ${id} after the restart`)
}
}
@@ -305,6 +316,7 @@ async function restartGroup(hard) {
let s = await startServer({ stateDir })
let saved
let markerRows
let before
try {
saved = await buildWorld(s.origin, gmKey)
players.alice = saved.alice
@@ -331,11 +343,14 @@ async function restartGroup(hard) {
assert.equal(linkedRows[String(saved.bob.id)], '')
assert.equal(linkedRows[String(saved.carol.id)], '',
'the reveal to Alice did not write Bob\'s or Carol\'s row (#27)')
// #36: the baseline is this live server's full resync, built by the CRUD above and never
// reloaded from disk. A field lost when the first server reloads the DB fails the comparison.
before = await compareAcross(s.origin, gmKey, players, saved.ids, EXPECTED)
} finally {
await stopServer(s)
await stopWithSignal(s, hard)
}
try {
await restartAndCompare(stateDir, gmKey, players, saved.ids, EXPECTED, hard)
await restartAndCompare(stateDir, before, gmKey, players, saved.ids, EXPECTED)
assert.deepEqual(dbMarkerRows(stateDir, saved.ids.window), markerRows,
'the marker_seen rows (player and opaque id) survive the restart unchanged')
} finally {
+5 -2
View File
@@ -11,7 +11,10 @@ fi
cat results/nimble-test.log
# One file at a time: every harness builds and runs the same real binary (run/test/server) and
# starts real servers; serialising removes build/write races. Ports and state dirs are isolated.
node --test --test-concurrency=1 tools/*.test.mjs > results/node-test.log 2>&1
node --test --test-concurrency=1 --test-reporter=spec tools/*.test.mjs > results/node-test.log 2>&1
rc=$?
cat results/node-test.log
exit $rc
[ $rc -eq 0 ] || exit $rc
# #36: the group map's evidence is only proof if the named tests actually ran and passed. This is a
# separate post-run step because groups.test.mjs runs inside the suite it would have to inspect.
node tools/evidence.mjs results/node-test.log || exit 1