// graceful-census: bind the four staged b-files to a check.
//
// Run from anywhere:  node oversight/oeis/graceful-census/verify-staged.mjs
//
// WHY THIS FILE EXISTS. graceful-census was the trigger case for the 2026-07-20
// coverage audit (research/oeis-coverage-audit/README.md) and was repaired by
// hand before the audit ran. Reconnaissance on 2026-07-27 found the repair
// incomplete, and re-checking it against the source confirmed:
//
//   * b-friendship.txt and b-book-quadrilateral.txt were opened by NO committed
//     script anywhere in the repository. Their values existed a second time only
//     as hardcoded literals in research/graceful-census/verify.mjs:57 and :59,
//     so a corrupted b-file for those two families passed every check silently.
//   * b-fan.txt and b-helm.txt were opened by research/graceful-census/verify.mjs
//     §8 (verify.mjs:199-206), but only at their LAST line, against literals
//     baked into the same two lines. §3 recomputes the mathematics, but compares
//     to its own literal arrays, which stop one term short of the staged files
//     (fan to n=11 of 12, helm to n=6 of 7). Nothing compared those b-files term
//     by term across their range.
//   * One correction to that reconnaissance, found here and worth recording:
//     research/made-not-retold/verify.mjs:178 DOES read b-fan.txt and b-helm.txt
//     term by term and recomputes fan(2..6) and helm(3) against them. So the
//     claim "read only at the last line" was true of this directory's own gate
//     and not true of the repository as a whole. That file is another
//     directory's and is untouched here; this gate carries its own copy of the
//     coverage instead of depending on it.
//
// This script is the binding. It reads THIS directory's own b-files, so the
// deposit bundle carries its own check.
//
// COVERAGE, stated exactly, by index. 26 staged terms across four files.
//
//   b-fan.txt                 n=2..12, 11 terms
//     n=2..9   (8)  RECOMPUTED by countByVertices from the graph definition.
//     n=10..12 (3)  DRIFT-GUARDED ONLY against ./expected-extension.mjs.
//                   n=11 and n=12 additionally matched against the committed
//                   permuted-recount artifact runs/independence-fan12.out,
//                   parsed live. n=10 has neither an artifact nor an OEIS
//                   cousin and is the weakest staged term here.
//   b-friendship.txt          k=1..5, 5 terms
//     k=1..5   (5)  RECOMPUTED. Every staged term. Nothing drift-guarded.
//   b-helm.txt                n=3..7, 5 terms
//     n=3..5   (3)  RECOMPUTED.
//     n=6,7    (2)  DRIFT-GUARDED ONLY, and additionally DERIVED from the
//                   outside-author OEIS sequence A387800 via helm = 4n*A387800.
//                   n=7 also matched against runs/independence-fan12.out.
//   b-book-quadrilateral.txt  n=1..5, 5 terms
//     n=1..4   (4)  RECOMPUTED.
//     n=5      (1)  DRIFT-GUARDED ONLY, and additionally DERIVED from A387795
//                   via book = 4*n!*A387795.
//
//   Recomputed here: 20 of 26. Drift-guarded only: 6 of 26. Unbound: 0 of 26.
//
// WHY THOSE CUTOFFS AND NOT MORE. Graceful labelings blow up fast. Measured on
// 2026-07-27 (Node v22.22.2, this container), countByVertices wall time per
// term: fan(9) 4.4 s, fan(10) 41.1 s, fan(11) and fan(12) far beyond;
// friendship(4) 0.3 s, friendship(5) 23.5 s; helm(5) 1.2 s, helm(6) 50.0 s;
// book(4) 1.0 s, book(5) 73.3 s. The C++ engine (research/graceful-census/
// graceful.cpp) was measured too, since its compile is cheap at 0.72 s: it is
// only about 2-3x faster here (book(5) 33.3 s, friendship(5) 8.4 s, helm(6)
// 20.5 s, fan(10) 16.7 s, fan(11) 154.9 s), so it does not bring any additional
// term inside the budget while it would make the gate's coverage depend on
// whether g++ is installed. This gate therefore uses pure JS and its coverage is
// the same on every machine.
//
// The budget is 60 s and the measured cost is about 33 s, dominated by
// friendship(5) at 23.5 s. That one term is paid for deliberately: it is what
// takes b-friendship.txt, a file the audit found bound to nothing, to every
// staged term recomputed.
//
// ON "TWO WAYS". research/graceful-census/graceful.mjs holds two exact counters
// and they are genuinely different searches, not one algorithm twice:
// countByVertices walks VERTICES in a greedy most-constrained-first order and
// picks a label for each, while countByLabels walks the LABEL VALUES 0..m in
// order and decides which still-unlabelled vertex (if any) receives each. The
// recursion, the branching factor and the pruning order all differ; the trees
// have different shapes and different sizes. What they SHARE is the file, the
// adjacency() helper, the graph constructors in FAMILIES, and the idea of
// pruning on a used-difference bitset. So a bug in a graph constructor, or in
// the definition of gracefulness itself, would be reproduced by both. That is
// the limit of this cross-check and it is not papered over. countByLabels is
// much the slower of the two (fan(8) 42.0 s against 0.7 s), so it runs here only
// on the cheap prefix named below.
//
// This gate does NOT re-run the parts of research/graceful-census/verify.mjs
// that establish the counters are correct in the first place: the reproduction
// of six published OEIS census sequences, the Burnside canonicalisation, and the
// Lean kernel proof. Those cost about 342 s and belong there. This gate assumes
// the engine and asks a narrower question: do the staged files hold what the
// engine produces.
//
// MEASURED COST (2026-07-27, Node v22.22.2, this container): about 33 s wall.
// Each run prints its own timing, so the number above can be checked.
'use strict';

