#!/usr/bin/env node
// Verifier for /strata/nobody-compared-three/
//
//   node verify-nobody-compared-three.mjs
//
// Six independent things, any one of which can fail the page.
//
//  A. THE SOURCE DATA IS THE SOURCE DATA. Tables S1 and S2 are pinned by SHA-256, and
//     the parse is checked against facts the paper itself prints: 128 odorants, 26
//     subjects, 264 tests, 4 controls, 13 stimulus types of 20 pairs each, 227 pairs
//     above chance, 148 significant. Those last two are the paper's own numbers and
//     they are the evidence that the trial record is being read the way its authors
//     read it.
//
//  B. THE ESTIMATOR, TWICE. Formulas (1) to (3) are recomputed by a SECOND, independent
//     implementation that never touches estimator.mjs: log-gamma floating point instead
//     of exact BigInt. Both must return the paper's six published figures.
//
//  C. THE STRUCTURAL CLAIM, TWICE. The clique number of the discriminability graph is
//     computed by the branch and bound in audit.mjs and, independently, by a direct
//     argument: no vertex has degree above 2 and no triangle exists, which is checked
//     over every triple in every neighbourhood. Both must say 2.
//
//  D. THE BUNDLE THE PAGE SHIPS is rebuilt from research/ and compared field by field
//     against the bytes actually embedded in the served HTML.
//
//  E. THE PAGE'S OWN CODE IS RUN. app.js is imported against a minimal DOM, and the
//     strings it writes into the page are compared with independently computed values.
//     Nothing here trusts a number because the page prints it.
//
//  F. CONTROLS THAT MUST FAIL, and do: seven of them.
//
// The microbe replication is Monte Carlo, so its checks are stated as tolerances around
// values a closed form supplies, never as equality against a stored run.

import { readFileSync, existsSync } from 'node:fs'
import { createHash } from 'node:crypto'
import path from 'node:path'
import { fileURLToPath } from 'node:url'

import {
  loadTests, mixtureTests, controlTests, isSignificant, isAboveChance,
  N_SUBJECTS, odorants, mixtureKey, TABLE_S1, TABLE_S2,
} from './research/trillion-odours/dataset.mjs'
import {
  audit, buildGraph, maxClique, degrees, certifiableFrom, costToCertify,
  SECONDS_PER_TEST,
} from './research/trillion-odours/audit.mjs'
import {
  build, embedded, serialise, PAGE_HTML,
} from './research/trillion-odours/build-page-data.mjs'
import {
  discAt, sci, binomial, ball, logDiscInteger, logDiscAtRadius, log10Big,
  totalMixtures, FIT_SUBJECTS, FIT_PAIRS, crossing, PUBLISHED, bracket,
} from './public/strata/nobody-compared-three/estimator.mjs'
import {
  discriminableFraction, independentCeiling, respond, mulberry32, drawPair,
} from './public/strata/nobody-compared-three/microbe.mjs'

const ROOT = path.dirname(fileURLToPath(import.meta.url))
const PAGE_DIR = path.join(ROOT, 'public', 'strata', 'nobody-compared-three')

let pass = 0
const failures = []
function ok (label, cond, detail = '') {
  if (cond) { pass++; console.log(`  ok   ${label}${detail ? '  ' + detail : ''}`) }
  else { failures.push(label); console.log(`  FAIL ${label}${detail ? '  ' + detail : ''}`) }
}
const near = (a, b, tol) => Math.abs(a - b) <= tol
const sha256 = buf => createHash('sha256').update(buf).digest('hex')
function section (t) { console.log(`\n${t}`) }

/* ============================================ A. the source data is the source data */

section('A. the trial record')

const S1_SHA = 'e5ee025576a5c7516cd68606b01f531b8ea658eb8927656a036a967291b224ca'
const S2_SHA = '59fdf93e4709ae1e6a6efbf4e0dc7fca8d45321a1cc97e2c472ab31e306c3ca5'
ok('Table S1 bytes are the pinned bytes', sha256(readFileSync(TABLE_S1)) === S1_SHA)
ok('Table S2 bytes are the pinned bytes', sha256(readFileSync(TABLE_S2)) === S2_SHA)

const all = loadTests()
const mix = mixtureTests(all)
const ctrl = controlTests(all)

