// verify.mjs: the check for "No Beat Twice".
//
//   node research/rhythmic-canons/verify.mjs
//   node research/rhythmic-canons/verify.mjs --page=<dir> --data=<dir>
//
// Offline, deterministic, no network, no clock. It re-derives with its own
// arithmetic wherever it can, and only then asserts the shipped bytes. Seven
// families:
//
//   A  the engine, against facts checkable by hand
//   B  the census, re-derived a THIRD way: brute force over every subset, no
//      seed trick, no canonical-form reasoning. If the clever sweep lost a
//      rhythm this finds it.
//   C  the shortcut that makes the 72-beat sweep tractable, shown to prune
//      nothing: over every n it can be tested on, no tiling rhythm is rejected
//   D  the eighteen canons of 72, each rebuilt from its two sets
//   E  the sweep summary, including the filtered and unfiltered runs agreeing
//   F  the shipped bytes: byte identity of the engine, SHA-256 of every file
//   G  the prose: every figure on the page and in the frontmatter came from a
//      computation, and the page states its hedges
//
// --page= and --data= let mutate.mjs aim this verifier at a DEFECTIVE COPY of
// the artefacts. Without that, "can it go red" is answered by assertions about
// assertions, which is not an answer.

import fs from 'node:fs';
import path from 'node:path';
import crypto from 'node:crypto';
import { fileURLToPath } from 'node:url';
import {
  tiles, complementClasses, someComplement, canonical, isPeriodic, period,
  obstruction, spectrumSA, satisfiesT1, satisfiesT2, dividesCyclotomic,
  cyclotomic, divisors, primePowersDividing, dividesPrimePower, eachComplement,
} from './canons.mjs';

const HERE = path.dirname(fileURLToPath(import.meta.url));
const ROOT = path.join(HERE, '..', '..');
const arg = (k, d) => { const h = process.argv.find((a) => a.startsWith(k)); return h ? h.slice(k.length) : d; };
const PAGE = path.resolve(arg('--page=', path.join(ROOT, 'public/strata/no-beat-twice')));
const DATA = path.resolve(arg('--data=', path.join(HERE, 'data')));
const MD = path.resolve(arg('--md=', path.join(ROOT, 'src/content/strata/no-beat-twice.md')));

let pass = 0; const failures = [];
const check = (name, cond, detail = '') => {
  if (cond) { pass++; } else { failures.push(name + (detail ? '  ·  ' + detail : '')); }
};
const eq = (name, got, want) => check(name, got === want, `got ${got}, want ${want}`);

const D = JSON.parse(fs.readFileSync(path.join(DATA, 'canons.json'), 'utf8'));
const html = fs.readFileSync(path.join(PAGE, 'index.html'), 'utf8');
const md = fs.readFileSync(MD, 'utf8');

// =========================================================== A. the engine
// Facts a reader can check on paper, so a broken engine cannot hide.
check('A1 three in a row tile a twelve beat cycle', tiles([0, 1, 2], 12) === true);
check('A2 and the only way is four voices a quarter turn apart',
  JSON.stringify(complementClasses([0, 1, 2], 12).list) === JSON.stringify([[0, 3, 6, 9]]));
check('A3 {0,1,3} does not tile twelve', tiles([0, 1, 3], 12) === false);
check('A4 the tresillo does not tile eight', tiles([0, 3, 6], 8) === false);
check('A5 a rhythm whose size does not divide n cannot tile', tiles([0, 1, 2, 3, 4], 12) === false);
check('A6 every singleton tiles', [8, 12, 15].every((n) => tiles([0], n) === true));
check('A7 the whole cycle tiles', [8, 12].every((n) => tiles([...Array(n).keys()], n) === true));
// periodicity, by hand
eq('A8 period of {0,1,6,7} in 12', period([0, 1, 6, 7], 12), 6);
eq('A9 period of {0,1,2} in 12', period([0, 1, 2], 12), 12);
check('A10 {0,3,6,9} in 12 is periodic', isPeriodic([0, 3, 6, 9], 12) === true);
// canonical form is rotation invariant and idempotent
{
  let ok = true;
  for (let n = 6; n <= 20; n++) for (let m = 1; m < (1 << Math.min(n, 12)); m++) {
    const A = []; for (let i = 0; i < Math.min(n, 12); i++) if ((m >> i) & 1) A.push(i);
    const c = canonical(A, n);
    if (canonical(c, n).join() !== c.join()) { ok = false; break; }
    const t = A.map((a) => (a + 3) % n).sort((x, y) => x - y);
    if (canonical(t, n).join() !== c.join()) { ok = false; break; }
  }
  check('A11 canonical form is idempotent and rotation invariant', ok);
}
// cyclotomic polynomials, against values anyone can look up
eq('A12 Phi_1', cyclotomic(1).join(','), '-1,1');
eq('A13 Phi_2', cyclotomic(2).join(','), '1,1');
eq('A14 Phi_6', cyclotomic(6).join(','), '1,-1,1');
eq('A15 Phi_12', cyclotomic(12).join(','), '1,0,-1,0,1');
eq('A16 Phi_105 is the first cyclotomic polynomial with a coefficient outside -1..1, and has two of them',
  cyclotomic(105).filter((c) => Math.abs(c) > 1).join(','), '-2,-2');
