import assert from 'node:assert/strict';
import { readFileSync, existsSync } from 'node:fs';
import { gunzipSync } from 'node:zlib';
import { createHash } from 'node:crypto';
import { fileURLToPath } from 'node:url';
import { dirname, resolve } from 'node:path';
import {
  CROP_SIZE, FALLBACK_SIZE, SIGMA0, LEVELS, WINDOWS, DB4, NULL_SHIFTS, MAX_TRAINING,
  MIN_GROUP, SCENE_LIMIT, CURVE_POINTS, SHIFT_RANGE, PCE_HALF_NEIGHBOURHOOD, SCALE_SEARCH,
  FALLBACK_ARCHIVE, HISTORICAL, Refusal, parseJPEG, parsePNG, inspectImage, validateGroup,
  compatibilityKey, selectMembership, cropPlane, decodeStoredGrayPNG, parseTar, denoise,
  residual, referenceMean, mlePattern, predictResidual, centeredNCC, shiftedNCC, pce,
  scaleAndRestore, shiftSurface, reconstructionError, runAnalysis, planeDigest
} from '../../public/strata/the-camera-in-the-noise/prnu.mjs';
import { analysisMatrix, orthogonalityError, oracleResidual, substituteRule, maxAbsDifference } from './oracle.mjs';
import { STORED, gainField, frame, grayPNG, ihdrPNG, idatPNG, concat, chunk, storedZlib, PNG_SIGNATURE, sha } from './specimens.mjs';

const HERE = dirname(fileURLToPath(import.meta.url));
const ROOT = resolve(HERE, '../..');
const PUB = resolve(ROOT, 'public/strata/the-camera-in-the-noise');
const INDEX = readFileSync(resolve(PUB, 'index.html'), 'utf8');
const PAGE = readFileSync(resolve(PUB, 'page.mjs'), 'utf8');
const WORKER = readFileSync(resolve(PUB, 'worker.mjs'), 'utf8');
const PRNU = readFileSync(resolve(PUB, 'prnu.mjs'), 'utf8');
const MAKE = readFileSync(resolve(PUB, 'make-fallback.mjs'), 'utf8');
const FRONT = readFileSync(resolve(ROOT, 'src/content/strata/the-camera-in-the-noise.md'), 'utf8');
const README = readFileSync(resolve(HERE, 'README.md'), 'utf8');
const ARCHIVE = readFileSync(resolve(PUB, FALLBACK_ARCHIVE.path));

let checks = 0;
function check(condition, message) { assert.ok(condition, message); checks++; }
function equal(actual, expected, message) { assert.equal(actual, expected, message); checks++; }
function near(actual, expected, tolerance, message) { assert.ok(Math.abs(actual - expected) <= tolerance, `${message}: ${actual} versus ${expected}, tolerance ${tolerance}`); checks++; }
function refuses(code, fn) {
  let caught = null;
  try { fn(); } catch (error) { caught = error; }
  check(caught instanceof Refusal, `${code} case must throw Refusal, got ${caught && caught.name}: ${caught && caught.message}`);
  equal(caught.code, code, `${code} case must name its refusal code`);
  // A refusal has to say what was wrong with the thing in front of it, not merely that
  // something was. This is a floor, not a proof of clarity: it catches bare codes.
  const informative = /(byte|file|pixel|group|sample|reference|residual|crop|dimension|precision|IHDR|IEND|marker|compatibility|expected|length|hash|SHA-256|window|level|correlation|archive|scale|shift|type|depth|palette|filter|scanline|DEFLATE|zlib|octal|name|identical|count|plane|energy|cancelled)/i;
  check(informative.test(caught.message) && /\d/.test(caught.message), `${code} refusal must explain what failed and name a number, got: ${caught.message}`);
  return caught;
}
async function refusesAsync(code, fn) {
  let caught = null;
  try { await fn(); } catch (error) { caught = error; }
  check(caught instanceof Refusal, `${code} case must throw Refusal, got ${caught && caught.name}: ${caught && caught.message}`);
  equal(caught.code, code, `${code} case must name its refusal code`);
  return caught;
}
const digest = plane => createHash('sha256').update(Buffer.from(plane.buffer, plane.byteOffset, plane.byteLength)).digest('hex');

// ---------------------------------------------------------------- 1. the shipped specimen

console.log('the-camera-in-the-noise: opening the shipped specimen');
check(!existsSync(resolve(PUB, 'fallback-archive.mjs')), 'the base64 copy of the archive is gone; the page carries the gzip bytes once');
equal(ARCHIVE.length, FALLBACK_ARCHIVE.bytes, 'shipped archive length equals the length pinned in prnu.mjs');
equal(sha(ARCHIVE), FALLBACK_ARCHIVE.sha256, 'shipped archive SHA-256 equals the digest pinned in prnu.mjs');
check(PAGE.includes('FALLBACK_ARCHIVE.sha256') && PAGE.includes('ARCHIVE_DIGEST'), 'the page refuses a specimen whose digest does not match the pin');
check(!PAGE.includes('FALLBACK_ARCHIVE_BASE64') && !MAKE.includes('fallback-archive.mjs'), 'no code path reintroduces the base64 duplicate');
const tar = gunzipSync(ARCHIVE), files = parseTar(tar);
equal(files.size, 63, 'tar entry count');
const manifest = JSON.parse(new TextDecoder().decode(files.get('manifest.json')));
equal(manifest.licence, 'CC0-1.0', 'fallback licence');
equal(manifest.crop.storedWidth, FALLBACK_SIZE, 'fallback stored width');
equal(manifest.crop.storedHeight, FALLBACK_SIZE, 'fallback stored height');
equal(manifest.crop.analysisSize, CROP_SIZE, 'analysis crop size');
equal(manifest.crop.origin[0], (FALLBACK_SIZE - CROP_SIZE) / 2, 'analysis crop x is the centered origin');
equal(manifest.crop.origin[1], (FALLBACK_SIZE - CROP_SIZE) / 2, 'analysis crop y is the centered origin');
equal(manifest.nullShifts.length, NULL_SHIFTS.length, 'manifest null-shift count equals the preregistered list');
equal(new Set(manifest.nullShifts.map(x => x.join(','))).size, NULL_SHIFTS.length, 'manifest null shifts unique');
check(manifest.nullShifts.every(([x, y]) => Math.hypot(x, y) >= 17), 'all preregistered shifts have magnitude at least 17');
check(manifest.provenance.includes('not photographs'), 'manifest refuses physical-camera provenance');
check(new TextDecoder().decode(files.get('LICENSE.txt')).includes('CC0 1.0'), 'archive carries CC0 text');
for (const [name, expected] of Object.entries(manifest.files)) {
  check(files.has(name), `archive contains ${name}`);
  equal(files.get(name).length, expected.bytes, `${name} byte count`);
  equal(sha(files.get(name)), expected.sha256, `${name} SHA-256`);
}
const mutated = Uint8Array.from(files.get('camera-a/train/a01.png'));
mutated[mutated.length - 20] ^= 1;
check(sha(mutated) !== manifest.files['camera-a/train/a01.png'].sha256, 'one-byte archive mutation fails the independent hash check');

