#!/usr/bin/env node
// verify-page.mjs — drive the real /tools/cut-list/ page in a real browser.
//
// The engine has its own verifier. This one asks the questions only a browser
// can answer: does the page actually reach the reader, does it talk to anybody
// it should not, does every shipped example really produce the verdict the page
// claims, and does the re-check button really re-check.
//
// THE FINDING THAT REBUILT THIS FILE, on 2026-09-04. The page's primary button,
// "Work it out", printed the literal string "[object PointerEvent]" above the
// verdict on every press, live on the production site, for weeks. The cause was
// one line: the click handler was handed straight to a function whose first
// parameter is a note to display. This file had 1,438 sibling assertions and a
// real browser and it never once clicked that button. It drove the specimen
// chips, the re-check button and the puzzle, which is to say it drove
// everything except the control the reader actually presses. A check that
// cannot fail on the most-travelled path on the page is not a check of the page.
//
// So the sections below are organised around the same question the engine's
// verifier asks of itself: WHICH ASSERTION HERE FAILS IF THE ANSWER IS MERELY
// WEAK RATHER THAN WRONG? A page assertion has an extra way to be vacuous that
// an engine assertion does not: it can pass because the thing it looks for is
// never rendered at all. Every absence asserted here is therefore paired with a
// presence asserted somewhere else, so that "no stray note" cannot pass on a
// page that has lost the ability to print notes, and "no dollar figure" cannot
// pass on a page that has lost the ability to print money.
//
//   node research/cut-list/verify-page.mjs
//   node research/cut-list/verify-page.mjs --shot      (also write an OG-sized shot)
//   node research/cut-list/verify-page.mjs --no-live   (skip the deployed-site section)
//
// RED ON PURPOSE. Every assertion added on 2026-09-04 was watched to fail
// before it was trusted to pass, by serving a MUTATED COPY of the tool to this
// same script. That is what CUT_LIST_PUBLIC is for, and for nothing else: it
// overrides the directory the local static server serves, so a scratch copy can
// be broken without touching the repository. Build the scratch copy by
// symlinking every entry of public/ except public/tools/cut-list/, which is
// copied, and then edit the copy:
//
//   MUTATION, IN THE COPY                                THE ASSERTION IT TURNS RED
//   app  hand `doSolve` to the click handler AND relax    the primary button prints nothing
//        its guard to `if (note)`                         above the verdict
//   app  never append the note paragraph at all           a specimen chip DOES print a note
//   app  drop 'pieces' from the markStale id list         editing the parts marks it stale
//   eng  `const unpriced = false && ...`                  the money objective refuses by name
//   eng  `boardsNeededAtLeast: null`                      how many boards the list needs
//   eng  `shortfallOfStock: false`                        the short-of-stock answer
//   app  print the scarce allowance one short of its sum  the stock line adds up
//   app  print the allowance without its breakdown        the breakdown is shown at all
//   app  drop the subtraction clause from the total       the scarcity term is taken off
//   app  copy a zero for every scarcity weight            the copied certificate re-verifies
//   app  multiply the printed quotient by 1.001           the quotient printed is that division
//   app  multiply the printed weight column by 1.01       the decimal weight beside each part
//   app  take the denominator from memory, not the page   doubling the shown denominator
//   uni  drop the tab rewrite in parseList                a tab-separated paste
//   app  fetch the parts box from a third-party host      nothing sent carries the job
//
// Two of those are worth their own sentence. Reverting the click handler ALONE
// does not turn anything red, because the note parameter is now type-guarded as
// well, so the page survives either mistake on its own: the assertion is
// sensitive to the defect a reader would see and not to either guard, which is
// the right sensitivity and worth knowing about. And the deployed-site section
// cannot be made red this way at all, because nobody here can mutate the
// deployed site; its detector is the same `leaksIn` the local run uses, and the
// last mutation in the table turns THAT red, so what runs against production is
// a detector already proven able to fail.

import { chromium } from 'playwright';
import http from 'node:http';
import { readFile } from 'node:fs/promises';
import { existsSync } from 'node:fs';
import path from 'node:path';
import { fileURLToPath } from 'node:url';
import { SPECIMENS } from '../../public/tools/cut-list/specimens.mjs';
// The re-verifier for the copied certificate. It is imported from the engine on
// purpose: what the "Copy the certificate" button hands a stranger has to pass
// the same exact-integer test the page runs, in a process that never saw the
// page. If the copy does not re-verify, that is the worst failure this tool can
// have, and until tonight nothing anywhere checked it.
import { certify } from '../../public/tools/cut-list/engine.mjs';

const HERE = path.dirname(fileURLToPath(import.meta.url));
const ROOT = path.resolve(HERE, '../..');
// CUT_LIST_PUBLIC exists for the red-on-purpose harness described in the header
// and for nothing else. Unset, this is the repository's own public directory.
const PUBLIC = process.env.CUT_LIST_PUBLIC
  ? path.resolve(process.env.CUT_LIST_PUBLIC)
  : path.join(ROOT, 'public');
const SHOT = process.argv.includes('--shot');
const LIVE = !process.argv.includes('--no-live');
const LIVE_URL = 'https://artwaste.land/tools/cut-list/';

const MIME = {
  '.html': 'text/html', '.css': 'text/css', '.js': 'text/javascript', '.mjs': 'text/javascript',
  '.woff2': 'font/woff2', '.woff': 'font/woff', '.json': 'application/json',
  '.svg': 'image/svg+xml', '.png': 'image/png', '.jpg': 'image/jpeg', '.webp': 'image/webp',
};

const server = http.createServer(async (req, res) => {
  try {
    let p = decodeURIComponent(req.url.split('?')[0]);
    if (p.endsWith('/')) p += 'index.html';
    const fp = path.join(PUBLIC, p);
    if (!fp.startsWith(PUBLIC) || !existsSync(fp)) { res.writeHead(404); res.end('nf'); return; }
    const body = await readFile(fp);
    res.writeHead(200, { 'Content-Type': MIME[path.extname(fp)] || 'application/octet-stream' });
    res.end(body);
  } catch (e) { res.writeHead(500); res.end(String(e)); }
});
await new Promise((r) => server.listen(0, r));
const base = `http://localhost:${server.address().port}`;

let pass = 0, fail = 0;
const failures = [];
const ok = (m) => { pass++; console.log('  \x1b[32m✓\x1b[0m ' + m); };
const bad = (m) => { fail++; failures.push(m); console.log('  \x1b[31m✗ ' + m + '\x1b[0m'); };
const note = (m) => console.log('  \x1b[2m·\x1b[0m \x1b[2m' + m + '\x1b[0m');
const is = (a, b, m) => (a === b ? ok(m) : bad(`${m} (got ${JSON.stringify(a)}, wanted ${JSON.stringify(b)})`));
const okIf = (cond, m) => (cond ? ok(m) : bad(m));
const near = (a, b, tol, m) => (Math.abs(a - b) <= tol ? ok(m) : bad(`${m} (got ${a}, wanted ${b} +/- ${tol})`));

