#!/usr/bin/env node

/*
  Independent numerical verifier for The Fringe That Would Not Move.

  Two halves, and they are different instruments.

  Sections up to the negative self-tests re-derive everything from the cited
  papers: the six session transcriptions and the published comparison rows are
  copied from Michelson and Morley 1887 and Miller 1933, and nothing there
  reads the page. That establishes the numbers and says nothing whatever about
  what the browser prints.

  The last section is the other instrument. Until 2026-07-31 this file read
  nothing this site serves, so no defect in the shipped page could turn it red.
  It now lifts the page's own data arrays and its own functions out of
  public/strata/michelson-morley/index.html, runs them, sweeps them against the
  routes above, and asserts the numbers the page prints as static text before
  any script runs.
*/

import { readFileSync } from "node:fs";

const failures = [];
let checks = 0;

function assert(name, condition, detail = "") {
  checks += 1;
  if (!condition) failures.push(`${name}${detail ? `: ${detail}` : ""}`);
}

function close(name, actual, expected, tolerance = 1e-12) {
  const ok = Number.isFinite(actual) &&
    Math.abs(actual - expected) <= tolerance * Math.max(1, Math.abs(expected));
  assert(name, ok, `got ${actual}, expected ${expected}, tolerance ${tolerance}`);
}

function rounded(name, actual, expected, digits) {
  close(name, Number(actual.toFixed(digits)), expected, 1e-12);
}

const runs = [
  {
    id: "noon-8",
    label: "July 8, noon",
    group: "noon",
    values: [44.7, 44.0, 43.5, 39.7, 35.2, 34.7, 34.3, 32.5, 28.2, 26.2, 23.8, 23.2, 20.3, 18.7, 17.5, 16.8, 13.7]
  },
  {
    id: "noon-9",
    label: "July 9, noon",
    group: "noon",
    values: [57.4, 57.3, 58.2, 59.2, 58.7, 60.2, 60.8, 62.0, 61.5, 63.3, 65.8, 67.3, 69.7, 70.7, 73.0, 70.2, 72.2]
  },
  {
    id: "noon-11",
    label: "July 11, noon",
    group: "noon",
    values: [27.3, 23.5, 22.0, 19.3, 19.2, 19.3, 18.7, 18.8, 16.2, 14.3, 13.3, 12.8, 13.3, 12.3, 10.2, 7.3, 6.5]
  },
  {
    id: "evening-8",
    label: "July 8, evening",
    group: "evening",
    values: [61.2, 63.3, 63.3, 68.2, 67.7, 69.3, 70.3, 69.8, 69.0, 71.3, 71.3, 70.5, 71.2, 71.2, 70.5, 72.5, 75.7]
  },
  {
    id: "evening-9",
    label: "July 9, evening",
    group: "evening",
    values: [26.0, 26.0, 28.2, 29.2, 31.5, 32.0, 31.3, 31.7, 33.0, 35.8, 36.5, 37.3, 38.8, 41.0, 42.7, 43.7, 44.0]
  },
  {
    id: "evening-12",
    label: "July 12, evening",
    group: "evening",
    values: [66.8, 66.5, 66.0, 64.3, 62.2, 61.0, 61.3, 59.7, 58.2, 55.7, 53.7, 54.7, 55.0, 58.2, 58.5, 57.0, 56.0]
  }
];

const publishedMeans = {
  noon: [43.1, 41.6, 41.2, 39.4, 37.7, 38.1, 37.9, 37.8, 35.3, 34.6, 34.3, 34.4, 34.4, 33.9, 33.6, 31.4, 30.8],
  evening: [51.3, 51.9, 52.5, 53.9, 53.8, 54.1, 54.3, 53.7, 53.4, 54.3, 53.8, 54.2, 55.0, 56.8, 57.2, 57.7, 58.6]
};

