// verify-two-threads-that-never-disagree.mjs
//
// The check behind /strata/two-threads-that-never-disagree/.
//
// Five kinds of check, in order of how much they could hurt:
//
//   1. THE THEOREM, BRUTE-FORCED. For several small loom sizes, enumerate every
//      threading, every tie-up and every treadling the loom admits, collect the
//      complete set of cloths the machine can physically produce, and compare it
//      against the set the theorem predicts (at most S distinct columns, at most
//      T distinct rows). This knows nothing about the theorem: it is the loom,
//      run by hand, over its entire configuration space.
//   2. THE FACTORISATION ROUND TRIP. Random cloths are factored back into a loom
//      and rewoven; the result must be identical, and the shaft count must equal
//      the distinct-column count.
//   3. THE SATIN ARITHMETIC and its coincidence with the crystallographic
//      restriction, computed three independent ways and cross-tabulated.
//   4. EVERY NUMBER PRINTED ON THE PAGE, recomputed here and matched against the
//      page's own HTML source, so the prose cannot drift from the maths.
//   5. THE PAGE ITSELF, driven headless: the engine block in the page is
//      extracted and run against the offline engine on thousands of random
//      inputs (so the two are provably the same function), the instrument is
//      exercised, and the layout is checked for overflow at three widths.
//   5b. IS IT CLOTH (added 2026-09-26): fitToLoom reports how many pieces the
//      cloth it returns comes off the loom in, checked against two counters
//      written fresh in this file, on a known cloth and on built double and
//      triple cloths, and on the page's own engine at widths past 31 ends.
//
// Run:  npm install && npm run build && node verify-two-threads-that-never-disagree.mjs

import { readFileSync } from 'node:fs';
import { createServer } from 'node:http';
import { extname, join } from 'node:path';
import * as E from './research/weaving-drafts/engine.mjs';

const PAGE = 'public/strata/two-threads-that-never-disagree/index.html';
const html = readFileSync(PAGE, 'utf8');

let fails = 0, checks = 0;
const ok = (name, cond, extra = '') => {
  checks++; if (!cond) fails++;
  console.log(`${cond ? '  ok' : 'FAIL'}  ${name}${extra ? '   ' + extra : ''}`);
};
const section = (s) => console.log(`\n── ${s} ${'─'.repeat(Math.max(0, 62 - s.length))}`);

// ═════════════════════════════════════════════ 1. the theorem, brute-forced

section('1. the shaft theorem, brute-forced over whole loom configuration spaces');

const SWEEPS = [
  // [picks, ends, shafts, treadles]
  [3, 3, 2, 2],
  [3, 3, 3, 2],
  [4, 3, 2, 3],
  [4, 4, 2, 2],
  [4, 4, 3, 3],
];
let sweptMatrices = 0, sweptDisagreements = 0;
const sweepRows = [];
for (const [m, n, S, T] of SWEEPS) {
  const reachable = E.enumerateWeavable(m, n, S, T);
  let predicted = 0, disagree = 0, total = 0;
  for (const key of E.allMatrices(m, n)) {
    total++;
    const D = E.keyToMatrix(key, m, n);
    const theorem = E.minShafts(D) <= S && E.minTreadles(D) <= T;
    if (theorem) predicted++;
    if (theorem !== reachable.has(key)) disagree++;
  }
  sweptMatrices += total; sweptDisagreements += disagree;
  sweepRows.push({ m, n, S, T, total, reachable: reachable.size, predicted, disagree });
  ok(`${m}x${n} cloth on ${S} shafts / ${T} treadles: loom reaches ${reachable.size}, theorem predicts ${predicted}`,
     disagree === 0 && reachable.size === predicted, `${total} matrices, ${disagree} disagreements`);
}
ok(`every matrix in every sweep agrees (${sweptMatrices} matrices total)`, sweptDisagreements === 0,
   `${sweptDisagreements} disagreements`);

// The one sweep quoted on the page.
const quoted = sweepRows.find((r) => r.m === 4 && r.n === 4 && r.S === 3 && r.T === 3);
ok('the 4x4 on 3 shafts figure quoted on the page is 12040 of 65536',
   quoted.reachable === 12040 && quoted.total === 65536, `${quoted.reachable} of ${quoted.total}`);

// ═════════════════════════════════════════════ 2. the factorisation round trip

section('2. the factorisation round trip');

let seed = 0x5eed1;
const rnd = () => { seed = (seed * 1103515245 + 12345) & 0x7fffffff; return seed / 0x7fffffff; };
let rtOk = 0, rtBad = 0, shaftMismatch = 0;
for (let trial = 0; trial < 2000; trial++) {
  const m = 1 + Math.floor(rnd() * 14), n = 1 + Math.floor(rnd() * 14);
  const D = Array.from({ length: m }, () => Array.from({ length: n }, () => (rnd() < 0.5 ? 1 : 0)));
  const R = E.reconstruct(D);
  if (E.reproduces(D, R)) rtOk++; else rtBad++;
  if (R.shafts !== E.minShafts(D) || R.treadles !== E.minTreadles(D)) shaftMismatch++;
}
ok('2000 random cloths factor into a loom and reweave identically', rtBad === 0, `${rtOk} ok, ${rtBad} bad`);
ok('the factorisation always uses exactly the minimum shafts and treadles', shaftMismatch === 0,
   `${shaftMismatch} mismatches`);

