// verify.mjs: the check behind the stratum
// "The Demonstration That Cannot Fail" (/strata/the-demonstration-that-cannot-fail/).
//
// THE CLAIM THE PAGE MAKES. The standard classroom demonstration of why metal feels
// colder than wood, a rail of specimens at one room temperature pressed in turn, is a
// severe test of one account of "cold" and no test at all of several others. In the
// specimen set everybody uses (copper, steel, glass, oak, foam), conductivity k,
// effusivity sqrt(k rho c), volumetric heat capacity rho c and density rho rank the
// five materials IDENTICALLY. No outcome of the demonstration distinguishes them.
//
// WHAT THIS SCRIPT PROVES, offline and from scratch:
//   1. The specimen table and the thermal quantities computed from it.
//   2. The confound: six of the fifteen account pairs have no distinguishing specimen
//      pair at all, and three of those six are confounded for CERTAIN, meaning the
//      co-ranking survives every value inside every published range.
//   3. The demonstration does do one job, and does it severely: it kills "the object
//      is colder" by more than eleven kelvin.
//   4. Ten specimen pairs in the pool invert conductivity against effusivity, and when
//      the literature's own disagreement is propagated through them, exactly ONE
//      survives: fused silica against water, by 3.3 per cent in effusivity.
//   5. That survivor is worth 0.16 K at the fingertip, while a published two-alternative
//      forced-choice experiment found people at CHANCE on copper against stainless
//      steel, which this model puts 1.36 K apart. So at a measured human resolution no
//      subset of the pool, at any size, separates conductivity from effusivity.
//   6. The exact minimum test set, against two greedy rules, neither of which finds it.
//      On the cupboard a demonstrator could actually assemble, the smallest bench that
//      separates all six accounts is four specimens and contains no metal. (The
//      ordering variant of this problem is SET COVER WITH PAIRS, not MINIMUM TEST SET,
//      so the standard logarithmic guarantee does not transfer to it.)
//   7. The axis nobody uses: thickness. The finite-slab solver reproduces the analytic
//      half-space contact temperature to machine precision, and shows one material at
//      two thicknesses spanning nearly as much as the whole classic bench, which refutes every
//      account in the family at once because none of them contains a length.
//
// It runs the PAGE'S OWN SCRIPTS, loaded the way a browser loads them (node:vm, as
// classic scripts), not a re-implementation of them. If the page and this file ever
// disagree it is because someone edited one of them, which is the point.
//
//   run:  node research/the-demonstration-that-cannot-fail/verify.mjs
//
// No dependencies.

import { readFileSync, existsSync } from 'node:fs';
import { fileURLToPath } from 'node:url';
import path from 'node:path';
import vm from 'node:vm';

const HERE = path.dirname(fileURLToPath(import.meta.url));
const PAGE = path.resolve(HERE, '../../public/strata/the-demonstration-that-cannot-fail');

function loadPageScripts(files) {
  const win = {};
  const sandbox = {
    window: win, console, Math, Float64Array, Float32Array, Array, Object, Number,
    String, JSON, Set, Map, isNaN, parseFloat, parseInt, Infinity, NaN,
  };
  sandbox.globalThis = sandbox;
  vm.createContext(sandbox);
  for (const f of files) {
    const p = path.join(PAGE, f);
    vm.runInContext(readFileSync(p, 'utf8'), sandbox, { filename: p });
  }
  return win;
}

const win = loadPageScripts(['engine.js', 'materials.js', 'spread.js']);
const E = win.DEMO;
const M = win.DEMO_MATERIALS;
const S = win.SPREAD;

let fails = 0, checks = 0;
const ok = (name, cond, extra = '') => {
  checks++;
  if (!cond) fails++;
  console.log(`${cond ? '  ok  ' : 'FAIL  '}${String(checks).padStart(3, '0')}  ${name}${extra ? '   ' + extra : ''}`);
};
const near = (a, b, eps) => Math.abs(a - b) <= eps;
const head = (s) => console.log(`\n── ${s} ──`);