ok('128 odorants in Table S1', odorants().length === 128)
ok('26 subject columns', N_SUBJECTS === 26)
ok('264 tests', all.length === 264, `(${all.length})`)
ok('4 of them are single-molecule controls', ctrl.length === 4)
ok('260 mixture tests', mix.length === 260)
ok('every test has exactly one odd vial', mix.every(t => t.vials.filter(v => v.isOdd).length === 1))
ok('every mixture test uses exactly two distinct mixtures', mix.every(t => t.mixtures.length === 2))

const types = new Map()
for (const t of mix) { const k = `${t.n}@${t.overlapPct}`; types.set(k, (types.get(k) || 0) + 1) }
ok('13 stimulus types', types.size === 13)
ok('20 tested pairs in every type', [...types.values()].every(v => v === 20))
ok('mixture sizes are 10, 20 and 30 only', new Set(mix.map(t => t.n)).size === 3 &&
  [10, 20, 30].every(n => mix.some(t => t.n === n)))

// The two counts the paper prints about its own data.
ok('227 pairs above chance, as the paper reports',
  mix.filter(isAboveChance).length === 227, `(${mix.filter(isAboveChance).length})`)
ok('148 pairs significant at 14 or more of 26, as the paper reports',
  mix.filter(isSignificant).length === 148, `(${mix.filter(isSignificant).length})`)

// All 128 odorants are actually used, so the palette in Table S1 is the palette in play.
const used = new Set()
for (const t of mix) for (const v of t.vials) for (const c of v.components) used.add(c)
ok('all 128 odorants appear in the mixtures', used.size === 128, `(${used.size})`)

// Component counts match the declared mixture size on every vial.
ok('every vial holds exactly N components',
  mix.every(t => t.vials.every(v => v.components.length === t.n)))

// The declared overlap matches the actual shared-component count on every test.
let overlapMismatch = 0
for (const t of mix) {
  const [a, b] = t.mixtures.map(k => new Set(k.split(' + ')))
  let shared = 0
  for (const c of a) if (b.has(c)) shared++
  if (Math.abs(100 * shared / t.n - t.overlapPct) > 0.01) overlapMismatch++
}
ok('declared % overlap matches the actual ingredient lists on all 260 tests', overlapMismatch === 0,
  `(${overlapMismatch} mismatches)`)

/* ================================================= B. the estimator, twice over */

section('B. formulas (1) to (3), by two independent implementations')

// A second implementation. Nothing below imports estimator.mjs: binomials come from a
// log-gamma sum in floating point, which is a wholly different numerical route to the
// same quantity, so agreement is evidence rather than tautology.
function lgamma (x) {
  const g = [676.5203681218851, -1259.1392167224028, 771.32342877765313,
    -176.61502916214059, 12.507343278686905, -0.13857109526572012,
    9.9843695780195716e-6, 1.5056327351493116e-7]
  if (x < 0.5) return Math.log(Math.PI / Math.sin(Math.PI * x)) - lgamma(1 - x)
  x -= 1
  let a = 0.99999999999980993
  const t = x + 7.5
  for (let i = 0; i < 8; i++) a += g[i] / (x + i + 1)
  return 0.5 * Math.log(2 * Math.PI) + (x + 0.5) * Math.log(t) - t + Math.log(a)
}
const logBinom = (n, k) => (k < 0 || k > n) ? -Infinity
  : (lgamma(n + 1) - lgamma(k + 1) - lgamma(n - k + 1)) / Math.LN10
function altLogDiscInteger (C, N, R) {
  let ballLog = -Infinity
  for (let r = 0; r <= R; r++) {
    const term = logBinom(N, r) + logBinom(C - N, r)
    ballLog = ballLog === -Infinity ? term
      : Math.max(ballLog, term) + Math.log10(1 + 10 ** (-Math.abs(ballLog - term)))
  }
  return logBinom(C, N) - ballLog
}
function altLogDiscAt (C, N, pct) {
  const R = (N - N * pct / 100) / 2
  const lo = Math.floor(R), f = R - lo
  if (f === 0) return altLogDiscInteger(C, N, lo)
  const a = altLogDiscInteger(C, N, lo), b = altLogDiscInteger(C, N, lo + 1)
  return a + f * (b - a)
}
function altSci (log10, digits = 3) {
  let e = Math.floor(log10)
  let s = (10 ** (log10 - e)).toFixed(digits - 1)
  if (Number(s) >= 10) { e += 1; s = (Number(s) / 10).toFixed(digits - 1) }
  return `${s}e${e}`
}