check('A16b and no smaller one does',
  [...Array(104).keys()].slice(1).every((d) => cyclotomic(d).every((c) => Math.abs(c) <= 1)));
// the product of all Phi_d over d | n is x^n - 1
{
  let ok = true;
  for (let n = 1; n <= 24 && ok; n++) {
    let prod = [1];
    for (const d of divisors(n)) {
      const q = cyclotomic(d), out = new Array(prod.length + q.length - 1).fill(0);
      for (let i = 0; i < prod.length; i++) for (let j = 0; j < q.length; j++) out[i + j] += prod[i] * q[j];
      prod = out;
    }
    const want = new Array(n + 1).fill(0); want[0] = -1; want[n] = 1;
    if (prod.join(',') !== want.join(',')) ok = false;
  }
  check('A17 the cyclotomic polynomials of the divisors of n multiply to x^n - 1', ok);
}
// the prime-power shortcut agrees with honest polynomial division
{
  let ok = true, tested = 0;
  for (const n of [8, 12, 16, 18, 24, 36]) {
    for (let m = 1; m < (1 << 10); m++) {
      const A = []; for (let i = 0; i < 10; i++) if ((m >> i) & 1) A.push(i % n);
      const set = [...new Set(A)].sort((a, b) => a - b);
      for (const { m: s, p } of primePowersDividing(n)) {
        tested++;
        if (dividesPrimePower(set, s, p) !== dividesCyclotomic(set, s)) ok = false;
      }
      if (!ok) break;
    }
  }
  check('A18 the coset test for a prime power agrees with polynomial division', ok, `${tested} pairs`);
}

// =========================================================== B. brute force
// The dumbest possible census: every subset of Z_n, no seeds, no canonical
// reasoning, decided one at a time. It must reproduce the table.
function bruteCensus(n) {
  const sets = new Set(); let ordered = 0;
  const all = [];
  for (let mask = 1; mask < (1 << n); mask++) {
    const A = []; for (let i = 0; i < n; i++) if ((mask >> i) & 1) A.push(i);
    if (A.length < 2 || A.length >= n || n % A.length) continue;
    if (!tiles(A, n)) continue;
    all.push(A);
    sets.add(canonical(A, n).join(','));
  }
  // ordered pairs of classes: for each tiling class A, count its complement classes
  for (const key of sets) {
    const A = key.split(',').map(Number);
    ordered += complementClasses(A, n).list.length;
  }
  return { sets: sets.size, ordered };
}
for (const n of [6, 8, 9, 10, 12, 14, 15, 16, 18, 20]) {
  const b = bruteCensus(n);
  const row = D.table.find((r) => r.n === n);
  eq(`B ${n} brute force finds the same number of tiling rhythms`, b.sets, row.factorSetClasses);
  eq(`B ${n} brute force finds the same number of canons`, b.ordered, row.orderedClassPairs);
}

