#!/usr/bin/env node
// verify-au-coins.mjs — the checks on the Australian coin catalogue.
//
// Every check here is run twice: once against the real catalogue, and once against a copy
// with a fault deliberately planted in exactly the property it claims to test. A check that
// stays green under its own planted fault is not a check, and this file fails if any of them
// does. That is the only reason to believe the green run.
//
//   node verify-au-coins.mjs

import { readFile } from 'node:fs/promises'
import { readFileSync, readdirSync, writeFileSync, mkdtempSync } from 'node:fs'
import { tmpdir } from 'node:os'
import { join } from 'node:path'
import { extractCoinPage, millionsToPieces, parseTable, blocks } from './research/au-coins/harvest/ram.mjs'

const DATA = 'research/au-coins/data/catalogue.json'
let pass = 0, fail = 0
const failures = []
const ok = (cond, msg) => { if (cond) pass++; else { fail++; failures.push(msg) } }


// Pulled out of the check so a negative control can aim it at a doctored copy of the pages;
// a check that can only ever read the real directory cannot be shown to fail.
function emDashAudit (root) {
  const bad = []
  const files = []
  const walk = d => {
    for (const e of readdirSync(d, { withFileTypes: true })) {
      const p = `${d}/${e.name}`
      if (e.isDirectory()) walk(p); else if (e.name.endsWith('.html')) files.push(p)
    }
  }
  try { walk(root) } catch { return ['published pages not found'] }
  let quoted = 0
  for (const f of files) {
    const html = readFileSync(f, 'utf8')
    const before = (html.match(/\u2014/g) ?? []).length
    // A quotation is not only a <blockquote>. A table cell holding a figure exactly as the
    // Mint printed it is quoted source too, and is marked <span class="verbatim">. Both are
    // removed before looking for OUR em dashes, and both count toward the requirement that
    // source dashes survive: stripping one would be the forbidden edit, not a house-style fix.
    const stripped = html
      .replace(/<blockquote>[\s\S]*?<\/blockquote>/g, '')
      .replace(/<span class="verbatim">[\s\S]*?<\/span>/g, '')
    const ours = (stripped.match(/\u2014/g) ?? []).length
    quoted += before - ours
    if (ours) bad.push(`${f}: ${ours} em dash(es) outside a quotation`)
  }
  if (!quoted) bad.push('no em dash survives inside any quotation, which means the source text is being altered')
  return bad
}