// ── the standing context ────────────────────────────────────────────────────
// Skin as a thermal solid, from Ho's review table (k 0.37, rho c 3.7e6, e 1.17e3).
// Every result is checked for sensitivity to this at the end.
const SKIN = { k: 0.37, rho: 1100, c: 3390 };
const ctx = (delta = 0, skin = SKIN) => ({
  skin, eSkin: E.effusivity(skin), Tskin: 33, Troom: 20, delta,
});
const C0 = ctx(0);
const CLASSIC = M.set(...M.CLASSIC);
const hk = E.hypothesisById('H_k'), he = E.hypothesisById('H_e');
const hrho = E.hypothesisById('H_rho'), ha = E.hypothesisById('H_a'), hc = E.hypothesisById('H_c');

// ── 1. the specimen table ───────────────────────────────────────────────────
head('the specimen pool');
console.log('  id                    k        rho*c         e     alpha [m2/s]     T_c [C]   source');
for (const m of M.MATERIALS) {
  console.log('  ' + m.id.padEnd(18) + String(m.k).padStart(8) + E.volHeatCapacity(m).toExponential(3).padStart(13) +
    E.effusivity(m).toFixed(0).padStart(10) + E.diffusivity(m).toExponential(3).padStart(15) +
    E.feltTemp(m, C0).toFixed(3).padStart(12) + '   ' + m.src + (m.alt ? '  [alt for ' + m.alt + ']' : ''));
}
ok('effusivity is the geometric blend of the three properties',
  near(E.effusivity({ k: 4, rho: 5, c: 5 }), 10, 1e-12));
ok('the contact temperature is the effusivity-weighted average of the two',
  near(E.contactTemp(1000, 33, 3000, 20), (1000 * 33 + 3000 * 20) / 4000, 1e-12));
ok('a specimen with the skin\'s own effusivity is felt at the midpoint',
  near(E.feltTemp({ k: SKIN.k, rho: SKIN.rho, c: SKIN.c }, C0), 26.5, 1e-9));
ok('every specimen carries a named source',
  M.MATERIALS.every((m) => M.SOURCES[m.src] && M.SOURCES[m.src].cite));
ok('alternative published values are kept out of the default pool',
  M.POOL.length === M.MATERIALS.filter((m) => !m.alt).length &&
  M.POOL.length < M.MATERIALS.length, `${M.POOL.length} of ${M.MATERIALS.length}`);
ok('water is the best-determined entry: its conductivity range is under 2 per cent wide',
  (M.byId('water').kR[1] - M.byId('water').kR[0]) / M.byId('water').k < 0.02);

// ── 2. the confound ─────────────────────────────────────────────────────────
head('what the classic five can and cannot separate');
for (const [A, B] of [[hk, he], [hk, hc], [hk, hrho], [he, hc], [he, hrho], [hc, hrho]]) {
  const r = E.rankCorrelation(A, B, CLASSIC, C0);
  ok(`${A.short} and ${B.short} rank the classic five identically`, r === 1, `Spearman = ${r}`);
}
ok('diffusivity is the one account the classic bench does separate',
  Math.abs(E.rankCorrelation(hk, ha, CLASSIC, C0)) < 1,
  `Spearman(k, alpha) = ${E.rankCorrelation(hk, ha, CLASSIC, C0).toFixed(3)}`);

const smClassic = E.separationMatrix(CLASSIC, E.HYPOTHESES, C0);
ok('with a perfect instrument the classic five separate 9 of the 15 account pairs',
  smClassic.separated === 9 && smClassic.pairs === 15, `${smClassic.separated}/${smClassic.pairs}`);
ok('and the six it cannot separate are every pair among {k, e, rho c, rho}',
  smClassic.confounded.join(' ') === 'H_k/H_e H_k/H_c H_k/H_rho H_e/H_c H_e/H_rho H_c/H_rho',
  smClassic.confounded.join(', '));