// =========================================================== C. the shortcut
// The 72-beat sweep skips a rhythm when a cyclotomic factor that has nowhere
// else to go fails to divide it. If that argument were wrong, the sweep would
// have missed canons. Test it the only way that settles it: on every n where a
// full census exists, no rhythm that tiles may be rejected by the filter.
{
  let rejectedTilers = 0, examined = 0;
  for (let n = 4; n <= 30; n++) {
    for (let mask = 1; mask < (1 << n) && n <= 20; mask++) {
      const A = []; for (let i = 0; i < n; i++) if ((mask >> i) & 1) A.push(i);
      if (A.length < 2 || A.length >= n || n % A.length) continue;
      examined++;
      const ob = obstruction(A, n);
      if (ob.reason === 'cyclotomic' && tiles(A, n)) rejectedTilers++;
    }
  }
  eq('C1 the cyclotomic filter never rejects a rhythm that tiles', rejectedTilers, 0);
  check('C2 the filter test actually looked at something', examined > 100000, `${examined} rhythms`);
  // and it is not vacuous: it must reject a great many rhythms that do not tile
  let rejected = 0, total = 0;
  for (let mask = 1; mask < (1 << 24); mask += 7919) {
    const A = []; for (let i = 0; i < 24; i++) if ((mask >> i) & 1) A.push(i);
    if (A.length < 2 || A.length >= 24 || 24 % A.length) continue;
    total++;
    if (obstruction(A, 24).reason === 'cyclotomic') rejected++;
  }
  check('C3 the filter is not vacuous', rejected > total * 0.5, `${rejected} of ${total} rejected at n=24`);
}
// the two lemmas the filter rests on, checked directly
{
  let ok = true;
  for (const n of [12, 16, 18, 24, 36]) {
    for (let mask = 1; mask < (1 << 12); mask++) {
      const A = []; for (let i = 0; i < 12; i++) if ((mask >> i) & 1) A.push(i);
      for (const { m, p } of primePowersDividing(n)) {
        if (dividesPrimePower(A, m, p) && A.length % p !== 0) ok = false;
      }
    }
  }
  check('C4 lemma: if the cyclotomic factor of p^k divides a rhythm, p divides its size', ok);
}

// =========================================================== D. the 72 canons
{
  const A3 = D.at72.aperiodicRhythms, B6 = D.at72.aperiodicPartners;
  eq('D1 three aperiodic rhythms at 72', A3.length, 3);
  eq('D2 six aperiodic partners at 72', B6.length, 6);
  let good = 0, bad = [];
  for (const A of A3) for (const B of B6) {
    const hit = new Array(72).fill(0);
    for (const a of A) for (const b of B) hit[(a + b) % 72]++;
    if (hit.every((h) => h === 1) && !isPeriodic(A, 72) && !isPeriodic(B, 72)) good++;
    else bad.push(`${A} / ${B}`);
  }
  eq('D3 all eighteen pairings cover every one of the 72 beats exactly once, both sides aperiodic', good, 18);
  check('D4 none of the eighteen is defective', bad.length === 0, bad.slice(0, 2).join(' | '));
  eq('D5 the canon count on the page is the product', D.at72.canonClassPairs, 18);
  // each rhythm really is a size 6 aperiodic set, each partner size 12
  check('D6 the three rhythms have six onsets each and no period',
    A3.every((A) => A.length === 6 && !isPeriodic(A, 72)));
  check('D7 the six partners have twelve entries each and no period',
    B6.every((B) => B.length === 12 && !isPeriodic(B, 72)));
  // rebuild the rhythms from scratch: search Z_72 for aperiodic six-sets with an
  // aperiodic complement, using the transversal structure the page describes
  // The lab's C sweep and this file pick different representatives of a
  // rotation class (C takes the smallest bitmask, canons.mjs the smallest sorted
  // tuple), so compare classes, not representatives.
  const found = new Set();
  for (const A of A3) {
    const { list, truncated } = complementClasses(A, 72, 4096);
    check('D8a the partner search for a 72-beat rhythm finished', !truncated);
    for (const B of list) if (!isPeriodic(B, 72)) found.add(canonical(B, 72).join(','));
  }
  eq('D8 re-searching the three rhythms recovers exactly the six partners', found.size, 6);
  check('D9 and they are the same six, compared as rotation classes',
    [...found].sort().join(' | ') === B6.map((b) => canonical(b, 72).join(',')).sort().join(' | '));
  // the cyclotomic split, divisor for divisor, against the unsigned enumeration
  const dvA = [...new Set(A3.map((A) => divisors(72).filter((d) => d > 1 && dividesCyclotomic(A, d)).join(',')))];
  const dvB = [...new Set(B6.map((B) => divisors(72).filter((d) => d > 1 && dividesCyclotomic(B, d)).join(',')))];
  eq('D10 all three rhythms carry the same cyclotomic divisors', dvA.length, 1);
  eq('D11 all six partners carry the same cyclotomic divisors', dvB.length, 1);
  eq('D12 the rhythms carry the unsigned enumeration\'s complement divisors', dvA[0], '3,4,6,12,24,36');
  eq('D13 the partners carry the unsigned enumeration\'s motif divisors', dvB[0], '2,8,9,18,72');
  check('D14 and the two sets partition the divisors of 72 above one',
    [...dvA[0].split(','), ...dvB[0].split(',')].map(Number).sort((a, b) => a - b).join(',')
    === divisors(72).filter((d) => d > 1).join(','));
  check('D15 the page records the match rather than asserting it', D.at72.enumerationDivisorSetsMatch === true);
  // (T1) holds on both sides, as Coven and Meyerowitz require of anything that tiles
  check('D16 (T1) holds for every one of the nine sets', [...A3, ...B6].every((S) => satisfiesT1(S, 72)));
  check('D17 (T2) holds for every one of the nine sets', [...A3, ...B6].every((S) => satisfiesT2(S, 72).holds));
}