console.log('the-camera-in-the-noise: decoding all 60 PNG files');
const decoded = new Map();
for (const name of Object.keys(manifest.files)) {
  const image = decodeStoredGrayPNG(files.get(name));
  equal(image.meta.width, FALLBACK_SIZE, `${name} decoded width`);
  equal(image.meta.height, FALLBACK_SIZE, `${name} decoded height`);
  decoded.set(name, image.plane);
}
const trainNames = [...decoded.keys()].filter(x => x.includes('/train/')).sort();
const heldName = [...decoded.keys()].find(x => x.includes('/heldout/'));
const controlNames = [...decoded.keys()].filter(x => x.includes('/control/')).sort();
equal(trainNames.length, MAX_TRAINING, 'training frame count equals the reference size the page claims');
equal(controlNames.length, 8, 'control frame count');
check(Boolean(heldName), 'held-out frame present');
equal(Object.keys(manifest.files).filter(x => x.endsWith('.png')).length, trainNames.length + controlNames.length + 1, 'every archived PNG is either training, control, or the held-out frame');

// ---------------------------------------------------------------- 2. the residual rule itself

console.log('the-camera-in-the-noise: checking the residual rule against a second implementation');
function fixturePlane(size = 64, seed = 20260809) {
  const out = new Float32Array(size * size);
  let s = seed >>> 0;
  for (let i = 0; i < out.length; i++) { s = (Math.imul(s, 1103515245) + 12345) >>> 0; out[i] = 32 + 176 * ((s >>> 8) / 16777216); }
  return out;
}
const fixture = fixturePlane();
equal(digest(fixture), '50a6a7f659a1e656f8adbeefff9e92c89c7a2b1a50898327dc3d6e3594b42a51', 'the frozen test fixture is the one these expectations were taken from');
for (const n of [256, 128, 64, 32, 16, 8]) {
  check(orthogonalityError(analysisMatrix(n)) < 1e-11, `the 8-tap analysis pair is orthogonal at length ${n}`);
}
const fixtureResidual = residual(fixture, 64);
const fixtureOracle = oracleResidual(fixture, 64);
check(maxAbsDifference(fixtureResidual, fixtureOracle) < 1e-9, `the page's residual equals a naive independent implementation on the fixture, worst element ${maxAbsDifference(fixtureResidual, fixtureOracle)}`);
const heldCropForOracle = cropPlane(decoded.get(heldName), FALLBACK_SIZE, FALLBACK_SIZE).plane;
const shippedOracle = oracleResidual(heldCropForOracle, CROP_SIZE);
const shippedResidual = residual(heldCropForOracle);
check(maxAbsDifference(shippedResidual, shippedOracle) < 1e-9, `the page's residual equals the independent implementation on the shipped held-out crop, worst element ${maxAbsDifference(shippedResidual, shippedOracle)}`);
// The oracle is only worth having if it can tell a wrong rule from the right one. This is the
// exact substitution the audit made, and it must not survive the comparison above.
const substituted = substituteRule(fixture, 64);
check(maxAbsDifference(substituted, fixtureOracle) > 1, `the independent implementation separates the stated rule from the audit's substitute by ${maxAbsDifference(substituted, fixtureOracle).toFixed(3)}`);
let residualEnergy = 0;
for (const v of fixtureResidual) residualEnergy += v * v;
check(Math.sqrt(residualEnergy / fixtureResidual.length) > 0.1, 'the residual on the fixture is not the zero array, so the comparison above has content');
equal(digest(fixtureResidual), '58ea5a0c94f58d402cdd4b1e14afdec425d2e3956b554bbc14a4f0a16bd944bd', 'frozen digest of the residual on the fixture');
equal(digest(shippedResidual), '161199a0904f0d5ecabaae89df2bbab03085fc946036c5d0babb7533045e3e4b', 'frozen digest of the residual on the shipped held-out crop');
const denoised = denoise(fixture, 64);
let denoiseDelta = 0;
for (let i = 0; i < fixture.length; i++) denoiseDelta = Math.max(denoiseDelta, Math.abs(fixture[i] - denoised[i]));
check(denoiseDelta > 0.5, 'the denoiser actually removes something, so W = I - F(I) is not I minus I');

// ---------------------------------------------------------------- 3. the shipped anchor

console.log('the-camera-in-the-noise: recomputing the live anchor through the shared analysis');
const started = performance.now();
const sample = name => ({ name, sha256: manifest.files[name].sha256, width: FALLBACK_SIZE, height: FALLBACK_SIZE, plane: decoded.get(name) });
const anchor = await runAnalysis({
  training: trainNames.map(sample),
  heldout: sample(heldName),
  controls: controlNames.map(sample)
});
const result = anchor.result;
const byId = Object.fromEntries(result.checks.map(c => [c.id, c]));
check(PAGE.includes('data-checks') && WORKER.includes('runAnalysis'), 'the panel the reader sees is produced by the function checked here');
equal(result.checks.length, 7, 'the check panel has seven lines');
equal(result.checksNotRun, 0, 'every check ran on the shipped specimen');
equal(result.checksPassed, result.checksRun, 'every check that ran passed on the shipped specimen');
check(result.anchorPass, 'the shipped anchor unlocks the reader controls');
check(result.heldScore > Math.max(...result.controlScores.map(x => x.score)), `held-out score ${result.heldScore} exceeds all different-source scores`);
check(result.heldScore > result.maxShift, `held-out score ${result.heldScore} exceeds all shifted scores`);
equal(result.rank, 1, 'held-out visible rank');
equal(result.population, 1 + controlNames.length + NULL_SHIFTS.length, 'visible comparator population');
equal(result.distinctCrops, trainNames.length + controlNames.length + 1, 'every decoded crop was pixel-distinct');
// Frozen observations of a byte-pinned specimen. Not tolerances tuned to make a claim pass:
// if the residual rule, the ordering, the crop origin, or the specimen changes, these move.
near(result.heldScore, 0.754144407, 1e-8, 'frozen held-out correlation for the pinned specimen');
near(result.maxControl, 0.077927320, 1e-8, 'frozen different-source maximum');
near(result.maxShift, 0.065333878, 1e-8, 'frozen shifted maximum');
near(result.sceneMax, 0.326686591, 1e-8, 'frozen closest scene correlation');
check(result.sceneMax < SCENE_LIMIT, `the shipped held-out frame is not a near-duplicate of any training frame, ${result.sceneMax} against ${SCENE_LIMIT}`);
const transform = Object.fromEntries(result.transforms.map(x => [`${x.kind}${x.value}`, x.score]));
check(transform.crop1 < result.heldScore, 'one-pixel native crop lowers zero-lag score');
check(transform.crop8 < result.heldScore, 'eight-pixel native crop lowers zero-lag score');
check(transform['scale0.98'] < result.heldScore, '0.98 scale lowers zero-lag score');
check(transform['scale0.95'] < result.heldScore, '0.95 scale lowers zero-lag score');
check(transform['scale0.9'] < result.heldScore, '0.90 scale lowers zero-lag score');
near(transform.crop1, -0.063276849, 1e-8, 'frozen one-pixel crop score');
near(transform['scale0.9'], 0.416893169, 1e-8, 'frozen 0.90 scale score');

