#!/usr/bin/env node
// verify-cut-list.mjs — the check behind /tools/cut-list/.
//
// Three kinds of assertion, and the mix is the point.
//
//   AGAINST SOMEBODY ELSE'S NUMBERS. Every integrality gap published in Table 1
//   of Kartak, Kurz, Ripatti & Scheithauer, "Minimal proper non-IRUP instances
//   of the one-dimensional cutting stock problem", Discrete Applied Mathematics
//   187 (2015) 120-129 (arXiv:1405.5988), re-derived here from the instance
//   data alone.
//
//   AGAINST A SECOND INSTRUMENT OF OUR OWN. The LP value from column generation
//   is compared with the same LP solved over EVERY pattern, enumerated by brute
//   force. The optimum from the branch and bound is compared with an
//   independent exhaustive assignment search. This pair is not decoration: it
//   caught a real traceback bug in the knapsack that made the LP value too low
//   and would have shipped weaker bounds on every page load.
//
//   AGAINST ITSELF, ON PURPOSE. Negative controls. A doctored certificate must
//   be rejected; an over-full board must be caught by the auditor; a plan that
//   cuts the wrong number of pieces must fail. A checker that cannot fail is
//   not a checker, so each of these is run in both directions.
//
//   AGAINST AN OPTIMUM SOMEBODY ELSE PROVED. Named instances from BPPLIB, with
//   the board count and the certified bound both asserted EQUAL to stated
//   values. Everything else in this file about the plan is an inequality, and
//   an inequality has a free direction: nothing above section 16 fails if the
//   search simply gets worse, or if the bound comes out correct but weak. The
//   sibling tool in this repo shipped a verifier whose only assertions were
//   "bound <= optimum" and "bound <= any supplied answer", and three separately
//   broken implementations passed all of them while reporting a figure sixty
//   times too weak. The question to run on any suite here is: WHICH ASSERTION
//   FAILS IF THE ANSWER IS MERELY WEAK RATHER THAN WRONG?
//
//   Sections 12 to 16 were added on 2026-09-04 with the warm-started master
//   (lp.mjs), the neighbourhood search (cns.mjs) and the split-out knapsack
//   (knapsack.mjs). Each of those sections names, in its own header, the
//   mutation that makes it go red, because a check nobody has watched fail is
//   not a check.
//
//   node research/cut-list/verify-cut-list.mjs
//   node research/cut-list/verify-cut-list.mjs --quick
//
// Sections 14 and 16 read the BPPLIB cache at research/cut-list/bench-cache/,
// which is gitignored and filled by `node research/cut-list/bpplib.mjs --fetch`.
// A missing cache FAILS those assertions by name rather than skipping them: a
// fixture that quietly does not run is the most expensive kind of green.

import fs from 'node:fs';
import path from 'node:path';
import { fileURLToPath } from 'node:url';
import {
  solve, normalise, scaleDown, simplex, certify, buildCertificate, lpRelaxation,
  auditPlan, boundedKnapsack, boundedKnapsackInt, exactSearch, consolidateOffcut, dffProposals,
  statusFor,
} from '../../public/tools/cut-list/engine.mjs';
import { parseLength, formatLength, parseList, parseStock, buildJob } from '../../public/tools/cut-list/units.mjs';
import { SPECIMENS, PUZZLE } from '../../public/tools/cut-list/specimens.mjs';
// The three modules split out or written on 2026-09-04, imported from where they LIVE
// rather than through the engine's re-exports. The re-exports are then checked to be
// the same objects, so this file tests the code the page actually loads.
import { simplex as coldSimplex, Master } from '../../public/tools/cut-list/lp.mjs';
import { cnsPack } from '../../public/tools/cut-list/cns.mjs';
import {
  boundedKnapsack as knapsackBoundedKnapsack,
  boundedKnapsackInt as knapsackBoundedKnapsackInt,
} from '../../public/tools/cut-list/knapsack.mjs';
import { loadSet } from './bpplib.mjs';

const HERE = path.dirname(fileURLToPath(import.meta.url));
const QUICK = process.argv.includes('--quick');
let pass = 0, fail = 0;
const failures = [];

function ok(cond, msg) {
  if (cond) pass++;
  else { fail++; failures.push(msg); console.error(`  FAIL  ${msg}`); }
}
function eq(a, b, msg) { ok(a === b, `${msg} (got ${a}, wanted ${b})`); }
function near(a, b, tol, msg) { ok(Math.abs(a - b) <= tol, `${msg} (got ${a}, wanted ${b} +/- ${tol})`); }
function section(title) { console.log(`\n${title}`); }

function rng(seed) {
  let s = seed >>> 0 || 1;
  return () => { s ^= s << 13; s >>>= 0; s ^= s >> 17; s ^= s << 5; s >>>= 0; return s / 4294967296; };
}

// ---------------------------------------------------------------------------
// independent re-implementations, deliberately written a different way
// ---------------------------------------------------------------------------

/**
 * Minimum bins by exhaustive assignment. Nothing shared with exactSearch: this
 * walks items in order and puts each into an existing bin or a fresh one,
 * pruning only on the incumbent. Slow, obviously correct, small inputs only.
 */
function bruteForceBins(widths, cap) {
  const n = widths.length;
  const order = widths.slice().sort((a, b) => b - a);
  let best = n;
  const bins = [];
  function rec(i) {
    if (bins.length >= best) return;
    if (i === n) { best = Math.min(best, bins.length); return; }
    const w = order[i];
    const seen = new Set();
    for (let b = 0; b < bins.length; b++) {
      if (bins[b] < w) continue;
      if (seen.has(bins[b])) continue;      // identical remaining space: same branch
      seen.add(bins[b]);
      bins[b] -= w; rec(i + 1); bins[b] += w;
    }
    if (bins.length + 1 < best) { bins.push(cap - w); rec(i + 1); bins.pop(); }
  }
  rec(0);
  return best;
}

/** The LP over EVERY feasible pattern, enumerated explicitly. No pricing. */
function lpByEnumeration(widths, demand, cap, { equality = false } = {}) {
  const m = widths.length;
  const cols = [];
  const seen = new Set();
  const a = new Array(m).fill(0);
  (function walk(i, space) {
    if (i === m) {
      if (a.some((q) => q > 0)) {
        const k = a.join(',');
        if (!seen.has(k)) { seen.add(k); cols.push(a.slice()); }
      }
      return;
    }
    const most = Math.min(demand[i], Math.floor(space / widths[i]));
    for (let q = 0; q <= most; q++) { a[i] = q; walk(i + 1, space - q * widths[i]); }
    a[i] = 0;
  })(0, cap);
  if (!cols.length) return { value: null, patterns: 0 };
  const A = [];
  for (let i = 0; i < m; i++) A.push(cols.map((c) => c[i]));
  if (equality) for (let i = 0; i < m; i++) A.push(cols.map((c) => c[i]));
  const b = equality ? demand.concat(demand) : demand.slice();
  const sol = simplex(A, b, cols.map(() => 1), m);
  return { value: sol.status === 'optimal' ? sol.obj : null, patterns: cols.length, status: sol.status };
}

/** Certificate feasibility checked by listing every pattern, not by a DP. */
function certifyByEnumeration(widths, demand, cap, num) {
  const m = widths.length;
  let best = 0;
  const a = new Array(m).fill(0);
  (function walk(i, space, val) {
    if (i === m) { if (val > best) best = val; return; }
    const most = Math.min(demand[i], Math.floor(space / widths[i]));
    for (let q = 0; q <= most; q++) walk(i + 1, space - q * widths[i], val + q * num[i]);
  })(0, cap, 0);
  return best;
}

/**
 * Bounded knapsack by listing every legal take vector. The point of comparison for
 * knapsack.mjs, and deliberately as stupid as possible: no splitting, no dynamic
 * programme, no shared state to get wrong. Small inputs only.
 */
function bruteKnapsack(weights, values, counts, cap) {
  const n = weights.length;
  let best = 0;
  (function rec(i, space, val) {
    if (i === n) { if (val > best) best = val; return; }
    const most = Math.min(counts[i], Math.floor(space / weights[i]));
    for (let q = 0; q <= most; q++) rec(i + 1, space - q * weights[i], val + q * values[i]);
  })(0, cap, 0);
  return best;
}

/**
 * Audit a cnsPack result the way `auditPlan` audits an engine plan: from the boards
 * alone. It returns bins as arrays of TYPE indices, so the two things worth checking
 * are that the type counts are exactly the demand and that no board is over capacity.
 */
function cnsCheck(res, widths, demand, cap) {
  const got = new Array(widths.length).fill(0);
  const problems = [];
  let over = 0;
  for (const b of res.bins) {
    if (!b.length) { problems.push('an empty board is in the plan'); over++; continue; }
    let load = 0;
    for (const i of b) { got[i]++; load += widths[i]; }
    if (load > cap) { problems.push(`a board carries ${load} of a ${cap} board`); over++; }
  }
  let exact = true;
  let wrong = 0;
  for (let i = 0; i < widths.length; i++) {
    if (got[i] === demand[i]) continue;
    exact = false;
    wrong++;
    if (problems.length < 4) problems.push(`part ${widths[i]}: the plan cuts ${got[i]}, the list asks for ${demand[i]}`);
  }
  // Truncated on purpose. A benchmark instance has two hundred distinct lengths and a
  // failure message naming every one of them is a failure message nobody reads.
  if (wrong > 4) problems.push(`and ${wrong - 4} more part lengths miscounted`);
  return { exact, over, boards: res.bins.length, problems: problems.join('; ') };
}

// The benchmark library, read once per set and remembered. `loadSet` parses every
// instance file in the set, so calling it per fixture would re-read 720 files to reach
// one of them.
const BENCH_MISSING = 'not in the BPPLIB cache; run `node research/cut-list/bpplib.mjs --fetch`';
const benchCache = new Map();
function benchSet(setName) {
  if (!benchCache.has(setName)) {
    let loaded = [];
    try { loaded = loadSet(setName); } catch { loaded = []; }
    benchCache.set(setName, new Map(loaded.map((i) => [i.name, i])));
  }
  return benchCache.get(setName);
}
function benchInstance(setName, name) { return benchSet(setName).get(name) || null; }
/** How many instances the cache actually holds for a set, so a count can be checked. */
function benchSetSize(setName) { return benchSet(setName).size; }
/** Whether the cache is populated at all: without it there is nothing to check against. */
function benchAvailable() { return benchSetSize('Hard28') > 0; }

function ffdCount(cap, widths) {
  const bins = [];
  for (const w of widths.slice().sort((x, y) => y - x)) {
    let t = -1;
    for (let b = 0; b < bins.length; b++) if (bins[b] >= w) { t = b; break; }
    if (t < 0) { bins.push(cap); t = bins.length - 1; }
    bins[t] -= w;
  }
  return bins.length;
}

// ---------------------------------------------------------------------------
// 1. units
// ---------------------------------------------------------------------------
section('Reading and printing lengths');
{
  eq(parseLength('2400', 'metric').ticks, 24000, 'metric plain millimetres');
  eq(parseLength('2400mm', 'metric').ticks, 24000, 'metric with a unit');
  eq(parseLength('240cm', 'metric').ticks, 24000, 'metric centimetres');
  eq(parseLength('2.4m', 'metric').ticks, 24000, 'metric metres');
  eq(parseLength('3.2', 'metric').ticks, 32, 'metric tenths survive');
  eq(parseLength('36', 'imperial').ticks, 36 * 64, 'whole inches');
  eq(parseLength('36 1/2', 'imperial').ticks, 36 * 64 + 32, 'inches with a fraction');
  eq(parseLength('36-1/2', 'imperial').ticks, 36 * 64 + 32, 'inches hyphenated');
  eq(parseLength('1/8', 'imperial').ticks, 8, 'a bare fraction');
  eq(parseLength("12'", 'imperial').ticks, 144 * 64, 'feet');
  eq(parseLength(`3' 6"`, 'imperial').ticks, 42 * 64, 'feet and inches');
  eq(parseLength('18', 'bare').ticks, 18, 'a bare number');
  ok(parseLength('banana', 'metric') === null, 'nonsense is rejected, metric');
  ok(parseLength('banana', 'imperial') === null, 'nonsense is rejected, imperial');
  ok(parseLength('2400mm', 'bare') === null, 'a unit is rejected where there are no units');
  eq(formatLength(24000, 'metric'), '2400 mm', 'printing metric');
  eq(formatLength(36 * 64 + 32, 'imperial'), '36 1/2"', 'printing a fraction');
  eq(formatLength(36 * 64 + 8, 'imperial'), '36 1/8"', 'printing eighths');
  eq(formatLength(18, 'bare'), '18', 'printing bare');

  const l = parseList('4 x 900 - shelf\n900 x 4\n# a comment\n\n1800', 'metric', { maxStock: 24000 });
  eq(l.errors.length, 0, 'a clean list has no errors');
  eq(l.pieces.length, 3, 'three entries read');
  eq(l.pieces[0].qty, 4, 'quantity before the length, the house convention');
  eq(l.pieces[0].label, 'shelf', 'the label is kept');
  eq(l.pieces[1].qty, 900, 'the house convention is applied even when it reads oddly');
  ok(l.pieces[1].alt && l.pieces[1].alt.qty === 4, 'and the other reading is offered rather than silently chosen');
  eq(l.pieces[1].alt.length, 9000, 'the other reading has the right length');
  ok(l.pieces[2].alt === null, 'a line with one number has no other reading');
  const bad = parseList('4 x banana\n900', 'metric');
  eq(bad.errors.length, 1, 'a bad line is reported, not skipped in silence');
  eq(bad.errors[0].line, 1, 'the bad line is named by number');

  const st = parseStock('2400 @ 18.40\n3600 x 3 @ 25.90\n4800', 'metric');
  eq(st.errors.length, 0, 'a clean stock list has no errors');
  eq(st.stock[0].price, 1840, 'price read as whole minor units');
  eq(st.stock[1].count, 3, 'a limited count is read');
  ok(st.stock[2].count === null, 'no count means unlimited');
}

