#!/usr/bin/env node
/**
 * Offline verifier for /strata/cut-only-what-they-could-not-guess/
 *
 * Two modes:
 *   --no-net (default when data/xml is absent)
 *       Part A: recompute every published number from the committed artefacts.
 *       Part C: confirm the page embeds those artefacts byte for byte.
 *   full (data/xml present)
 *       Part B as well: re-parse the raw EpiDoc XML with the independent
 *       implementation below and require it to agree with build_artifacts.py
 *       on every corpus-level figure. The Python side walks an ElementTree;
 *       this side runs a streaming tag scanner. They share no code.
 *
 * Source data: Epigraphic Database Heidelberg, CC BY-SA 4.0.
 */
import { readFileSync, existsSync, readdirSync, statSync } from 'node:fs';
import { createHash } from 'node:crypto';
import { fileURLToPath } from 'node:url';
import { dirname, join } from 'node:path';

const here = dirname(fileURLToPath(import.meta.url));
const PAGE = join(here, '../../public/strata/cut-only-what-they-could-not-guess/index.html');
const XMLDIR = join(here, 'data/xml');

let pass = 0, fail = 0;
const ok = (name, cond, detail = '') => {
  if (cond) { pass++; console.log(`  ok   ${name}${detail ? '  ' + detail : ''}`); }
  else { fail++; console.log(`  FAIL ${name}${detail ? '  ' + detail : ''}`); }
};
const near = (a, b, tol) => Math.abs(a - b) <= tol;

const S = JSON.parse(readFileSync(join(here, 'stats.json'), 'utf8'));
const C = JSON.parse(readFileSync(join(here, 'corpus.json'), 'utf8'));

// ===================================================================== Part A
console.log('\nPart A — every published number, recomputed from the artefacts');

ok('the corpus is the Latin subset of the epitaphs',
   S.corpus.epitaphsLatin < S.corpus.epitaphsAllLanguages &&
   S.corpus.epitaphsLatin === C.n,
   `${S.corpus.epitaphsLatin} of ${S.corpus.epitaphsAllLanguages}`);
ok('EDH record count matches the database\'s own published figure',
   S.corpus.edhRecords === 81882);
ok('licence recorded as CC BY-SA 4.0', S.corpus.licence === 'CC BY-SA 4.0');

// -- the law
ok('the law has nine sharedness bands', S.law.length === 9);
let monoA = true, monoC = true;
for (let i = 1; i < S.law.length; i++) {
  if (S.law[i].abbrev <= S.law[i - 1].abbrev) monoA = false;
  if (S.law[i].carved >= S.law[i - 1].carved) monoC = false;
}
let mono8 = true;
for (let i = 1; i < S.law.length - 1; i++) if (S.law[i].abbrev <= S.law[i - 1].abbrev) mono8 = false;
ok('abbreviation rate rises without reversal across the first eight bands', mono8,
   S.law.slice(0, 8).map(b => b.abbrev + '%').join(' < '));
ok('the ninth band dips, and stats.json says so rather than claiming monotone',
   S.law[8].abbrev < S.law[7].abbrev && S.lawMonotone === false &&
   S.lawMonotoneFirstEight === true, `${S.law[7].abbrev}% then ${S.law[8].abbrev}%`);
ok('the dip is a composition effect: excluding words under four letters restores the order',
   S.topBandDip.band9Long.abbrev > S.topBandDip.band8Long.abbrev,
   `${S.topBandDip.band8Long.abbrev}% then ${S.topBandDip.band9Long.abbrev}%`);
ok('the ninth band really is dominated by shorter words',
   S.topBandDip.band9All.meanLen < S.topBandDip.band8All.meanLen);
ok('"et" is the two-letter word that drags the top band down',
   S.topBandDip.etLetters === 2 && S.topBandDip.etAbbrev < 1 && S.topBandDip.etStones > 5000);