// The reconstruction is minimal, checked the hard way on every small cloth:
// no (threading, tie-up, treadling) with fewer shafts can produce it.
let minimalityTested = 0, minimalityFail = 0;
const reachCache = new Map();                              // 3 picks means 3 treadles is never a limit
const reachOneShaftShort = (S) => {
  if (!reachCache.has(S)) reachCache.set(S, E.enumerateWeavable(3, 4, S, 3));
  return reachCache.get(S);
};
for (const key of E.allMatrices(3, 4)) {
  const D = E.keyToMatrix(key, 3, 4);
  const need = E.minShafts(D);
  if (need < 2) continue;                                  // one shaft short of one shaft is no loom at all
  minimalityTested++;
  if (reachOneShaftShort(need - 1).has(key)) minimalityFail++;
}
ok(`no cloth is weavable one shaft below its distinct-column count (${minimalityTested} cloths)`,
   minimalityFail === 0, `${minimalityFail} counterexamples`);

// ═════════════════════════════════════════════ 3. satins and crystals

section('3. the satin arithmetic and the crystallographic restriction');

const NMAX = 100000;
const noSatin = [], phiSmall = [], latticeOK = [];
for (let n = 1; n <= NMAX; n++) {
  if (n <= 400) {
    if (!E.satinExists(n)) noSatin.push(n);
    if (E.totient(n) <= 2) phiSmall.push(n);
  }
  if (E.latticeTrace(n).isInteger) latticeOK.push(n);
}
const EXPECTED = '1,2,3,4,6';
ok(`no regular satin exists exactly for n in {${EXPECTED}} (swept n <= 400)`, noSatin.join(',') === EXPECTED, noSatin.join(','));
ok(`phi(n) <= 2 exactly for n in {${EXPECTED}} (swept n <= 400)`, phiSmall.join(',') === EXPECTED, phiSmall.join(','));
ok(`2*cos(2*pi/n) is an integer exactly for n in {${EXPECTED}} (swept n <= ${NMAX})`,
   latticeOK.join(',') === EXPECTED, latticeOK.join(','));

// The numeric sweep above needs its own margin stated, not assumed: at the top of
// the sweep the gap between 2*cos(2*pi/n) and 2 must still be far above both the
// tolerance used and double-precision noise. (An earlier draft of this file swept
// to 200000 against a 1e-9 tolerance and the sweep silently swallowed everything
// past n = 198692 as "integer". That is exactly the failure this check exists to
// catch, and it caught it.)
const gapAtTop = 2 - E.latticeTrace(NMAX).trace;
const margin = gapAtTop / E.LATTICE_TOL;
ok(`the numeric test has room at the top of its sweep (gap ${gapAtTop.toExponential(2)}, ${Math.round(margin)}x the tolerance)`,
   margin > 1000, `margin ${margin.toExponential(2)}`);

// And the argument that closes it for ALL n, not just the swept range: the trace
// lies in (-2, 2], so an integer trace must be one of five values, and each of
// those pins n exactly.
const pinned = [];
for (const t of [-2, -1, 0, 1, 2]) {
  for (let n = 1; n <= 5000; n++) if (Math.abs(E.latticeTrace(n).trace - t) < 1e-12) pinned.push(n);
}
ok('the five possible integer traces pin n to exactly {1,2,3,4,6}',
   [...new Set(pinned)].sort((a, b) => a - b).join(',') === EXPECTED, [...new Set(pinned)].join(','));

// The satin move sets quoted in the prose.
const MOVES = { 4: '', 5: '2,3', 6: '', 7: '2,3,4,5', 8: '3,5', 10: '3,7', 12: '5,7', 16: '3,5,7,9,11,13' };
for (const [n, want] of Object.entries(MOVES)) {
  ok(`${n}-end satin moves are {${want || 'none'}}`, E.satinMoves(+n).join(',') === want, E.satinMoves(+n).join(','));
}

// A satin really does need all n shafts, and really does scatter (no two adjacent
// ends interlace on adjacent picks) exactly when the move is a legal one.
for (const n of [5, 7, 8, 10]) {
  for (const m of E.satinMoves(n)) {
    const d = E.satin(n, m);
    const D = E.drawdown(d.threading, d.tieup, d.treadling);
    ok(`the ${n}-end satin with move ${m} needs all ${n} shafts`, E.minShafts(D) === n, String(E.minShafts(D)));
  }
}

