// verify-why-is-thread-twisted.mjs: checks /strata/why-is-thread-twisted/ ("No Fibre Reaches the End")
// against the engine, lock model, data and page text it actually serves, against independent
// computations written here, and (unless --offline) against the scanned sources it quotes.
//
//   node verify-why-is-thread-twisted.mjs            # everything, including the source texts (~1.5 MB)
//   node verify-why-is-thread-twisted.mjs --offline  # proofs, arithmetic, data and page text only
//
// Needs only Node 18+. Inside the repository it tests the local files; from an empty directory it
// downloads the page's engine.mjs, lock.mjs, data/*.json and index.html from https://artwaste.land into
// ./why-is-thread-twisted-files/ (the bytes your browser runs) and imports them from there.
// Exit 0 = every check passed.

import { existsSync, readFileSync, mkdirSync, writeFileSync } from 'node:fs';
import { fileURLToPath, pathToFileURL } from 'node:url';
import { dirname, join, resolve } from 'node:path';

const here = dirname(fileURLToPath(import.meta.url));
const slug = 'why-is-thread-twisted';
const OFFLINE = process.argv.includes('--offline');
const FILES = ['engine.mjs', 'lock.mjs', 'app.mjs', 'index.html', 'data/measurements.json', 'data/breaks1935.json', 'data/lock-summary.json', 'data/lock-N20.json', 'data/lock-N30.json', 'data/lock-N50.json'];
let dir = join(here, 'public/strata', slug);
if (!existsSync(join(dir, 'engine.mjs'))) {
  dir = resolve(`${slug}-files`);
  for (const f of FILES) {
    const r = await fetch(`https://artwaste.land/strata/${slug}/${f}`);
    if (!r.ok) throw new Error(`could not download ${f}: ${r.status}`);
    mkdirSync(dirname(join(dir, f)), { recursive: true }); writeFileSync(join(dir, f), Buffer.from(await r.arrayBuffer()));
  }
}
console.error(`files: ${dir}`);
const E = await import(pathToFileURL(join(dir, 'engine.mjs')).href);
const LK = await import(pathToFileURL(join(dir, 'lock.mjs')).href);
const J = (f) => JSON.parse(readFileSync(join(dir, f), 'utf8'));
const MEAS = J('data/measurements.json'), BR = J('data/breaks1935.json'), SUM = J('data/lock-summary.json');
const html = readFileSync(join(dir, 'index.html'), 'utf8');
const app = readFileSync(join(dir, 'app.mjs'), 'utf8');
const plain = html.replace(/<script[\s\S]*?<\/script>/g, ' ').replace(/<[^>]+>/g, ' ').replace(/&amp;/g, '&').replace(/\s+/g, ' ');

let fails = 0, passes = 0;
const ok = (c, msg) => { if (c) passes++; else fails++; console.log((c ? 'PASS  ' : 'FAIL  ') + msg); };
const near = (a, b, tol) => Math.abs(a - b) <= tol;
const say = (s) => plain.includes(s);

