#!/usr/bin/env node
// research/paternity-check/verify.mjs: the checks behind /tools/paternity-check/.
//
//   node research/paternity-check/verify.mjs
//
// WHICH ASSERTIONS FAIL IF THE TOOL IS SIMPLY WRONG?
//   - "identity" re-derives PI/(k*PI+1-k) by exact pedigree enumeration in a separate
//     program (public/tools/paternity-check/checker.mjs, which imports nothing from the
//     tool) and requires the wrong k to be caught (the negative control).
//   - "forrel" compares the tool's per-locus formula with likelihood ratios computed by the
//     R package forrel, an engine this project did not write, on stored cases.
//   - "examples" pins the published sample reports: their printed combined index must sit
//     inside the product of their printed per-locus indices, read as rounding intervals.
//   - "tamper" alters one value at a time in serialised certificate text and requires the
//     kit's re-check to fail; "refusals" requires every disqualifying answer to stop the
//     relative figure.
// Fixtures are .mjs modules so this file can be published and run on its own.

import assert from 'node:assert/strict';
import { readFileSync, writeFileSync, mkdtempSync } from 'node:fs';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
import { spawnSync } from 'node:child_process';
import vm from 'node:vm';

import * as E from '../../public/tools/paternity-check/engine.mjs';
import * as N from '../../public/tools/paternity-check/numbers.mjs';
import { normalizeLocus, LINKED_PAIRS } from '../../public/tools/paternity-check/loci.mjs';
import { EXAMPLES } from '../../public/tools/paternity-check/examples.mjs';
import { EXAMPLES as ALL_EXAMPLES } from './examples.mjs';
import { FORREL_COMPACT as FORREL } from './forrel-compact.mjs';
import { parseFigure } from '../../public/tools/printed-numbers/engine-a.mjs';
import { RESULTS as BENCH } from './bench/results.mjs';
import { LAYOUTS } from './layout-fixtures.mjs';

const ROOT = new URL('../../', import.meta.url);
const CHECKER = new URL('public/tools/paternity-check/checker.mjs', ROOT);

const kitSource = readFileSync(new URL('public/_kit/certificate.js', ROOT), 'utf8');
const sandbox = { window: {} };
vm.runInContext(kitSource, vm.createContext(sandbox));
const C = sandbox.window.AW.certificate;
E.defineCertificates(C);

let passed = 0, failed = 0, n = 0;
function test(name, fn) {
  n++;
  try { fn(); passed++; console.log(`${n}. PASS ${name}`); }
  catch (e) { failed++; console.log(`${n}. FAIL ${name}\n     ${e.message.split('\n')[0]}`); }
}
const Q = N.Q;
const half = Q(1n, 2n), quarter = Q(1n, 4n), eighth = Q(1n, 8n);
const ALL_NO = { motherRelated: 'no', relativeRelatedToMother: 'no', relativeTested: 'no', theta: 'no', twin: 'no', doubleRelated: 'no' };
const R = (s) => N.exactText(s);

// ── printed figures ──────────────────────────────────────────────────────────
test('a printed index denotes the half-open interval of its last digit', () => {
  const r = N.readPrinted('1.85');
  assert.equal(R(r.lo), '1.845'); assert.equal(R(r.hi), '1.855'); assert.equal(R(r.value), '1.85');
  const t = N.readPrinted('1.7412952650');
  assert.equal(R(t.lo), '1.74129526495'); assert.equal(R(t.hi), '1.74129526505');
});
test('thousands separators, percent, exponent and superscript forms read exactly', () => {
  assert.equal(R(N.readPrinted('5,479.8022').value), '5479.8022');
  const w = N.readPrinted('99.9817545%'); assert.equal(R(w.value), '0.999817545'); assert.equal(R(w.lo), '0.9998175445');
  const e = N.readPrinted('2.70 x 10^7'); assert.equal(R(e.lo), '26950000'); assert.equal(R(e.hi), '27050000');
  assert.equal(R(N.readPrinted('2.7E+07').lo), '26500000');
  assert.equal(R(N.readPrinted('2.7 × 10⁷').hi), '27500000');
});
test('an integer with trailing zeros carries both readings', () => {
  const r = N.readPrinted('27,000,000');
  assert.ok(r.ambiguous); assert.equal(R(r.lo), '26999999.5'); assert.equal(R(r.loose.lo), '26500000'); assert.equal(R(r.loose.hi), '27500000');
});
test('figures that do not denote an interval are refused, not guessed', () => {
  for (const s of ['1,85', 'about 5', '1/2', '', 'n/a', '< 0.01']) assert.throws(() => N.readPrinted(s), undefined, s);
  assert.throws(() => N.readPrinted('> 5'));
  assert.equal(N.readPrinted('> 99.99%', { allowBound: true }).hi, null);
});
test('the printed-number rule is the printed-numbers tool\'s own rule (same intervals)', () => {
  for (const s of ['1.85', '0.896', '12', '3.6553362570']) {
    const a = parseFigure(s), b = N.readPrinted(s);
    assert.ok(N.eq(Q(a.lo.n, a.lo.d), b.lo) && N.eq(Q(a.hi.n, a.hi.d), b.hi), s);
  }
});

// ── the formula ──────────────────────────────────────────────────────────────
test('PI/(k*PI+1-k): worked values and the cap 1/k', () => {
  assert.equal(R(N.relativeRatio(N.exactDecimal('1.85'), half)), R(N.div(N.exactDecimal('3.7'), N.exactDecimal('2.85'))));
  assert.equal(R(N.relativeRatio(Q(1n), half)), '1');                  // PI = 1 is uninformative against anyone
  for (const k of [half, quarter, eighth]) {
    const big = N.relativeRatio(Q(10n ** 30n), k);
    assert.ok(N.lt(big, N.div(N.ONE, k)), 'never reaches 1/k');
    assert.ok(N.lt(N.sub(N.div(N.ONE, k), big), Q(1n, 10n ** 20n)), 'approaches 1/k');
  }
});
test('the ratio is increasing in PI, so rounding intervals map end to end', () => {
  let prev = Q(0n);
  for (const s of ['0.001', '0.2', '0.5', '1', '1.85', '7', '300']) {
    const r = N.relativeRatio(N.exactDecimal(s), half);
    assert.ok(N.lt(prev, r)); prev = r;
  }
});
test('the same combined index, two very different brother figures (computed, not quoted)', () => {
  const [a, b] = E.cpiOnlyDemo();
  assert.equal(R(a.cpi), '1048576'); assert.equal(R(b.cpi), '1000000');
  assert.ok(N.eq(a.lr, Q(4n ** 20n, 3n ** 20n)));                     // (2*2/3)^20
  assert.ok(N.eq(b.lr, Q(20n ** 6n, 11n ** 6n)));                     // (2*10/11)^6
  assert.equal(N.show(a.lr, 3), '315'); assert.equal(N.show(b.lr, 3), '36.1');
});

// ── the independent checker: identity by enumeration, with a negative control ─
test('identity: exact pedigree enumeration agrees for all eight relatives, and the wrong k is caught', () => {
  const r = spawnSync(process.execPath, [CHECKER.pathname, '--identity', '--cases', '24', '--control'], { encoding: 'utf8', timeout: 600000 });
  assert.equal(r.status, 0, r.stdout + r.stderr);
  assert.match(r.stdout, /192 of 192 enumerated likelihood ratios equal/);
  assert.match(r.stdout, /the wrong k is caught in \d+ of \d+ cases/);
  for (const name of ['full brother', 'father of the tested man', 'son of the tested man', 'half-brother', 'uncle', 'grandfather', 'nephew', 'first cousin']) assert.match(r.stdout, new RegExp(`ok\\s+${name}`));
});

// ── an engine we did not write ───────────────────────────────────────────────
test(`forrel ${FORREL.forrel} (R): the per-locus formula matches its relative likelihood ratios in ${FORREL.cases.length} cases`, () => {
  let worst = 0, count = 0, zeros = 0;
  const rels = new Set();
  for (const [relative, k, loci, total] of FORREL.cases) {
    rels.add(relative);
    let prod = 1;
    for (const [pi, theirs] of loci) {
      const mine = pi / (k * pi + 1 - k);
      // exclusion loci: PI = 0, and forrel's LR is 0 too; the formula gives exactly 0
      if (theirs === 0) { assert.equal(mine, 0, `${relative}: forrel 0, formula ${mine}`); zeros++; }
      else worst = Math.max(worst, Math.abs(mine - theirs) / Math.abs(theirs));
      prod *= mine; count++;
    }
    if (total === 0) assert.equal(prod, 0); else worst = Math.max(worst, Math.abs(prod - total) / Math.abs(total));
  }
  assert.ok(count > 2000 && rels.size >= 9, `cases ${count}, relatives ${rels.size}`);
  assert.ok(worst < 1e-9, `worst relative error ${worst}`);
  // negative control: the same comparison with k = phi (half the right value) must fail badly
  let wrong = 0;
  for (const [, k, loci] of FORREL.cases) for (const [pi, theirs] of loci) if (theirs) wrong = Math.max(wrong, Math.abs(pi / (k / 2 * pi + 1 - k / 2) - theirs) / theirs);
  assert.ok(wrong > 0.1, `the wrong k should disagree, got ${wrong}`);
});