ok('carved-letter fraction falls across every band, no inversion', monoC);
ok('stats.json agrees with itself that the law is monotone', S.lawMonotone === monoA);
ok('the bands partition the frequency range without a gap',
   S.law.every((b, i) => i === 0 || b.lo === S.law[i - 1].hi + 1));
ok('band occurrence counts sum to the corpus word instances',
   S.law.reduce((a, b) => a + b.occ, 0) === S.corpus.wordInstances,
   `${S.law.reduce((a, b) => a + b.occ, 0)} = ${S.corpus.wordInstances}`);
ok('band type counts sum to the corpus word types',
   S.law.reduce((a, b) => a + b.types, 0) === S.corpus.wordTypes);

// -- the length control
let rowsOK = 0, rowsTested = 0;
for (const row of S.lengthControl) {
  const v = row.cells.filter(Boolean).map(c => c.abbrev);
  if (v.length >= 3) { rowsTested++; if (v.every((x, i) => i === 0 || v[i - 1] <= x)) rowsOK++; }
}
ok('the length control is monotone in every populated row',
   rowsOK === rowsTested && rowsTested === S.lengthControlMonotone.rows,
   `${rowsOK}/${rowsTested}`);
ok('stats.json agrees on the length-control tally',
   S.lengthControlMonotone.monotone === rowsOK);

// -- the name slots
ok('praenomen is a closed slot: ten forms cover almost all of it',
   S.nameSlots.praenomenTop10Share > 95);
ok('cognomen is an open slot: ten forms cover almost none of it',
   S.nameSlots.cognomenTop10Share < 15);
ok('praenomen entropy far below cognomen entropy',
   S.nameSlots.cognomenBitsMM - S.nameSlots.praenomenBitsMM > 6,
   `${S.nameSlots.praenomenBitsMM} vs ${S.nameSlots.cognomenBitsMM} bits`);
ok('the Miller-Madow correction only ever raises the plug-in entropy',
   S.nameSlots.praenomenBitsMM >= S.nameSlots.praenomenBits &&
   S.nameSlots.cognomenBitsMM >= S.nameSlots.cognomenBits);
ok('praenomen abbreviated far more often than cognomen',
   S.praenomen.abbrev - S.cognomen.abbrev > 50,
   `${S.praenomen.abbrev}% vs ${S.cognomen.abbrev}%`);
ok('the closed slot has fewer letters cut than the open one',
   S.praenomen.meanLettersCut < S.cognomen.meanLettersCut);

// -- surprisal vs carving, corrected specification
const U = S.surprisal, T = S.slotTest;
ok('the carved fraction is nearly independent of word length, unlike mean letters cut',
   T.token.lenOnly < 0.05 && T.token.oldDVlen > 0.3,
   `logit(fraction) R2 ${T.token.lenOnly} vs mean-letters R2 ${T.token.oldDVlen}`);
ok('surprisal predicts the carved fraction', T.token.surprisalOnly > 0.2,
   `R2 ${T.token.surprisalOnly}`);
ok('surprisal keeps its full slope when length enters the model',
   T.token.slopeKept >= 95, `${T.token.slopeKept}% of the slope`);
ok('frequency is estimated on held-out stones, not the ones being predicted',
   T.heldOutTypes > 5000 && T.heldOutTokens > 100000,
   `${T.heldOutTypes} types, ${T.heldOutTokens} tokens`);
ok('the type-weighted version is much weaker and the page prints it rather than hiding it',
   T.type.joint < T.token.joint / 3, `${T.type.joint} vs ${T.token.joint}`);
ok('surprisal predicts carving within every word length tested',
   U.byLen.length >= 8 && U.byLen.every(r => r.slope > 0), `${U.byLen.length} lengths`);
ok('and within every word length with all attested names deleted',
   U.byLenNonName.length >= 8 && U.byLenNonName.every(r => r.slope > 0));
ok('the name-form lexicon deleted is the whole of EDH prosopography',
   U.nameFormsInEDH > 40000, `${U.nameFormsInEDH} forms`);

