Files
RingBRP/tools/check-lethality.mjs
T
slaguru666andClaude Opus 5 4cfacd47fe check-lethality compares exactly, because it already seeded per creature (R-97)
I asked for this on a false premise of my own: I reported that adding a
creature shifted a shared random stream and perturbed every other
creature's recorded number. That is not true and the code never did it.
measure() builds its own mulberry32 from the seed on every call, and
check-lethality calls it once per creature, so a creature's numbers do
not depend on its neighbours or its position. Measured rather than
argued: inserting a creature ahead of the barghest changes 0 of 47
existing entries. The file's own claim — "the only thing that can move
the number is a change to the rules or to the creature" — was accurate
all along, and my last commit message says otherwise. It is wrong.

The real cause, found by replaying each commit against the baseline as
committed at 4b71859:

  4b71859  baseline recorded            0 of 46 differ
  322389b  bestiary                     0 of 46 differ
  ddc4f99  hit locations reach combat  26 of 46 differ   <-- here
  a90c4f3 .. e5dc9b5                   26 of 46 differ

ddc4f99 routed every ordinary blow through the hit location table. That
is the largest change the combat system has had and it moved 26 of 46
creatures, which is correct and expected. What is not correct is that
nobody noticed for four commits: each creature moved by one or two
points, the guard allowed six, and it reported OK while describing a
game nobody was playing.

So the tolerance goes. It exists for sampling noise and there is no
sampling noise here — same party, same seed, same counts, and two
recordings of unchanged code are byte-identical. Anything that moves is
a real change, which is the entire point of the file. `rounds` is now
compared too; it was recorded and then never read, so a creature could
take a round longer to kill forever without a word.

Because exactness only means something if the measurement is exact, the
guard now proves it instead of assuming it: one creature measured twice
must come back identical, and it says so plainly if a future change
reaches for Math.random.

Negative-tested. A 2% change to locationMaxHp now trips 8 creatures at
+1.5 and +0.5 points of wipe rate — every one of which the old tolerance
would have passed. Breaking determinism is caught and named.

Also fixes update-readme, which advertised 8 guards while the build ran
9: check-anatomy was added without touching the list, which is precisely
what the comment above that list already warned had happened once. The
list is no longer trusted — it is checked against the `check` script in
package.json, and refuses to write a README advertising a different set
than the build runs.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-09-12 22:22:19 +01:00

170 lines
8.2 KiB
JavaScript