// ── locus table ──────────────────────────────────────────────────────────────
test('Amelogenin, Y markers and X markers are never autosomal', () => {
  for (const s of ['AMEL', 'Amelogenin', 'DYS391', 'DYS576', 'Yindel']) assert.notEqual(normalizeLocus(s).kind, 'autosomal', s);
  for (const s of ['THO1', 'TH01', 'vWA', 'VWA', 'Penta D', 'D21S11', 'FGA', 'CSF1PO']) assert.equal(normalizeLocus(s).kind, 'autosomal', s);
});
test('vWA and D12S391 are a listed linked pair', () => {
  assert.ok(LINKED_PAIRS.some((p) => (p.a === 'vWA' && p.b === 'D12S391') || (p.a === 'D12S391' && p.b === 'vWA')));
});

test('the linked pairs printed on the page are exactly the locus table\'s, with the same fractions', () => {
  const html = readFileSync(new URL('public/tools/paternity-check/index.html', ROOT), 'utf8');
  const m = /<span id="linked-pairs">([^<]*)<\/span>/.exec(html);
  assert.ok(m, 'the list is on the page');
  const printed = [...m[1].matchAll(/([\w ]+?) and ([\w ]+?) \(([\d.]+)\)/g)].map((x) => [x[1].trim(), x[2].trim(), Number(x[3])]);
  assert.equal(printed.length, LINKED_PAIRS.length);
  for (const p of LINKED_PAIRS) assert.ok(printed.some(([a, b, r]) => a === p.a && b === p.b && r === p.recombinationFraction), `${p.a}-${p.b} ${p.recombinationFraction}`);
});

// ── parsing what people paste ────────────────────────────────────────────────
test('a tab-separated trio with a header row reads into the right columns', () => {
  const p = E.parseReportText('Locus\tMother\tChild\tAlleged Father\tPI\nD8S1179\t12, 13\t13, 14\t14, 15\t1.85\nTH01\t6, 9.3\t9.3, 9.3\t7, 9.3\t1.20\nCombined Paternity Index: 2.22\nProbability of Paternity: 68.94%\nPrior Probability: 0.5');
  assert.equal(p.rows.length, 2);
  assert.deepEqual([p.rows[0].mother, p.rows[0].child, p.rows[0].af, p.rows[0].pi], ['12, 13', '13, 14', '14, 15', '1.85']);
  assert.equal(p.summary.cpi, '2.22'); assert.equal(p.summary.w, '68.94%'); assert.equal(p.summary.prior, '0.5');
});
test('a single-spaced header still fixes the order of three genotype columns', () => {
  const p = E.parseReportText('Locus Child Mother Alleged Father PI\nD8S1179 13/14 12/13 14/15 1.85');
  assert.deepEqual([p.rows[0].child, p.rows[0].mother, p.rows[0].af], ['13/14', '12/13', '14/15']);
  assert.ok(!p.notes.length);
});
test('with no header, three genotype columns are read as mother, child, tested man, and the person is told', () => {
  const p = E.parseReportText('D8S1179 12/13 13/14 14/15 1.85');
  assert.deepEqual([p.rows[0].mother, p.rows[0].child, p.rows[0].af], ['12/13', '13/14', '14/15']);
  assert.ok(p.notes.some((t) => /cannot tell the mother from the tested man/.test(t)));
});
test('comma-grouped alleles separated by single spaces pair up', () => {
  const p = E.parseReportText('Penta D 9, 13 13, 13 1.42');
  assert.equal(p.rows[0].locus, 'Penta D'); assert.equal(p.rows[0].child, '9, 13'); assert.equal(p.rows[0].af, '13, 13'); assert.equal(p.rows[0].pi, '1.42');
});
test('alleles that cannot be paired are left for the person, not guessed', () => {
  const p = E.parseReportText('D8S1179 13 14 12 13 14 1.85');
  assert.ok(p.rows[0].ambiguous);
});

// The paste reader on real report layouts (layouts.md, transcribed with their whitespace).
const LAY = (name) => E.parseReportText(LAYOUTS[name]);
const cols = (r) => [r.mother, r.child, r.af, r.pi];
test('real layout, Genomia: unlabelled "Person A/B" columns read as child and tested man, with the summary lines', () => {
  const p = LAY('genomia');
  assert.deepEqual(cols(p.rows[0]), ['', '20/24', '20/21', '1.7412952650']);
  assert.deepEqual(p.summary, { cpi: '5479.8022', w: '99.9817545 %', prior: '50 %' });
  assert.ok(p.rows[0].guessedOrder && p.notes.some((n) => /usual order/.test(n)), 'the guess is declared');
});
test('real layout, DNA-VIEW: two-line header, the X and Y columns ignored, the ratio taken as the index, the prior from the parenthesis', () => {
  const p = LAY('dnaview');
  assert.deepEqual(cols(p.rows[0]), ['12 14', '12 15', '14 15', '2.47']);
  assert.deepEqual(cols(p.rows[1]), ['30 30', '30.2', '29 30.2', '32.5']);
  assert.equal(p.summary.prior, '50%');
});
test('real layout, DDC: the index before the alleles, a homozygote printed once', () => {
  const p = LAY('ddc');
  assert.deepEqual(cols(p.rows[0]), ['', '16', '15, 16', '2.02']);
  assert.deepEqual(cols(p.rows[1]), ['', '14, 19', '18, 19', '2.89']);
});
test('real layout, Validity: "DI" is the index; the empty mother column stays empty', () => {
  const p = LAY('validity');
  assert.deepEqual(cols(p.rows[0]), ['', '14, 17', '14, 18', '2.344']);
  assert.equal(p.summary.cpi, '56,730,050,000');
});
test('real layout, workshop slides: one allele per printed line, joined; the avuncular column ignored', () => {
  const p = LAY('eisenberg');
  assert.deepEqual(cols(p.rows[0]), ['12, 8', '12, 8', '12, 10', '1.52']);
  assert.deepEqual(cols(p.rows[1]), ['11, 8', '11, 8', '11, 8', '1.25']);
});
test('real layout, Goodwin 2004: row numbers stripped, one allele per column, and PI (not the brother column PI*) taken as the index', () => {
  const p = LAY('goodwin');
  assert.deepEqual(cols(p.rows[0]), ['16, 16', '16, 16', '14, 16', '2.222']);
  assert.deepEqual(cols(p.rows[1]), ['14, 17', '16, 17', '14, 16', '2.531']);
});
test('the mutation-handled locus of a linked pair is the one kept, and the swap flips it', () => {
  assert.deepEqual(E.setAsideLoci([{ locus: 'D5S818' }, { locus: 'CSF1PO', mutation: true }]), ['D5S818']);
  assert.deepEqual(E.setAsideLoci([{ locus: 'D5S818' }, { locus: 'CSF1PO' }]), ['CSF1PO']);
  assert.deepEqual(E.setAsideLoci([{ locus: 'D5S818' }, { locus: 'CSF1PO', mutation: true }], { swap: true }), ['CSF1PO']);
});