const publishedWavelengthMeans = {
  noon: [0.862, 0.832, 0.824, 0.788, 0.754, 0.762, 0.758, 0.756, 0.706, 0.692, 0.686, 0.688, 0.688, 0.678, 0.672, 0.628, 0.616],
  evening: [1.026, 1.038, 1.050, 1.078, 1.076, 1.082, 1.086, 1.074, 1.068, 1.086, 1.076, 1.084, 1.100, 1.136, 1.144, 1.154, 1.172]
};

function mean(values) {
  return values.reduce((sum, value) => sum + value, 0) / values.length;
}

for (const group of ["noon", "evening"]) {
  const selected = runs.filter((run) => run.group === group);
  publishedMeans[group].forEach((published, index) => {
    const computed = mean(selected.map((run) => run.values[index]));
    rounded(`${group} published mean at ledger column ${index + 1}`, computed, published, 1);
    close(`${group} published wavelength mean at ledger column ${index + 1}`, published * 0.02, publishedWavelengthMeans[group][index]);
  });
}

assert("six source sessions", runs.length === 6);
assert("seventeen readings including closure in each session", runs.every((run) => run.values.length === 17));
close("one screw division conversion", 1 / 50, 0.02);
close("six revolutions times seventeen observations", 6 * 17, 102);

function exactShift90(pathWavelengths, beta) {
  const z = Math.sqrt(1 - beta * beta);
  return 4 * pathWavelengths * beta * beta / ((1 + z) * z * z);
}

function approximateShift90(pathWavelengths, beta) {
  return 2 * pathWavelengths * beta * beta;
}

const historicalPath = 2e7;
const historicalBeta = 1e-4;
const exactHistorical = exactShift90(historicalPath, historicalBeta);
const approximateHistorical = approximateShift90(historicalPath, historicalBeta);

rounded("external 0.4 fringe anchor", approximateHistorical, 0.4, 1);
close("stable exact Galilean 90 degree shift", exactHistorical, 0.40000000500000016, 1e-13);
close("centered amplitude is half the 90 degree change", exactHistorical / 2, 0.20000000250000008, 1e-13);
close("twentieth of historical prediction", approximateHistorical / 20, 0.02);
close("fortieth of historical prediction", approximateHistorical / 40, 0.01);

function prepare(values, rule) {
  let adjusted = values.slice();
  if (rule === "endpoint") {
    const slope = (adjusted[16] - adjusted[0]) / 16;
    adjusted = adjusted.map((value, index) => value - index * slope);
    close("endpoint rule closes the repeated mark", adjusted[16], adjusted[0], 1e-12);
  } else if (rule === "linear") {
    const tMean = 8;
    const yMean = mean(adjusted);
    const numerator = adjusted.reduce((sum, value, index) => sum + (index - tMean) * (value - yMean), 0);
    const denominator = adjusted.reduce((sum, value, index) => sum + (index - tMean) ** 2, 0);
    const slope = numerator / denominator;
    adjusted = adjusted.map((value, index) => value - (yMean + slope * (index - tMean)));
  }
  adjusted = adjusted.slice(0, 16).map((value) => value * 0.02);
  const center = mean(adjusted);
  return adjusted.map((value) => value - center);
}

function harmonic(values) {
  let c = 0;
  let s = 0;
  for (let index = 0; index < 16; index += 1) {
    const theta = 2 * Math.PI * index / 16;
    c += values[index] * Math.cos(2 * theta);
    s += values[index] * Math.sin(2 * theta);
  }
  c *= 2 / 16;
  s *= 2 / 16;
  return {
    c,
    s,
    amplitude: Math.hypot(c, s),
    phase: (Math.atan2(s, c) * 90 / Math.PI + 180) % 180
  };
}