// A fixed locale, because half the assertions below read numbers back out of
// the page and `toLocaleString` is what put them there. Under a locale that
// groups with dots, "1.816.214.400" would be scrubbed into a different number
// and the arithmetic checks would compare two wrong things and agree.
const browser = await chromium.launch();
const context = await browser.newContext({ viewport: { width: 1100, height: 900 }, locale: 'en-US' });
await context.grantPermissions(['clipboard-read', 'clipboard-write'], { origin: base });
const page = await context.newPage();
const errors = [];
const offOrigin = [];
page.on('console', (m) => { if (m.type() === 'error') errors.push(m.text()); });
page.on('pageerror', (e) => errors.push(String(e)));
page.on('request', (r) => { if (!r.url().startsWith(base) && !r.url().startsWith('data:')) offOrigin.push(r.url()); });

const url = base + '/tools/cut-list/';

// ---------------------------------------------------------------------------
// did the job leave the browser
// ---------------------------------------------------------------------------

/**
 * A JOB WRITTEN SO THAT NOTHING ELSE COULD PRODUCE IT.
 *
 * The first draft of the leak check used plain four-digit lengths and fired on
 * a performance beacon that happened to report a timing of 1129 milliseconds. A
 * number a job shares with a stopwatch is a coincidence, not a leak, and a
 * detector that cannot tell the two apart is worse than no detector. So the
 * labels are invented words and the lengths carry four decimal places, which
 * nothing but this job produces.
 */
const TOKEN_JOB = { stock: '4813.0625', pieces: '3 x 1607.3125 - keelson\n2 x 1129.9375 - futtock' };
const TOKENS = ['keelson', 'futtock', '4813.0625', '1607.3125', '1129.9375'];

/** Watch everything a page asks for, including what it sends and where it says it came from. */
function recordRequests(target) {
  const seen = [];
  const headerWaits = [];
  target.on('request', (r) => {
    const entry = { url: r.url(), method: r.method(), body: r.postData() || '', ref: '' };
    seen.push(entry);
    headerWaits.push(r.allHeaders().then((h) => { entry.ref = h.referer || ''; }).catch(() => {}));
  });
  return { seen, settle: () => Promise.all(headerWaits) };
}

/**
 * Every place the job turned up in something the browser sent.
 *
 * URL, body and referrer, because the page puts the whole job into its own
 * query string with `history.replaceState`, and a referrer is the quiet way a
 * query string reaches a third party.
 */
function leaksIn(seen, tokens) {
  const out = [];
  for (const r of seen) {
    const hay = `${r.url}\n${r.body}\n${r.ref}`;
    for (const t of tokens) {
      const at = hay.indexOf(t);
      if (at < 0) continue;
      // Carry the surrounding text into the failure, so a hit is diagnosable at
      // a glance as a leak or as a collision.
      out.push(`"${t}" in ${r.method} ${r.url.slice(0, 70)} near ...${hay.slice(Math.max(0, at - 30), at + t.length + 30).replace(/\s+/g, ' ')}...`);
    }
  }
  return out;
}

const localRequests = recordRequests(page);

// ---------------------------------------------------------------------------
// reading the page
// ---------------------------------------------------------------------------

/** The verdict's own words, WITHOUT the stamp that gets appended after them. */
const headline = () => page.evaluate(() => {
  const b = document.querySelector('#out .verdict .big');
  if (!b) return null;
  const first = b.childNodes[0];
  return (first && first.nodeType === 3 ? first.textContent : b.textContent).trim();
});
const stampText = () => page.locator('#out .verdict .stamp').first().textContent().catch(() => '');
const boardCount = () => page.locator('#out .board').count();
const outText = () => page.evaluate(() => document.getElementById('out').textContent);
const bodyText = () => page.evaluate(() => document.body.textContent);
const strayNotes = () => page.locator('#out > p.note').count();
// Defensive readers. An assertion that throws when the element it looks for is
// missing takes the rest of the run down with it, and a suite that stops at the
// first defect reports one defect however many there are.
const text = (sel) => page.evaluate((s) => { const n = document.querySelector(s); return n ? n.textContent.trim() : null; }, sel);
const attr = (sel, name) => page.evaluate(([s, a]) => { const n = document.querySelector(s); return n ? n.getAttribute(a) : null; }, [sel, name]);
const errorsVisible = async () => (await page.locator('#errors:not(.hidden)').count()) > 0;
const errorsText = () => page.textContent('#errors');
/** Every part the plan actually draws, tallied by the length printed on it. */
const drawnParts = () => page.evaluate(() => {
  const t = {};
  for (const n of document.querySelectorAll('#out .board .seg-piece .seg-len')) {
    const k = n.textContent.trim();
    t[k] = (t[k] || 0) + 1;
  }
  return t;
});

/**
 * Run a solve and wait for it to finish.
 *
 * The status line is stamped with a sentinel first, so "status is empty" can
 * only become true by `doSolve` running all the way through. Without the
 * sentinel this waits on a condition that is already true and returns before
 * the page has done anything, which is the shape of a browser assertion that
 * passes against a page that never ran.
 */
async function solving(action, what) {
  await page.evaluate(() => { document.getElementById('status').textContent = '…pending…'; });
  await action();
  try {
    await page.waitForFunction(() => {
      const s = document.getElementById('status');
      return s && s.textContent === '';
    }, null, { timeout: 60000 });
  } catch (e) {
    // FAIL, DO NOT THROW. A solve that never finishes is a defect like any
    // other, and a suite that dies on the first one reports one defect however
    // many there are. The assertions after this will read whatever is on screen
    // and go red on their own, which is the right amount of noise.
    bad(`the page never finished working out ${what || 'this job'} within 60 seconds `
      + '(a refusal in the errors box does this: nothing then clears the status line)');
  }
}

/** A solve that is expected to be refused before it starts, in the errors box. */
async function refusedBeforeSolving(action) {
  await page.evaluate(() => { document.getElementById('errors').classList.add('hidden'); });
  await action();
  await page.waitForSelector('#errors:not(.hidden)', { timeout: 20000 }).catch(() => {});
}

async function freshPage() {
  await page.goto(url, { waitUntil: 'load' });
  await page.waitForSelector('#out .verdict', { timeout: 45000 });
  await page.waitForFunction(() => {
    const s = document.getElementById('status');
    return s && s.textContent === '';
  }, null, { timeout: 120000 });
}