// ── genotype classes and implied frequencies ─────────────────────────────────
const G = (s) => E.parseAlleles(s);
test('duo formula classes', () => {
  assert.equal(E.classifyGenotypes(G('12,12'), null, G('12,12')).formula, '1/p');
  assert.equal(E.classifyGenotypes(G('12,12'), null, G('12,14')).formula, '1/(2p)');
  assert.equal(E.classifyGenotypes(G('12,13'), null, G('12,12')).formula, '1/(2p)');
  assert.equal(E.classifyGenotypes(G('12,13'), null, G('12,14')).formula, '1/(4p)');
  assert.equal(E.classifyGenotypes(G('12,13'), null, G('12,13')).formula, '(p+q)/(4pq)');
  assert.equal(E.classifyGenotypes(G('12,13'), null, G('14,15')).status, 'mutation');
});
test('trio formula classes, the shared heterozygote, and a maternal mismatch', () => {
  assert.equal(E.classifyGenotypes(G('13,14'), G('12,13'), G('14,14')).formula, '1/p');
  assert.equal(E.classifyGenotypes(G('13,14'), G('12,13'), G('14,15')).formula, '1/(2p)');
  assert.equal(E.classifyGenotypes(G('13,14'), G('13,14'), G('13,15')).formula, '1/(2(p+q))');
  assert.equal(E.classifyGenotypes(G('13,14'), G('13,14'), G('13,14')).formula, '1/(p+q)');
  assert.equal(E.classifyGenotypes(G('13,14'), G('12,13'), G('15,16')).status, 'mutation');
  assert.equal(E.classifyGenotypes(G('13,14'), G('10,11'), G('13,14')).status, 'mother-mismatch');
});
test('a printed index impossible under its formula is flagged (1/p cannot be below 1)', () => {
  const cls = E.classifyGenotypes(G('12,12'), null, G('12,12'));
  assert.equal(E.impliedFrequency(cls, N.readPrinted('0.80')).feasible, false);
  assert.equal(E.impliedFrequency(cls, N.readPrinted('4.00')).feasible, true);
  assert.equal(E.impliedFrequency(E.classifyGenotypes(G('12,13'), null, G('12,13')), N.readPrinted('0.9')).feasible, false);
});

// ── the analysis ─────────────────────────────────────────────────────────────
const mini = {
  kind: 'trio',
  rows: [
    { locus: 'D8S1179', mother: '12,13', child: '13,14', af: '14,15', pi: '1.85' },
    { locus: 'vWA', mother: '15,16', child: '16,17', af: '17,17', pi: '3.40' },
    { locus: 'D12S391', mother: '18,19', child: '19,20', af: '20,21', pi: '2.10' },
    { locus: 'TPOX', mother: '8,11', child: '8,9', af: '10,11', pi: '0.0020' },
    { locus: 'AMEL', mother: 'X', child: 'X,Y', af: 'X,Y', pi: '' },
    { locus: 'DYS391', mother: '', child: '10', af: '10', pi: '1.50' },
    { locus: 'D99S999', mother: '', child: '', af: '', pi: '2.00' },
  ],
  cpi: '27.0', w: '96.4%', prior: '0.5',
};
test('the relative figure uses only autosomal, recognised, unlinked rows, and names why each other row is out', () => {
  const res = E.analyse(mini, { screening: ALL_NO });
  assert.deepEqual(res.used, ['D8S1179', 'vWA', 'TPOX']);
  const out = Object.fromEntries(res.notUsed.map((x) => [x.locus, x.reason]));
  assert.match(out.AMEL, /no index|sex marker/);
  assert.match(out.DYS391, /Y-chromosome/);
  assert.match(out.D99S999, /not a locus name this tool recognises/);
  assert.deepEqual(res.unrecognised, ["D99S999"]);
  assert.ok(res.relatives[0].variants.some((v) => v.id === "with-unrecognised"), "a variant shows the figure with the unrecognised row");
  assert.match(out.D12S391, /linked to vWA/);
});
test('the mutation-handled locus stays in the headline and is shown without, with the direction', () => {
  const res = E.analyse(mini, { screening: ALL_NO });
  const bro = res.relatives.find((r) => r.id === 'k2');
  const expect = [1.85, 3.40, 0.0020].reduce((a, pi) => a * (2 * pi / (pi + 1)), 1);
  assert.ok(Math.abs(Number(bro.main.point.n) / Number(bro.main.point.d) - expect) < 1e-12);
  const v = bro.variants.find((x) => x.id === 'without-mutation');
  assert.ok(v && v.direction === 'higher');
  assert.ok(res.rows.find((r) => r.locus === 'TPOX').mutation);
});
test('linked pairs: both members, and the other member, are shown as variants; the swap is honoured', () => {
  const res = E.analyse(mini, { screening: ALL_NO });
  const ids = res.relatives[0].variants.map((v) => v.id);
  assert.ok(ids.includes('with-linked') && ids.includes('other-member'));
  const swapped = E.analyse(mini, { screening: ALL_NO, swapLinked: true });
  assert.deepEqual(swapped.used, ['D8S1179', 'D12S391', 'TPOX']);
});
test('the cap is (1/k)^n exactly', () => {
  const res = E.analyse(mini, { screening: ALL_NO });
  assert.equal(R(res.relatives[0].cap), '8'); assert.equal(R(res.relatives[1].cap), '64'); assert.equal(R(res.relatives[2].cap), '512');
});

// ── refusals ─────────────────────────────────────────────────────────────────
test('every disqualifying answer stops the relative figure, and unanswered questions hold it back', () => {
  for (const key of ['motherRelated', 'relativeRelatedToMother', 'relativeTested', 'theta', 'doubleRelated']) {
    const res = E.analyse(mini, { screening: { ...ALL_NO, [key]: 'yes' } });
    assert.equal(res.relatives.length, 0, key);
    assert.ok(res.screening.stops.length === 1, key);
  }
  const pending = E.analyse(mini, { screening: { ...ALL_NO, theta: null } });
  assert.equal(pending.relatives.length, 0);
  assert.equal(pending.screening.pending.length, 1);
});
test('identical twins give exactly 1, not a computed figure', () => {
  const res = E.analyse(mini, { screening: { ...ALL_NO, twin: 'yes' } });
  assert.ok(res.relatives.every((r) => r.twin && !r.main));
});
test('a combined index with no per-locus table is refused, with the demonstration', () => {
  const res = E.analyse({ kind: 'duo', rows: [], cpi: '1,000,000' }, { screening: ALL_NO });
  assert.ok(res.refusals.some((r) => r.code === 'cpi-only'));
  assert.equal(res.relatives.length, 0);
});

// ── two tested men ───────────────────────────────────────────────────────────
test('two tested men: product of PI_A/PI_B over shared loci, and one-sided loci listed', () => {
  const A = [{ locus: 'D8S1179', pi: '1.85' }, { locus: 'TH01', pi: '2.00' }, { locus: 'FGA', pi: '3.0' }];
  const B = [{ locus: 'D8S1179', pi: '0.925' }, { locus: 'TH01', pi: '2.00' }, { locus: 'D5S818', pi: '1.1' }];
  const r = E.compareMen(A, B, { kind: 'trio' });
  assert.deepEqual(r.shared, ['D8S1179', 'TH01']); assert.deepEqual(r.onlyA, ['FGA']); assert.deepEqual(r.onlyB, ['D5S818']);
  assert.equal(R(r.point), '2');
  const t = E.parseTwoMenText('D8S1179\t1.85\t0.925\nTH01  2.00  -');
  assert.equal(t.rowsB[1].pi, '');
});

// ── certificates, and what tampering does to them ────────────────────────────
const resMini = E.analyse(mini, { screening: ALL_NO });
const cd = E.certificateData(resMini, 'k2');
const certA = C.make('paternity-arithmetic', cd.arithmetic);
const certR = C.make('paternity-relative', cd.relative);
test('both certificates pass when read back from their own text', () => {
  for (const c of [certA, certR]) { const back = C.readback(C.serialise(c)); assert.ok(C.check(back).ok, c.kind); }
});
const tamper = (cert, re, rep) => {
  const t = C.serialise(cert).replace(re, rep);
  assert.notEqual(t, C.serialise(cert), 'the tamper did nothing');
  try { return C.check(C.readback(t)).ok; } catch { return false; }
};
test('tamper: a changed locus ratio fails', () => assert.equal(tamper(certR, /^ratio: (\S+)/m, (m, a) => `ratio: ${a}1`), false));
test('tamper: a changed product fails', () => assert.equal(tamper(certR, /^product: (\S+)/m, (m, a) => `product: ${a}1`), false));
test('tamper: a changed printed index fails', () => assert.equal(tamper(certR, /^printed: 1\.85/m, 'printed: 1.86'), false));
test('tamper: a different k fails', () => assert.equal(tamper(certR, /^k: \S+/m, 'k: 1/4'), false));
test('a relative certificate that multiplies both loci of a linked pair fails its own check', () => {
  const pis = ['3.40', '2.10'];
  const ratios = pis.map((t) => N.relativeRatio(N.readPrinted(t).value, half));
  const lo = pis.map((t) => N.relativeRatio(N.readPrinted(t).lo, half)), hi = pis.map((t) => N.relativeRatio(N.readPrinted(t).hi, half));
  const prod = (xs) => xs.reduce((a, b) => N.mul(a, b), N.ONE);
  const c = C.make('paternity-relative', { relationship: 'full brother, father or son', k: '1/2', loci: ['vWA', 'D12S391'], printed: pis, ratio: ratios.map(R), product: R(prod(ratios)), product_lo: R(prod(lo)), product_hi: R(prod(hi)), table_loci: ['vWA', 'D12S391'], table_printed: pis, set_aside: 'none' });
  const res = C.check(C.readback(C.serialise(c)));
  assert.equal(res.ok, false);
  assert.ok(res.lines.some((l) => !l.ok && /linked pair/.test(l.text)));
});
test('a relative certificate that uses a Y-chromosome row fails its own check', () => {
  const r = N.relativeRatio(N.exactDecimal('1.5'), half);
  const c = C.make('paternity-relative', { relationship: 'full brother, father or son', k: '1/2', loci: ['DYS391'], printed: ['1.5'], ratio: [R(r)], product: R(r), product_lo: R(N.relativeRatio(N.exactDecimal('1.45'), half)), product_hi: R(N.relativeRatio(N.exactDecimal('1.55'), half)), table_loci: ['DYS391'], table_printed: ['1.5'], set_aside: 'none' });
  assert.equal(C.check(C.readback(C.serialise(c))).ok, false);
});
test('tamper: an arithmetic end changed by one digit fails', () => assert.equal(tamper(certA, /^product_hi: (\S+)/m, (m, a) => `product_hi: ${a}7`), false));
test('tamper: a dropped row fails (the shape row guards it)', () => assert.equal(tamper(certA, /^printed: [^\n]*$/m, (m) => m.replace(/ \| [^|]*$/, '')), false));