// Is the confound a fact about the world or about a value choice? An ordering is
// CERTAIN when the two published intervals do not overlap.
head('which of the confounds survive the literature\'s own disagreement');
{
  const iv = (m, q) => q === 'k' ? E.bounds(m, 'k')
    : q === 'rho' ? E.bounds(m, 'rho')
      : q === 'e' ? E.effusivityBounds(m)
        : { lo: E.bounds(m, 'rho').lo * E.bounds(m, 'c').lo, hi: E.bounds(m, 'rho').hi * E.bounds(m, 'c').hi };
  const certainOrder = (q, a, b) => { const p = iv(a, q), r = iv(b, q); return p.lo > r.hi ? 1 : (r.lo > p.hi ? -1 : 0); };
  const certainlyConfounded = (q1, q2) => {
    for (let x = 0; x < CLASSIC.length; x++)
      for (let y = x + 1; y < CLASSIC.length; y++) {
        const o1 = certainOrder(q1, CLASSIC[x], CLASSIC[y]), o2 = certainOrder(q2, CLASSIC[x], CLASSIC[y]);
        if (o1 === 0 || o2 === 0 || o1 !== o2) return false;
      }
    return true;
  };
  for (const [q1, q2, label] of [['k', 'e', 'k/e'], ['k', 'rho', 'k/rho'], ['e', 'rho', 'e/rho']])
    ok(`${label} is confounded for CERTAIN, at every value in every published range`,
      certainlyConfounded(q1, q2));
  for (const [q1, q2, label] of [['k', 'rhoc', 'k/rho c'], ['e', 'rhoc', 'e/rho c'], ['rhoc', 'rho', 'rho c/rho']])
    ok(`${label} is confounded at the published point values but NOT for certain`,
      !certainlyConfounded(q1, q2));
  console.log('  (the escape is copper against steel: their rho c intervals overlap, so that one ordering is undecided)');
}

// NEGATIVE CONTROL: the confound must be a property of the specimen set, not of the code.
{
  const repaired = M.set('copper', 'steel', 'silica', 'water', 'foam');
  const sm = E.separationMatrix(repaired, E.HYPOTHESES, C0);
  ok('CONTROL: swapping oak for water and glass for fused silica breaks the k/e confound',
    !sm.confounded.includes('H_k/H_e'), `still confounded: ${sm.confounded.join(', ') || 'nothing'}`);
}

// ── 3. the one job the demonstration does do ────────────────────────────────
head('the demonstration IS a severe test of "the object is colder"');
{
  const row = smClassic.rows.find((r) => r.A === 'H_T' && r.B === 'H_e');
  const biggest = Math.max(...row.inPrinciple.map((p) => p.gapK));
  ok('every specimen sits at one temperature, so H_T predicts no difference at all',
    E.prediction(E.hypothesisById('H_T'), M.byId('copper'), M.byId('foam'), C0) === 0);
  ok('yet the felt spread across the five exceeds 11 K', biggest > 11, `${biggest.toFixed(2)} K`);
}

// ── 4. the repair, propagated ───────────────────────────────────────────────
head('every k-against-e inversion in the pool, with the literature ranges propagated');
{
  const inv = E.inversions(M.POOL, hk, he, C0);
  for (const p of inv)
    console.log(`  ${(p.a + ' > ' + p.b).padEnd(26)}${p.verdict.toUpperCase().padEnd(12)}felt gap ${p.gapK.toFixed(3)} K   e [${p.eA.lo.toFixed(0)}, ${p.eA.hi.toFixed(0)}] vs [${p.eB.lo.toFixed(0)}, ${p.eB.hi.toFixed(0)}]`);
  const robust = inv.filter((p) => p.verdict === 'robust');
  ok('ten specimen pairs invert conductivity against effusivity at the point values',
    inv.length === 10, `${inv.length}`);
  ok('exactly one of them survives the propagated ranges', robust.length === 1, `${robust.length}`);
  ok('and it is fused silica against water',
    robust[0] && robust[0].a === 'silica' && robust[0].b === 'water');
  ok('fused silica conducts heat better than water, with certainty',
    robust[0].kOrder, `k [${robust[0].kA.lo}, ${robust[0].kA.hi}] vs [${robust[0].kB.lo}, ${robust[0].kB.hi}]`);
  ok('and draws it from skin more slowly, with certainty, by 3.3 per cent',
    robust[0].eOrder && near(robust[0].eMargin, 0.033, 0.004),
    `${(robust[0].eMargin * 100).toFixed(1)} per cent`);
  ok('window glass against water is BROKEN: the two effusivity intervals overlap',
    inv.find((p) => p.a === 'glass' && p.b === 'water').verdict === 'broken');
  ok('and the reason is a textbook: Incropera puts soda lime glass at k = 1.4, which flips it',
    E.effusivity(M.byId('glass_incropera')) > E.effusivity(M.byId('water')),
    `e = ${E.effusivity(M.byId('glass_incropera')).toFixed(0)} vs water ${E.effusivity(M.byId('water')).toFixed(0)}`);
  ok('CONTROL: an inversion with an unsourced range is reported incomplete, never robust',
    inv.some((p) => p.verdict === 'incomplete'),
    inv.filter((p) => p.verdict === 'incomplete').map((p) => p.a + '>' + p.b).join(', '));
}