/**
* check-lethality — no creature may quietly become something else.
*
* The seven guards before this one check that content is WELL FORMED. None of them
* checks what it DOES. A creature can validate perfectly, pack perfectly, and have
* become twice as dangerous as it was last week because somebody adjusted a damage
* modifier, a hit-point formula or the armour on a service vest. That change is
* invisible in a diff of the creature, because the creature did not change.
*
* This is the guard the creature-forge plan called for, built as a regression test
* rather than as a set of hand-declared bands. Bands were the plan's design and they
* are the wrong one here: declaring "keepers: dangerous" on forty-six creatures means
* inventing forty-six judgements, and the judgement that matters is not "is this
* dangerous" but "is this the same as it was". A baseline answers that exactly, needs
* no authoring, and cannot be argued with.
*
* node tools/check-lethality.mjs compare against the committed baseline
* node tools/check-lethality.mjs --update re-record it (after a deliberate change)
* node tools/check-lethality.mjs --verbose print every creature, not just drift
*
* WHY A FIXED PARTY. --spread exists because one number cannot describe an encounter:
* the Act Three standoff runs 0% to 100% depending which four agents were picked. That
* is true and it is why this guard does NOT try to describe danger. It measures the
* same creature against the same four agents with the same seed, so the only thing that
* can move the number is a change to the rules or to the creature. The party below is
* deliberately mixed — two armed postings and two trades — so that a change affecting
* either kind of agent shows up, and it is frozen for reproducibility rather than
* chosen for realism.
*/
import { readFile, writeFile } from "node:fs/promises";
import { existsSync } from "node:fs";
import path from "node:path";
import { NPCS } from "./content.mjs";
import { ROSTER } from "./roster.mjs";
import { measure } from "./simulate.mjs";
const ROOT = path.resolve(path.dirname(new URL(import.meta.url).pathname.replace(/^\/([A-Za-z]:)/, "$1")), "..");
const BASELINE = path.join(ROOT, "tools", "lethality-baseline.json");
const argv = process.argv.slice(2);
const UPDATE = argv.includes("--update");
const VERBOSE = argv.includes("--verbose");
/* Frozen. Changing this invalidates every recorded number, so if it ever must change,
change it in the same commit as a --update and say why in the message. */
const PARTY_KEYS = ["pc_holloway", "pc_okonkwo", "pc_nkemdirim", "pc_ferriby"];
const RUNS = 200;
const SEED = 11;
/* NO TOLERANCE, deliberately. The reasoning it replaces sounded right — "200 runs of a
coin flip has a standard error around 3.5 points, so anything under 6 is inside the
noise" — and it is exactly backwards for this measurement. Sampling error would apply
if the runs were random; they are not. The guard used to allow six points of wipe
rate and a third of an agent before it complained, which sounds prudent and was why it
sat silent through the largest combat change the system has had: ddc4f99 routed every
ordinary blow through the hit location table, 26 of 46 creatures moved, and not one
of them moved far enough in a single number to trip the threshold. The baseline went
four commits describing a game nobody was playing.
A tolerance is for noise, and there is none here: same party, same seed, same counts,
and measure() builds its own generator per creature, so two recordings of unchanged
code are byte-identical. Anything that moves is a real change to the rules or to the
creature, which is exactly what this file exists to notice. `rounds` is compared too;
it was recorded and then ignored, so a creature could take a round longer to kill
forever without a word. */
const party = PARTY_KEYS.map(k => {
const found = ROSTER.find(r => r.key === k);
if (!found) {
console.error(`check-lethality: the frozen party names "${k}", which is not on the roster.`);
process.exit(1);
}
return found;
});
/** Solo, because a creature is the unit under test — counts are an encounter's business. */
const current = {};
for (const spec of NPCS) {
const r = measure(party, [spec], { runs: RUNS, seed: SEED });
current[spec.key] = {
wipe: Number((r.wipeRate * 100).toFixed(1)),
down: Number(r.downMean.toFixed(2)),
rounds: r.roundsMedian
};
}
if (UPDATE) {
await writeFile(BASELINE, JSON.stringify({
note: "Generated by tools/check-lethality.mjs --update. Do not edit by hand.",
party: PARTY_KEYS, runs: RUNS, seed: SEED,
creatures: current
}, null, 2) + "\n", "utf8");
console.log(`check-lethality: baseline recorded — ${Object.keys(current).length} creatures, `
+ `party ${PARTY_KEYS.map(k => k.replace(/^pc_/, "")).join(", ")}, ${RUNS} runs, seed ${SEED}`);
process.exit(0);
}
if (!existsSync(BASELINE)) {
console.error("check-lethality: no baseline. Run with --update to record one.");
process.exit(1);
}
const base = JSON.parse(await readFile(BASELINE, "utf8"));
/* The recorded numbers mean nothing if they were taken under different conditions, and
a guard comparing incomparable numbers is worse than no guard. */
if (base.runs !== RUNS || base.seed !== SEED
|| base.party.join() !== PARTY_KEYS.join()) {
console.error("check-lethality: FAILED — the baseline was recorded under different conditions "
+ `(party ${base.party.join(",")}, ${base.runs} runs, seed ${base.seed}). Re-record it with --update.`);
process.exit(1);
}
/* Comparing exactly is only honest if the measurement IS exact. Prove it here rather
than trust it: one creature, measured twice, must come back identical. If a future
change reaches for Math.random or a Set iteration order, this says so instead of
letting the whole guard degrade into noise-chasing. */
{
const probe = NPCS[0];
const a = measure(party, [probe], { runs: RUNS, seed: SEED });
const b = measure(party, [probe], { runs: RUNS, seed: SEED });
const shape = r => JSON.stringify([r.wipeRate, r.downMean, r.roundsMedian, r.hurtMean]);
if (shape(a) !== shape(b)) {
console.error("check-lethality: FAILED — the simulation is not deterministic, so an exact "
+ `baseline cannot mean anything. ${probe.key} measured twice gave ${shape(a)} and ${shape(b)}.`);
process.exit(1);
}
}
const problems = [];
const added = [], removed = [];
for (const [key, now] of Object.entries(current)) {
const was = base.creatures[key];
if (!was) { added.push(key); continue; }
if (now.wipe === was.wipe && now.down === was.down && now.rounds === was.rounds) continue;
const dWipe = now.wipe - was.wipe, dDown = now.down - was.down;
const bits = [];
if (now.wipe !== was.wipe)
bits.push(`wiped ${was.wipe}% -> ${now.wipe}% (${dWipe >= 0 ? "+" : ""}${dWipe.toFixed(1)})`);
if (now.down !== was.down)
bits.push(`down ${was.down} -> ${now.down} (${dDown >= 0 ? "+" : ""}${dDown.toFixed(2)} of 4)`);
if (now.rounds !== was.rounds)
bits.push(`rounds ${was.rounds} -> ${now.rounds}`);
problems.push({ key, dWipe, text: `${key}: ${bits.join(", ")}` });
}
for (const key of Object.keys(base.creatures)) if (!(key in current)) removed.push(key);
if (VERBOSE) {
for (const [key, now] of Object.entries(current)) {
console.log(` ${key.padEnd(22)} ${String(now.wipe).padStart(5)}% wiped ${now.down.toFixed(2)} down ${now.rounds} rounds`);
}
}
if (added.length) console.log(` note: ${added.length} new creature(s) not in the baseline — ${added.join(", ")}`);
if (removed.length) console.log(` note: ${removed.length} creature(s) gone from content — ${removed.join(", ")}`);
if (problems.length) {
console.error(`check-lethality: FAILED — ${problems.length} of ${Object.keys(current).length} `
+ `creature(s) fight differently than recorded`);
problems.sort((a, b) => Math.abs(b.dWipe) - Math.abs(a.dWipe));
for (const p of problems) console.error(" " + p.text);
console.error("\n If this was deliberate, re-record with --update and say what changed in the commit.");
process.exit(1);
}
console.log(`check-lethality: OK — ${Object.keys(current).length} creatures, every one fighting `
+ `exactly as recorded against the frozen party`
+ `${added.length ? `, ${added.length} new` : ""}`);