// ── the record round-trips through the independent checker ───────────────────
test('the downloadable record passes the independent checker, and a tampered record fails it', () => {
  const dir = mkdtempSync(join(tmpdir(), 'pc-'));
  const rec = E.record(resMini, mini, ALL_NO);
  const good = join(dir, 'good.json'); writeFileSync(good, JSON.stringify(rec));
  let r = spawnSync(process.execPath, [CHECKER.pathname, good], { encoding: 'utf8' });
  assert.equal(r.status, 0, r.stdout);
  const bad = structuredClone(rec); bad.relatives[0].product = bad.relatives[0].product + '1';
  const badPath = join(dir, 'bad.json'); writeFileSync(badPath, JSON.stringify(bad));
  r = spawnSync(process.execPath, [CHECKER.pathname, badPath], { encoding: 'utf8' });
  assert.notEqual(r.status, 0);
  const sneaky = structuredClone(rec);
  sneaky.relatives[0].rows.push({ locus: 'D12S391', pi: '2.10', ratio: R(N.relativeRatio(N.exactDecimal('2.10'), half)), interval: null });
  const sneakyPath = join(dir, 'sneaky.json'); writeFileSync(sneakyPath, JSON.stringify(sneaky));
  r = spawnSync(process.execPath, [CHECKER.pathname, sneakyPath], { encoding: 'utf8' });
  assert.notEqual(r.status, 0, 'the checker accepted a linked pair');
});

// ── the bench numbers printed on the page are the bench's own ────────────────
// Each printed figure must equal the stored value to the precision it is printed at, so a
// re-run bench or an edited page cannot drift apart without this failing.
test('every bench figure printed on the page matches research/paternity-check/bench/results.mjs', () => {
  const html = readFileSync(new URL('public/tools/paternity-check/index.html', ROOT), 'utf8');
  const C = BENCH.populations.Combined;
  const table = (id) => {
    const m = new RegExp(`<table[^>]*id="${id}"[\\s\\S]*?<tbody>([\\s\\S]*?)</tbody>`).exec(html);
    assert.ok(m, `table ${id} on the page`);
    return [...m[1].matchAll(/<tr>([\s\S]*?)<\/tr>/g)].map((r) => [...r[1].matchAll(/<t[hd][^>]*>([\s\S]*?)<\/t[hd]>/g)].map((c) => c[1].trim()));
  };
  const num = (t) => Number(t.replace(/,/g, ''));
  // a printed decimal agrees with v if |v - printed| is at most half a unit in its last place
  const agrees = (printed, v, scale = 1) => {
    const t = printed.replace(/,/g, '').replace('%', '');
    const places = (t.split('.')[1] ?? '').length;
    return Math.abs(v * scale - Number(t)) <= 0.5 * 10 ** -places + 1e-12;
  };
  const triple = (cell) => { const m = /^([\d,.]+) \(([\d,.]+) to ([\d,.]+)\)$/.exec(cell); assert.ok(m, cell); return [m[1], m[2], m[3]]; };
  const frac = (cell, v, n) => {
    if (/^none of ([\d,]+)$/.test(cell)) return v === 0 && num(cell.match(/[\d,]+/)[0]) === n;
    const m = /^(\d+) in ([\d,]+)$/.exec(cell);
    if (m) return Math.abs(v - Number(m[1]) / num(m[2])) < 1e-12 && num(m[2]) === n;
    return agrees(cell, v, 100);
  };
  const panels = ['ID15', 'CODIS20', 'P22'];
  const t1 = table('bench-true');
  assert.equal(t1.length, 3);
  t1.forEach((row, i) => {
    const p = panels[i];
    const tr = C.trio.true[p], du = C.duo.true[p];
    const P = BENCH.panels[p];
    assert.ok(row[0].startsWith(`${P.lociTyped},`) && row[0].includes(`(${P.lociUsed} used)`), `row ${i} is the ${P.lociTyped}-locus panel with ${P.lociUsed} used: ${row[0]}`);
    const [a, b, c] = triple(row[1]);
    assert.ok(agrees(a, tr.lrBrother.p50) && agrees(b, tr.lrBrother.p5) && agrees(c, tr.lrBrother.p95), `${p} trio ${row[1]}`);
    assert.ok(frac(row[2], tr.fracBrotherBelow[100], tr.n), `${p} trio below 100: ${row[2]}`);
    const [d, e, f] = triple(row[3]);
    assert.ok(agrees(d, du.lrBrother.p50) && agrees(e, du.lrBrother.p5) && agrees(f, du.lrBrother.p95), `${p} duo ${row[3]}`);
    assert.ok(frac(row[4], du.fracBrotherBelow[100], du.n), `${p} duo below 100: ${row[4]}`);
  });
  const t2 = table('bench-brother');
  const order = [['trio', 'ID15'], ['trio', 'CODIS20'], ['trio', 'P22'], ['duo', 'ID15'], ['duo', 'CODIS20'], ['duo', 'P22']];
  assert.equal(t2.length, 6);
  t2.forEach((row, i) => {
    const [mode, p] = order[i];
    const b = C[mode].brother.panels[p];
    assert.ok(row[0] === `${BENCH.panels[p].lociTyped}, ${mode}`, row[0]);
    assert.ok(agrees(row[1], b.reportReadsAsProof.fracOfAllCases, 100), `${row[0]} share ${row[1]}`);
    assert.ok(agrees(row[2], b.reportReadsAsProof.lrBrother.p50), `${row[0]} median ${row[2]}`);
    assert.ok(agrees(row[3], b.reportReadsAsProof.fracToolBrotherLRBelow10, 100), `${row[0]} below 10 ${row[3]}`);
    assert.ok(agrees(row[4], b.fracBrotherLRAtLeast100AllCases, 100), `${row[0]} at least 100 ${row[4]}`);
  });
  assert.ok(html.includes(`in ${t2[0][4]} of all brother-fathered 15-locus trios`), 'the prose repeats the table');
});