// =========================================================== E. the sweeps
{
  const raw = (f) => fs.readFileSync(path.join(DATA, f), 'utf8').split('\n').filter((l) => l.startsWith('{')).map((l) => JSON.parse(l));
  const sweep = raw('vuza-sweep-raw.txt').filter((o) => o.mode);
  eq('E1 the sweep covers every cycle length from 2 to 71', sweep.length, 70);
  check('E2 it runs 2 to 71 with no gap', sweep.every((o, i) => o.n === i + 2));
  check('E3 every one of them finished', sweep.every((o) => o.complete));
  // Do not take the flag's word for it. census.c sets `complete` from the cap
  // counters, so the two must agree; if they ever disagree the record has been
  // edited, not computed. (The mutation harness found this gap, 2026-08-16.)
  eq('E3a no sweep hit a per-seed cap', sweep.reduce((a, o) => a + o.cappedSeeds, 0), 0);
  check('E3b the completeness flag agrees with the cap counter it is derived from',
    sweep.every((o) => o.complete === (o.cappedSeeds === 0)));
  eq('E4 not one canon below 72 has two aperiodic sides', sweep.reduce((a, o) => a + o.vuzaOrderedClassPairs, 0), 0);
  eq('E5 the page quotes the true number of candidates swept', D.sweep.seedsScanned, sweep.reduce((a, o) => a + o.seeds, 0));
  eq('E6 and the true number of aperiodic rhythms that do tile', D.sweep.aperiodicTilingSeedClasses, sweep.reduce((a, o) => a + o.vuzaSeedClasses, 0));
  check('E7 the sweep really searched: the biggest single length scanned over 500 million',
    Math.max(...sweep.map((o) => o.seeds)) > 5e8, `max ${Math.max(...sweep.map((o) => o.seeds))}`);

  const f72 = raw('vuza-72-filtered.txt').find((o) => o.mode);
  const u72 = raw('vuza-72-unfiltered.txt').find((o) => o.mode);
  check('E8 the 72-beat sweep finished', f72.complete === true && f72.cappedSeeds === 0);
  check('E9 the control run with the shortcut switched off also finished',
    u72.complete === true && u72.cappedSeeds === 0);
  eq('E10 both scanned the same number of candidates', f72.seeds, u72.seeds);
  eq('E11 and found the same canons', f72.vuzaOrderedClassPairs, u72.vuzaOrderedClassPairs);
  eq('E12 and the same partners', f72.vuzaPartnerClasses, u72.vuzaPartnerClasses);
  check('E13 the shortcut really did cut the work', f72.seedsKept * 10 < u72.seedsKept,
    `${f72.seedsKept} vs ${u72.seedsKept}`);
  eq('E14 only the six-and-twelve split yields anything at 72',
    D.at72.byFactorSize.filter((r) => r.vuzaClassPairs > 0).map((r) => r.size).join(','), '6');
  const eight = D.at72.byFactorSize.find((r) => r.size === 8);
  check('E15 the near miss is real: many aperiodic eight-onset rhythms tile 72 and none has an aperiodic partner',
    eight.tilingSeedClasses > 100000 && eight.vuzaClassPairs === 0, `${eight.tilingSeedClasses}`);
  // the census table: complete rows are complete, blank rows are blank
  const complete = D.table.filter((r) => r.censusComplete);
  check('E16 the census is complete for every listed row', complete.every((r) => r.factorSetClasses !== null));
  eq('E17 the largest completed census length is 50 beats', Math.max(...complete.map((r) => r.n)), 50);
  check('E18 the C sweep and the JavaScript census agreed', D.crossCheck.agreed === true, D.crossCheck.disagreements.join('; '));
  check('E19 they agreed over a real range', D.crossCheck.jsRange[1] >= 40, JSON.stringify(D.crossCheck.jsRange));
  // the reason the census stops, checked rather than asserted
  const r54 = eachComplement([0, 27], 54, null);
  eq('E20 {0,27} in a 54-beat cycle has 2^26 entry sets containing beat 0', r54.solutions, 2 ** 26);
}