const expectedFits = {
  "noon-8": {
    none: [0.10474167155862375, 31.00507439545902],
    endpoint: [0.010460765525054915, 177.09027196577716],
    linear: [0.010059025160515427, 166.24442437324558]
  },
  "noon-9": {
    none: [0.0616654187559672, 119.43400071163983],
    endpoint: [0.015653321946187456, 105.62670302803531],
    linear: [0.010859874673382267, 94.52197590431331]
  },
  "noon-11": {
    none: [0.04676624482381179, 26.72261354986236],
    endpoint: [0.025270864173628768, 137.1031382413563],
    linear: [0.01616821856775948, 146.0614204263214]
  },
  "evening-8": {
    none: [0.041344255360241784, 115.6804654487086],
    endpoint: [0.01380466937148736, 61.92844627867939],
    linear: [0.013178120624471188, 93.39903425197323]
  },
  "evening-9": {
    none: [0.06707944691280633, 120.59995419581455],
    endpoint: [0.01078255080246806, 102.22331795026076],
    linear: [0.009510246029297672, 98.39232876758403]
  },
  "evening-12": {
    none: [0.022653928034462867, 11.868603982865125],
    endpoint: [0.024563163355746365, 143.5681544257889],
    linear: [0.026576025995233656, 141.81420094883606]
  }
};

const expectedRms = {
  "noon-8": [0.17297637264826862, 0.023174715582179435, 0.0218328145958043],
  "noon-9": [0.09203353975494806, 0.028204097770084837, 0.026378784703705457],
  "noon-11": [0.09557926905213103, 0.02716853348929608, 0.02149205259533892],
  "evening-8": [0.05759135155866337, 0.04237021457370682, 0.03198768467990801],
  "evening-9": [0.09755592383825805, 0.01768057335314945, 0.017778618761526876],
  "evening-12": [0.08204358458956243, 0.04064803811968615, 0.03920617123800531]
};

for (const run of runs) {
  for (const [ruleIndex, rule] of ["none", "endpoint", "linear"].entries()) {
    const fit = harmonic(prepare(run.values, rule));
    close(`${run.id} ${rule} amplitude`, fit.amplitude, expectedFits[run.id][rule][0], 1e-12);
    close(`${run.id} ${rule} phase`, fit.phase, expectedFits[run.id][rule][1], 1e-12);
    close(`${run.id} ${rule} residual RMS`, Math.sqrt(mean(prepare(run.values, rule).map((value, index) => {
      const theta = 2 * Math.PI * index / 16;
      const fitted = fit.c * Math.cos(2 * theta) + fit.s * Math.sin(2 * theta);
      return (value - fitted) ** 2;
    }))), expectedRms[run.id][ruleIndex], 1e-12);
  }
  close(`${run.id} displayed closure drift`, (run.values[16] - run.values[0]) * 0.02,
    [ -0.62, 0.296, -0.416, 0.29, 0.36, -0.216 ][runs.indexOf(run)], 1e-12);
}

const millerEpochs = [
  { label: "8 February 1926", raHours: 6, decDeg: -(77 + 27 / 60), velocity: 9.3, displacement: 0.104 },
  { label: "1 April 1925", raHours: 3 + 42 / 60, decDeg: -(76 + 48 / 60), velocity: 10.1, displacement: 0.123 },
  { label: "1 August 1925", raHours: 3 + 57 / 60, decDeg: -(64 + 47 / 60), velocity: 11.2, displacement: 0.152 },
  { label: "15 September 1925", raHours: 5 + 5 / 60, decDeg: -(62 + 4 / 60), velocity: 9.6, displacement: 0.110 }
];

assert("Miller external four epoch anchor", millerEpochs.length === 4);
close("Miller February displacement anchor", millerEpochs[0].displacement, 0.104);
close("Miller April velocity anchor", millerEpochs[1].velocity, 10.1);
close("Miller August displacement anchor", millerEpochs[2].displacement, 0.152);
close("Miller September south right ascension anchor", millerEpochs[3].raHours, 5.083333333333333, 1e-14);

function direction(epoch) {
  const ra = epoch.raHours * Math.PI / 12;
  const dec = epoch.decDeg * Math.PI / 180;
  const cosDec = Math.cos(dec);
  return [cosDec * Math.cos(ra), cosDec * Math.sin(ra), Math.sin(dec)];
}