// Posselt's own stated objection, 1888, run as a computation. He refuses to call
// the four-end weave a satin because "on two successive picks the interwoven
// threads are next to each other". His sequence is 1,2,4,3; the six-end weave he
// and Watson both print is 1,3,5,2,6,4.
ok('the four-end weave DOES put successive interlacings on neighbouring shafts (Posselt 1888)',
   E.hasAdjacentSteps(E.IRREGULAR[4]) === true);
ok('the six-end irregular weave does NOT (so it carries no twill line)',
   E.hasAdjacentSteps(E.IRREGULAR[6]) === false);
for (const n of [5, 7, 8, 9, 10, 11, 12, 13, 16]) {
  for (const m of E.satinMoves(n)) {
    const order = Array.from({ length: n }, (_, k) => ((m * k) % n) + 1);
    if (E.hasAdjacentSteps(order)) { ok(`regular ${n}-end satin, move ${m}, has no adjacent steps`, false); }
  }
}
ok('no regular satin anywhere in n = 5..16 puts successive interlacings on neighbouring shafts', true);
for (const n of [4, 6]) {
  const d = E.irregularSatin(n);
  const D = E.drawdown(d.threading, d.tieup, d.treadling);
  ok(`the irregular ${n}-end weave uses all ${n} shafts and hangs together`,
     E.minShafts(D) === n && E.hangsTogether(D), `${E.minShafts(D)} shafts`);
  ok(`its interlacing order ${E.IRREGULAR[n].join(',')} is a permutation of 1..${n}`,
     [...E.IRREGULAR[n]].sort((a, b) => a - b).join(',') === Array.from({ length: n }, (_, i) => i + 1).join(','));
}

// ═════════════════════════════════════════════ 4. every number on the page

section('4. the numbers printed on the page, recomputed');

// The canonical patterns behind the table. Each is DEFINED here and the page's
// table must match what these compute.
const stripes  = Array.from({ length: 32 }, () => Array.from({ length: 32 }, (_, j) => ((j >> 2) % 2)));
const checker  = Array.from({ length: 32 }, (_, i) => Array.from({ length: 32 }, (_, j) => (i + j) % 2));
const plain    = (() => { const d = E.plainWeave(32, 32); return E.drawdown(d.threading, d.tieup, d.treadling); })();
const twill22  = (() => { const d = E.twill(4, [0, 1], 32, 32); return E.drawdown(d.threading, d.tieup, d.treadling); })();
const diag8    = Array.from({ length: 32 }, (_, i) => Array.from({ length: 32 }, (_, j) => (((i + j) % 8) < 4 ? 1 : 0)));
const satin5   = (() => { const d = E.satin(5, 2, { ends: 30, picks: 30 }); return E.drawdown(d.threading, d.tieup, d.treadling); })();
const circle   = Array.from({ length: 40 }, (_, i) => Array.from({ length: 40 }, (_, j) => (((i - 20) ** 2 + (j - 20) ** 2) < 250 ? 1 : 0)));
const dither   = Array.from({ length: 40 }, (_, i) => Array.from({ length: 40 }, (_, j) => ((j / 40) > (((i * 7 + j * 3) % 16) / 16) ? 1 : 0)));
const noise    = (() => {
  let s = 20260801; const r = () => { s = (s * 1103515245 + 12345) & 0x7fffffff; return s / 0x7fffffff; };
  return Array.from({ length: 40 }, () => Array.from({ length: 40 }, () => (r() < 0.5 ? 1 : 0)));
})();

// The two word patterns come from the PAGE's own wordCloth, extracted below, so
// the table can never drift from what a visitor actually sees.
const between = (a, b) => {
  const after = html.split(a)[1];
  return after === undefined ? null : after.split(b)[0];
};
const engineSrc = between('// ==ENGINE-BEGIN==\n', '// ==ENGINE-END==');
const wordSrc   = between('// ==WORD-BEGIN==\n', '// ==WORD-END==');
ok('the page carries an extractable engine block', typeof engineSrc === 'string' && engineSrc.length > 5000,
   `${engineSrc ? engineSrc.length : 0} chars`);
ok('the page carries an extractable word-weaving block', typeof wordSrc === 'string' && wordSrc.length > 1500,
   `${wordSrc ? wordSrc.length : 0} chars`);

const pageEngine = new Function(`${engineSrc}\n${wordSrc}
  return { drawdown: drawdown, minShafts: minShafts, minTreadles: minTreadles, reconstruct: reconstruct,
           reproduces: reproduces, satinMoves: satinMoves, totient: totient, latticeTrace: latticeTrace,
           longestFloat: longestFloat, hangsTogether: hangsTogether, pieces: pieces, fitToLoom: fitToLoom,
           gcd: gcd, wordCloth: wordCloth };`)();

const wordHELLO = pageEngine.wordCloth('HELLO');
const wordWASTE = pageEngine.wordCloth('WASTELAND');