// ── the published sample reports ─────────────────────────────────────────────
test('the page\'s worked examples are copied unchanged from the transcriptions', () => {
  const byId = new Map(ALL_EXAMPLES.map((e) => [e.id, e]));
  assert.ok(EXAMPLES.length >= 5);
  for (const ex of EXAMPLES) {
    const t = byId.get(ex.id);
    assert.ok(t, ex.id);
    assert.equal(ex.printedCPI ?? null, t.printedCPI ?? null, ex.id); assert.equal(ex.printedW ?? null, t.printedW ?? null, ex.id); assert.equal(ex.kind, t.kind, ex.id);
    assert.equal(ex.rows.length, t.rows.length, ex.id);
    ex.rows.forEach((r, i) => { for (const f of ['locus', 'mother', 'child', 'af', 'pi']) assert.equal(r[f] ?? '', t.rows[i][f] ?? '', `${ex.id} row ${i} ${f}`); });
  }
});
const analyseEx = (ex) => E.analyse({ kind: ex.kind, rows: ex.rows, cpi: ex.printedCPI, w: ex.printedW, prior: ex.prior }, { screening: ALL_NO });
for (const ex of ALL_EXAMPLES) {
  test(`transcription "${ex.id}": every index reads, and the printed combined index and probability are consistent with the printed indices`, () => {
    const res = analyseEx(ex);
    assert.ok(res.rows.every((r) => !r.piError), 'every index reads');
    if (ex.rows.length && ex.printedCPI) assert.ok(['inside', 'inside-loose', 'inside-truncated'].includes(res.arithmetic.cpiVerdict), `cpi verdict ${res.arithmetic.cpiVerdict}`);
    if (ex.rows.length && ex.printedW) assert.ok(['inside', 'inside-truncated'].includes(res.arithmetic.wVerdict), `w verdict ${res.arithmetic.wVerdict}`);
  });
}
const exById = (id) => ALL_EXAMPLES.find((e) => e.id === id);
test('Genomia demo: CSF1PO is set aside (linked to D5S818); 25.58 against a brother, 30.85 multiplying all 15', () => {
  const res = analyseEx(exById('genomia-duo-demo'));
  const bro = res.relatives.find((r) => r.id === 'k2');
  assert.deepEqual(res.setAside.map((s) => s.locus), ['CSF1PO']);
  assert.equal(N.show(bro.main.point, 4), '25.58');
  assert.equal(N.show(bro.variants.find((v) => v.id === 'with-linked').result.point, 4), '30.85');
  // the same loci, read the other way: the report's support for the brother over a stranger
  const all = bro.main.perRow.reduce((a, p) => N.mul(a, p.pi.value), N.ONE);
  assert.ok(N.eq(N.div(all, bro.main.point), bro.main.stranger.point), 'LR(AF:U) / LR(AF:R) = LR(R:U) over the same loci');
});
test('Goodwin 2004: the figure points at the brother (below 1) with or without the linked loci, and not without the mutation loci', () => {
  const res = analyseEx(exById('goodwin-2004-trio'));
  const bro = res.relatives.find((r) => r.id === 'k2');
  assert.ok(N.lt(bro.main.point, N.ONE));
  assert.ok(N.lt(bro.variants.find((v) => v.id === 'with-linked').result.point, N.ONE));
  assert.ok(!N.lt(bro.variants.find((v) => v.id === 'without-mutation').result.point, N.ONE));
  assert.deepEqual(res.rows.filter((r) => r.mutation).map((r) => r.locus), ['D21S11', 'SE33']);
});
test('Validity: the printed probability fits only as a truncated figure, and the page says so rather than calling it wrong', () => {
  assert.equal(analyseEx(exById('validity-duo-inclusion')).arithmetic.wVerdict, 'inside-truncated');
});
test('an exclusion report: no relative figure is headlined; each relative is weighed against a stranger instead', () => {
  const res = analyseEx(exById('genomia-duo-exclusion-demo'));
  const bro = res.relatives.find((r) => r.id === 'k2');
  assert.ok(bro.excluded && bro.excluded.length >= 1);
  assert.equal(E.certificateData(res, 'k2').relative, undefined, 'no relative certificate for an exclusion');
  // at an excluded locus a brother counts exactly 1/2
  const ex = bro.main.perRow.find((p) => p.pi.value.n === 0n);
  assert.equal(R(ex.stranger), '0.5');
});
test('a report with only a combined index is refused, with the demonstration', () => {
  const res = analyseEx(exById('genomia-duo-anonymous-demo'));
  assert.ok(res.refusals.some((r) => r.code === 'cpi-only'));
});
test('DNA-VIEW\'s illustrative sample: 3-figure indices, so the printed 27000000 is consistent only as an interval', () => {
  const res = analyseEx(exById('dnaview-pater-sample'));
  // 2.47 x 32.5 x 9.17 x 44.7 x 1.63 x 2.4 x 4.06 x 1.97 x 2.76 x 3 x 1.37 x 2.31, done by hand-checkable arithmetic
  const byHand = ['2.47', '32.5', '9.17', '44.7', '1.63', '2.4', '4.06', '1.97', '2.76', '3', '1.37', '2.31'].reduce((a, t) => N.mul(a, N.exactDecimal(t)), N.ONE);
  assert.ok(N.eq(res.arithmetic.product.point, byHand));
  assert.equal(N.show(res.arithmetic.product.point, 8), '26,978,088');
  assert.equal(res.arithmetic.cpiVerdict, 'inside', 'the printed 27000000 sits inside the product interval of 3-figure indices');
  assert.ok(['inside', 'inside-loose'].includes(res.arithmetic.cpiVerdict));
  assert.ok(res.rows.filter((r) => r.cls?.status === 'mother-mismatch').length === 2, 'its fictional genotypes have two maternal mismatches, which the page flags');
});