// ---------------------------------------------------------------------------
// 2. kerf arithmetic
// ---------------------------------------------------------------------------
section('Kerf and trim arithmetic');
{
  // every-cut: n pieces cost n kerfs, so the leftover is always separable.
  const r1 = solve({ stock: [{ length: 2400 }], pieces: [{ length: 797, qty: 3 }], kerf: 3 });
  eq(r1.boards.length, 1, 'three 797s and three 3 mm cuts fill 2400 exactly');
  eq(r1.boards[0].offcut, 0, 'and leave nothing');
  const r2 = solve({ stock: [{ length: 2400 }], pieces: [{ length: 798, qty: 3 }], kerf: 3 });
  eq(r2.boards.length, 2, 'one millimetre more per piece and it needs two boards');

  // last-piece-to-end: the final cut is skipped, so one more kerf is available.
  const r3 = solve({ stock: [{ length: 2400 }], pieces: [{ length: 798, qty: 3 }], kerf: 3, kerfModel: 'last-piece-to-end' });
  eq(r3.boards.length, 1, 'letting the last piece run to the end saves the board');
  eq(r3.boards[0].remainder, 0, 'with nothing left over');

  // the flagged case: leftover thinner than the blade
  const r4 = solve({ stock: [{ length: 2400 }], pieces: [{ length: 1198, qty: 2 }], kerf: 3, kerfModel: 'last-piece-to-end' });
  eq(r4.boards[0].remainder, 1, 'one millimetre of board past the last piece');
  ok(r4.boards[0].tightFinalCut, 'and it is flagged, because a 3 mm blade cannot take a 1 mm cut');
  eq(r4.boards[0].offcut, 0, 'so there is no offcut to claim');

  // trims come off the usable length exactly
  const r5 = solve({ stock: [{ length: 2400 }], pieces: [{ length: 790, qty: 3 }], kerf: 3, leadTrim: 10, tailTrim: 11 });
  eq(r5.prob.stock[0].usable, 2379, 'lead and tail trim both come off');
  eq(r5.boards.length, 1, '3 x 790 + 3 kerfs = 2379 still fits the trimmed board');
  const r6 = solve({ stock: [{ length: 2400 }], pieces: [{ length: 790, qty: 3 }], kerf: 3, leadTrim: 10, tailTrim: 12 });
  eq(r6.boards.length, 2, 'one more millimetre of trim and it does not');

  // a stated shortfall is a real reduction, not a warning
  const r7 = solve({ stock: [{ length: 2400 }], pieces: [{ length: 797, qty: 3 }], kerf: 3, shortfall: 1 });
  eq(r7.boards.length, 2, 'planning for boards 1 mm short costs a board here');
}

// ---------------------------------------------------------------------------
// 3. the auditor, in both directions
// ---------------------------------------------------------------------------
section('The plan auditor, and what it refuses');
{
  const input = { stock: [{ length: 2400 }], pieces: [{ length: 800, qty: 4 }], kerf: 3 };
  const r = solve(input);
  ok(r.audit.ok, 'a real plan passes its own audit');
  const prob = normalise(input);

  // negative control 1: an over-full board
  const overfull = [{ stockIndex: 0, pieces: [{ index: 0, length: 800 }, { index: 0, length: 800 }, { index: 0, length: 800 }, { index: 0, length: 800 }] }];
  const a1 = auditPlan(prob, overfull);
  ok(!a1.ok && /over-full/.test(a1.problems.join(' ')), 'an over-full board is caught');

  // negative control 2: too few pieces
  const short = [{ stockIndex: 0, pieces: [{ index: 0, length: 800 }] }];
  const a2 = auditPlan(prob, short);
  ok(!a2.ok && /asks for 4/.test(a2.problems.join(' ')), 'a plan that cuts too few pieces is caught');

  // negative control 3: a piece nobody asked for
  const extra = [{ stockIndex: 0, pieces: [{ index: 0, length: 800 }, { index: 0, length: 500 }] }];
  const a3 = auditPlan(prob, extra);
  ok(!a3.ok && /never asked for/.test(a3.problems.join(' ')), 'an invented piece is caught');

  // negative control 4: more boards than exist
  const limited = normalise({ stock: [{ length: 2400, count: 1 }], pieces: [{ length: 800, qty: 4 }], kerf: 3 });
  const a4 = auditPlan(limited, [
    { stockIndex: 0, pieces: [{ index: 0, length: 800 }, { index: 0, length: 800 }] },
    { stockIndex: 0, pieces: [{ index: 0, length: 800 }, { index: 0, length: 800 }] },
  ]);
  ok(!a4.ok && /only 1 are available/.test(a4.problems.join(' ')), 'using stock that is not there is caught');
}

// ---------------------------------------------------------------------------
// 4. the certificate
// ---------------------------------------------------------------------------
section('The certificate, and what it refuses');
{
  const input = { stock: [{ length: 100 }], pieces: [{ length: 45, qty: 4 }, { length: 30, qty: 5 }, { length: 22, qty: 3 }], kerf: 0 };
  const prob = normalise(input);
  const r = solve(input);
  ok(r.bound.verified, 'the shipped bound carries a verified certificate');
  ok(r.bound.value <= r.boards.length + 1e-9, 'and never exceeds a plan that exists');

  const cert = r.bound.certificate;
  const base = certify(prob, cert);
  ok(base.valid, 'the certificate re-verifies from its own numbers');

  // negative control 1: double every dual. The bound doubles; it must be refused.
  const doubled = { ...cert, num: cert.num.map((v) => v * 2) };
  ok(!certify(prob, doubled).valid, 'doubling the certificate is refused');

  // negative control 2: inflate the largest dual until the bound exceeds the truth
  const idx = cert.num.indexOf(Math.max(...cert.num));
  const inflated = { ...cert, num: cert.num.slice() };
  inflated.num[idx] = Math.ceil(inflated.num[idx] * 1.5) + cert.denom;
  const infl = certify(prob, inflated);
  ok(!infl.valid || infl.value <= r.boards.length + 1e-9,
    'an inflated certificate is either refused or still below a plan that exists');

  // negative control 3: a negative dual
  const negative = { ...cert, num: cert.num.slice() };
  negative.num[0] = -1;
  ok(!certify(prob, negative).valid, 'a negative dual is refused');

  // negative control 4: charging for stock that is unlimited
  const freeStock = { ...cert, stockNum: [cert.denom] };
  ok(!certify(prob, freeStock).valid, 'a scarcity charge on unlimited stock is refused');

  // the DP verdict against an explicit enumeration of every pattern
  const { widths, caps } = scaleDown(prob);
  const d = prob.pieces.map((p) => p.qty);
  const byDp = boundedKnapsackInt(widths, cert.num, d, caps[0]);
  const byEnum = certifyByEnumeration(widths, d, caps[0], cert.num);
  eq(byDp, byEnum, 'the exact knapsack agrees with listing every pattern by hand');

  // and the bound really is a bound, on many small random instances
  const rnd = rng(31337);
  let checked = 0;
  for (let t = 0; t < (QUICK ? 40 : 200); t++) {
    const cap = 40 + Math.floor(rnd() * 60);
    const m = 2 + Math.floor(rnd() * 4);
    const pieces = [];
    for (let i = 0; i < m; i++) pieces.push({ length: 5 + Math.floor(rnd() * (cap * 0.7)), qty: 1 + Math.floor(rnd() * 4) });
    const res = solve({ stock: [{ length: cap }], pieces, kerf: 0 }, { timeMs: 1500 });
    if (!res.boards.length) continue;
    const widthsR = res.prob.pieces.map((p) => p.width);
    const flat = [];
    res.prob.pieces.forEach((p) => { for (let q = 0; q < p.qty; q++) flat.push(p.width); });
    if (flat.length > 13) continue;
    const trueOpt = bruteForceBins(flat, res.prob.stock[0].capacity);
    checked++;
    ok(res.bound.value <= trueOpt + 1e-9, `certified bound ${res.bound.value} must not exceed the true optimum ${trueOpt}`);
    ok(res.audit.ok, 'random instance: the plan audits clean');
    if (res.status === 'optimal') eq(res.boards.length, trueOpt, 'a plan called optimal really is the exhaustive optimum');
    ok(res.boards.length >= trueOpt, 'the solver never claims fewer boards than are possible');
  }
  ok(checked > (QUICK ? 15 : 80), `enough random instances were exhaustively settled (${checked})`);
}

// ---------------------------------------------------------------------------
// 5. column generation against brute-force enumeration
// ---------------------------------------------------------------------------
section('Column generation against an enumeration of every pattern');
{
  const rnd = rng(99991);
  let n = 0;
  for (let t = 0; t < (QUICK ? 25 : 120); t++) {
    const cap = 30 + Math.floor(rnd() * 50);
    const m = 2 + Math.floor(rnd() * 4);
    const pieces = [];
    for (let i = 0; i < m; i++) pieces.push({ length: 4 + Math.floor(rnd() * (cap * 0.6)), qty: 1 + Math.floor(rnd() * 3) });
    const prob = normalise({ stock: [{ length: cap }], pieces, kerf: 0 });
    if (!prob.pieces.length || prob.impossible.length) continue;
    const { widths, caps } = scaleDown(prob);
    const d = prob.pieces.map((p) => p.qty);
    for (const equality of [false, true]) {
      const cg = lpRelaxation(prob, [1], { capped: true, equality });
      const be = lpByEnumeration(widths, d, caps[0], { equality });
      if (be.value == null || cg.value == null) continue;
      near(cg.value, be.value, 1e-7, `column generation matches full enumeration (${equality ? 'equality' : 'at least'})`);
    }
    n++;
  }
  ok(n > (QUICK ? 10 : 50), `enough LPs cross-checked (${n})`);
}

// ---------------------------------------------------------------------------
// 6. the published gaps
// ---------------------------------------------------------------------------
section('Every gap published in Kartak, Kurz, Ripatti & Scheithauer (2015), Table 1');
{
  const TABLE = [
    ['m=9  L=104 (a)', 104, [7, 12, 16, 19, 22, 27, 30, 36, 40], 103 / 104],
    ['m=9  L=104 (b)', 104, [11, 15, 18, 20, 24, 27, 28, 32, 34], 103 / 104],
    ['m=10 L=81', 81, [4, 6, 6, 9, 16, 29, 32, 37, 40, 62], 1],
    ['m=10 L=89', 89, [4, 6, 7, 10, 18, 32, 35, 41, 44, 68], 1],
    ['m=10 L=101', 101, [5, 7, 8, 11, 20, 36, 40, 46, 50, 78], 1],
    ['m=10 L=142', 142, [7, 10, 11, 16, 28, 51, 56, 65, 70, 108], 1],
    ['m=11 L=155', 155, [9, 12, 12, 16, 16, 46, 46, 54, 69, 77, 102], 126 / 125],
    ['m=11 L=193', 193, [11, 15, 15, 20, 20, 57, 58, 67, 86, 96, 127], 126 / 125],
    ['m=11 L=204', 204, [12, 16, 16, 21, 21, 60, 61, 71, 91, 101, 134], 126 / 125],
    ['m=11 L=207', 207, [12, 16, 16, 21, 22, 61, 62, 72, 92, 103, 136], 126 / 125],
    ['m=11 L=218', 218, [13, 17, 17, 22, 23, 64, 65, 76, 97, 108, 143], 126 / 125],
    ['m=11 L=221', 221, [13, 17, 17, 23, 23, 65, 66, 77, 98, 110, 145], 126 / 125],
    ['m=12 L=18', 18, [4, 4, 6, 6, 6, 7, 7, 9, 9, 9, 10, 12], 31 / 30],
    ['m=13 L=34', 34, [8, 8, 10, 11, 11, 12, 12, 13, 13, 17, 17, 17, 18], 53 / 50],
    ['m=13 L=48', 48, [11, 11, 14, 15, 16, 17, 17, 18, 19, 24, 24, 24, 25], 53 / 50],
    ['m=14 L=42', 42, [7, 7, 10, 10, 12, 15, 15, 21, 21, 21, 22, 22, 28, 31], 17 / 16],
    ['m=14 L=50', 50, [8, 9, 12, 12, 14, 18, 18, 25, 25, 25, 26, 26, 33, 37], 17 / 16],
  ];
  let matched = 0;
  for (const [name, L, lengths, published] of TABLE) {
    const input = { stock: [{ length: L }], pieces: lengths.map((l) => ({ length: l, qty: 1 })), kerf: 0 };
    const prob = normalise(input);
    const zc = lpRelaxation(prob, [1], { capped: true, equality: true }).value;
    const r = solve(input, { timeMs: 30000, restarts: 40 });
    eq(r.status, 'optimal', `${name}: the optimum is settled`);
    ok(r.audit.ok, `${name}: the plan audits clean`);
    const gap = r.boards.length - zc;
    near(gap, published, 1e-9, `${name}: the integrality gap matches the published value`);
    if (Math.abs(gap - published) < 1e-9) matched++;
  }
  eq(matched, TABLE.length, 'all seventeen published gaps reproduce');
}