function lockedDirection(epochs) {
  const sum = [0, 0, 0];
  for (const epoch of epochs) {
    const vector = direction(epoch);
    for (let i = 0; i < 3; i += 1) sum[i] += vector[i];
  }
  const length = Math.hypot(...sum);
  const vector = sum.map((value) => value / length);
  return {
    vector,
    raHours: (Math.atan2(vector[1], vector[0]) * 12 / Math.PI + 24) % 24,
    decDeg: Math.asin(vector[2]) * 180 / Math.PI
  };
}

function angularDistance(a, b) {
  const dot = a.reduce((sum, value, index) => sum + value * b[index], 0);
  return Math.acos(Math.max(-1, Math.min(1, dot))) * 180 / Math.PI;
}

const locked = lockedDirection(millerEpochs);
const residualAngles = millerEpochs.map((epoch) => angularDistance(direction(epoch), locked.vector));
const sumSquareAngles = residualAngles.reduce((sum, value) => sum + value * value, 0);
const leaveOneOut = millerEpochs.map((_, omitted) => {
  const fit = lockedDirection(millerEpochs.filter((__, index) => index !== omitted));
  return angularDistance(fit.vector, locked.vector);
});
const nCoordinates = 8;
const lockedParameters = 2;
const freeParameters = 8;
const sigmaExample = 10;
const lockedBic = sumSquareAngles / sigmaExample ** 2 + lockedParameters * Math.log(nCoordinates);
const freeBic = freeParameters * Math.log(nCoordinates);
const crossoverSigma = Math.sqrt(sumSquareAngles / ((freeParameters - lockedParameters) * Math.log(nCoordinates)));

close("Miller locked right ascension", locked.raHours, 4.633631382597105, 1e-11);
close("Miller locked declination", locked.decDeg, -70.69247574154525, 1e-11);
close("Miller maximum directional residual", Math.max(...residualAngles), 9.026184310749192, 1e-11);
close("Miller maximum leave-one-out movement", Math.max(...leaveOneOut), 3.020686635243427, 1e-11);
close("locked BIC at chosen 10 degree scatter", lockedBic, 6.747681904186273, 1e-11);
close("free BIC at chosen 10 degree scatter", freeBic, 16.635532333438686, 1e-12);
close("BIC crossover scatter", crossoverSigma, 4.555123623560698, 1e-11);
assert("free per epoch direction is saturated", freeParameters === nCoordinates);

const syntheticDefault = Array.from({ length: 16 }, (_, index) => {
  const t = index / 15;
  return 0.3 * (t - 0.5) + 0.06 * (t - 0.5) ** 2 + 0.008 * Math.sin(2 * Math.PI * index / 16);
});
const syntheticCenter = mean(syntheticDefault);
const syntheticFit = harmonic(syntheticDefault.map((value) => value - syntheticCenter));
close("synthetic default amplitude", syntheticFit.amplitude, 0.05228958787645456, 1e-12);
close("synthetic default phase", syntheticFit.phase, 124.67184334716006, 1e-12);

function expectFailure(name, operation) {
  let failed = false;
  try {
    operation();
  } catch {
    failed = true;
  }
  assert(`negative self-test ${name}`, failed);
}

function demand(condition) {
  if (!condition) throw new Error("deliberate negative test caught");
}

expectFailure("factor of two", () => demand(Math.abs(approximateHistorical / 2 - 0.4) < 1e-12));
expectFailure("0.4 cannot be centered amplitude", () => demand(Math.abs(approximateHistorical - 0.2) < 1e-12));
expectFailure("altered source cell", () => {
  const changed = runs[0].values.slice();
  changed[4] += 1;
  demand(Number(mean([changed[4], runs[1].values[4], runs[2].values[4]]).toFixed(1)) === 37.7);
});
expectFailure("free epoch fit cannot evidence coherence", () => demand(freeParameters < nCoordinates));