const ref = anchor.kept.ref, heldResidual = anchor.kept.heldResidual, heldCrop = anchor.kept.heldCrop;
const crop1Plane = residual(cropPlane(decoded.get(heldName), FALLBACK_SIZE, FALLBACK_SIZE, CROP_SIZE, 1, 0).plane);
const cropSurface = shiftSurface(ref, crop1Plane, CROP_SIZE, SHIFT_RANGE);
check(Math.abs(cropSurface.peak.dx) === 1 && cropSurface.peak.dy === 0, `crop search recovers one-pixel translation at ${cropSurface.peak.dx},${cropSurface.peak.dy}`);
check(cropSurface.peak.score > transform.crop1, 'crop search raises the damaged zero-lag score');
check(Number.isFinite(cropSurface.pce), 'displayed crop-search PCE is finite');
const scale95 = residual(scaleAndRestore(heldCrop, CROP_SIZE, 0.95));
const scaleSteps = Math.round((SCALE_SEARCH.to - SCALE_SEARCH.from) / SCALE_SEARCH.step);
const scaleRows = [];
for (let i = 0; i <= scaleSteps; i++) {
  const scale = SCALE_SEARCH.from + i * SCALE_SEARCH.step;
  scaleRows.push({ scale, score: centeredNCC(scale95, scaleAndRestore(ref, CROP_SIZE, scale)) });
}
const scaleBest = scaleRows.reduce((a, b) => (b.score > a.score ? b : a), scaleRows[0]);
check(Math.abs(scaleBest.scale - 0.95) <= 0.01, `coarse scale search peaks near applied 0.95 at ${scaleBest.scale}`);

equal(result.curve.map(x => x.n).join(','), CURVE_POINTS.join(','), 'the displayed N curve is the module list, not a literal repeated here');
check(result.curve.every(row => Number.isFinite(row.meanScore) && Number.isFinite(row.mleScore)), 'all displayed estimator scores finite');
const curveEnd = result.curve[result.curve.length - 1];
near(curveEnd.meanScore, result.heldScore, 1e-12, 'the last curve point is the headline score, so the two cannot disagree');
const khat = mlePattern(anchor.kept.trainResiduals, anchor.kept.trainCrops);
near(centeredNCC(heldResidual, predictResidual(khat, heldCrop)), curveEnd.mleScore, 1e-12, 'the displayed intensity-weighted comparator recomputes');
const waveletImpulse = new Float32Array(CROP_SIZE * CROP_SIZE);
waveletImpulse[(CROP_SIZE >> 1) * CROP_SIZE + (CROP_SIZE >> 1)] = 1;
const waveletError = reconstructionError(waveletImpulse);
check(waveletError < 1e-10, `four-level wavelet reconstruction error ${waveletError} is below 1e-10`);
equal(DB4.length, 8, 'displayed analysis filter has eight taps');
near(DB4.reduce((s, x) => s + x * x, 0), 1, 1e-12, 'Daubechies filter energy');
equal(WINDOWS.join(','), '3,5,7,9', 'displayed local windows');
equal(SIGMA0, 5, 'displayed sigma0');
equal(LEVELS, 4, 'displayed decomposition levels');

// ---------------------------------------------------------------- 4. can each check go red

console.log('the-camera-in-the-noise: forcing every check line red');
const gain = { c: gainField(0xc0ffee), d: gainField(0xd0d0d0) };
const frames = { c: [], d: [] };
for (let i = 1; i <= 60; i++) frames.c.push(frame(gain.c, 0x11110000, i));
for (let i = 1; i <= 12; i++) frames.d.push(frame(gain.d, 0x22220000, i));
const asSample = (pixels, name) => ({ name, sha256: sha(pixels), width: STORED, height: STORED, plane: Float32Array.from(pixels) });
const cSamples = frames.c.map((p, i) => asSample(p, `c${String(i + 1).padStart(2, '0')}.png`));
const dSamples = frames.d.map((p, i) => asSample(p, `d${String(i + 1).padStart(2, '0')}.png`));

const wrongHeldout = await runAnalysis({
  training: cSamples.slice(0, MAX_TRAINING),
  heldout: dSamples[0],
  controls: dSamples.slice(1, 9)
});
check(!wrongHeldout.result.anchorPass, 'a held-out frame from a different source does not pass the panel');
check(wrongHeldout.result.checksPassed < wrongHeldout.result.checksRun, `${wrongHeldout.result.checksRun - wrongHeldout.result.checksPassed} check lines go red when the held-out frame is from the wrong source`);
const wrongById = Object.fromEntries(wrongHeldout.result.checks.map(c => [c.id, c]));
check(wrongById.control.state === 'fail' || wrongById.shifts.state === 'fail', 'the control or shift line is the one that catches a wrong held-out frame');
check(wrongHeldout.result.rank > 1, `the wrong held-out frame does not rank first, it ranks ${wrongHeldout.result.rank} of ${wrongHeldout.result.population}`);

const underpowered = await runAnalysis({ training: cSamples.slice(0, 8), heldout: cSamples[8] });
equal(underpowered.result.checks.find(c => c.id === 'n').state, 'fail', 'a reference below the printed recommendation fails the N line');
equal(underpowered.result.checks.find(c => c.id === 'control').state, 'not-run', 'with no control group the control line reads NOT RUN');
equal(underpowered.result.checksNotRun, 1, 'the not-run line is counted apart from the passes');
check(!underpowered.result.anchorPass, 'a run with an unsupplied control cannot present itself as fully checked');
check(underpowered.result.curve.map(x => x.n).join(',') === '2,4,8', 'the curve stops at the training count actually used');

// Changed inside the analysis crop on purpose: a change outside it leaves the decoded pixels
// identical, and that case is caught one rule earlier, by DUPLICATE_PIXELS.
const nearDuplicate = Uint8Array.from(frames.c[0]);
for (let k = 0; k < 5; k++) nearDuplicate[(150 + k) * STORED + 150] ^= 1;
const outsideCropOnly = Uint8Array.from(frames.c[0]);
outsideCropOnly[0] ^= 3;
await refusesAsync('DUPLICATE_PIXELS', () => runAnalysis({
  training: cSamples.slice(0, 4),
  heldout: asSample(outsideCropOnly, 'changed-outside-the-crop.png')
}));
const nearRun = await runAnalysis({
  training: cSamples.slice(0, MAX_TRAINING),
  heldout: asSample(nearDuplicate, 'held-out-copy.png')
});
const nearScene = nearRun.result.checks.find(c => c.id === 'scene');
equal(nearScene.state, 'fail', 'a held-out frame that is a near copy of a training frame fails the scene line');
check(nearRun.result.sceneMax > 0.999, `the near copy is caught at scene correlation ${nearRun.result.sceneMax}`);
check(nearRun.result.checks.find(c => c.id === 'shifts').state === 'pass', 'the shift null does not catch it, which is why the scene line exists');

// ---------------------------------------------------------------- 5. the audit's specimen