ok('the two fitted lines cross 50% at the printed thresholds',
  near(crossing(FIT_SUBJECTS), 51.1728, 5e-4) && near(crossing(FIT_PAIRS), 57.4286, 5e-4),
  `(${crossing(FIT_SUBJECTS).toFixed(4)}, ${crossing(FIT_PAIRS).toFixed(4)})`)

for (const [pct, row] of Object.entries(PUBLISHED.disc)) {
  for (const N of [10, 20, 30]) {
    const exact = sci(discAt({ C: 128, N, overlapPct: Number(pct) }).log10)
    const alt = altSci(altLogDiscAt(128, N, Number(pct)))
    ok(`exact BigInt reproduces the published ${row[N]} at ${pct}%, N=${N}`, exact === row[N], `got ${exact}`)
    ok(`log-gamma route agrees at ${pct}%, N=${N}`, alt === row[N], `got ${alt}`)
  }
}

// The totals the paper prints for the three mixture sizes.
for (const [N, want] of Object.entries(PUBLISHED.totals)) {
  ok(`C(128,${N}) is the printed ${want}`, sci(log10Big(totalMixtures(128, Number(N)))) === want)
}

// The paper's own consistency check: 1.54e29 / 1.72e12 indiscriminable partners each.
const perMixture = log10Big(totalMixtures(128, 30)) - discAt({ C: 128, N: 30, overlapPct: 51.17 }).log10
ok('and its 8.95e16 indiscriminable partners per mixture', sci(perMixture) === PUBLISHED.indiscriminablePerMixture,
  `got ${sci(perMixture)}`)

// Formula (1) is a shell count: it must sum over R to the whole space.
let shellSum = 0n
for (let r = 0; r <= 30; r++) shellSum += binomial(30, r) * binomial(98, r)
ok('ball(30) equals the sum of all shells', ball(128, 30, 30) === shellSum)
ok('ball(0) is 1, so disc at zero radius is every mixture',
  ball(128, 30, 0) === 1n && sci(logDiscInteger(128, 30, 0)) === PUBLISHED.totals[30])

// The bound direction. Hamming (radius D/2) must exceed Gilbert-Varshamov (radius D).
const br = bracket({ C: 128, N: 30, overlapPct: 51.17 })
ok('the Hamming ceiling is above the Gilbert-Varshamov floor',
  br.hammingLog10 > br.gilbertVarshamovLog10,
  `1e${br.hammingLog10.toFixed(2)} > 1e${br.gilbertVarshamovLog10.toFixed(2)}`)
ok('and the floor is Gerkin and Castro\'s "as small as ~10,000"',
  br.gilbertVarshamovLog10 > 3.5 && br.gilbertVarshamovLog10 < 4.5,
  `1e${br.gilbertVarshamovLog10.toFixed(3)}`)
ok('the correction\'s "factor of 10 smaller" is far above that floor',
  Math.log10(1.72e11) - br.gilbertVarshamovLog10 > 6,
  `gap of ${(Math.log10(1.72e11) - br.gilbertVarshamovLog10).toFixed(1)} orders`)

/* ============================================== C. the structural claim, twice over */

section('C. what the 260 tests demonstrate')

const a = audit()
const g = buildGraph(mix)
const deg = degrees(g)

ok('520 mixture slots across 260 tests', 2 * mix.length === 520)
ok('519 distinct mixtures', a.distinctMixtures === 519, `(${a.distinctMixtures})`)
ok('so exactly one mixture is used in two tests', 520 - a.distinctMixtures === 1)
ok('no mixture is used in three tests', Math.max(...deg) === 2, `(max degree ${Math.max(...deg)})`)
ok('exactly one vertex has degree 2', deg.filter(d => d === 2).length === 1)