// -- the slot test: the level the coincidence actually lived on
ok('the slot test covers enough grammatical slots to be worth running',
   T.allSlots.n >= 8, `${T.allSlots.n} slots`);
ok('letters per bit is NOT constant across slots, by the agreed criterion',
   T.bigSlots.cv > T.killCriterionCV,
   `CV ${T.bigSlots.cv} against a threshold of ${T.killCriterionCV}`);
ok('the surviving slots still span a wide range', T.bigSlots.spread > 2,
   `${T.bigSlots.min} to ${T.bigSlots.max}, ${T.bigSlots.spread}x`);
ok('slots are reported in ascending order of rate',
   T.slots.every((r, i) => i === 0 || T.slots[i - 1].perBit <= r.perBit));
ok('the two name slots the page noticed sit at the bottom of that range',
   T.slots[0].slot.includes('nomen') && T.slots[1].slot.includes('nomen'),
   `${T.slots[0].slot} ${T.slots[0].perBit}, ${T.slots[1].slot} ${T.slots[1].perBit}`);
ok('the near-zero-entropy slot is excluded from the headline, and said to be',
   T.bigSlots.n === T.allSlots.n - 1 && T.bigSlots.minBits >= 1);

// -- the ages// -- the ages
const mean = S.ages.djPerDecade.reduce((a, b) => a + b, 0) / S.ages.djPerDecade.length;
ok('Duncan-Jones index recomputes from its four decade percentages',
   near((mean - 20) * 1.25, S.ages.djIndex, 0.15),
   `(${mean.toFixed(2)} - 20) x 1.25 = ${((mean - 20) * 1.25).toFixed(1)}`);
ok('the published mean percentage matches the decade percentages',
   near(mean, S.ages.djMeanPct, 0.15));
ok('rounding intensifies decade by decade, as Duncan-Jones states',
   S.ages.djPerDecade.every((x, i) => i === 0 || S.ages.djPerDecade[i - 1] < x),
   S.ages.djPerDecade.join(' < '));
ok('Whipple index is five times the percentage divisible by five',
   near(S.ages.whipple, S.ages.pctMultipleOf5 * 5, 0.6),
   `${S.ages.whipple} vs ${(S.ages.pctMultipleOf5 * 5).toFixed(1)}`);
ok('Whipple index is far beyond the UN "very rough" threshold of 175',
   S.ages.whipple > 175);
const digitSum = S.ages.terminalDigits.reduce((a, b) => a + b, 0);
ok('terminal digit shares sum to 100', near(digitSum, 100, 0.6), digitSum.toFixed(2));
ok('the 0 and 5 digits dominate every other digit',
   S.ages.terminalDigits.every((v, i) => (i === 0 || i === 5) || v < S.ages.terminalDigits[5]));
ok('digits 0 and 5 together match the published multiple-of-five share',
   near(S.ages.terminalDigits[0] + S.ages.terminalDigits[5], S.ages.pctMultipleOf5, 0.3));
ok('our index exceeds Duncan-Jones\'s Italian civilian figure, as the provincial skew predicts',
   S.ages.djIndex > S.ages.djReference.italyCivilianMales);
ok('every province index is computed on at least 80 ages in span',
   S.ages.byProvince.every(p => p.n >= 80));
ok('province indices are returned in ascending order',
   S.ages.byProvince.every((p, i) => i === 0 || S.ages.byProvince[i - 1].index <= p.index));

// -- the control
const cs = S.control.service_3_27, ca = S.control.ageOnSameStones_23_62;
ok('service years are far less rounded than ages on the same stones',
   ca.pct - cs.pct > 30, `${cs.pct}% vs ${ca.pct}%`);
ok('service years nevertheless exceed the 20% no-rounding baseline',
   cs.pct > S.control.expectedIfUnrounded);
ok('our service figure is honestly above Duncan-Jones\'s three',
   cs.pct > Math.max(...Object.values(S.control.duncanJones_service_3_27)));