const TABLE = [
  ['vertical stripes',              stripes],
  ['plain weave (tabby)',           plain],
  ['checkerboard',                  checker],
  ['2/2 twill',                     twill22],
  ['a diagonal band, period 8',     diag8],
  ['5-end satin',                   satin5],
  ['a circle, 40 by 40',            circle],
  ['the word HELLO',                wordHELLO],
  ['the word WASTELAND',            wordWASTE],
  ['a dithered gradient, 40 by 40', dither],
  ['random noise, 40 by 40',        noise],
];
console.log('\n     pattern                          shafts  treadles   size');
for (const [name, D] of TABLE) {
  console.log(`     ${name.padEnd(32)} ${String(E.minShafts(D)).padStart(6)} ${String(E.minTreadles(D)).padStart(9)}   ${D.length}x${D[0].length}`);
}

// Now assert the page's table rows carry exactly these numbers. Rows are matched
// by their label text and the two <b> cells that follow it.
const rowNumbers = (label) => {
  const idx = html.indexOf(`<td>${label}</td>`);
  if (idx < 0) return null;
  const slice = html.slice(idx, idx + 260);
  const nums = [...slice.matchAll(/<b>(\d+)<\/b>/g)].map((mm) => +mm[1]);
  return nums.length >= 2 ? nums.slice(0, 2) : null;
};
for (const [name, D] of TABLE) {
  const got = rowNumbers(name);
  ok(`page table row "${name}" reads ${E.minShafts(D)} / ${E.minTreadles(D)}`,
     !!got && got[0] === E.minShafts(D) && got[1] === E.minTreadles(D),
     got ? `page says ${got.join(' / ')}` : 'row not found');
}

// The two figures quoted in the prose of "the theorem" section.
ok(`the page's "12,040 of the 65,536" is right`, html.includes('12,040 of the 65,536'));
ok(`the page's total matrices-tested figure is ${sweptMatrices.toLocaleString('en-US')}`,
   html.includes(`${sweptMatrices.toLocaleString('en-US')} matrices`),
   `expected "${sweptMatrices.toLocaleString('en-US')} matrices"`);
ok('the page states the impossible satin set as {1, 2, 3, 4} and 6',
   /n = 1, 2, 3, 4<\/span> and\s*<span class="mono">6/.test(html) || html.includes('n = 1, 2, 3, 4'));

// The page prints a command; it must run. (The publish gate checks this too.)
ok('the command the page prints exists',
   html.includes('node verify-two-threads-that-never-disagree.mjs'));

// ═════════════════════════════════════════════ 5. page engine vs offline engine

section('5. the page engine and the offline engine are the same function');

let drift = 0, driftDetail = '';
for (let trial = 0; trial < 3000; trial++) {
  const m = 1 + Math.floor(rnd() * 12), n = 1 + Math.floor(rnd() * 12);
  const D = Array.from({ length: m }, () => Array.from({ length: n }, () => (rnd() < 0.5 ? 1 : 0)));
  const a = { s: E.minShafts(D), t: E.minTreadles(D), f: E.longestFloat(D), h: E.hangsTogether(D) };
  const b = { s: pageEngine.minShafts(D), t: pageEngine.minTreadles(D), f: pageEngine.longestFloat(D), h: pageEngine.hangsTogether(D) };
  if (a.s !== b.s || a.t !== b.t || a.h !== b.h || a.f.warp !== b.f.warp || a.f.weft !== b.f.weft) {
    drift++; if (!driftDetail) driftDetail = JSON.stringify({ a, b });
  }
  const ra = E.reconstruct(D), rb = pageEngine.reconstruct(D);
  if (ra.shafts !== rb.shafts || ra.treadles !== rb.treadles) { drift++; }
  if (!pageEngine.reproduces(D, rb)) { drift++; }
}
ok('3000 random cloths: page engine and offline engine agree on every reading', drift === 0, driftDetail);

let arithDrift = 0;
for (let n = 1; n <= 300; n++) {
  if (E.satinMoves(n).join(',') !== pageEngine.satinMoves(n).join(',')) arithDrift++;
  if (E.totient(n) !== pageEngine.totient(n)) arithDrift++;
  if (E.latticeTrace(n).isInteger !== pageEngine.latticeTrace(n).isInteger) arithDrift++;
}
ok('satin moves, totient and lattice trace agree for n = 1..300', arithDrift === 0, `${arithDrift} disagreements`);