/* ---------------------------------------------------------------------------
   THE SHIPPED PAGE, lifted out of the HTML and swept against this file.

   Extraction is deliberately value-agnostic. Pinning a literal into a pattern
   would make a drifted number fail the EXTRACTION and silently skip every check
   behind it, so the file would go quiet exactly when the page went wrong. That
   is the failure this section exists to remove, so constants are matched by
   shape and their values compared separately, below.
   --------------------------------------------------------------------------- */

const html = readFileSync(
  new URL("../../public/strata/michelson-morley/index.html", import.meta.url),
  "utf8"
);

/** Take one bracketed declaration out of the page's inline script by matching brackets. */
function grab(marker, open = "{", shut = "}") {
  const at = html.indexOf(marker);
  if (at < 0) return null;
  const from = html.indexOf(open, at + marker.length - 1);
  if (from < 0) return null;
  let depth = 0;
  for (let i = from; i < html.length; i += 1) {
    if (html[i] === open) depth += 1;
    else if (html[i] === shut) {
      depth -= 1;
      if (depth === 0) return html.slice(at, i + 1) + (open === "[" || open === "{" ? ";" : "");
    }
  }
  return null;
}

const lifted = {
  TAU: (html.match(/var TAU\s*=[^;]+;/) || [null])[0],
  RUNS: grab("var RUNS = [", "[", "]"),
  PUBLISHED_MEANS: grab("var PUBLISHED_MEANS = {", "{", "}"),
  MILLER: grab("var MILLER = [", "[", "]"),
  mean: grab("function mean(values)"),
  clamp: grab("function clamp(value, low, high)"),
  exactShift90: grab("function exactShift90(path, speedRatio)"),
  approximateShift90: grab("function approximateShift90(path, speedRatio)"),
  prepare: grab("function prepare(values, rule)"),
  harmonic: grab("function harmonic(values)"),
  aggregate: grab("function aggregate(group, rule)"),
  direction: grab("function direction(epoch)"),
  lockedDirection: grab("function lockedDirection(epochs)"),
  angleBetween: grab("function angleBetween(a, b)"),
  millerModel: grab("function millerModel()")
};
const missing = Object.keys(lifted).filter((key) => !lifted[key]);
assert("page declares every data array and function this section sweeps",
  missing.length === 0, `not lifted: ${missing.join(", ")}`);