ok('both control samples are large enough to report', cs.n > 300 && ca.n > 300);

// -- precision
const P = S.precision.bands;
ok('the precision gradient falls from the 20-39 band to the 40-plus band',
   P[P.length - 1].days < P[P.length - 2].days,
   `${P[P.length - 2].days}% -> ${P[P.length - 1].days}%`);
ok('months are given more often than days in every band',
   P.every(b => b.months >= b.days));
ok('days are given more often than hours in every band',
   P.every(b => b.days >= b.hours));
ok('the hour-counting stones are a handful and mostly children',
   S.precision.hourStones < 40 && S.precision.hourUnderFive > 0,
   `${S.precision.hourStones} stones, ${S.precision.hourUnderFive} under five`);
ok('hour ids listed match the hour count',
   S.precision.hourIds.length === S.precision.hourStones);

// -- the packed stones
let words = 0, bad = 0, gold = 0, maxdf = 0;
for (const st of C.stones) {
  for (const line of st.lines) for (const tk of line) {
    words++;
    if (!tk.seg || !tk.seg.length) bad++;
    if (tk.df < 0 || tk.df > C.n) bad++;
    if (!tk.seg.every(s => ['cut', 'ex', 'sup', 'supex'].includes(s[1]))) bad++;
    if (tk.nm) gold++;
    if (tk.df > maxdf) maxdf = tk.df;
  }
}
ok('every packed word has valid segments and a frequency in range', bad === 0,
   `${words} words across ${C.stones.length} stones`);
ok('some packed words are marked as names', gold > 100, `${gold} name words`);
ok('the commonest packed word frequency does not exceed the corpus',
   maxdf <= C.n && maxdf > 1000, `max df ${maxdf}`);
ok('the frequency table carries 400 head words', C.top.length === 400);
ok('the head word list is sorted by descending frequency',
   C.top.every((r, i) => i === 0 || C.top[i - 1][1] >= r[1]));
ok('the commonest word in the table is the commonest in the stats',
   C.top[0][0] === S.topWords[0].w && C.top[0][1] === S.topWords[0].stones,
   `${C.top[0][0]} on ${C.top[0][1]} stones`);
ok('top-word shares agree with the stone counts and corpus size',
   S.topWords.every(r => near(r.share, 100 * r.stones / C.n, 0.02)));
ok('lexical concentration rises with the number of words counted',
   [10, 20, 50, 100, 200, 500].every((k, i, a) =>
     i === 0 || S.concentration[a[i - 1]] <= S.concentration[k]));

