budgetbench / check.mjs
n3r's picture
Pulse Local 0.4.19 rows, the 0.6B checker, 25 October 2026
66f16a0 verified
Raw History Blame Contribute Delete
13.5 kB
#!/usr/bin/env node
// BudgetBench GUARD. Fails (exit 1) when:
// 1. a frozen file's hash differs from FROZEN.sha256, or a file was added to or removed from a frozen folder;
// 2. the sealed split's plain files are present and differ from sealed.sha256;
// 3. a household no longer regenerates byte for byte from its config (the generator is deterministic);
// 4. the oracle cannot compute a gold for some turn, or disagrees with eval v0's reference.py on a classic case;
// or its new_merchants measure (v1.0.3) disagrees with an independent computation on the public households;
// 5. the grader's adversarial checks fail (grader/check.mjs: oracle answers right, wrong figures, months, sides,
// currencies, offered-wrong choices, taps, not sure, refusals; plus fixed probes);
// 6. the v2 sealed split's guard fails when its plain files are present (check-sealed-v2.mjs: hashes against
// sealed-v2.sha256, households regenerate, every gold computes, the grader's checks on its golds).
// 7. the v3 sealed split's guard fails when its plain files are present (check-sealed-v3.mjs, the same checks).
// node budgetbench/check.mjs (from pulse-local/ or anywhere)
// node budgetbench/check.mjs --write re-writes FROZEN.sha256 and sealed.sha256 (ONLY at a version bump, with a
// CHANGELOG entry; never to make a run pass)
import {createHash} from "node:crypto";
import {spawnSync} from "node:child_process";
import fs from "node:fs";
import os from "node:os";
import path from "node:path";
import {fileURLToPath, pathToFileURL} from "node:url";
const BB = path.dirname(fileURLToPath(import.meta.url));
const WRITE = process.argv.includes("--write");
let failures = 0;
const fail = (m) => { failures++; console.log(`FAIL ${m}`); };
const ok = (m) => console.log(`ok ${m}`);
const sha = (f) => createHash("sha256").update(fs.readFileSync(f)).digest("hex");
const walk = (d) => fs.existsSync(d) ? fs.readdirSync(d, {withFileTypes: true}).flatMap((e) => e.isDirectory() ? walk(path.join(d, e.name)) : [path.join(d, e.name)]) : [];
const rel = (f) => path.relative(BB, f).split(path.sep).join("/");
// what is frozen: the data, the gold and the scorer (runners and systems are recorded per run in inputs.json)
const FROZEN_DIRS = ["cases/public", "households/public", "households/classic", "oracle", "grader", "help"];
const FROZEN_FILES = ["households/gen.mjs", "households/csv.mjs", "households/sources.mjs", "households/public.config.mjs", "households/templates.mjs", "writers/BRIEF.md", "writers/validate.mjs", "writers/make-packet.mjs", "systems/tools.mjs"];
const SEALED_DIRS = ["sealed/cases", "sealed/households", "sealed/personas"];
const SEALED_FILES = ["sealed/households.config.mjs", "sealed/AUDIT-LOG.md"];
const listOf = (dirs, files) => [...dirs.flatMap((d) => walk(path.join(BB, d))), ...files.map((f) => path.join(BB, f))]
.filter((f) => !/(^|\/)(__pycache__|\.DS_Store)/.test(rel(f))).map(rel).sort();
const manifest = (list) => list.map((f) => `${sha(path.join(BB, f))} ${f}`).join("\n") + "\n";
function verify(name, file, list) {
const want = new Map(fs.readFileSync(path.join(BB, file), "utf8").trim().split("\n").map((l) => { const [h, ...p] = l.split(" "); return [p.join(" "), h]; }));
const have = new Set(list);
let bad = 0;
for (const [f, h] of want) {
if (!have.has(f)) { fail(`${name}: ${f} is missing`); bad++; continue; }
if (sha(path.join(BB, f)) !== h) { fail(`${name}: ${f} changed (hash differs from ${file})`); bad++; }
}
for (const f of list) if (!want.has(f)) { fail(`${name}: ${f} was added to a frozen folder`); bad++; }
if (!bad) ok(`${name}: ${want.size} files match ${file}`);
}
const pub = listOf(FROZEN_DIRS, FROZEN_FILES);
const sealedHere = fs.existsSync(path.join(BB, "sealed/cases"));
if (WRITE) {
fs.writeFileSync(path.join(BB, "FROZEN.sha256"), manifest(pub));
if (sealedHere) fs.writeFileSync(path.join(BB, "sealed.sha256"), manifest(listOf(SEALED_DIRS, SEALED_FILES)));
console.log(`wrote FROZEN.sha256 (${pub.length} files)${sealedHere ? " and sealed.sha256" : ""}`);
}
verify("public split", "FROZEN.sha256", pub);
if (sealedHere) verify("sealed split", "sealed.sha256", listOf(SEALED_DIRS, SEALED_FILES));
else console.log(`-- sealed split: plain files not here (expected outside the release machine); ${fs.readFileSync(path.join(BB, "sealed.sha256"), "utf8").trim().split("\n").length} hashes on record`);
// 3. determinism: regenerate every household into a temporary folder and compare byte for byte
{
const tmp = fs.mkdtempSync(path.join(os.tmpdir(), "bb-regen-"));
const configs = [["public", "households/public.config.mjs", "households/public"], ...(sealedHere ? [["sealed", "sealed/households.config.mjs", "sealed/households"]] : [])];
for (const [name, cfg, dir] of configs) {
const out = path.join(tmp, name);
const r = spawnSync(process.execPath, [path.join(BB, "households/gen.mjs"), path.join(BB, cfg), out], {encoding: "utf8"});
if (r.status !== 0) { fail(`${name} households: the generator failed: ${r.stderr.slice(0, 300)}`); continue; }
let diff = 0;
for (const f of walk(path.join(BB, dir))) { const g = path.join(out, path.relative(path.join(BB, dir), f)); if (!fs.existsSync(g) || sha(g) !== sha(f)) { diff++; if (diff < 4) fail(`${name} households: ${rel(f)} does not regenerate byte for byte`); } }
if (!diff) ok(`${name} households regenerate byte for byte from ${cfg}`);
}
fs.rmSync(tmp, {recursive: true, force: true});
}
// 4. every gold computes; the two oracles agree on the classic household
{
const {loadHousehold, goldOf} = await import(pathToFileURL(path.join(BB, "oracle/oracle.mjs")).href);
for (const [split, cdir, hdir] of [["public", "cases/public", "households/public"], ...(sealedHere ? [["sealed", "sealed/cases", "sealed/households"]] : [])]) {
let turns = 0, cases = 0, errs = 0;
const hhs = new Map();
for (const f of walk(path.join(BB, cdir)).filter((x) => x.endsWith(".jsonl"))) for (const l of fs.readFileSync(f, "utf8").split("\n").filter(Boolean)) {
const c = JSON.parse(l); cases++;
if (!hhs.has(c.household)) hhs.set(c.household, loadHousehold(path.join(BB, hdir, c.household)));
for (const t of c.turns) { turns++; try { goldOf(hhs.get(c.household), t.meaning); } catch (e) { errs++; if (errs < 4) fail(`${split} ${c.id}: ${e.message}`); } }
}
if (!errs) ok(`${split}: every gold computes (${cases} cases, ${turns} turns)`);
}
const hh = loadHousehold(path.join(BB, "households/public/p-classic"));
let agree = 0, differ = 0;
for (const l of fs.readFileSync(path.join(BB, "cases/public/classic.jsonl"), "utf8").split("\n").filter(Boolean)) {
const c = JSON.parse(l), ref = c.reference_gold, g = goldOf(hh, c.turns[0].meaning).gold;
const same = ref.type === "money" || ref.type === "percent" ? g.type === ref.type && Math.abs(g.value - ref.value) < 0.005
: ref.type === "count" ? g.type === "count" && [g.value, ...(g.alt ?? [])].includes(ref.value)
: ref.type === "name" ? g.type === "names" && ref.any.includes(g.all[0][0]) : g.type === ref.type;
if (same) agree++; else { differ++; fail(`classic ${c.id}: oracle ${JSON.stringify(g)} vs reference.py ${JSON.stringify(ref)}`); }
}
if (!differ) ok(`two independent oracles agree on all ${agree} classic cases (oracle/oracle.mjs vs eval v0 reference.py)`);
// (and reference.py still computes the frozen golds itself)
const py = spawnSync("python3", [path.join(BB, "households/classic/make_cases.py")], {encoding: "utf8"});
if (py.status !== 0) fail(`make_cases.py failed: ${py.stderr.slice(0, 200)}`);
else if (py.stdout !== fs.readFileSync(path.join(BB, "cases/public/classic.jsonl"), "utf8")) fail("cases/public/classic.jsonl is not what make_cases.py (reference.py) writes");
else ok("classic.jsonl is exactly what reference.py's generator writes");
}
// 4b. the oracle's new_merchants measure (added 2026-10-22, before the v3 sealed writers) against a second, independent
// computation on every public household: for each currency and each month after the first, the shops with a purchase
// that month and none in any earlier month; plus spans, a category scope, an exclusion, the refusals and pinned answers.
{
const {loadHousehold, goldOf} = await import(pathToFileURL(path.join(BB, "oracle/oracle.mjs")).href);
const NOT_SPEND = new Set(["Income", "Transfers", "Debt Payments"]);
let n = 0, bad = 0;
const namesOf = (g) => g.type === "none" ? [] : g.type === "names" ? g.all.map((a) => a[0]).sort() : null;
const same = (what, g, want) => { n++; const got = namesOf(g); if (got == null || JSON.stringify(got) !== JSON.stringify([...want].sort())) { bad++; if (bad < 6) fail(`new_merchants ${what}: oracle ${JSON.stringify(got)}, independent ${JSON.stringify([...want].sort())}`); } };
const throws = (what, hh, m) => { n++; try { goldOf(hh, m); bad++; fail(`new_merchants ${what}: no error`); } catch { /* refused, as it must be */ } };
for (const id of fs.readdirSync(path.join(BB, "households/public")).sort()) {
const hh = loadHousehold(path.join(BB, "households/public", id));
// (independent: the months in which each shop bought, per currency, from the raw rows)
const bought = new Map();
for (const r of hh.rows) if (!NOT_SPEND.has(r.group) && r.amount < 0) { const k = `${r.currency}|${r.merchant}`; if (!bought.has(k)) bought.set(k, new Set()); bought.get(k).add(r.month); }
const newIn = (cur, ks, keep = () => true) => [...bought].filter(([k, ms]) => k.startsWith(`${cur}|`) && keep(k.slice(cur.length + 1)) && ks.some((x) => ms.has(x)) && ![...ms].some((x) => x < ks[0] && !ks.includes(x))).map(([k]) => k.slice(cur.length + 1));
for (const cur of [...new Set(hh.rows.map((r) => r.currency))]) for (const k of hh.months.slice(1)) same(`${id} ${cur} ${k}`, goldOf(hh, {act: "lookup", measure: "new_merchants", months: [k], currency: cur}).gold, newIn(cur, [k]));
if (hh.months.length >= 3) same(`${id} span`, goldOf(hh, {act: "lookup", measure: "new_merchants", months: hh.months.slice(1, 3)}).gold, newIn(hh.home, hh.months.slice(1, 3)));
const cat = hh.rows.find((r) => r.category === "Groceries" && r.currency === hh.home) ? "Groceries" : null;
if (cat) same(`${id} ${cat}`, goldOf(hh, {act: "lookup", measure: "new_merchants", category: cat, months: [hh.months[1]]}).gold, newIn(hh.home, [hh.months[1]], (mm) => hh.rows.some((r) => r.merchant === mm && r.category === cat)));
const first = newIn(hh.home, [hh.months[1]]);
if (first.length) same(`${id} leaving out ${first[0]}`, goldOf(hh, {act: "lookup", measure: "new_merchants", months: [hh.months[1]], exclude: {merchants: [first[0]]}}).gold, first.slice(1));
throws(`${id} first month`, hh, {act: "lookup", measure: "new_merchants", months: [hh.months[0]]});
throws(`${id} all`, hh, {act: "lookup", measure: "new_merchants", months: "all"});
}
// (pinned: the euro card of the two-currency household opens in September 2026; no dollar shop is new that month)
const mc = loadHousehold(path.join(BB, "households/public/p-multicurrency"));
same("p-multicurrency EUR 2026-09 pinned", goldOf(mc, {act: "lookup", measure: "new_merchants", account: "Revolut EUR", months: ["2026-09"]}).gold, ["Café de Flore", "Le Petit Bistro", "Monoprix", "SNCF"]);
same("p-multicurrency USD 2026-09 pinned", goldOf(mc, {act: "lookup", measure: "new_merchants", months: ["2026-09"]}).gold, []);
if (!bad) ok(`oracle new_merchants agrees with an independent computation on the public households (${n} checks)`);
}
// 5. the grader on known answers
{
const r = spawnSync(process.execPath, [path.join(BB, "grader/check.mjs"), "--quiet"], {encoding: "utf8", maxBuffer: 64 << 20});
const last = r.stdout.trim().split("\n").at(-1);
if (r.status !== 0) { fail(`grader adversarial checks: ${last}`); console.log(r.stdout.split("\n").filter((l) => l.startsWith("FAIL")).slice(0, 10).join("\n")); }
else ok(`grader adversarial checks: ${last}`);
}
// 6. the v2 sealed split (sealed-v2/, git-ignored): its own guard, which never reads v1's sealed/ (check-sealed-v2.mjs)
{
const r = spawnSync(process.execPath, [path.join(BB, "check-sealed-v2.mjs"), "--grader"], {encoding: "utf8", maxBuffer: 64 << 20});
for (const l of r.stdout.split("\n").filter((x) => /^(ok|FAIL|--)\s/.test(x))) console.log(l.replace(/^(ok|FAIL|--)(\s+)/, "$1$2v2 sealed: "));
if (r.status !== 0) fail("the v2 sealed split's guard (check-sealed-v2.mjs)");
}
// 7. the v3 sealed split (sealed-v3/, git-ignored): its own guard, which never reads sealed/ or sealed-v2/ (check-sealed-v3.mjs)
{
const r = spawnSync(process.execPath, [path.join(BB, "check-sealed-v3.mjs"), "--grader"], {encoding: "utf8", maxBuffer: 64 << 20});
for (const l of r.stdout.split("\n").filter((x) => /^(ok|FAIL|--)\s/.test(x))) console.log(l.replace(/^(ok|FAIL|--)(\s+)/, "$1$2v3 sealed: "));
if (r.status !== 0) fail("the v3 sealed split's guard (check-sealed-v3.mjs)");
}
console.log(failures ? `\nBUDGETBENCH CHECK FAILED (${failures})` : "\nBUDGETBENCH CHECK PASSED");
process.exit(failures ? 1 : 0);