// ---------------------------------------------------------------------------
// 7. the exact search against exhaustive assignment
// ---------------------------------------------------------------------------
section('Branch and bound against exhaustive assignment');
{
  const rnd = rng(4242);
  let n = 0;
  for (let t = 0; t < (QUICK ? 60 : 300); t++) {
    const cap = 20 + Math.floor(rnd() * 40);
    const count = 4 + Math.floor(rnd() * 8);
    const flat = [];
    for (let i = 0; i < count; i++) flat.push(2 + Math.floor(rnd() * (cap * 0.75)));
    const byLen = new Map();
    for (const l of flat) byLen.set(l, (byLen.get(l) || 0) + 1);
    const pieces = [...byLen.entries()].map(([length, qty]) => ({ length, qty }));
    const prob = normalise({ stock: [{ length: cap }], pieces, kerf: 0 });
    if (prob.impossible.length) continue;
    const { widths, caps } = scaleDown(prob);
    const demand = prob.pieces.map((p) => p.qty);
    const r = exactSearch(widths, demand, [{ cap: caps[0], cost: 1, count: Infinity }], Infinity, 0, { timeMs: 4000 });
    if (!r.proved) continue;
    const scaledFlat = [];
    prob.pieces.forEach((p, i) => { for (let q = 0; q < p.qty; q++) scaledFlat.push(widths[i]); });
    const truth = bruteForceBins(scaledFlat, caps[0]);
    eq(r.cost, truth, 'branch and bound finds the exhaustive optimum');
    n++;
  }
  ok(n > (QUICK ? 30 : 150), `enough exact searches cross-checked (${n})`);
}

// ---------------------------------------------------------------------------
// 8. the shipped specimens
// ---------------------------------------------------------------------------
section('The specimens the page ships');
{
  for (const spec of SPECIMENS) {
    const job = buildJob(spec);
    eq(job.errors.length, 0, `${spec.id}: the specimen text parses cleanly`);
    const r = solve(job.input, { timeMs: 30000, restarts: 40 });
    ok(r.audit.ok, `${spec.id}: the plan audits clean`);
    eq(r.status, spec.expect.status, `${spec.id}: status`);
    eq(r.boards.length, spec.expect.boards, `${spec.id}: board count`);
    if (spec.expect.proof) eq(r.proof, spec.expect.proof, `${spec.id}: kind of proof`);
    if (spec.expect.bound != null) eq(r.bound.integer, spec.expect.bound, `${spec.id}: certified bound`);
    if (spec.expect.money != null) eq(r.objective.value, spec.expect.money, `${spec.id}: cost`);
    if (spec.expect.ffd != null) {
      const flat = [];
      r.prob.pieces.forEach((p) => { for (let q = 0; q < p.qty; q++) flat.push(p.width); });
      eq(ffdCount(r.prob.stock[0].capacity, flat), spec.expect.ffd, `${spec.id}: first-fit decreasing really does use that many`);
      ok(spec.expect.ffd > spec.expect.boards, `${spec.id}: and that is more than the optimum`);
    }
    // determinism: the same job twice is the same plan
    const again = solve(buildJob(spec).input, { timeMs: 30000, restarts: 40 });
    eq(JSON.stringify(again.boards.map((b) => b.pieces.map((p) => p.length))),
      JSON.stringify(r.boards.map((b) => b.pieces.map((p) => p.length))),
      `${spec.id}: the same job gives the same plan twice`);
  }
}

// ---------------------------------------------------------------------------
// 9. the puzzle the page invites you to try
// ---------------------------------------------------------------------------
section('The puzzle: 12 pieces, a board of 18, and five boards that will not do');
{
  eq(PUZZLE.pieces.reduce((a, b) => a + b, 0), PUZZLE.total, 'the pieces add up to what the page prints');
  ok(PUZZLE.total <= PUZZLE.boards * PUZZLE.capacity, 'five boards hold more material than there is');
  const truth = bruteForceBins(PUZZLE.pieces.slice(), PUZZLE.capacity);
  eq(truth, PUZZLE.truth, 'and yet exhaustive assignment needs six');
  eq(truth, 6, 'six, specifically');
  // the same answer from the other instrument
  const r = solve({ stock: [{ length: PUZZLE.capacity }], pieces: PUZZLE.pieces.map((l) => ({ length: l, qty: 1 })), kerf: 0 }, { timeMs: 20000 });
  eq(r.boards.length, 6, 'branch and bound agrees');
  eq(r.bound.integer, 5, 'while the certified bound stops at five');
  eq(r.proof, 'search', 'so the proof here is the search, not the certificate, and the page says so');
}

// ---------------------------------------------------------------------------
// 10. consolidating the offcut
// ---------------------------------------------------------------------------
section('Gathering the waste into one usable length');
{
  const input = { stock: [{ length: 2400 }], kerf: 3, pieces: [
    { length: 1800, qty: 2 }, { length: 760, qty: 5 }, { length: 800, qty: 2 }, { length: 745, qty: 4 },
  ] };
  // A case where gathering the waste genuinely helps.
  const loose = { stock: [{ length: 2400 }], kerf: 3, pieces: [
    { length: 1100, qty: 5 }, { length: 700, qty: 4 }, { length: 500, qty: 3 },
  ] };
  const baseL = solve(loose, { timeMs: 8000 });
  const floorL = Math.max(...baseL.boards.map((b) => b.offcut));
  eq(floorL, 1394, 'the plain plan leaves a longest offcut of 1394');
  const conL = consolidateOffcut(loose, baseL.boards.length, { timeMs: 8000, floor: floorL });
  ok(conL && conL.improved, 'gathering the waste finds something longer');
  eq(conL.reserve, 1694, 'and it is 1694, on the same number of boards');
  eq(conL.boards.length, baseL.boards.length, 'the board count does not move');
  ok(conL.maximal, 'and one more tick is proved to cost a board, so 1694 is the limit');
  const auditL = auditPlan(normalise(loose), conL.boards);
  ok(auditL.ok, `the gathered plan still cuts exactly the list: ${auditL.problems.join('; ')}`);

  // A case where the plan already gathers as well as any plan can. The honest
  // report is not "nothing found" but "nothing longer exists", and only the
  // decisive probe earns that word.
  const base = solve(input, { timeMs: 8000 });
  const longestBefore = Math.max(...base.boards.map((b) => b.offcut));
  eq(longestBefore, 904, 'the bookcase plan already leaves a 904 offcut');
  const con = consolidateOffcut(input, base.boards.length, { timeMs: 6000, floor: longestBefore });
  ok(con && !con.improved, 'and nothing longer is found');
  ok(con && con.maximal, 'because one more millimetre is proved to cost a seventh board');
}

// ---------------------------------------------------------------------------
// 11. the knapsack traceback, the bug that actually happened
// ---------------------------------------------------------------------------
section('The knapsack never takes more of a piece than exists');
{
  const rnd = rng(20260817);
  let bad = 0, n = 0;
  for (let t = 0; t < (QUICK ? 200 : 1500); t++) {
    const m = 2 + Math.floor(rnd() * 8);
    const cap = 20 + Math.floor(rnd() * 200);
    const w = [], v = [], c = [];
    for (let i = 0; i < m; i++) { w.push(1 + Math.floor(rnd() * (cap / 2))); v.push(rnd() * 10); c.push(1 + Math.floor(rnd() * 4)); }
    const kp = boundedKnapsack(w, v, c, cap);
    let weight = 0, value = 0;
    for (let i = 0; i < m; i++) {
      if (kp.take[i] > c[i]) bad++;
      weight += kp.take[i] * w[i];
      value += kp.take[i] * v[i];
    }
    if (weight > cap) bad++;
    if (Math.abs(value - kp.value) > 1e-6) bad++;
    n++;
  }
  eq(bad, 0, `the returned pattern is always legal and worth what the DP says (${n} random knapsacks)`);
}

// ---------------------------------------------------------------------------
// 12. the bounded knapsack returns the BEST pattern, not merely a legal one
// ---------------------------------------------------------------------------
// Section 11 asks whether the pattern that comes back is legal and worth what the
// dynamic programme says it is worth. Both of those hold for a knapsack that quietly
// returns a WORSE pattern than the best one, and a knapsack that returns a worse
// pattern is a certificate checker that accepts weights it should refuse and a column
// generator that stops before the linear program has converged. So this section asks
// the other question, against a complete enumeration of every legal take vector.
//
// RED ON PURPOSE, measured on a copy of the tool rather than guessed at:
//
//   · knapsack.mjs `boundedKnapsack`, the backward loop `c >= w` becomes `c > w`. The
//     first assertion below fails on 159 of 800 instances. Every assertion in section 11
//     stays green, because the pattern that comes back is still legal and still worth
//     exactly what the dynamic programme claims: only smaller than the best one. The
//     converged-LP-value fixtures in section 16 fail as well, since this routine is what
//     prices a column, which is the coverage the two sections buy each other.
//   · the same change in `boundedKnapsackInt`, which has a loop of its own: the second
//     assertion fails on 150 of 800, and so does the scarcity negative control in
//     section 15, because a weakened exact knapsack accepts a certificate it should be
//     refusing. That is the failure mode this routine exists to prevent.
section('The bounded knapsack returns the best pattern, not merely a legal one');
{
  ok(boundedKnapsack === knapsackBoundedKnapsack, 'the engine re-exports the routine knapsack.mjs defines');
  ok(boundedKnapsackInt === knapsackBoundedKnapsackInt, 'and the exact one too, so this section tests what ships');
  const rnd = rng(0xbee5ac);
  let worseFloat = 0, worseInt = 0, n = 0;
  for (let t = 0; t < (QUICK ? 150 : 800); t++) {
    const m = 2 + Math.floor(rnd() * 4);
    const cap = 12 + Math.floor(rnd() * 40);
    const w = [], v = [], vi = [], c = [];
    for (let i = 0; i < m; i++) {
      w.push(1 + Math.floor(rnd() * Math.max(1, Math.floor(cap / 2))));
      v.push(Math.round(rnd() * 1000) / 100);
      vi.push(1 + Math.floor(rnd() * 20));
      c.push(1 + Math.floor(rnd() * 3));
    }
    const kp = boundedKnapsack(w, v, c, cap);
    if (Math.abs(kp.value - bruteKnapsack(w, v, c, cap)) > 1e-6) worseFloat++;
    if (boundedKnapsackInt(w, vi, c, cap) !== bruteKnapsack(w, vi, c, cap)) worseInt++;
    n++;
  }
  eq(worseFloat, 0, `the floating-point knapsack is exhaustively optimal (${n} instances)`);
  eq(worseInt, 0, `the exact integer knapsack is exhaustively optimal (${n} instances)`);
}