// ── fixes from the review: each test fails on the code as it was before the fix ──
// The critical one: an index of 0 on the member of a linked pair that the rule would set
// aside must still decide the report, for every listed pair.
for (const pp of LINKED_PAIRS) {
  test(`an index of 0 at ${pp.b} (linked to ${pp.a}) excludes him: no positive figure, no relative certificate`, () => {
    const rows = [
      { locus: 'D8S1179', child: '13,14', af: '14,15', pi: '1.85' },
      { locus: pp.a, child: '', af: '', pi: '3.40' },
      { locus: pp.b, child: '', af: '', pi: '0' },
      { locus: 'TH01', child: '', af: '', pi: '2.10' },
    ];
    for (const swap of [false, true]) {
      const res = E.analyse({ kind: 'duo', rows }, { screening: ALL_NO, swapLinked: swap });
      assert.ok(res.excludedLoci.includes(pp.b), 'the zero is an exclusion');
      for (const rel of res.relatives) assert.ok(rel.excluded && rel.excluded.includes(pp.b), `${rel.id} is excluded`);
      assert.equal(E.certificateData(res, 'k2').relative, undefined);
      if (!swap) assert.ok(res.used.includes(pp.b), 'the rule keeps the excluding locus of the pair');
    }
  });
}
test('a row printed 0 is an exclusion, not a locus the lab handled as a mutation', () => {
  const r = E.readRows([{ locus: 'vWA', child: '16, 17', af: '18, 19', pi: '0' }], { trio: false })[0];
  assert.equal(r.exclusion, true); assert.equal(r.mutation, false);
});
test('an index of 0 on a row whose genotypes fit is read, not a crash', () => {
  for (const pi of ['0', '0.0', '0.00']) {
    const r = E.readRows([{ locus: 'vWA', child: '16, 17', af: '16, 18', pi }], { trio: false })[0];
    assert.equal(r.exclusion, true);
  }
});
test('linked-pair tie wording: D5S818 and CSF1PO are on the same kits, so "more kits" is not claimed', () => {
  const res = E.analyse({ kind: 'duo', rows: [{ locus: 'D5S818', pi: '1.5' }, { locus: 'CSF1PO', pi: '2.5' }] }, { screening: ALL_NO });
  assert.match(res.setAside[0].why, /same kits/);
});
test('numbers: space thousands read, point thousands refused, capital X and ** exponents, unit carried', () => {
  assert.equal(R(N.readPrinted('27 000 000').value), '27000000');
  assert.equal(R(N.readPrinted('27 000 000').value), '27000000');
  assert.throws(() => N.readPrinted('27.000.000'), /more than one point/);
  assert.throws(() => N.readPrinted('1 2'), /space/);
  assert.equal(R(N.readPrinted('2.7 X 10^7').value), '27000000');
  assert.equal(R(N.readPrinted('2.7 x 10**7').value), '27000000');
  assert.equal(R(N.readPrinted('2.7 x 10^−3').value), '0.0027');
  assert.equal(R(N.readPrinted('1.85').unit), '0.01');
});
test('numbers: a figure cut off at 0 means [0, 1), not half of it', () => {
  const t = N.truncated(N.readPrinted('0', { nonNegative: true }));
  assert.equal(R(t.lo), '0'); assert.equal(R(t.hi), '1');
  const t2 = N.truncated(N.readPrinted('0.0', { nonNegative: true }));
  assert.equal(R(t2.hi), '0.1');
});
test('numbers: "<= 1.5" includes 1.5, "< 1.5" does not', () => {
  const iv = { lo: N.exactDecimal('1.5'), hi: N.exactDecimal('2.5') };
  assert.equal(N.intersects(iv, N.readPrinted('<= 1.5', { allowBound: true, nonNegative: true })), true);
  assert.equal(N.intersects(iv, N.readPrinted('≤ 1.5', { allowBound: true, nonNegative: true })), true);
  assert.equal(N.intersects(iv, N.readPrinted('< 1.5', { allowBound: true, nonNegative: true })), false);
});
test('numbers: intervals shown outward in scientific form too, and tiny ones not as runs of zeros', () => {
  assert.equal(N.showInterval({ lo: Q(1234567890500001n), hi: Q(1234567891400000n) }, 10), '1.234567890e+15 to 1.234567892e+15');
  assert.equal(N.showInterval({ lo: Q(654678n, 10n ** 54n), hi: Q(151381n, 10n ** 53n) }, 6), '6.54678e-49 to 1.51381e-48');
});
test('a combined index in exponent, superscript, space-grouped or parenthesised forms is read whole', () => {
  // eight indices that multiply to exactly 27,000,000
  const rows = ['10', '10', '10', '10', '10', '10', '9', '3'].map((pi, i) => ({ locus: ['D8S1179', 'D21S11', 'D7S820', 'D3S1358', 'TH01', 'D13S317', 'D16S539', 'D2S1338'][i], pi }));
  for (const cpi of ['2.7 x 10^7', '2.7 × 10⁷', '2.7·10^7', '2.7 * 10^7', '2.7 X 10^7', '27,000,000', '27 000 000', '2.7E+07']) {
    const res = E.analyse({ kind: 'duo', rows, cpi }, { screening: ALL_NO });
    assert.ok(['inside', 'inside-loose'].includes(res.arithmetic.cpiVerdict), `${cpi}: ${res.arithmetic.cpiVerdict} ${res.arithmetic.cpiError ?? ''}`);
  }
  for (const cpi of ['27 million', 'about 27,000,000']) {
    const res = E.analyse({ kind: 'duo', rows, cpi }, { screening: ALL_NO });
    assert.ok(res.arithmetic.cpiError, `${cpi} is refused, not read as 27`);
  }
  const lines = (t) => E.parseReportText(`Locus\tChild\tAlleged Father\tPI\nD8S1179\t13, 14\t14, 15\t1.85\n${t}`).summary;
  assert.equal(lines('Combined Paternity Index: 6.0 × 10³').cpi, '6.0 × 10³');
  assert.equal(lines('Combined Paternity Index (15 loci): 2.22').cpi, '2.22');
  assert.equal(lines('Combined Paternity Index: 1 200 000').cpi, '1 200 000');
  assert.equal(lines('Probability of Paternity (Prior = 0.5): 99.98%').w, '99.98%');
  assert.equal(lines('Probability of Paternity (Prior = 0.5): 99.98%').prior, '0.5');
  assert.equal(lines('The probability of paternity is calculated using a prior probability of 0.5.\nProbability of Paternity: 64.91%').w, '64.91%');
});
test('the arithmetic certificate reads the combined index the way the analysis does', () => {
  const rows = ['10', '10', '10', '10', '10', '10', '9', '3'].map((pi, i) => ({ locus: ['D8S1179', 'D21S11', 'D7S820', 'D3S1358', 'TH01', 'D13S317', 'D16S539', 'D2S1338'][i], pi }));
  const res = E.analyse({ kind: 'duo', rows, cpi: '2.7 × 10⁷' }, { screening: ALL_NO });
  const c = C.make('paternity-arithmetic', E.certificateData(res).arithmetic);
  assert.equal(C.check(C.readback(C.serialise(c))).ok, true);
});
test('a relative certificate whose relationship does not match k fails its own check', () => {
  const res = E.analyse(mini, { screening: ALL_NO });
  const d = E.certificateData(res, 'k2').relative;
  const bad = { ...d, relationship: 'first cousin' };
  assert.equal(C.check(C.readback(C.serialise(C.make('paternity-relative', bad)))).ok, false);
  assert.equal(C.check(C.readback(C.serialise(C.make('paternity-relative', d)))).ok, true);
});
test('a relative certificate that quietly drops a usable locus fails its own check', () => {
  const res = E.analyse(mini, { screening: ALL_NO });
  const d = E.certificateData(res, 'k2').relative;
  // drop TPOX (the mutation-handled locus) and recompute every number the check could test
  const keep = d.loci.map((l, i) => i).filter((i) => d.loci[i] !== 'TPOX');
  const ratios = keep.map((i) => N.relativeRatio(N.readPrinted(d.printed[i]).value, half));
  const prod = (xs) => xs.reduce((a, b) => N.mul(a, b), N.ONE);
  const dropped = { ...d, loci: keep.map((i) => d.loci[i]), printed: keep.map((i) => d.printed[i]), ratio: ratios.map(R), product: R(prod(ratios)),
    product_lo: R(prod(keep.map((i) => N.relativeRatio(N.readPrinted(d.printed[i]).lo, half)))), product_hi: R(prod(keep.map((i) => N.relativeRatio(N.readPrinted(d.printed[i]).hi, half)))) };
  const res2 = C.check(C.readback(C.serialise(C.make('paternity-relative', dropped))));
  assert.equal(res2.ok, false);
  assert.ok(res2.lines.some((l) => !l.ok && /TPOX/.test(l.text)));
});
test('a "|" in a locus name is replaced, so both certificates are still made', () => {
  const res = E.analyse({ kind: 'duo', rows: [{ locus: 'D8S1179', pi: '1.85' }, { locus: 'TH01 | lab B', pi: '2.10' }] }, { screening: ALL_NO });
  const d = E.certificateData(res, 'k2');
  assert.ok(d.arithmetic && !d.arithmetic.loci.some((l) => l.includes('|')));
  assert.equal(C.check(C.readback(C.serialise(C.make('paternity-arithmetic', d.arithmetic)))).ok, true);
});
test('parser: footnote marks, row numbers and unrecognised names keep the row', () => {
  const p = E.parseReportText('Locus\tChild\tAlleged Father\tPI\nD8S1179\t13, 14\t14, 15\t1.85\nD5S818*\t11, 12\t9, 13\t0.0042\n1. TH01\t9.3\t7, 9.3\t1.20\nD6S474\t11, 12\t11, 13\t1.30');
  assert.deepEqual(p.rows.map((r) => r.locus), ['D8S1179', 'D5S818', 'TH01', 'D6S474']);
  assert.ok(p.notes.some((n) => /Footnote/.test(n)) && p.notes.some((n) => /D6S474/.test(n)));
});
test('parser: names used as column headers are not taken for roles ("Man Yee Wong", "Son Nguyen")', () => {
  for (const names of [['Man Yee Wong', 'Kelly Wong', 'David Chan'], ['Mai Tran', 'Linh Tran', 'Son Nguyen']]) {
    const p = E.parseReportText(`Locus\t${names.join('\t')}\tPI\nD8S1179\t12/13\t13/14\t14/15\t1.85`);
    const r = p.rows[0];
    assert.deepEqual([r.mother, r.child, r.af], ['12/13', '13/14', '14/15']);
    assert.ok(p.notes.some((n) => n.includes(names[0])), 'the person is told the columns were read in the usual order');
  }
});
test('parser: Spanish headers and a "Cumulative CPI" column', () => {
  const sp = E.parseReportText('Locus\tHijo\tMadre\tPresunto padre\tPI\nD8S1179\t13, 14\t12, 13\t14, 15\t1.85').rows[0];
  assert.deepEqual([sp.mother, sp.child, sp.af], ['12, 13', '13, 14', '14, 15']);
  const cum = E.parseReportText('Locus\tChild\tAlleged Father\tCumulative CPI\tPI\nD8S1179\t13, 14\t14, 15\t1.85\t1.85').rows[0];
  assert.equal(cum.mother, ''); assert.equal(cum.pi, '1.85');
});
test('parser: a misaligned row is read by cell order when it has one cell per column, else flagged', () => {
  const p = E.parseReportText('Locus  Mother  Child  Alleged Father  PI\nD8S1179  12, 13  13, 14  14, 15  1.85\nD21S11  28, 30  29, 30  29, 31.2  2.40');
  assert.deepEqual(p.rows.map((r) => [r.mother, r.child, r.af, r.pi]), [['12, 13', '13, 14', '14, 15', '1.85'], ['28, 30', '29, 30', '29, 31.2', '2.40']]);
  const q = E.parseReportText('Locus  Child  Alleged Father  PI\nD3S1358          16    15 16');
  assert.ok(q.rows[0].ambiguous, 'a figure in the wrong column is flagged');
});
test('parser: trio rows with once-printed homozygotes, and two index-like figures, are left for the person', () => {
  const p = E.parseReportText('Locus PI Mother Child Alleged Father\nD8S1179 1.85 12 13 13 14 14 15\nvWA 2.50 14 17 17 17');
  assert.ok(p.rows[1].ambiguous && !p.rows[1].child);
  const g = E.parseReportText('D8S1179  12 13  13 14  14 15  3.70  2.35').rows[0];
  assert.ok(g.ambiguous && g.pi === '');
  const f = E.parseReportText('D8S1179 2.5 12 14 12 15 14 15').rows[0];
  assert.equal(f.pi, '2.5', 'one non-allele figure before the alleles is the index');
});
test('parser: a page number between two pages is not joined to the locus above', () => {
  const p = E.parseReportText('                 CHILD                    Alleged FATHER\nLocus     PI     Allele Sizes             Allele Sizes\nD16S539   1.94   11                       11     12\n\n                  1\n\n                 CHILD                    Alleged FATHER\nLocus     PI     Allele Sizes             Allele Sizes\nCSF1PO    1.51   10     12                10     11');
  assert.equal(p.rows[0].child, '11');
});
test('two tested men: an index of 0 is reported as an exclusion, and a mutation-like index is shown without', () => {
  const r = E.compareMen(
    [['D8S1179', '1.85'], ['TPOX', '0'], ['TH01', '0.0021']].map(([locus, pi]) => ({ locus, pi })),
    [['D8S1179', '0.93'], ['TPOX', '1.30'], ['TH01', '1.40']].map(([locus, pi]) => ({ locus, pi })), { kind: 'trio' });
  assert.deepEqual(r.excludedA, ['TPOX']);
  assert.deepEqual(r.low, ['TH01']);
  assert.ok(r.withoutLow && r.withoutLow.flips);
  const dup = E.compareMen([{ locus: 'vWA', pi: '3.0' }, { locus: 'VWA', pi: '0.002' }], [{ locus: 'vWA', pi: '1.5' }], {});
  assert.ok(dup.skippedA.some((s) => /twice/.test(s.reason)));
});
test('the "other member" variant says when it sets aside the mutation locus (Goodwin)', () => {
  const g = EXAMPLES.find((e) => e.id === 'goodwin-2004-trio');
  const res = E.analyse({ kind: g.kind, rows: g.rows, cpi: g.printedCPI, w: g.printedW, prior: g.prior }, { screening: ALL_NO });
  const v = res.relatives[0].variants.find((x) => x.id === 'other-member');
  assert.match(v.note, /D21S11/);
  assert.ok(N.cmp(v.result.point, N.ONE) > 0 && N.cmp(res.relatives[0].main.point, N.ONE) < 0, 'it reverses the direction, which the headline must say');
});
test('the stranger paragraph identity: LR = (product of PI) / (product of k*PI+1-k) over the same loci', () => {
  const res = E.analyse(mini, { screening: ALL_NO });
  for (const rel of res.relatives) assert.ok(N.eq(N.mul(rel.main.point, rel.main.stranger.point), rel.main.piPoint));
});
test('CSV: decimals rather than fractions, the printed digits kept, an unused duplicate row not credited', () => {
  const res = E.analyse({ kind: 'duo', rows: [{ locus: 'vWA', pi: '3.40' }, { locus: 'HUMvWA31', pi: '0.0020' }, { locus: 'TH01', pi: '2.00' }] }, { screening: ALL_NO });
  const lines = E.csv(res).trim().split('\n');
  assert.ok(!/\d+\/\d+/.test(lines.slice(1).join('\n')), 'no n/d fraction anywhere');
  assert.match(lines[3], /"=""2\.00"""/, 'the printed index, CSV-quoted as ="2.00"');
  assert.match(lines[2], /,no,/);
});
test('the downloadable record carries every row with its reading, for the checker to recompute', () => {
  const res = E.analyse(mini, { screening: ALL_NO });
  const rec = E.record(res, mini, ALL_NO);
  assert.equal(rec.format, 'paternity-check-record/2');
  assert.equal(rec.rows.length, mini.rows.length);
  assert.deepEqual(rec.rows.filter((r) => r.used).map((r) => r.canonical), ['D8S1179', 'vWA', 'TPOX']);
  assert.equal(rec.rows.find((r) => r.locus === 'D99S999').canonical, null);
});
test('the page says what the theta refusal rests on, and makes no claim about what labs usually do', () => {
  const html = readFileSync(new URL('public/tools/paternity-check/index.html', ROOT), 'utf8');
  assert.ok(!/exact only without/.test(html));
  assert.ok(!E.ASSUMPTIONS.some((a) => /usually/.test(a)));
  const app = readFileSync(new URL('public/tools/paternity-check/app.mjs', ROOT), 'utf8');
  assert.ok(!/Most US parentage reports/.test(app) && !/labs often/.test(app));
});