// ── 1. the lock: proofs on both sides of each threshold ──────────────────────────────────────────
for (const N of [20, 30, 50]) {
  const rec = J(`data/lock-N${N}.json`), c = rec.cert;
  const S = LK.buildAssembly({ seed: rec.seed, N: rec.N });
  // the structure is what the page says it is
  const perCol = new Array(S.K).fill(0);
  S.fibres.forEach((fb) => { for (let j = 0; j < S.N; j++) perCol[(fb.start + j) % S.K]++; });
  ok(S.F === 80 && S.m === 20 && S.K === 4 * N && perCol.every((v) => v === 20) && S.contacts.length === 10 * S.K && S.lone.length === 0,
    `N=${N}: 80 fibres in 20 rows of 4, every one of ${S.K} cross-sections crossed by exactly 20 fibres, ${S.contacts.length} contacts, none unpaired`);
  const L = LK.checkLocked(S, c.lockedAt, c.T);
  ok(L.ok, `N=${N}: the locking tension state obeys every cap and balance at N*lambda = ${(N * c.lockedAt).toFixed(3)} (worst excess ${L.rel.toExponential(1)} of the largest tension)`);
  const U = LK.checkUnlocked(S, c.slidesAt, c);
  ok(U.ok && U.min > 0.99, `N=${N}: the Farkas certificate proves sliding at N*lambda = ${(N * c.slidesAt).toFixed(3)} (every coefficient >= ${U.min.toFixed(4)})`);
  ok(!LK.checkLocked(S, c.slidesAt, c.T).ok && !LK.checkUnlocked(S, c.lockedAt, c).ok, `N=${N}: swapped, both proofs fail (they are not vacuous)`);
  ok(LK.checkLocked(S, 2 * c.lockedAt, c.T).ok && LK.checkUnlocked(S, 0.5 * c.slidesAt, c).ok, `N=${N}: the locking proof holds at double the grip and the sliding proof at half, as monotonicity says`);
  const T2 = c.T.map((t) => 1000 * t);
  ok(LK.checkLocked(S, c.lockedAt, T2).ok, `N=${N}: the locked state scaled by 1000 still passes (the problem has no scale)`);
  const bad = { ...c, p: c.p.slice() }; const k = bad.p.findIndex((x) => x > 1e-3); bad.p[k] = -bad.p[k];
  ok(!LK.checkUnlocked(S, c.slidesAt, bad).ok && !LK.checkLocked(S, c.lockedAt, c.T.map(() => 0)).ok, `N=${N}: a corrupted certificate and an all-zero state are both rejected`);
  const loads = LK.crossLoads(S, c.T), lmax = Math.max(...loads), lmin = Math.min(...loads);
  ok((lmax - lmin) / lmax < 1e-8, `N=${N}: the load is the same across all ${S.K} cross-sections (spread ${((lmax - lmin) / lmax).toExponential(1)})`);
  ok(near(c.slidesAt, 0.99 * rec.lamLo, 1e-12) && near(c.lockedAt, 1.01 * rec.lamHi, 1e-12) && (rec.lamHi - rec.lamLo) / rec.lamHi < 3e-4,
    `N=${N}: proofs sit 1% outside the solver's bracket [${rec.lamLo.toFixed(5)}, ${rec.lamHi.toFixed(5)}], which is ${(1e2 * (rec.lamHi - rec.lamLo) / rec.lamHi).toFixed(3)}% wide`);
  const row = SUM.byN.find((r) => r.N === N), i = row.seeds.indexOf(rec.seed);
  ok(i >= 0 && near(row.values[i], N * (rec.lamLo + rec.lamHi) / 2, 1e-3), `N=${N}: the showcased tangle is seed ${rec.seed} of the sweep, threshold ${row.values[i]}`);
}
// every tension shown is zero at the fibre ends by construction: the unknowns simply omit them
{
  const S = LK.buildAssembly({ seed: 1, N: 30 });
  ok(LK.vid(S, 0, 0) === -1 && LK.vid(S, 0, 30) === -1 && LK.nVars(S) === 80 * 29, 'fibre end elements carry no unknown (they are fixed at zero): 80 fibres x 29 interior elements');
}

// ── 2. the sweep ──────────────────────────────────────────────────────────────────────────────────
{
  const med = (a) => { const s = [...a].sort((x, y) => x - y), n = s.length; return n % 2 ? s[(n - 1) / 2] : (s[n / 2 - 1] + s[n / 2]) / 2; };
  let good = true, total = 0, never = 0, partial = 0;
  for (const r of SUM.byN) {
    total += r.values.length;
    r.values.forEach((v, i) => { const [lo, hi] = r.brackets[i], part = r.partial && r.partial[i]; if (part) partial++; if (!near(v, r.N * (lo + hi) / 2, 1e-3) || !(hi > lo) || (!part && (hi - lo) / hi > 3e-4)) good = false; if (!part && hi >= 2 - 1e-3) never++; });
    if (!near(r.median, med(r.values.filter((_, i) => !(r.partial && r.partial[i]))), 1e-3)) good = false;
  }
  ok(good && total === SUM.total && never === SUM.neverBelow2 && partial === (SUM.partial || 0), `sweep: ${SUM.total} tangles, every value is N x the midpoint of its bracket, every bracket narrower than 0.03% except the ${partial} marked partial, medians recomputed over the rest, ${never} that lock only at lambda = 2`);
  const big = SUM.byN.filter((r) => r.N >= 30);
  ok(big.every((r) => r.median >= 6.8 && r.median <= 7.6), `sweep: for N >= 30 every median lies between 6.8 and 7.6 (${big.map((r) => `N${r.N} ${r.median.toFixed(2)}`).join(', ')}); the paper reports 7.3 +/- 0.2`);
  const ms = SUM.byN.filter((r) => r.N >= 20).map((r) => r.median);
  ok(ms.every((m, i) => i === 0 || m <= ms[i - 1] + 0.1), 'sweep: medians fall toward the mean-field limit as fibres lengthen (N >= 20)');
}