// ── 5. the instrument, anchored to a measurement rather than a guess ────────
head('the resolution a fingertip has actually been measured to have');
{
  const anchor = E.feltGap(M.byId('copper'), M.byId('stainless'), C0);
  const eRatio = E.effusivity(M.byId('copper')) / E.effusivity(M.byId('stainless'));
  console.log(`  copper against stainless steel: effusivity ratio ${eRatio.toFixed(1)}, felt gap ${anchor.toFixed(3)} K`);
  console.log('  Jones and Berris (HAPTICS 2003) put subjects at 42 per cent correct on that pair, i.e. chance.');
  ok('so the fingertip threshold for this task exceeds 1.3 K', anchor > 1.3, `${anchor.toFixed(3)} K`);

  const silicaWater = E.feltGap(M.byId('silica'), M.byId('water'), C0);
  ok('the one robust discriminating pair is worth 0.16 K', near(silicaWater, 0.163, 0.01),
    `${silicaWater.toFixed(3)} K`);
  ok('which is more than eight times below that measured threshold',
    anchor / silicaWater > 8, `${(anchor / silicaWater).toFixed(1)} times`);

  const best = Math.max(...E.inversions(M.POOL, hk, he, C0).map((p) => p.gapK));
  ok('even the LARGEST k-against-e inversion in the pool falls below it', best < anchor,
    `${best.toFixed(3)} K vs ${anchor.toFixed(3)} K`);
  ok('so at that resolution NO subset of the pool separates conductivity from effusivity',
    E.minTestSet(M.POOL, [hk, he], ctx(anchor), 6).size === null);
  ok('CONTROL: at a resolution just below the largest inversion, a set does exist',
    E.minTestSet(M.POOL, [hk, he], ctx(best - 1e-6), 6).size !== null);
}

// ── 6. the minimum test set ─────────────────────────────────────────────────
head('the smallest bench that could come out wrong');
{
  for (const d of [0, 0.1, 0.163, 0.5, 1.0]) {
    const mts = E.minTestSet(M.POOL, E.HYPOTHESES, ctx(d), 5);
    console.log(`  resolution ${d.toFixed(3)} K  ->  ${mts.size ? mts.size + ' specimens: ' + mts.set.join(', ') : 'no bench of size 5 or under works'}`);
  }
  const mts0 = E.minTestSet(M.POOL, E.HYPOTHESES, C0, 5);
  ok('a perfect instrument needs only three specimens', mts0.size === 3, mts0.set.join(', '));
  ok('no pair of specimens is ever enough, whatever they are',
    !(() => {
      for (let i = 0; i < M.POOL.length; i++)
        for (let j = i + 1; j < M.POOL.length; j++)
          if (E.covers([M.POOL[i], M.POOL[j]], E.HYPOTHESES, C0)) return true;
      return false;
    })());
  ok('the found set really does cover all 15 account pairs',
    E.covers(M.set(...mts0.set), E.HYPOTHESES, C0));
  ok('the classic five, for comparison, cover only 9', smClassic.separated === 9);

  const gp = E.greedyByPairs(M.POOL, E.HYPOTHESES, C0);
  const gs = E.greedyBySpecimen(M.POOL, E.HYPOTHESES, C0);
  console.log(`  greedy over specimen pairs: ${gp.size} specimens (${gp.set.join(', ')}), covers ${gp.covered}/${gp.needed}`);
  console.log(`  greedy one specimen at a time: ${gs.size} specimens (${gs.set.join(', ')}), covers ${gs.covered}/${gs.needed}`);
  ok('both greedy rules do reach a cover on this pool', gp.complete && gs.complete);
  ok('but neither finds the optimum', gp.size > mts0.size && gs.size > mts0.size,
    `pairs ${gp.size}, one-at-a-time ${gs.size}, exact ${mts0.size}`);
}