if (!missing.length) {
  const names = Object.keys(lifted).filter((key) => key !== "TAU");
  const PAGE = new Function(
    Object.values(lifted).join("\n") + `\n; return { ${names.map((n) => `${n}:${n}`).join(", ")} };`
  )();

  /* the page's transcriptions are this file's transcriptions */
  assert("page ships the same six sessions in the same order",
    PAGE.RUNS.length === runs.length &&
    PAGE.RUNS.every((run, index) => run.id === runs[index].id && run.group === runs[index].group),
    PAGE.RUNS.map((run) => run.id).join(", "));
  for (const [index, run] of runs.entries()) {
    const shipped = PAGE.RUNS[index].values;
    assert(`page session ${run.id} ships all 17 readings unchanged`,
      shipped.length === 17 && shipped.every((value, i) => value === run.values[i]),
      shipped.join(","));
  }
  for (const group of ["noon", "evening"]) {
    assert(`page ships the published ${group} means unchanged`,
      PAGE.PUBLISHED_MEANS[group].length === 17 &&
      PAGE.PUBLISHED_MEANS[group].every((value, i) => value === publishedMeans[group][i]),
      PAGE.PUBLISHED_MEANS[group].join(","));
  }
  assert("page ships the four Miller epochs unchanged",
    PAGE.MILLER.length === millerEpochs.length &&
    PAGE.MILLER.every((epoch, i) =>
      epoch.ra === millerEpochs[i].raHours && epoch.dec === millerEpochs[i].decDeg &&
      epoch.speed === millerEpochs[i].velocity && epoch.displacement === millerEpochs[i].displacement),
    PAGE.MILLER.map((epoch) => `${epoch.ra}/${epoch.dec}`).join(" "));

  /* sweep 1: the fringe-shift formulas, over the page's own slider ranges */
  let gapExact = 0;
  let gapApprox = 0;
  for (let path = 1e6; path <= 4e7; path += 1e6) {
    for (let b = 0; b <= 2.0001e-4; b += 5e-6) {
      gapExact = Math.max(gapExact, Math.abs(PAGE.exactShift90(path, b) - exactShift90(path, b)));
      gapApprox = Math.max(gapApprox, Math.abs(PAGE.approximateShift90(path, b) - approximateShift90(path, b)));
    }
  }
  assert("page exactShift90 matches this file over every reachable slider pair",
    gapExact < 1e-15, `worst gap ${gapExact.toExponential(2)} fringe`);
  assert("page approximateShift90 matches this file over every reachable slider pair",
    gapApprox < 1e-15, `worst gap ${gapApprox.toExponential(2)} fringe`);

  /* sweep 2: detrending and the half-turn harmonic, every session by every rule */
  let gapPrepared = 0;
  for (const run of runs) {
    for (const [ruleIndex, rule] of ["none", "endpoint", "linear"].entries()) {
      const here = prepare(run.values, rule);
      const there = PAGE.prepare(PAGE.RUNS.find((r) => r.id === run.id).values, rule).turn;
      assert(`page prepare(${run.id}, ${rule}) returns sixteen centered turn values`,
        there.length === 16);
      there.forEach((value, i) => { gapPrepared = Math.max(gapPrepared, Math.abs(value - here[i])); });
      const fit = PAGE.harmonic(there);
      close(`page harmonic amplitude, ${run.id} ${rule}`, fit.amplitude, expectedFits[run.id][rule][0], 1e-12);
      close(`page harmonic phase, ${run.id} ${rule}`, fit.phase, expectedFits[run.id][rule][1], 1e-12);
      close(`page harmonic residual RMS, ${run.id} ${rule}`, fit.rms, expectedRms[run.id][ruleIndex], 1e-12);
    }
  }
  assert("page prepare matches this file on all six sessions by all three rules",
    gapPrepared < 1e-15, `worst gap ${gapPrepared.toExponential(2)} fringe`);

  /* sweep 3: the Miller aggregate screen the page draws and prints */
  const pageMiller = PAGE.millerModel();
  close("page locked right ascension", pageMiller.locked.ra, locked.raHours, 1e-13);
  close("page locked declination", pageMiller.locked.dec, locked.decDeg, 1e-13);
  pageMiller.residuals.forEach((value, index) =>
    close(`page directional residual, epoch ${index + 1}`, value, residualAngles[index], 1e-13));
  close("page maximum leave-one-out movement", pageMiller.maxLoo, Math.max(...leaveOneOut), 1e-13);
  close("page BIC crossover scatter", pageMiller.crossover, crossoverSigma, 1e-13);

  /* the printed page: what a reader sees before a single line of script runs.
     Asserted on the rounded form, because the rounding is what is on screen. */
  const shippedPath = Number((html.match(/<input id="pathRatio"[^>]*\svalue="([\d.]+)"/) || [])[1]);
  const shippedBeta = Number((html.match(/<input id="beta"[^>]*\svalue="([\d.]+)"/) || [])[1]);
  assert("page opens at the historical path ratio and speed ratio this file uses",
    shippedPath === historicalPath && shippedBeta === historicalBeta,
    `page opens at D/lambda ${shippedPath}, beta ${shippedBeta}`);

  const openExact = PAGE.exactShift90(shippedPath, shippedBeta);
  const openApprox = PAGE.approximateShift90(shippedPath, shippedBeta);
  const openError = openApprox ? Math.abs(openExact - openApprox) / openApprox * 100 : 0;
  const printed = [
    [`id="exact90">${openExact.toFixed(9)}<`, "exact 90 degree change"],
    [`id="approx90">${openApprox.toFixed(9)}<`, "second order approximation"],
    [`id="centerAmp">${(openExact / 2).toFixed(9)}<`, "centered amplitude"],
    [`id="approxError">${openError.toFixed(6)}%<`, "approximation difference"],
    [`id="checkPhysics">${openExact.toFixed(9)} versus ${openApprox.toFixed(9)} fringe<`, "check panel, physics"]
  ];
  for (const [fragment, label] of printed) {
    assert(`page prints the opening ${label} its own formula produces`,
      html.includes(fragment), fragment);
  }

  /* The session and drift rule the page opens on, derived the way the page actually
     determines them rather than pinned.

     This used to read `(html.match(/<option value="..."[^>]*selected/) || [, "noon-8"])[1]`,
     and the page marks no option `selected`, so the regex never matched and the literal
     was always used: a check that silently tested a constant, in the file whose own
     comment forbids exactly that. The browser opens a <select> on its FIRST option when
     none carries `selected`, so that is what is read here, with the `selected` case still
     honoured if the page ever grows one. Both extractions are asserted, so a drifted
     default goes red instead of quiet. (Fixed 2026-07-31.) */
  const runSelect = (html.match(/<select id="runSelect"[^>]*>([\s\S]*?)<\/select>/) || [])[1];
  assert("page ships a session selector this file can read a default out of",
    typeof runSelect === "string" && /<option\s/.test(runSelect));
  const runOptions = [...(runSelect || "").matchAll(/<option\s([^>]*)value="([^"]+)"([^>]*)>/g)];
  const markedRun = runOptions.find((match) => /\bselected\b/.test(match[1] + match[3]));
  const openingRun = markedRun ? markedRun[2] : (runOptions[0] || [])[2];
  assert("the session the page opens on is one of the six this file transcribed",
    runs.some((run) => run.id === openingRun), `page opens on ${openingRun}`);
  const openingRule = (html.match(/var detrendRule\s*=\s*"([a-z]+)"/) || [])[1];
  assert("the drift rule the page opens on is one of the three this file implements",
    ["none", "endpoint", "linear"].includes(openingRule), `page opens on ${openingRule}`);

  const openingPrepared = PAGE.prepare(
    PAGE.RUNS.find((run) => run.id === openingRun).values, openingRule);
  const openingFit = PAGE.harmonic(openingPrepared.turn);
  assert("page prints the opening harmonic its own fit produces",
    html.includes(`id="checkFit">amplitude ${openingFit.amplitude.toFixed(6)}, phase ${openingFit.phase.toFixed(2)} deg<`),
    `${openingRun} ${openingRule}: amplitude ${openingFit.amplitude.toFixed(6)}, phase ${openingFit.phase.toFixed(2)}`);

  /* The six fit cards and the three slider readouts. These are printed as static text and
     were, until 2026-07-31, checked by nothing at all: a wrong C coefficient or a wrong
     closure drift shipped green. Each is recomputed here from the page's own functions
     and its own transcribed session, then matched against the page's own formatting
     (`signed()` for the coefficients and the drift, toFixed for the rest). */
  const openingValues = PAGE.RUNS.find((run) => run.id === openingRun).values;
  const pageSigned = (value, digits) => (value >= 0 ? "+" : "") + value.toFixed(digits);
  const fitCards = [
    [`id="fitC">${pageSigned(openingFit.c, 6)}<`, "C coefficient"],
    [`id="fitS">${pageSigned(openingFit.s, 6)}<`, "S coefficient"],
    [`id="fitAmp">${openingFit.amplitude.toFixed(6)}<`, "amplitude"],
    [`id="fitPhase">${openingFit.phase.toFixed(2)} deg<`, "phase"],
    [`id="fitRms">${openingFit.rms.toFixed(6)}<`, "residual RMS"],
    [`id="closureDrift">${pageSigned((openingValues[16] - openingValues[0]) * 0.02, 3)} fringe<`,
      "closure drift"]
  ];
  for (const [fragment, label] of fitCards) {
    assert(`page prints the opening ${label} card its own fit produces`,
      html.includes(fragment), fragment);
  }

  /* the C and S coefficients again, this time against this file's own harmonic, so the
     cards are pinned to an independent re-derivation and not only to the page's code */
  const hereOpening = harmonic(prepare(
    runs.find((run) => run.id === openingRun).values, openingRule));
  close("opening C coefficient, page fit versus this file's fit", openingFit.c, hereOpening.c, 1e-13);
  close("opening S coefficient, page fit versus this file's fit", openingFit.s, hereOpening.s, 1e-13);
  close("opening residual RMS, page fit versus this file's fit", openingFit.rms,
    expectedRms[openingRun][["none", "endpoint", "linear"].indexOf(openingRule)], 1e-12);

  /* the three slider readouts, each printed from its own input's value attribute */
  const shippedSigma = Number((html.match(/<input id="directionSigma"[^>]*\svalue="([\d.]+)"/) || [])[1]);
  assert("page opens the directional scatter slider at the scatter its BIC panel reports",
    shippedSigma === 10, `page opens at ${shippedSigma} deg`);
  const readouts = [
    [`id="pathNow">${shippedPath.toLocaleString("en-US")}<`, "optical distance readout"],
    [`id="betaNow">${shippedBeta.toFixed(6)}<`, "speed ratio readout"],
    [`id="sigmaNow">${shippedSigma.toFixed(1)} deg<`, "directional scatter readout"]
  ];
  for (const [fragment, label] of readouts) {
    assert(`page prints the opening ${label} its own slider value produces`,
      html.includes(fragment), fragment);
  }
  assert("page prints the opening locked direction its own screen produces",
    html.includes(`id="checkMiller">locked RA ${pageMiller.locked.ra.toFixed(4)} h, dec ${pageMiller.locked.dec.toFixed(4)} deg<`),
    `RA ${pageMiller.locked.ra.toFixed(4)} h, dec ${pageMiller.locked.dec.toFixed(4)} deg`);
}