// ── 3. the mean-field threshold ───────────────────────────────────────────────────────────────────
{
  const mf = E.meanField();
  // Dawson's integral against its power series, F(x) = sum (-1)^n 2^n x^(2n+1) / (1*3*...*(2n+1))
  const series = (x) => { let s = 0, t = x; for (let n = 0; n < 80; n++) { s += t; t *= -2 * x * x / (2 * n + 3); } return s; };
  let w = 0; for (const x of [0.1, 0.5, 0.924, 1, 1.5, 2]) w = Math.max(w, Math.abs(E.dawson(x) - series(x)));
  ok(w < 1e-10, `Dawson's integral by quadrature matches its power series (worst ${w.toExponential(1)})`);
  // 2 x F(x) = 1 is F'(x) = 0: x0 is where Dawson's integral peaks, tabulated as 0.9241388730
  ok(near(mf.x0, 0.924138873, 1e-8), `x0 = ${mf.x0.toFixed(9)}, the maximum of Dawson's integral (tabulated 0.9241388730); the paper prints 0.924`);
  ok(near(mf.Lc, 3.416, 5e-4) && near(mf.NlamC, 6.83, 5e-3), `Lambda_c = 4 x0^2 = ${mf.Lc.toFixed(4)} (paper 3.416), N lambda_c = ${mf.NlamC.toFixed(3)} (paper 6.83)`);
  let res = 0; const M = 4000;
  for (const s of [0.05, 0.2, 0.37, 0.5, 0.63, 0.8, 0.95]) {
    const d = 1e-5, dT = (mf.T(s + d) - mf.T(s - d)) / (2 * d);
    let I = 0; for (let j = 0; j < M; j++) { const sp = (j + 0.5) / M; I += Math.sign(sp - s) * (mf.T(s) + mf.T(sp)) / M; }
    res = Math.max(res, Math.abs(dT - mf.Lc * I));
  }
  let mean = 0; for (let j = 0; j < M; j++) mean += mf.T((j + 0.5) / M) / M;
  ok(res < 1e-3 && Math.abs(mf.T(0)) < 1e-12 && Math.abs(mf.T(1)) < 1e-12 && near(mean, 1, 1e-4), `T(s) solves dT/ds = Lambda_c * int sgn(s'-s)[T(s)+T(s')] ds' (worst residual ${res.toExponential(1)}), vanishes at both ends, and has mean ${mean.toFixed(5)}`);
  ok(say(`x₀ =`) && app.includes('mf.x0.toFixed(5)') && app.includes('mf.NlamC.toFixed(3)'), 'the page prints these numbers from the engine, not by hand');
}

// ── 4. helix geometry ─────────────────────────────────────────────────────────────────────────────
{
  // curvature of r(t) = (rho cos t, rho sin t, c t) by finite differences, against sin^2(theta)/rho
  let w = 0;
  for (const rho of [0.05, 0.14, 1]) for (const thDeg of [5, 20, 35, 60]) {
    const th = thDeg * E.DEG, c = rho / Math.tan(th), h = 1e-4;
    const P = (t) => [rho * Math.cos(t), rho * Math.sin(t), c * t];
    const d1 = [0, 1, 2].map((k) => (P(h)[k] - P(-h)[k]) / (2 * h)), d2 = [0, 1, 2].map((k) => (P(h)[k] - 2 * P(0)[k] + P(-h)[k]) / (h * h));
    const cr = [d1[1] * d2[2] - d1[2] * d2[1], d1[2] * d2[0] - d1[0] * d2[2], d1[0] * d2[1] - d1[1] * d2[0]];
    const kappa = Math.hypot(...cr) / Math.hypot(...d1) ** 3;
    w = Math.max(w, Math.abs(kappa / E.helixCurvature(rho, th) - 1));
  }
  ok(w < 1e-5, `helix curvature sin^2(theta)/rho matches a numerical helix (worst relative ${w.toExponential(1)})`);
  // cross-section averages by quadrature over area, with tan(theta) = (rho/R) tan(alpha)
  let w1 = 0, w2 = 0;
  for (const aDeg of [5, 15, 25, 40]) {
    const a = aDeg * E.DEG, R = 0.2, n = 20000; let k = 0, c4 = 0;
    for (let i = 0; i < n; i++) { const x = (i + 0.5) / n, th = Math.atan(x * Math.tan(a)); k += (x > 0 ? E.helixCurvature(x * R, th) : 0) * 2 * x / n; c4 += Math.cos(th) ** 4 * 2 * x / n; }
    w1 = Math.max(w1, Math.abs(k / E.meanCurvature(R, a) - 1)); w2 = Math.max(w2, Math.abs(c4 / Math.cos(a) ** 2 - 1));
  }
  ok(w1 < 1e-6, `area-averaged curvature (2/R)(1 - a/tan a) matches quadrature (worst relative ${w1.toExponential(1)})`);
  ok(w2 < 1e-6, `area average of cos^4(theta) is exactly cos^2(a), the tilt-only strength factor (worst relative ${w2.toExponential(1)})`);
}