// ---------------------------------------------------------------------------
// 13. the warm-started master against the cold simplex
// ---------------------------------------------------------------------------
// lp.mjs keeps both solvers on purpose: the revised, warm-started `Master` that the
// column generation now runs on, and the original dense two-phase `simplex`, which is
// slower and simpler and was here first. Two implementations that disagree is the
// signal; one implementation agreeing with itself is not evidence.
//
// The three properties are not interchangeable, and it is worth being exact about which
// direction each of them is blind in.
//
//   Equal objectives is the one that catches a master that merely STOPS SHORT. This is a
//   minimisation, so a restricted master abandoned half way reports a value that is too
//   large; the duals that go with it then fail exact certification in engine.mjs and the
//   bound the reader gets falls back to something weaker. That is not a wrong answer, and
//   it is precisely the failure that shipped before lp.mjs existed.
//
//   Strong duality says the duals belong to the basis being reported and not to some
//   other one. It is the check that a dual vector cannot pass by accident.
//
//   Dual feasibility, which is the property the whole certificate rests on, says that no
//   column prices out. It is the direction in which duals are WRONG rather than weak: a
//   dual vector scaled DOWN stays feasible and merely gives a smaller bound, while one
//   scaled UP is a claim nobody can support. `certify` is the last line against that, in
//   exact integers; this is the first.
//
// RED ON PURPOSE, measured, three mutations for the three properties. The first guess
// here was wrong and the measurement said so: removing the anti-stall switch to Bland's
// rule changed nothing at all, because random master problems of this size do not cycle.
// What follows is what actually goes red.
//
//   · `Master.#run`, the entering threshold `bestv = 1e-9` becomes `0.5`, so the master
//     stops pivoting while reduced costs are still small: 121 of 468 objectives disagree
//     with the cold simplex, 90 instances leave a column pricing out, and 102 give a
//     dual the wrong sign. The objective count is the one that matters here: it is the
//     assertion that notices a solver which is merely unfinished.
//   · `Master.duals` returns `this.#multipliers(1)` instead of `(2)`, so the duals are
//     phase one's: strong duality fails on all 468, and the scarcity charge in section 15
//     collapses with it.
//   · `Master.duals` scales its answer by 1.05 on the way out: the primal objective is
//     untouched, and dual feasibility fails on all 468. Strong duality catches this one
//     too, which is why both are here.
section('The warm-started master against the cold simplex, on the master problem shape');
{
  ok(simplex === coldSimplex, 'the engine re-exports the cold simplex lp.mjs defines');
  const rnd = rng(0x51dec0de);
  let n = 0, objMismatch = 0, dualityGap = 0, priceOut = 0, signWrong = 0;
  for (let t = 0; t < (QUICK ? 80 : 500); t++) {
    // The shape column generation actually builds: demand rows as >=, then either a
    // supply row as <= (limited stock) or a second copy of the demand rows as <=
    // (the `equality` formulation the published gaps are quoted in).
    const nGe = 2 + Math.floor(rnd() * 4);
    const mode = rnd();
    const nLe = mode < 0.4 ? 0 : (mode < 0.75 ? 1 : nGe);
    const m = nGe + nLe;
    const nCols = m + 2 + Math.floor(rnd() * 8);
    const cols = [], cost = [];
    for (let j = 0; j < nCols; j++) {
      const a = new Array(m).fill(0);
      for (let i = 0; i < nGe; i++) a[i] = Math.floor(rnd() * 3);
      if (a.every((q) => q === 0)) a[Math.floor(rnd() * nGe)] = 1;
      if (nLe === 1) a[nGe] = 1;
      else if (nLe === nGe) for (let i = 0; i < nGe; i++) a[nGe + i] = a[i];
      cols.push(a);
      cost.push(1 + Math.floor(rnd() * 4));
    }
    // Without a column covering every demand row the program is infeasible and the
    // comparison is about nothing, so make sure of it rather than discarding the draw.
    for (let i = 0; i < nGe; i++) {
      if (cols.some((a) => a[i] > 0)) continue;
      const j = i % nCols;
      cols[j][i] = 1;
      if (nLe === nGe) cols[j][nGe + i] = 1;
    }
    const b = [];
    for (let i = 0; i < nGe; i++) b.push(1 + Math.floor(rnd() * 6));
    if (nLe === 1) b.push(6 + Math.floor(rnd() * 20));
    else if (nLe === nGe) for (let i = 0; i < nGe; i++) b.push(b[i]);
    const A = [];
    for (let i = 0; i < m; i++) A.push(cols.map((a) => a[i]));

    const cold = coldSimplex(A, b, cost, nGe);
    const master = new Master(m, nGe, b);
    // Loaded in two batches on purpose. The entire reason this class exists is that a
    // column arriving AFTER the basis is optimal must not disturb it, and a test that
    // hands over every column before the first solve never exercises the warm start.
    const split = 1 + Math.floor(rnd() * (nCols - 1));
    for (let j = 0; j < split; j++) master.addColumn(cols[j], cost[j]);
    master.solve();
    for (let j = split; j < nCols; j++) master.addColumn(cols[j], cost[j]);
    const st = master.solve();
    if (cold.status !== 'optimal' || st !== 'optimal') continue;
    n++;
    const obj = master.objective();
    if (Math.abs(obj - cold.obj) > 1e-6 * (1 + Math.abs(cold.obj))) objMismatch++;
    const y = master.duals();
    let yb = 0;
    for (let i = 0; i < m; i++) yb += y[i] * b[i];
    if (Math.abs(yb - obj) > 1e-6 * (1 + Math.abs(obj))) dualityGap++;
    for (let j = 0; j < nCols; j++) {
      let z = 0;
      for (let i = 0; i < m; i++) z += y[i] * cols[j][i];
      if (z > cost[j] + 1e-6) { priceOut++; break; }
    }
    for (let i = 0; i < m; i++) if (i < nGe ? y[i] < -1e-6 : y[i] > 1e-6) { signWrong++; break; }
  }
  ok(n > (QUICK ? 40 : 300), `enough master problems were solved both ways (${n})`);
  eq(objMismatch, 0, 'the warm-started master returns the cold simplex objective');
  eq(dualityGap, 0, "the master's duals are the duals of the basis it reports");
  eq(priceOut, 0, 'no column prices out against those duals, which is what a certificate needs');
  eq(signWrong, 0, 'the duals carry the signs their stated convention promises');
}

// ---------------------------------------------------------------------------
// 14. consistent neighbourhood search, called directly
// ---------------------------------------------------------------------------
// `cnsPack` is where the plan now comes from on a single stock length, and solve()
// only ever adopts a plan of its that is SHORTER than what it already had. So a
// cnsPack that quietly returns rubbish would leave every assertion above green and
// simply cost boards, and one that returns an invalid plan would be silently
// discarded by `auditPlan`. Neither shows up unless it is called on its own.
//
// RED ON PURPOSE, measured, one mutation per claim:
//
//   · `packBoard` drops the last part of the fill it has just made (`bin.items.pop()`
//     before the sort): the multiset check fails on four of the five benchmark cases,
//     and so does "never fewer boards than the published optimum", because parts that
//     vanish are boards that vanish. 18 failures across this section and section 16.
//   · `closeOnTwoBoards` relaxed from `> st.cap` to `> 2 * st.cap`, so the second
//     reserve board is allowed to overflow: the capacity check fails on three cases.
//     Through solve() this one is invisible AS A BUG: `auditPlan` rejects the over-full
//     plan and the engine silently keeps the one it already had, so the only symptom a
//     reader ever sees is a board that was not saved.
//   · the pair reduction's `widths[i] + widths[j] !== cap` becomes `!== cap + 1`, so it
//     fixes pairs that do not fit and stops fixing the ones that do: `reduced` comes
//     back 0 on the all-pairs fixture, 2 instead of 5 on the full-board one, and the
//     capacity check fails on three benchmark cases.
section('Consistent neighbourhood search, called on its own');
{
  // The pair reduction is the one step in that file carrying a proof written above it,
  // so it gets a list made of nothing else: every part pairs with another to exactly
  // one board, so the reduction settles the whole instance and the search never runs.
  const pw = [70, 60, 50, 40, 30], pd = [3, 3, 4, 3, 3];
  const paired = cnsPack(pw, pd, 100, 0, { timeMs: 1000 });
  eq(paired.reduced, 8, 'the pair reduction fixes every board of a list that is all pairs');
  eq(paired.boards, 8, 'and eight boards is the whole plan');
  eq(paired.bins.length, 8, 'the reported count is the number of boards actually returned');
  ok(paired.bins.every((b) => b.reduce((s, i) => s + pw[i], 0) === 100), 'each fixed board is exactly full');
  const pa = cnsCheck(paired, pw, pd, 100);
  ok(pa.exact && pa.over === 0, `the paired plan cuts exactly the list, no board over-full (${pa.problems})`);
  // A part exactly one board long is the same argument with the second part empty.
  const sw = [100, 70, 30], sd = [2, 3, 3];
  const solo = cnsPack(sw, sd, 100, 0, { timeMs: 1000 });
  eq(solo.reduced, 5, 'a part that fills a board on its own is fixed the same way');
  eq(solo.boards, 5, 'and five boards is the whole plan');
  const sa = cnsCheck(solo, sw, sd, 100);
  ok(sa.exact && sa.over === 0, `the full-board plan cuts exactly the list (${sa.problems})`);

  // And then on instances whose optimum somebody else proved, with no help from the
  // engine: no start plan, no certificate, nothing but the parts and the board.
  // `ms` is set well above where each case starts to slip, because this search is on a
  // wall clock and a wall clock is the one input a test cannot hold fixed. Measured on
  // this machine: the first four settle inside 500 ms, and Hard28_BPP742 needs between
  // 500 ms and a second, so it gets eight times that.
  //
  // The floor handed to cnsPack is ZERO, not the published optimum. Passing the optimum
  // would stop the search the moment it arrived there and make "never fewer boards than
  // the optimum" a property of the argument rather than of the search, which is a check
  // that cannot fail.
  const CNS_CASES = [
    { set: 'Falkenauer_U', name: 'Falkenauer_u120_00', opt: 48, atMost: 48, ms: 2000 },
    { set: 'Falkenauer_U', name: 'Falkenauer_u120_08', opt: 50, atMost: 50, ms: 2000 },
    { set: 'Falkenauer_T', name: 'Falkenauer_t60_00', opt: 20, atMost: 20, ms: 2000 },
    { set: 'Wascher', name: 'Waescher_TEST0049', opt: 11, atMost: 11, ms: 2000 },
    { set: 'Hard28', name: 'Hard28_BPP742', opt: 64, atMost: 64, ms: 4000 },
  ];
  for (const c of CNS_CASES) {
    const inst = benchInstance(c.set, c.name);
    if (!inst) {
      for (let k = 0; k < 4; k++) ok(false, `${c.name}: ${BENCH_MISSING}`);
      continue;
    }
    const widths = inst.pieces.map((p) => p.length);
    const demand = inst.pieces.map((p) => p.qty);
    const res = cnsPack(widths, demand, inst.cap, 0, { timeMs: c.ms, perTargetMs: c.ms / 2 });
    const a = cnsCheck(res, widths, demand, inst.cap);
    ok(a.exact, `${c.name}: the plan cuts exactly the demanded multiset (${a.problems})`);
    eq(a.over, 0, `${c.name}: no board is over capacity`);
    ok(res.boards >= c.opt, `${c.name}: never fewer boards than the published optimum ${c.opt} (got ${res.boards})`);
    ok(res.boards <= c.atMost, `${c.name}: cnsPack on its own still reaches ${c.atMost} boards (got ${res.boards})`);
  }
}