console.log("Michelson and Morley 1887");
console.log(`  source sessions: ${runs.length} x 17 readings, each entry a six-revolution mean`);
console.log(`  conversion: 1 screw division = ${(1 / 50).toFixed(2)} wavelength`);
console.log(`  historical approximate 90 degree change: ${approximateHistorical.toFixed(9)} fringe`);
console.log(`  exact Galilean 90 degree change: ${exactHistorical.toFixed(9)} fringe`);
console.log(`  centered exact amplitude: ${(exactHistorical / 2).toFixed(9)} fringe`);
for (const run of runs) {
  const values = ["none", "endpoint", "linear"].map((rule) => harmonic(prepare(run.values, rule)).amplitude.toFixed(6));
  console.log(`  ${run.label}: amplitudes none ${values[0]}, endpoint ${values[1]}, linear ${values[2]}`);
}
console.log("Miller 1933 aggregate screen");
console.log(`  locked direction: RA ${locked.raHours.toFixed(4)} h, dec ${locked.decDeg.toFixed(4)} deg`);
console.log(`  residual angles: ${residualAngles.map((value) => value.toFixed(4)).join(", ")} deg`);
console.log(`  maximum leave-one-out movement: ${Math.max(...leaveOneOut).toFixed(4)} deg`);
console.log(`  BIC at freely chosen 10 deg scatter: locked ${lockedBic.toFixed(4)}, free ${freeBic.toFixed(4)}`);
console.log(`  BIC crossover scatter: ${crossoverSigma.toFixed(4)} deg`);
console.log(`  synthetic default free fit: amplitude ${syntheticFit.amplitude.toFixed(6)}, phase ${syntheticFit.phase.toFixed(4)} deg`);
// The verdict comes last and comes once. This used to print PASS unconditionally and then
// the failure list underneath it, so a red run still had the word PASS in its output.
if (failures.length) {
  console.error(`FAIL ${failures.length} of ${checks} checks`);
  for (const failure of failures) console.error(`  ${failure}`);
  process.exit(1);
}
console.log(`PASS ${checks} checks, including 4 negative self-tests`);