// ── 5. the 1935 tables: two transcriptions, and the table against itself ──────────────────────────
{
  let agree = true;
  for (const k of ['10s', '80s']) {
    const t = BR.tables[k], rows = MEAS.schiefer1935.yarns[k].rows;
    rows.forEach((r, j) => { if (t.tm[j] !== r.M || +t.average[j] !== r.y || +t.sd[j] !== r.sd || +t.cv[j] !== r.cv || +t.cvPm[j] !== r.cvPm) agree = false; });
  }
  ok(agree, 'the summary rows transcribed twice, independently (measurements.json and breaks1935.json), agree in every twist, average, deviation and coefficient of variation');
  let sums = true, total = 0; const meanMiss = [], sdMiss = [];
  for (const k of ['10s', '80s']) {
    const t = BR.tables[k], dp = k === '10s' ? 0.05 : 0.005, sdp = k === '10s' ? 0.015 : 0.005;
    t.tm.forEach((tm, j) => {
      const col = t.counts.map((row) => row[j]), n = col.reduce((a, b) => a + b, 0);
      total += n; if (n !== 100) sums = false;
      const mean = t.mids.reduce((s, m, i) => s + m * col[i], 0) / n;
      const sd = Math.sqrt(t.mids.reduce((s, m, i) => s + col[i] * (m - mean) ** 2, 0) / n);
      if (!near(mean, +t.average[j], dp)) meanMiss.push(`${k} M ${tm}: printed ${t.average[j]}, counts ${mean.toFixed(3)}`);
      if (!near(sd, +t.sd[j], sdp)) sdMiss.push(`${k} ${tm}`);
    });
  }
  ok(sums && total === 3200, `every one of the 32 columns sums to 100 breaks: ${total} in all (80s M 6.66 prints its total as "00")`);
  ok(meanMiss.length === 1 && meanMiss[0].startsWith('80s M 4.07'), `31 of 32 printed averages match their own counts to rounding; the one that does not: ${meanMiss.join('; ')}`);
  ok(sdMiss.join(',') === '10s 4.5,10s 7,80s 3.33,80s 3.86,80s 6.37,80s 6.66', `26 of 32 printed standard deviations match the population deviation of their own counts; these 6 do not: ${sdMiss.join(', ')} (the page uses printed deviations only for error bars)`);
  // printed V against printed A and SD, with each printed value's rounding interval
  const vMiss = [];
  for (const k of ['10s', '80s']) {
    const t = BR.tables[k], da = k === '10s' ? 0.05 : 0.005, ds = k === '10s' ? 0.005 : 0.0005;
    t.tm.forEach((tm, j) => {
      const a = +t.average[j], s = +t.sd[j], v = +t.cv[j];
      const lo = 100 * (s - ds) / (a + da), hi = 100 * (s + ds) / (a - da);
      if (v + 0.05 < lo || v - 0.05 > hi) vMiss.push(`${k} M ${tm}`);
    });
  }
  ok(vMiss.length === 1 && vMiss[0] === '80s M 4.07', `every printed coefficient of variation is its printed deviation over its printed average, within rounding, except ${vMiss.join(', ')}`);
  const t = BR.tables['80s'], j = t.tm.indexOf(4.07), col = t.counts.map((r) => r[j]);
  const mean = t.mids.reduce((s, m, i) => s + m * col[i], 0) / 100;
  ok(near(100 * 0.618 / mean, 14.6, 0.05) && !near(100 * 0.618 / 4.27, 14.6, 0.05), `the misprint: 0.618 / ${mean.toFixed(3)} = ${(100 * 0.618 / mean).toFixed(2)}% (printed V 14.6), while 0.618 / 4.27 = ${(100 * 0.618 / 4.27).toFixed(2)}%`);
  ok(say('3,200') && say('31 of the 32 printed averages') && app.includes("t.tm.indexOf(4.07)"), 'the page states 3,200 breaks and 31 of 32, and works the misprint from the counts it serves');
}