// ---------------------------------------------------------------------------
// 15. the price and the supply, neither of which had any coverage at all
// ---------------------------------------------------------------------------
// Until this section the word "price" did not appear in this file. The three paths
// below are the ones where the tool can be wrong about money and stock rather than
// about geometry, and two of them are refusals, which are the easiest thing in any
// program to break without noticing: a refusal that stops refusing looks like a
// feature working.
//
// RED ON PURPOSE, measured, one per block:
//
//   · `certify`, `limit` loses its scarcity term (`cost[t] * denom` alone): the scarce
//     stock's charge comes back zero, the bound drops from 3800 to 3000, and the
//     negative control stops refusing. 3 failures.
//   · `certify`, the loop subtracting `count * stockNum` from `raw` deleted: the bound
//     comes out 5400 against a plan costing 3800, which the engine itself then calls a
//     contradiction rather than a triumph. 3 failures.
//   · `normalise`, `unpriced` forced to false: the money question is answered with a
//     two-board plan costing nothing at all, which is the lie this refusal exists to
//     stop. 2 failures.
//   · `normalise`, `shortfallOfStock` forced to false: both refusals stop firing, the
//     job comes back "unproved", and every figure in the shortfall object is undefined.
//     8 failures.
section('Prices, scarce stock, and the two questions the engine refuses');
{
  // A yard with two cheap boards and an expensive open supply. The cheap stock is
  // scarce, so its certificate carries a nonzero scarcity charge and the bound is the
  // dual value MINUS what that scarcity is worth: the term that a one-sided check
  // would never notice going missing, because dropping it makes the bound LARGER and
  // a larger bound is what a broken bound looks like.
  const yard = {
    stock: [{ length: 2400, price: 1000, count: 2 }, { length: 2400, price: 1800 }],
    pieces: [{ length: 1200, qty: 6 }],
    kerf: 0, objective: 'money',
  };
  const rj = solve(yard, { totalMs: 3000 });
  eq(rj.status, 'optimal', 'the priced job with scarce stock is settled');
  eq(rj.objective.value, 3800, 'two cheap boards and one dear one, in whole minor units');
  ok(rj.bound.verified, 'and the bound carries a verified certificate');
  const probJ = normalise(yard);
  const certJ = rj.bound.certificate;
  const again = certify(probJ, certJ);
  // Through JSON and back, which is what the page's re-check button does with the numbers
  // it reads out of the table. `certify` is a pure function of (prob, cert), so re-calling
  // it on the same objects could only ever catch nondeterminism; a round trip can catch a
  // number that does not survive being written down.
  const wire = JSON.parse(JSON.stringify({ denom: certJ.denom, num: certJ.num, stockNum: certJ.stockNum, cost: certJ.cost }));
  const afterWire = certify(probJ, wire);
  ok(afterWire.valid, 'the certificate re-verifies after a round trip through JSON, which is what the page does');
  near(afterWire.value, again.value, 1e-9, 'and to the same value');
  ok(certJ.stockNum[0] > 0, 'the scarce stock carries a nonzero scarcity charge');
  eq(certJ.stockNum[1], 0, 'and the unlimited stock carries none');
  // The bound, re-derived here by the arithmetic in the docstring rather than read off
  // the result. sum(demand_i * num_i) minus sum(count_t * stockNum_t), over denom,
  // rounded up.
  let rawJ = 0;
  probJ.pieces.forEach((p, i) => { rawJ += p.qty * certJ.num[i]; });
  probJ.stock.forEach((s, t) => { if (isFinite(s.count)) rawJ -= s.count * (certJ.stockNum[t] || 0); });
  eq(Math.ceil(rawJ / certJ.denom), rj.bound.integer, 'the printed bound is that arithmetic and nothing else');
  eq(rj.bound.integer, 3800, 'and it meets the plan, which is why the job is settled');
  // Negative control: strike the scarcity charge and the certificate must be refused,
  // because without it the limited board is being asked to carry more than it costs.
  const noCharge = { ...certJ, stockNum: certJ.stockNum.map(() => 0) };
  ok(!certify(probJ, noCharge).valid, 'striking the scarcity charge is refused');

  // Money with no prices. This used to answer in dollars derived from millimetres.
  const noPrice = solve({ stock: [{ length: 2400 }], pieces: [{ length: 800, qty: 4 }], kerf: 0, objective: 'money' }, { totalMs: 500 });
  eq(noPrice.status, 'unpriced', 'a priced question of an unpriced list is refused');
  eq(noPrice.boards.length, 0, 'and no plan is offered with it');
  eq(normalise({ stock: [{ length: 2400, price: 1840 }], pieces: [{ length: 800, qty: 4 }], objective: 'money' }).unpriced, false,
    'one priced line is enough to make the question answerable');

  // Not enough stock, the counting way: six parts longer than half a board, three
  // boards in the yard. No arrangement helps, so the answer is a refusal with a number
  // attached, and the number is itself proved.
  const shortCount = solve({ stock: [{ length: 2400, count: 3 }], pieces: [{ length: 1300, qty: 6 }], kerf: 0 }, { totalMs: 2000 });
  // `?? {}` because a suite that throws instead of failing loses every assertion after
  // the throw, and the count this file prints is then a count of nothing.
  const shortCountFall = shortCount.shortfall ?? {};
  eq(shortCount.status, 'short-of-stock', 'a yard that cannot supply the job says so');
  eq(shortCountFall.boardsAvailable, 3, 'and says how many boards it has');
  eq(shortCountFall.boardsNeededAtLeast, 6, 'and how many the parts need at minimum');
  // That figure has to be a bound and not a guess, so re-derive it two more ways: the
  // same list with the supply lifted, and exhaustive assignment.
  const opened = solve({ stock: [{ length: 2400 }], pieces: [{ length: 1300, qty: 6 }], kerf: 0 }, { totalMs: 2000 });
  eq(opened.bound.integer, shortCountFall.boardsNeededAtLeast, 'the shortfall figure is the certified bound of the same list unrestricted');
  ok(opened.bound.verified, 'which is a verified certificate');
  eq(bruteForceBins(new Array(6).fill(1300), 2400), 6, 'and exhaustive assignment agrees six is right');

  // And the material way: one board, four parts that will not fit on it.
  const shortMaterial = solve({ stock: [{ length: 2400, count: 1 }], pieces: [{ length: 800, qty: 4 }], kerf: 0 }, { totalMs: 2000 });
  const shortMaterialFall = shortMaterial.shortfall ?? {};
  eq(shortMaterial.status, 'short-of-stock', 'running out of material is the same refusal');
  eq(shortMaterialFall.need, 3200, 'the material the list needs');
  eq(shortMaterialFall.have, 2400, 'against the material the yard holds');
  eq(shortMaterialFall.boardsNeededAtLeast, 2, 'and two boards would do it');
  // The refusal must not fire on a job the yard CAN supply, or it becomes a way of
  // never being wrong.
  const enough = solve({ stock: [{ length: 2400, count: 2 }], pieces: [{ length: 800, qty: 4 }], kerf: 0 }, { totalMs: 2000 });
  eq(enough.status, 'optimal', 'a yard with exactly enough is not refused');
  eq(enough.boards.length, 2, 'and gets the two-board plan');
}

// ---------------------------------------------------------------------------
// 16. against optima other people proved, on named instances
// ---------------------------------------------------------------------------
// EVERY assertion above this line about the PLAN is either "the plan is valid" or "the
// plan is no worse than this other method of ours". Not one of them fails if the search
// simply gets worse, and the search is the half that was at fault: measured against
// BPPLIB, this engine used a board more than the proved optimum on 59 instances, and on
// 58 of those its own certificate already said the optimum was reachable. So this
// section names instances and the number of boards that must come back.
//
// The same solve pins the other side. `bound.integer` is asserted EQUAL to a stated
// number rather than merely below the optimum, and where the linear program converges
// inside the budget the value it converges to is asserted too. A bound that is correct
// but weak passes every inequality in this file, and a weak bound is exactly what
// shipped before tonight.
//
// HOW THESE WERE CHOSEN, and the choosing is most of the work. Twenty-eight candidates
// drawn from six sets were each solved six times, twice at each of 4, 6 and 8 seconds,
// and only the ones that returned the SAME board count, the same bound and the same kind
// of proof on all six runs were kept. Two were dropped for wobbling by a board between
// runs (Hard28_BPP144 gave 73 or 74, Hard28_BPP531 gave 83 or 84), and one more
// (Waescher_TEST0005)
// was dropped after it came back a board worse under load and again at a LONGER budget:
// the neighbourhood search runs on a wall clock, so more time is not monotonically
// better and a fixture has to be shown stable rather than assumed to be.
//
// The rows split three ways on purpose:
//
//   · the plan MEETS the certificate, so the bound is exactly the optimum and the proof
//     is one a stranger can re-check;
//   · ceil(LP) is one BELOW the optimum, so no LP-dual certificate can ever close the
//     gap and only the search can have found the plan. These are the five Hard28
//     instances with that property (BPP14, BPP119, BPP175, BPP359, BPP716), plus
//     Waescher_TEST0022;
//   · the ANI set, built by Delorme, Iori and Martello so that the optimum is the
//     rounded-up LP bound PLUS ONE. An engine that ever reports proof "certificate" on
//     one of those has a bug; one that reports a gap of exactly one is telling the
//     truth. Their bound is asserted to be exactly optimum minus one, so the honesty
//     control fails in both directions: a bound that creeps up to the optimum fails,
//     and a bound that sags below it fails too.
//
// The AI row is the mirror of the ANI ones: the same construction, augmented to be IRUP
// instead, so the certificate closes to the published optimum exactly even though the
// plan stays a board above it. It is the row that says the bound is not weak on an
// instance where the plan cannot confirm it.
//
// RED ON PURPOSE, measured rather than assumed, and the measuring corrected three
// guesses. Each of these was applied to a copy of the tool, the suite was run, and the
// count is what actually went red:
//
//   · engine.mjs solve(), `opts.cns ?? true` becomes `?? false` so the neighbourhood
//     search never runs: 5 rows lose a board (u120_08, u120_17, t60_00, t120_00,
//     BPP742) and their certificate assertions go with them, 10 failures. NOT the six
//     rows where the certificate cannot close the gap: on those the optimum is already
//     reached by the constructive heuristics or the exhaustive search, which is worth
//     knowing and was not the guess.
//   · `lpRelaxation`, `maxRounds` becomes 1, so the column generation stops after one
//     round: every one of the 11 rows carrying an LP value fails, both assertions each,
//     and N1W1B1R0 loses its bound and its proof on top. 24 failures. The BOUND
//     assertions on the Hard28, ANI and AI rows do not move at all, because on those
//     instances the certificate that finally wins comes from the dual feasible functions
//     and not from the linear program, which is why the LP value is asserted separately
//     rather than trusted to show up in the bound.
//   · `bestCertificate`, the LP duals multiplied by 0.9 before anything is built from
//     them. Every bound stays valid, stays below the optimum and passes every
//     inequality in this file; N1W1B1R0 and the priced job in section 15 fail on the
//     exact value, which is the whole point of asserting an equality.
section('The search\'s quality, over a whole set rather than one instance');
{
  // WHY AN AGGREGATE, when every other assertion here names one instance.
  //
  // The mutation harness found four defects nothing could see, and all four are TUNING: two
  // fewer independent starts, no retry of a failed board count, one denominator instead of
  // two, one dual feasible function instead of thirty. Each of them makes the search or the
  // bound a little worse and none of them changes the answer on any single instance the
  // fixture table names, so pinning them one instance at a time would mean hunting for a
  // knife edge and then depending on it, which is a flaky test dressed as a strict one.
  //
  // The property that is actually worth holding is the one a reader cares about: HOW MANY
  // of a set this thing settles. That is stable where a single instance is not, because a
  // change has to move several instances to move the count, and it catches a regression in
  // the search whatever knob caused it.
  //
  // The floor is set below the measured figure on purpose. At the page's own six seconds
  // this reaches the published optimum on 15 of the 17 and proves 13 of them; the floor
  // asks for 12 and 10, which leaves room for a loaded machine and still fails on any real
  // loss. If a change takes it ABOVE 15, raise the floor deliberately: that is the point.
  if (QUICK) {
    ok(true, 'the whole-set search-quality pass is skipped under --quick (it is 17 solves)');
    ok(true, 'and so is its proof count');
  } else if (!benchAvailable()) {
    ok(false, `the whole-set pass needs the BPPLIB cache: ${BENCH_MISSING}`);
    ok(false, `the whole-set pass needs the BPPLIB cache: ${BENCH_MISSING}`);
  } else {
    const insts = loadSet('Wascher');
    let atOptimum = 0, proved = 0, below = 0;
    for (const inst of insts) {
      const r = solve({ stock: [{ length: inst.cap }], pieces: inst.pieces, kerf: 0, objective: 'boards' },
        { totalMs: 6000 });
      if (r.boards.length === inst.optimum) atOptimum++;
      if (r.boards.length < inst.optimum) below++;
      if (r.status === 'optimal' && r.proof === 'certificate' && r.boards.length === inst.optimum) proved++;
    }
    eq(below, 0, 'no Wascher instance came out below its published optimum');
    ok(atOptimum >= 12, `the search reaches the published optimum on most of the Wascher set (${atOptimum} of ${insts.length})`);
    ok(proved >= 10, `and proves it by certificate on most of those (${proved} of ${insts.length})`);
  }
}

section('The linear program converges inside a budget a page could offer');
{
  // WHY THIS IS AN ASSERTION AND NOT A NOTE. The whole reason lp.mjs exists is that the
  // restricted master used to be rebuilt and re-solved from scratch on every round, which
  // on a 180-part instance is 180 ms a round and hundreds of rounds: it hit its wall clock
  // having converged nowhere, and the bound the reader got was the trivial material figure
  // with the linear program contributing nothing. Warm-starting fixed it, and nothing in
  // the suite noticed when a mutation took the warm start away, because at a generous
  // fixture budget the slow version still converges and reaches the same value.
  //
  // So what is pinned is the thing the warm start actually buys: convergence inside a
  // clock. Measured on this instance, warm start converges in about 2.2 seconds and the
  // cold version does not converge in eighteen, so a ten-second budget separates them by
  // more than four times and survives a loaded machine.
  //
  // RED ON PURPOSE: lp.mjs `if (!this.phase1Done)` -> `if (true)`, which is a cold start in
  // warm clothing.
  if (!benchAvailable()) {
    for (let k = 0; k < 3; k++) ok(false, `this needs the BPPLIB cache: ${BENCH_MISSING}`);
  } else {
    const inst = benchInstance('Hard28', 'Hard28_BPP13');
    if (!inst) {
      for (let k = 0; k < 3; k++) ok(false, `Hard28_BPP13 is ${BENCH_MISSING}`);
    } else {
      const prob = normalise({ stock: [{ length: inst.cap }], pieces: inst.pieces, kerf: 0, objective: 'boards' });
      const t0 = Date.now();
      const lp = lpRelaxation(prob, [1], { lpMs: 10000 });
      const took = Date.now() - t0;
      eq(lp.status, 'optimal', `column generation converges on a 180-part instance inside ten seconds (took ${took} ms)`);
      near(lp.value, 66.99964, 1e-4, 'and reaches the value of this instance, which is a property of the instance');
      ok(lp.rounds > 50, `having actually generated columns rather than stopping early (${lp.rounds} rounds)`);
    }
  }
}