head('the smallest bench a demonstrator could actually build');
{
  const cup = M.set(...M.CUPBOARD);
  console.log('  the cupboard: ' + M.CUPBOARD.join(', ') + '   (the classic five, plus the two candidate repairs)');
  const mts = E.minTestSet(cup, E.HYPOTHESES, C0, 7);
  console.log(`  smallest bench that separates all six accounts: ${mts.size} specimens, ${mts.set.join(', ')}`);
  ok('four specimens suffice', mts.size === 4, mts.set.join(', '));
  ok('and there is no metal among them',
    !mts.set.some((id) => ['copper', 'aluminium', 'iron', 'steel', 'stainless', 'lead', 'titanium'].includes(id)),
    mts.set.join(', '));
  ok('no three of the seven will do', !(() => {
    for (let i = 0; i < cup.length; i++)
      for (let j = i + 1; j < cup.length; j++)
        for (let l = j + 1; l < cup.length; l++)
          if (E.covers([cup[i], cup[j], cup[l]], E.HYPOTHESES, C0)) return true;
    return false;
  })());
  ok('it survives a 0.2 K instrument and dies at 0.5 K',
    E.minTestSet(cup, E.HYPOTHESES, ctx(0.2), 7).size === 4 &&
    E.minTestSet(cup, E.HYPOTHESES, ctx(0.5), 7).size === null);
  const gs = E.greedyBySpecimen(cup, E.HYPOTHESES, C0);
  ok('the natural one-at-a-time rule spends five, and the specimen it wastes is copper',
    gs.size === 5 && gs.set.includes('copper') && !mts.set.includes('copper'),
    gs.set.join(', '));
  const gp = E.greedyByPairs(cup, E.HYPOTHESES, C0);
  ok('scoring specimen PAIRS instead of specimens finds the optimum here',
    gp.size === 4, gp.set.join(', '));
}

// ── 7. thickness ────────────────────────────────────────────────────────────
head('the finite-slab solver against the analytic half-space it must reproduce');
{
  const times = [1e-4, 1e-3, 1e-2, 0.1, 0.5, 1, 2];
  let worst = 0;
  for (const id of ['copper', 'steel', 'glass', 'water', 'oak', 'foam', 'concrete']) {
    const m = M.byId(id), analytic = E.feltTemp(m, C0);
    worst = Math.max(worst, ...E.slabContact(m, 0.2, C0, times).map((r) => Math.abs(r.Tc - analytic)));
  }
  ok('a 20 cm block reproduces T_c = (e1 T1 + e2 T2)/(e1 + e2) to 1e-9 K', worst < 1e-9,
    `worst error ${worst.toExponential(2)} K`);
}
head('what thickness does, in one dimension');
{
  const cu = M.byId('copper');
  const block = E.feltTemp(cu, C0);
  const rows = [0.0002, 0.0005, 0.002, 0.02].map((L) => ({ L, Tc: E.slabContact(cu, L, C0, [1])[0].Tc }));
  for (const r of rows)
    console.log(`  copper ${String(r.L * 1000).padStart(6)} mm  ->  T_c(1 s) = ${r.Tc.toFixed(2)} C   (block: ${block.toFixed(2)} C)`);
  ok('thinner is warmer, monotonically', rows.every((r, i) => i === 0 || r.Tc < rows[i - 1].Tc));
  ok('a 2 cm block is already indistinguishable from an infinite one',
    Math.abs(rows[3].Tc - block) < 0.02, `${(rows[3].Tc - block).toFixed(3)} K`);
}

// ── 8. the geometry the one-dimensional model leaves out ────────────────────
// A finger is a disc of about 8 mm radius, not an infinite plane, so heat runs
// sideways INSIDE the specimen into material the finger is not touching. spread.js
// solves that in (r, z); its own validation suite is spread.test.mjs. This section
// checks what changes, and two of the claims an earlier draft of this page made are
// killed here rather than quietly dropped.
const FINGER = { skin: SKIN, Tskin: 33, Troom: 20, a: 0.008, eSkin: E.effusivity(SKIN), delta: 0 };
const BLOCK = 1e3;
const avg = (m, L, t) => S.contact(m, L, FINGER, [t])[0].Tavg;