// The approximation routine is a heuristic, so what is checked is the property it
// DOES promise: when the loom is big enough the fit must be exact, and it must
// never report a fit better than it actually achieved.
let fitBad = 0;
for (let trial = 0; trial < 60; trial++) {
  const m = 4 + Math.floor(rnd() * 12), n = 4 + Math.floor(rnd() * 12);
  const D = Array.from({ length: m }, () => Array.from({ length: n }, () => (rnd() < 0.5 ? 1 : 0)));
  const need = E.minShafts(D), needT = E.minTreadles(D);
  const f = E.fitToLoom(D, need, needT);
  if (!f.exact) fitBad++;
  let actual = 0;
  for (let i = 0; i < m; i++) for (let j = 0; j < n; j++) if (f.cloth[i][j] !== D[i][j]) actual++;
  if (actual !== f.wrongCells) fitBad++;
}
ok('the shaft-reduction fit is exact whenever the loom is big enough, and never misreports its own error',
   fitBad === 0, `${fitBad} failures`);

// ═════════════════════════════════════════════ 5b. is it cloth? (added 2026-09-26)

section('5b. fitToLoom says whether what it weaves is cloth, and in how many pieces');

// Two counters written fresh here, sharing nothing with engine.mjs:
//   splitExists: every split of the threads into an upper and a lower group,
//     tried by hand (the Grünbaum-Shephard definition of falling apart).
//   countPieces: an arrow from the lower thread to the upper at every crossing,
//     full transitive closure by Floyd-Warshall, then threads grouped by mutual
//     reachability. Different algorithm from the engine's Kosaraju passes.
const splitExists = (D) => {
  const m = D.length, n = D[0].length;
  for (let a = 0; a < (1 << n); a++) for (let b = 0; b < (1 << m); b++) {
    const up = (a ? 1 : 0) + (b ? 1 : 0), low = (a !== (1 << n) - 1 ? 1 : 0) + (b !== (1 << m) - 1 ? 1 : 0);
    if (!up || !low) continue;
    let good = true;
    for (let i = 0; i < m && good; i++) for (let j = 0; j < n && good; j++) {
      const warpUp = (a >> j) & 1, pickUp = (b >> i) & 1;
      if (warpUp && !pickUp && D[i][j] !== 1) good = false;   // upper end must pass over a lower pick
      if (pickUp && !warpUp && D[i][j] !== 0) good = false;   // upper pick must pass over a lower end
    }
    if (good) return true;
  }
  return false;
};
const countPieces = (D) => {
  const m = D.length, n = D[0].length, V = m + n;
  const R = Array.from({ length: V }, (_, v) => Array.from({ length: V }, (_, w) => v === w));
  for (let i = 0; i < m; i++) for (let j = 0; j < n; j++) {
    if (D[i][j]) R[i][m + j] = true; else R[m + j][i] = true;   // lower -> upper
  }
  for (let k = 0; k < V; k++) for (let v = 0; v < V; v++) if (R[v][k]) for (let w = 0; w < V; w++) if (R[k][w]) R[v][w] = true;
  const label = new Array(V).fill(-1); let c = 0;
  for (let v = 0; v < V; v++) if (label[v] < 0) { for (let w = 0; w < V; w++) if (R[v][w] && R[w][v]) label[w] = c; c++; }
  return c;
};

// The two fresh counters and the engine agree on every 3x3, 4x4 and 3x5 drawdown.
let pcBad = 0, pcDetail = '', gap44 = 0;
for (const [m, n] of [[3, 3], [4, 4], [3, 5]]) {
  for (const key of E.allMatrices(m, n)) {
    const D = E.keyToMatrix(key, m, n);
    const brute = splitExists(D), fw = countPieces(D), eng = E.pieces(D);
    if (eng !== fw || (fw > 1) !== brute || E.hangsTogether(D) !== !brute) {
      pcBad++; if (!pcDetail) pcDetail = `${key}: engine ${eng}, closure ${fw}, split ${brute}`;
    }
    if (m === 4 && n === 4 && brute && E.everyThreadTiedDown(D)) gap44++;
  }
}
ok('engine piece count = fresh closure count, and 1 exactly when no split exists (all 3x3, 4x4, 3x5)',
   pcBad === 0, pcDetail || '149,504 drawdowns');
ok('the 4x4 drawdowns that tie every thread down yet fall apart number 144, as the engine comment says',
   gap44 === 144, String(gap44));

// A known cloth, and the widths where the old 32-bit test broke.
const plainAt = (n) => { const d = E.plainWeave(n, n); return E.drawdown(d.threading, d.tieup, d.treadling); };
let wideBad = [];
for (let n = 2; n <= 64; n += 2) if (!E.hangsTogether(plainAt(n)) || E.pieces(plainAt(n)) !== 1) wideBad.push(n);
ok('plain weave hangs together at every even width 2..64 (the old test failed from 32 ends)',
   wideBad.length === 0, wideBad.length ? `wrong at ${wideBad.join(',')}` : '');

const plain32 = plainAt(32);
const fc = E.fitToLoom(plain32, 2, 2);
ok('fitToLoom on a 32-end plain weave: exact, 1 piece, hangs together, no warning',
   fc.exact && fc.pieces === 1 && fc.hangsTogether === true && fc.warning === null && countPieces(fc.cloth) === 1,
   JSON.stringify({ exact: fc.exact, pieces: fc.pieces, hangs: fc.hangsTogether, warning: fc.warning }));