// ── fixes from the second review ─────────────────────────────────────────────
test('an unrecognised row printed 0 is named, never multiplied into a variant (no zero-denominator crash)', () => {
  const rows = [{ locus: 'D8S1179', pi: '1.85' }, { locus: 'TH01', pi: '2.40' }, { locus: 'D7S0820', pi: '0' }, { locus: 'FGA', pi: '3.10' }];
  const res = E.analyse({ kind: 'duo', rows }, { screening: ALL_NO });
  assert.deepEqual(res.unrecognisedZero, ['D7S0820']);
  for (const rel of res.relatives) for (const v of rel.variants) assert.ok(v.result.point.n !== 0n, `${v.id} is not 0`);
  assert.match(res.notUsed.find((x) => x.locus === 'D7S0820').reason, /excludes the tested man/);
});
test('two tested men: an index of 0 on a locus reported for one man only still excludes him', () => {
  const r = E.compareMen([{ locus: 'D8S1179', pi: '1.85' }, { locus: 'Penta E', pi: '0' }], [{ locus: 'D8S1179', pi: '0.93' }], {});
  assert.deepEqual(r.excludedA, ['Penta E']);
  const u = E.compareMen([{ locus: 'D8S1179', pi: '1,85' }, { locus: 'TH01', pi: '1.4' }], [{ locus: 'D8S1179', pi: '1.20' }, { locus: 'TH01', pi: '0.7' }], {});
  assert.deepEqual(u.onlyB, [], 'an unreadable index is not "reported for one man only"');
  const one = E.compareMen([{ locus: 'TPOX', pi: '0.0021' }], [{ locus: 'TPOX', pi: '1.30' }], {});
  assert.ok(one.withoutLow.nothingLeft, 'no "without it" figure when nothing is left');
  const flat = E.compareMen([['D8S1179', '2.00'], ['TH01', '1.50'], ['TPOX', '0.0021']].map(([locus, pi]) => ({ locus, pi })), [['D8S1179', '2.00'], ['TH01', '1.50'], ['TPOX', '1.30']].map(([locus, pi]) => ({ locus, pi })), {});
  assert.equal(flat.withoutLow.flips, false); assert.equal(flat.withoutLow.neither, true);
});
test('a relative certificate over a table that prints 0 on a usable row fails, whichever locus of the pair it used', () => {
  const pis = ['3.40', '1.50', '2.20', '1.85'];
  const loci = ['vWA', 'TH01', 'FGA', 'D8S1179'];
  const ratios = pis.map((t) => N.relativeRatio(N.readPrinted(t).value, half));
  const prod = (xs) => xs.reduce((a, b) => N.mul(a, b), N.ONE);
  const c = C.make('paternity-relative', { relationship: 'full brother, father or son', k: '1/2', loci, printed: pis, ratio: ratios.map(R), product: R(prod(ratios)),
    product_lo: R(prod(pis.map((t) => N.relativeRatio(N.readPrinted(t).lo, half)))), product_hi: R(prod(pis.map((t) => N.relativeRatio(N.readPrinted(t).hi, half)))),
    table_loci: ['vWA', 'D12S391', 'TH01', 'FGA', 'D8S1179'], table_printed: ['3.40', '0', '1.50', '2.20', '1.85'], set_aside: 'D12S391' });
  const res = C.check(C.readback(C.serialise(c)));
  assert.equal(res.ok, false);
  assert.ok(res.lines.some((l) => !l.ok && /index of 0 at D12S391/.test(l.text)));
});
test('the arithmetic certificate says a printed combined index could not be read, rather than "not given"', () => {
  const res = E.analyse({ kind: 'duo', rows: [{ locus: 'D8S1179', pi: '1.85' }], cpi: '13.8 million' }, { screening: ALL_NO });
  const d = E.certificateData(res).arithmetic;
  assert.match(d.cpi_printed, /^printed but not readable: 13\.8 million$/);
  assert.equal(C.check(C.readback(C.serialise(C.make('paternity-arithmetic', d)))).ok, true);
  const lie = { ...d, cpi_printed: 'printed but not readable: 1.85' };
  assert.equal(C.check(C.readback(C.serialise(C.make('paternity-arithmetic', lie)))).ok, false, 'a readable figure cannot be called unreadable');
});
test('labels: every line break and invisible character the kit refuses is cleaned, so certificates are still made', () => {
  for (const bad of ['FGA\u0085x', 'FGA x', 'FGA\u000bx', 'FGA​x', 'FGA|x']) {
    const res = E.analyse({ kind: 'duo', rows: [{ locus: 'D8S1179', pi: '1.85' }, { locus: bad, pi: '2.10' }] }, { screening: ALL_NO });
    const d = E.certificateData(res, 'k2');
    assert.doesNotThrow(() => C.make('paternity-arithmetic', d.arithmetic), JSON.stringify(bad));
    assert.doesNotThrow(() => C.make('paternity-relative', d.relative), JSON.stringify(bad));
  }
});
test('record and CSV reasons belong to their own row when rows share a locus name; relativeFigure says whether one was computed', () => {
  const res = E.analyse({ kind: 'duo', rows: [{ locus: 'TH01', pi: '1,85' }, { locus: 'TH01', pi: '' }, { locus: 'FGA', pi: '2.00' }] }, { screening: ALL_NO });
  const rec = E.record(res, { kind: 'duo', rows: [] }, ALL_NO);
  assert.match(rec.rows[0].reason, /could not be read/); assert.match(rec.rows[1].reason, /no index printed/);
  assert.equal(rec.relativeFigure, true);
  const stopped = E.analyse({ kind: 'duo', rows: [{ locus: 'FGA', pi: '2.00' }] }, { screening: { ...ALL_NO, motherRelated: 'yes' } });
  assert.equal(E.record(stopped, { kind: 'duo', rows: [] }, ALL_NO).relativeFigure, false);
  assert.match(E.csv(stopped), /eligible \(no relative figure was computed\)/);
});
test('an index only a mutation can produce is treated as one even with no genotypes (duo below 1/4, trio below 1/2)', () => {
  const res = E.analyse({ kind: 'duo', rows: [{ locus: 'D8S1179', pi: '1.20' }, { locus: 'TH01', pi: '0.0021' }, { locus: 'FGA', pi: '1.10' }, { locus: 'D3S1358', pi: '0.95' }] }, { screening: ALL_NO });
  assert.ok(res.rows[1].lowIndex && res.rows[1].mutation);
  const v = res.relatives[0].variants.find((x) => x.id === 'without-mutation');
  assert.ok(v && N.cmp(v.result.point, N.ONE) > 0 && N.cmp(res.relatives[0].main.point, N.ONE) < 0, 'the variant reverses the direction');
  assert.equal(E.readRows([{ locus: 'TH01', pi: '0.30' }], { trio: false })[0].lowIndex, false, '0.30 is possible in a duo');
  assert.equal(E.readRows([{ locus: 'TH01', pi: '0.30' }], { trio: true })[0].lowIndex, true, '0.30 is not possible in a trio');
});
test('per-pair linked choices: one that reverses the direction is shown when neither whole-rule choice does', () => {
  const rows = [['D8S1179', '0.333'], ['TH01', '1.00'], ['vWA', '0.90'], ['D12S391', '9.00'], ['D5S818', '9.00'], ['CSF1PO', '0.90']].map(([locus, pi]) => ({ locus, pi }));
  const res = E.analyse({ kind: 'duo', rows }, { screening: ALL_NO });
  const v = res.relatives[0].variants.find((x) => x.id === 'linked-combination');
  assert.ok(v, 'shown');
  assert.ok(N.cmp(v.result.point, N.ONE) > 0 && N.cmp(res.relatives[0].main.point, N.ONE) < 0);
});
test('with the linked choice swapped, the default is called the fixed rule and the dropped mutation locus is named', () => {
  const g = EXAMPLES.find((e) => e.id === 'goodwin-2004-trio');
  const res = E.analyse({ kind: g.kind, rows: g.rows }, { screening: ALL_NO, swapLinked: true });
  assert.deepEqual(res.swapDroppedTelling, ['D21S11']);
  const v = res.relatives[0].variants.find((x) => x.id === 'other-member');
  assert.match(v.label, /^with the page's default choice/); assert.match(v.note, /fixed rule/);
  assert.ok(!res.notUsed.some((x) => /at your request\), a rule that never looks/.test(x.reason)));
});
test('parser: "50 percent", "1 in 6,000" and "about 5,000" stay whole; "6.000" against a product of 6,000 gets the thousands hint', () => {
  const sum = (t) => E.parseReportText(`Locus\tChild\tAlleged Father\tPI\nD8S1179\t13, 14\t14, 15\t1.85\n${t}`).summary;
  assert.equal(sum('Prior probability: 50 percent').prior, '50%');
  assert.equal(sum('Combined Paternity Index: 1 in 6,000').cpi, '1 in 6,000');
  assert.equal(sum('Combined Paternity Index: about 5,000').cpi, 'about 5,000');
  const rows = ['10', '10', '10', '6'].map((pi, i) => ({ locus: ['D8S1179', 'D21S11', 'D7S820', 'TH01'][i], pi }));
  const res = E.analyse({ kind: 'duo', rows, cpi: '6.000' }, { screening: ALL_NO });
  assert.equal(res.arithmetic.cpiVerdict, 'outside');
  assert.match(res.arithmetic.cpiThousandsHint, /6000/);
});
test('parser: index-only rows with unrecognised names are kept; HUMvWA31/A is vWA; ":" is not a footnote; Comments is not a person', () => {
  const p = E.parseReportText('Locus\tPI\nD8S1179\t1.85\nHUMvWA31/A\t0.0042\nD6S474\t1.30');
  assert.deepEqual(p.rows.map((r) => r.locus), ['D8S1179', 'HUMvWA31/A', 'D6S474']);
  assert.equal(normalizeLocus('HUMvWA31/A').canonical, 'vWA');
  assert.ok(!E.parseReportText('Locus\tChild\tAlleged Father\tPI\nD8S1179:\t13, 14\t14, 15\t1.85').notes.some((n) => /Footnote/.test(n)));
  const c = E.parseReportText('Locus\tChild\tAlleged Father\tPI\tRemarks\nD5S818\t11, 12\t9, 13\t0.0042\tmutation').rows[0];
  assert.equal(c.mother, '');
  const q = E.parseReportText('Locus\tChild\tAlleged Father\tPI\nD8S1179\t13, 14\t14, 15\t1.85\nSample collected 12 03 2026 at 9 am\tok');
  assert.ok(q.notes.some((n) => /not read as a row/.test(n)), 'a skipped line with figures is named');
});
test('the theta stop and the page no longer give an unsourced reason or call the figure "wrong" or "false"', () => {
  const st = E.screen({ ...ALL_NO, theta: 'yes' }).stops[0].text;
  assert.ok(!/condition on/.test(st));
  const html = readFileSync(new URL('public/tools/paternity-check/index.html', ROOT), 'utf8');
  assert.ok(!/condition on/.test(html) && !/printing a wrong one/.test(html) && !/where the formula is false/.test(html));
});