// ── 6. the 1925 table and the angle rule ──────────────────────────────────────────────────────────
{
  const rows = MEAS.mcgowan1925.rows;
  const off = rows.filter((r) => !near(r.tpi / Math.sqrt(7), r.M, 0.011)); // within one unit of the last printed place
  ok(rows.length === 19 && off.length === 1 && off[0].no === 9, `McGowan et al. 1925: 18 of 19 printed twist multipliers are turns per inch over the square root of 7, to within one unit in the last place; row ${off.map((r) => `${r.no} prints ${r.tpi} turns and ${r.M}, where ${r.tpi}/sqrt 7 = ${(r.tpi / Math.sqrt(7)).toFixed(3)}`).join('; ')}`);
  ok(say('13.07 turns per inch') && say('4.96'), 'the page names that inconsistency');
  const ang = rows.map((r) => ({ M: r.M, deg: r.deg })), fit = E.fitK(ang);
  const rms28 = Math.sqrt(ang.reduce((s, p) => s + (E.alphaOf(p.M, 28) / E.DEG - p.deg) ** 2, 0) / ang.length);
  ok(near(rms28, 2.1, 0.05) && near(fit.rms, 1.0, 0.05) && near(fit.K, 30.3, 0.05), `their microscope angles sit ${rms28.toFixed(2)} degrees rms from tan a = pi M / 28; the best constant is ${fit.K.toFixed(2)} (${fit.rms.toFixed(2)} degrees rms)`);
  const heavier = rows[18].grains120yd / rows[0].grains120yd - 1;
  ok(near(heavier, 0.16, 0.01), `the 1925 yarn grew ${(100 * heavier).toFixed(1)}% heavier per 120 yards from lowest to highest twist (the page computes this from the table)`);
}