section('The six verdicts, including the one that has never happened');
{
  // WHY THE LADDER IS A FUNCTION NOW. A mutation that deleted the CONTRADICTION branch, the
  // one that fires when a plan costs less than a bound this engine verified in exact
  // integers, left all sixteen hundred assertions untouched. Not because the suite is weak
  // but because the branch is unreachable from outside: producing that state requires a bug
  // in one of the two halves, and if there were one the suite would be failing elsewhere.
  //
  // A tripwire nothing can test is a tripwire nobody knows is connected. As a pure function
  // of six numbers it is reachable in one line, and that is the whole argument for the
  // refactor.
  //
  // RED ON PURPOSE: delete the contradiction line from `statusFor` in engine.mjs.
  const st = (o) => statusFor({ hasPlan: true, auditOk: true, boundValid: true, proved: false, ...o });
  eq(st({ objValue: 6, boundInt: 6 }), 'optimal', 'plan meets its verified bound: settled');
  eq(st({ objValue: 7, boundInt: 6 }), 'gap', 'plan above its verified bound: an interval, not a verdict');
  eq(st({ objValue: 5, boundInt: 6 }), 'contradiction',
    'plan BELOW its own verified bound: a contradiction, and the page must say so rather than report the cheaper number');
  eq(st({ objValue: 5.9999999999, boundInt: 6 }), 'optimal',
    'and floating point a hair under the bound is still "settled", not a contradiction');
  eq(st({ objValue: 7, boundInt: 6, proved: true }), 'optimal',
    'a plan above the certificate but closed by exhaustive search is settled too');
  eq(st({ objValue: 7, boundInt: 0, boundValid: false }), 'unproved',
    'no verified bound at all: nothing is settled');
  eq(st({ objValue: 7, boundInt: 6, hasPlan: false }), 'unproved', 'and no plan is not a verdict either');
  eq(st({ objValue: 6, boundInt: 6, auditOk: false }), 'plan-invalid',
    'a plan that fails its own audit is never reported as settled, whatever the bound says');
  // The order matters as much as the cases: an invalid plan must beat every other verdict,
  // and a contradiction must beat "optimal".
  eq(st({ objValue: 5, boundInt: 6, auditOk: false }), 'plan-invalid',
    'and an invalid plan outranks a contradiction, because the plan is the thing in front of the reader');
}

section('Money is refused unless every board has a price');
{
  // TWO DEFECTS, ONE AFTER THE OTHER, and the second was mine.
  //
  // Originally the money objective fell back to the board's LENGTH when no price was given,
  // so an unpriced list produced "6 boards costing $1440.00" out of millimetres. The fix
  // refused when NO line carried a price, which opened a worse hole: with one line priced
  // and one not, the unpriced board cost zero, the cheapest plan bought nothing but those,
  // and the page reported "4 boards costing $0.00", stamped proved. A board of unknown
  // price is not a free board.
  //
  // The second defect was found by the mutation harness listing `money-invents-a-price` as
  // surviving: the mutation was inert because the refusal now happens earlier, and looking
  // at why led straight to the neighbouring case nobody had tried.
  //
  // RED ON PURPOSE: change the filter in `normalise` from `unpricedLines.length > 0` back
  // to `stock.every((s) => s.price == null)`.
  const parts = [{ length: 1800, qty: 2 }, { length: 760, qty: 5 }];
  const none = solve({ stock: [{ length: 2400 }], pieces: parts, kerf: 3, objective: 'money' }, { totalMs: 2000 });
  eq(none.status, 'unpriced', 'no priced line at all: refused');
  const some = solve({ stock: [{ length: 2400, price: 1200 }, { length: 3600 }], pieces: parts, kerf: 3, objective: 'money' },
    { totalMs: 2000 });
  eq(some.status, 'unpriced', 'one line priced and one not: still refused, because an unpriced board is not a free one');
  // In whatever unit the caller used: `normalise` rounds the length it was given and does
  // not scale it, because the caller decides what a tick is. Here the call is direct, so
  // the figure is 3600 rather than the page's 36,000 tenths of a millimetre.
  ok(some.reason.includes(3600), 'and the refusal names the length of the line that is missing a price');
  const all = solve({ stock: [{ length: 2400, price: 1200 }, { length: 3600, price: 1650 }], pieces: parts, kerf: 3, objective: 'money' },
    { totalMs: 4000 });
  ok(all.status !== 'unpriced', 'every line priced: answered');
  ok(all.objective.value > 0, `and the answer is a real amount of money (${all.objective.value})`);
  // AND THE BELT BEHIND THE REFUSAL. `normalise` makes an uncostable job unreachable, so
  // this cannot be triggered through solve(); what is asserted is that the guard exists and
  // names the offending line, because the mutation harness showed that without it the
  // arithmetic goes to NaN and the solve HANGS, which in a browser is a frozen page.
  const forced = solve({ stock: [{ length: 2400, price: 1200 }, { length: 3600 }], pieces: parts, kerf: 3,
    objective: 'money' }, { totalMs: 2000 });
  ok(forced.status === 'unpriced' || forced.status === 'uncostable',
    `an unpriced line is refused by name, one way or the other (${forced.status})`);
  ok(Array.isArray(forced.reason) && forced.reason.length > 0, 'and the refusal says which line');

  // The other two objectives are unaffected by prices, and must stay so.
  const boards = solve({ stock: [{ length: 2400 }, { length: 3600 }], pieces: parts, kerf: 3, objective: 'boards' }, { totalMs: 2000 });
  ok(boards.status !== 'unpriced', 'the fewest-boards question needs no prices');
  const material = solve({ stock: [{ length: 2400 }, { length: 3600 }], pieces: parts, kerf: 3, objective: 'material' }, { totalMs: 2000 });
  ok(material.status !== 'unpriced', 'and neither does the least-material question');
}

section('A certificate of the wrong shape is a different problem\'s certificate');
{
  // WHY THIS SECTION EXISTS. `certify` checked that every numerator was a non-negative
  // whole number and never that there were the RIGHT NUMBER of them. A numerator vector one
  // entry too long returned `valid: true` with a bound of NaN: the extra term poisoned the
  // sum while the knapsack quietly ignored an item it had no width for. One too short
  // returned valid with a quietly different bound.
  //
  // It was reachable. The page's re-check button rebuilds the problem from the form and
  // reads the weights out of the table, so editing the parts box after a solve and pressing
  // re-check handed `certify` a certificate for a different problem. A serialised proof must
  // declare its own dimensions, or truncation is a silent pass.
  //
  // The mutation harness reported the shape guard as SURVIVED before this section existed,
  // which is the only reason it exists. RED ON PURPOSE: disable any one of the four length
  // or positivity guards at the top of `certify`.
  const prob = normalise({ stock: [{ length: 2400, count: 3, price: 1200 }, { length: 3600 }],
    pieces: [{ length: 800, qty: 4 }, { length: 700, qty: 3 }, { length: 500, qty: 2 }], kerf: 3, objective: 'boards' });
  const m = prob.pieces.length;
  const good = { denom: 720720, num: new Array(m).fill(1000), stockNum: [0, 0], cost: [1, 1] };
  ok(certify(prob, good).valid, 'a well-shaped certificate of small weights verifies');

  const shapes = [
    { name: 'one weight too many', cert: { ...good, num: [...good.num, 1000] } },
    { name: 'one weight too few', cert: { ...good, num: good.num.slice(0, m - 1) } },
    { name: 'no weights at all', cert: { ...good, num: [] } },
    { name: 'a scarcity weight for a stock line that does not exist', cert: { ...good, stockNum: [0, 0, 0] } },
    { name: 'a cost for a stock line that does not exist', cert: { ...good, cost: [1, 1, 1] } },
    { name: 'a denominator of zero', cert: { ...good, denom: 0 } },
    { name: 'a negative denominator', cert: { ...good, denom: -720720 } },
    { name: 'a fractional denominator', cert: { ...good, denom: 720720.5 } },
    { name: 'a negative weight', cert: { ...good, num: good.num.map((v, i) => (i === 0 ? -1 : v)) } },
    { name: 'a fractional weight', cert: { ...good, num: good.num.map((v, i) => (i === 0 ? 0.5 : v)) } },
    { name: 'a negative scarcity weight', cert: { ...good, stockNum: [-1, 0] } },
    { name: 'weights that are not an array', cert: { ...good, num: 1000 } },
  ];
  for (const sh of shapes) {
    const res = certify(prob, sh.cert);
    ok(!res.valid, `refused: ${sh.name}`);
    ok(typeof res.reason === 'string' && res.reason.length > 0, `and said why: ${sh.name}`);
    // The bound must not be a number either, because a refused certificate that still
    // hands back a figure is a figure something downstream may print.
    ok(!Number.isFinite(res.value) || res.value === 0,
      `and offered no bound: ${sh.name} (got ${res.value})`);
  }
}

section('A search that did not finish must not say it did');
{
  // THE MOST DANGEROUS DEFECT THIS TOOL CAN HAVE, and until this section existed nothing
  // in 1,643 assertions could see it.
  //
  // `exactSearch` returns `proved` only when it exhausted the space. Change that to
  // `proved: true` and the page stamps "proved by search - nothing on earth does better"
  // on a plan the search abandoned halfway. The mutation harness reported it as SURVIVED,
  // twice: the fixtures whose plan is already optimal cannot see it (a true claim about a
  // true plan), the never-certificate fixtures only assert that the proof is not a
  // CERTIFICATE, and on the hard instances the search is never even started.
  //
  // So the flag is tested where it lives, on a budget deliberately too small to finish,
  // and the invariant is tested where it matters, over instances whose optimum somebody
  // else proved.
  //
  // RED ON PURPOSE: engine.mjs `proved: !timedOut && !incomplete` -> `proved: true`.
  const w = [7, 5, 4, 3];
  const demand = [6, 6, 6, 6];
  const stocks = [{ cap: 12, cost: 1, count: Infinity }];
  const starved = exactSearch(w, demand, stocks, Infinity, 0, { timeMs: 0, nodes: 1 });
  ok(starved.timedOut, 'a search given one node reports that it stopped early');
  ok(!starved.proved, 'and does NOT report that it proved anything');
  const finished = exactSearch(w, demand, stocks, Infinity, 0, { timeMs: 20000, nodes: 5e6 });
  ok(finished.proved, 'the same search, given room, does prove it');
  ok(!finished.timedOut, 'and says it did not stop early');
  // Ten, and it is checkable by hand, which is why this instance is here rather than a
  // random one: the parts come to 6 x (7+5+4+3) = 114, and 114 over 12 is 9.5, so ten is
  // the floor; and ten is reachable as six boards of 7+5, two of 4+4+4, one of 3+3+3+3 and
  // one of 3+3. (I first wrote nine here and the assertion said otherwise, which is the
  // whole argument for writing the expected value down.)
  eq(finished.cost, 10, 'and gets the answer: ten boards of twelve for six each of 7, 5, 4 and 3');

  // The same flag through a truncated NODE, which is the other way completeness is lost:
  // a pattern list cut short makes the search non-exhaustive even though it never timed
  // out, and `incomplete` is what withholds the claim.
  const cramped = exactSearch(w, demand, stocks, Infinity, 0, { timeMs: 20000, nodes: 5e6, patternCap: 1 });
  ok(cramped.incomplete || cramped.timedOut, 'a search whose pattern list was cut short knows it');
  ok(!cramped.proved, 'and does not claim a proof either');

  // AND THE INVARIANT, over instances whose optimum somebody else proved: a job this tool
  // calls settled must use exactly as many boards as the published optimum. This is the
  // one assertion that catches a false proof of ANY kind, by certificate or by search.
  if (!benchAvailable()) {
    for (let k = 0; k < 3; k++) ok(false, `the invariant needs the BPPLIB cache: ${BENCH_MISSING}`);
  } else {
    let settled = 0, checked = 0;
    for (const set of ['Falkenauer_U', 'Wascher', 'Hard28']) {
      const insts = loadSet(set).filter((i) => i.n <= 200).slice(0, QUICK ? 3 : 9);
      for (const inst of insts) {
        const r = solve({ stock: [{ length: inst.cap }], pieces: inst.pieces, kerf: 0, objective: 'boards' },
          { totalMs: QUICK ? 2500 : 6000 });
        checked++;
        if (r.status === 'optimal') {
          settled++;
          if (r.boards.length !== inst.optimum) {
            ok(false, `${inst.name}: called the job settled at ${r.boards.length} boards, `
              + `but the published optimum is ${inst.optimum}`);
          }
        }
        if (r.boards.length < inst.optimum) {
          ok(false, `${inst.name}: ${r.boards.length} boards is below the proved optimum of ${inst.optimum}`);
        }
      }
    }
    ok(checked >= (QUICK ? 9 : 27), `the invariant was run on enough instances (${checked})`);
    ok(settled > checked * 0.3, `and enough of them were settled for it to mean anything (${settled} of ${checked})`);
    ok(true, `every job called settled used exactly the published optimum (${settled} of ${settled})`);
  }
}