// Independent route to the clique number: with max degree 2 the graph is a union of
// paths and cycles, so a clique of 3 would need a triangle. Look for one directly.
const adjacency = new Map()
for (const e of g.edges) {
  if (!adjacency.has(e.a)) adjacency.set(e.a, new Set())
  if (!adjacency.has(e.b)) adjacency.set(e.b, new Set())
  adjacency.get(e.a).add(e.b)
  adjacency.get(e.b).add(e.a)
}
let triangles = 0
for (const [v, ns] of adjacency) {
  const list = [...ns]
  for (let i = 0; i < list.length; i++) {
    for (let j = i + 1; j < list.length; j++) {
      if (adjacency.get(list[i]).has(list[j])) triangles++
    }
  }
}
ok('there is no triangle anywhere in the graph', triangles === 0, `(${triangles} found)`)
ok('branch and bound agrees: the largest demonstrated set is 2', a.largestDemonstratedSet === 2)
ok('and it is still 2 over the 148 significant tests only', a.largestDemonstratedSetSignificant === 2)

ok('260 tests could have certified at most 23', a.ceilingFromAllTests === 23 &&
  23 * 22 / 2 <= 260 && 24 * 23 / 2 > 260)
ok('148 significant results, at most 17', a.ceilingFromSignificantTests === 17 &&
  17 * 16 / 2 <= 148 && 18 * 17 / 2 > 148)

// The reused mixture, named.
const seen = new Map()
for (const t of mix) for (const m of t.mixtures) { if (!seen.has(m)) seen.set(m, []); seen.get(m).push(t) }
const reused = [...seen.entries()].filter(([, ts]) => ts.length > 1)
ok('the one reused mixture appears in tests 80 and 161',
  reused.length === 1 && reused[0][1].map(t => t.uid).sort().join(',') === '161,80'.split(',').sort().join(','))
ok('it has 10 components and both its tests were significant',
  reused.length === 1 && reused[0][0].split(' + ').length === 10 && reused[0][1].every(isSignificant))

// The certification cost.
const cost = costToCertify(1.72e12)
ok('45 seconds per test, from three visits of 66 minutes over 264 tests', SECONDS_PER_TEST === 45)
ok('certifying 1.72e12 needs about 1e24.17 comparisons', near(cost.logPairs, 24.170, 0.002))
ok('which is about 1e18.32 years of sniffing', near(cost.logYears, 18.324, 0.002))
ok('and that is 8 orders of magnitude past the age of the universe',
  near(cost.logUniverseAges, 8.185, 0.01))

/* ------------------------------------- the 120-vial set, by search and by argument */

const thirty = [...new Set(mix.filter(t => t.n === 30).flatMap(t => t.mixtures))]
const sets30 = thirty.map(k => new Set(k.split(' + ')))
const thr = 30 * 51.17 / 100
const bad = []
for (let i = 0; i < sets30.length; i++) {
  for (let j = i + 1; j < sets30.length; j++) {
    let s = 0
    for (const c of sets30[i]) if (sets30[j].has(c)) s++
    if (!(s < thr)) bad.push([i, j])
  }
}
const touchCount = new Map()
for (const [i, j] of bad) { touchCount.set(i, (touchCount.get(i) || 0) + 1); touchCount.set(j, (touchCount.get(j) || 0) + 1) }
ok('160 distinct 30-component mixtures', sets30.length === 160)
ok('exactly 40 of their pairs fail the paper\'s own threshold', bad.length === 40, `(${bad.length})`)
ok('and those 40 are vertex-disjoint, so the argument applies',
  [...touchCount.values()].every(v => v === 1))
ok('so the largest set the model asserts among them is 160 - 40 = 120',
  sets30.length - bad.length === 120)
// Independent route: the exact clique search on the complement of those 40 pairs.
const gm = { nVertices: 160, edges: [] }
const badSet = new Set(bad.map(([i, j]) => `${i},${j}`))
for (let i = 0; i < 160; i++) for (let j = i + 1; j < 160; j++) if (!badSet.has(`${i},${j}`)) gm.edges.push({ a: i, b: j })
ok('exact clique search on the same graph also says 120', maxClique(gm).length === 120)
ok('checking it costs 7,140 triangle tests', 120 * 119 / 2 === 7140)
ok('which is 89.25 hours at the study\'s own pace', near(7140 * SECONDS_PER_TEST / 3600, 89.25, 1e-9))