// ── 7. every number the page's prose states ───────────────────────────────────────────────────────
{
  const K = 28, Y10 = MEAS.schiefer1935.yarns['10s'].rows, Y80 = MEAS.schiefer1935.yarns['80s'].rows;
  const R10 = 25.4 / (2 * K * Math.sqrt(10)), R80 = 25.4 / (2 * K * Math.sqrt(80)), L10 = 25.4, L80 = (1 + 5 / 16) * 25.4;
  const lockM = (L, R, mu, mean) => E.mOfAlpha(E.lockAngle({ L, R, mu, mean }), K);
  const lo10 = lockM(L10, R10, 0.4, false), hi10 = lockM(L10, R10, 0.3, true), hi80 = lockM(L80, R80, 0.3, true);
  ok(near(lo10, 3.0, 0.06) && near(hi10, 4.2, 0.05) && say('about 3.0 and 4.2'), `10s lock band for mu 0.3 to 0.4: M ${lo10.toFixed(2)} to ${hi10.toFixed(2)} ("about 3.0 and 4.2")`);
  ok(hi80 < 2.1 && say('below 2.1'), `80s lock is below M 2.1 for mu 0.3 to 0.4 (at most ${hi80.toFixed(2)})`);
  ok(near(R10 / R80, 2.83, 0.01) && near(L80 / L10, 1.31, 0.01) && say('2.8 times thinner') && say('1.3 times longer'), `80s yarn ${(R10 / R80).toFixed(2)} times thinner, fibres ${(L80 / L10).toFixed(2)} times longer`);
  ok(near(Y80[0].y / E.measuredPeak(Y80).y, 0.79, 0.005) && say('79% of the best'), `80s at M 2.48 held ${(100 * Y80[0].y / E.measuredPeak(Y80).y).toFixed(1)}% of its best`);
  ok(near(7 / 0.4, 17.5, 1e-9) && near(7 / 0.3, 23.3, 0.05) && say('18 to 23 radians'), 'mu Theta = 7 with mu 0.3 to 0.4 needs Theta of 17.5 to 23.3 radians ("something like 18 to 23")');
  const tex = E.texOfCount(10), den = 0.1 / 0.9; // 1 denier = 1/9 tex
  const nLo = tex / (2.3 * den), nHi = tex / (0.7 * den);
  ok(near(tex, 59, 0.1) && near(nLo, 230, 2) && near(nHi, 759, 2) && say('59 tex') && say('between about 230 and 760'), `10s is ${tex.toFixed(2)} tex; at 0.7 to 2.3 denier per fibre that is ${nLo.toFixed(0)} to ${nHi.toFixed(0)} fibres per cross-section`);
  ok(near(L10 / (2 * R10), 88.5, 0.5) && say('about 90 times the yarn'), `a 1-inch fibre is ${(L10 / (2 * R10)).toFixed(1)} times the 10s yarn's width`);
  const a375 = E.alphaOf(3.75, K);
  ok(near(a375 / E.DEG, 22.8, 0.05) && near(3.75 * Math.sqrt(10), 11.9, 0.05), `at M 3.75 the hero reads ${(a375 / E.DEG).toFixed(2)} degrees and ${(3.75 * Math.sqrt(10)).toFixed(2)} turns per inch`);
  // the cost paragraph, recomputed the way the page does
  const cost = (rows) => { const pk = E.measuredPeak(rows), last = rows[rows.length - 1]; const past = rows.filter((r) => r.M > pk.M); return { got: last.y / pk.y, allow: E.obliquityFrom(pk, last.M, K) / pk.y, below: past.filter((r) => r.y < E.obliquityFrom(pk, r.M, K) - 1e-9).length, past: past.length }; };
  const c10 = cost(Y10), c80 = cost(Y80), c25 = cost(MEAS.mcgowan1925.rows);
  ok(Math.round(100 * c10.got) === 48 && Math.round(100 * c10.allow) === 58 && c10.below === 3 && c10.past === 7, `10s ends at ${(100 * c10.got).toFixed(1)}% of its best against a tilt-only ${(100 * c10.allow).toFixed(1)}%; ${c10.below} of ${c10.past} points past the peak fall below`);
  ok(Math.round(100 * c80.got) === 69 && Math.round(100 * c80.allow) === 73, `80s ends at ${(100 * c80.got).toFixed(1)}% against ${(100 * c80.allow).toFixed(1)}% (${c80.below} of ${c80.past} below)`);
  ok(Math.round(100 * c25.got) === Math.round(100 * c25.allow), `the 1925 Pima yarn ends at ${(100 * c25.got).toFixed(1)}% against ${(100 * c25.allow).toFixed(1)}%: on the line`);
  const W = MEAS.wadc1952; let maxRise = 0;
  for (const v of Object.values(W.series)) maxRise = Math.max(maxRise, Math.max(...v.filter((x) => x != null)) / v[0] - 1);
  ok(near(100 * maxRise, 4.7, 0.05) && near(E.measuredPeak(Y10).y / Y10[0].y, 3.8, 0.05), `no nylon series rose more than ${(100 * maxRise).toFixed(2)}%; the 10s cotton rose ${(E.measuredPeak(Y10).y / Y10[0].y).toFixed(2)}-fold`);
  const cvs = MEAS.schiefer1935.yarns['10s'].rows; const minCv = cvs.reduce((a, b) => (b.cv < a.cv ? b : a));
  ok(minCv.M === E.measuredPeak(Y10).M && minCv.cv === 8, `the 10s yarn's tightest spread (${minCv.cv}%) is at its strongest twist (M ${minCv.M})`);
  ok(say('41,000 and 52,000') && say('6.2 mm') && say('7.3 ± 0.2') && say('1638'), 'page carries the sourced figures it quotes (6.2 mm, 41,000 to 52,000 years, 7.3 +/- 0.2, 1638)');
  ok(!/—/.test(plain), 'no em dash in the page text');
}