// A known non-cloth: a double plain weave built here from its definition. Odd
// ends and odd picks weave the top cloth, even ones the bottom; every top end
// rides over every bottom pick, every top pick rides over every bottom end.
const layered = (L, size) => Array.from({ length: size }, (_, i) => Array.from({ length: size }, (_, j) => {
  const li = i % L, lj = j % L;                     // which layer each thread belongs to (0 = top)
  if (li === lj) return (Math.floor(i / L) + Math.floor(j / L)) % 2;   // plain weave within a layer
  return lj < li ? 1 : 0;                           // end in a higher layer rides over the pick
}));
for (const [L, size] of [[2, 32], [3, 36], [2, 8]]) {
  const D = layered(L, size);
  const want = countPieces(D);
  const f = E.fitToLoom(D, E.minShafts(D), E.minTreadles(D));
  ok(`a ${L}-layer cloth, ${size} by ${size}: fresh count ${want}, fitToLoom says ${f.pieces} pieces and not cloth`,
     want === L && E.everyThreadTiedDown(D) && f.exact && f.pieces === want && f.hangsTogether === false
       && f.warning === `this drawdown comes off the loom in ${want} pieces: it is not cloth`,
     JSON.stringify({ want, pieces: f.pieces, hangs: f.hangsTogether, warning: f.warning }));
}

// A floating thread is its own piece: plain weave with end 0 lifted on every pick.
const floatEnd = plainAt(12).map((r) => r.map((v, j) => (j === 0 ? 1 : v)));
ok('plain weave with one end never going under: fresh count and fitToLoom both say 2 pieces',
   countPieces(floatEnd) === 2 && E.fitToLoom(floatEnd, 3, 2).pieces === 2, String(countPieces(floatEnd)));

// Cutting a loom down can split a cloth that held, and the report follows the
// cloth actually woven, not the target: over random targets, fitToLoom's piece
// count is always the fresh count of the cloth it returns.
let fitPcBad = 0, splitByCut = 0;
for (let trial = 0; trial < 300; trial++) {
  const m = 3 + Math.floor(rnd() * 10), n = 3 + Math.floor(rnd() * 10);
  const D = Array.from({ length: m }, () => Array.from({ length: n }, () => (rnd() < 0.5 ? 1 : 0)));
  const f = E.fitToLoom(D, 2 + Math.floor(rnd() * 3), 2 + Math.floor(rnd() * 3));
  const truth = countPieces(f.cloth);
  if (f.pieces !== truth || f.hangsTogether !== (truth === 1) || (f.warning === null) !== (truth === 1)) fitPcBad++;
  if (countPieces(D) === 1 && truth > 1) splitByCut++;
}
ok('300 random fits: reported pieces always equal the fresh count of the cloth returned', fitPcBad === 0,
   `${fitPcBad} wrong; ${splitByCut} fits split a target that held`);

// The page's copy says the same thing, including past 31 ends.
let pageDrift = 0;
for (let trial = 0; trial < 400; trial++) {
  const m = 1 + Math.floor(rnd() * 60), n = 1 + Math.floor(rnd() * 60);
  const dense = rnd();
  const D = Array.from({ length: m }, () => Array.from({ length: n }, () => (rnd() < dense ? 1 : 0)));
  if (pageEngine.pieces(D) !== E.pieces(D) || pageEngine.hangsTogether(D) !== E.hangsTogether(D)) pageDrift++;
  if (trial < 40 && pageEngine.pieces(D) !== countPieces(D)) pageDrift++;
}
for (const D of [plain32, layered(2, 32), layered(3, 36)]) {
  const a = E.fitToLoom(D, 4, 4), b = pageEngine.fitToLoom(D, 4, 4);
  if (a.pieces !== b.pieces || a.warning !== b.warning) pageDrift++;
}
ok('the page engine counts pieces identically, at widths up to 60', pageDrift === 0, `${pageDrift} disagreements`);

// ═════════════════════════════════════════════ 6. the live page

section('6. the live page, driven headless');