import { readStagedBfile, compareStaged, stagedSummary }
  from "../../../research/oeis-term-coverage/staged.mjs";
import { FAMILIES, countByVertices, countByLabels }
  from "../../../research/graceful-census/graceful.mjs";
import { EXPECTED_EXTENSION, EXPECTED_PROVENANCE, PUBLISHED_FD }
  from "./expected-extension.mjs";
import { readFileSync, existsSync } from "node:fs";
import { createHash } from "node:crypto";
import { dirname, resolve, join } from "node:path";
import { fileURLToPath } from "node:url";

const HERE = dirname(fileURLToPath(import.meta.url));
const ROOT = resolve(HERE, "..", "..", "..");
const BUDGET_SECONDS = 60;

// file -> family, staged index range, and the prefix this gate recomputes.
const PLAN = [
  { file: "b-fan.txt",                fam: "fan",        idxName: "n", first: 2, last: 12, recomputeTo: 9, secondWitnessTo: 7 },
  { file: "b-friendship.txt",         fam: "friendship", idxName: "k", first: 1, last: 5,  recomputeTo: 5, secondWitnessTo: 3 },
  { file: "b-helm.txt",               fam: "helm",       idxName: "n", first: 3, last: 7,  recomputeTo: 5, secondWitnessTo: 3 },
  { file: "b-book-quadrilateral.txt", fam: "bookQuad",   idxName: "n", first: 1, last: 5,  recomputeTo: 4, secondWitnessTo: 3 },
];

let pass = 0, fail = 0;
const ok = (name, cond, extra) => {
  if (cond) { pass++; console.log(`  ok   ${name}`); }
  else { fail++; console.log(`  FAIL ${name}`, extra ?? ""); }
};

// stagedSummary() phrases its count as "recomputed and matched", which is only
// true when nothing mismatched. Use it verbatim in the green case; say the other
// thing plainly in the red case rather than let a helper overstate.
const coverageLine = (b, r) => r.mismatches.length === 0
  ? stagedSummary(b, r)
  : `${b.path}: ${r.checked}/${b.terms.length} staged terms recomputed, ` +
    `${r.checked - r.mismatches.length} matched, ${r.mismatches.length} DID NOT MATCH`;

const disagreements = [];
const record = (file, route, r) => { for (const m of r.mismatches) disagreements.push({ file, route, ...m }); };

// ---------------------------------------------------------------------------
console.log(`graceful-census -- staged b-file gate`);
console.log(`node ${process.version}   budget ${BUDGET_SECONDS}s\n`);
const t0 = Date.now();