/** Type a job into the desk, in the order the desk expects it. */
async function setJob(spec) {
  if (spec.system) {
    await page.click(spec.system === 'imperial' ? '#sysIN' : spec.system === 'bare' ? '#sysBARE' : '#sysMM');
  }
  if (spec.objective !== undefined) await page.selectOption('#objective', spec.objective);
  if (spec.kerfModel !== undefined) await page.selectOption('#kerfModel', spec.kerfModel);
  if (spec.stock !== undefined) await page.fill('#stock', spec.stock);
  if (spec.kerf !== undefined) await page.fill('#kerf', spec.kerf);
  if (spec.pieces !== undefined) await page.fill('#pieces', spec.pieces);
  if (spec.lead !== undefined || spec.tail !== undefined || spec.short !== undefined) {
    await page.evaluate(() => { const d = document.querySelector('details.adv'); if (d) d.open = true; });
    if (spec.lead !== undefined) await page.fill('#lead', spec.lead);
    if (spec.tail !== undefined) await page.fill('#tail', spec.tail);
    if (spec.short !== undefined) await page.fill('#short', spec.short);
  }
}

const openCertPanel = () => page.evaluate(() => {
  const d = document.getElementById('certPanel');
  if (d) d.open = true;
  return !!d;
});

// ---------------------------------------------------------------------------
// reading the numbers the certificate panel prints
// ---------------------------------------------------------------------------

/** Strip every grouping character `toLocaleString` may have inserted. */
const NUM = (s) => Number(String(s).replace(/[,\s   ]/g, ''));

/** "$255.60" -> 25560 minor units; "6 boards" -> 6; "18030 mm" -> 18030. */
function figure(text) {
  const s = String(text == null ? '' : text).trim();
  const money = s.match(/^\$\s*([\d.,]+)/);
  if (money) return Math.round(Number(money[1].replace(/,/g, '')) * 100);
  const m = s.match(/^([\d.,]+)/);
  return m ? Number(m[1].replace(/,/g, '')) : NaN;
}

/** Everything the certificate panel says, as raw text, for reconciling in node. */
const scrapeCertificate = () => page.evaluate(() => {
  const panel = document.getElementById('certPanel');
  if (!panel) return null;
  const denom = document.getElementById('certDenom');
  const rows = [...document.querySelectorAll('#certTable tbody tr')].map((r) => ({
    part: r.children[0].textContent.trim(),
    qty: r.querySelector('td[data-qty]').textContent.trim(),
    num: r.querySelector('td[data-num]').textContent.trim(),
    weight: r.children[3].textContent.trim(),
  }));
  const box = panel.querySelector('.certbox');
  return {
    denom: denom ? denom.textContent.trim() : null,
    rows,
    items: [...box.querySelectorAll('ul.tight li')].map((li) => li.textContent.replace(/\s+/g, ' ').trim()),
    paragraphs: [...box.querySelectorAll('p')].map((p) => p.textContent.replace(/\s+/g, ' ').trim()),
  };
});

/**
 * Reconcile every number the certificate panel PRINTS against every other
 * number it prints, and against the bound it concludes with.
 *
 * This is the assertion the panel most needs and least had. The panel's whole
 * purpose is that a stranger can follow the arithmetic by hand; a reader who
 * adds up what is on the page and gets a different figure from the sentence at
 * the bottom has been told, by the page itself, that it cannot add up. That has
 * already happened here twice: once when the scarcity allowance was left out of
 * the per-board line, leaving a reader applying the page's own stated rule with
 * a figure nearly three times too small, and once when the subtraction and the
 * rounding were invisible in the total.
 *
 * Every check below is an EQUALITY, deliberately. An inequality between two
 * printed numbers would pass on a panel whose numbers were merely weak.
 */
function reconcileCertificate(scr, opts) {
  const label = opts.label;
  const denom = NUM(scr.denom);
  okIf(Number.isInteger(denom) && denom > 0, `${label}: the denominator is printed as a whole number (${scr.denom})`);

  // 1. the table
  const rowTotal = scr.rows.reduce((s, r) => s + NUM(r.qty) * NUM(r.num), 0);
  scr.rows.forEach((r) => {
    near(Number(r.weight), NUM(r.num) / denom, 5e-7,
      `${label}: the decimal weight beside ${r.part} is its own numerator over the denominator`);
  });

  // 2. every per-stock allowance line.
  //
  // `best <= allowance` is the one genuinely one-sided check in this function,
  // and it is here because it is the page's own printed claim rather than a
  // claim of ours. Its teeth come from its neighbours: the allowance has to be
  // the price the reader typed times the denominator plus the scarcity term, the
  // parts of that sum have to add up to the total printed beside them, and the
  // quotient at the bottom has to round up to the figure the plan costs. A
  // certificate that were merely weak would satisfy this line and fail those.
  let scarcityFromItems = 0;
  scr.items.forEach((li, t) => {
    const m = li.match(/is\s+([\d,\s]+?),\s*and it is allowed\s+(.+?)\.\s*(Within|Over)/);
    if (!m) { bad(`${label}: stock line ${t + 1} does not read as an allowance sentence: ${li.slice(0, 120)}`); return; }
    const best = NUM(m[1]);
    const allowed = m[2];
    const verdict = m[3];
    const split = allowed.match(/^([\d,\s]+)\s*for one board plus\s*([\d,\s]+)\s*because only\s*(\d+)\s*of them exist\s*=\s*([\d,\s]+)$/);
    if (opts.expectScarcity && t === 0) {
      // Printing only the total was the bug: a reader applying the page's own
      // stated rule got a figure nearly three times too small and concluded the
      // proof was broken. So the breakdown has to be there, not merely add up.
      is(!!split, true, `${label}: the scarce stock line shows its allowance broken into cost and scarcity`);
    }
    if (split) {
      const perBoard = NUM(split[1]), scarce = NUM(split[2]), count = Number(split[3]), total = NUM(split[4]);
      is(perBoard + scarce, total, `${label}: stock line ${t + 1} adds up (${perBoard} + ${scarce} = ${total})`);
      if (opts.costMinor != null && t === 0) {
        is(perBoard, opts.costMinor * denom,
          `${label}: the per-board allowance is the price the reader typed times the denominator`);
      }
      if (opts.stockCount != null && t === 0) {
        is(count, opts.stockCount, `${label}: and it names the number of boards the reader said exist`);
      }
      scarcityFromItems += count * scarce;
      is(best <= total, true, `${label}: the fullest a stock-line-${t + 1} board can be is within its allowance`);
      is(verdict, 'Within', `${label}: and the line says so`);
    } else {
      const total = NUM(allowed);
      is(best <= total, true, `${label}: the fullest a stock-line-${t + 1} board can be is within its allowance`);
      is(verdict, 'Within', `${label}: and the line says so`);
    }
  });

  // 3. the total, which is the sentence the reader is asked to believe
  const total = scr.paragraphs.find((p) => p.startsWith('Add the weight of everything on the list'));
  if (!total) { bad(`${label}: the certificate panel prints no total line`); return null; }
  const mT = total.match(/list:\s*([\d,\s]+?)(?:,\s*then take off|\.\s*Divide by)/);
  if (!mT) { bad(`${label}: the total line does not state the weight of the list`); return null; }
  const T = NUM(mT[1]);
  is(T, rowTotal, `${label}: the stated weight of the list is the table's own quantities times its own weights`);

  let subtracted = 0;
  const mS = total.match(/beyond its cost\s*\(([^)]*)\),\s*leaving\s*([\d,\s]+?)\.\s*Divide/);
  if (opts.expectScarcity) {
    if (!mS) { bad(`${label}: the total line does not show the scarcity term being taken off`); return null; }
    const terms = mS[1].split(/\s*\+\s*/).map((x) => x.match(/([\d,\s]+)\s*[×x]\s*([\d,\s]+)/));
    let sum = 0;
    terms.forEach((tm, i) => {
      if (!tm) { bad(`${label}: scarcity term ${i + 1} is unreadable`); return; }
      sum += NUM(tm[1]) * NUM(tm[2]);
    });
    const stated = NUM(mS[1].split('=').pop());
    is(sum, stated, `${label}: the scarcity terms multiply out to the figure the sentence states`);
    is(sum, scarcityFromItems, `${label}: and to the same figure the per-board lines allowed`);
    subtracted = stated;
    is(T - subtracted, NUM(mS[2]), `${label}: the list's weight minus the scarcity term is the figure it says is left`);
  } else {
    is(mS, null, `${label}: no scarcity term is printed, because no stock line here is in limited supply`);
  }

  const mD = total.match(/Divide by the denominator:\s*([\d,\s]+)\s*\/\s*([\d,\s]+)\s*=\s*(\d+(?:\.\d+)?)/);
  if (!mD) { bad(`${label}: the total line does not show the division`); return null; }
  const net = NUM(mD[1]);
  is(net, T - subtracted, `${label}: the number being divided is the one the sentence just arrived at`);
  is(NUM(mD[2]), denom, `${label}: and it is divided by the denominator the panel declared`);
  is(mD[3], (net / denom).toFixed(6), `${label}: and the quotient printed is that division`);

  const mF = total.match(/so no plan can use fewer than\s*(.+?), and this plan uses\s*(.+?)\.\s*$/);
  if (!mF) { bad(`${label}: the total line does not finish with the bound and the plan`); return null; }
  const boundFigure = figure(mF[1]);
  const planFigure = figure(mF[2]);
  is(Math.ceil(net / denom - 1e-9), boundFigure,
    `${label}: the bound the panel concludes with is its own quotient, rounded up`);
  return { denom, T, subtracted, net, boundFigure, planFigure, boundText: mF[1].trim(), planText: mF[2].trim() };
}