console.log('the-camera-in-the-noise: rerunning the audit that produced a fully green result');
const oneFile = grayPNG(frames.c[0]);
const copies = [];
for (let i = 0; i < 52; i++) copies.push({ name: `copy-${String(i + 1).padStart(2, '0')}.png`, bytes: oneFile });
const readerItems = list => list.map(x => ({ name: x.name, sha256: sha(x.bytes), meta: inspectImage(x.bytes, x.name), bytes: x.bytes }));
const copyItems = readerItems(copies);
equal(new Set(copyItems.map(x => compatibilityKey(x.meta))).size, 1, 'the 52 copies form one compatibility group, as they did for the audit');
validateGroup(copyItems, MIN_GROUP);
checks++;
const duplicateRefusal = refuses('DUPLICATE_FILE', () => selectMembership(copyItems));
check(/same SHA-256/.test(duplicateRefusal.message), 'the duplicate refusal names the reason');

// Same pixels, different bytes: the file hash no longer catches it, so the pixel rule must.
const splitFile = grayPNG(frames.c[0], STORED, true);
check(sha(splitFile) !== sha(oneFile), 'the split-IDAT encoding is a different file');
check(digest(decodeStoredGrayPNG(splitFile).plane) === digest(decodeStoredGrayPNG(oneFile).plane), 'and it decodes to exactly the same pixels');
const disguised = [{ name: 'original.png', bytes: oneFile }, { name: 'disguised.png', bytes: splitFile }];
for (let i = 2; i < 6; i++) disguised.push({ name: `other-${i}.png`, bytes: grayPNG(frames.c[i]) });
const disguisedItems = readerItems(disguised);
const disguisedMembership = selectMembership(disguisedItems);
checks++;
const toSample = item => {
  const image = decodeStoredGrayPNG(item.bytes);
  return { name: item.name, sha256: item.sha256, width: image.meta.width, height: image.meta.height, plane: image.plane };
};
await refusesAsync('DUPLICATE_PIXELS', () => runAnalysis({
  training: disguisedMembership.training.map(toSample),
  heldout: toSample(disguisedMembership.heldout)
}));

// ---------------------------------------------------------------- 6. a malformed specimen

console.log('the-camera-in-the-noise: a specimen with malformed members');
const malformed = [
  { name: 'truncated.png', bytes: PNG_SIGNATURE.slice(0, 5), code: 'PNG_TRUNCATED_SIGNATURE' },
  { name: 'palette.png', bytes: ihdrPNG({ colorType: 3 }), code: 'PNG_UNSUPPORTED_COLOR' },
  { name: 'sixteen-bit.png', bytes: ihdrPNG({ depth: 16 }), code: 'PNG_UNSUPPORTED_DEPTH' },
  { name: 'zero.png', bytes: ihdrPNG({ width: 0 }), code: 'PNG_ZERO_SIZE' },
  { name: 'lying.jpg', bytes: Uint8Array.of(0xff, 0xd8, 0xff, 0xe0, 0x01, 0x00, 1, 2, 3), code: 'JPEG_LYING_LENGTH' },
  { name: 'notes.pdf', bytes: Uint8Array.of(0x25, 0x50, 0x44, 0x46, 0x2d, 0x31), code: 'UNSUPPORTED_MAGIC' }
];
const mixedSpecimen = [];
for (let i = 0; i < 48; i++) mixedSpecimen.push({ name: `m${String(i + 1).padStart(2, '0')}.png`, bytes: grayPNG(frames.c[i]) });
const accepted = [], refused = [];
for (const entry of [...mixedSpecimen, ...malformed]) {
  try {
    const meta = inspectImage(entry.bytes, entry.name);
    accepted.push({ name: entry.name, sha256: sha(entry.bytes), meta, bytes: entry.bytes });
  } catch (error) {
    refused.push({ name: entry.name, code: error.code, message: error.message });
  }
}
equal(refused.length, malformed.length, 'every malformed member is refused at the audit, before any score');
for (const bad of malformed) {
  const seen = refused.find(x => x.name === bad.name);
  equal(seen.code, bad.code, `${bad.name} is refused as ${bad.code}`);
}
equal(accepted.length, 48, 'the readable members survive the malformed ones');
const mixedMembership = selectMembership(accepted);
equal(mixedMembership.training.length, 47, 'a group short of the recommendation still runs, with fewer training files');
const mixedRun = await runAnalysis({
  training: mixedMembership.training.map(toSample),
  heldout: toSample(mixedMembership.heldout)
});
equal(mixedRun.result.checks.find(c => c.id === 'n').state, 'fail', 'and it says so on the N line rather than quietly using 47');
check(mixedRun.result.checks.find(c => c.id === 'shifts').state === 'pass', 'while the shift null still runs on what remains');
check(mixedRun.result.heldScore > mixedRun.result.maxShift, `the malformed-member specimen still scores ${mixedRun.result.heldScore.toFixed(6)} against a shifted maximum of ${mixedRun.result.maxShift.toFixed(6)}`);

// ---------------------------------------------------------------- 7. an unseen clean specimen

console.log('the-camera-in-the-noise: an unseen specimen, through the reader path');
const unseen = [];
for (let i = 0; i < 52; i++) unseen.push({ name: `u${String(i + 1).padStart(2, '0')}.png`, bytes: grayPNG(frames.c[i]) });
const unseenControls = [];
for (let i = 0; i < 8; i++) unseenControls.push({ name: `v${String(i + 1).padStart(2, '0')}.png`, bytes: grayPNG(frames.d[i]) });
const unseenItems = readerItems(unseen);
const unseenMembership = selectMembership(unseenItems);
equal(unseenMembership.training.length, MAX_TRAINING, 'the unseen specimen fills the reference');
equal(unseenMembership.heldout.name, unseenItems.slice().sort((a, b) => a.sha256.localeCompare(b.sha256))[MAX_TRAINING].name, 'the held-out position is the hash order, fixed before decode');
const unseenRun = await runAnalysis({
  training: unseenMembership.training.map(toSample),
  heldout: toSample(unseenMembership.heldout),
  controls: readerItems(unseenControls).map(toSample)
});
check(unseenRun.result.anchorPass, `a specimen this page has never seen passes all seven lines, held-out ${unseenRun.result.heldScore.toFixed(6)} against control maximum ${unseenRun.result.maxControl.toFixed(6)} and shifted maximum ${unseenRun.result.maxShift.toFixed(6)}`);
equal(unseenRun.result.checksNotRun, 0, 'with a control group supplied, nothing reads NOT RUN');
equal(unseenRun.result.rank, 1, 'and its held-out frame ranks first among visible comparators');
check(nearRun.result.heldScore > unseenRun.result.heldScore, `the near copy scored ${nearRun.result.heldScore.toFixed(6)}, higher than the genuine held-out frame's ${unseenRun.result.heldScore.toFixed(6)}, which is exactly why it must not pass quietly`);

// ---------------------------------------------------------------- 8. every refusal path