// --- shape and bytes --------------------------------------------------------
console.log("SHAPE  ::  the four staged files parse, span their declared range, and are clean bytes");
const B = {};
for (const p of PLAN) {
  const rel = `oversight/oeis/graceful-census/${p.file}`;
  const b = readStagedBfile(rel);
  B[p.file] = b;
  const want = p.last - p.first + 1;
  // Truncation is the specific hazard derive.mjs creates (it rewrites all four
  // of these files from scratch), so check the range before anything excuses it.
  ok(`${p.file}: indices ${p.first}..${p.last}, no gap, ${want} terms`,
     b.first === p.first && b.last === p.last && b.terms.length === want,
     `first=${b.first} last=${b.last} count=${b.terms.length}`);
  const bytes = readFileSync(resolve(ROOT, rel));
  const text = bytes.toString("utf8");
  console.log(`       sha256 ${createHash("sha256").update(bytes).digest("hex")}  (${bytes.length} bytes)`);
  ok(`${p.file}: clean b-file text (LF only, exactly one trailing newline)`,
     !text.includes("\r") && text.endsWith("\n") && !text.endsWith("\n\n"));
}

// --- RECOMPUTED -------------------------------------------------------------
console.log("\nRECOMPUTED  ::  countByVertices, from the graph definition, no table consulted");
const recomputed = {};
const memo = new Map();
const countV = (fam, n) => {
  const k = `${fam}/${n}`;
  if (!memo.has(k)) { const g = FAMILIES[fam](n); memo.set(k, BigInt(countByVertices(g.v, g.e))); }
  return memo.get(k);
};
for (const p of PLAN) {
  const t = Date.now();
  const r = compareStaged(B[p.file], (i) => (i <= p.recomputeTo ? countV(p.fam, i) : null));
  const ms = Date.now() - t;
  console.log(`  ${coverageLine(B[p.file], r)}  [${ms} ms]`);
  ok(`${p.file}: staged ${p.idxName}=${p.first}..${p.recomputeTo} reproduced by countByVertices`,
     r.mismatches.length === 0 && r.checked === p.recomputeTo - p.first + 1,
     r.mismatches.slice(0, 5));
  record(p.file, "countByVertices", r);
  recomputed[p.file] = r;
}

// --- SECOND WITNESS ---------------------------------------------------------
console.log("\nSECOND WITNESS  ::  countByLabels, a different search tree (label-major, not");
console.log("                    vertex-major). Same file and same graph constructors, so it");
console.log("                    cannot catch a wrong constructor. Slow, hence the short range.");
const secondWitness = {};
for (const p of PLAN) {
  const t = Date.now();
  const r = compareStaged(B[p.file], (i) => {
    if (i > p.secondWitnessTo) return null;
    const g = FAMILIES[p.fam](i);
    return BigInt(countByLabels(g.v, g.e));
  });
  const ms = Date.now() - t;
  ok(`${p.file}: staged ${p.idxName}=${p.first}..${p.secondWitnessTo} also reproduced by countByLabels ` +
     `(${r.checked} terms) [${ms} ms]`,
     r.mismatches.length === 0 && r.checked === p.secondWitnessTo - p.first + 1,
     r.mismatches.slice(0, 5));
  record(p.file, "countByLabels", r);
  secondWitness[p.file] = r;
}

// --- a theorem the recomputed friendship terms have to satisfy ---------------
// Bermond-Kotzig: the k-triangle windmill is graceful iff k = 0 or 1 (mod 4).
// b-friendship.txt is fully recomputed above, so this is a check on the staged
// zeros themselves, not on a table.
{
  let agree = true; const shown = [];
  for (const t of B["b-friendship.txt"].terms) {
    const graceful = (t.index % 4 === 0 || t.index % 4 === 1);
    if ((t.value > 0n) !== graceful) agree = false;
    shown.push(`k=${t.index}:${t.value > 0n ? "pos" : "0"}`);
  }
  ok(`staged friendship zeros follow Bermond-Kotzig (graceful iff k = 0,1 mod 4): ${shown.join(" ")}`, agree);
}