// ── 8. the quotations, against the sources' own text ──────────────────────────────────────────────
if (OFFLINE) console.log('SKIP  source texts (--offline)');
else {
  const norm = (s) => s.replace(/[‘’]/g, "'").replace(/[“”]/g, '"').replace(/-\s+\n?\s*/g, '').replace(/\s+/g, ' ').toLowerCase();
  const get = async (u) => { const r = await fetch(u); if (!r.ok) throw new Error(`${u}: ${r.status}`); return norm(await r.text()); };
  const src = {
    galileo: await get('https://archive.org/download/dialoguesconcern00galiuoft/dialoguesconcern00galiuoft_djvu.txt'),
    s35: await get('https://archive.org/download/jresv15n3p237/jresv15n3p237_A1b_djvu.txt'),
    m25: await get('https://archive.org/download/effectoftwisto1925278mcgo/effectoftwisto1925278mcgo_djvu.txt'),
    h31: await get('https://archive.org/download/relationbetweent74617hamm/relationbetweent74617hamm_djvu.txt'),
    hardy: (await get('https://www.nature.com/articles/s41598-020-61839-w')).replace(/<[^>]+>/g, ' ').replace(/\s+/g, ' '),
  };
  // [source, text, is it quoted on the page (true) or a fact the page restates in its own words (false)]
  const quotes = [
    ['galileo', 'The first question is, How are fibres, each not more than two or three cubits in length, so tightly bound together in the case of a rope one hundred cubits long that great force [violenza] is required to break it?', true],
    ['galileo', 'the very act of twisting causes the threads to bind one another in such a way that when the rope is stretched with a great force the fibres break rather than separate from each other.', true],
    ['galileo', 'ropes sometimes break not by a lengthwise pull but by excessive twisting.', true],
    ['s35', 'introduces torsional forces or shearing stresses in the individual fibers thereby decreasing their breaking strength in tension', true],
    ['s35', 'maximum strength of fine yarns is obtained at lower twist multipliers than in coarse yarn', true],
    ['s35', 'the longer fibers require less twist to increase the resistance of fiber slippage', true],
    ['s35', 'was presented by Joseph Kochlin on November 28, 1828, before the Societe Industrielle de Mulhouse', false],
    ['m25', 'can be continued until the yarn breaks under no longitudinal strain, but merely from the shearing action of the twisting.', true],
    ['h31', 'is not materially changed with an increase in twist up to about 20 turns per inch, but that it decreases rapidly with increase in twist beyond 20 turns.', true],
    ['hardy', '3 bundles of fibres with S-twist which were then plied together with a Z-twist to form a 3-ply cord', true],
    ['hardy', 'in the opposite direction to prevent unravelling', true],
    ['hardy', 'dating to between 41 and 52 ka', false],
    ['hardy', 'approximately 6.2 mm in length', false],
  ];
  // OCR is imperfect ("twdst" for "twist"), so a quote passes if some window of the source is within a
  // small edit distance of it (4% of its length); the distance is printed so a reader sees how close
  // "found" was. Candidate windows are anchored on five short pieces of the quote.
  const lev = (a, b) => { const m = a.length, n = b.length; let prev = Array.from({ length: n + 1 }, (_, j) => j); for (let i = 1; i <= m; i++) { const cur = [i]; for (let j = 1; j <= n; j++) cur[j] = Math.min(prev[j] + 1, cur[j - 1] + 1, prev[j - 1] + (a[i - 1] === b[j - 1] ? 0 : 1)); prev = cur; } return prev[n]; };
  const pagePlain = norm(plain + ' ' + app); // some prose is written by app.mjs from the data
  for (const [k, q0, quoted] of quotes) {
    const q = norm(q0), s = src[k], allowed = Math.ceil(q.length * 0.04);
    let best = s.includes(q) ? 0 : Infinity;
    for (let f = 0; f < 5 && best > 0; f++) {
      const off = Math.floor((f / 5) * (q.length - 10)), piece = q.slice(off, off + 10);
      for (let i = s.indexOf(piece); i >= 0 && best > 0; i = s.indexOf(piece, i + 1)) {
        for (let d = -6; d <= 6; d += 2) { const st = Math.max(0, i - off + d); const x = lev(q, s.slice(st, st + q.length)); if (x < best) best = x; }
      }
    }
    ok(best <= allowed, `source ${k} contains (edit distance ${best} of ${q.length}, allowed ${allowed}): "${q0.slice(0, 64)}..."`);
    if (quoted) ok(pagePlain.includes(q), `  and the page quotes it exactly`);
  }
}

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