console.log('the-camera-in-the-noise: forcing every refusal the parsers name');
const jpegCases = [
  ['JPEG_TRUNCATED_SOI', Uint8Array.of(0xff)],
  ['JPEG_BAD_MAGIC', Uint8Array.of(0xff, 0xd9, 0, 0)],
  ['JPEG_EXPECTED_MARKER', Uint8Array.of(0xff, 0xd8, 0x00, 0x11, 0x22)],
  ['JPEG_TRUNCATED_MARKER', Uint8Array.of(0xff, 0xd8, 0xff)],
  ['JPEG_TRUNCATED_LENGTH', Uint8Array.of(0xff, 0xd8, 0xff, 0xe0, 0)],
  ['JPEG_BAD_LENGTH', Uint8Array.of(0xff, 0xd8, 0xff, 0xe0, 0x00, 0x01)],
  ['JPEG_LYING_LENGTH', Uint8Array.of(0xff, 0xd8, 0xff, 0xe0, 0x01, 0x00, 1, 2, 3)],
  ['JPEG_SHORT_SOF', Uint8Array.of(0xff, 0xd8, 0xff, 0xc0, 0x00, 0x07, 8, 0, 16, 0, 16)],
  ['JPEG_NO_SOF', Uint8Array.of(0xff, 0xd8, 0xff, 0xd9)],
  ['JPEG_UNSUPPORTED_PRECISION', Uint8Array.of(0xff, 0xd8, 0xff, 0xc0, 0, 8, 12, 0, 16, 0, 16, 0, 0xff, 0xd9)],
  ['JPEG_ZERO_SIZE', Uint8Array.of(0xff, 0xd8, 0xff, 0xc0, 0x00, 0x08, 8, 0, 16, 0, 0, 0)]
];
for (const [code, bytes] of jpegCases) refuses(code, () => parseJPEG(bytes));
const sosLying = Uint8Array.of(0xff, 0xd8, 0xff, 0xc0, 0x00, 0x08, 8, 0, 16, 0, 16, 0, 0xff, 0xda, 0x01, 0x00, 1);
refuses('JPEG_LYING_LENGTH', () => parseJPEG(sosLying));

const pngCases = [
  ['PNG_TRUNCATED_SIGNATURE', Uint8Array.of(137, 80, 78)],
  ['PNG_BAD_MAGIC', Uint8Array.of(137, 80, 78, 70, 13, 10, 26, 10)],
  ['PNG_TRUNCATED_CHUNK', concat([PNG_SIGNATURE, Uint8Array.of(0, 0, 0, 1)])],
  ['PNG_LYING_LENGTH', Uint8Array.of(137, 80, 78, 71, 13, 10, 26, 10, 0, 0, 1, 0, 73, 72, 68, 82, 0, 0)],
  ['PNG_BAD_IHDR', concat([PNG_SIGNATURE, chunk('IHDR', new Uint8Array(12))])],
  ['PNG_NO_IHDR', concat([PNG_SIGNATURE, chunk('IEND', new Uint8Array())])],
  ['PNG_ZERO_SIZE', ihdrPNG({ width: 0 })],
  ['PNG_UNSUPPORTED_DEPTH', ihdrPNG({ depth: 16 })],
  ['PNG_UNSUPPORTED_COLOR', ihdrPNG({ colorType: 3 })]
];
for (const [code, bytes] of pngCases) refuses(code, () => parsePNG(bytes));
const firstPng = files.get('camera-a/train/a01.png');
refuses('PNG_NO_IEND', () => parsePNG(firstPng.slice(0, firstPng.length - 12)));

console.log('the-camera-in-the-noise: forcing every refusal the fallback decoder names');
refuses('PNG_FALLBACK_FORMAT', () => decodeStoredGrayPNG(idatPNG(storedZlib(new Uint8Array(16)), { width: 4, height: 4, colorType: 2 })));
refuses('PNG_ZLIB_SHORT', () => decodeStoredGrayPNG(idatPNG(Uint8Array.of(0x78, 0x01, 0), { width: 4, height: 4 })));
refuses('PNG_DEFLATE_TRUNCATED', () => decodeStoredGrayPNG(idatPNG(Uint8Array.of(0x78, 0x01, 1, 2, 3, 4), { width: 4, height: 4 })));
refuses('PNG_DEFLATE_UNSUPPORTED', () => decodeStoredGrayPNG(idatPNG(Uint8Array.of(0x78, 0x01, 0x03, 0, 0, 0, 0, 0, 0, 0, 0), { width: 4, height: 4 })));
refuses('PNG_DEFLATE_LENGTH', () => decodeStoredGrayPNG(idatPNG(Uint8Array.of(0x78, 0x01, 0x01, 4, 0, 4, 0, 1, 2, 3, 4, 0, 0, 0, 0), { width: 4, height: 4 })));
refuses('PNG_DEFLATE_LYING_LENGTH', () => decodeStoredGrayPNG(idatPNG(Uint8Array.of(0x78, 0x01, 0x01, 40, 0, 215, 255, 1, 2, 3, 4, 0, 0, 0, 0), { width: 4, height: 4 })));
refuses('PNG_SCANLINE_LENGTH', () => decodeStoredGrayPNG(idatPNG(storedZlib(new Uint8Array(8)), { width: 4, height: 4 })));
const wrongFilter = new Uint8Array(20);
for (let y = 0; y < 4; y++) wrongFilter[y * 5] = y === 2 ? 3 : 0;
refuses('PNG_FILTER_UNSUPPORTED', () => decodeStoredGrayPNG(idatPNG(storedZlib(wrongFilter), { width: 4, height: 4 })));

console.log('the-camera-in-the-noise: forcing every refusal the instrument names');
refuses('UNSUPPORTED_MAGIC', () => inspectImage(Uint8Array.of(0x25, 0x50, 0x44, 0x46), 'probe.pdf'));
refuses('UNSUPPORTED_MAGIC', () => inspectImage(new Uint8Array(0), 'empty.bin'));
const meta = (over = {}) => ({ type: 'png', width: 288, height: 288, orientation: 1, make: '', model: '', ...over });
const item = (name, hash, over) => ({ name, sha256: hash, meta: meta(over) });
refuses('GROUP_TOO_SMALL', () => validateGroup([item('one', 'a'.repeat(64))], MIN_GROUP));
refuses('GROUP_MIXED', () => validateGroup([
  item('a', 'a'.repeat(64)), item('b', 'b'.repeat(64), { type: 'jpeg' }),
  item('c', 'c'.repeat(64)), item('d', 'd'.repeat(64))
], MIN_GROUP));
refuses('IMAGE_TOO_SMALL', () => validateGroup([
  item('a', 'a'.repeat(64), { width: 100, height: 100 }), item('b', 'b'.repeat(64), { width: 100, height: 100 }),
  item('c', 'c'.repeat(64), { width: 100, height: 100 }), item('d', 'd'.repeat(64), { width: 100, height: 100 })
], MIN_GROUP));
refuses('GROUP_TOO_SMALL', () => selectMembership([item('a', 'a'.repeat(64))]));
refuses('MEMBER_NO_HASH', () => selectMembership([item('a'), item('b'), item('c'), item('d')]));
refuses('CROP_OUTSIDE', () => cropPlane(new Float32Array(256 * 256), 256, 256, 256, 1, 0));
refuses('PLANE_LENGTH', () => cropPlane(new Float32Array(10), 256, 256));
refuses('DENOISE_SIZE', () => denoise(new Float32Array(10), 10));
refuses('DENOISE_LEVELS', () => denoise(new Float32Array(4), 2));
refuses('NCC_LENGTH', () => centeredNCC(new Float32Array(2), new Float32Array(3)));
refuses('NCC_ZERO_NORM', () => centeredNCC(new Float32Array(4).fill(3), new Float32Array(4).fill(3)));
refuses('REFERENCE_EMPTY', () => referenceMean([]));
refuses('REFERENCE_LENGTH', () => referenceMean([new Float32Array(4), new Float32Array(5)]));
refuses('MLE_INPUT', () => mlePattern([], []));
refuses('SHIFT_SIZE', () => shiftedNCC(new Float32Array(4), new Float32Array(4), 3, 0, 0));
refuses('SHIFT_ZERO_NORM', () => shiftedNCC(new Float32Array(4).fill(1), new Float32Array(4).fill(1), 2, 0, 0));
refuses('PCE_EMPTY', () => pce(new Float32Array(9), 3, { score: 0, dx: 0, dy: 0 }, 1, PCE_HALF_NEIGHBOURHOOD));
refuses('TAR_EMPTY', () => parseTar(new Uint8Array(512)));
const namelessTar = new Uint8Array(1024);
namelessTar[124] = 0x30;
refuses('TAR_EMPTY_NAME', () => parseTar(namelessTar));
refuses('TAR_BAD_SIZE', () => {
  const b = Uint8Array.from(tar);
  new TextEncoder().encode('9999abc\0\0\0\0\0').forEach((v, i) => { b[124 + i] = v; });
  parseTar(b);
});
refuses('TAR_LYING_SIZE', () => {
  const b = Uint8Array.from(tar);
  new TextEncoder().encode('77777777777\0').forEach((v, i) => { b[124 + i] = v; });
  parseTar(b);
});
await refusesAsync('NO_HELDOUT', () => runAnalysis({ training: cSamples.slice(0, 4) }));
await refusesAsync('TRAIN_TOO_SMALL', () => runAnalysis({ training: cSamples.slice(0, 2), heldout: cSamples[3] }));
await refusesAsync('CANCELLED', () => runAnalysis({
  training: cSamples.slice(0, 4), heldout: cSamples[5],
  checkCancel: () => { throw new Refusal('CANCELLED', 'Processing was cancelled after the current residual finished'); }
}));