head('a real finger is a disc, and the difference is not small');
{
  const rows = ['copper', 'aluminium', 'stainless', 'silica', 'glass', 'water', 'oak', 'foam']
    .map((id) => { const m = M.byId(id); const an = E.feltTemp(m, C0); const two = avg(m, BLOCK, 1); return { id, m, an, two, d: two - an }; });
  for (const r of rows)
    console.log(`  ${r.id.padEnd(11)}half-space ${r.an.toFixed(3)} C   8 mm finger ${r.two.toFixed(3)} C   difference ${r.d.toFixed(3)} K`);
  ok('a finite finger reads COLDER than the half-space formula on every specimen',
    rows.every((r) => r.d < 0));
  ok('and the correction is largest on the best conductors, which can reach furthest sideways',
    Math.abs(rows.find((r) => r.id === 'aluminium').d) > 8 * Math.abs(rows.find((r) => r.id === 'water').d),
    `aluminium ${rows.find((r) => r.id === 'aluminium').d.toFixed(3)} K vs water ${rows.find((r) => r.id === 'water').d.toFixed(3)} K`);
}

head('what that does to the one surviving discriminating pair');
{
  const oneD = E.feltGap(M.byId('silica'), M.byId('water'), C0);
  const twoD = Math.abs(avg(M.byId('silica'), BLOCK, 1) - avg(M.byId('water'), BLOCK, 1));
  console.log(`  fused silica against water:  half-space ${oneD.toFixed(3)} K   8 mm finger ${twoD.toFixed(3)} K`);
  ok('the half-space model overstates the signal by more than a factor of ten',
    oneD / twoD > 10, `${(oneD / twoD).toFixed(0)} times`);
  ok('under a real finger the surviving pair is worth under 0.02 K', twoD < 0.02, `${twoD.toFixed(4)} K`);
  const anchor2 = Math.abs(avg(M.byId('copper'), BLOCK, 1) - avg(M.byId('stainless'), BLOCK, 1));
  ok('CONTROL: the copper-against-stainless anchor is NOT inflated the same way, it survives',
    Math.abs(anchor2 - E.feltGap(M.byId('copper'), M.byId('stainless'), C0)) < 0.1,
    `${anchor2.toFixed(3)} K under a finger vs ${E.feltGap(M.byId('copper'), M.byId('stainless'), C0).toFixed(3)} K half-space`);
  ok('so the discriminating signal is more than a hundred times below the measured threshold',
    anchor2 / twoD > 100, `${Math.round(anchor2 / twoD)} times`);
}

head('thickness, done properly: one material, two thicknesses');
{
  const al = M.byId('aluminium'), oak = M.byId('oak');
  const foil = avg(al, 0.000016, 1), blk = avg(al, BLOCK, 1), oakBlk = avg(oak, BLOCK, 1);
  console.log(`  aluminium block ${blk.toFixed(2)} C   aluminium kitchen foil (0.016 mm) ${foil.toFixed(2)} C   oak block ${oakBlk.toFixed(2)} C`);
  ok('one material at two thicknesses spans more than 11 K', foil - blk > 11, `${(foil - blk).toFixed(2)} K`);
  ok('that swing is nearly as wide as the whole classic bench\'s spread',
    (foil - blk) > (avg(M.byId('foam'), BLOCK, 1) - avg(M.byId('copper'), BLOCK, 1)) * 0.85,
    `${(foil - blk).toFixed(2)} K on aluminium alone, bench spread ${(avg(M.byId('foam'), BLOCK, 1) - avg(M.byId('copper'), BLOCK, 1)).toFixed(2)} K`);
  ok('kitchen foil on foam is felt WARMER than a block of oak', foil > oakBlk,
    `${foil.toFixed(2)} C vs ${oakBlk.toFixed(2)} C`);
  ok('no account that assigns one number to a substance can produce that, since none holds a length',
    E.HYPOTHESES.every((h) => h.score.length <= 2));
}