// ── the independent checker against tampering ────────────────────────────────
test('the independent checker passes every genuine record and catches every tampering attack (checker-attacks.mjs)', () => {
  const r = spawnSync(process.execPath, [new URL('research/paternity-check/checker-attacks.mjs', ROOT).pathname], { encoding: 'utf8', timeout: 600000 });
  assert.equal(r.status, 0, (r.stdout || '').split('\n').filter((l) => /FAIL/.test(l)).slice(0, 3).join(' | ') || r.stderr);
  assert.match(r.stdout, / 0 failed/);
});
test('on a report that excludes the tested man the fixed linked rule applies, so the stranger figure includes the excluding locus', () => {
  const rows = [{ locus: 'D8S1179', pi: '1.85' }, { locus: 'vWA', pi: '3.40' }, { locus: 'D12S391', pi: '0' }, { locus: 'TH01', pi: '2.10' }];
  const res = E.analyse({ kind: 'duo', rows }, { screening: ALL_NO, swapLinked: true });
  assert.equal(res.linkedChoice, 'default');
  assert.ok(res.used.includes('D12S391'));
  assert.ok(res.relatives[0].main.perRow.some((p) => p.locus === 'D12S391' && R(p.stranger) === '0.5'));
});

console.log(`\n${passed} passed, ${failed} failed (of ${n}).`);
process.exit(failed ? 1 : 0);