const clone = o => JSON.parse(JSON.stringify(o))
// Compare on collapsed whitespace and decoded entities so a quote is not rejected for
// line wrapping, but IS rejected for saying something the source never said.
const normalise = s => String(s).replace(/&nbsp;/g, ' ').replace(/&amp;/g, '&')
  .replace(/&#0?39;|&apos;/g, "'").replace(/&quot;/g, '"').replace(/\s+/g, ' ').trim()


// Every coin must be reachable, and a coin gets a page of its own only when it has more
// than a bare figure. Consolidating 652 issues onto 17 denomination pages has exactly one
// serious failure mode, and it is not a wrong number: it is a coin that quietly stops being
// published at all, present in the data and absent from the site, which nothing else here
// would notice. So this walks the built pages and requires every issue in the catalogue to
// turn up either as its own page or as an anchored row on its denomination page.
//
// Honest about its limit: the story rule is a policy, so restating it cannot tell you the
// policy is wrong. What it tells you is that the pages and the data have not come apart,
// and the negative control below proves that coupling is live rather than assumed.
const SUBSTANTIVE_STATUS = new Set([
  'disputed', 'different-basis', 'summed-from-components', 'report-total-below-website',
])
function reachAudit (root, catalogue) {
  const bad = []
  const varieties = new Set((catalogue.varieties ?? []).map(v => v.issue))
  const factsBySubject = new Map()
  for (const f of catalogue.facts ?? []) {
    if (!factsBySubject.has(f.subject)) factsBySubject.set(f.subject, [])
    factsBySubject.get(f.subject).push(f)
  }
  const photographed = new Set((catalogue.specimens ?? []).map(s => s.issue))
  const bounded = new Set((catalogue.bounds ?? []).map(b => b.issue))
  const stories = new Set((catalogue.stories ?? []).map(s => s.issue))
  const shouldHavePage = id => {
    if (stories.has(id)) return true
    // A page is now earned only by having something to READ at length: a written story, or
    // sources that contradict each other. Everything else, a photograph, a variety, a
    // ceiling, a report-year figure, appears inline on the denomination page and in the
    // collection grid, which is where 243 near-identical coin pages went. The REACHABILITY
    // half below is unchanged and is what stops that becoming a way to lose coins.
    // A photograph and a ceiling used to promote a coin to its own page. They no longer do:
    // 118 pages existed for no reason but a photograph, which /collection/ shows better than
    // a page can. What earns a page is something to READ. The REACHABILITY half of this
    // check is unchanged and is what stops that becoming a way to lose coins.
    const fl = factsBySubject.get(id)
    if (!fl?.length) return true
    return fl.some(f => f.resolution?.status === 'disputed')
  }

  const files = []
  const walk = d => {
    for (const e of readdirSync(d, { withFileTypes: true })) {
      const p = `${d}/${e.name}`
      if (e.isDirectory()) walk(p); else if (e.name === 'index.html') files.push(p)
    }
  }
  try { walk(root) } catch { return ['published pages not found'] }

  // The id is printed on a coin's own page; a denomination page advertises the years it
  // carries as anchor ids. Read both off the HTML rather than re-deriving URL shapes.
  const ownPage = new Set()
  const anchored = new Set()
  for (const f of files) {
    const html = readFileSync(f, 'utf8')
    const id = html.match(/class="note mono">(au-[a-z0-9-]+)</)?.[1]
    if (id) { ownPage.add(id); continue }
    for (const m of html.matchAll(/<details class="yr"[^>]*data-issue="(au-[a-z0-9-]+)"/g)) {
      anchored.add(m[1])
    }
  }
  if (!anchored.size) bad.push('no denomination page carries an anchored year, so this check read nothing')

  for (const issue of catalogue.issues ?? []) {
    const reachable = ownPage.has(issue.id) || anchored.has(issue.id)
    if (!reachable) bad.push(`${issue.id} is in the catalogue and on no page a reader can reach`)
    const want = shouldHavePage(issue.id)
    if (want && !ownPage.has(issue.id)) bad.push(`${issue.id} has more to say than a row holds and has no page of its own`)
    if (!want && ownPage.has(issue.id)) bad.push(`${issue.id} carries one bare figure and was given a page anyway`)
  }
  return bad
}


// ---------------------------------------------------------------- the checks
// Each check is a pure function of the catalogue returning a list of problems, so the same
// function can be pointed at a doctored copy.

const CHECKS = {
  'ids are unique': c => {
    const seen = new Set(), bad = []
    for (const i of c.issues) { if (seen.has(i.id)) bad.push(i.id); seen.add(i.id) }
    return bad
  },

  'ids match the published scheme': c =>
    c.issues.filter(i => !/^au-[a-z0-9]+(-[a-z0-9]+)*-\d{4}(-[a-z0-9-]+)?$/.test(i.id)).map(i => i.id),

  'ids carry no positional counter': c =>
    c.issues.filter(i => /-\d{1,3}$/.test(i.id) && !/-\d{4}$/.test(i.id)).map(i => i.id),

  'every fact value cites a source that exists': c => {
    const ids = new Set(c.sources.map(s => s.id))
    const bad = []
    for (const f of c.facts) for (const v of f.values) if (!ids.has(v.source)) bad.push(`${f.subject}/${v.source}`)
    return bad
  },

  'every source has a url and an access date': c =>
    c.sources.filter(s => !s.url || !/^\d{4}-\d{2}-\d{2}$/.test(s.accessed ?? '')).map(s => s.id),

  // The one that matters most: the number in the record must be re-derivable from the words
  // quoted beside it. If a figure drifts from its own quote, the citation is decoration.
  'every mintage value is re-derivable from its own quote': c => {
    const bad = []
    for (const f of c.facts) {
      if (f.field !== 'mintage') continue
      for (const v of f.values) {
        if (typeof v.value !== 'number' || !v.quote) continue
        if (v.value === 0) continue // statement rows quote prose, checked separately
        // Only a reconstructed table row carries "year | figure | mint". A prose quote from a
        // mint report is checked by the provenance test instead, which is the right instrument
        // for it; applying this one to prose measures the format, not the claim.
        if (v.quote_kind && v.quote_kind !== 'reconstructed-row') continue
        const printed = v.quote.split('|')[1]?.trim()
        const parsed = printed ? millionsToPieces(printed) : null
        if (!parsed) { bad.push(`${f.subject}: quote has no parsable figure (${v.quote})`); continue }
        if (parsed.value !== v.value) bad.push(`${f.subject}: value ${v.value} but quote says ${parsed.value}`)
      }
    }
    return bad
  },

  'summed totals equal the sum of their components': c => {
    const bad = []
    for (const f of c.facts) {
      if (!f.resolution?.components_summed) continue
      const parts = f.values.filter(v => v.component && typeof v.value === 'number')
      const sum = parts.reduce((a, v) => a + v.value, 0)
      if (sum !== f.resolution.value) bad.push(`${f.subject}: ${f.resolution.value} != sum ${sum}`)
    }
    return bad
  },

  // Scoped to MINTAGE facts on purpose. The harm this guards against is a partial figure
  // being read as a whole coinage, which is a hazard for the field that answers "how many
  // were struck". The `dated-portion` field exists precisely so a partial statement is not
  // filed as a mintage, and a lone one there is the normal case: the Mint often assigned
  // only part of a year's delivery to a date.
  'a component is never presented as a rival claim': c => {
    const bad = []
    for (const f of c.facts.filter(f => f.field === 'mintage')) {
      const comps = f.values.filter(v => v.component)
      if (comps.length && comps.length !== f.values.length) bad.push(f.subject)
      if (comps.length === 1) bad.push(`${f.subject}: single value flagged as a component`)
    }
    return bad
  },

  'rounded figures carry their precision': c => {
    const bad = []
    for (const f of c.facts) for (const v of f.values) {
      if (v.rounded && typeof v.value === 'number' && v.value !== 0 && !(v.precision > 0)) bad.push(`${f.subject}/${v.value}`)
    }
    return bad
  },

  'no mintage is silently exact when its source printed millions': c => {
    const bad = []
    for (const f of c.facts) for (const v of f.values) {
      if (v.source?.startsWith('src:ram-mintage') && typeof v.value === 'number' && v.value > 0 && v.rounded !== true) {
        bad.push(`${f.subject}`)
      }
    }
    return bad
  },


  // THE CHECK THAT MATTERS MOST, and the reason it exists: during this build a worker handed
  // back seven "verbatim quotes" with HTTP 200 attached, for a legend that appears nowhere in
  // the page, cached or live. Fabricated citations are the one failure that would destroy
  // this catalogue, and prose rules do not stop them. So every quote is re-found in the
  // cached source before it can ship. A quote whose source cannot be re-read is not a quote.
  'every quote is re-findable in its cached source': c => {
    const bad = []
    const cache = new Map()
    const read = p => {
      if (!cache.has(p)) {
        try {
          const raw = readFileSync(p, 'utf8')
          // A cached OCR page is a JSON envelope; comparing against its escaped source would
          // fail every quote that spans a line break, for no reason a reader would accept.
          let body = raw
          if (p.endsWith('.json')) {
            try { const j = JSON.parse(raw); body = j.text ?? (j.meta ?? []).map(m => m?.data ?? '').join(' ') } catch {}
          }
          cache.set(p, normalise(body))
        } catch { cache.set(p, null) }
      }
      return cache.get(p)
    }
    let checked = 0
    for (const f of c.facts) for (const v of f.values) {
      if (!v.quote) continue
      if (!v.source_cache) { bad.push(`${f.subject}: quote with no cached source to check against`); continue }
      const doc = read(v.source_cache)
      // AN ABSENT SOURCE IS NOT A BAD CITATION, and conflating the two is the worst
      // available error for this particular check. 1,047 of the 1,511 quotes here cite a
      // cache under /home/liam/aw-coins-work/, outside the repository, so on every machine
      // but one this reported them as quotations that could not be found in their sources,
      // which is exactly what a fabricated citation looks like. Absences are counted and
      // stated by citationCoverage() below; only a source we can actually read and that
      // does NOT contain its quote is a failure. Corrected 2026-09-04.
      if (doc === null) continue
      checked++
      if (v.quote_kind === 'summed-components') {
        // Every component of a sum must be re-findable, and the components must add to the
        // total. A sum whose parts cannot be checked is a number with a citation stapled on.
        let sum = 0
        for (const comp of v.components ?? []) {
          sum += comp.pieces
          const cdoc = comp.source_cache ? read(comp.source_cache) : null
          if (cdoc === null) continue          // absent, not wrong; counted by citationCoverage()
          if (!cdoc.includes(normalise(comp.quote))) bad.push(`${f.subject}: component ${comp.fiscal_year} quote is not in its source`)
        }
        if (sum !== v.value) bad.push(`${f.subject}: components sum to ${sum}, value says ${v.value}`)
      } else if (v.quote_kind === 'verbatim-span') {
        if (!doc.includes(normalise(v.quote))) bad.push(`${f.subject}: quoted text is not in the source: ${JSON.stringify(v.quote.slice(0, 60))}`)
      } else {
        // A reconstructed row must have every one of its cells present in the source.
        for (const cell of v.quote.split('|').map(x => x.trim()).filter(Boolean)) {
          if (!doc.includes(normalise(cell))) { bad.push(`${f.subject}: row cell not in source: ${JSON.stringify(cell)}`); break }
        }
      }
    }
    // The guard the record check below already had, and this one needed for the same reason:
    // skipping absent sources must never let the check go green having examined nothing.
    if (!checked) bad.push('no quote was actually checked against a source')
    return bad
  },


  // --- the branch mint production record ---

  'every production record cites a known source': c =>
    (c.production ?? []).filter(p => !c.sources.some(s => s.id === p.source)).map(p => `${p.report_year}/${p.denomination}`),

  // The conversion is the finding, so it is the thing most worth checking.
  'every pound-to-pieces conversion is arithmetically right': c => {
    const bad = []
    for (const p of c.production ?? []) {
      if (!p.derived) continue
      if (p.pounds === null || !p.coins_per_pound) { bad.push(`${p.report_year}/${p.denomination}: derived without inputs`); continue }
      if (p.pounds * p.coins_per_pound !== p.derived.pieces) {
        bad.push(`${p.report_year}/${p.denomination}: £${p.pounds} x ${p.coins_per_pound} != ${p.derived.pieces}`)
      }
    }
    return bad
  },

  'a conversion never overwrites the printed figure': c =>
    (c.production ?? []).filter(p => p.derived && p.printed_unit === 'pounds' && p.pieces !== null && p.pieces !== p.derived.pieces)
      .map(p => `${p.report_year}/${p.denomination}`),

  // The whole reason production is a separate entity.
  // This began as a flat ban: a report-year figure could not be attached to an issue at all.
  // The ban was too blunt. The reports are the only source that says anything about most
  // pre-decimal years, and refusing to publish their figures left 114 coins showing nothing
  // while this same catalogue published the identical numbers a click away as production
  // records. What the ban was really protecting against is the SILENT version, where a
  // report-year figure is presented as the mintage of a coin bearing that date.
  //
  // So the rule is now conditional rather than absent, and it asserts more than it used to.
  // A report-year figure may sit on an issue only if it is impossible to mistake for a
  // coin-dated one: it must NOT claim the struck-dated basis, it must carry a plain sentence
  // saying what it counts, and the fact's resolution must be flagged no-coin-dated-figure so
  // that every consumer, page or API, sees the gap and not a number.
  'a report-year figure is never presented as a coin-dated mintage': c => {
    // Keyed on the BASIS, not on a list of source ids. The first version whitelisted two
    // sources, so the moment a third arrived its figures walked straight past and the control
    // went green to say so. A check that enumerates what it covers stops covering whatever
    // comes next, so this one enumerates the HAZARD and treats anything it does not recognise
    // as a failure rather than a pass.
    const COIN_DATED = new Set(['struck-dated', 'final-mintage-as-published', 'surviving-graded-population'])
    const REPORT_YEAR = new Set(['struck-in-report-year', 'delivered', 'issued'])
    const READS_AS_AN_ANSWER = new Set(['single-source', 'agreed'])
    const bad = []
    for (const f of c.facts) {
      if (f.field !== 'mintage') continue
      const bases = f.values.map(v => v.basis)
      for (const b of bases) {
        if (!COIN_DATED.has(b) && !REPORT_YEAR.has(b) && b !== 'unstated') {
          bad.push(`${f.subject}: basis ${JSON.stringify(b)} is neither a known coin-dated nor a known report-year basis, so this check cannot judge it`)
        }
      }
      if (bases.some(b => COIN_DATED.has(b))) continue      // a coin-dated figure is present
      if (!bases.some(b => REPORT_YEAR.has(b))) continue     // nothing report-year to guard
      if (READS_AS_AN_ANSWER.has(f.resolution?.status)) {
        bad.push(`${f.subject}: every figure counts a report year, presented under status "${f.resolution?.status}"`)
        continue
      }
      if (f.resolution?.status !== 'no-coin-dated-figure') continue
      for (const v of f.values) if (!v.counts) bad.push(`${f.subject}: a ${v.basis} figure with no sentence saying what it counts`)
      if (!/date/i.test(f.resolution?.note ?? '')) bad.push(`${f.subject}: the note does not tell the reader the coin date is unknown`)
    }
    return bad
  },

  // A figure the scanner mangled has no numeric value YET, and that is an honest state, not a
  // defect. What would be a defect is a CLEAN printed figure with no value parsed from it.
  'every cleanly printed figure carries a value': c => {
    // A trailing period IS the pound mark ("10,000,0001." is £10,000,000 with the mark
    // swallowed into the digits), so a figure ending in one is damaged, not clean.
    const clean = v => /^£?[\d,]+$/.test(String(v ?? '').replace(/\s/g, ''))
    return (c.production ?? []).filter(p =>
      clean(p.as_printed) &&
      ((p.printed_unit === 'pounds' && p.pounds === null) || (p.printed_unit === 'pieces' && p.pieces === null))
    ).map(p => `${p.report_year}/${p.denomination}: ${p.as_printed}`)
  },


  // A shortfall against the website can always be explained by a row we failed to extract, so
  // it must never be filed as the Mint contradicting itself. Only an EXCESS is evidence.
  'no shortfall is published as a disagreement': c =>
    c.facts.filter(f => f.resolution?.status === 'disputed').filter(f => {
      const web = f.values.find(v => v.source?.startsWith('src:ram-mintage'))
      const rep = f.values.find(v => v.source === 'src:ram-annual-reports')
      return web && rep && typeof web.value === 'number' && typeof rep.value === 'number' && rep.value < web.value
    }).map(f => f.subject),


  // A flattened table divorces a number from its row label, so a positional reading can be
  // confidently wrong while its quote verifies perfectly. Those figures must never be
  // presented at the same standing as ones the table's own arithmetic confirms.
  'a positional reading is never presented as confirmed': c => {
    const bad = []
    for (const f of c.facts) for (const v of f.values) {
      if (v.quote_kind !== 'flattened-table-row') continue
      if (!v.reading) { bad.push(`${f.subject}: flattened-table figure with no reading standing`); continue }
      if (v.reading === 'positional-only' && !/positional/i.test(f.resolution?.note ?? '')) {
        bad.push(`${f.subject}: positional-only but its note does not say so`)
      }
      // "confirmed" also appears in the POSITIONAL note ("rather than silently mixed with
      // confirmed figures"), so matching that word let a doctored record pass. Require the
      // phrase that names the actual evidence.
      if (v.reading === 'checksum-confirmed' && !/which the table prints/i.test(f.resolution?.note ?? '')) {
        bad.push(`${f.subject}: claims checksum confirmation without naming what closed`)
      }
    }
    return bad
  },


  // --- varieties ---

  'every variety carries an evidence grade': c =>
    (c.varieties ?? []).filter(v => !['primary', 'scholarly', 'trade', 'hobbyist', 'folklore'].includes(v.evidence)).map(v => v.id),

  'a variety attached to an issue names one that exists': c => {
    const ids = new Set(c.issues.map(i => i.id))
    return (c.varieties ?? []).filter(v => v.issue && !ids.has(v.issue)).map(v => `${v.id} -> ${v.issue}`)
  },

  // A variety that spans years must not be filed against a single one, which would invent a
  // precision the claim never had.
  'a variety spanning years is not pinned to one issue': c =>
    (c.varieties ?? []).filter(v => v.applies_to && v.issue).map(v => v.id),

  // "$1" and "$2" are the NAMES of two Australian coins, and a mule struck on a Hong Kong $2
  // planchet is a description, not a valuation. The check has to know the difference or it
  // condemns the very records it exists to protect.
  'no variety carries a price': c =>
    (c.varieties ?? []).filter(v => {
      const t = JSON.stringify(v)
      // "fetched" is also how these records describe RETRIEVING a source ("no mint record
      // fetched"), so it only counts as an auction word when money follows it.
      return /\$\s?\d{3,}|\bAUD\s?\d|\bworth\s+(about\s+)?[\$\d]|\bvalued?\s+at\s+[\$\d]|\bsold\s+for\s+[\$\d]|\bfetch(ed|es)\s+[\$\d]/i.test(t)
    }).map(v => v.id),

  'every variety says how it is physically told apart': c =>
    (c.varieties ?? []).filter(v => !v.identified_by || v.identified_by.length < 8).map(v => v.id),


  // House style forbids the em dash in OUR prose and requires it be left alone in a source's.
  // Both halves matter: editing a quotation's dash would turn "verbatim" into a lie, which is
  // the one unforgivable move here, so this checks the published pages rather than the data.
  'no em dash in our own prose, and every one in a quotation survives': c =>
    emDashAudit(c.__pagesRoot ?? 'public/tools/australian-coins'),

  // The mined seams are held to exactly the standard the mintage figures are held to. A
  // withdrawal figure or a yield percentage is no more allowed to arrive without a page it
  // can be re-found on than a mintage is. This matters most for these records because they
  // came from four independent workers, and a worker that invents a plausible sentence is
  // the failure this catalogue has already survived once.
  'every mined record is re-findable in its cached page': c => {
    const bad = []
    const cache = new Map()
    const read = p => {
      if (!cache.has(p)) {
        try {
          const raw = readFileSync(p, 'utf8')
          let body = raw
          try { const j = JSON.parse(raw); body = j.text ?? body } catch {}
          cache.set(p, normalise(body))
        } catch { cache.set(p, null) }
      }
      return cache.get(p)
    }
    let checked = 0
    for (const r of c.records ?? []) {
      if (!r.source_cache) { bad.push(`${r.kind} ${r.report_year}: no cached page named`); continue }
      const doc = read(r.source_cache)
      if (doc === null) continue          // absent, not wrong; counted by citationCoverage()
      checked++
      if (!doc.includes(normalise(r.quote))) {
        bad.push(`${r.kind} ${r.report_year} p${r.page}: quote is not on the page it cites -> ${JSON.stringify(String(r.quote).slice(0, 70))}`)
      }
    }
    if ((c.records ?? []).length && !checked) bad.push('no mined record was actually checked against a page')
    return bad
  },

  // Publishing someone else's photograph is the only thing this catalogue does that could
  // wrong a third party rather than a reader, so the licence conditions are checked, not
  // trusted. Two permissions have to stack and both are asserted here.
  'every published photograph carries a usable licence and its attribution': c => {
    const bad = []
    const OK = new Set(['CC BY', 'CC0', 'Public Domain'])
    for (const s of c.specimens ?? []) {
      for (const h of s.held) {
        if (!h.images?.length) bad.push(`${s.issue}: a held object with no image`)
        for (const i of h.images ?? []) {
          if (!OK.has(i.licence)) bad.push(`${s.issue}: image licensed ${JSON.stringify(i.licence)}`)
          if (!i.attribution || !/Museums Victoria/.test(i.attribution)) bad.push(`${s.issue}: an image with no attribution`)
          if (!i.small) bad.push(`${s.issue}: an image with no source URL`)
        }
      }
    }
    return bad
  },

  // The design copyright binds regardless of who took the photograph: nothing designed on
  // or after 1 May 1969 belongs to us to publish.
  'no photograph is published of a design still in copyright': c =>
    (c.specimens ?? []).filter(s => s.year >= 1969).map(s => `${s.issue}: dated ${s.year}, on or after the 1969 cutoff`),

  // A forgery, a replica and a coin die are not evidence that a coin was struck.
  'only genuine mint products are counted as proof a coin exists': c => {
    const OKKIND = new Set(['circulating', 'proof', 'specimen', 'pattern'])
    const bad = []
    for (const s of c.specimens ?? []) for (const h of s.held) {
      if (!OKKIND.has(h.kind)) bad.push(`${s.issue}: counted a ${h.kind}`)
      if (/Replica|Forgery|Electrotype|Coin Die/i.test(h.title ?? '')) bad.push(`${s.issue}: counted ${JSON.stringify(h.title)}`)
    }
    return bad
  },

  // A ceiling without its assumption is a number with better manners.
  'every published ceiling states the assumption that produces it': c =>
    (c.bounds ?? []).filter(b => !b.assumption || !b.assumption_caveat || !(b.ceiling > 0))
      .map(b => `${b.issue}: a bound with no stated assumption`),

  // Found while chasing full coverage: 63 issues existed twice, once as a bare
  // au-sovereign-1855 minted by the museum ingest and once as au-sovereign-1855-s from the
  // gold tables. The bare one showed no figure while its twin showed one, so the catalogue
  // reported a gap it did not have. A shell may only exist where the ambiguity is real.
  'no coin exists twice, once with a figure and once without': c => {
    const withFig = new Set(c.facts.filter(f => f.field === 'mintage').map(f => f.subject))
    const byYear = new Map()
    for (const i of c.issues) {
      const k = `${i.denomination}|${i.year}`
      if (!byYear.has(k)) byYear.set(k, [])
      byYear.get(k).push(i)
    }
    const bad = []
    for (const [k, group] of byYear) {
      if (group.length < 2) continue
      const [den, year] = k.split('|')
      const bare = group.find(i => i.id === `au-${den}-${year}`)
      if (!bare || withFig.has(bare.id)) continue
      if (!group.some(i => i !== bare && withFig.has(i.id))) continue
      // A shell is allowed ONLY when it says why it cannot be merged.
      if (!/does not (name|say)/i.test(bare.known_from ?? '')) {
        bad.push(`${bare.id}: empty duplicate of ${group.find(i => i !== bare && withFig.has(i.id)).id}`)
      }
    }
    return bad
  },

  // A story is prose, which is exactly why its quotes need the same gate as a figure's: a
  // fluent paragraph is the easiest place in this catalogue to put a sentence the source
  // never said.
  'every quote in a story is re-findable in its cached page': c => {
    const bad = []
    let checked = 0, quoted = 0
    for (const s of c.stories ?? []) {
      for (const sec of s.sections ?? []) {
        if (!sec.quote) continue
        quoted++
        // A story may quote the catalogue's own variety records rather than a report page.
        // That is still a provenance claim and still checked, just against a different thing.
        if (sec.from_variety) {
          const v = (c.varieties ?? []).find(x => x.id === sec.from_variety)
          if (!v) { bad.push(`${s.issue}/${sec.heading}: names a variety that does not exist`); continue }
          const hay = normalise([v.identified_by, v.disagreement, v.name].filter(Boolean).join(' '))
          if (!hay.includes(normalise(sec.quote))) bad.push(`${s.issue}/${sec.heading}: quote is not in the variety it cites`)
          checked++
          continue
        }
        if (!sec.source_cache) { bad.push(`${s.issue}/${sec.heading}: a quote with no cached page`); continue }
        let body = null
        try { body = JSON.parse(readFileSync(sec.source_cache, 'utf8')).text } catch {}
        if (body == null) continue      // absent, not wrong; counted by citationCoverage()
        checked++
        if (!normalise(body).includes(normalise(sec.quote))) {
          bad.push(`${s.issue}/${sec.heading}: quote is not on the page it cites`)
        }
      }
    }
    // Same guard as the two checks above: skipping absent pages must not buy a green.
    if (quoted && !checked) bad.push('no story quote was actually checked against a page')
    return bad
  },

  // Search hygiene, checked rather than asserted. See robotsAudit above.
  'every coin is reachable, and only the ones with a story get their own page': c =>
    reachAudit(c.__pagesRoot ?? 'public/tools/australian-coins', c),
}

// ---------------------------------------------------------------- planted faults
// One per check, each aimed at exactly the property that check claims to test.

const FAULTS = {
  'ids are unique': c => { c.issues[1].id = c.issues[0].id; return c },
  'ids match the published scheme': c => { c.issues[0].id = 'AU_Penny_1930'; return c },
  'ids carry no positional counter': c => { c.issues[0].id += '-12'; return c },
  'every fact value cites a source that exists': c => { c.facts[0].values[0].source = 'src:does-not-exist'; return c },
  'every source has a url and an access date': c => { c.sources[0].accessed = 'sometime'; return c },
  'every mintage value is re-derivable from its own quote': c => {
    const f = c.facts.find(x => x.field === 'mintage' && typeof x.values[0].value === 'number' && x.values[0].value > 0)
    f.values[0].value = f.values[0].value + 100000
    return c
  },
  'summed totals equal the sum of their components': c => {
    const f = c.facts.find(x => x.resolution?.components_summed)
    f.resolution.value += 1
    return c
  },
  'a component is never presented as a rival claim': c => {
    const f = c.facts.find(x => x.values.length > 1 && x.values[0].component)
    f.values[1].component = false
    return c
  },
  'rounded figures carry their precision': c => {
    const f = c.facts.find(x => x.values.some(v => v.rounded && v.value > 0))
    f.values.find(v => v.rounded && v.value > 0).precision = null
    return c
  },
  'no mintage is silently exact when its source printed millions': c => {
    const f = c.facts.find(x => x.values.some(v => v.rounded && v.value > 0))
    f.values.find(v => v.rounded && v.value > 0).rounded = false
    return c
  },

  // THE CHECK THAT MATTERS MOST, and the reason it exists: during this build a worker handed
  // back seven "verbatim quotes" with HTTP 200 attached, for a legend that appears nowhere in
  // the page, cached or live. Fabricated citations are the one failure that would destroy
  // this catalogue, and prose rules do not stop them. So every quote is re-found in the
  // cached source before it can ship. A quote whose source cannot be re-read is not a quote.
  'every quote is re-findable in its cached source': c => {
    const bad = []
    const cache = new Map()
    const read = p => {
      if (!cache.has(p)) {
        try {
          const raw = readFileSync(p, 'utf8')
          // A cached OCR page is a JSON envelope; comparing against its escaped source would
          // fail every quote that spans a line break, for no reason a reader would accept.
          let body = raw
          if (p.endsWith('.json')) {
            try { const j = JSON.parse(raw); body = j.text ?? (j.meta ?? []).map(m => m?.data ?? '').join(' ') } catch {}
          }
          cache.set(p, normalise(body))
        } catch { cache.set(p, null) }
      }
      return cache.get(p)
    }
    for (const f of c.facts) for (const v of f.values) {
      if (!v.quote) continue
      if (!v.source_cache) { bad.push(`${f.subject}: quote with no cached source to check against`); continue }
      const doc = read(v.source_cache)
      if (doc === null) { bad.push(`${f.subject}: cached source unreadable (${v.source_cache})`); continue }
      if (v.quote_kind === 'summed-components') {
        // Every component of a sum must be re-findable, and the components must add to the
        // total. A sum whose parts cannot be checked is a number with a citation stapled on.
        let sum = 0
        for (const comp of v.components ?? []) {
          sum += comp.pieces
          const cdoc = comp.source_cache ? read(comp.source_cache) : null
          if (cdoc === null) { bad.push(`${f.subject}: component ${comp.fiscal_year} has no readable cached source`); continue }
          if (!cdoc.includes(normalise(comp.quote))) bad.push(`${f.subject}: component ${comp.fiscal_year} quote is not in its source`)
        }
        if (sum !== v.value) bad.push(`${f.subject}: components sum to ${sum}, value says ${v.value}`)
      } else if (v.quote_kind === 'verbatim-span') {
        if (!doc.includes(normalise(v.quote))) bad.push(`${f.subject}: quoted text is not in the source: ${JSON.stringify(v.quote.slice(0, 60))}`)
      } else {
        // A reconstructed row must have every one of its cells present in the source.
        for (const cell of v.quote.split('|').map(x => x.trim()).filter(Boolean)) {
          if (!doc.includes(normalise(cell))) { bad.push(`${f.subject}: row cell not in source: ${JSON.stringify(cell)}`); break }
        }
      }
    }
    return bad
  },

  'every quote is re-findable in its cached source': c => {
    const f = c.facts.find(x => x.values.some(v => v.quote))
    const v = f.values.find(v => v.quote)
    // Exactly the fault that got through today: a plausible legend nobody printed.
    v.quote = 'RAM = Royal Australian Mint'
    v.quote_kind = 'verbatim-span'
    return c
  },

  // --- the branch mint production record ---

  'every production record cites a known source': c =>
    (c.production ?? []).filter(p => !c.sources.some(s => s.id === p.source)).map(p => `${p.report_year}/${p.denomination}`),

  // The conversion is the finding, so it is the thing most worth checking.
  'every pound-to-pieces conversion is arithmetically right': c => {
    const bad = []
    for (const p of c.production ?? []) {
      if (!p.derived) continue
      if (p.pounds === null || !p.coins_per_pound) { bad.push(`${p.report_year}/${p.denomination}: derived without inputs`); continue }
      if (p.pounds * p.coins_per_pound !== p.derived.pieces) {
        bad.push(`${p.report_year}/${p.denomination}: £${p.pounds} x ${p.coins_per_pound} != ${p.derived.pieces}`)
      }
    }
    return bad
  },

  'a conversion never overwrites the printed figure': c =>
    (c.production ?? []).filter(p => p.derived && p.printed_unit === 'pounds' && p.pieces !== null && p.pieces !== p.derived.pieces)
      .map(p => `${p.report_year}/${p.denomination}`),

  // A figure the scanner mangled has no numeric value YET, and that is an honest state, not a
  // defect. What would be a defect is a CLEAN printed figure with no value parsed from it.
  'every cleanly printed figure carries a value': c => {
    // A trailing period IS the pound mark ("10,000,0001." is £10,000,000 with the mark
    // swallowed into the digits), so a figure ending in one is damaged, not clean.
    const clean = v => /^£?[\d,]+$/.test(String(v ?? '').replace(/\s/g, ''))
    return (c.production ?? []).filter(p =>
      clean(p.as_printed) &&
      ((p.printed_unit === 'pounds' && p.pounds === null) || (p.printed_unit === 'pieces' && p.pieces === null))
    ).map(p => `${p.report_year}/${p.denomination}: ${p.as_printed}`)
  },

  'every production record cites a known source': c => { c.production[0].source = 'src:nope'; return c },
  'every pound-to-pieces conversion is arithmetically right': c => {
    const p = c.production.find(x => x.derived); p.derived.pieces += 240; return c
  },
  'a conversion never overwrites the printed figure': c => {
    const p = c.production.find(x => x.derived && x.printed_unit === 'pounds'); p.pieces = p.derived.pieces + 1; return c
  },
  // The silent version is the whole hazard: a report-year figure sitting under a status that
  // reads like an answer. Plant exactly that.
  'a report-year figure is never presented as a coin-dated mintage': c => {
    const f = c.facts.find(x => x.resolution?.status === 'no-coin-dated-figure')
    f.resolution.status = 'single-source'
    return c
  },
  'every cleanly printed figure carries a value': c => {
    const p = c.production.find(x => x.printed_unit === 'pounds' && x.pounds !== null)
    p.as_printed = '123,456'; p.pounds = null; return c
  },

  // A shortfall against the website can always be explained by a row we failed to extract, so
  // it must never be filed as the Mint contradicting itself. Only an EXCESS is evidence.
  'no shortfall is published as a disagreement': c =>
    c.facts.filter(f => f.resolution?.status === 'disputed').filter(f => {
      const web = f.values.find(v => v.source?.startsWith('src:ram-mintage'))
      const rep = f.values.find(v => v.source === 'src:ram-annual-reports')
      return web && rep && typeof web.value === 'number' && typeof rep.value === 'number' && rep.value < web.value
    }).map(f => f.subject),

  'no shortfall is published as a disagreement': c => {
    const f = c.facts.find(x => x.resolution?.status === 'report-total-below-website')
    if (f) f.resolution.status = 'disputed'
    return c
  },

  // A flattened table divorces a number from its row label, so a positional reading can be
  // confidently wrong while its quote verifies perfectly. Those figures must never be
  // presented at the same standing as ones the table's own arithmetic confirms.
  'a positional reading is never presented as confirmed': c => {
    const bad = []
    for (const f of c.facts) for (const v of f.values) {
      if (v.quote_kind !== 'flattened-table-row') continue
      if (!v.reading) { bad.push(`${f.subject}: flattened-table figure with no reading standing`); continue }
      if (v.reading === 'positional-only' && !/positional/i.test(f.resolution?.note ?? '')) {
        bad.push(`${f.subject}: positional-only but its note does not say so`)
      }
      // "confirmed" also appears in the POSITIONAL note ("rather than silently mixed with
      // confirmed figures"), so matching that word let a doctored record pass. Require the
      // phrase that names the actual evidence.
      if (v.reading === 'checksum-confirmed' && !/which the table prints/i.test(f.resolution?.note ?? '')) {
        bad.push(`${f.subject}: claims checksum confirmation without naming what closed`)
      }
    }
    return bad
  },

  'a positional reading is never presented as confirmed': c => {
    const f = c.facts.find(x => x.values.some(v => v.reading === 'positional-only'))
    f.values.find(v => v.reading === 'positional-only').reading = 'checksum-confirmed'
    return c
  },

  // --- varieties ---

  'every variety carries an evidence grade': c =>
    (c.varieties ?? []).filter(v => !['primary', 'scholarly', 'trade', 'hobbyist', 'folklore'].includes(v.evidence)).map(v => v.id),

  'a variety attached to an issue names one that exists': c => {
    const ids = new Set(c.issues.map(i => i.id))
    return (c.varieties ?? []).filter(v => v.issue && !ids.has(v.issue)).map(v => `${v.id} -> ${v.issue}`)
  },

  // A variety that spans years must not be filed against a single one, which would invent a
  // precision the claim never had.
  'a variety spanning years is not pinned to one issue': c =>
    (c.varieties ?? []).filter(v => v.applies_to && v.issue).map(v => v.id),

  // "$1" and "$2" are the NAMES of two Australian coins, and a mule struck on a Hong Kong $2
  // planchet is a description, not a valuation. The check has to know the difference or it
  // condemns the very records it exists to protect.
  'no variety carries a price': c =>
    (c.varieties ?? []).filter(v => {
      const t = JSON.stringify(v)
      // "fetched" is also how these records describe RETRIEVING a source ("no mint record
      // fetched"), so it only counts as an auction word when money follows it.
      return /\$\s?\d{3,}|\bAUD\s?\d|\bworth\s+(about\s+)?[\$\d]|\bvalued?\s+at\s+[\$\d]|\bsold\s+for\s+[\$\d]|\bfetch(ed|es)\s+[\$\d]/i.test(t)
    }).map(v => v.id),

  'every variety says how it is physically told apart': c =>
    (c.varieties ?? []).filter(v => !v.identified_by || v.identified_by.length < 8).map(v => v.id),

  'every variety carries an evidence grade': c => { c.varieties[0].evidence = 'probably real'; return c },
  'a variety attached to an issue names one that exists': c => { c.varieties.find(v => v.issue).issue = 'au-nope-1900'; return c },
  'a variety spanning years is not pinned to one issue': c => {
    const v = c.varieties.find(x => x.applies_to) ?? c.varieties[0]
    v.applies_to = '1955-1956'; v.issue = 'au-penny-1955'; return c
  },
  'no variety carries a price': c => { c.varieties[0].identified_by += ' sold for $4,000'; return c },
  'every variety says how it is physically told apart': c => { c.varieties[0].identified_by = ''; return c },

  // Hand a variety to a coin that has no page of its own. Nothing on disk changes, so the
  // check only fires if it is genuinely reading the pages against the data.
  // Two faults in one, because the check makes two claims and the old fault stopped biting
  // when the page rule changed: it planted a VARIETY, which no longer earns a page, and the
  // control went green to say so.
  //
  // Fault one is the one that matters: a coin present in the data and on no page at all.
  // That is the failure this check exists to prevent, and it is exactly what consolidating
  // 243 coin pages into their denomination pages could have caused.
  'every coin is reachable, and only the ones with a story get their own page': c => {
    const donor = c.issues[0]
    c.issues = [...c.issues, { id: `au-${donor.denomination}-1799`, type: donor.type, year: 1799,
      denomination: donor.denomination, mint: null, mintmark: null, design: null, commemorative: null }]
    return c
  },

  'every published photograph carries a usable licence and its attribution': c => {
    c.specimens = JSON.parse(JSON.stringify(c.specimens ?? []))
    c.specimens[0].held[0].images[0].licence = 'All Rights Reserved'
    return c
  },
  'no photograph is published of a design still in copyright': c => {
    c.specimens = JSON.parse(JSON.stringify(c.specimens ?? []))
    c.specimens[0].year = 1988
    return c
  },
  'only genuine mint products are counted as proof a coin exists': c => {
    c.specimens = JSON.parse(JSON.stringify(c.specimens ?? []))
    c.specimens[0].held[0].title = 'Coin Forgery - Florin, Australia, 1910'
    return c
  },
  'every published ceiling states the assumption that produces it': c => {
    c.bounds = JSON.parse(JSON.stringify(c.bounds ?? []))
    delete c.bounds[0].assumption_caveat
    return c
  },

  'no coin exists twice, once with a figure and once without': c => {
    const withFig = new Set(c.facts.filter(f => f.field === 'mintage').map(f => f.subject))
    const donor = c.issues.find(i => withFig.has(i.id) && /-[a-z]+$/.test(i.id))
    c.issues = [...c.issues, { id: `au-${donor.denomination}-${donor.year}`, type: donor.type,
      year: donor.year, denomination: donor.denomination, mint: null, mintmark: null,
      design: null, commemorative: null }]
    return c
  },

  // Planted in EVERY quoted section, not just the first. That check has two branches, one
  // against a cached page and one against the catalogue's own variety records, and since
  // 2026-09-04 it skips a section whose cached page is not on this machine. A fault aimed
  // only at section zero therefore went unnoticed on any machine without that page, and the
  // control silently stopped being a control. Planting it everywhere means whichever branch
  // a given checkout can actually examine is the one that catches it.
  'every quote in a story is re-findable in its cached page': c => {
    c.stories = JSON.parse(JSON.stringify(c.stories ?? []))
    for (const s of c.stories) for (const sec of s.sections ?? []) {
      if (sec.quote) sec.quote = 'Australia; Bronze-Penny 1,500 struck at Melbourne in 1930'
    }
    return c
  },

  // Plant a sentence that reads like the Mint and is not in the corpus. This is the exact
  // shape of the fabrication this catalogue has already met once: fluent, plausible, and
  // attributed to a page that returns 200 and does not contain it.
  'every mined record is re-findable in its cached page': c => {
    c.records = [...(c.records ?? [])]
    c.records[0] = { ...c.records[0], quote: 'Worn Australian silver coin to the value of 44,180l. was withdrawn and melted during the year at the Adelaide Branch.' }
    return c
  },

  // Write a page that breaks the rule into a scratch tree and require the check to see it.
  'no em dash in our own prose, and every one in a quotation survives': c => {
    const dir = mkdtempSync(join(tmpdir(), 'aw-emdash-'))
    writeFileSync(join(dir, 'ok.html'), '<blockquote>a source said \u2014 this</blockquote>')
    writeFileSync(join(dir, 'bad.html'), '<p>our own prose \u2014 with a tell</p>')
    return { ...c, __pagesRoot: dir }
  },
  'every fact states what was counted': c => { delete c.facts[0].values[0].basis; return c },
}

// ---------------------------------------------------------------- parser unit checks
// The harvester's own arithmetic, including the shapes that produced real bugs.

function parserChecks () {
  const m = millionsToPieces('133.3')
  ok(m.value === 133300000, `133.3 million -> ${m?.value}, expected exactly 133300000`)
  ok(Number.isInteger(m.value), '133.3 million must be an exact integer, not a float artefact')
  ok(m.precision === 50000, `precision of a one-decimal millions figure -> ${m?.precision}`)

  const mk = millionsToPieces('2.0**')
  ok(mk?.value === 2000000 && mk.marker === '**', 'a footnote marker must be kept, not swallowed or dropped')

  ok(millionsToPieces('') === null, 'empty string must not parse as a figure')
  ok(millionsToPieces('n/a') === null, 'prose must not parse as a figure')
  ok(millionsToPieces('1.2.3') === null, 'malformed number must not parse')

  const rows = parseTable('<table><tr><th>Year</th><th>Mintage</th></tr><tr><td>1990</td><td>133.3</td></tr><tr><td colspan="3">No coins in 1986</td></tr></table>')
  ok(rows.length === 3, `parseTable rows -> ${rows.length}, expected 3`)
  ok(rows[2].spanned === 'No coins in 1986', 'a colspan statement row must be captured, not dropped')

  // Two adjacent block elements must not fuse into one word.
  const fused = extractCoinPage('<div class="paragraph paragraph--type--mintage-figure"><div class="clearfix text-formatted field field--name-field-body"><p>Alpha</p><p>Beta</p></div><table class="coin-mintage-table"><tr><th>Year</th></tr><tr><td>1999</td><td>1.0</td><td>RAM</td></tr></table></div>', 't')
  ok(fused.groups[0]?.design === 'Alpha Beta', `adjacent blocks -> ${JSON.stringify(fused.groups[0]?.design)}, expected "Alpha Beta"`)

  ok(blocks('<div><div>a</div></div>', /<div/, 'div').length === 2, 'nested blocks must both be found')

  // A CSS colour is not a footnote. This was a real false positive.
  const css = extractCoinPage('<style>.x{color:#000022}</style><div class="paragraph paragraph--type--mintage-figure"><table class="coin-mintage-table"><tr><th>Year</th></tr><tr><td>1999</td><td>1.0</td><td>RAM</td></tr></table></div>', 't')
  ok(css.footnotes.length === 0, `a hex colour must not be read as a footnote (got ${JSON.stringify(css.footnotes)})`)
}

// ---------------------------------------------------------------- run

const catalogue = JSON.parse(await readFile(DATA, 'utf8'))

// ---------------------------------------------------------------- citation coverage
//
// The citation checks skip a quote whose cached source is not on this machine, because an
// absent source is not a bad citation and reporting it as one is indistinguishable from
// reporting a fabrication. Skipping silently would be worse still: a suite that examined
// nothing could look as green as one that examined everything. So the split is counted and
// printed, every run, before any check is allowed to claim anything.
function citationCoverage(c) {
  const seen = new Map()
  const here = (p) => {
    if (!p) return false
    if (!seen.has(p)) { try { readFileSync(p, 'utf8'); seen.set(p, true) } catch { seen.set(p, false) } }
    return seen.get(p)
  }
  let present = 0, absent = 0
  const roots = new Map()
  const note = (p) => {
    if (here(p)) { present++; return }
    absent++
    const root = String(p).split('/').slice(0, 4).join('/')
    roots.set(root, (roots.get(root) ?? 0) + 1)
  }
  for (const f of c.facts ?? []) for (const v of f.values ?? []) {
    if (v.quote && v.source_cache) note(v.source_cache)
  }
  for (const r of c.records ?? []) if (r.source_cache) note(r.source_cache)
  for (const st of c.stories ?? []) for (const sec of st.sections ?? []) {
    if (sec.quote && sec.source_cache && !sec.from_variety) note(sec.source_cache)
  }
  return { present, absent, roots: [...roots].sort((a, b) => b[1] - a[1]) }
}

{
  const cov = citationCoverage(catalogue)
  const total = cov.present + cov.absent
  console.log('citation coverage')
  console.log(`  ${cov.present} of ${total} cited sources are present here and were checked`)
  if (cov.absent) {
    console.log(`  ${cov.absent} are NOT in this checkout and were therefore NOT CHECKED, by root:`)
    for (const [root, n] of cov.roots) console.log(`     ${n.toString().padStart(5)}  ${root}/…`)
    console.log('  Those quotations are unverified here. That is a limit on this run, not a')
    console.log('  finding about the catalogue, and it is why they are not counted as failures.')
  }
  console.log('')
}

console.log('parser checks')
parserChecks()

console.log('\ncatalogue checks (real data)')
for (const [name, fn] of Object.entries(CHECKS)) {
  const bad = fn(clone(catalogue))
  ok(bad.length === 0, `${name}: ${bad.length} problem(s) -> ${bad.slice(0, 3).join(' ; ')}`)
  console.log(`  ${bad.length === 0 ? 'ok  ' : 'FAIL'} ${name}${bad.length ? ` (${bad.length})` : ''}`)
}

console.log('\nnegative controls (each check must go red under its own planted fault)')
let controlsFired = 0
for (const [name, fn] of Object.entries(CHECKS)) {
  const fault = FAULTS[name]
  if (!fault) { fail++; failures.push(`no planted fault written for check "${name}"`); console.log(`  MISSING control for ${name}`); continue }
  let fired = false
  try { fired = fn(fault(clone(catalogue))).length > 0 } catch { fired = true }
  ok(fired, `check "${name}" stayed green under a fault aimed at exactly what it tests: it is not a check`)
  if (fired) controlsFired++
  console.log(`  ${fired ? 'red ' : 'GREEN(bad)'} ${name}`)
}

console.log(`\n${pass} passed, ${fail} failed`)
console.log(`${controlsFired}/${Object.keys(CHECKS).length} negative controls fired`)
if (fail) { console.log('\nfailures:'); failures.forEach(f => console.log('  - ' + f)) }
process.exit(fail ? 1 : 0)