// --- DERIVED FROM PUBLISHED OEIS -------------------------------------------
// helm total = 4n*A387800(n) and book total = 4*n!*A387795(n) are exact
// relations to an outside author's up-to-symmetry counts. Calibrate each
// relation on the terms this gate recomputed itself BEFORE leaning on it for
// the terms it could not, so the relation is never taken on faith.
console.log("\nDERIVED FROM PUBLISHED OEIS  ::  helm = 4n*A387800, book = 4*n!*A387795.");
console.log("                    Arithmetic on an independent author's number, not an");
console.log("                    enumeration of the graph. Calibrated on recomputed terms first.");
const fact = (k) => { let r = 1n; for (let i = 2n; i <= BigInt(k); i++) r *= i; return r; };
const derived = {
  "b-helm.txt": (n) => (PUBLISHED_FD.A387800[n] === undefined ? null : 4n * BigInt(n) * PUBLISHED_FD.A387800[n]),
  // The book relation holds for n >= 2 only (n=1 has an extra symmetry), so n=1 returns null.
  "b-book-quadrilateral.txt": (n) => (n < 2 || PUBLISHED_FD.A387795[n] === undefined ? null : 4n * fact(n) * PUBLISHED_FD.A387795[n]),
};
const derivedResult = {};
for (const [file, fn] of Object.entries(derived)) {
  const p = PLAN.find((q) => q.file === file);
  // calibration: on the recomputed prefix, relation vs the number we just enumerated
  let calOk = true; const cal = [];
  for (let i = p.first; i <= p.recomputeTo; i++) {
    const d = fn(i);
    if (d === null) continue;
    const c = countV(p.fam, i);
    cal.push(`${p.idxName}=${i}`);
    if (d !== c) calOk = false;
  }
  ok(`${file}: the published-OEIS relation is calibrated against terms this gate enumerated (${cal.join(",")})`, calOk);
  const r = compareStaged(B[file], fn);
  const idx = r.covered.join(",");
  ok(`${file}: staged ${p.idxName}=${idx} agree with the published-OEIS relation (${r.checked} terms)`,
     r.mismatches.length === 0 && r.checked > 0, r.mismatches.slice(0, 5));
  record(file, "published-OEIS relation", r);
  derivedResult[file] = r;
}

// --- COMMITTED RUN ARTIFACT -------------------------------------------------
// runs/independence-fan12.out is a seeded-vertex-permutation recount: the same
// total counted down a different search tree because the greedy order breaks
// ties by vertex id. Parsed live rather than transcribed, so the b-file is bound
// to the artifact itself.
console.log("\nCOMMITTED RUN ARTIFACT  ::  research/graceful-census/runs/independence-fan12.out");
const RUNS = join(ROOT, "research", "graceful-census", "runs", "independence-fan12.out");
const artifact = {};
let artifactPairs = 0;
if (existsSync(RUNS)) {
  const parsed = new Map(); // "fam/n" -> BigInt
  for (const line of readFileSync(RUNS, "utf8").split("\n")) {
    if (line.trim().startsWith("#")) continue;           // skip commented duplicates
    const m = /^(\w+)\((\d+)\)\s+permuted\s*=\s*(\d+)\s*$/.exec(line.trim());
    if (m) parsed.set(`${m[1]}/${m[2]}`, BigInt(m[3]));
  }
  ok(`artifact parsed: ${[...parsed.keys()].join(", ")}`, parsed.size >= 3, `${parsed.size} entries`);
  for (const file of ["b-fan.txt", "b-helm.txt"]) {
    const p = PLAN.find((q) => q.file === file);
    const r = compareStaged(B[file], (i) => parsed.get(`${p.fam}/${i}`) ?? null);
    artifact[file] = r;
    artifactPairs += r.checked;
    if (r.checked === 0) { ok(`${file}: artifact covers no staged index`, false); continue; }
    ok(`${file}: staged ${p.idxName}=${r.covered.join(",")} match the permuted recount (${r.checked} terms)`,
       r.mismatches.length === 0, r.mismatches.slice(0, 5));
    record(file, "permuted recount artifact", r);
  }
} else {
  // Not a silent pass: the artifact is committed, so its absence is a failure.
  ok("runs/independence-fan12.out is present", false, RUNS);
}

// --- DRIFT-GUARDED ONLY -----------------------------------------------------
console.log("\nDRIFT-GUARDED ONLY  ::  compared against ./expected-extension.mjs");
console.log("  This is NOT a recomputation. It catches truncation of a b-file and a");
console.log("  transcription slip in it. Where the same value is also derived from published");
console.log("  OEIS data or matched against the run artifact above, that is the stronger");
console.log("  binding and it is reported separately. See expected-extension.mjs for the");
console.log("  file:line provenance of every value below.");
const guarded = {};
for (const p of PLAN) {
  const tbl = EXPECTED_EXTENSION[p.file];
  if (!tbl) { guarded[p.file] = { checked: 0, covered: [], mismatches: [] }; continue; }
  const prov = EXPECTED_PROVENANCE[p.file];
  for (const [i, v] of tbl) {
    const row = prov.get(i);
    console.log(`  ${p.fam}(${i}) = ${v}  ${row.recomputedElsewhere
      ? "(recomputed by a committed script elsewhere: see its citations)"
      : "(NOT recomputed by any committed script; artifact / published-OEIS bindings only)"}`);
    for (const c of row.from) console.log(`      <- ${c}`);
  }
  const r = compareStaged(B[p.file], (i) => (tbl.has(i) ? tbl.get(i) : null));
  ok(`${p.file}: staged ${p.idxName}=${r.covered.join(",")} match the provenance-commented table ` +
     `(drift guard, not recomputation)`,
     r.mismatches.length === 0 && r.checked === tbl.size, r.mismatches.slice(0, 5));
  record(p.file, "expected-extension table (drift guard)", r);
  guarded[p.file] = r;
}