// ---------------------------------------------------------------------------
// reading the certificate the copy button hands a stranger
// ---------------------------------------------------------------------------

/**
 * Parse the text "Copy the certificate" puts on the clipboard, exactly as
 * somebody who had only that text would have to.
 *
 * The demands travel as comment lines, which is a wart worth naming: a parser
 * that skipped comments outright would get the weights and no idea how many of
 * each part there are, and could not compute the bound at all. So this reads
 * them, and asserts that every weight has one.
 */
function parseCopiedCertificate(text) {
  const order = [];
  const weight = new Map();
  const demand = new Map();
  const stock = [];
  let denom = null, claim = null;
  for (const raw of String(text).split('\n')) {
    const line = raw.trim();
    let m;
    if ((m = line.match(/^#\s+(\d+)\s*x\s*(\d+)$/))) { demand.set(Number(m[1]), Number(m[2])); continue; }
    if ((m = line.match(/^#\s*claim: no plan costs less than\s*([\d.eE+-]+)/))) { claim = Number(m[1]); continue; }
    if (line.startsWith('#') || !line) continue;
    if ((m = line.match(/^denominator\s+(\d+)$/))) { denom = Number(m[1]); continue; }
    if ((m = line.match(/^weight\s+(\d+)\s+(-?\d+)$/))) { order.push(Number(m[1])); weight.set(Number(m[1]), Number(m[2])); continue; }
    if ((m = line.match(/^stock\s+(\d+)\s+(\d+|unlimited)\s+(-?\d+)\s+(-?\d+)$/))) {
      stock.push({ capacity: Number(m[1]), count: m[2] === 'unlimited' ? Infinity : Number(m[2]), cost: Number(m[3]), y: Number(m[4]) });
      continue;
    }
  }
  const missingDemand = order.filter((w) => !demand.has(w));
  return {
    denom, claim, order, stock, missingDemand,
    prob: {
      pieces: order.map((w) => ({ width: w, qty: demand.get(w) })),
      stock: stock.map((s) => ({ capacity: s.capacity, count: s.count })),
    },
    cert: {
      denom,
      num: order.map((w) => weight.get(w)),
      stockNum: stock.map((s) => s.y),
      cost: stock.map((s) => s.cost),
    },
  };
}

// ===========================================================================

await freshPage();

console.log('\nThe page loads and solves on arrival');
{
  const head = await headline();
  ok(`the opening verdict reads: ${head}`);
  is(head, '6 boards.', 'the default bookcase comes out at six boards');
  is(await stampText(), 'proved', 'and is stamped proved');
  is(await boardCount(), 6, 'six boards are drawn');
}

// ---------------------------------------------------------------------------
console.log('\nThe primary button, which nothing here used to press');
// Red on purpose: handing `doSolve` to the click handler AND relaxing its note
// guard to `if (note)` turns the first two of these red, with the second one
// printing the original defect back verbatim. Either mutation on its own turns
// nothing red, which is correct: the page survives either mistake alone, and
// these lines are about what a reader sees rather than about which guard holds.
{
  await freshPage();
  await solving(() => page.click('#go'));
  is(await strayNotes(), 0, 'pressing "Work it out" prints nothing above the verdict');
  is(/\[object /.test(await bodyText()), false, 'and no part of the page reads "[object something]"');
  is(await headline(), '6 boards.', 'the verdict after the press reads exactly "6 boards."');
  is(await stampText(), 'proved', 'and is stamped proved');
  is(await boardCount(), 6, 'and six boards are drawn under it');

  // THE PAIRED PRESENCE. "No note" must not pass on a page that has lost the
  // ability to print notes, so the slot is shown to work in the same breath.
  const spec = SPECIMENS[0];
  await solving(() => page.locator('.chip', { hasText: spec.name }).click());
  is(await strayNotes(), 1, 'a specimen chip DOES print a note, so the empty slot above is a fact about the button');
  // Read defensively. An assertion that throws when the element it looks for is
  // missing takes the rest of the run down with it, and a suite that stops at
  // the first defect reports one defect however many there are.
  is(await page.evaluate(() => {
    const n = document.querySelector('#out > p.note');
    return n ? n.textContent.trim() : null;
  }), spec.blurb, 'and the note is the specimen blurb, verbatim');

  // The same button, on a job typed into the form rather than shipped with the page.
  await freshPage();
  await setJob({ system: 'metric', stock: '4800', kerf: '3', pieces: '4 x 2250\n9 x 1425\n5 x 1250\n7 x 600' });
  await solving(() => page.click('#go'));
  is(await strayNotes(), 0, 'and prints nothing above the verdict on an edited job either');
  is(await headline(), '7 boards.', 'the edited job comes out at seven boards');
  is(await stampText(), 'proved', 'stamped proved');
  is(await boardCount(), 7, 'seven boards drawn');
  is(/\[object /.test(await bodyText()), false, 'still nothing reading "[object something]"');

  // The keyboard route into the same function.
  await page.focus('#pieces');
  await solving(() => page.keyboard.press('Control+Enter'));
  is(await strayNotes(), 0, 'nor does the keyboard shortcut, which reaches the same function');
  is(await headline(), '7 boards.', 'and it produces the same verdict');
}

// ---------------------------------------------------------------------------
console.log('\nA result the form no longer describes is marked as stale');
{
  await freshPage();
  is(await page.locator('#out.stale').count(), 0, 'a result just worked out is not stale');
  await page.fill('#pieces', '2 x 1800\n5 x 760\n1 x 500');
  is(await page.locator('#out.stale').count(), 1, 'editing the parts marks the standing verdict stale');
  await solving(() => page.click('#go'));
  is(await page.locator('#out.stale').count(), 0, 'and pressing the button clears the mark');

  // The trim allowance is part of the job, and it changes the answer: take 700
  // off the leading end of a 2400 board and the 1800 side no longer fits at
  // all. A standing "6 boards, proved" over that form is a false statement.
  await freshPage();
  await setJob({ lead: '700' });
  is(await page.locator('#out.stale').count(), 1,
    'editing the trim allowance marks it stale too (with 700 off the end the 1800 side no longer fits, so the standing "6 boards, proved" is false)');
}

// ---------------------------------------------------------------------------
console.log('\nThe money objective with nothing priced refuses, by name');
// Red on purpose: `const unpriced = false && ...` in the engine turns all six
// of these red at once, because the page then answers, cheerfully, in dollars
// derived from millimetres: "6 boards costing $0.00.".
{
  await freshPage();
  await setJob({ objective: 'money', stock: '2400', kerf: '3' });
  await solving(() => page.click('#go'));
  is(await headline(), 'No prices, so no price.', 'it refuses by name');
  is(await attr('#out .verdict', 'class'), 'verdict bad', 'and says so in the refusing style');
  is(/\$/.test(await outText()), false, 'and prints no dollar figure anywhere in the result');
  is(await boardCount(), 0, 'no plan is drawn');
  is(await page.locator('#certPanel').count(), 0, 'and no certificate is offered for a question it declined to answer');
  is(/nothing here is settled/.test(await outText()), false, 'it does not fall back to saying nothing is settled');

  // THE PAIRED PRESENCE. "No dollar figure" must not pass on a page that has
  // stopped printing money at all.
  await page.fill('#stock', '2400 @ 18.40');
  await solving(() => page.click('#go'));
  is(/\$\d/.test(await outText()), true, 'add a price and the money comes back, so the silence above was about the missing price');
  is(await headline(), '6 boards costing $110.40.', 'and the priced answer is six boards at $110.40');
}

// ---------------------------------------------------------------------------
console.log('\nA job the yard cannot supply is answered, not shrugged at');
// Red on purpose: `boardsNeededAtLeast: null` in the engine turns the two
// counted assertions red while leaving the headline intact, and
// `shortfallOfStock: false` turns the headline red as well, which is the state
// the page was in before tonight.
{
  await freshPage();
  await setJob({ objective: 'boards', stock: '2400 x 2', kerf: '3', pieces: '10 x 1800 - stud' });
  await solving(() => page.click('#go'));
  is(await headline(), 'Not enough stock.', 'it says so');
  const bolds = await page.locator('#out .verdict .why b').allTextContents();
  is(bolds[0], '10 boards', 'and how many boards the list needs at least, which is a certified figure and not a guess');
  is(bolds[1], '2', 'and how many boards you have');
  const t = await outText();
  is(/The parts come to 18030 mm of material/.test(t), true, 'and the material the parts come to, in the reader\'s own units');
  is(/the stock on hand offers 4800 mm/.test(t), true, 'and the material the yard can offer');
  is(/nothing here is settled/.test(t), false, 'it does not claim nothing is settled, because something is');
  is(await page.locator('#out .warnbox').count(), 0, 'and it does not fall back to a red box quoting internal tick counts');
  is(await boardCount(), 0, 'no plan is drawn for a job that cannot be cut');

  // THE PAIRED PRESENCE. The refusal must be about the supply and not about the list.
  await page.fill('#stock', '2400 x 12');
  await solving(() => page.click('#go'));
  is(await headline(), '10 boards.', 'raise the supply and the same list cuts in ten boards');
  is(await stampText(), 'proved', 'proved, so the refusal above was about the yard and not about the parts');
}

// ---------------------------------------------------------------------------
console.log('\nThe certificate panel adds up, on limited priced stock');
// Red on purpose: printing the scarce allowance one short of its own sum turns
// the "adds up" assertion red while leaving every other number on the page
// untouched, which is exactly the failure shape a reader doing the arithmetic
// by hand would hit. Printing the allowance without its breakdown, or dropping
// the subtraction clause from the total, each turn a different line red.
{
  await freshPage();
  await setJob({
    system: 'metric', objective: 'money', kerf: '3',
    stock: '4800 x 3 @ 30.00\n2400 @ 18.40',
    pieces: '4 x 2250\n9 x 1425\n5 x 1250\n7 x 600',
  });
  await solving(() => page.click('#go'));
  is(await headline(), '12 boards costing $255.60.', 'twelve boards at $255.60');
  is(await stampText(), 'proved', 'and the certificate meets the plan, so it is stamped proved');
  is(await openCertPanel(), true, 'the certificate panel is there to open');
  const scr = await scrapeCertificate();
  const r = reconcileCertificate(scr, {
    label: 'limited priced stock', expectScarcity: true, costMinor: 3000, stockCount: 3,
  });
  if (r) {
    // THE EQUALITY THAT FAILS IF THE BOUND IS MERELY WEAK. A panel whose
    // certificate had come out below the plan would still print an internally
    // consistent page; only this line notices.
    is(r.boundFigure, 25560, 'the bound the panel concludes with is $255.60');
    is(r.planFigure, r.boundFigure, 'and the plan costs exactly that, which is what "proved" means here');
  }

  console.log('\nAnd the copied certificate re-verifies away from the page');
  // Red on purpose: copying a zero for every scarcity weight, which is the bug
  // app.mjs's own comments describe, turns the "verifies" assertion red. So does
  // raising any single weight by one, which the controls below do in place.
  if (await page.locator('#copyCert').count()) await page.click('#copyCert');
  await page.waitForTimeout(250);
  const copied = await page.evaluate(() => navigator.clipboard.readText());
  is(copied.startsWith('# Cut List lower-bound certificate'), true, 'the copy button puts a certificate on the clipboard');
  const parsed = parseCopiedCertificate(copied);
  is(parsed.order.length, scr.rows.length, 'with one weight for every part length the panel showed');
  is(parsed.missingDemand.length, 0, 'and a demand beside every weight, so the copy can be checked on its own');
  is(parsed.denom, NUM(scr.denom), 'over the denominator the panel printed');
  const check = certify(parsed.prob, parsed.cert);
  is(check.valid, true, 'and it VERIFIES, in exact integers, in a process that never saw the page');
  near(check.value, parsed.claim, 1e-6, 'to exactly the value the copy claims for itself');
  is(Math.ceil(check.value - 1e-9), 25560, 'which rounds up to $255.60');
  // The equality that fails if the bound is merely weak rather than wrong: the
  // copied certificate, re-verified by a stranger, has to reach the very figure
  // the plan on screen costs. A weak bound re-verifies perfectly well and lands
  // short, and every other assertion in this section would still pass.
  is(Math.ceil(check.value - 1e-9), r ? r.planFigure : null,
    'the same figure the plan on screen costs, so the copy alone settles the job');

  // Both negative controls, because a re-verifier that cannot fail proves nothing.
  is(certify(parsed.prob, { ...parsed.cert, num: parsed.cert.num.map((v, i) => (i === 0 ? v + 1 : v)) }).valid, false,
    'raise one weight by one and the same check refuses it');
  is(certify(parsed.prob, { ...parsed.cert, stockNum: parsed.cert.stockNum.map(() => 0) }).valid, false,
    'drop the scarcity weights and it refuses too, which is why the copy has to carry them');
}

// ---------------------------------------------------------------------------
console.log('\nThe same panel adds up on the ordinary job, with no scarcity term');
{
  await freshPage();
  is(await openCertPanel(), true, 'the default job offers a certificate');
  const scr = await scrapeCertificate();
  const r = reconcileCertificate(scr, { label: 'the bookcase', expectScarcity: false });
  if (r) {
    is(r.boundFigure, 6, 'the bound the panel concludes with is six boards');
    is(r.planFigure, 6, 'and the plan uses six');
  }
  if (await page.locator('#copyCert').count()) await page.click('#copyCert');
  await page.waitForTimeout(250);
  const parsed = parseCopiedCertificate(await page.evaluate(() => navigator.clipboard.readText()));
  const check = certify(parsed.prob, parsed.cert);
  is(check.valid, true, 'and its copy re-verifies away from the page');
  near(check.value, parsed.claim, 1e-9, 'to the value it claims');
  is(Math.ceil(check.value - 1e-9), 6, 'which rounds up to the six boards the plan uses');
  is(certify(parsed.prob, { ...parsed.cert, num: parsed.cert.num.map((v, i) => (i === 0 ? v + 1 : v)) }).valid, false,
    'and one weight raised by one is refused, so that check can fail');
}

// ---------------------------------------------------------------------------
console.log('\nThe certificate re-checks from what is on screen');
{
  await freshPage();
  await openCertPanel();
  await page.click('#recheck');
  await page.waitForTimeout(400);
  const cls = await attr('#recheckOut', 'class');
  const txt = (await text('#recheckOut')) || '';
  is(cls, 'verdictline good', 'the re-check comes back settled');
  ok(`  it says: ${txt.slice(0, 110)}…`);

  // negative control: doctor the displayed weights and re-check. It must refuse.
  await page.evaluate(() => {
    const cell = document.querySelector('#certTable tbody tr td[data-num]');
    cell.textContent = String(Number(cell.textContent) * 4 + 1000);
  });
  await page.click('#recheck');
  await page.waitForTimeout(400);
  is(await attr('#recheckOut', 'class'), 'verdictline bad',
    'and a doctored weight is refused, so the button is really checking');

  // the other half of the same promise: the denominator is read off the page too.
  await freshPage();
  await openCertPanel();
  await page.evaluate(() => {
    const d = document.getElementById('certDenom');
    d.textContent = String(Number(d.textContent) * 2);
  });
  await page.click('#recheck');
  await page.waitForTimeout(400);
  const cls3 = await attr('#recheckOut', 'class');
  is(cls3 === 'verdictline' || cls3 === 'verdictline bad', true,
    'and doubling the displayed denominator stops it saying "settled", so the denominator is read off the page as well');
}

// ---------------------------------------------------------------------------
console.log('\nA paste that looks like a spreadsheet is read or refused, never guessed at');
// Red on purpose: dropping the tab rewrite from `parseList` turns every tab
// assertion red, because a tab then falls through to the same unreadable pair a
// space makes, and the page refuses the line instead of cutting it.
{
  // A tab between the count and the length is what a spreadsheet paste is.
  await freshPage();
  await setJob({ system: 'metric', stock: '2400', kerf: '3', pieces: '2\t1800\n5\t760' });
  await solving(() => page.click('#go'), 'a tab-separated paste in millimetres');
  const tab = await drawnParts();
  is(tab['1800'], 2, 'a tab-separated paste of "2<tab>1800" cuts two parts of 1800');
  is(tab['760'], 5, 'and "5<tab>760" cuts five of 760');
  is(Object.keys(tab).length, 2, 'and nothing else');

  // A space between them cannot be told from a length with a thousands
  // separator, so it must be refused rather than guessed.
  await freshPage();
  await setJob({ system: 'metric', stock: '2400', kerf: '3', pieces: '2 1800' });
  await refusedBeforeSolving(() => page.click('#go'));
  is(await errorsVisible(), true, 'a space-separated "2 1800" is refused rather than read');
  is(/line 1/.test((await errorsText()) || ''), true, 'and the refusal names the line');
  // The property is "a reason is given", not "the reason is this sentence". Keying this to
  // the literal wording made it fail the moment the wording improved from "could not read
  // a length" to one that names both readings and shows how to write either.
  is(/\(.+\)/.test((await errorsText()) || ''), true, 'and gives a reason');
  is(/x 1800|21800/.test((await errorsText()) || ''), true, 'and the reason shows how to write each reading');

  // The same shape, in plain numbers, where there is no unit to disambiguate.
  await freshPage();
  await setJob({ system: 'bare', stock: '18', kerf: '0', pieces: '2 6' });
  await refusedBeforeSolving(() => page.click('#go'));
  is(await errorsVisible(), true, 'so is "2 6" in plain numbers');

  await freshPage();
  await setJob({ system: 'bare', stock: '18', kerf: '0', pieces: '2\t6' });
  await solving(() => page.click('#go'), 'a tab-separated paste in plain numbers');
  const bareTab = await drawnParts();
  is(bareTab['6'], 2, 'while "2<tab>6" in plain numbers cuts two sixes');

  // THE PAIRED PRESENCE for the whole section: the page's ambiguity warning is
  // reachable, so "no warning was shown" below is a fact and not a dead branch.
  await freshPage();
  await setJob({ system: 'metric', stock: '2400', kerf: '3', pieces: '900 x 4' });
  await solving(() => page.click('#go'));
  is(await page.locator('#out .warnbox').count(), 1,
    '"900 x 4" raises the ambiguity warning, so the page can say which reading it used');

  // AND THE TWO THAT MATTER MOST, because here the misreading cuts wood. A
  // space between two digit groups where the second has exactly three digits is
  // read as a thousands separator, so "4 900" becomes one part 4,900 mm long.
  // With stock short enough the page refuses it for being too long, which at
  // least names the length; with stock long enough it plans it, silently, and
  // the reader gets one board instead of four parts.
  await freshPage();
  await setJob({ system: 'metric', stock: '5000', kerf: '3', pieces: '4 900' });
  await solving(() => page.click('#go'));
  {
    const parts = await drawnParts();
    const readAsFourNineHundreds = parts['900'] === 4 && Object.keys(parts).length === 1;
    const saidSomething = (await errorsVisible()) || (await page.locator('#out .warnbox').count()) > 0;
    okIf(readAsFourNineHundreds || saidSomething,
      'a space-separated "4 900" on 5000 stock is either read as four parts of 900 or flagged; '
      + `it must not become one silent 4,900 mm part (drew ${JSON.stringify(parts)})`);
  }

  // Imperial has the same hole and no length limit to catch it: space-separated
  // groups are SUMMED, so "2 46" becomes a single 48 inch part, it fits the
  // stock, and a plan for the wrong job is printed with no complaint at all.
  await freshPage();
  await setJob({ system: 'imperial', stock: "12'", kerf: '1/8', pieces: '2\t46' });
  await solving(() => page.click('#go'), 'a tab-separated paste in inches');
  const impTab = await drawnParts();
  is(impTab['46'], 2, 'in inches, "2<tab>46" cuts two parts of 46 inches');

  await freshPage();
  await setJob({ system: 'imperial', stock: "12'", kerf: '1/8', pieces: '2 46' });
  await solving(() => page.click('#go'));
  {
    const parts = await drawnParts();
    const readAsTwoFortySixes = parts['46'] === 2 && Object.keys(parts).length === 1;
    const saidSomething = (await errorsVisible()) || (await page.locator('#out .warnbox').count()) > 0;
    okIf(readAsTwoFortySixes || saidSomething,
      'in inches, a space-separated "2 46" is either read as two parts of 46 or flagged; '
      + `it must not become one silent 48 inch part (drew ${JSON.stringify(parts)})`);
  }
}

// ---------------------------------------------------------------------------
console.log('\nEvery shipped example gives the verdict the page claims');
for (const spec of SPECIMENS) {
  await freshPage();
  await solving(() => page.locator('.chip', { hasText: spec.name }).click());
  await page.waitForSelector('#out .verdict .big', { timeout: 30000 });
  const head = await headline();
  is(await boardCount(), spec.expect.boards, `${spec.id}: ${spec.expect.boards} boards drawn`);
  const stamp = await stampText();
  const wanted = spec.expect.proof === 'certificate' ? 'proved' : 'proved by search';
  is(stamp, wanted, `${spec.id}: stamped "${wanted}"`);
  if (spec.expect.money != null) {
    is(head.includes('$' + (spec.expect.money / 100).toFixed(2)), true, `${spec.id}: the price is printed`);
  }
}

// ---------------------------------------------------------------------------
console.log('\nThe puzzle refuses an over-full board and never lets five work');
{
  await page.goto(url, { waitUntil: 'load' });
  await page.waitForSelector('#puzzle', { timeout: 20000 });
  // 12 and 9 on the same board is 21, over the capacity of 18
  await page.locator('#puzPieces .pc', { hasText: /^12$/ }).first().click();
  await page.locator('#puzBoards .pb .slot').first().click();
  await page.locator('#puzPieces .pc', { hasText: /^9$/ }).first().click();
  await page.locator('#puzBoards .pb .slot').first().click();
  const msg = (await page.textContent('#puzMsg')).trim();
  is(msg, 'That board is over eighteen.', 'the over-capacity board is called out');
  is(await page.locator('#puzBoards .pb .slot.over').count(), 1, 'and shown');
  await page.click('#puzGive');
  const why = (await page.textContent('#puzMsg')).trim();
  is(/no five-board arrangement/.test(why), true, 'and the answer names the impossibility, with its source');
}

// ---------------------------------------------------------------------------
console.log('\nIt fits on a phone');
for (const w of [390, 768, 1100]) {
  await page.setViewportSize({ width: w, height: 900 });
  await page.goto(url, { waitUntil: 'load' });
  await page.waitForSelector('#out .verdict', { timeout: 30000 });
  const over = await page.evaluate(() => document.documentElement.scrollWidth - window.innerWidth);
  over <= 1 ? ok(`${w}px, no horizontal overflow`) : bad(`${w}px overflows by ${over}px`);
}
await page.setViewportSize({ width: 1100, height: 900 });

// ---------------------------------------------------------------------------
console.log('\nNothing leaves this origin, in this build');
{
  // WHAT THIS CAN AND CANNOT CATCH, said plainly, because the version of this
  // section that ran until tonight could not fail. It is served by a local
  // static server, so the site's analytics injection does not exist here and a
  // count of off-origin requests is zero by construction rather than by virtue.
  // What it still catches is a change to the TOOL: an import from a CDN, a
  // font pulled from elsewhere, a telemetry call added to app.mjs. That is
  // worth keeping. What it cannot see is anything the deployed site wraps
  // around the page, which is what the section after this one is for.
  // The job, typed in and solved, then searched for in everything this browser
  // sent. Against the unmutated tool it finds nothing, and it would find
  // nothing whatever the tool did, because there is nowhere to send it to. What
  // this pair of lines is really for is that it is the SAME detector the
  // deployed check below runs, and adding one telemetry call to app.mjs turns
  // it red here. A detector proven on a page we control, applied to a page we
  // do not.
  await freshPage();
  await setJob({ system: 'metric', kerf: '3', ...TOKEN_JOB });
  await solving(() => page.click('#go'));
  is((await page.evaluate(() => location.search)).includes('keelson'), true,
    'the job reaches the page\'s own query string, so there is something here to leak');
  await localRequests.settle();
  const localLeaks = leaksIn(localRequests.seen, TOKENS);
  is(localLeaks.length, 0, `nothing this build sent carries any part of the job${localLeaks.length ? ': ' + localLeaks.join('; ') : ` (${localRequests.seen.length} requests searched, url, body and referrer)`}`);

  is(offOrigin.length, 0, `no off-origin request from any page this run touched${offOrigin.length ? ': ' + offOrigin.join(', ') : ''}`);
  const abs = await page.evaluate(async () => {
    const files = ['./app.mjs', './engine.mjs', './units.mjs', './specimens.mjs', './worker.mjs',
                   './lp.mjs', './cns.mjs', './knapsack.mjs'];
    const out = [];
    for (const f of files) {
      const r = await fetch(new URL(f, location.href));
      if (!r.ok) continue;
      const t = await r.text();
      for (const m of t.matchAll(/https?:\/\/[^\s'"`)]+/g)) out.push(f + ': ' + m[0]);
    }
    return out;
  });
  is(abs.length, 0, `no absolute URL anywhere in the tool's own scripts${abs.length ? ': ' + abs.join(', ') : ''}`);
}

// ---------------------------------------------------------------------------
console.log('\nNothing leaves the DEPLOYED page either, which is where the analytics live');
if (!LIVE) {
  bad('the deployed-site section DID NOT RUN (--no-live was passed), so nothing here has checked the page a reader actually loads');
} else {
  // The only assertion worth making against a page wrapped in somebody else's
  // analytics is not "no third party is contacted", because one is: it is that
  // no request anywhere carries the reader's job. So a job is typed in with
  // words no beacon could produce by accident, the page is made to solve it,
  // and then every request this browser made is searched, in its URL, its body
  // and its referrer, for any of them.
  //
  // The detector is the same code path the local run exercises, and the local
  // run can be made to fail it (mutation E in the header), so this is a proven
  // detector applied to a page nobody here can modify.
  //
  // One page view lands in the site's own traffic counter every time this runs.
  // That is the price of checking the real thing rather than a copy of it.
  const live = await browser.newContext({ locale: 'en-US' });
  const lp = await live.newPage();
  const rec = recordRequests(lp);
  const seen = rec.seen;
  try {
    await lp.goto(LIVE_URL, { waitUntil: 'load', timeout: 45000 });
    await lp.waitForSelector('#out .verdict', { timeout: 45000 });
    ok('the deployed page loads and reaches a verdict');

    await lp.fill('#stock', TOKEN_JOB.stock);
    await lp.fill('#pieces', TOKEN_JOB.pieces);
    await lp.click('#go');
    await lp.waitForFunction(() => {
      const s = document.getElementById('status');
      return s && s.textContent === '';
    }, null, { timeout: 90000 });

    // The anti-vacuous control. If the job never reached the page's own state,
    // there would be nothing for a beacon to leak and the search below would
    // pass on an empty question.
    const inState = await lp.evaluate(() => location.search + ' ' + document.getElementById('pieces').value);
    is(TOKENS.every((t) => inState.includes(t)), true,
      'the job really is in the deployed page\'s own URL and form, so there is something there to leak');

    // REPORTED, NOT ASSERTED, and the reason is worth stating: the deployed
    // build lags this checkout, so a behaviour assertion here would be an
    // assertion about the last deploy rather than about the code in hand. The
    // behaviour is asserted against the local build above. This line exists so
    // that a run of this file says out loud what production is currently doing,
    // which is how the "[object PointerEvent]" note was found in the first place.
    const deployed = await lp.evaluate(() => {
      const n = document.querySelector('#out > p.note');
      return { note: n ? n.textContent.trim() : null, object: /\[object /.test(document.body.textContent) };
    });
    note(deployed.note || deployed.object
      ? `deployed build prints a stray note above the verdict: ${JSON.stringify(deployed.note)} (not asserted here; the local build is)`
      : 'deployed build prints no stray note above the verdict');

    // Navigate away to about:blank rather than to another page of the site, so
    // that any beacon held until unload is flushed without inflating some other
    // page's count in the process.
    await lp.goto('about:blank', { waitUntil: 'load', timeout: 30000 });
    await lp.waitForTimeout(3000);
    await rec.settle();

    const leaks = leaksIn(seen, TOKENS);
    is(leaks.length, 0, `no request carries any part of the job${leaks.length ? ': ' + leaks.join('; ') : ` (${seen.length} requests searched, url, body and referrer)`}`);

    const ALLOWED = new Set(['artwaste.land', 'static.cloudflareinsights.com', 'cloudflareinsights.com']);
    const hosts = [...new Set(seen.map((r) => { try { return new URL(r.url).host; } catch (e) { return r.url; } }))]
      .filter((h) => h && h !== 'about:blank');
    const strangers = hosts.filter((h) => !ALLOWED.has(h));
    is(strangers.length, 0, `the deployed page talks to nobody new${strangers.length ? ': ' + strangers.join(', ') : ` (${hosts.join(', ')})`}`);
  } catch (e) {
    bad(`the deployed page could not be checked: ${String(e && e.message || e).split('\n')[0]}. `
      + 'If this box has no network, say so and run with --no-live, which fails by name rather than passing quietly.');
  } finally {
    await live.close().catch(() => {});
  }
}

// ---------------------------------------------------------------------------
console.log('\nNo script errors');
is(errors.length, 0, `console clean${errors.length ? ': ' + errors.slice(0, 3).join(' | ') : ''}`);

if (SHOT) {
  await page.setViewportSize({ width: 1280, height: 800 });
  await page.goto(url, { waitUntil: 'load' });
  await page.waitForSelector('#out .board', { timeout: 30000 });
  await page.evaluate(() => {
    const y = document.getElementById('out').getBoundingClientRect().top + window.scrollY;
    window.scrollTo(0, Math.max(0, y - 96));
  });
  await page.waitForTimeout(400);
  const out = path.join(ROOT, 'public', 'media', 'tool-cut-list.png');
  await page.screenshot({ path: out });
  console.log(`\nwrote ${out}`);
}

await browser.close();
server.close();
if (failures.length) {
  console.log('\nwhat failed:');
  for (const f of failures) console.log('  \x1b[31m' + f + '\x1b[0m');
}
console.log(fail
  ? `\n${pass} passed, ${fail} failed`
  : `\nall ${pass} page checks passed`);
process.exit(fail ? 1 : 0);