// ===================================================================== Part B
const haveXml = existsSync(XMLDIR) && readdirSync(XMLDIR).length > 1000;
if (!haveXml) {
  console.log('\nPart B — skipped: raw EpiDoc dump not present (run fetch.mjs for the full pass)');
} else {
  console.log('\nPart B — re-parsing the raw EpiDoc with a second implementation');

  // An independent parser. Where the Python walks an ElementTree recursively,
  // this scans the edition markup as a token stream and tracks two flags.
  const SKIP = new Set(['head', 'note', 'certainty', 'am', 'g', 'del', 'surplus']);
  // The edition div nests <div type="textpart"> children, so the closing tag has
  // to be found by depth rather than by the first </div>.
  function editionBody(xml) {
    const start = xml.indexOf('<div type="edition"');
    if (start < 0) return null;
    const open = xml.indexOf('>', start);
    if (open < 0) return null;
    let depth = 1, i = open + 1;
    const re = /<(\/?)div\b[^>]*?(\/?)>/g;
    re.lastIndex = i;
    let m;
    while ((m = re.exec(xml)) !== null) {
      if (m[2] === '/') continue;             // self-closing div, not a real nest
      depth += m[1] === '/' ? -1 : 1;
      if (depth === 0) return xml.slice(open + 1, m.index);
    }
    return null;
  }
  function parseEdition(xml) {
    const body = editionBody(xml);
    if (body === null) return null;
    const words = [];
    let cur = [];           // [text, kind]
    let supDepth = 0, exDepth = 0, skipDepth = 0;
    const flush = () => { if (cur.length) words.push(cur); cur = []; };
    const add = (text, kind) => {
      for (const ch of text) {
        if (/\p{L}/u.test(ch)) {   // any Unicode letter, matching Python's str.isalpha()
          if (cur.length && cur[cur.length - 1][1] === kind) cur[cur.length - 1][0] += ch;
          else cur.push([ch, kind]);
        } else flush();
      }
    };
    const re = /<\/?([a-zA-Z]+)([^>]*)>|([^<]+)/g;
    let t;
    while ((t = re.exec(body)) !== null) {
      if (t[3] !== undefined) {
        if (skipDepth) continue;
        // EDH escapes its own "<a=B>" correction notation twice, so it arrives
        // here as "&amp;lt;a=B&amp;gt;". Keep the editor's reading, drop the notation.
        let text = t[3].replace(/&amp;lt;([^=&<>]*)(?:=[^&<>]*)?&amp;gt;/g, (_x, keep) => keep);
        text = text.replace(/&amp;/g, '&').replace(/&lt;/g, '<').replace(/&gt;/g, '>');
        add(text, supDepth ? (exDepth ? 'supex' : 'sup') : (exDepth ? 'ex' : 'cut'));
        continue;
      }
      const tag = t[1], attrs = t[2] || '', closing = t[0][1] === '/';
      const selfClose = attrs.endsWith('/');
      if (tag === 'lb') { if (!/break="no"/.test(attrs)) flush(); continue; }
      if (tag === 'gap') { flush(); continue; }
      if (SKIP.has(tag)) {
        if (selfClose) continue;
        skipDepth += closing ? -1 : 1;
        if (skipDepth < 0) skipDepth = 0;
        continue;
      }
      if (skipDepth) continue;
      // A self-closing <ex/> or <supplied/> opens and shuts in one tag: changing
      // the depth for it would mark the whole rest of the text as editorial.
      if (!selfClose) {
        if (tag === 'supplied') { supDepth += closing ? -1 : 1; if (supDepth < 0) supDepth = 0; }
        if (tag === 'ex') { exDepth += closing ? -1 : 1; if (exDepth < 0) exDepth = 0; }
      }
      if (tag === 'ab' && closing) flush();
    }
    flush();
    return words;
  }

  const ROMAN = /^[IVXLCDM]+$/;
  const norm = w => w.toLowerCase().replace(/j/g, 'i').replace(/v/g, 'u');
  const wtext = w => w.map(s => s[0]).join('');
  const isAbbrev = w => w.some(s => s[1] === 'ex' || s[1] === 'supex');
  const cutOf = w => w.filter(s => s[1] === 'cut').reduce((a, s) => a + s[0].length, 0);

  // which epitaphs are Latin, from the CSV (a simple quoted-field scan)
  const csv = readFileSync(join(here, 'data/edh_data_text.csv'), 'utf8');
  const latin = new Set();
  {
    // hd_nr is column 0, nl_text is a named column; find its index from the header
    const headerEnd = csv.indexOf('\n');
    const header = csv.slice(0, headerEnd).split(',');
    const iLang = header.indexOf('nl_text');
    let i = headerEnd + 1, field = 0, cell = '', q = false, hd = '';
    for (; i < csv.length; i++) {
      const ch = csv[i];
      if (q) { if (ch === '"') { if (csv[i + 1] === '"') { cell += '"'; i++; } else q = false; } else cell += ch; continue; }
      if (ch === '"') { q = true; continue; }
      if (ch === ',') { if (field === 0) hd = cell; if (field === iLang && cell === 'L') latin.add(hd); field++; cell = ''; continue; }
      if (ch === '\n') { if (field === iLang && cell === 'L') latin.add(hd); field = 0; cell = ''; hd = ''; continue; }
      cell += ch;
    }
  }
  ok('the Latin filter is read independently from the CSV', latin.size > 20000,
     `${latin.size} Latin texts of all genres`);

  const files = readdirSync(XMLDIR).filter(f => f.endsWith('.xml'));
  const df = new Map(), occ = new Map(), abb = new Map(), cutL = new Map(), fullL = new Map();
  let nLatinEpitaph = 0, nEpitaph = 0, instances = 0;
  const bump = (m, k, v = 1) => m.set(k, (m.get(k) || 0) + v);
  for (const f of files) {
    const xml = readFileSync(join(XMLDIR, f), 'utf8');
    if (!xml.includes('>epitaph<')) continue;
    const hd = f.slice(0, -4);
    const words = parseEdition(xml);
    if (!words || !words.length) continue;
    nEpitaph++;                       // an epitaph with a readable edition, any language
    if (!latin.has(hd)) continue;
    const keep = words.filter(w => /^[A-Za-z]+$/.test(wtext(w)));
    if (!keep.length) continue;
    nLatinEpitaph++;
    const seen = new Set();
    for (const w of keep) {
      const s = wtext(w);
      if (ROMAN.test(s)) continue;
      const n = norm(s);
      instances++;
      bump(occ, n);
      if (isAbbrev(w)) bump(abb, n);
      bump(cutL, n, cutOf(w));
      bump(fullL, n, s.length);
      if (!seen.has(n)) { seen.add(n); bump(df, n); }
    }
  }

  ok('independent parser finds the same number of epitaphs in all languages',
     nEpitaph === S.corpus.epitaphsAllLanguages, `${nEpitaph} vs ${S.corpus.epitaphsAllLanguages}`);
  ok('independent parser finds the same number of Latin epitaphs',
     nLatinEpitaph === S.corpus.epitaphsLatin, `${nLatinEpitaph} vs ${S.corpus.epitaphsLatin}`);
  ok('independent parser finds the same word-instance total',
     instances === S.corpus.wordInstances, `${instances} vs ${S.corpus.wordInstances}`);
  ok('independent parser finds the same number of word types',
     df.size === S.corpus.wordTypes, `${df.size} vs ${S.corpus.wordTypes}`);

  for (const r of S.topWords.slice(0, 12)) {
    ok(`"${r.w}" agrees on stones, abbreviation rate and carved fraction`,
       df.get(r.w) === r.stones &&
       near(100 * abb.get(r.w) / occ.get(r.w), r.abbrev, 0.05) &&
       near(100 * cutL.get(r.w) / fullL.get(r.w), r.carved, 0.05),
       `${df.get(r.w)} stones, ${(100 * abb.get(r.w) / occ.get(r.w)).toFixed(1)}% abbrev`);
  }

  // rebuild the law bands from the independent parse
  const BANDS = S.law.map(b => [b.lo, b.hi]);
  BANDS.forEach(([lo, hi], i) => {
    let o = 0, a = 0, cl = 0, fl = 0, types = 0;
    for (const [w, c] of df) if (c >= lo && c <= hi) {
      types++; o += occ.get(w); a += abb.get(w) || 0; cl += cutL.get(w); fl += fullL.get(w);
    }
    ok(`band ${lo}-${hi} agrees on types, abbreviation rate and carved fraction`,
       types === S.law[i].types && near(100 * a / o, S.law[i].abbrev, 0.05) &&
       near(100 * cl / fl, S.law[i].carved, 0.05),
       `${types} types, ${(100 * a / o).toFixed(1)}% abbrev`);
  });

  // the source dumps are the ones we published against
  const HASHES = {
    'edh_data_text.csv': '2346db8c1b578ae09c00f29222fe852b420c502bf80265a62d06e7aa2645643f',
    'edh_data_pers.csv': '990ae11cd8fbc858d9b77c9dfca93577d243f2d5f03eab47cb56016268a6dfcd',
  };
  for (const [f, want] of Object.entries(HASHES)) {
    const p = join(here, 'data', f);
    if (!existsSync(p)) { ok(`${f} present for hashing`, false); continue; }
    const got = createHash('sha256').update(readFileSync(p)).digest('hex');
    ok(`${f} is the published dump`, got === want, got.slice(0, 16));
  }
}