head('a claim the one-dimensional model made, and the two-dimensional one refutes');
{
  // In 1-D a thin slab is limited by the heat it holds, rho c L, so stainless steel
  // (the larger rho c) should overtake aluminium once both are thin. It does, in 1-D.
  const al = M.byId('aluminium'), ss = M.byId('stainless');
  const oneA = E.slabContact(al, 0.0005, C0, [1])[0].Tc, oneB = E.slabContact(ss, 0.0005, C0, [1])[0].Tc;
  ok('in one dimension, 0.5 mm stainless is predicted colder than 0.5 mm aluminium', oneB < oneA,
    `${oneB.toFixed(2)} vs ${oneA.toFixed(2)} C`);
  const twoA = avg(al, 0.0005, 1), twoB = avg(ss, 0.0005, 1);
  ok('under a real finger it is not: aluminium stays colder, and by MORE than as a block',
    twoA < twoB && (twoB - twoA) > Math.abs(avg(ss, BLOCK, 1) - avg(al, BLOCK, 1)),
    `sheets ${twoA.toFixed(2)} vs ${twoB.toFixed(2)} C; blocks ${avg(al, BLOCK, 1).toFixed(2)} vs ${avg(ss, BLOCK, 1).toFixed(2)} C`);
  console.log('  the mechanism: a thin sheet of a good conductor is a heat SPREADER, and reaches');
  console.log('  sideways into metal the finger never touches. Stainless steel cannot.');

  // And so the 1-D model's whole picture of the foil regime is wrong.
  const foils = ['copper', 'aluminium', 'iron', 'steel', 'stainless'].map((id) => {
    const m = M.byId(id);
    return { id, one: E.slabContact(m, 0.000016, C0, [1])[0].Tc, two: avg(m, 0.000016, 1) };
  });
  const spread1 = Math.max(...foils.map((f) => f.one)) - Math.min(...foils.map((f) => f.one));
  const spread2 = Math.max(...foils.map((f) => f.two)) - Math.min(...foils.map((f) => f.two));
  for (const f of foils) console.log(`  ${f.id.padEnd(11)}foil, 1-D ${f.one.toFixed(2)} C   2-D ${f.two.toFixed(2)} C`);
  ok('in one dimension every metal foil is within a quarter of a kelvin of every other',
    spread1 < 0.25, `${spread1.toFixed(3)} K`);
  ok('under a real finger they spread over nearly a kelvin and a half',
    spread2 > 1.4, `${spread2.toFixed(3)} K`);
  ok('which is six times the one-dimensional spread', spread2 / spread1 > 6,
    `${(spread2 / spread1).toFixed(1)} times`);
  ok('and copper foil, the best conductor, is the coldest of them',
    foils.reduce((a, b) => (a.two < b.two ? a : b)).id === 'copper');
}

// ── 9. sensitivity to the least certain input ───────────────────────────────
head('sensitivity to the skin properties');
{
  const variants = [
    ['a cool, dry finger', { k: 0.3, rho: 1050, c: 3200 }],
    ['the value used above', SKIN],
    ['a warm, well-perfused one', { k: 0.55, rho: 1200, c: 4000 }],
  ];
  let allSame = true;
  const gaps = [];
  for (const [label, skin] of variants) {
    const c = ctx(0, skin);
    const sm = E.separationMatrix(CLASSIC, E.HYPOTHESES, c);
    const g = E.feltGap(M.byId('silica'), M.byId('water'), c);
    gaps.push(g);
    console.log(`  ${label.padEnd(26)} e_skin = ${E.effusivity(skin).toFixed(0).padStart(5)}   separates ${sm.separated}/15   silica/water gap ${g.toFixed(3)} K`);
    if (sm.separated !== smClassic.separated) allSame = false;
  }
  ok('the confound is unchanged across the plausible range of skin effusivity', allSame);
  ok('and the one robust discriminating signal stays under 0.2 K throughout',
    Math.max(...gaps) < 0.2, `${Math.min(...gaps).toFixed(3)} to ${Math.max(...gaps).toFixed(3)} K`);
}

// ── 10. the page says what this file says ────────────────────────────────────
head('the page and this file are the same code');
{
  for (const f of ['engine.js', 'materials.js', 'spread.js', 'spread.test.mjs', 'index.html', 'page.js'])
    ok(`${f} exists and is loaded by the page`, existsSync(path.join(PAGE, f)));
  const html = readFileSync(path.join(PAGE, 'index.html'), 'utf8');
  for (const f of ['engine.js', 'materials.js', 'spread.js', 'page.js'])
    ok(`index.html actually pulls in ${f}`, html.includes(`src="${f}"`));
  ok('the page prints the command that runs this file',
    html.includes('node research/the-demonstration-that-cannot-fail/verify.mjs'));
}

console.log(`\n${fails === 0 ? 'ALL' : String(checks - fails) + ' of'} ${checks} checks passed${fails ? `, ${fails} FAILED` : ''}.`);
process.exit(fails ? 1 : 0);
