#!/usr/bin/env node
// verify-the-face-an-hour-before-sunset.mjs: recomputes every number the page shows from the frozen
// files, checks the shipped page, frontmatter, head tags, JSON-LD and record.json against the
// recomputation, and exits non-zero on any disagreement.
//
//   node research/the-face-an-hour-before-sunset/verify-the-face-an-hour-before-sunset.mjs            # every assertion
//   node research/the-face-an-hour-before-sunset/verify-the-face-an-hour-before-sunset.mjs --ledger   # the nine ledger cells
//   node research/the-face-an-hour-before-sunset/verify-the-face-an-hour-before-sunset.mjs --regen    # rewrite record.json and
//        the literal inventory, only if every other assertion passes. It never rewrites a data file.
//
// Two kinds of check are kept apart. The page's own functions are run on the frozen files and on
// doctored copies of them. And the anchors outside the engine are checked against things the engine
// did not make: the label's checksum and the file's own histogram for the decoder, the PDS archive's
// MD5, NASA's printed Mars24 worked example, independent arithmetic for Table II and the shadow
// formula, an independent reading of the terrain bytes, and a separate numpy measurement on the full
// 2 m terrain model (data/crosscheck-2m.json).

import fs from 'node:fs';
import path from 'node:path';
import crypto from 'node:crypto';
import assert from 'node:assert/strict';
import { spawnSync } from 'node:child_process';
import { fileURLToPath } from 'node:url';
import * as E from '../../public/strata/the-face-an-hour-before-sunset/engine.js';
import * as An from '../../public/strata/the-face-an-hour-before-sunset/analysis.js';
import { figures } from '../../public/strata/the-face-an-hour-before-sunset/figures.js';
import { VERDICT, NOVELTY, QUOTES } from '../../public/strata/the-face-an-hour-before-sunset/readings.js';
import { FILES, SHA256, PDS_MD5 } from '../../public/strata/the-face-an-hour-before-sunset/data.js';
import * as S from './surface.mjs';

// The site's chrome writers inject marked blocks and a banner script into every shipped page after the
// build. This verifier checks the page's OWN content, so it reads the page with all of them removed.
const stripChrome = (s) => s.replace(/\s*<!--aw-([a-z-]+):start-->[\s\S]*?<!--aw-\1:end-->/g, '')
  .replace(/\s*<script src="\/media\/home-banner\.js" defer><\/script>/g, '');

const here = path.dirname(fileURLToPath(import.meta.url));
const root = path.resolve(here, '../..');
const dir = path.join(root, 'public/strata', S.SLUG);
const mdPath = path.join(root, 'src/content/strata', S.SLUG + '.md');
const readB = (f) => fs.readFileSync(path.join(dir, f));
const rawHtml = fs.readFileSync(path.join(dir, 'index.html'), 'utf8');
const html = stripChrome(rawHtml);
const md = fs.readFileSync(mdPath, 'utf8');
const readme = fs.readFileSync(path.join(here, 'README.md'), 'utf8');
const cross = JSON.parse(fs.readFileSync(path.join(here, 'data/crosscheck-2m.json'), 'utf8'));
const recordPath = path.join(dir, 'record.json');
const record = fs.existsSync(recordPath) ? JSON.parse(fs.readFileSync(recordPath, 'utf8')) : null;
const REGEN = process.argv.includes('--regen');
const LEDGER = process.argv.includes('--ledger');

const results = [];
function test(group, name, fn) {
  try { fn(); results.push({ group, name, pass: true }); }
  catch (error) { results.push({ group, name, pass: false, error: error.message }); }
}
const near = (a, b, tol, msg) => assert.ok(Number.isFinite(a) && Math.abs(a - b) <= tol, (msg || '') + ` ${a} differs from ${b} beyond ${tol}`);
const EM_DASH = String.fromCharCode(0x2014);
const qnorm = (t) => t.replace(/[‘’]/g, "'").replace(/[“”]/g, '"');
const sha = (b) => crypto.createHash('sha256').update(b).digest('hex');
const md5 = (b) => crypto.createHash('md5').update(b).digest('hex');