// ===================================================================== Part C
console.log('\nPart C — the page carries exactly these artefacts');
const html = readFileSync(PAGE, 'utf8');
const prose = html.replace(/\s+/g, ' ');
const slot = id => {
  const m = html.match(new RegExp(`<script id="${id}" type="application/json">([\\s\\S]*?)</script>`));
  return m ? m[1] : null;
};
const embeddedCorpus = slot('corpus-data');
const embeddedStats = slot('stats-data');
ok('the page has both data slots', !!embeddedCorpus && !!embeddedStats);
ok('embedded corpus is byte-identical to corpus.json',
   embeddedCorpus === readFileSync(join(here, 'corpus.json'), 'utf8').trim());
ok('embedded stats is byte-identical to stats.json',
   embeddedStats === readFileSync(join(here, 'stats.json'), 'utf8').trim());
ok('the embedded JSON parses', (() => { try { JSON.parse(embeddedCorpus); JSON.parse(embeddedStats); return true; } catch { return false; } })());

// every hard-coded figure in the prose must match the artefacts
const proseChecks = [
  ['26,108', S.corpus.epitaphsLatin.toLocaleString('en-US')],
  ['81,882', S.corpus.edhRecords.toLocaleString('en-US')],
  ['229', String(S.stones)],
  ['26,107', (S.corpus.epitaphsLatin - 1).toLocaleString('en-US')],
];
for (const [needle, expect] of proseChecks) {
  ok(`the prose figure ${needle} matches the artefacts`,
     needle === expect && prose.includes(needle), `expected ${expect}`);
}
ok('the page cites Duncan-Jones 1977 with the right pages',
   prose.includes('Chiron</i> 7 (1977) 333-354'));