// =========================================================== F. shipped bytes
{
  const labEngine = fs.readFileSync(path.join(HERE, 'canons.mjs'));
  const shipEngine = fs.readFileSync(path.join(PAGE, 'canons.mjs'));
  check('F1 the engine the page runs is byte-identical to the one the lab ran', labEngine.equals(shipEngine),
    `${labEngine.length} vs ${shipEngine.length} bytes`);
  const meta = JSON.parse(fs.readFileSync(path.join(PAGE, 'meta.json'), 'utf8'));
  // As build-data.mjs hashes them: an .html file without the blocks landing writes into every page.
  const sansGenerated = (f, buf) => (f.endsWith('.html') ? Buffer.from(buf.toString('utf8').replace(/<!--aw-([a-z-]+):start-->[\s\S]*?<!--aw-\1:end-->/g, '').replace(/\n[ \t]*(?=\n)/g, '')) : buf);
  const sha = (f) => crypto.createHash('sha256').update(sansGenerated(f, fs.readFileSync(path.join(PAGE, f)))).digest('hex');
  let bad = [];
  for (const [f, want] of Object.entries(meta.files)) { if (sha(f) !== want) bad.push(f); }
  check('F2 every shipped file matches its recorded SHA-256', bad.length === 0, bad.join(', '));
  const shipped = fs.readdirSync(PAGE).filter((f) => f !== 'meta.json');
  check('F3 meta.json lists every shipped file', shipped.every((f) => f in meta.files),
    shipped.filter((f) => !(f in meta.files)).join(', '));
  const pageData = JSON.parse(fs.readFileSync(path.join(PAGE, 'canons.json'), 'utf8'));
  check('F4 the data the page fetches is the data the lab wrote',
    JSON.stringify(pageData) === JSON.stringify(D));
  check('F5 the lab engine has no search budget of its own',
    /budget = Infinity/.test(labEngine.toString()));
}