section('Mixed stock, where the constructive heuristics are the whole answer');
{
  // WHY THIS SECTION EXISTS, and it exists because a mutation survived.
  //
  // `buildPlan` runs several heuristics and keeps the best. Changing it to keep the FIRST
  // valid one instead left all 1,643 assertions untouched, which is a true fact about the
  // code rather than a blind spot in it: on a single stock length the neighbourhood search
  // runs afterwards and reaches the same place from its own start, so which constructive
  // heuristic won stops mattering. On MIXED stock the search does not run at all (its
  // apparatus assumes one capacity and one board cost), and the heuristics are the entire
  // answer, and no fixture covered that.
  //
  // This job is that case, found by search rather than by taste: three part lengths on a
  // merchant's three, asked in money. The mixed-stock greedy buys $49.00 of timber and the
  // LP rounding buys $41.00, and the certificate proves $41.00 is the floor. A version
  // that kept the first plan would report $49.00 and call the job unsettled.
  //
  // RED ON PURPOSE: `research/cut-list/mutate.mjs --root <copy>` with the
  // `first-plan-not-best` mutation, which was green before this section and is red after.
  const yard = [
    { length: 2400, price: 1200 },
    { length: 3600, price: 1650 },
    { length: 4800, price: 2050 },
  ];
  const parts = [{ length: 464, qty: 2 }, { length: 1796, qty: 4 }, { length: 411, qty: 2 }];
  const r = solve({ stock: yard, pieces: parts, kerf: 3, objective: 'money' }, { totalMs: 6000 });
  ok(r.audit.ok, `the mixed-stock money plan audits clean (${r.audit.problems.join('; ')})`);
  eq(r.objective.value, 4100, 'the cheapest plan for this job costs $41.00');
  eq(r.proof, 'certificate', 'and the certificate proves it, so the job is settled');
  eq(r.bound.integer, 4100, 'and the certified floor is that same figure');
  // The point of the fixture, stated as an assertion rather than as a comment: more than
  // one heuristic produced a valid plan here and they did NOT agree, so keeping the best
  // one is load-bearing on this job.
  const valid = (r.heuristics || []).filter((h) => h.valid).map((h) => h.value);
  ok(valid.length >= 2, `more than one heuristic produced a valid plan (${valid.length})`);
  ok(Math.max(...valid) > Math.min(...valid),
    `and they disagreed, so choosing the best one matters (${valid.join(', ')})`);
  eq(r.objective.value, Math.min(...valid), 'and the plan reported is the best of them');

  // The same yard and parts asked three ways, because the objective is the fork this tool
  // makes a reader choose and the three answers should be different objects.
  const byBoards = solve({ stock: yard, pieces: parts, kerf: 3, objective: 'boards' }, { totalMs: 4000 });
  const byMaterial = solve({ stock: yard, pieces: parts, kerf: 3, objective: 'material' }, { totalMs: 4000 });
  eq(byBoards.boards.length, 2, 'asked for the fewest boards, the same job takes two');
  ok(byMaterial.objective.value >= 9000, `asked for the least material it buys at least the certified floor (${byMaterial.objective.value})`);
  ok(byMaterial.objective.value <= byBoards.boards.reduce((a, b) => a + b.stockLength, 0),
    'and no more material than the fewest-boards plan buys');
  // The board-count floor, reported beside a job asked in money, and the caveat that goes
  // with it: it is a floor on a different question and need not be attainable at once.
  ok(r.boardFloor && r.boardFloor.floor >= 1, 'a money job also carries the board-count floor');
  ok(r.boardFloor.boards === r.boards.length, 'and the board count it names is this plan\'s');

  // A SECOND JOB, BIG ENOUGH THAT NOTHING RESCUES A BAD CHOICE.
  //
  // The small job above is repaired downstream: eight parts is well inside the exhaustive
  // search's reach, so even a version that kept the worse plan ends up at the right answer
  // and the mutation stays green. This one has 462 parts, which is past the point where
  // the exhaustive search is started at all, and mixed stock, which is past the point where
  // the neighbourhood search applies. The constructive heuristics ARE the answer here, and
  // nothing downstream will cover for them.
  //
  // The assertion is deliberately not a number. Which value the LP rounding reaches depends
  // on how far the column generation got inside its share of the clock, so pinning 183,250
  // would be pinning the machine. What is pinned is the property: the two heuristics
  // disagree, and the one that is reported is the better of them.
  const many = solve({
    stock: yard,
    pieces: [
      { length: 359, qty: 64 }, { length: 1643, qty: 79 }, { length: 1045, qty: 71 },
      { length: 1183, qty: 102 }, { length: 815, qty: 55 }, { length: 333, qty: 91 },
    ],
    kerf: 3,
    objective: 'money',
  }, { totalMs: 6000 });
  ok(many.audit.ok, `the 462-part mixed-stock plan audits clean (${many.audit.problems.join('; ')})`);
  ok(!many.search, 'the exhaustive search is not reached on a job this size, as intended');
  ok(!many.cns || many.cns.skipped, 'and the neighbourhood search does not apply to mixed stock');
  const tried = (many.heuristics || []).filter((h) => h.valid).map((h) => h.value);
  ok(tried.length >= 2, `more than one heuristic produced a valid plan (${tried.length})`);
  ok(Math.max(...tried) > Math.min(...tried), `and they disagreed (${tried.join(', ')})`);
  eq(many.objective.value, Math.min(...tried),
    'and the plan reported is the better of them, with nothing downstream to cover for the choice');
  ok(many.interval && many.interval.floor > 0 && many.interval.headroom >= 0,
    'and the job still comes with a certified floor and an interval');
}

section('The certificate checker\'s second acceptance path, which skips the knapsack');
{
  // WHY THIS SECTION EXISTS. `certify` is the one function this whole tool's trust rests
  // on, and on 2026-09-04 it gained a SECOND way to say yes: a linear sufficient condition
  // in BigInt, used when the bounded knapsack would be too expensive to run. On a board
  // 1.5 million ticks long with five hundred distinct lengths that knapsack is a
  // 750-million-cell table, about eight seconds, so a page promising six had no honest way
  // to check its own certificate.
  //
  // The condition is: if every weight is at most its part's share of a board's cost, then
  // no arrangement can exceed one board's worth, because
  //     sum (num_i/denom) a_i <= (cost/C) sum w_i a_i <= (cost/C) * C = cost.
  // The implication runs ONE WAY, so the linear path can only ever accept a certificate
  // the knapsack would also accept. That is exactly what is asserted here, on random
  // problems, in both directions:
  //
  //   forward: whenever the linear path accepts, the knapsack accepts too;
  //   negative: a weight pushed one tick past its share must be refused by the linear
  //             path, so the path is not simply saying yes to everything.
  //
  // RED ON PURPOSE: change the comparison in engine.mjs from `<=` to `<= 2n *` and the
  // negative control fires; drop the `counts[i] <= 0 || v <= 0` guard and the forward
  // check fires on problems with an unused part length.
  const rnd = rng(20260904);
  let agree = 0, linearUsed = 0, refusedInflated = 0, checked = 0, controls = 0;
  const trials = QUICK ? 60 : 240;
  for (let t = 0; t < trials; t++) {
    const m = 2 + Math.floor(rnd() * 6);
    const cap = 40 + Math.floor(rnd() * 200);
    const pieces = [];
    for (let i = 0; i < m; i++) {
      pieces.push({ length: 3 + Math.floor(rnd() * (cap - 3)), qty: 1 + Math.floor(rnd() * 4) });
    }
    const input = { stock: [{ length: cap }], pieces, kerf: 0, objective: 'boards' };
    const prob = normalise(input);
    if (!prob.pieces.length || prob.impossible.length) continue;
    for (const f of dffProposals(prob, [1])) {
      const byKnapsack = buildCertificate(prob, f.u, [0], [1], 720720, { noSearch: true, maxCells: Infinity });
      const byLinear = buildCertificate(prob, f.u, [0], [1], 720720, { noSearch: true, maxCells: 0 });
      const how = byLinear.res.perStock[0];
      checked++;
      if (how && how.by === 'linear') {
        linearUsed++;
        // The whole soundness claim of the second path, in one line.
        if (byKnapsack.res.valid) agree++;
        else ok(false, `the linear path accepted a certificate the knapsack refuses (cap ${cap}, ${f.name})`);
      }
    }
    // THE NEGATIVE CONTROL, and getting it the right way round took a red light.
    //
    // The shortcut is a SUFFICIENT condition, so the thing it must never do is take
    // itself when a weight is above its share of a board. It is not required to reject
    // the certificate: a weight a hair over its share may still be perfectly valid, and
    // the knapsack is the one that gets to say so. So what is asserted is that the
    // shortcut DECLINES TO ANSWER, and the check falls through to the search.
    //
    // The first version of this counted a fall-through as a failure and demanded that
    // half of them be refusals, which is the opposite of the property, and it went red
    // 226 times out of 240 on a correct engine. That red light is the only reason this
    // paragraph exists.
    // THE SCALED capacity, not the raw one. `scaleDown` divides every width and every
    // capacity by their common divisor, so mixing a scaled width with an unscaled capacity
    // understates each part's share by that divisor and the "inflated" weight can land
    // back under it. Caught by this very assertion, on one draw in sixty.
    const { widths, caps: scaledCaps } = scaleDown(prob);
    const sc = scaledCaps[0];
    const denom = 720720;
    // Comfortably over the share, so flooring cannot absorb it: a part gets a full
    // thousandth of a board more weight than its length entitles it to.
    const num = widths.map((w) => Math.floor((w / sc) * denom));
    num[0] = Math.ceil((widths[0] / sc) * denom) + Math.ceil(denom / 1000);
    const res = certify(prob, { denom, num, stockNum: [0], cost: [1] }, { maxCells: 0 });
    const ps = res.perStock[0];
    controls++;
    if (ps && ps.by !== 'linear') refusedInflated++;
  }
  ok(checked > 100 || QUICK, `enough certificates were checked both ways (${checked})`);
  ok(linearUsed > 20, `the linear path was actually reached (${linearUsed} times of ${checked})`);
  eq(agree, linearUsed, 'every certificate the linear path accepted is one the knapsack accepts too');
  // Against the number of controls that actually RAN, not against the trial count: some
  // random draws are rejected before the control is reached, and comparing to `trials`
  // made the assertion fail by exactly that number on a correct engine.
  ok(controls > trials * 0.8, `the negative control ran on nearly every draw (${controls} of ${trials})`);
  eq(refusedInflated, controls,
    'a weight above its share of a board makes the shortcut decline to answer, every time');

  // And one hand-checkable case, because a random sweep is not a worked example. Three
  // parts of 5 on a board of 15, weights exactly 1/3 each: no board can hold more than
  // three of them, so the total is exactly 1 and the linear test must accept.
  const tri = normalise({ stock: [{ length: 15 }], pieces: [{ length: 5, qty: 3 }], kerf: 0, objective: 'boards' });
  const triRes = certify(tri, { denom: 3, num: [1], stockNum: [0], cost: [1] }, { maxCells: 0 });
  ok(triRes.valid, 'three parts of five on a board of fifteen, at a weight of a third each, verifies by the line of algebra');
  eq(triRes.perStock[0].by, 'linear', 'and it verifies without running a knapsack at all');
  const triBad = certify(tri, { denom: 3, num: [2], stockNum: [0], cost: [1] }, { maxCells: 0 });
  ok(!triBad.valid, 'and at two thirds each it is refused, because three of them would be two boards worth');
}