// ------------------------------------------------------------------ the one run the page also makes
const inp = {
  claim: JSON.parse(readB(FILES.claim)), regions: JSON.parse(readB(FILES.regions)), terrainMeta: JSON.parse(readB(FILES.terrainMeta)),
  terrainBytes: new Uint8Array(readB(FILES.terrain)), edr: { '35A72': new Uint8Array(readB(FILES.edr35)), '70A13': new Uint8Array(readB(FILES.edr70)) },
};
const claim = inp.claim;
const all = An.runAll(inp);
const { A, B, C, D, Es, F: Fd, G, R } = all;
const F = figures(R);
const X = S.texts(F);
const T = A.T;
const tI = An.geometryOf(claim, '35A72');
const CLAIMED = Number(E.parseCombined(claim.tableII.rows.find((r) => r.id === 'height').combined_printed).mean);
const fm = (md.match(/^---\n([\s\S]*?)\n---/) || [])[1] || '';
const fmField = (k) => { const m = fm.match(new RegExp('^' + k + ':\\s*"(.*)"\\s*$', 'm')); return m ? m[1].replace(/\\"/g, '"') : null; };
const mdBody = md.slice(md.indexOf('\n---', 4) + 4).trim();
const meta = (attr, name) => { const m = html.match(new RegExp('<meta ' + attr + '="' + name.replace(/[.*+?^${}()|[\]\\]/g, '\\$&') + '" content="([^"]*)"')); return m ? m[1] : null; };
const fullVisible = S.decodeEntities(html.slice(html.indexOf('<body')).replace(/<script[\s\S]*?<\/script>/g, ' ').replace(/<style[\s\S]*?<\/style>/g, ' ').replace(/<!--[\s\S]*?-->/g, ' ').replace(/<[^>]+>/g, ' ')).replace(/\s+/g, ' ');
const has = (s) => qnorm(fullVisible).includes(qnorm(s.replace(/\s+/g, ' ')));
function surfaceDisagreements(h, figs) {
  const out = [];
  for (const d of S.dataFigs(h)) if (!(d.key in figs) || S.decodeEntities(d.inner.trim()) !== figs[d.key]) out.push(d.key);
  return out;
}

// ================================================================== anchor: the claim at full strength
test('anchor', 'the two Viking frames decode to their labels’ checksums and their own histograms', () => {
  for (const [id, name] of [['35A72', FILES.edr35], ['70A13', FILES.edr70]]) {
    const e = A.edr[id];
    assert.equal(e.checksumOK, true, id + ' checksum');
    assert.equal(e.pixelSum, e.checksum, id);
    assert.equal(e.histDiff, 0, id + ' histogram');
    assert.deepEqual([e.lines, e.samples, e.imageTime], [1056, 1204, claim.frames[id].image_time]);
    assert.equal(md5(readB(name)), claim.frames[id].pds_md5, id + ' is the PDS archive’s file (MD5 from the volume’s checksum list)');
  }
  assert.deepEqual([A.edr['35A72'].checksum, A.edr['70A13'].checksum], [101666114, 109472420]);
});
test('anchor', 'Table II’s Combined column comes out of combineFrames at the printed rounding, checked by independent arithmetic', () => {
  const rows = E.tableIIReproduced(claim.tableII);
  assert.equal(rows.length, 4);
  for (const r of rows) {
    assert.equal(r.agrees, true, r.id);
    const src = claim.tableII.rows.find((x) => x.id === r.id).frames;
    const a = src['35A72'], b = src['70A13'];
    near(r.mean, (a + b) / 2, 1e-12); near(r.half, Math.abs(a - b) / 2, 1e-12); near(r.pct, 100 * Math.abs(a - b) / (a + b), 1e-9);
  }
  const s = rows.find((r) => r.id === 'slope');
  near(s.mean, 39.005, 1e-9); near(s.half, 5.825, 1e-9);
  assert.equal(CLAIMED, 412.5);
  assert.equal(claim.headline_as_printed, 'Peak height 412.5 ± 17.5 (4.2%)');
});
test('anchor', 'a corrupted Table II fails the same combination', () => {
  const bad = structuredClone(claim.tableII); bad.rows[0].frames['35A72'] = 440;
  assert.equal(E.tableIIReproduced(bad)[0].agrees, false, '440 and 395 do not combine to 412.5 ± 17.5');
  const bad2 = structuredClone(claim.tableII); bad2.rows[3].frames['70A13'] = 33.28;
  assert.equal(E.tableIIReproduced(bad2)[3].agrees, false);
});
test('anchor', 'the 1988 shadow method on the decoded 35A72, with Table I’s inputs, lands in the band "approximately 400" covers', () => {
  const L = B.shadow.frame['0.5'].tipPx;
  assert.equal(B.anchor.lengthPx, L);
  // independent arithmetic of the 1988 formula, with Table I read from the claim file
  const scm = claim.tableI.rows.find((r) => r.id === 'scm')['35A72'], ina = claim.tableI.rows.find((r) => r.id === 'ina')['35A72'];
  near(B.anchor.heightM, L * scm * Math.tan((90 - ina) * Math.PI / 180), 1e-9);
  assert.ok(B.anchor.heightM >= 350 && B.anchor.heightM < 450, 'height ' + B.anchor.heightM);
  assert.equal(B.anchor.inBand, true);
  near(L, 39.5, 0.6, 'the frame’s midway shadow');
  // the length is the page's function on the page's placement of the frame
  const again = E.shadowProfile(E.frameToGrid(B.F, B.reg.xf, tI.cam, B.G), B.G, tI.sun, B.start, { frac: 0.5 });
  near(again.tipPx, L, 1e-9);
});
test('anchor', 'the band can fail: the caption’s 20 degrees, or a shadow read from a corrupted frame, leave it', () => {
  assert.equal(B.anchor.captionInBand, false);
  assert.ok(B.anchor.captionHeightM > 700, 'caption sun gives ' + B.anchor.captionHeightM);
  // corrupt the frame: brighten the shadow region of the prepared frame copy so the dark run ends early
  const F2 = { ...B.F, med: new Float32Array(B.F.med) };
  const img0 = E.frameToGrid(F2, B.reg.xf, tI.cam, B.G);
  const p0 = E.shadowProfile(img0, B.G, tI.sun, B.start, { frac: 0.5 });
  const a = (tI.sun.az + 180) * Math.PI / 180;
  for (let k = 12; k <= 60; k++) { // paint plain-level pixels along the line from 12 pixels out
    const i = B.start.i - k * Math.cos(a), j = B.start.j + k * Math.sin(a);
    const { x, y } = E.frameXY(B.reg.xf, tI.cam, (j - (B.G.n - 1) / 2) * B.G.s, -(i - (B.G.n - 1) / 2) * B.G.s);
    for (let dy = -2; dy <= 2; dy++) for (let dx = -2; dx <= 2; dx++) { const q = (Math.round(y) + dy) * F2.w + Math.round(x) + dx; if (q >= 0 && q < F2.med.length) F2.med[q] = p0.flat; }
  }
  const p1 = E.shadowProfile(E.frameToGrid(F2, B.reg.xf, tI.cam, B.G), B.G, tI.sun, B.start, { frac: 0.5 });
  const h1 = p1.refused ? 0 : E.shadowHeight(p1.tipPx, 51.73, tI.sun.el);
  assert.ok(!(h1 >= 350 && h1 < 450), 'a frame whose shadow was painted over must leave the band, got ' + h1);
});
test('anchor', 'a corrupted byte in the archived frame is caught by the decoder’s checksum', () => {
  const bad = new Uint8Array(inp.edr['35A72']);
  const recs = E.edrRecords(bad); const lab = E.parseEdrLabel(recs);
  // flip one bit deep inside image line 400
  const line = recs[lab.IMAGE - 1 + 400];
  const off = line.byteOffset - bad.byteOffset + 50;
  bad[off] ^= 0x10;
  const d = E.decodeEDR(bad);
  assert.equal(d.checksumOK, false);
});

// ================================================================== control: the terrain, measured and relit
test('control', 'the terrain’s height, independently read from the shipped bytes, and against the numpy measurement on the full 2 m model', () => {
  // an independent reading: max of the uint16 file, and the median ground on the 2 km ring
  const meta = inp.terrainMeta, dv = new DataView(inp.terrainBytes.buffer, inp.terrainBytes.byteOffset, inp.terrainBytes.byteLength);
  let qmax = -1, imax = -1;
  for (let i = 0; i < meta.rows * meta.cols; i++) { const q = dv.getUint16(2 * i, true); if (q !== meta.missing && q > qmax) { qmax = q; imax = i; } }
  const zmax = meta.z0_m + qmax / meta.units_per_m;
  near(A.peak.z, zmax, 1e-3);
  near(zmax, cross.block_mean_peak_z_m, 0.006, 'the shipped peak is the block mean of the 2 m model, to the centimetre');
  const pr = Math.floor(imax / meta.cols), pc = imax % meta.cols;
  const dyN = meta.map_scale_m * meta.block, lat = (meta.line_projection_offset - (4 * (meta.rows - 1) / 2 + 1.5) - 0.5) / meta.map_resolution_pix_per_deg;
  const dxE = dyN * Math.cos(lat * Math.PI / 180) / Math.cos(meta.center_latitude_deg * Math.PI / 180);
  const ring = [];
  for (let r = 0; r < meta.rows; r++) for (let c = 0; c < meta.cols; c++) {
    const q = dv.getUint16(2 * (r * meta.cols + c), true); if (q === meta.missing) continue;
    const d = Math.hypot((c - pc) * dxE, (r - pr) * dyN); if (Math.abs(d - 2000) <= 100) ring.push(meta.z0_m + q / meta.units_per_m);
  }
  ring.sort((a, b) => a - b);
  const med = ring.length % 2 ? ring[(ring.length - 1) / 2] : (ring[ring.length / 2 - 1] + ring[ring.length / 2]) / 2;
  near(A.bases.ring2000, zmax - med, 1e-3, 'the engine’s 2 km ring height');
  // against the full-resolution numpy measurement: the 8 m block means lower the peak by about 0.6 m
  for (const k of ['ring1500', 'ring2000', 'ring2500']) near(A.bases[k], cross[k + '_height_m'], 1.0, k + ' against 2 m');
  near(A.relief.height, cross.plane_height_m, 1.0, 'the plane-based height against 2 m');
  near(A.relief.height, 362.0, 0.5);
  assert.ok(Math.min(...Object.values(R.bases)) > 350 && Math.max(...Object.values(R.bases)) < 370);
});
test('control', 'the relit terrain matches both Viking frames, with the labels’ north and a ground scale near theirs', () => {
  assert.ok(B.reg.nccAll >= 0.95, '35A72 ' + B.reg.nccAll); assert.ok(C.nccAll >= 0.95, '70A13 ' + C.nccAll);
  near(B.reg.xf.norAz, claim.frames['35A72'].msss_label.NOR_AZ, 2, '35A72 north');
  near(C.xf.norAz, claim.frames['70A13'].msss_label.NOR_AZ, 2, '70A13 north');
  assert.ok(B.reg.xf.scale > 44 && B.reg.xf.scale < 52 && C.xf.scale > 42 && C.xf.scale < 50);
  assert.ok(R.scaleRange.sHi - R.scaleRange.sLo < 0.05 * B.reg.xf.scale, 'the scale is pinned within 5%, so the frame may be used to measure the hill');
  // the correlation readout is the page's ncc on the page's grids
  near(E.ncc(B.reg.render, B.reg.frame).r, B.reg.nccAll, 1e-12);
});
test('control', 'the 1988 shadow arithmetic, run on the render of the terrain as measured at the fitted scale, comes within 3% of the terrain’s height', () => {
  near(R.calib.heightM, B.shadow.render['0.5'].tipPx * B.reg.xf.scale * Math.tan(tI.sun.el * Math.PI / 180), 1e-9);
  assert.ok(Math.abs(R.calib.heightM / A.relief.height - 1) < 0.03, 'calibration ' + R.calib.heightM + ' against ' + A.relief.height);
  near(Number(F['scale.excess'].replace('%', '')), 100 * (51.73 / B.reg.xf.scale - 1), 0.5);
});
test('control', 'Mars24 reproduces NASA’s printed worked example and Table I’s suns', () => {
  const w = A.worked.ex1;
  near(w.Ls, 277.18758, 2e-5); near(w.EOT, -5.18774, 2e-5); near(w.subLonW, 174.72600, 2e-5); near(w.dec, -25.22825, 2e-5);
  near(w.MST, 23 + 59 / 60 + 39 / 3600, 1 / 3600);
  near(A.worked.ex2.Ls, 327.32416, 2e-5); near(A.worked.ex2.subLonW, 4.70500, 2e-5);
  for (const id of ['35A72', '70A13']) { assert.ok(Math.abs(A.sun[id].dAz) < 0.5 && Math.abs(A.sun[id].dEl) < 0.5, id + ' sun within 0.5 degrees of Table I'); }
  near(A.minutesToSunset, 64, 1.5);
  near(A.sun['35A72'].mars24.LTST, 18.57, 0.02);
});
test('control', 'the day scan finds the frame’s hour: the best match within 5 minutes of the time in its label', () => {
  assert.ok(Math.abs(G.minutesFromImage) < 5, 'best at ' + G.minutesFromImage + ' minutes');
  assert.ok(G.curve.every((c) => c.r <= G.best.r + 1e-9));
  assert.ok(Math.min(...G.curve.map((c) => c.r)) < -0.8, 'the morning is anti-correlated');
  assert.ok(G.window01.from < 0 && G.window01.to > 0);
});

// ================================================================== power: the claimed height, planted
test('power', 'the claimed height, planted into a copy of the terrain, is recovered by the unmodified measurement', () => {
  const before = sha(Buffer.from(T.z.buffer));
  const U = E.plantRelief(T, CLAIMED);
  assert.equal(sha(Buffer.from(T.z.buffer)), before, 'the original terrain is untouched');
  assert.notEqual(sha(Buffer.from(U.z.buffer)), before, 'the doctored copy differs');
  assert.equal(U.meta2.plantedHeight, CLAIMED, 'planted at the size Table II prints');
  near(U.z[A.peak.r * T.cols + A.peak.c] - T.z[A.peak.r * T.cols + A.peak.c], CLAIMED - A.relief.height, 1e-3);
  near(E.measureRelief(U, {}).height, CLAIMED, 1.0);
  near(R.plants['412.5'].measured, CLAIMED, 1.0);
  near(R.plants['243.84'].measured, 243.84, 1.0);
  // the plain is untouched: every post below the planting contour is the same
  let changedLow = 0;
  for (let i = 0; i < T.z.length; i++) if (T.z[i] === T.z[i] && T.z[i] - A.relief.baseAtPeak < 15 && U.z[i] !== T.z[i]) changedLow++;
  assert.equal(changedLow, 0);
});
test('power', 'the rule counts the render-to-frame mismatch as uncertainty, and the hill as measured never passes it', () => {
  const s = B.reg.xf.scale, { sLo, sHi } = R.scaleRange;
  for (const f of An.THRESHOLDS) {
    const tf = B.shadow.frame[f].tipPx, tr = B.shadow.render[f].tipPx;
    for (const H of [CLAIMED, An.CLAIM_LOW, An.NASA_HEIGHT, 'measured']) {
      const p = B.power[H][f];
      const tp = H === 'measured' ? tr : B.plants[H].tips[f];
      // independent arithmetic of the stated rule: two sigma, sigma = hypot(scale term, 1 pixel, |render - frame|)
      const sig = Math.sqrt((tp * (sHi - sLo) / (2 * s)) ** 2 + 1 + (tr - tf) ** 2);
      near(p.sigma, sig, 1e-9, H + ' at ' + f);
      assert.equal(p.decisive, Math.abs(tp - tf) >= 2 * sig, H + ' at ' + f);
      assert.equal(p.plantedPx, tp); assert.equal(p.framePx, tf);
    }
    assert.equal(B.power.measured[f].decisive, false, 'the hill as measured must never be ruled out, at ' + f);
    assert.ok(B.power.measured[f].sigmaMismatch > 0);
  }
  assert.equal(F['powm.where'], 'at no threshold');
});
test('power', 'planted, the claimed hill is ruled out midway and at three quarters, not at a quarter; its lower edge only at three quarters', () => {
  const d = (H) => An.THRESHOLDS.map((f) => B.power[H][f].decisive);
  assert.deepEqual(d(CLAIMED), [false, true, true]);
  assert.deepEqual(d(An.CLAIM_LOW), [false, false, true]);
  assert.deepEqual(d(An.NASA_HEIGHT), [false, true, true]);
  assert.equal(F['pow.count'], '2 of 3'); assert.equal(F['pow.where'], 'midway and at three quarters');
  assert.equal(F['pow395.where'], 'only at three quarters'); assert.equal(F['pow244.where'], 'midway and at three quarters');
  for (const f of An.THRESHOLDS) assert.ok(B.power[CLAIMED][f].separation > 0, 'the claimed hill’s shadow is longer than the frame’s at ' + f);
  // the lower edge is the claim's own printed number
  const hRow = claim.tableII.rows.find((r) => r.id === 'height');
  assert.equal(An.CLAIM_LOW, CLAIMED - Number(E.parseCombined(hRow.combined_printed).half));
  near(R.plants['395'].measured, An.CLAIM_LOW, 1.0);
});
test('power', 'render against render, the planting lengthens the shadow by about 4 pixels at every threshold, away from the frame', () => {
  for (const f of An.THRESHOLDS) {
    const tf = B.shadow.frame[f].tipPx, tr = B.shadow.render[f].tipPx, tp = B.plants[CLAIMED].tips[f];
    near(B.power[CLAIMED][f].likeForLike, tp - tr, 1e-12);
    assert.ok(tp - tr > 4.0 && tp - tr < 4.4, 'like for like at ' + f + ': ' + (tp - tr));
    assert.ok(tf < tr && tr < tp, 'the frame is shorter than the render of the hill as measured, which is shorter than the planted hill’s, at ' + f);
    assert.ok(tr - B.plants[An.NASA_HEIGHT].tips[f] > 10, '800 feet, render against render, at ' + f);
  }
  assert.equal(F['pow.like.0.5'], '4.1'); assert.equal(F['pow.like.range'], '4.1 to 4.2');
});
test('power', 'the planted shadow went through the same functions as the frame’s, and the null plant changes nothing', () => {
  const view = { az: tI.cam.scAz, el: 90 - tI.cam.ema };
  const U = E.plantRelief(T, CLAIMED);
  const pk = E.findPeak(U), pp = E.projectPoint(pk.E, pk.N, pk.z, view, A.zRef), st = E.gridOfEN(B.G, pp.E, pp.N);
  const img = E.sceneImage(U, tI.sun, view, A.zRef, B.G, B.reg.psf).img;
  near(E.shadowProfile(img, B.G, tI.sun, st, { frac: 0.5 }).tipPx, B.plants[CLAIMED].tips['0.5'], 1e-9);
  // planting the measured height is the identity, and its shadow is the terrain's
  const U0 = E.plantRelief(T, A.relief.height);
  const img0 = E.sceneImage(U0, tI.sun, view, A.zRef, B.G, B.reg.psf).img;
  near(E.shadowProfile(img0, B.G, tI.sun, B.start, { frac: 0.5 }).tipPx, B.shadow.render['0.5'].tipPx, 0.05);
  // the shadow grows with the planted height
  const t = An.PLANT_HEIGHTS.map((H) => B.plants[H].tips['0.5']);
  for (let k = 1; k < t.length; k++) if (t[k] != null && t[k - 1] != null) assert.ok(t[k] > t[k - 1], 'monotone in height');
});
test('power', 'the grade is A, and the page states the rule and its terms', () => {
  assert.match(html, /This is grade A of the wave’s power test|This is grade A of the wave&rsquo;s power test/);
  assert.ok(has('A planted height is ruled out when its shadow differs from the frame’s by at least twice the combined uncertainty'));
  assert.ok(has('the whole mismatch between the frame and the render of the hill as measured'));
});

// ================================================================== null: the 1988 draping on a flat plane
test('null', 'the drape was run from 72 viewpoints; a flat plane keeps the draped picture from high views and the relief matters from low ones', () => {
  assert.equal(Fd.views.length, 72);
  assert.ok(Fd.byEl[70].min > 0.9 && Fd.byEl[50].min > 0.8, 'high views');
  assert.ok(Fd.byEl[20].min < 0.6, 'low views');
  for (let k = 1; k < An.DRAPE.elevations.length; k++) assert.ok(Fd.byEl[An.DRAPE.elevations[k]].mean > Fd.byEl[An.DRAPE.elevations[k - 1]].mean);
});
test('null', 'the drape can tell a surface from nothing: the flat drape on a flat plane is perfect, and a relief three times higher departs further', () => {
  const view = { az: 210, el: 30 };
  const flatT = E.coarsen(E.flatTerrain(T, A.zRef), An.DRAPE.coarsen).T;
  near(E.drapeNull(flatT, Fd.tF, Fd.tF, view, A.zRef, Fd.win).r, 1, 1e-9);
  const tall = E.cloneTerrain(Fd.Tc);
  for (let i = 0; i < tall.z.length; i++) if (tall.z[i] === tall.z[i]) tall.z[i] = A.zRef + 3 * (tall.z[i] - A.zRef);
  tall.zMax = A.zRef + 3 * (Fd.Tc.zMax - A.zRef); tall.zMin = A.zRef + 3 * (Fd.Tc.zMin - A.zRef);
  const base = E.drapeNull(Fd.Tc, Fd.tD, Fd.tF, view, A.zRef, Fd.win).r;
  const r3 = E.drapeNull(tall, Fd.tD, Fd.tF, view, A.zRef, Fd.win).r;
  assert.ok(r3 < base - 0.05, 'three times the relief ' + r3 + ' against ' + base);
  // the page prints the same comparison
  assert.deepEqual([Fd.tall.az, Fd.tall.el], [view.az, view.el]);
  near(Fd.tall.base, base, 1e-12); near(Fd.tall.tripled, r3, 1e-12);
});

// ================================================================== surface: what the reader sees
test('surface', 'every figure printed in the page equals the recomputation', () => {
  const figs = S.dataFigs(html);
  assert.ok(figs.length >= 140, 'figure spans: ' + figs.length);
  assert.deepEqual(surfaceDisagreements(html, F), []);
  const used = new Set(figs.map((f) => f.key));
  for (const k of ['edr.35.sum', 'edr.70.sum', 't2.height', 't2.slope', 'anchor.px', 'anchor.h', 'anchor.caption', 'relief.h', 'base.range', 'reg35.ncc', 'reg70.ncc', 'sh.frame.0.5', 'sh.p412.0.5', 'pow.sep.0.5', 'pow.sig.0.5', 'pow.like.0.5', 'pow.count', 'rule.412.0.5', 'rule.m.0.5', 'rule.395.0.75', 'plant.412', 'calib.h', 'scale.excess', 'morning.close', 'wrong.maxrefit', 'mirror', 'drape.20', 'drape.70', 'day.best.utc', 'day.best.min', 'morning.holds', 'sunset.min', 'implied.0.5', 'limit'])
    assert.ok(used.has(k), 'the page prints ' + k);
});
test('surface', 'dek, headline, title, meta description, OG, Twitter and JSON-LD match the recomputed text', () => {
  assert.equal((html.match(/<p class="dek" data-dek>([\s\S]*?)<\/p>/) || [])[1], S.escText(X.DEK));
  assert.equal((html.match(/<p class="lede" id="headline" data-headline>([\s\S]*?)<\/p>/) || [])[1], S.escText(X.HEADLINE));
  assert.equal((html.match(/<title>([\s\S]*?)<\/title>/) || [])[1], S.escText(X.SEO));
  assert.equal(meta('name', 'description'), S.escAttr(X.DEK));
  assert.equal(meta('property', 'og:description'), S.escAttr(X.OG));
  assert.equal(meta('name', 'twitter:description'), S.escAttr(X.TW));
  assert.equal(meta('property', 'og:image:alt'), S.escAttr(X.OG_ALT));
  assert.equal(meta('property', 'og:image'), S.OG_IMAGE); assert.equal(meta('name', 'twitter:image'), S.OG_IMAGE);
  assert.equal(meta('property', 'og:url'), S.URL);
  assert.equal(meta('property', 'og:title'), 'The Face an Hour Before Sunset &middot; Artificial Wasteland');
  assert.equal(meta('name', 'twitter:title'), 'The Face an Hour Before Sunset &middot; Artificial Wasteland');
  assert.match(html, /<link rel="canonical" href="https:\/\/artwaste\.land\/strata\/the-face-an-hour-before-sunset\/" \/>/);
  const scripts = [...html.matchAll(/<script type="application\/ld\+json">([\s\S]*?)<\/script>/g)];
  assert.equal(scripts.length, 1);
  const ld = JSON.parse(scripts[0][1]);
  assert.equal(ld['@type'], 'Article'); assert.equal(ld.name, X.SEO); assert.equal(ld.headline, S.TITLE); assert.equal(ld.description, X.DEK);
  assert.equal(ld.url, S.URL); assert.equal(ld.image, S.OG_IMAGE); assert.match(ld.datePublished, /^\d{4}-\d{2}-\d{2}$/);
});
test('surface', 'frontmatter: dek, plain, seoTitle and body match the recomputed text; placard rules hold', () => {
  assert.equal(fmField('title'), S.TITLE);
  assert.equal(fmField('dek'), X.DEK); assert.equal(fmField('seoTitle'), X.SEO); assert.equal(fmField('plain'), X.PLAIN);
  assert.equal(fmField('seam'), 'groundtruth'); assert.equal(fmField('href'), '/strata/' + S.SLUG + '/');
  assert.equal(mdBody, X.BODY.join('\n\n'));
  const plain = fmField('plain');
  assert.ok(plain.length >= 90 && plain.length <= 420, 'plain length ' + plain.length);
  assert.ok(!plain.includes('"'));
  assert.ok((plain.match(/[.!?](\s|$)/g) || []).length <= 3, 'at most three sentences');
  const aw = rawHtml.match(/<meta name="aw-plain" content="([^"]*)"/);
  if (aw) assert.equal(S.decodeEntities(aw[1]), X.PLAIN, 'an injected placard must match the frontmatter');
  const relBlock = (fm.match(/^relates:\n([\s\S]*?)\ndraft:/m) || [])[1];
  assert.equal(relBlock, S.RELATES.map(([to, note]) => '  - to: ' + to + '\n    note: "' + note + '"').join('\n'));
  const rel = [...fm.matchAll(/^\s+- to: (\S+)$/gm)].map((m) => m[1]);
  assert.ok(rel.length >= 3 && rel.length <= 5);
  for (const r of rel) assert.ok(fs.existsSync(path.join(root, 'src/content/strata', r + '.md')), 'relates target exists: ' + r);
  // the one numeric claim in a relates note is the page's own height range
  assert.ok(S.RELATES[1][1].includes('between ' + F['base.rangeInt'].replace(' to ', ' and ').replace(' m', ' m')), 'the Everest note carries the recomputed range');
});
test('surface', 'every other number a reader can see matches the inventory, in order', () => {
  const inv = path.join(here, 'surface-literals.json');
  const now = S.literalNumbers(html);
  if (REGEN && results.every((r) => r.pass)) fs.writeFileSync(inv, JSON.stringify(now, null, 0) + '\n');
  assert.ok(fs.existsSync(inv), 'surface-literals.json missing: run with --regen once every other assertion passes');
  assert.deepEqual(now, JSON.parse(fs.readFileSync(inv, 'utf8')));
});
test('surface', 'every quotation appears as its source prints it', () => {
  for (const q of claim.abstract_sentences) assert.ok(has(q), 'abstract: ' + q.slice(0, 50));
  const cv = claim.corrected_version_sentences;
  for (const k of ['shadow', 'morning', 'conclusion', 'noise']) assert.ok(has(cv[k].replace(/\.$/, '')), 'corrected version: ' + k);
  assert.ok(has('the image of the Face from 35A72 was projected onto the elevation map computed above and reprojected using a computer graphics rendering system'));
  assert.ok(has('the facial features evident in the down-looking view of the orbiter photography are also present when the object is viewed from radically different perspectives'));
  assert.ok(has('The huge rock formation in the center, which resembles a human head, is formed by shadows giving the illusion of eyes, nose and mouth. The feature is 1.5 kilometers (one mile) across, with the sun angle at approximately 20 degrees.'));
  for (const k of ['hirise2025a', 'esa2006', 'nasa2002', 'hirise2007', 'mola', 'mola2', 'mola3', 'mola4', 'ssrn2023a', 'ssrn2023b', 'ssrn2023c', 'reply2018a', 'reply2018b']) assert.ok(has(QUOTES[k].replace(/\.$/, '')), 'quote ' + k);
  assert.equal(claim.abstract_sentences[0], QUOTES.pubmedAbstract, 'the abstract sentence before “also” is quoted, as PubMed prints it');
  assert.ok(has(QUOTES.hirise2025b.slice(QUOTES.hirise2025b.indexOf('the features of the mimetolith'))), 'quote hirise2025b');
  assert.ok(has(QUOTES.sfsShadow.slice(QUOTES.sfsShadow.indexOf('forces the reconstructed surface')).replace(/\.$/, '')), 'quote sfsShadow');
  assert.ok(has('this 800-foot-high mass of rock with steep flanks'));
  assert.ok(has('a recognizable face-like mesa in visual inspection'));
  // Table I and II as printed
  for (const r of claim.tableI.rows) for (const id of ['35A72', '70A13']) assert.ok(has(String(r[id])), 'Table I ' + r.id + ' ' + id);
  for (const r of claim.tableII.rows) { for (const p of r.printed) assert.ok(has(p), 'Table II ' + p); assert.ok(has(r.combined_printed), 'Table II combined ' + r.id); }
});
test('surface', 'the overstatements the 2026-09-23 audits found stay retired, and their corrections stay printed', () => {
  // each of these was on the built page and was withdrawn at the fix stage, with the evidence in the fix report
  for (const gone of ['from almost any side', 'keeps its face on a flat plane', 'a few metres from the altimetry reply', 'found from the terrain and the sun alone',
    'At all three thresholds', 'Five published heights', 'aerocentric', 'where its label prints 154', 'Drawn by eye, once, before any morning render; their SHA-256 is pinned',
    'Society for Planetary SETI Research, ends', 'refits the frame to the wrong render', 'P-17384', 'about 5 m per pixel', 'So the page reproduces the 1988 shadow height'])
    assert.ok(!has(gone), 'retired wording is back: ' + gone);
  assert.ok(!/photographed a face on Mars/.test(html), 'the shareable surface does not assert a face in the page’s own voice');
  for (const kept of ['areocentric solar coordinates with improved timing recipes for Mars seasonal/diurnal climate studies', 'doi:10.1016/S0032-0633(99)00092-6',
    'Four published heights and the page’s own two readings', 'concludes: “It is the author’s belief', 'where the MSSS ancillary label prints 154', 'about 6 m per pixel',
    'the page does not read the midway value’s nearness to the altimetry reply’s 330 m as agreement', 'in the record’s reading', 'whether a face persists in those low views is a judgment the page does not score',
    'with the frame’s placement fitted under Table I’s sun', 'which shows the regions have not changed since, though not when they were drawn', 'It gets there on Table I’s 51.73 m per pixel'])
    assert.ok(has(kept), 'correction missing: ' + kept);
});
test('surface', 'house rules: no em dash, no forbidden words, no third-party requests, no shell at the reader, no repository link', () => {
  const files = fs.readdirSync(dir).filter((f) => fs.statSync(path.join(dir, f)).isFile() && /\.(html|js|json|txt|md)$/.test(f));
  for (const f of files) assert.ok(!readB(f).toString('utf8').includes(EM_DASH), 'em dash in ' + f);
  for (const f of fs.readdirSync(here).filter((f) => /\.(mjs|md|py|json)$/.test(f))) assert.ok(!fs.readFileSync(path.join(here, f), 'utf8').includes(EM_DASH), 'em dash in research/' + f);
  assert.ok(!md.includes(EM_DASH));
  const text = fullVisible.toLowerCase() + ' ' + md.toLowerCase();
  for (const w of ['fraud', 'hoax', 'fabricat', 'misconduct', 'debunk', 'believer', 'conspiracy', 'pseudoscien', 'fringe', 'crank', 'gullib'])
    assert.ok(!text.includes(w), 'forbidden word: ' + w);
  assert.ok(!/github\.com\/[^"]*Artificial-Wasteland/i.test(html));
  assert.ok(!/\b(node|npm|npx|python3?) [\w./-]+/.test(fullVisible), 'no shell command at the reader');
  for (const m of html.matchAll(/<(?:script|img|iframe|audio|video|source)\b[^>]*\ssrc="([^"]+)"/g)) assert.ok(!/^(https?:)?\/\//.test(m[1]), 'external resource ' + m[1]);
  for (const m of html.matchAll(/<link\b([^>]*)>/g)) {
    const relv = (m[1].match(/\srel="([^"]+)"/) || [])[1] || '', href = (m[1].match(/\shref="([^"]+)"/) || [])[1] || '';
    if (/stylesheet|preload|modulepreload|icon|manifest|prefetch/.test(relv)) assert.ok(!/^(https?:)?\/\//.test(href), 'external resource ' + href);
  }
  for (const f of files.filter((f) => f.endsWith('.js'))) {
    const src = readB(f).toString('utf8');
    assert.ok(!/(fetch|import)\s*\(\s*['"`]https?:/.test(src) && !/from\s+['"]https?:/.test(src) && !/XMLHttpRequest|WebSocket|sendBeacon|EventSource|importScripts/.test(src), 'third-party request in ' + f);
    for (const u of src.match(/(?:https?:)?\/\/[a-z0-9.-]+\.[a-z]{2,}[^\s'"`)]*/gi) || []) {
      if (u === 'http://www.w3.org/2000/svg') continue;
      assert.ok(f === 'readings.js', 'absolute URL in ' + f + ': ' + u);   // readings.js holds citation URLs as words, never fetched
    }
    if (/fetch\s*\(/.test(src)) assert.equal(f, 'data.js', 'only data.js fetches, and only beside itself');
  }
  assert.match(readB('data.js').toString('utf8'), /fetch\(new URL\(name, base\)\)/);
});
test('surface', 'structure: closing tags, one inline script (the JSON-LD), modules parse, accessibility basics', () => {
  assert.match(html.trimEnd(), /<script type="module" src="page\.js"><\/script>\s*<\/body>\s*<\/html>$/);
  const inline = [...html.matchAll(/<script(?![^>]*\ssrc=)([^>]*)>([\s\S]*?)<\/script>/g)];
  assert.equal(inline.length, 1); assert.match(inline[0][1], /application\/ld\+json/);
  for (const f of fs.readdirSync(dir).filter((f) => f.endsWith('.js'))) {
    const r = spawnSync(process.execPath, ['--check', path.join(dir, f)], { encoding: 'utf8' });
    assert.equal(r.status, 0, f + ': ' + r.stderr);
  }
  assert.match(html, /prefers-reduced-motion/); assert.match(html, /:focus-visible/);
  assert.ok((html.match(/role="status"/g) || []).length >= 10, 'live readouts');
  assert.ok((html.match(/aria-live="polite"/g) || []).length >= 10);
  assert.ok(!/<span[^>]*(onclick|role="button"|tabindex)/.test(html), 'no clickable span');
  for (const m of html.matchAll(/<button\b([^>]*)>/g)) assert.match(m[1], /type="button"/);
  for (const m of html.matchAll(/<input\b([^>]*)>/g)) {
    const attrs = m[1]; const id = (attrs.match(/\sid="([^"]+)"/) || [])[1];
    const wrapped = /type="radio"/.test(attrs);
    const labelled = id && (html.includes('for="' + id + '"') || new RegExp('<label[^>]*>[^<]*(?:<[^/][^>]*>[^<]*)*<input[^>]*id="' + id + '"').test(html));
    assert.ok(wrapped || labelled || /aria-label=/.test(attrs), 'unlabelled input ' + attrs);
  }
  for (const m of html.matchAll(/<canvas\b([^>]*)>/g)) { assert.match(m[1], /aria-label="/, 'canvas has a label'); assert.match(m[1], /role="img"/, 'canvas is exposed as an image'); }
  for (const m of html.matchAll(/<table\b/g)) assert.match(html.slice(Math.max(0, m.index - 120), m.index), /<div class="scroll">\s*$/, 'every table sits in a horizontal scroller');
  assert.match(html, /\.grid2 > \*,\.grid3 > \*\{min-width:0\}/);
  assert.match(html, /\.scroll\{overflow-x:auto/);
  assert.match(html, /<link rel="stylesheet" href="\/fonts\/fonts\.css" \/>/);
  // wiring the audits asked for: the anchor's second paragraph follows the controls, an empty date is named,
  // charts draw a narrow layout on phones instead of hiding their marks off-screen, and the grid has marks
  const pageJs = readB('page.js').toString('utf8'), renderJs = readB('render.js').toString('utf8');
  assert.ok(html.includes('id="anchorMore"') && pageJs.includes("setText('anchorMore'"));
  assert.ok(pageJs.includes('Enter a date and time first.'));
  assert.ok(!/min-width:34rem/.test(html) && /function sized\(svg, H\)/.test(renderJs) && /function gridMark\(/.test(renderJs));
  assert.ok(pageJs.includes("state.sunSource === 'mars24' ? sunMars24() : sunTableI()"), 'the sun switch drives the planted render');
});

// ================================================================== choices: each changes an output
const CHOICES = [
  { id: 'threshold', label: 'Where the shadow ends: the fraction of the way from the shadow’s level to flat ground', options: [0.25, 0.5, 0.75], default: 0.5, affects: ['frame shadow length', 'shadow height', 'planted-versus-frame separation'], inert: false },
  { id: 'shadowScale', label: 'Metres per pixel for the shadow height', options: ['tableI', 'lit', 'msss'], default: 'tableI', affects: ['shadow height'], inert: false },
  { id: 'base', label: 'What the peak’s height is measured from', options: ['plane', 'ring1500', 'ring2000', 'ring2500', 'tip'], default: 'plane', affects: ['peak height'], inert: false },
  { id: 'contourM', label: 'The outline the length and width are read at, metres above the base', options: [10, 20, 50, 100], default: 20, affects: ['length', 'width', 'refusal at 10 m'], inert: false },
  { id: 'slopeCellPosts', label: 'The cell the maximum slope is read over, in 8 m posts (half a post is offered, and refused)', options: [0.5, 1, 2, 3, 4, 5, 6, 7], default: 6, affects: ['maximum slope', 'refusal below one post'], inert: false },
  { id: 'planted', label: 'The terrain: as measured, raised to the claim’s lower edge or to the 1988 height, or lowered to 800 feet', options: ['measured', '395', '412.5', '243.84'], default: 'measured', affects: ['measured height', 'render', 'shadow length'], inert: false },
  { id: 'renderScale', label: 'The ground scale of the render', options: ['post', 'frame', '100', '250', '4'], default: 'frame', affects: ['render', 'refusal at 4 m'], inert: false },
  { id: 'sunSource', label: 'The sun for the control render of 35A72: Table I or Mars24 at the label’s time', options: ['tableI', 'mars24'], default: 'tableI', affects: ['rendered shadow length'], inert: false },
  { id: 'drapeView', label: 'The viewpoint of the draped photograph', options: ['az 0 to 330 by 30', 'el 20 to 70 by 10'], default: 'az 210, el 30', affects: ['drape correlation'], inert: false },
];
test('choices', 'the threshold moves the frame’s shadow and the height', () => {
  const t = An.THRESHOLDS.map((f) => B.shadow.frame[f].tipPx);
  assert.equal(new Set(t.map((v) => v.toFixed(2))).size, 3);
  assert.ok(t[0] < t[1] && t[1] < t[2]);
  const h = An.THRESHOLDS.map((f) => B.anchor.byScale.tableI[f]);
  assert.ok(h[0] < h[1] && h[1] < h[2]);
});
test('choices', 'the scale moves the shadow height, and the base, contour and slope cell move the terrain’s numbers', () => {
  const h = ['tableI', 'lit', 'msss'].map((k) => B.anchor.byScale[k]['0.5']);
  assert.equal(new Set(h.map((v) => v.toFixed(1))).size, 3);
  const bases = Object.values(R.bases);
  assert.equal(new Set(bases.map((v) => v.toFixed(1))).size, bases.length);
  near(E.measureRelief(T, { base: 'tip', sun: tI.sun }).height, R.bases.tip, 1e-9);
  const L = [20, 50, 100].map((c) => A.contours[c].lengthM);
  assert.ok(L[0] > L[1] && L[1] > L[2]);
  assert.equal(A.contours[10].refused, true);
  const sl = Object.values(A.slopes).map((s) => s.maxDeg);
  for (let k = 1; k < sl.length; k++) assert.notEqual(sl[k].toFixed(2), sl[k - 1].toFixed(2));
});
test('choices', 'the planted terrain, the render scale, the sun source and the drape viewpoint each move an output', () => {
  assert.ok(R.plants['412.5'].tips['0.5'] > B.shadow.render['0.5'].tipPx && R.plants['243.84'].tips['0.5'] < B.shadow.render['0.5'].tipPx);
  const sh = E.shade(T, tI.sun);
  const G1 = E.makeGrid(B.G.cE, B.G.cN, 60, 100), G2 = E.makeGrid(B.G.cE, B.G.cN, 24, 250);
  const a = E.toGrid(T, sh.I, G1), b = E.toGrid(T, sh.I, G2);
  assert.ok(!a.refused && !b.refused && a.length !== b.length);
  assert.ok(E.toGrid(T, sh.I, E.makeGrid(B.G.cE, B.G.cN, 10, 4)).refused);
  assert.ok(Math.abs(B.otherSun.tipPx - B.shadow.render['0.5'].tipPx) > 0.2, 'Mars24 sun moves the rendered shadow');
  const v = Fd.views; assert.ok(new Set(v.map((x) => x.r.toFixed(3))).size > 60);
});
test('choices', 'every choice is well formed for the gate, declared on the page and in record.json', () => {
  for (const c of CHOICES) {
    assert.ok(c.id && Array.isArray(c.options) && c.options.length >= 2 && c.default !== undefined && Array.isArray(c.affects) && typeof c.inert === 'boolean', c.id);
    assert.equal(new Set(c.options.map(String)).size, c.options.length);
  }
  for (const id of ['threshold', 'shadowScale', 'base', 'contourM', 'planted', 'renderScale', 'sunSource']) assert.ok(html.includes('data-state="' + id + '"'), 'control for ' + id);
  for (const c of CHOICES.filter((c) => ['threshold', 'shadowScale', 'base', 'contourM', 'planted', 'renderScale', 'sunSource'].includes(c.id)))
    for (const o of c.options) assert.ok(html.includes('data-state="' + c.id + '" value="' + o + '"'), 'a control for ' + c.id + ' = ' + o);
  assert.ok(html.includes('id="slopeCell" min="0" max="7"') && html.includes('id="drapeAz"') && html.includes('id="drapeEl"'));
  if (record) assert.deepEqual(record.choices, CHOICES);
});

// ================================================================== fault: planted into copies of the data
test('fault', 'a misread sun (the frame’s own SUN AZ, the pilot’s azimuths) cannot be fitted to the frame', () => {
  for (const w of D.wrong) { assert.ok(w.refit < 0.75, w.az + ' refit ' + w.refit); assert.ok(w.fixed < 0.75, w.az + ' fixed ' + w.fixed); }
  assert.ok(D.west.every((w) => w.fixed > 0.8 && w.fixed < B.reg.nccAll));
});
test('fault', 'the frame mirrored left to right cannot be fitted to the terrain', () => {
  assert.ok(D.mirror.nccAll < 0.75, 'mirrored ' + D.mirror.nccAll);
});
test('fault', 'the terrain scaled to the claimed height lengthens the shadow by at least 4 pixels', () => {
  assert.ok(B.plants[CLAIMED].tips['0.5'] - B.shadow.render['0.5'].tipPx >= 4, 'lengthened by ' + (B.plants[CLAIMED].tips['0.5'] - B.shadow.render['0.5'].tipPx));
});
test('fault', 'the surface check goes red on a corrupted figure and a corrupted dek', () => {
  const first = S.dataFigs(html).find((d) => d.key === 'reg35.ncc');
  const corrupted = html.slice(0, first.index) + first.full.replace(F['reg35.ncc'], '0.971') + html.slice(first.index + first.full.length);
  assert.deepEqual(surfaceDisagreements(corrupted, F), ['reg35.ncc']);
  assert.notEqual(S.escText(X.DEK.replace(F['reg35.ncc'], '0.971')), (html.match(/<p class="dek" data-dek>([\s\S]*?)<\/p>/) || [])[1]);
  const lits = S.literalNumbers(html);
  assert.notDeepEqual(S.literalNumbers(html.replace('51.73 m/pixel</td>', '51.74 m/pixel</td>')), lits, 'a changed literal is visible to the inventory');
});
function pinMismatches(bufs) { return Object.entries(bufs).filter(([f, b]) => sha(b) !== SHA256[f]).map(([f]) => f).sort(); }
test('fault', 'a changed byte in a frozen file is caught by the same pin check the provenance group runs', () => {
  const real = Object.fromEntries(Object.values(FILES).map((f) => [f, readB(f)]));
  assert.deepEqual(pinMismatches(real), []);
  const bad = { ...real, [FILES.terrain]: Buffer.from(real[FILES.terrain]) };
  bad[FILES.terrain][123456] ^= 1;
  assert.deepEqual(pinMismatches(bad), [FILES.terrain]);
});

// ================================================================== refusal: outside what the record supports
test('refusal', 'the engine refuses renders finer than its posts, suns outside 1976 to 1980, shadows off the terrain, unreadable outlines and slopes', () => {
  const sh = E.shade(T, tI.sun);
  assert.match(E.toGrid(T, sh.I, E.makeGrid(B.G.cE, B.G.cN, 10, 4)).refused, /finer than the shipped terrain/);
  assert.match(E.sunAt('1985-07-25T15:25:14Z', A.peak.lat, A.peak.lonE).refused, /1976 to 1980/);
  assert.match(E.sunAt('1975-07-25T15:25:14Z', A.peak.lat, A.peak.lonE).refused, /1976 to 1980/);
  assert.ok(!E.sunAt('1976-07-25T15:25:14Z', A.peak.lat, A.peak.lonE).refused);
  const low = { az: tI.sun.az, el: B.limit.minElevation - 0.5 };
  assert.match(E.shadowTipGround(T, A.peak, low).refused || '', /leaves the terrain model/);
  assert.ok(!E.shadowTipGround(T, A.peak, { az: tI.sun.az, el: B.limit.minElevation + 0.5 }).refused);
  assert.ok(B.limit.minElevation < B.limit.flatEstimate, 'rising ground beyond the plain catches the shadow below the flat-plain limit');
  assert.match(E.measureRelief(T, { contourM: 10 }).footprint.refused, /runs to the edge of the terrain model/);
  assert.ok(!E.measureRelief(T, { contourM: 20 }).footprint.refused);
  assert.match(E.measureRelief(T, { slopeCellPosts: 0.5 }).slope.refused, /smaller than one post/);
  // under a 25 degree sun from 35A72's direction the peak casts no shadow of its own: what is dark is the flank
  const s25 = { az: tI.sun.az, el: 25 };
  assert.equal(E.shadowTipGround(T, A.peak, s25).noShadow, true);
  // under a high sun no shadow separates from the hill at all, and the profile refuses
  const s60 = { az: tI.sun.az, el: 60 };
  const img = E.sceneImage(T, s60, { az: tI.cam.scAz, el: 90 - tI.cam.ema }, A.zRef, B.G, B.reg.psf).img;
  assert.ok(E.shadowProfile(img, B.G, s60, B.start, { frac: 0.5 }).refused, 'a 60 degree sun must be refused');
});
test('refusal', 'the morning test will not call a sun whose margin is under the stated band, and the band is what the page prints', () => {
  const g = Es.grid;
  assert.equal(g.length, 42);
  assert.equal(E.MORNING_TIE, 0.05); assert.equal(F['morning.tie'], '5%');
  for (const c of g) {
    const inBand = Math.abs(c.leftMargin) < E.MORNING_TIE || Math.abs(c.eyeMargin) < E.MORNING_TIE;
    assert.equal(c.close, inBand, c.az + ',' + c.el);
    assert.equal(c.verdict, c.holds ? 'holds' : inBand ? 'close' : 'fails');
    // the margins are the region means over the brightness of flat ground under that sun
    near(c.leftMargin, (c.means.right_side - c.means.left_side) / Math.sin(c.el * Math.PI / 180), 1e-9);
    near(c.eyeMargin, (c.means.left_eye - c.means.left_side) / Math.sin(c.el * Math.PI / 180), 1e-9);
  }
  const n = (v) => g.filter((c) => c.verdict === v).length;
  assert.equal(n('holds') + n('close') + n('fails'), 42);
  assert.equal(F['morning.close'], String(n('close'))); assert.equal(F['morning.fails'], String(n('fails')));
  assert.ok(g.find((c) => c.az === 45 && c.el === 45).close, 'a sun whose eye margin is a thousandth is too close to call');
  // the first half of the sentence follows from any eastern sun
  assert.ok(Math.min(...g.map((c) => c.leftMargin)) > 0.2);
  assert.equal(Es.afternoon.reversed, true); assert.equal(Es.afternoon.close, false);
});
test('refusal', '70A13’s shadow is refused, for the reason the terrain gives, and the page says so', () => {
  assert.ok(C.refusal && /casts no shadow of its own/.test(C.refusal), C.refusal);
  assert.equal(C.tip.noShadow, true);
  const p300 = C.probe.find((p) => p.d === 300); assert.ok(p300.drop < p300.rayDrop);
  assert.ok(has('The peak casts no shadow of its own along that line'));
  assert.ok(has('the page refuses to read it') && has('The page refuses cells smaller than its') && has('The page refuses three things here and says why'));
  assert.ok(has('the slider’s first stop, half a post, shows the refusal'));
  assert.ok(E.measureRelief(T, { slopeCellPosts: 0.5 }).slope.refused, 'the half-post stop is refused by the engine the page calls');
});

// ================================================================== provenance
test('provenance', 'every frozen file’s SHA-256 matches its pin, record.json and the README', () => {
  for (const f of Object.values(FILES)) {
    const h = sha(readB(f));
    assert.equal(h, SHA256[f], f);
    assert.ok(readme.includes(h), 'README lists ' + f);
    if (record) assert.ok(record.records.some((r) => r.sha256 === h), 'record.json lists ' + f);
  }
  const tm = inp.terrainMeta;
  assert.equal(tm.sha256, SHA256[FILES.terrain]);
  assert.equal(tm.source_sha256, '3d325768738dd54ea642cdc6339e67c0daeb9a3d73450f958bc21646f2c30a60');
  assert.equal(cross.source_sha256, tm.source_sha256);
  assert.ok(readme.includes(tm.source_sha256));
  for (const [f, m] of Object.entries(PDS_MD5)) { assert.equal(md5(readB(f)), m); assert.ok(readme.includes(m)); }
  const regionsSha = sha(readB(FILES.regions));
  assert.equal(regionsSha, 'e0c7d3bc549f3b77c65f84565268565f7e80c3ee6b7ee473677fc680d0bd1374', 'the regions are unchanged since they were pinned');
});

// ================================================================== verdict
test('verdict', 'category, date, scope, sources and what would change it are printed and match record.json', () => {
  assert.match(html, /<p class="cat" id="verdictCat">ARTEFACT<\/p>/);
  assert.equal(VERDICT.category, 'ARTEFACT'); assert.equal(VERDICT.as_of, '2026-09-23');
  assert.match(html, /<time datetime="2026-09-23" id="verdictDate">23 September 2026<\/time>/);
  assert.equal(S.decodeEntities((html.match(/<span id="verdictScope">([\s\S]*?)<\/span>/) || [])[1] || ''), VERDICT.scope);
  assert.equal(S.decodeEntities((html.match(/<span id="verdictChange">([\s\S]*?)<\/span>/) || [])[1] || ''), VERDICT.would_change);
  const lis = [...html.matchAll(/<li id="src-[a-z]+">([\s\S]*?)<\/li>/g)];
  assert.ok(lis.length >= 2); assert.equal(lis.length, VERDICT.sources.length);
  lis.forEach((li, i) => assert.equal(S.decodeEntities(li[1]), VERDICT.sources[i]));
  assert.equal(S.decodeEntities((html.match(/<span id="novelty">([\s\S]*?)<\/span>/) || [])[1] || ''), NOVELTY);
  assert.ok(NOVELTY.startsWith('we searched ') && NOVELTY.includes('on 2026-09-23'));
  assert.ok(has(X.HEADLINE));
  assert.ok(has(QUOTES.hirise2025a) && has(QUOTES.esa2006), 'the verdict sources’ own words');
  if (record) {
    assert.deepEqual(record.verdict, { category: VERDICT.category, as_of: VERDICT.as_of, sources: [...VERDICT.sources], would_change: VERDICT.would_change });
    assert.equal(record.decided_by, VERDICT.decided_by); assert.equal(record.years_to_decision, VERDICT.years_to_decision);
  }
});

// ================================================================== record.json
function makeRecord(ledger) {
  const f35 = claim.frames['35A72'], f70 = claim.frames['70A13'];
  const hashes = Object.fromEntries(Object.values(FILES).map((f) => [f, sha(readB(f))]));
  const PD = 'NASA Science Data license: Creative Commons Zero for data from NASA-led missions unless the file is marked otherwise (the file carries no such mark)';
  return {
    slug: S.SLUG, title: S.TITLE, href: '/strata/' + S.SLUG + '/', field: 'planetary science',
    claim: {
      statement: claim.abstract_sentences.join(' '),
      claimants: 'Mark J. Carlotto (The Analytic Sciences Corporation)',
      citation: 'Mark J. Carlotto; 1988; Digital imagery analysis of unusual Martian surface features; Applied Optics; volume 27, issue 10; pages 1926-1933; 15 May 1988; doi:10.1364/AO.27.001926; no arXiv id',
      year: 1988,
      headline_as_printed: claim.headline_as_printed,
    },
    records: [
      { file: FILES.edr35, role: 'claimant-data', name: 'Viking Orbiter 1 frame 035A72 (25 July 1976), the PDS EDR exactly as archived (Huffman first-difference coded)', url: f35.pds_url, licence: PD, licence_url: 'https://science.data.nasa.gov/about/license', retrieved: '2026-09-23', sha256: hashes[FILES.edr35], units: 1056 * 1204 },
      { file: FILES.edr70, role: 'claimant-data', name: 'Viking Orbiter 1 frame 070A13 (30 August 1976), the PDS EDR exactly as archived', url: f70.pds_url, licence: PD, licence_url: 'https://science.data.nasa.gov/about/license', retrieved: '2026-09-23', sha256: hashes[FILES.edr70], units: 1056 * 1204 },
      { file: FILES.claim, role: 'claimant-data', name: 'The 1988 paper’s Tables I and II and sentences as printed, with each frame’s label values, crop and search window', url: 'https://opg.optica.org/ao/abstract.cfm?uri=ao-27-10-1926; http://spsr.nmcc.edu/pages/peer-reviewed-journal-publications-and-other-articles/digital-imagery-analysis-of-unusual-martian-surface-features.php', licence: 'Transcribed facts and short quotations with citation', licence_url: 'https://doi.org/10.1364/AO.27.001926', retrieved: '2026-09-23', sha256: hashes[FILES.claim], units: claim.tableI.rows.length + claim.tableII.rows.length },
      { file: FILES.terrain, role: 'control-data', name: 'HiRISE stereo terrain model DTEED_080970_2210_080535_2210_A01, 4 by 4 block means of its 2 m posts, to the centimetre', url: inp.terrainMeta.source_url, licence: PD + '; HiRISE usage policy: public domain, credit NASA/JPL-Caltech/UArizona', licence_url: 'https://science.data.nasa.gov/about/license', retrieved: '2026-09-23', sha256: hashes[FILES.terrain], units: inp.terrainMeta.valid_posts },
      { file: FILES.terrainMeta, role: 'control-data', name: 'The terrain’s projection keywords, encoding and the source file’s SHA-256', url: inp.terrainMeta.source_url, licence: PD, licence_url: 'https://science.data.nasa.gov/about/license', retrieved: '2026-09-23', sha256: hashes[FILES.terrainMeta], units: 1 },
      { file: FILES.regions, role: 'reference', name: 'The three regions of the Face for the morning-light test, drawn before any morning render', url: 'https://artwaste.land/strata/the-face-an-hour-before-sunset/regions.json', licence: 'The page’s own', licence_url: 'https://artwaste.land/strata/the-face-an-hour-before-sunset/NOTICE.txt', retrieved: '2026-09-23', sha256: hashes[FILES.regions], units: 3 },
      { file: FILES.hirise2007, role: 'reference', name: 'HiRISE PSP_003234_2210 (5 April 2007), a reduced crop of the browse image, shown and never computed from', url: 'https://hirise-pds.lpl.arizona.edu/PDS/EXTRAS/RDR/PSP/ORB_003200_003299/PSP_003234_2210/PSP_003234_2210_RED.abrowse.jpg', licence: 'HiRISE usage policy: public domain, credit NASA/JPL-Caltech/UArizona', licence_url: 'https://www.uahirise.org/PSP_003234_2210', retrieved: '2026-09-23', sha256: hashes[FILES.hirise2007], units: 1 },
    ],
    anchor: {
      what: 'Table II’s Combined column through combineFrames, and the 1988 shadow method (length x scale x tan(sun elevation)) run by shadowProfile on frame 35A72 decoded from the PDS file, with Table I’s inputs',
      expected: 'Combined: 412.5 ± 17.5 (4.2%), 2.54 ± 0.08 (3.1%), 2.045 ± 0.015 (0.7%), 39.01 ± 5.82 (15%); shadow height: approximately 400 meters',
      computed: 'Combined: ' + F['t2.height'] + ', ' + F['t2.length'] + ', ' + F['t2.width'] + ', ' + F['t2.slope'] + ' (' + F['t2.agree'] + ' rows agree at the printed rounding); shadow: ' + F['anchor.px'] + ' pixels midway, ' + F['anchor.h'] + ' at 51.73 m per pixel and 10.07 degrees (' + F['anchor.t1.0.25'] + ' to ' + F['anchor.t1.0.75'] + ' across the three thresholds)',
      agrees: B.anchor.inBand && A.tableII.every((t) => t.agrees),
      tolerance: 'Table II: within half a unit of the last printed digit, inclusive; the shadow: the band 350 up to 450 m that approximately 400, printed to one significant figure, covers',
    },
    control: {
      name: 'The HiRISE team’s 2025 stereo terrain model of the hill, measured, and relit under the 35A72 and 70A13 suns as the Viking camera would record it',
      citation: 'University of Arizona HiRISE team (producers Alfred McEwen, Kris Amanda Akers); DTEED_080970_2210_080535_2210_A01; MRO-M-HIRISE-5-DTM-V1.0; stereo pair ESP_080970_2210 (4 November 2023) and ESP_080535_2210 (1 October 2023); NASA Planetary Data System',
      computed: 'peak ' + F['relief.h'] + ' above the fitted plain (' + F['base.range'] + ' across five bases); correlation of the relit terrain with 35A72 ' + F['reg35.ncc'] + ' and with 70A13 ' + F['reg70.ncc'] + '; maximum slope ' + F['slope.6'] + ' over ' + F['slope.6cell'] + ' cells; outline ' + F['fp.20'] + ' at 20 m',
      as_printed: QUOTES.hirise2025a + ' ' + QUOTES.hirise2025b,
    },
    power: {
      grade: 'A-injection',
      planted: 'The relief above the fitted plain scaled by ' + F['plant.412.factor'] + ' inside the hill’s outline at 20 m (tapering over the next 20 m) in a copy of the terrain, so that the peak stands at Table II’s 412.5 m; also 395 m (the claim’s own lower edge, 412.5 minus 17.5) and 243.84 m (800 feet) for balance; each run through the unmodified measureRelief, sceneImage and shadowProfile',
      recovered: 'measured ' + F['plant.412'] + ' (395 m planted: ' + F['plant.395'] + '; 800 feet: ' + F['plant.244'] + '); under the 35A72 sun the planted hill’s shadow is ' + F['sh.p412.0.5'] + ' pixels midway against the frame’s ' + F['sh.frame.0.5'] + ' and the render of the hill as measured ' + F['sh.render.0.5'] + ', so render against render the planting lengthens it by ' + F['pow.like.range'] + ' pixels across the three thresholds; against the frame: ' + F['rule.412.0.25'] + ' at a quarter, ' + F['rule.412.0.5'] + ' midway, ' + F['rule.412.0.75'] + ' at three quarters (difference against twice the uncertainty; the hill as measured decides ' + F['powm.where'] + ')',
      verdict: 'the control COULD have confirmed the claim: the terrain model recovers a planted 412.5 m hill to within a metre. The 1976 frame, under a stated rule (a difference of at least twice the combined uncertainty of scale fit, one pixel and the frame-to-render mismatch), rules out 412.5 m ' + F['pow.where'] + ' and cannot decide at a quarter; it rules out the claim’s lower edge of 395 m ' + F['pow395.where'],
    },
    null_through_claimant_method: {
      applicable: true,
      what: 'The 1988 Figure 8 procedure (drape the 35A72 photograph over a surface and view it from elsewhere) run with drapeTexture and drapeNull on the true terrain and on a flat plane, which has no relief, from 72 viewpoints',
      result: 'the flat-plane view correlates ' + F['drape.20'] + ' with the true-terrain view from 20 degrees up, ' + F['drape.50'] + ' from 50 and ' + F['drape.70'] + ' from 70; ' + F['drape.hi'] + ' views from 50 degrees up correlate at least 0.8',
    },
    verdict: { category: VERDICT.category, as_of: VERDICT.as_of, sources: [...VERDICT.sources], would_change: VERDICT.would_change },
    decided_by: VERDICT.decided_by,
    years_to_decision: VERDICT.years_to_decision,
    choices: CHOICES,
    headline: X.HEADLINE,
    novelty: NOVELTY,
    ledger,
  };
}
const ASSERTIONS = {
  claim_reproduced: 'anchor:tableII-combineFrames-and-35A72-shadow-through-shadowProfile',
  control_computed: 'control:hirise-dtm-measureRelief-and-registerFrame-both-frames',
  control_can_confirm: 'power:412.5-m-planted-into-the-dtm-recovered-and-shadow-ruled-by-a-rule-the-measured-hill-never-passes',
  rendered_figures_asserted: 'surface:data-fig-spans-head-frontmatter-and-literal-inventory',
  choices_are_live: 'choices:nine-choices-each-moves-an-output',
  planted_fault_caught: 'fault:misread-sun-mirrored-frame-scaled-terrain-corrupted-bytes',
  refusal_asserted: 'refuse:finer-than-posts-years-shadow-off-terrain-70A13-outline-slope',
  provenance_pinned: 'provenance:sha256-md5-pins-readme-record',
  verdict_dated: 'verdict:category-date-scope-sources-printed',
};
const group = (name) => results.some((t) => t.group === name) && results.filter((t) => t.group === name).every((t) => t.pass);
const ledger = {
  claim_reproduced: group('anchor'),
  control_computed: group('control'),
  control_can_confirm: group('power'),
  rendered_figures_asserted: group('surface'),
  choices_are_live: group('choices'),
  planted_fault_caught: group('fault'),
  refusal_asserted: group('refusal'),
  provenance_pinned: group('provenance'),
  verdict_dated: group('verdict') && group('null'),
};
const expected = makeRecord(Object.fromEntries(Object.entries(ledger).map(([k, v]) => [k, { value: v, assertion: ASSERTIONS[k] }])));
if (REGEN) {
  if (results.some((t) => !t.pass)) { for (const f of results.filter((t) => !t.pass)) console.error('FAIL ' + f.group + ': ' + f.name + '\n  ' + f.error); throw new Error('Refusing to write record.json while assertions fail.'); }
  fs.writeFileSync(recordPath, JSON.stringify(expected, null, 2) + '\n');
}
test('manifest', 'record.json equals the manifest built from this run’s own results', () => {
  assert.ok(fs.existsSync(recordPath), 'record.json missing');
  assert.deepEqual(JSON.parse(fs.readFileSync(recordPath, 'utf8')), expected);
});

const failures = results.filter((t) => !t.pass);
for (const f of failures) console.error('FAIL ' + f.group + ': ' + f.name + '\n  ' + f.error);
if (LEDGER) for (const [k, v] of Object.entries(ledger)) console.log(k + '=' + v);
else console.log((results.length - failures.length) + '/' + results.length + ' assertions passed.');
if (failures.length) process.exitCode = 1;