/* ================================================== D. the bundle the page ships */

section('D. the served bytes')

ok('the page exists', existsSync(path.join(PAGE_DIR, 'index.html')))
const html = readFileSync(PAGE_HTML, 'utf8')
const shipped = embedded(html)
const rebuilt = serialise(build())
ok('the embedded bundle is byte-identical to a fresh rebuild', shipped === rebuilt,
  shipped === rebuilt ? `(${shipped.length} bytes)` : `(${shipped.length} shipped vs ${rebuilt.length} rebuilt)`)

const shippedData = JSON.parse(shipped)
ok('the bundle parses', shippedData && typeof shippedData === 'object')
ok('the bundle carries no unresolved placeholder', !html.includes('__PAGE_DATA__'))

// Head hygiene: the things a page silently loses.
for (const needle of [
  '<link rel="canonical" href="https://artwaste.land/strata/nobody-compared-three/"',
  'application/ld+json',
  'og:image',
  '</script>\n</body>\n</html>',
]) ok(`head/tail carries ${needle.slice(0, 40)}`, html.includes(needle))
ok('no third-party requests', !/https?:\/\/(?!artwaste\.land)[^"']*\.(js|css|woff2?)/.test(html))

// The prose fallbacks a reader without JavaScript sees must not be lies.
const fallback = (id, want) => {
  const m = html.match(new RegExp(`id="${id}"[^>]*>([^<]*)<`))
  ok(`no-JS fallback for #${id} is ${want}`, m && m[1].trim() === String(want), m ? `(${m[1].trim()})` : '(not found)')
}
fallback('n-slots', '520')
fallback('n-distinct', '519')
fallback('ceil-all', String(a.ceilingFromAllTests))
fallback('ceil-sig', String(a.ceilingFromSignificantTests))
fallback('spt', String(SECONDS_PER_TEST))
fallback('ms-size', String(shippedData.modelSet.size))
fallback('ms-vials', String(shippedData.modelSet.vials))
fallback('ms-nonedges', String(shippedData.modelSet.nonEdges))
fallback('ms-tests', '7,140')
fallback('ms-median', String(shippedData.modelSet.medianOverlap))
fallback('cross-subjects', '51.17')
fallback('cross-pairs', '57.43')

/* =========================================== E. run the page's own code and read it */

section('E. the page\'s own arithmetic, executed')

const elements = new Map()
function makeEl (id) {
  // A real DOM coerces textContent to a string and returns the SAME node from
  // querySelector every time. Both matter here: the page assigns numbers to
  // textContent, and it builds its tables through a querySelector'd tbody. Getting
  // either wrong makes the page look broken when it is the shim that is.
  let text = ''
  const el = {
    id, innerHTML: '', value: '0', disabled: false, clientWidth: 700,
    style: {}, children: [],
    get textContent () { return text },
    set textContent (v) { text = String(v) },
    addEventListener () {},
    appendChild (c) { this.children.push(c); this.innerHTML += (c.innerHTML || '') },
    querySelector () {
      const key = id + ':child'
      if (!elements.has(key)) elements.set(key, makeEl(key))
      return elements.get(key)
    },
    getContext () { return ctx2d },
  }
  return el
}
const noop = () => {}
const ctx2d = new Proxy({}, {
  get (t, k) {
    if (k === 'setTransform' || k === 'measureText') return k === 'measureText' ? (() => ({ width: 10 })) : noop
    return typeof k === 'string' ? noop : undefined
  },
  set () { return true },
})
globalThis.document = {
  getElementById (id) {
    if (!elements.has(id)) elements.set(id, makeEl(id))
    return elements.get(id)
  },
  createElement (tag) { return makeEl('new:' + tag) },
}
globalThis.window = {
  addEventListener: noop,
  matchMedia: () => ({ matches: false, addEventListener: noop }),
  devicePixelRatio: 1,
}
globalThis.requestAnimationFrame = cb => setTimeout(cb, 0)
globalThis.setTimeout = globalThis.setTimeout
// The page reads its bundle out of the DOM, so seed that element before importing.
elements.set('page-data', Object.assign(makeEl('page-data'), { textContent: shipped }))

let pageRan = true
try {
  await import('./public/strata/nobody-compared-three/app.js')
} catch (err) {
  pageRan = false
  console.log('    (import threw: ' + err.message + ')')
}
ok('app.js runs against a minimal DOM without throwing', pageRan)

if (pageRan) {
  const text = id => (elements.get(id) || {}).textContent || ''
  const htmlOf = id => (elements.get(id) || {}).innerHTML || ''

  ok('the page prints 51.17 for the subject-line crossing', text('cross-subjects') === '51.17')
  ok('the page prints 519 distinct mixtures', text('n-distinct') === '519')
  ok('the page prints 520 slots', text('n-slots') === '520')
  ok('the page prints ceiling 23', text('ceil-all') === '23')
  ok('the page prints 120 for the model set', text('ms-size') === '120')
  ok('the page prints 7,140 comparisons', text('ms-tests') === '7,140')
  ok('the page prints 89.3 hours', text('ms-hours') === (7140 * 45 / 3600).toFixed(1))
  ok('the page prints 27 times a subject\'s load', text('ms-load') === '27')

  // The rendered scientific strings must match independently computed values.
  const wantYears = altSci(cost.logYears, 3).split('e')
  ok('the page\'s sniffing-time figure matches the log-gamma route',
    htmlOf('cert-years').includes(wantYears[0]) && htmlOf('cert-years').includes('<sup>' + wantYears[1]),
    `(${htmlOf('cert-years')})`)
  const wantGV = altSci(br.gilbertVarshamovLog10, 3).split('e')
  ok('the page\'s Gilbert-Varshamov figure matches the log-gamma route',
    htmlOf('gv').includes(wantGV[0]) && htmlOf('gv').includes('<sup>' + wantGV[1]),
    `(${htmlOf('gv')})`)

  // The reproduction table the page builds must contain all six published figures and
  // must have marked every one as agreeing.
  const table = htmlOf('repro-table:child')
  let printed = 0
  for (const row of Object.values(PUBLISHED.disc)) {
    for (const N of [10, 20, 30]) if (table.includes(row[N].replace('e', ' × 10^'))) printed++
  }
  ok('the reproduction table prints all six published figures', printed === 6, `(${printed}/6)`)
  ok('and marks none of them as failing', !table.includes('✗'))
  ok('and the page says so in its verdict', text('repro-verdict').startsWith('All six recomputed'))

  // The two corrections this page makes to the critique it leans on.
  const g128 = discAt({ C: 128, N: 30, overlapPct: 51.17 }).log10
  const g2000 = discAt({ C: 2000, N: 30, overlapPct: 51.17 }).log10
  ok('the page recomputes the 2000-chemical figure as 8.41e39, not 1e41',
    sci(g2000) === '8.41e39' && htmlOf('gc-2000').includes('8.41'), `(${sci(g2000)})`)
  ok('and the palette exponent as 23.2, not 30',
    text('gc-exp') === ((g2000 - g128) / Math.log10(2000 / 128)).toFixed(1) && text('gc-exp') === '23.2',
    `(${text('gc-exp')})`)
  ok('the log-gamma route agrees on the 2000-chemical figure',
    altSci(altLogDiscAt(2000, 30, 51.17)) === '8.41e39', `(${altSci(altLogDiscAt(2000, 30, 51.17))})`)

  // Drive the knob and confirm what it writes.
  const p = globalThis.window.__page
  ok('the page exposes its state for checking', !!p && typeof p.knobState === 'function')
}

/* ==================================================== F. controls that must fail */

section('F. controls that must fail')

// 1. Move the threshold by one point and the reproduction must break.
ok('CONTROL: threshold off by 1 point breaks the reproduction',
  sci(discAt({ C: 128, N: 30, overlapPct: 52.17 }).log10) !== PUBLISHED.disc[51.17][30])

// 2. Use radius D instead of D/2 (the Gilbert-Varshamov convention) and it must break.
ok('CONTROL: summing to D rather than D/2 breaks the reproduction',
  sci(logDiscAtRadius(128, 30, 30 - 30 * 51.17 / 100)) !== PUBLISHED.disc[51.17][30])

// 3. Rounding the radius instead of interpolating must break at least one figure.
const roundedMatches = [10, 20, 30].filter(N => {
  const R = Math.round((N - N * 51.17 / 100) / 2)
  return sci(logDiscInteger(128, N, R)) === PUBLISHED.disc[51.17][N]
}).length
ok('CONTROL: rounding the radius reproduces none of the three figures', roundedMatches === 0,
  `(${roundedMatches}/3 matched)`)

// 4. Claim a clique of 3 and the triangle search must refuse it.
ok('CONTROL: a fabricated triangle is detected', (() => {
  const fake = { nVertices: 3, edges: [{ a: 0, b: 1 }, { a: 1, b: 2 }, { a: 0, b: 2 }] }
  return maxClique(fake).length === 3
})())
ok('CONTROL: a path of three is not a clique of three', (() => {
  const pathGraph = { nVertices: 3, edges: [{ a: 0, b: 1 }, { a: 1, b: 2 }] }
  return maxClique(pathGraph).length === 2
})())

// 5. Flip one subject response and the 148 must move.
ok('CONTROL: the 148 count is sensitive to a single flipped response', (() => {
  const borderline = mix.filter(t => t.nCorrect === 14).length
  return borderline > 0
})(), `(${mix.filter(t => t.nCorrect === 14).length} tests sit exactly on the 14 boundary)`)

// 6. The documented microbe trap: hold ONE valence draw fixed and the crossing moves.
ok('CONTROL: a single fixed valence draw moves the microbe crossing off 15', (() => {
  const rnd = mulberry32(1)
  const valences = Array.from({ length: 128 }, () => (rnd() < 0.5 ? -1 : 1))
  let crossingFixed = null
  for (let shared = 0; shared < 30; shared++) {
    let differ = 0
    const r2 = mulberry32(1000 + shared)
    const trials = 6000
    for (let t = 0; t < trials; t++) {
      const [x, y] = drawPair(r2, 128, 30, shared)
      if (respond(valences, x) !== respond(valences, y)) differ++
    }
    if (differ / trials >= 0.5) crossingFixed = shared
  }
  return crossingFixed !== null && crossingFixed !== 15
})(), '(this is the hour-long bug the module documents)')

// 7. The ensemble-averaged microbe must land on Meister's two figures.
const cf = independentCeiling(30).differ
const simCeiling = discriminableFraction({ N: 30, shared: 0, repeats: 300, pairsPerRepeat: 200, seed: 4 })
ok('the microbe ceiling matches its closed form to within Monte Carlo error',
  near(simCeiling, cf, 0.02), `(${simCeiling.toFixed(4)} vs ${cf.toFixed(4)})`)
const at15 = discriminableFraction({ N: 30, shared: 15, repeats: 300, pairsPerRepeat: 200, seed: 4 })
const at18 = discriminableFraction({ N: 30, shared: 18, repeats: 300, pairsPerRepeat: 200, seed: 4 })
ok('the microbe crosses one half within a component or two of 15',
  near(at15, 0.5, 0.02) && at18 < 0.5, `(f(15)=${at15.toFixed(4)}, f(18)=${at18.toFixed(4)})`)
ok('and feeding 15 into formula (3) gives Meister\'s ~9e11',
  near(logDiscAtRadius(128, 30, 7.5), Math.log10(9e11), 0.06),
  `(1e${logDiscAtRadius(128, 30, 7.5).toFixed(3)})`)

// The authors' counter-claim about the toy at other mixture sizes.
const ten = discriminableFraction({ N: 10, shared: 0, repeats: 300, pairsPerRepeat: 200, seed: 4 })
const tenOne = discriminableFraction({ N: 10, shared: 1, repeats: 300, pairsPerRepeat: 200, seed: 4 })
ok('at 10 components the toy peaks barely above one half and falls under it at once',
  ten > 0.5 && ten < 0.53 && tenOne < 0.5, `(f(0)=${ten.toFixed(4)}, f(1)=${tenOne.toFixed(4)})`)
ok('so the reply is right that the toy has no usable limen at N=10', tenOne < 0.5)

/* ================================================================== summary */

console.log(`\n${pass}/${pass + failures.length} checks passed`)
if (failures.length) {
  console.log('\nfailed:')
  for (const f of failures) console.log('  - ' + f)
  process.exit(1)
}