// =========================================================== G. the prose
{
  const reg = new Set();
  const put = (v) => {
    if (typeof v !== 'number' || !isFinite(v)) return;
    reg.add(String(v));
    if (Number.isInteger(v)) reg.add(v.toLocaleString('en-US'));
    else { reg.add(v.toFixed(1)); reg.add(v.toFixed(2)); }
  };
  const walk = (o) => {
    if (typeof o === 'number') { put(o); return; }
    if (Array.isArray(o)) { o.forEach(walk); return; }
    if (o && typeof o === 'object') { Object.values(o).forEach(walk); return; }
  };
  walk(D);
  // figures the prose is entitled to derive, each with its reason
  put(2 ** 26);                                  // the complements of {0,27} in 54
  put(1999);                                     // the year of Coven and Meyerowitz
  put(1991); put(1993);                          // Vuza's series
  put(212); put(161); put(174);                  // the journal volume and pages
  put(D.sweep.seedsScanned + D.at72.seedsScanned);
  reg.add('72'); reg.add('18');
  // the film caption's mutation control (2026-11-06): the strike film-facts.mjs removes, read from its source,
  // and the 3 x 72 strikes its onset check reads. The 67 of them whose removal it misses is two digits, so G1
  // does not ask for it; it comes from social/bluesky/dossiers/2026-11-06-past-the-edge/ (drop-sweep.mjs).
  put(Number(fs.readFileSync(path.join(HERE, 'film', 'film-facts.mjs'), 'utf8').match(/const DROP = (\d+);/)[1]));
  put(3 * 72);

  // The page's own prose: not the blocks landing writes into every page (placard, Nearby, plain card, the folded
  // claims record), whose figures are batch names and counts no computation here makes (2026-10-18, landing 12).
  const prose = html
    .replace(/<!--aw-([a-z-]+):start-->[\s\S]*?<!--aw-\1:end-->/g, ' ')
    .replace(/<script[\s\S]*?<\/script>/g, ' ')
    .replace(/<style[\s\S]*?<\/style>/g, ' ')
    .replace(/<[^>]+>/g, ' ')
    .replace(/&#?\w+;/g, ' ');
  const orphans = [], seen = new Set();
  for (const m of prose.matchAll(/\d[\d,]*(?:\.\d+)?/g)) {
    const raw = m[0], digits = raw.replace(/,/g, '');
    if (!raw.includes(',') && digits.length < 3) continue;   // 1..99 read as English
    seen.add(raw);
    if (!reg.has(raw) && !reg.has(digits)) orphans.push(raw);
  }
  check('G1 every figure in the page prose came from a computation', orphans.length === 0,
    `unregistered: ${[...new Set(orphans)].join(', ')}`);
  check('G2 there were figures to check', seen.size >= 6, `${seen.size} found`);

  const fmProse = md.replace(/^---[\s\S]*?\ndek: /, 'dek: ');
  const fmOrphans = [];
  for (const m of fmProse.matchAll(/\d[\d,]*(?:\.\d+)?/g)) {
    const raw = m[0], digits = raw.replace(/,/g, '');
    if (!raw.includes(',') && digits.length < 3) continue;
    if (/\d{4}-\d\d-\d\d/.test(fmProse.slice(Math.max(0, m.index - 6), m.index + 12))) continue;  // the date
    if (!reg.has(raw) && !reg.has(digits)) fmOrphans.push(raw);
  }
  check('G3 every figure in the frontmatter came from a computation too', fmOrphans.length === 0,
    `unregistered: ${[...new Set(fmOrphans)].join(', ')}`);

  // the page must say what it is and is not
  check('G4 the frontmatter points at the page that exists', md.includes('href: "/strata/no-beat-twice/"'));
  check('G5 the canonical is the real slug', html.includes('https://artwaste.land/strata/no-beat-twice/'));
  check('G6 the page names where the census stops being computable', /2<sup>26<\/sup>/.test(html) || /2\^26/.test(html));
  check('G7 the page says the exhaustive claim is exhaustive', /Every subset that could be the smaller side/.test(html));
  check('G8 the page does not claim to have settled the open conjecture',
    /It is still open now/.test(html) && /main open problem/.test(html)
    && /worth almost nothing as evidence/.test(html));
  check('G8a the page says its own sweep sits inside the settled region',
    /inside the region where the answer was already known/.test(html));
  check('G8b the page carries the correction rather than the claim it used to make',
    /Correction, 2026-08-17/.test(html) && /That was wrong/.test(html)
    && /which-goes-with-which/.test(html) && /did not attempt it/.test(html));
  check('G8c the page warns about the motif labelling trap',
    /Reading it the natural way/.test(html));
  check('G8d the OEIS absence is reported with its positive control',
    /same query form returns\s+the Fibonacci numbers/.test(html));
  check('G9 the page credits Vuza, Coven and Meyerowitz, and Fripertinger',
    /Vuza/.test(html) && /Coven/.test(html) && /Meyerowitz/.test(html) && /Fripertinger/.test(html));
  check('G10 the page says the classification is quoted and not used',
    /We use it nowhere in the computation/.test(html));
  check('G11 the page names its free choices', /Free choices worth naming/.test(html));
  check('G12 the page names the check by a path that exists',
    fs.existsSync(path.join(ROOT, 'research/rhythmic-canons/verify.mjs')));
  // the character is written by code point on purpose: an earlier pass recast
  // every em dash in this directory and turned these two literals into ": ",
  // which quietly inverted both checks. A gate that can be edited by a
  // find-and-replace over its own file is not a gate.
  const EM = String.fromCharCode(0x2014);
  check('G13 no em dash in the page prose', !prose.includes(EM));
  check('G14 no em dash in the frontmatter', !md.includes(EM));
}

console.log(`\n${pass}/${pass + failures.length} checks pass`);
if (failures.length) { console.log('\nFAILURES:'); for (const f of failures) console.log('  x ' + f); process.exit(1); }
console.log('no-beat-twice: green.');