// --- nothing left unbound ---------------------------------------------------
console.log("\nCLOSURE  ::  every staged index is reached by at least one route");
let unboundTotal = 0;
for (const p of PLAN) {
  const reached = new Set([
    ...(recomputed[p.file]?.covered ?? []),
    ...(guarded[p.file]?.covered ?? []),
    ...(derivedResult[p.file]?.covered ?? []),
    ...(artifact[p.file]?.covered ?? []),
  ]);
  const unbound = B[p.file].terms.map((t) => t.index).filter((i) => !reached.has(i));
  unboundTotal += unbound.length;
  ok(`${p.file}: every staged index recomputed or bound (none left unbound)`,
     unbound.length === 0, `unbound: ${unbound.join(",")}`);
}

// ---------------------------------------------------------------------------
const secs = ((Date.now() - t0) / 1000).toFixed(1);

if (disagreements.length) {
  // A disagreement is a DISCOVERY, not a typo. Do not edit a b-file.
  console.log("\nSTAGED TERMS THAT COULD NOT BE REPRODUCED (do not \"fix\" the b-file, report this):");
  for (const d of disagreements.slice(0, 40)) {
    console.log(`  ${d.file} index ${d.index}: staged ${d.staged}, got ${d.recomputed} (via ${d.route})`);
  }
}

ok(`whole gate finished inside its ${BUDGET_SECONDS}s budget (${secs}s)`,
   Number(secs) <= BUDGET_SECONDS, `${secs}s`);

const totalStaged = PLAN.reduce((a, p) => a + B[p.file].terms.length, 0);
const totalRecomputed = PLAN.reduce((a, p) => a + recomputed[p.file].checked, 0);
const totalGuarded = PLAN.reduce((a, p) => a + (guarded[p.file]?.checked ?? 0), 0);

console.log("\nPER FILE:");
for (const p of PLAN) {
  const g = guarded[p.file];
  const gTxt = g && g.checked
    ? `${g.checked} drift-guarded only (${p.idxName}=${g.covered.join(",")}, NOT recomputed)`
    : "0 drift-guarded (every staged term recomputed)";
  console.log(`  ${p.file.padEnd(26)} ${recomputed[p.file].checked}/${B[p.file].terms.length} recomputed ` +
              `(${p.idxName}=${p.first}..${p.recomputeTo}); ${gTxt}`);
}
console.log(`  ${totalRecomputed} of ${totalStaged} staged terms recomputed; ${totalGuarded} drift-guarded only; ` +
            `${unboundTotal} unbound. ${artifactPairs} of the drift-guarded also matched a committed run artifact.`);

// Every number and every range in the summary line is derived from what this
// run actually did. Nothing here is a hardcoded description of the intended
// coverage: if a range is narrowed or a term goes unbound, the line says so.
const rangeOf = (p, cov) => cov.length
  ? `${p.fam} ${p.idxName}=${cov[0]}..${cov[cov.length - 1]}`
  : `${p.fam} none`;
const recomputedRanges = PLAN.map((p) => rangeOf(p, recomputed[p.file].covered)).join(", ");
const guardedRanges = PLAN.filter((p) => guarded[p.file]?.checked)
  .map((p) => rangeOf(p, guarded[p.file].covered)).join(", ") || "none";
const matched = totalRecomputed - new Set(
  disagreements.filter((d) => d.route === "countByVertices").map((d) => `${d.file}/${d.index}`)).size;

console.log(`\n${fail === 0 ? "ALL PASS" : "FAILURES PRESENT"}  -  ${pass}/${pass + fail} checks; ` +
            `${matched}/${totalStaged} staged terms RECOMPUTED and matched (${recomputedRanges}), ` +
            `${totalGuarded}/${totalStaged} drift-guarded only (${guardedRanges}), ` +
            `${unboundTotal} unbound, in ${secs}s`);
process.exit(fail === 0 ? 0 : 1);