ok('the page cites Hopkins 1966 with its DOI',
   prose.includes('10.1080/00324728.1966.10406097'));
ok('the page cites Piantadosi, Tily and Gibson 2011 with its DOI',
   prose.includes('10.1073/pnas.1012551108'));
ok('the page credits EDH and its licence',
   prose.includes('CC BY-SA 4.0') && prose.includes('Epigraphic Database Heidelberg'));
ok('the page quotes Hopkins verbatim on discarding the ages',
   prose.includes('must be discarded as useful evidence for estimating life expectation'));
ok('the page states the corpus is provincial, not the whole Roman world',
   prose.includes('provinces of the Roman Empire'));
ok('the page names the service control as an imperfect replication',
   prose.includes('not a clean replication'));
ok('the page drops the letters-per-bit coincidence on the right test',
   prose.includes('It is not constant.'));
ok('the page owns the category error it published for an hour',
   prose.includes('did exactly that for about an hour after it first went up'));
ok('the page does not claim the 2011 contextual refinement, only Zipf',
   prose.includes("this measures Zipf's 1949 law of abbreviation, not the 2011") ||
   prose.includes('not the 2011 refinement'));
ok('the page prints the weak type-weighted number next to the strong one',
   prose.includes('The vocabulary as a list barely shows it'));
ok('the page reports the ninth-band dip in its own prose',
   prose.includes('dips slightly in the ninth'));
ok('closing tags are present (the silent-script bug)',
   html.trimEnd().endsWith('</html>') && html.includes('</script>\n</body>'));

console.log(`\n${fail === 0 ? 'PASS' : 'FAIL'}  ${pass}/${pass + fail}` +
            (haveXml ? '  (full: raw EpiDoc re-parsed)' : '  (--no-net: artefacts only)'));
process.exit(fail === 0 ? 0 : 1);