section('Against optima other people proved, on named benchmark instances');
{
  // One clock for the whole solve, which is how the page calls it: `totalMs` is shared
  // out between the linear program, the neighbourhood search and the exhaustive search
  // rather than handed to each of them in turn.
  //
  // AND IT IS DELIBERATELY LARGER THAN THE PAGE'S, because a wall-clock budget is not
  // reproducible. Run this suite while two other jobs have the machine and the same
  // instance gets a quarter of a core, so the assertions below stop being about the method
  // and start being about the load: measured under contention at the page's own six
  // seconds, the certified bound on Falkenauer_u120_00 came back as 36 rather than 48 and
  // eleven fixtures went red on a correct engine. The budget here is generous enough that
  // what these assertions pin is the answer the method reaches, not the answer the machine
  // had time for. The page's own budget is measured in research/cut-list/bench-results.md,
  // which is where a figure about the clock belongs.
  const FIXTURE_MS = 25000;
  // set, instance, published optimum, the board count the search must not exceed, the
  // exact certified bound, and what may be claimed about the proof.
  const FIXTURES = [
    { set: 'Falkenauer_U', name: 'Falkenauer_u120_00', opt: 48, atMost: 48, bound: 48, lp: 47.26595745, honesty: 'certificate' },
    { set: 'Falkenauer_U', name: 'Falkenauer_u120_08', opt: 50, atMost: 50, bound: 50, lp: 49.91156463, honesty: 'certificate' },
    { set: 'Falkenauer_U', name: 'Falkenauer_u120_17', opt: 52, atMost: 52, bound: 52, lp: 51.5, honesty: 'certificate' },
    { set: 'Falkenauer_T', name: 'Falkenauer_t60_00', opt: 20, atMost: 20, bound: 20, lp: 20, honesty: 'certificate' },
    { set: 'Falkenauer_T', name: 'Falkenauer_t120_00', opt: 40, atMost: 40, bound: 40, lp: 40, honesty: 'certificate' },
    { set: 'Scholl_2', name: 'N1W1B1R0', opt: 18, atMost: 18, bound: 18, lp: 17.41203704, honesty: 'certificate' },
    { set: 'Wascher', name: 'Waescher_TEST0044', opt: 14, atMost: 14, bound: 14, lp: 13.9989, honesty: 'certificate' },
    { set: 'Hard28', name: 'Hard28_BPP742', opt: 64, atMost: 64, bound: 64, lp: 64, honesty: 'certificate' },
    { set: 'Hard28', name: 'Hard28_BPP14', opt: 62, atMost: 62, bound: 61, lp: 60.99796382, honesty: 'never-certificate', slow: true },
    { set: 'Hard28', name: 'Hard28_BPP119', opt: 77, atMost: 77, bound: 76, honesty: 'never-certificate', slow: true },
    { set: 'Hard28', name: 'Hard28_BPP175', opt: 84, atMost: 84, bound: 83, honesty: 'never-certificate', slow: true },
    { set: 'Hard28', name: 'Hard28_BPP359', opt: 76, atMost: 76, bound: 75, lp: 74.99825991, honesty: 'never-certificate', slow: true },
    { set: 'Hard28', name: 'Hard28_BPP716', opt: 76, atMost: 76, bound: 75, honesty: 'never-certificate', slow: true },
    { set: 'Wascher', name: 'Waescher_TEST0022', opt: 15, atMost: 15, bound: 14, lp: 13.99991144, honesty: 'never-certificate' },
    { set: 'ANI', name: '201_2500_NR_15', opt: 66, atMost: 66, bound: 65, honesty: 'never-certificate', slow: true },
    { set: 'ANI', name: '201_2500_NR_12', opt: 66, atMost: 66, bound: 65, honesty: 'never-certificate', slow: true },
    // atMost here is TODAY'S BEHAVIOUR, not the published optimum: this is the one row in
    // the table that is a regression guard rather than an external anchor, and it is
    // marked so that nobody counts it as one. Every other atMost equals the optimum.
    { set: 'AI', name: '201_2500_DI_15', opt: 65, atMost: 66, atMostIsToday: true, bound: 65, honesty: 'bound-is-the-optimum', slow: true },
  ];
  // QUICK SHRINKS THE BUDGET RATHER THAN DROPPING FIXTURES, and the difference matters.
  //
  // Seven of these seventeen rows were marked slow and skipped entirely under --quick,
  // and those seven are both ANI rows, the AI row and five of the six never-certificate
  // Hard28 rows: every honesty control in the file, the only assertions that check the
  // engine does not claim a proof it cannot have. Worse, mutate.mjs runs --quick by
  // default, so the instrument whose whole purpose is to prove this suite can fail was
  // being run against a suite with its honesty controls removed.
  //
  // The split that makes both possible: the BOUND and the honesty class are properties of
  // the instance and are reached in a second or two, so they are asserted always. The
  // BOARD COUNT is a property of the search under a clock, so under --quick it is skipped
  // by name and counted, rather than the whole row disappearing.
  let fixturesRun = 0;
  let boardCountsChecked = 0;
  for (const f of FIXTURES) {
    const budget = QUICK && f.slow ? 4000 : FIXTURE_MS;
    const checkBoards = !(QUICK && f.slow);
    fixturesRun++;
    const inst = benchInstance(f.set, f.name);
    if (!inst) {
      // The same number of assertions a present instance would make, so that a missing
      // cache changes the count of FAILURES and never the count of assertions.
      for (let k = 0; k < (f.lp == null ? 6 : 8); k++) ok(false, `${f.name}: ${BENCH_MISSING}`);
      continue;
    }
    eq(inst.optimum, f.opt, `${f.name}: the library still publishes the optimum this fixture was chosen for`);
    const r = solve(
      { stock: [{ length: inst.cap }], pieces: inst.pieces, kerf: 0, objective: 'boards' },
      { totalMs: budget, restarts: 8 },
    );
    ok(r.audit.ok, `${f.name}: the plan audits clean (${r.audit.problems.join('; ')})`);
    ok(r.boards.length >= f.opt, `${f.name}: never fewer boards than a proved optimum (got ${r.boards.length}, optimum ${f.opt})`);
    if (checkBoards) {
      boardCountsChecked++;
      ok(r.boards.length <= f.atMost, `${f.name}: the search still reaches ${f.atMost} boards (got ${r.boards.length})`);
    } else {
      ok(true, `${f.name}: board count not checked at the reduced quick-mode budget of ${budget} ms`);
    }
    eq(r.bound.integer, f.bound, `${f.name}: the certified bound is exactly this, not merely below the optimum`);
    // Where the linear program converges inside the budget, pin the value it converges
    // TO. That number is a property of the instance and not of the search: any correct
    // column generation reaches it by whatever route, so it is the one dual-side figure
    // that is neither an inequality nor an artefact of the clock. It is also the only
    // assertion here that notices the column generation stopping early, because on most
    // of these instances the certificate that finally wins comes from the dual feasible
    // functions rather than from the LP.
    if (f.lp != null) {
      eq(r.bound.lpStatus, 'optimal', `${f.name}: the column generation converges inside ${FIXTURE_MS} ms`);
      near(r.bound.lpValue, f.lp, 1e-6, `${f.name}: and converges to the LP value of this instance`);
    }
    if (f.honesty === 'certificate') {
      eq(r.proof, 'certificate', `${f.name}: and the plan meets it, so the proof is one a stranger can re-read`);
    } else if (f.honesty === 'never-certificate') {
      ok(r.proof !== 'certificate',
        `${f.name}: ceil(LP) is below the optimum here, so no certificate can close this gap and none may be claimed`);
    } else {
      ok(r.bound.verified && r.bound.integer === f.opt,
        `${f.name}: the certificate closes to the published optimum on this augmented-IRUP instance`);
    }
  }
  // The tripwire this section needs, because every assertion above is inside a loop: a
  // change that makes the loop run fewer times would otherwise make the suite quieter
  // rather than redder.
  eq(fixturesRun, FIXTURES.length, 'every named fixture was reached');
  // Derived, not typed: under --quick the board count is checked on exactly the fixtures
  // that are not marked slow, and a hard-coded floor would drift the moment one is added.
  const expectBoardChecks = QUICK ? FIXTURES.filter((x) => !x.slow).length : FIXTURES.length;
  eq(boardCountsChecked, expectBoardChecks,
    `and its board count was checked on every fixture that carries one (${boardCountsChecked} of ${FIXTURES.length})`);
}

// ---------------------------------------------------------------------------
// 17. the page prints the numbers this directory measured, and no others
// ---------------------------------------------------------------------------
section('The page and the measurements agree');
{
  const html = fs.readFileSync(path.join(HERE, '../../public/tools/cut-list/index.html'), 'utf8');
  const popPath = path.join(HERE, 'population.json');
  if (!fs.existsSync(popPath)) {
    ok(false, 'population.json is present (run population.mjs --out research/cut-list/population.json)');
  } else {
    const pop = JSON.parse(fs.readFileSync(popPath, 'utf8'));
    const table = (html.match(/<table class="data" id="popTable">[\s\S]*?<\/table>/) || [])[0] || '';
    const rows = [...table.matchAll(/<tr><td>([\s\S]*?)<\/td><td class="num">(\d+)<\/td><td class="num">([\d.]+)%<\/td><td class="num">(\d+)<\/td><\/tr>/g)];
    eq(rows.length, pop.populations.length, 'the page has one row per measured population');
    pop.populations.forEach((p, i) => {
      const r = rows[i];
      if (!r) { ok(false, `${p.id}: no row on the page`); return; }
      eq(Number(r[2]), p.kept, `${p.id}: the page prints the number of lists actually kept`);
      eq(r[3], p.ffdWorsePct.toFixed(2), `${p.id}: the page prints the measured first-fit rate`);
      eq(Number(r[4]), p.nonIrup, `${p.id}: the page prints the measured count of unreachable bounds`);
    });
  }
  const printedGaps = (html.match(/id="statGaps">([^<]*)</) || [])[1] || '';
  eq(printedGaps, 'seventeen of seventeen', 'the page claims exactly what the gap table checked');

  // THE BENCHMARK FIGURES ON THE PAGE COME FROM A MACHINE-READABLE SUMMARY, not from a
  // regular expression over the generated markdown.
  //
  // This block used to parse `bench-results.md` with a pattern tuned to the exact shape of
  // its table. That is a check that goes green the moment the table's shape changes and the
  // numbers stop being found at all, which is the enumerate-do-not-match failure in its
  // purest form. `report.mjs` now writes `bench-summary.json` from the same counts it
  // renders, so the page and this suite read one artefact and a format change breaks
  // loudly rather than silently.
  const sumPath = path.join(HERE, 'bench-summary.json');
  if (!fs.existsSync(sumPath)) {
    ok(false, 'bench-summary.json is present (node research/cut-list/report.mjs > research/cut-list/bench-results.md)');
    for (let k = 0; k < 6; k++) ok(false, 'bench-summary.json is present, so the page figures can be checked');
  } else {
    const sum = JSON.parse(fs.readFileSync(sumPath, 'utf8'));
    const say = (id) => Number(((html.match(new RegExp(`id="${id}">([\\d,]+)<`)) || [])[1] || '-1').replace(/,/g, ''));
    eq(sum.belowOptimum, 0, 'no benchmark instance was ever solved BELOW a published optimum');
    eq(say('statBenchN'), sum.instances, 'the page prints the number of benchmark instances actually run');
    eq(say('statBenchProved'), sum.provedByCertificate, 'the page prints the number it proved by certificate');
    eq(say('statBenchMatched'), sum.matchedOptimum, 'the page prints the number whose plan equalled the published optimum');
    eq(say('statBenchAbove'), sum.aboveOptimum, 'the page prints the number it came out above on');
    eq(say('statCertPossible'), sum.certificatePossible, 'the page prints how many instances a certificate could close at all');
    eq(say('statProvedOfPossible'), sum.provedOfPossible, 'and how many of those it actually closed');
    // WHAT USED TO BE HERE AND WHY IT IS GONE. Three assertions: that the outcome counts
    // sum to the instance count, that the ceiling counts do too, and that the number of
    // instances proved is at most the number where a proof was possible. All three are
    // tautologies of how report.mjs defines those tallies: `other` is the exact complement
    // of the five named outcomes, the three ceiling classes are the complement of each
    // other, and `provedOfPossible` filters a strict refinement of `certificatePossible`,
    // so a subset can never be larger than its superset. They read like invariants and
    // could not be moved by any defect in the engine or in the report.
    //
    // Replaced by one that can fail: the summary must describe the log it claims to, and
    // the instance count must match what the cache actually holds for the sets it names.
    if (benchAvailable()) {
      const held = sum.sets.reduce((acc, name) => acc + benchSetSize(name), 0);
      eq(sum.instances, held,
        'the summary scored every instance the cache holds for the sets it names');
    }
    eq(sum.belowOptimum + sum.other, 0,
      'no scored instance fell outside the five outcomes, and none was below a proved optimum');

    // THE PAIR THE PAGE USES TO DESCRIBE ITS OWN DEEP BUTTON, and both halves have to come
    // from a measurement rather than from a memory of one. The page names four figures for
    // Hard28: found and proved at the page's budget, found and proved at the deep one.
    const deepPath = path.join(HERE, 'bench-summary-deep.json');
    if (!fs.existsSync(deepPath)) {
      for (let k = 0; k < 5; k++) {
        ok(false, 'bench-summary-deep.json is present (node research/cut-list/bench.mjs --set Hard28 --time 120000 ...)');
      }
    } else {
      const deep = JSON.parse(fs.readFileSync(deepPath, 'utf8'));
      const hardFast = sum.bySet.find((r) => r.set === 'Hard28');
      const hardDeep = deep.bySet.find((r) => r.set === 'Hard28');
      const found = (r) => r.provedByCertificate + r.provedBySearch + r.matchedNotProved;
      eq(say('statHardFastFound'), found(hardFast), 'the page prints how many Hard28 optima it found at its own budget');
      eq(say('statHardFastProved'), hardFast.provedByCertificate, 'and how many of those it proved');
      eq(say('statHardDeepFound'), found(hardDeep), 'the page prints how many it found at the deep budget');
      eq(say('statHardDeepProved'), hardDeep.provedByCertificate, 'and how many of those it proved');
      eq(say('statHardCeiling'), hardFast.certificatePossible, 'and how many of that set admit a certificate at all');
      // The deep run must be the SAME instrument with more clock, not a different one, or
      // the comparison the page draws is between two tools.
      eq(deep.opts.restarts != null, true, 'the deep run recorded its options');
      ok(deep.opts.totalMs > sum.opts.totalMs,
        `and the deep budget really is larger (${deep.opts.totalMs} against ${sum.opts.totalMs})`);
      ok(found(hardDeep) >= found(hardFast),
        'more clock did not find fewer optima, which would mean the search is not monotone in time');
    }
  }
}

// ---------------------------------------------------------------------------
console.log(`\n${pass} passed, ${fail} failed`);
{
  // Self-referential on purpose: the page prints how many assertions stand
  // behind it, and that number has to be this number.
  const html = fs.readFileSync(path.join(HERE, '../../public/tools/cut-list/index.html'), 'utf8');
  const printed = Number(((html.match(/id="statAsserts">([\d,]+)</) || [])[1] || '0').replace(/,/g, ''));
  const total = pass + fail + 1;
  if (printed !== total) {
    console.error(`  FAIL  the page says ${printed} assertions; this run made ${total}`);
    fail++;
  } else pass++;
}
if (fail) { console.log('\nfailures:'); failures.forEach((f) => console.log('  - ' + f)); }
process.exit(fail ? 1 : 0);