// Refusals that only exist on the browser side. Named here so the count above is not read as
// a claim of completeness: these are exercised by the in-page self-tests and by a headless run.
const browserOnly = ['NO_GZIP_STREAM', 'NO_WORKER', 'ARCHIVE_FETCH_FAILED', 'ARCHIVE_HTTP_STATUS', 'ARCHIVE_LENGTH', 'ARCHIVE_DIGEST', 'ARCHIVE_NOT_LOCAL', 'ARCHIVE_MISSING_FILE', 'ARCHIVE_HASH_MISMATCH', 'ARCHIVE_SIZE_MISMATCH', 'ARCHIVE_NO_MANIFEST', 'ARCHIVE_NO_HELDOUT', 'ARCHIVE_MEMBERSHIP', 'MANIFEST_JSON', 'FILE_CHANGED', 'DECODE_REFUSED', 'SAMPLE_TOO_SMALL', 'FILE_CAP', 'CONTROL_SAME_GROUP', 'CONTROL_TOO_SMALL'];
for (const code of browserOnly) check(PAGE.includes(`'${code}'`), `the page defines the browser-side refusal ${code}`);
// Every refusal code in the shared module is written as CODE followed by its message, so the
// full set can be read out of the source and compared with the set this file actually forced.
const declared = new Set([...PRNU.matchAll(/'([A-Z][A-Z0-9_]{3,})',\s*[`'"]/g)].map(m => m[1]));
check(declared.size > 40, `the refusal roster read out of prnu.mjs has ${declared.size} codes, which is the number this file has to cover`);
const forced = new Set(['JPEG_TRUNCATED_SOI', 'JPEG_BAD_MAGIC', 'JPEG_EXPECTED_MARKER', 'JPEG_TRUNCATED_MARKER', 'JPEG_TRUNCATED_LENGTH', 'JPEG_BAD_LENGTH', 'JPEG_LYING_LENGTH', 'JPEG_SHORT_SOF', 'JPEG_NO_SOF', 'JPEG_UNSUPPORTED_PRECISION', 'JPEG_ZERO_SIZE', 'PNG_TRUNCATED_SIGNATURE', 'PNG_BAD_MAGIC', 'PNG_TRUNCATED_CHUNK', 'PNG_LYING_LENGTH', 'PNG_BAD_IHDR', 'PNG_NO_IHDR', 'PNG_NO_IEND', 'PNG_ZERO_SIZE', 'PNG_UNSUPPORTED_DEPTH', 'PNG_UNSUPPORTED_COLOR', 'PNG_FALLBACK_FORMAT', 'PNG_ZLIB_SHORT', 'PNG_DEFLATE_TRUNCATED', 'PNG_DEFLATE_UNSUPPORTED', 'PNG_DEFLATE_LENGTH', 'PNG_DEFLATE_LYING_LENGTH', 'PNG_SCANLINE_LENGTH', 'PNG_FILTER_UNSUPPORTED', 'UNSUPPORTED_MAGIC', 'GROUP_TOO_SMALL', 'GROUP_MIXED', 'IMAGE_TOO_SMALL', 'MEMBER_NO_HASH', 'DUPLICATE_FILE', 'DUPLICATE_PIXELS', 'CROP_OUTSIDE', 'PLANE_LENGTH', 'DENOISE_SIZE', 'DENOISE_LEVELS', 'NCC_LENGTH', 'NCC_ZERO_NORM', 'REFERENCE_EMPTY', 'REFERENCE_LENGTH', 'MLE_INPUT', 'SHIFT_SIZE', 'SHIFT_ZERO_NORM', 'PCE_EMPTY', 'TAR_EMPTY', 'TAR_EMPTY_NAME', 'TAR_BAD_SIZE', 'TAR_LYING_SIZE', 'NO_HELDOUT', 'TRAIN_TOO_SMALL']);
const unforced = [...declared].filter(code => !forced.has(code) && code !== 'PARSER_ERROR');
check(unforced.length === 0, `every refusal code declared in prnu.mjs is forced above, except PARSER_ERROR which only wraps a non-Refusal throw; unforced: ${unforced.join(', ')}`);
const stale = [...forced].filter(code => !declared.has(code));
check(stale.length === 0, `the forced list contains no codes the module no longer declares; stale: ${stale.join(', ')}`);
equal(forced.size, declared.size - 1, `this file forces ${forced.size} of the ${declared.size} declared refusals, all but PARSER_ERROR`);

// ---------------------------------------------------------------- 9. displayed constants

console.log('the-camera-in-the-noise: checking every shareable numerical claim');
equal(MAX_TRAINING, 51, 'smallest integer satisfying Np greater than 50');
equal(HISTORICAL.smallestN, MAX_TRAINING, 'the displayed recommendation and the reference size are the same number');
check(HISTORICAL.smallestN > 50 && HISTORICAL.smallestN - 1 === 50, 'N recommendation boundary is falsifiable');
equal(HISTORICAL.experimentN, 300, '2006 Experiment I reference count');
equal(HISTORICAL.unprocessed.length, 9, 'Table II unprocessed camera row count');
for (const [camera, t, frr] of HISTORICAL.unprocessed) {
  check(t > 0 && t < 0.1, `${camera} displayed threshold in source range`);
  check(frr >= 0 && frr < 1, `${camera} displayed FRR is a probability`);
}
check(PAGE.includes('((1 - frr) * 100).toFixed(6)}% <small>derived</small>'), 'the derived detection column carries the word derived beside every number');
check(INDEX.includes('<th>1 minus FRR</th>'), 'and the column is headed as a subtraction, not as a measurement');
const g2 = HISTORICAL.unprocessed.find(x => x[0] === 'Canon G2');
equal(((1 - g2[2]) * 100).toFixed(4), '99.9769', 'displayed G2 derived rate');
equal(HISTORICAL.largeScaleFingerprints, 6827, '2009 fingerprint count');
equal(HISTORICAL.largeScaleImagesPerFingerprint, 50, '2009 images per fingerprint');
equal(HISTORICAL.largeScalePceThreshold, 60, '2009 displayed PCE threshold');
near(HISTORICAL.largeScaleDR + HISTORICAL.largeScaleFRR, 100, 1e-12, '2009 DR and FRR complement');
const nikon50 = HISTORICAL.jpeg.find(x => x[0] === 'Nikon D100' && x[1] === 50);
equal(nikon50[3], 0.163, 'displayed Nikon quality 50 FRR');
equal(HISTORICAL.jpeg.length, 21, 'all controlled JPEG rows displayed');
for (const [camera, quality, t, frr] of HISTORICAL.jpeg) {
  check([90, 70, 50].includes(quality), `${camera} JPEG quality is one of the printed columns`);
  check(t > 0 && t < 0.1, `${camera} quality ${quality} threshold is in source range`);
  check(frr >= 0 && frr < 1, `${camera} quality ${quality} FRR is a probability`);
}
// Constants are read out of the implementation rather than retyped as arithmetic here.
const lumaFromPage = [...PAGE.matchAll(/plane\[j\]\s*=\s*([\d.]+)\*rgba\[i\]\+([\d.]+)\*rgba\[i\+1\]\+([\d.]+)\*rgba\[i\+2\]/g)][0];
check(Boolean(lumaFromPage), 'the luma reduction is readable in the page source');
const lumaCoefficients = lumaFromPage.slice(1).map(Number);
near(lumaCoefficients.reduce((a, b) => a + b, 0), 1, 1e-15, 'the implemented luma coefficients sum to one');
const lumaShown = /Luma is Y = ([\d.]+)R \+ ([\d.]+)G \+ ([\d.]+)B/.exec(PAGE);
equal(lumaShown.slice(1).map(Number).join(','), lumaCoefficients.join(','), 'the displayed luma coefficients are the implemented ones');
equal(cropSurface.side, 2 * SHIFT_RANGE + 1, 'the shift surface side comes from the search range the module exports');
check(PAGE.includes('plus or minus ${SHIFT_RANGE}'), 'and the page prints that range from the same constant');
const pceExplicit = pce(cropSurface.values, cropSurface.side, cropSurface.peak, cropSurface.range, PCE_HALF_NEIGHBOURHOOD);
near(cropSurface.pce, pceExplicit, 0, 'the displayed PCE uses the exported exclusion neighborhood');
check(PAGE.includes('${2 * PCE_HALF_NEIGHBOURHOOD + 1} by ${2 * PCE_HALF_NEIGHBOURHOOD + 1}'), 'and the page prints that neighborhood from the same constant');
equal(scaleRows.length, scaleSteps + 1, 'the scale-search candidate count comes from the exported sweep');
check(WORKER.includes('SCALE_SEARCH.from + i * SCALE_SEARCH.step'), 'and the worker sweeps that same range');
equal(Object.keys(manifest.files).filter(x => x.endsWith('.png')).length, 60, 'the archive really carries 60 PNG files');
check(PAGE.includes(`training.length !== ${MAX_TRAINING} || controls.length !== 8`), 'the page refuses an archive whose membership is not 51 and 8');
equal(SCENE_LIMIT, 0.95, 'the near-duplicate limit is the one the page discloses');
check(INDEX.includes('above 0.95 fails a new near-duplicate check'), 'and the page names it as a rule added after seeing data');
check(INDEX.includes('Rules that were changed after seeing data'), 'the page has a section for rules changed after seeing data');
check(INDEX.includes('fifty-two times under different names'), 'which describes the audit that caused them');

// ---------------------------------------------------------------- 10. the shareable surface

const dek = 'Bring at least four unedited, same-size photographs and this local browser lab will average their aligned noise residual, lock one file out before estimating the reference, and test crop, shift, scale, and JPEG controls without uploading a byte. The shipped anchor uses 51 training images because the 2006 paper recommends more than 50, but its fallback is openly synthetic, so a positive score is evidence of an aligned shared residual and never proof of a unique camera.';
check(INDEX.includes(`<meta name="description" content="${dek}"`), 'meta description equals verified honest dek');
check(INDEX.includes(`"description":"${dek}"`), 'JSON-LD description equals verified honest dek');
check(FRONT.includes(`dek: "${dek}"`), 'frontmatter dek equals verified honest dek');
check(FRONT.includes('plain: "Choose a run of photographs') && FRONT.includes('not proof of a unique physical camera'), 'plain field carries the concession');
check(FRONT.includes('seoTitle: "Camera Sensor Noise Test in Your Browser"'), 'search title describes a test, not identification');
check(FRONT.includes('date: 2026-08-09T00:00:00Z'), 'frontmatter has binding publication date');
check(FRONT.includes('seam: "physical"'), 'frontmatter keeps the binding seam');
check(FRONT.includes('"the specimen is yours"') && FRONT.includes('"show-the-check"'), 'frontmatter has wave and check tags');
equal((FRONT.match(/\n  - to:/g) || []).length, 4, 'frontmatter relation count');
check(INDEX.includes('<title>Camera Sensor Noise Test in Your Browser</title>'), 'HTML title matches search title');
check(INDEX.includes('positive score is evidence of an aligned shared residual and never proof of a unique camera'), 'visible dek carries the concession');
check((INDEX + PAGE).includes('Synthetic, not photographed.'), 'page names fallback substitution');
const og = /<meta property="og:description" content="([^"]+)"/.exec(INDEX)[1];
check(og.includes('A score is not a camera identity.'), 'OG description refuses identification');
check(!/break it with/i.test(og), 'OG description does not promise that a control breaks the result');
check(/probe it with|stress it with/i.test(og) && /forces no direction|may help, hurt/i.test(og), 'OG description matches the body on what the controls do');
check(INDEX.includes('Compression may suppress non-unique correlation'), 'the body still refuses a universal JPEG verdict');
check(!/>\s*(?:MATCH|NOT MATCH)\s*</i.test(INDEX) && !/['"](?:MATCH|NOT MATCH)['"]/.test(PAGE), 'shareable surface never turns a score into a match label');
check(PAGE.includes("'not-run'") && PAGE.includes("'NOT RUN'"), 'a check that did not run renders as NOT RUN, never as PASS');
check(!/pass:\s*maxControl === null/.test(WORKER + PRNU), 'no code path turns a missing control into a pass');
check(INDEX.includes('aria-describedby="anchor-comparators"') && INDEX.includes('aria-describedby="user-comparators"'), 'both scatter canvases point at a text list of every plotted value');
check(PAGE.includes('data-comparators'), 'and that list is filled with every control and shift score');

const jsonBlocks = [...INDEX.matchAll(/<script type="application\/ld\+json">([\s\S]*?)<\/script>/g)];
equal(jsonBlocks.length, 1, 'one JSON-LD block');
const article = JSON.parse(jsonBlocks[0][1]);
equal(article['@type'], 'Article', 'JSON-LD Article type');
equal(article.name, 'Camera Sensor Noise Test in Your Browser', 'JSON-LD SEO name');
equal(article.headline, 'The Camera in the Noise', 'JSON-LD headline');
equal(article.datePublished, '2026-08-09T00:00:00Z', 'JSON-LD date');
check(article.url.endsWith('/strata/the-camera-in-the-noise/'), 'JSON-LD canonical URL');
// The site-wide chrome generators (site-bar, way-out, plain-cards, check-placard) inject
// their own script and style blocks into every shipped page, so an assertion that pins the
// exact script inventory or the exact bytes before </body> fails on a page that is
// perfectly correct. Assert the property being claimed instead of an incidental order.
check(/<script type="module" src="\.\/page\.mjs"><\/script>/.test(INDEX), 'the page module is loaded and its tag is closed');
check(/<\/body>\s*<\/html>\s*$/.test(INDEX.trimEnd() + '\n'), 'document ends with a closed body and html');

// The specimen is now fetched, so the policy has to say so and the ledger has to explain it.
check(INDEX.includes("connect-src 'self'"), 'CSP allows exactly one connection target, this origin');
check(!INDEX.includes("connect-src 'none'"), 'and the page no longer claims a policy it does not have');
check(INDEX.includes("connect-src 'self'</span>, so the only address this code may open a connection to is this origin"), 'the ledger explains the change in words, not only in a header');
check(PAGE.includes('crossOriginAttempts') && INDEX.includes('Cross-origin attempts by this code'), 'the ledger counts cross-origin attempts separately from the one same-origin fetch');
check(!/\b(?:sendBeacon|XMLHttpRequest|WebSocket)\s*\(/.test(PAGE + WORKER + PRNU), 'page code has no beacon, XHR, or socket');
const fetchCalls = [...PAGE.matchAll(/\bfetch\s*\(/g)];
equal(fetchCalls.length, 1, 'page code makes exactly one fetch call');
check(/fetch\(url, \{ cache: 'no-store', credentials: 'omit', mode: 'same-origin' \}\)/.test(PAGE), 'and it is the same-origin, credential-free specimen request');
check(!/\bfetch\s*\(/.test(WORKER + PRNU), 'neither the worker nor the shared module opens a connection');

// Indirect runtime dependencies, which a source scan of the page alone would miss.
const dependencies = ['public/media/home-banner.js', 'public/media/plain-button.js', 'public/fonts/fonts.css'];
for (const relative of dependencies) {
  const text = readFileSync(resolve(ROOT, relative), 'utf8');
  check(!/\b(?:fetch|sendBeacon|XMLHttpRequest|WebSocket)\s*\(/.test(text), `${relative} opens no connection`);
  const external = [...text.matchAll(/https?:\/\/([^\s"'`)]+)/g)].map(m => m[1]).filter(host => !host.startsWith('artwaste.land') && !host.startsWith('www.w3.org'));
  check(external.length === 0, `${relative} references no third-party host, found ${external.join(', ')}`);
}
check(readFileSync(resolve(ROOT, 'public/media/home-banner.js'), 'utf8').includes("pb.src = '/media/plain-button.js'"), 'the banner loads the plain-button script from this origin, which is why it is checked above');
check(!/<(?:script|img|link)[^>]+(?:src|href)="https?:\/\/(?!artwaste\.land)/i.test(INDEX), 'no third-party script, image, or stylesheet request');
const ownFiles = [['index', INDEX], ['page', PAGE], ['worker', WORKER], ['prnu', PRNU], ['make-fallback', MAKE], ['frontmatter', FRONT], ['README', README],
  ['oracle', readFileSync(resolve(HERE, 'oracle.mjs'), 'utf8')],
  ['specimens', readFileSync(resolve(HERE, 'specimens.mjs'), 'utf8')],
  ['verifier', readFileSync(fileURLToPath(import.meta.url), 'utf8')]];
// Written as an escape so this file can check itself without containing the character.
const EM_DASH = String.fromCharCode(0x2014);
for (const [name, text] of ownFiles) check(!text.includes(EM_DASH), `${name} contains no em dash`);
check(INDEX.includes('@media(max-width:680px)') && INDEX.includes('overflow-x:hidden'), 'responsive overflow defenses present');
check(INDEX.includes('@media(prefers-reduced-motion:reduce)'), 'reduced-motion preference present');
check(INDEX.includes(':focus-visible'), 'visible keyboard focus present');
check(INDEX.includes('role="status"') && INDEX.includes('aria-live="polite"'), 'live status region present');
check(INDEX.includes('id="control-select"') && INDEX.includes('<label for="control-select">'), 'the different-source control group has a labelled control');

console.log(JSON.stringify({
  checks,
  archiveBytes: ARCHIVE.length,
  pageDirectoryBytes: ARCHIVE.length + INDEX.length + PAGE.length + WORKER.length + PRNU.length + MAKE.length,
  tarBytes: tar.length,
  anchorSeconds: Number(((performance.now() - started) / 1000).toFixed(3)),
  heldScore: Number(result.heldScore.toFixed(9)),
  maxControl: Number(result.maxControl.toFixed(9)),
  maxShift: Number(result.maxShift.toFixed(9)),
  sceneMax: Number(result.sceneMax.toFixed(9)),
  transforms: Object.fromEntries(Object.entries(transform).map(([k, v]) => [k, Number(v.toFixed(9))])),
  scaleSearchBest: { scale: Number(scaleBest.scale.toFixed(3)), score: Number(scaleBest.score.toFixed(9)) },
  cropSearch: { dx: cropSurface.peak.dx, dy: cropSurface.peak.dy, score: Number(cropSurface.peak.score.toFixed(9)), pce: Number(cropSurface.pce.toFixed(3)) },
  curve: result.curve.map(x => ({ n: x.n, mean: Number(x.meanScore.toFixed(9)), mle: Number(x.mleScore.toFixed(9)) })),
  waveletError,
  unseenSpecimens: {
    clean: { held: Number(unseenRun.result.heldScore.toFixed(6)), control: Number(unseenRun.result.maxControl.toFixed(6)), shift: Number(unseenRun.result.maxShift.toFixed(6)), passed: `${unseenRun.result.checksPassed} of ${unseenRun.result.checksRun}` },
    fiftyTwoCopies: 'refused DUPLICATE_FILE before decode, DUPLICATE_PIXELS after decode',
    malformedMembers: { refused: refused.length, ran: mixedRun.result.nUsed, passed: `${mixedRun.result.checksPassed} of ${mixedRun.result.checksRun}` },
    wrongSource: { held: Number(wrongHeldout.result.heldScore.toFixed(6)), rank: `${wrongHeldout.result.rank} of ${wrongHeldout.result.population}`, passed: `${wrongHeldout.result.checksPassed} of ${wrongHeldout.result.checksRun}` }
  }
}, null, 2));
console.log(`PASS ${checks} checks`);