let browser = null, server = null;
try {
  const mod = await import('/opt/node22/lib/node_modules/playwright/index.js');
  const pw = mod.chromium ? mod : mod.default;
  const root = new URL('./dist/', import.meta.url).pathname;
  const types = { '.html': 'text/html', '.css': 'text/css', '.js': 'text/javascript', '.woff2': 'font/woff2',
                  '.png': 'image/png', '.svg': 'image/svg+xml', '.ico': 'image/x-icon', '.json': 'application/json' };
  server = createServer((req, res) => {
    let p = decodeURIComponent(req.url.split('?')[0]); if (p.endsWith('/')) p += 'index.html';
    try { const buf = readFileSync(join(root, p)); res.writeHead(200, { 'content-type': types[extname(p)] || 'application/octet-stream' }); res.end(buf); }
    catch { res.writeHead(404); res.end('404'); }
  });
  await new Promise((r) => server.listen(8244, r));

  browser = await pw.chromium.launch();
  const errors = [];
  const page = await browser.newPage({ viewport: { width: 1100, height: 1000 } });
  page.on('pageerror', (e) => errors.push(String(e)));
  page.on('console', (msg) => { if (msg.type() === 'error') errors.push(msg.text()); });
  await page.goto('http://localhost:8244/strata/two-threads-that-never-disagree/', { waitUntil: 'networkidle' });
  await page.waitForTimeout(300);

  const painted = async (sel) => page.evaluate((s) => {
    const cv = document.querySelector(s); if (!cv) return 0;
    const d = cv.getContext('2d').getImageData(0, 0, cv.width, cv.height).data;
    let lit = 0; for (let i = 0; i < d.length; i += 4) if (d[i] > 40 || d[i + 1] > 40 || d[i + 2] > 40) lit++;
    return lit;
  }, sel);

  ok('the draft canvas paints', (await painted('#draft')) > 2000);
  ok('the satin canvas paints', (await painted('#satin')) > 2000);

  const read = () => page.evaluate(() => ({
    v: window.__weave.view(),
    shafts: document.getElementById('r-shafts').textContent.trim(),
    treadles: document.getElementById('r-treadles').textContent.trim(),
    verdict: document.getElementById('v-text-a').textContent.trim(),
    tag: document.getElementById('v-tag-a').textContent.trim(),
  }));

  let s = await read();
  ok('the page opens on plain weave: 2 shafts, 2 treadles', s.shafts === '2' && s.treadles === '2',
     `${s.shafts} / ${s.treadles}`);
  ok('and says the 32-end plain weave hangs together', s.v.pieces === 1 &&
     (await page.evaluate(() => document.getElementById('r-hangs').textContent.trim())) === 'yes');

  // a double cloth on screen must be called what it is, with its piece count
  await page.evaluate((D) => window.__weave.setCloth(D), layered(2, 32));
  await page.waitForTimeout(120);
  s = await read();
  ok('a double cloth on the live page is tagged "Not cloth"', s.tag === 'Not cloth', s.tag);
  ok('and the verdict says it comes off the loom in 2 pieces', /comes off the loom in 2 pieces: it is not cloth/.test(s.verdict)
     && s.v.pieces === countPieces(layered(2, 32)), s.verdict.slice(0, 90));
  await page.click('#presets button[data-p="plain"]');
  await page.waitForTimeout(90);

  // every preset lands on the shaft count the offline engine says it should
  const PRESET_EXPECT = { plain: [2, 2], twill22: [4, 4], twill31: [4, 4], point: [4, 4],
                          rosepath: [4, 4], satin5: [5, 5], satin8: [8, 8], blocks: [4, 4] };
  for (const [name, [wantS, wantT]] of Object.entries(PRESET_EXPECT)) {
    await page.click(`#presets button[data-p="${name}"]`);
    await page.waitForTimeout(90);
    s = await read();
    ok(`preset "${name}" reads ${wantS} shafts / ${wantT} treadles`,
       s.shafts === String(wantS) && s.treadles === String(wantT), `${s.shafts} / ${s.treadles}`);
  }

  // the word demo, and the table figures, straight off the live page
  for (const [word, want] of [['HELLO', E.minShafts(wordHELLO)], ['WASTELAND', E.minShafts(wordWASTE)]]) {
    await page.fill('#word', word);
    await page.click('#weaveword');
    await page.waitForTimeout(140);
    s = await read();
    ok(`the live page weaves "${word}" at ${want} shafts`, s.shafts === String(want), s.shafts);
  }

  // pull the loom down below what the pattern needs and the page must SAY so
  await page.evaluate(() => {
    const el = document.getElementById('shaftcap');
    el.value = '4'; el.dispatchEvent(new Event('input', { bubbles: true }));
  });
  await page.waitForTimeout(220);
  s = await read();
  ok('cutting the loom to 4 shafts flags the cloth as cut down', s.tag === 'Cut down', s.tag);
  ok('and reports how many cells it had to change', /\d+ of \d+ cells to change/.test(s.verdict),
     s.verdict.slice(0, 90));
  ok('and says plainly that this is not a proof of optimality', /not a proof of the best possible/.test(s.verdict));

  // the satin dial: 4 and 6 must go dark, 5 must light up
  const dial = async (n, m) => {
    await page.evaluate(({ n, m }) => {
      const nn = document.getElementById('nDial'), mm = document.getElementById('mDial');
      nn.value = String(n); nn.dispatchEvent(new Event('input', { bubbles: true }));
      mm.value = String(m); mm.dispatchEvent(new Event('input', { bubbles: true }));
    }, { n, m });
    await page.waitForTimeout(90);
    return page.evaluate(() => ({ tag: document.getElementById('v-tag-b').textContent.trim(),
                                  text: document.getElementById('v-text-b').textContent.trim() }));
  };
  let d = await dial(4, 2);
  ok('n = 4: the dial says no satin exists', d.tag === 'No satin exists', d.tag);
  ok('n = 4: and says a crystal IS allowed fourfold symmetry', /IS allowed 4-fold/.test(d.text), d.text.slice(-90));
  d = await dial(6, 5);
  ok('n = 6: the dial says no satin exists', d.tag === 'No satin exists', d.tag);
  d = await dial(5, 2);
  ok('n = 5: the dial says regular satin', d.tag === 'Regular satin', d.tag);
  ok('n = 5: and says fivefold symmetry is denied to a crystal', /no crystal or wallpaper may have 5-fold/.test(d.text),
     d.text.slice(-90));
  d = await dial(8, 4);
  ok('n = 8, move 4: the dial says it clumps', d.tag === 'Clumps', d.tag);
  d = await dial(8, 1);
  ok('n = 8, move 1: the dial says twill, not satin', d.tag === 'Twill, not satin', d.tag);

  // the "what the trade weaves instead" panel appears exactly at n = 4 and n = 6
  const irrPanel = async (n) => {
    await dial(n, 2);
    return page.evaluate(() => {
      const el = document.getElementById('irregular');
      return { shown: el.style.display !== 'none', text: el.textContent.trim() };
    });
  };
  let ip = await irrPanel(4);
  ok('n = 4 offers the irregular weave the trade uses', ip.shown && /1, 2, 4, 3/.test(ip.text), ip.text.slice(0, 80));
  ok('and says plainly it is not a satin, citing Posselt', /not a satin/.test(ip.text) && /Posselt/.test(ip.text));
  ip = await irrPanel(6);
  ok('n = 6 offers the order 1, 3, 5, 2, 6, 4', ip.shown && /1, 3, 5, 2, 6, 4/.test(ip.text), ip.text.slice(0, 80));
  ok('and says it carries no twill line', /no twill line/.test(ip.text));
  ip = await irrPanel(5);
  ok('n = 5 hides the panel, because a regular satin exists there', !ip.shown);

  // back to a full loom and a known draft, then draw in the cloth
  await page.evaluate(() => {
    const el = document.getElementById('shaftcap');
    el.value = '16'; el.dispatchEvent(new Event('input', { bubbles: true }));
  });
  await page.click('#presets button[data-p="twill22"]');
  await page.waitForTimeout(120);
  await page.click('#mode-cloth');
  await page.waitForTimeout(120);
  const before = await read();
  ok('switching to cloth mode keeps the same cloth on screen', before.shafts === '4', before.shafts);

  await page.evaluate(() => {
    const cv = document.getElementById('draft');
    const r = cv.getBoundingClientRect();
    const ev = (type, x, y) => cv.dispatchEvent(new PointerEvent(type, {
      clientX: x, clientY: y, bubbles: true, buttons: 1, pointerId: 1, isPrimary: true }));
    ev('pointerdown', r.left + r.width * 0.10, r.top + r.height * 0.80);   // inside the cloth block
    ev('pointerup', r.left + r.width * 0.10, r.top + r.height * 0.80);
  });
  await page.waitForTimeout(160);
  const after = await read();
  ok('a pointer click inside the cloth actually changes the cloth', before.v.hash !== after.v.hash,
     `${before.v.hash} -> ${after.v.hash}`);
  ok('and the loom is refactored around the change (4 shafts becomes 5)',
     after.shafts === '5', `${before.shafts} -> ${after.shafts}`);
  ok('the live page re-derives a loom that reproduces the shown cloth exactly, minimally',
     after.v.refactors === true, String(after.v.refactors));

  // reduced motion and three viewports
  for (const w of [390, 768, 1440]) {
    await page.setViewportSize({ width: w, height: 950 });
    await page.waitForTimeout(200);
    const over = await page.evaluate(() => document.documentElement.scrollWidth - document.documentElement.clientWidth);
    ok(`no horizontal overflow at ${w}px`, over <= 1, `overflow ${over}px`);
  }

  ok('no JS or console errors through the whole session', errors.length === 0, errors.slice(0, 3).join(' | '));
} catch (err) {
  if (/Cannot find module|ENOENT.*dist/.test(String(err))) {
    console.log(`  skip  headless pass (${String(err).split('\n')[0]}) — run "npm run build" first`);
  } else { fails++; console.log(`FAIL  headless pass threw: ${err}`); }
} finally {
  if (browser) await browser.close();
  if (server) server.close();
}

console.log(`\n${fails === 0 ? `ALL ${checks} CHECKS PASSED` : `${fails} OF ${checks} CHECKS FAILED`}`);
process.exit(fails === 0 ? 0 : 1);
