import fs from 'node:fs';
import path from 'node:path';
import crypto from 'node:crypto';
import vm from 'node:vm';

const root = path.resolve(import.meta.dirname, '../..');
const kitContext = { module:{exports:{}}, exports:{} };
vm.runInNewContext(fs.readFileSync(path.join(root, 'public/_kit/multiverse.js'), 'utf8'), kitContext);
const mv = kitContext.module.exports;
const pagePath = path.join(root, 'public/strata/the-gap-and-its-controls/index.html');
const logicPath = path.join(root, 'public/strata/the-gap-and-its-controls/the-gap-and-its-controls.js');
const dataPath = path.join(root, 'public/strata/the-gap-and-its-controls/data/cps-asec-2024.bin');
const gridPath = path.join(root, 'public/strata/the-gap-and-its-controls/data/major-grid.json');
const frontPath = path.join(root, 'src/content/strata/the-gap-and-its-controls.md');
const readmePath = path.join(root, 'research/the-gap-and-its-controls/README.md');

const page = fs.readFileSync(pagePath, 'utf8');
const logic = fs.readFileSync(logicPath, 'utf8');
const front = fs.readFileSync(frontPath, 'utf8');
const readme = fs.readFileSync(readmePath, 'utf8');
const packed = fs.readFileSync(dataPath);
const stored = JSON.parse(fs.readFileSync(gridPath, 'utf8'));
let assertions = 0;

function check(condition, message) {
  assertions++;
  if (!condition) throw new Error('assertion ' + assertions + ' failed: ' + message);
}
function close(actual, expected, tolerance, message) {
  check(Number.isFinite(actual) && Math.abs(actual - expected) <= tolerance, message + ' (got ' + actual + ', expected ' + expected + ' ± ' + tolerance + ')');
}
function includes(text, needle, message) { check(text.includes(needle), message + ' (missing ' + JSON.stringify(needle) + ')'); }
function sha256(buffer) { return crypto.createHash('sha256').update(buffer).digest('hex'); }

check(packed.length === 2128977, 'packed byte size');
check(sha256(packed) === '878c11b4516f0cd0d8dfb419b7a7ba47bcc21d0b59c4878d37b42a69023949e3', 'packed SHA-256');
check(sha256(fs.readFileSync(gridPath)) === 'edd3fb0481983a2f2b56655193ae736c481a103851d69e83de2dd0f99d325f9f', 'grid SHA-256');
check(stored.length === 7776, 'stored grid length');

const N = 73413;
let offset = 0;
function take(Type) {
  const out = new Type(packed.buffer, packed.byteOffset + offset, N);
  offset += N * Type.BYTES_PER_ELEMENT;
  return out;
}
const data = { earn:take(Int32Array), wsal:take(Int32Array), wt:take(Uint16Array), occ:take(Uint16Array), ind:take(Uint16Array) };
for (const name of ['age','female','wks','hrs','edu2','mjocc','mjind','cls','mar','race','hisp','div','kids','tc','alloc']) data[name] = take(Uint8Array);
check(offset === packed.length, 'binary schema consumes every byte');

function censusMedian(female, ftyrOnly) {
  const bins = new Float64Array(101);
  let total = 0;
  let rows = 0;
  for (let i = 0; i < N; i++) {
    if (data.female[i] !== female) continue;
    if (ftyrOnly && !(data.wks[i] >= 50 && data.hrs[i] >= 35)) continue;
    const bin = data.earn[i] >= 250000 ? 100 : Math.max(0, Math.floor(data.earn[i] / 2500));
    bins[bin] += data.wt[i];
    total += data.wt[i];
    rows++;
  }
  let cumulative = 0;
  for (let bin = 0; bin < bins.length; bin++) {
    if (cumulative + bins[bin] >= total / 2) {
      const value = bin === 100 ? 250000 : bin * 2500 + ((total / 2 - cumulative) / bins[bin]) * 2500;
      return { value, total, rows };
    }
    cumulative += bins[bin];
  }
  throw new Error('median interval not found');
}

const maleFtyr = censusMedian(0, true);
const femaleFtyr = censusMedian(1, true);
const maleAll = censusMedian(0, false);
const femaleAll = censusMedian(1, false);
const anchorRatio = femaleFtyr.value / maleFtyr.value;
const allRatio = femaleAll.value / maleAll.value;

close(maleFtyr.value, 66792.893891983, 1e-8, 'male FTYR interpolated median');
close(femaleFtyr.value, 55243.631396082485, 1e-8, 'female FTYR interpolated median');
close(anchorRatio, 0.8270884547302607, 1e-13, 'FTYR ratio');
close(maleAll.value, 56280.09435853872, 1e-8, 'male all-worker interpolated median');
close(femaleAll.value, 42107.50781764898, 1e-8, 'female all-worker interpolated median');
close(allRatio, 0.7481776336300775, 1e-13, 'all-worker ratio');
check(Math.round(maleFtyr.value / 10) * 10 === 66790, 'male median rounds to paper');
check(Math.round(femaleFtyr.value / 10) * 10 === 55240, 'female median rounds to paper');
check(anchorRatio.toFixed(3) === '0.827', 'ratio rounds to paper');
check(Math.round(maleFtyr.total / 10000) * 10 === 68470, 'male weighted count rounds to paper thousands');
check(Math.round(femaleFtyr.total / 10000) * 10 === 52850, 'female weighted count rounds to paper thousands');
check(Math.round(maleAll.value / 10) * 10 === 56280, 'male all-worker median rounds to paper');
check(Math.round(femaleAll.value / 10) * 10 === 42110, 'female all-worker median rounds to paper');
check(allRatio.toFixed(3) === '0.748', 'all-worker ratio rounds to displayed precision');

let positive = 0;
let negative = 0;
let positiveFtyr = 0;
let roundedWeight = 0;
for (let i = 0; i < N; i++) {
  roundedWeight += data.wt[i];
  if (data.earn[i] > 0) {
    positive++;
    if (data.wks[i] >= 50 && data.hrs[i] >= 35) positiveFtyr++;
  } else if (data.earn[i] < 0) negative++;
}
check(positive === 73309, 'positive regression universe');
check(negative === 104, 'negative earners retained for anchor');
check(positiveFtyr === 51588, 'positive FTYR universe');
check(roundedWeight === 173056824, 'trimmed rounded weight sum');

function dims() {
  return [
    {name:'sample',options:[{label:'FTYR',value:'ftyr'},{label:'all workers',value:'all'}]},
    {name:'age',options:[{label:'15+',value:'15-99'},{label:'25-54',value:'25-54'},{label:'25-34',value:'25-34'}]},
    {name:'fam',options:[{label:'all family statuses',value:0},{label:'never married, no children',value:1}]},
    {name:'alloc',options:[{label:'keep allocations',value:0},{label:'drop allocations',value:1}]},
    {name:'tc',options:[{label:'top-code as is',value:'asis'},{label:'drop top-code',value:'drop'},{label:'top-code x1.4',value:'x1.4'}]},
    {name:'earnv',options:[{label:'total earnings',value:'total'},{label:'wage only',value:'wage'}]},
    {name:'meas',options:[{label:'annual',value:'annual'},{label:'weekly',value:'weekly'},{label:'hourly',value:'hourly'}]},
    {name:'wtd',options:[{label:'weighted',value:1},{label:'unweighted',value:0}]},
    {name:'rung',options:Array.from({length:9},(_,i)=>({label:'rung '+i,value:i}))}
  ];
}
const dimensions = dims();
const specs = mv.grid(dimensions);
check(specs.length === 7776, 'shared kit rebuilds full 7,776 grid');
for (let i = 0; i < specs.length; i++) {
  for (const key of Object.keys(specs[i])) check(stored[i][key] === specs[i][key], 'stored row ' + i + ' preserves shared-kit order for ' + key);
  check(Number.isFinite(stored[i].coef), 'stored coefficient ' + i + ' is finite');
  check(Number.isInteger(stored[i].n) && stored[i].n >= 400, 'stored cell ' + i + ' has its declared minimum sample');
}

const results = mv.runSync(specs, (_,i)=>({value:100*(1-Math.exp(stored[i].coef)),n:stored[i].n,coef:stored[i].coef}));
const curve = mv.curve(results, {reference:17.3});
const decomp = mv.decompose(dimensions, results);
check(curve.n === 7776 && curve.nOk === 7776 && curve.nFailed === 0, 'all grid cells are counted and defined');
close(curve.min, -1.6318203337842618, 1e-12, 'curve minimum');
close(curve.quantile(.05), 5.94532091461763, 1e-12, 'curve fifth percentile');
close(curve.median, 14.258801746630784, 1e-12, 'curve median');
close(curve.quantile(.95), 27.842250818010164, 1e-12, 'curve 95th percentile');
close(curve.max, 36.0109327317895, 1e-12, 'curve maximum');
check(curve.values.filter(v=>v<0).length === 45, '45 specifications put women ahead');
check(curve.values.filter(v=>v<2).length === 116, '116 specifications are below two points');
const belowPaper = curve.values.filter(v=>v<17.3).length;
check(belowPaper === 5112, 'paper point has 5,112 estimates below it');
close(100*belowPaper/curve.nOk, 65.74074074074075, 1e-12, 'paper-point percentile');
check(belowPaper + 1 === 5113, 'paper-point rank');
close(curve.max-curve.min, 37.642753065573764, 1e-12, 'surface spread');
close((curve.max-curve.min)/1.07, 35.180143051938096, 1e-12, 'spread-to-MOE ratio');

const shares = Object.fromEntries(decomp.factors.map(f=>[f.name,f.share]));
check(decomp.exact === true && decomp.nFailed === 0, 'decomposition is exact and balanced');
close(shares.fam, 0.5610685601712137, 1e-14, 'family restriction share');
close(shares.rung, 0.20669859736072254, 1e-14, 'ladder share');
close(shares.meas, 0.025258148827567424, 1e-14, 'measure share');
close(shares.age, 0.023584179184970715, 1e-14, 'age share');
close(shares.alloc, 0.007211239903949943, 1e-14, 'allocation share');
close(shares.sample, 0.005439763983188373, 1e-14, 'sample share');
close(shares.tc, 0.000650255375768762, 1e-14, 'top-code share');
close(shares.wtd, 0.0006466488827495084, 1e-14, 'weighting share');
close(shares.earnv, 0.0003839266058092183, 1e-14, 'earnings-definition share');
close(decomp.interactionShare, 0.1690586797040597, 1e-14, 'interaction share');
close(decomp.factors.reduce((s,f)=>s+f.share,0)+decomp.interactionShare, 1, 2e-14, 'variance shares sum to one');

function locate(where) {
  const out = mv.locate(results, where);
  check(out && out.ok, 'located specification ' + JSON.stringify(where));
  return out.result;
}
const anchorOls = locate({sample:'ftyr',age:'15-99',fam:0,alloc:0,tc:'asis',earnv:'total',meas:'annual',wtd:1,rung:0});
const educationOls = locate({sample:'ftyr',age:'15-99',fam:0,alloc:0,tc:'asis',earnv:'total',meas:'annual',wtd:1,rung:1});
close(anchorOls.value, 17.7551653360422, 1e-12, 'anchor-choice raw OLS gap');
close(educationOls.value, 23.56996833148074, 1e-12, 'education-only OLS gap');

// The ladder is not a staircase. Printed on the page rung by rung, because a ladder shown
// only at its endpoints reports a drift of 0.73 points and hides a 5.81-point widening.
const ladderPath = [];
for (let rung = 0; rung <= 8; rung++) ladderPath.push(locate({sample:'ftyr',age:'15-99',fam:0,alloc:0,tc:'asis',earnv:'total',meas:'annual',wtd:1,rung}).value);
const ladderShown = ladderPath.map(v => v.toFixed(2)).join(', ');
check(ladderShown === '17.76, 23.57, 23.08, 22.42, 20.19, 17.64, 18.71, 18.42, 18.48', 'the anchor ladder path is ' + ladderShown);
includes(page, ladderShown, 'page prints the ladder rung by rung rather than only its endpoints');
const risingAll = ladderPath.every((v, i) => i === 0 || v >= ladderPath[i - 1]);
const fallingAll = ladderPath.every((v, i) => i === 0 || v <= ladderPath[i - 1]);
check(!risingAll && !fallingAll, 'the ladder is non-monotone in both directions');
check(Math.min(...ladderPath) < ladderPath[0], 'the ladder passes below where it started');
const biggestStep = Math.max(...ladderPath.slice(1).map((v, i) => Math.abs(v - ladderPath[i])));
close(biggestStep, ladderPath[1] - ladderPath[0], 1e-12, 'the largest single step on the ladder is the education step');
check(biggestStep > 0 && ladderPath[1] > ladderPath[0], 'and it widens the gap, so omitting education is not the conservative choice');
check(page.includes(biggestStep.toFixed(2) + '-point widening'), 'page prints the size of that widening');

function rawCell(spec) {
  const sw = [0,0];
  const sy = [0,0];
  let n = 0;
  const [lo,hi] = spec.age.split('-').map(Number);
  for (let i = 0; i < N; i++) {
    if (data.earn[i] <= 0) continue;
    if (spec.sample === 'ftyr' && !(data.wks[i] >= 50 && data.hrs[i] >= 35)) continue;
    if (data.age[i] < lo || data.age[i] > hi) continue;
    if (spec.fam && !(data.mar[i] === 7 && data.kids[i] === 0)) continue;
    if (spec.alloc && data.alloc[i] !== 0) continue;
    if (spec.tc === 'drop' && data.tc[i] !== 0) continue;
    let earnings = spec.earnv === 'wage' ? data.wsal[i] : data.earn[i];
    if (earnings <= 0) continue;
    if (spec.tc === 'x1.4' && data.tc[i] !== 0) earnings *= 1.4;
    if (spec.meas === 'weekly') {
      if (data.wks[i] <= 0) continue;
      earnings /= data.wks[i];
    } else if (spec.meas === 'hourly') {
      if (data.wks[i] <= 0 || data.hrs[i] <= 0) continue;
      earnings /= data.wks[i] * data.hrs[i];
    }
    const f = data.female[i];
    const w = spec.wtd ? data.wt[i] : 1;
    sw[f] += w;
    sy[f] += w * Math.log(earnings);
    n++;
  }
  if (!sw[0] || !sw[1]) return null;
  return { n, coef:sy[1]/sw[1]-sy[0]/sw[0] };
}

let rawCells = 0;
let maxRoundedWeightDelta = 0;
for (let i = 0; i < stored.length; i += 9) {
  check(stored[i].rung === 0, 'every ninth stored row is raw rung');
  const live = rawCell(stored[i]);
  check(live !== null, 'raw cell ' + i + ' has both sexes');
  check(live.n === stored[i].n, 'raw cell ' + i + ' row count recomputes');
  maxRoundedWeightDelta = Math.max(maxRoundedWeightDelta, Math.abs(live.coef-stored[i].coef));
  rawCells++;
}
check(rawCells === 864, 'all 864 raw cells recomputed from shipped binary');
check(maxRoundedWeightDelta < 0.000008, 'whole-person weight rounding changes every raw coefficient by less than 0.000008 log points');

const low = rawCell({sample:'ftyr',age:'25-34',fam:1,alloc:0,tc:'asis',earnv:'total',meas:'hourly',wtd:1,rung:0});
const pair = rawCell({sample:'ftyr',age:'25-34',fam:0,alloc:0,tc:'asis',earnv:'total',meas:'hourly',wtd:1,rung:0});
check(low.n === 4790, 'restricted screenshot-trap sample n');
check(pair.n === 11258, 'unrestricted paired sample n');
close(100*(1-Math.exp(low.coef)), 0.6974026809768552, 1e-11, 'restricted raw live gap');
close(100*(1-Math.exp(pair.coef)), 9.571938266369994, 1e-11, 'unrestricted raw live gap');

// ---------------------------------------------------------------------------------------
// THE TWO DEAD CONTROLS.
//
// Both assertions are written in BOTH directions on purpose. "The measure dial does nothing
// at rung 4 and above" is, on its own, a check that a broken pipeline returning one constant
// for every cell would also pass. Pairing it with "and it moves the answer by at least a
// point everywhere else" is what makes it capable of failing.
// ---------------------------------------------------------------------------------------
const byKey = new Map(stored.map(r => [[r.sample,r.age,r.fam,r.alloc,r.tc,r.earnv,r.meas,r.wtd,r.rung].join('|'), r]));
const at = (row, over) => byKey.get([
  over.sample ?? row.sample, over.age ?? row.age, over.fam ?? row.fam, over.alloc ?? row.alloc,
  over.tc ?? row.tc, over.earnv ?? row.earnv, over.meas ?? row.meas, over.wtd ?? row.wtd,
  over.rung ?? row.rung].join('|'));
const asPoints = coef => 100 * (1 - Math.exp(coef));

const HOURS_RUNG = 4;
const FAMILY_RUNG = 7;
let deadMeasureCells = 0, deadMeasureWorst = 0, liveMeasureLow = Infinity, liveMeasureHigh = 0, liveMeasureTriples = 0;
for (const row of stored) {
  if (row.meas !== 'annual') continue;
  let worst = 0;
  for (const m of ['weekly','hourly']) worst = Math.max(worst, Math.abs(asPoints(row.coef) - asPoints(at(row, {meas:m}).coef)));
  if (row.rung >= HOURS_RUNG) { deadMeasureCells += 3; deadMeasureWorst = Math.max(deadMeasureWorst, worst); }
  else { liveMeasureLow = Math.min(liveMeasureLow, worst); liveMeasureHigh = Math.max(liveMeasureHigh, worst); liveMeasureTriples++; }
}
check(deadMeasureCells === 4320, '4,320 cells sit at or above the hours-and-weeks rung');
check(liveMeasureTriples === 1152, '1,152 measure triples sit below it');
check(deadMeasureWorst < 1e-8, 'the earnings-measure dial is a mathematical no-op once hours and weeks are controlled (worst ' + deadMeasureWorst.toExponential(2) + ' points)');
check(liveMeasureLow > 1, 'the same dial moves every cell below that rung by more than a point, so the identity above is algebra and not a stuck pipeline');
close(liveMeasureLow, 1.211040742650182, 1e-9, 'smallest live measure spread');
close(liveMeasureHigh, 14.249988383600218, 1e-9, 'largest live measure spread');
check(page.includes(liveMeasureLow.toFixed(2)) && page.includes(liveMeasureHigh.toFixed(2)), 'page prints the live measure spread it was measured to have');

let deadFamilyCells = 0, deadFamilyWorst = 0, liveFamilyLow = Infinity, liveFamilyHigh = 0, liveFamilyCells = 0;
for (const row of stored) {
  if (row.rung !== FAMILY_RUNG) continue;
  const step = Math.abs(asPoints(row.coef) - asPoints(at(row, {rung:FAMILY_RUNG - 1}).coef));
  if (row.fam === 1) { deadFamilyCells++; deadFamilyWorst = Math.max(deadFamilyWorst, step); }
  else { liveFamilyLow = Math.min(liveFamilyLow, step); liveFamilyHigh = Math.max(liveFamilyHigh, step); liveFamilyCells++; }
}
check(deadFamilyCells === 432 && liveFamilyCells === 432, 'the family-control rung is reached by 432 restricted and 432 unrestricted cells');
check(deadFamilyWorst < 1e-8, 'marital status and children are a no-op inside the never-married childless sample (worst ' + deadFamilyWorst.toExponential(2) + ' points)');
check(liveFamilyLow > 0, 'the same rung moves every unrestricted cell, so the no-op above is the sample filter and not a dropped control');
close(liveFamilyHigh, 0.6836411876667619, 1e-9, 'largest live family-control step');
close(liveFamilyLow, 0.0004827093256203341, 1e-12, 'smallest live family-control step');
// The cause, not just the consequence: the two variables the rung-7 control uses have to be
// genuinely variable in the data and genuinely constant inside the restricted sample. Asking
// "is mar always 7 among rows filtered on mar === 7" is a check that cannot fail, so the test
// is the contrast between the two universes.
let restrictedRows = 0;
const marAll = new Set(), kidsAll = new Set(), marRestricted = new Set(), kidsRestricted = new Set();
for (let i = 0; i < N; i++) {
  if (data.earn[i] <= 0) continue;
  marAll.add(data.mar[i]);
  kidsAll.add(Math.min(3, data.kids[i]));
  if (!(data.mar[i] === 7 && data.kids[i] === 0)) continue;
  restrictedRows++;
  marRestricted.add(data.mar[i]);
  kidsRestricted.add(Math.min(3, data.kids[i]));
}
check(restrictedRows === 20297, 'the never-married childless universe is 20,297 positive earners');
check(marAll.size === 7 && kidsAll.size === 4, 'marital status and capped children really do vary across the full universe');
check(marRestricted.size === 1 && kidsRestricted.size === 1, 'and take exactly one value each inside the restricted one, so the rung-7 columns are constant there');

// ---------------------------------------------------------------------------------------
// WHICH AXIS WINS IS ALSO A CHOICE. Recomputed the way the page recomputes it, so the table
// on the page cannot drift from the grid underneath it.
// ---------------------------------------------------------------------------------------
const sampleLevels = [...new Set(stored.map(r => r.sample + '|' + r.age + '|' + r.fam))];
const otherLevels = [...new Set(stored.map(r => [r.alloc,r.tc,r.earnv,r.meas,r.wtd].join('|')))];
const rungLevels = [...new Set(stored.map(r => r.rung))].sort((a,b) => a - b);
const cube = sampleLevels.map(() => rungLevels.map(() => new Float64Array(otherLevels.length)));
for (const r of stored) {
  cube[sampleLevels.indexOf(r.sample + '|' + r.age + '|' + r.fam)][rungLevels.indexOf(r.rung)][otherLevels.indexOf([r.alloc,r.tc,r.earnv,r.meas,r.wtd].join('|'))] = r.coef;
}
function axisSpreads(sPick, rPick) {
  let ss = 0, cc = 0;
  for (const rg of rPick) for (let o = 0; o < otherLevels.length; o++) {
    let lo = Infinity, hi = -Infinity;
    for (const s of sPick) { const v = cube[s][rg][o]; if (v < lo) lo = v; if (v > hi) hi = v; }
    ss += hi - lo;
  }
  for (const s of sPick) for (let o = 0; o < otherLevels.length; o++) {
    let lo = Infinity, hi = -Infinity;
    for (const rg of rPick) { const v = cube[s][rg][o]; if (v < lo) lo = v; if (v > hi) hi = v; }
    cc += hi - lo;
  }
  return { sample: ss / (rPick.length * otherLevels.length), cov: cc / (sPick.length * otherLevels.length) };
}
const allSampleIdx = sampleLevels.map((_, i) => i);
const allRungIdx = rungLevels.map((_, i) => i);
const unrestrictedIdx = allSampleIdx.filter(i => !/\|1$/.test(sampleLevels[i]));
check(sampleLevels.length === 12 && unrestrictedIdx.length === 6, 'twelve sample definitions, six of them unrestricted');
const fullAxes = axisSpreads(allSampleIdx, allRungIdx);
const noFamilyAxes = axisSpreads(unrestrictedIdx, allRungIdx);
close(fullAxes.sample, 0.17467402172051458, 1e-12, 'full-grid sample-axis spread');
close(fullAxes.cov, 0.11903358160415461, 1e-12, 'full-grid covariate-axis spread');
check(fullAxes.sample > fullAxes.cov, 'on the full grid the sample axis carries more spread');
close(noFamilyAxes.sample, 0.08728316761802093, 1e-12, 'sample-axis spread without the never-married childless option');
close(noFamilyAxes.cov, 0.12046602335267931, 1e-12, 'covariate-axis spread without it');
check(noFamilyAxes.cov > noFamilyAxes.sample, 'REMOVING ONE OPTION FLIPS THE ORDERING: the covariate ladder then carries more spread');
close(noFamilyAxes.cov / noFamilyAxes.sample, 1.3801747420519517, 1e-12, 'flipped ratio');
// and nothing else flips it, which is what makes "one option deep" a measurement
let worstSampleDrop = Infinity, worstRungDrop = Infinity;
for (const i of allSampleIdx) { const s = axisSpreads(allSampleIdx.filter(x => x !== i), allRungIdx); worstSampleDrop = Math.min(worstSampleDrop, s.sample / s.cov); }
for (const i of allRungIdx) { const s = axisSpreads(allSampleIdx, allRungIdx.filter(x => x !== i)); worstRungDrop = Math.min(worstRungDrop, s.sample / s.cov); }
check(worstSampleDrop > 1, 'dropping any single sample definition never flips it');
check(worstRungDrop > 1, 'dropping any single ladder rung never flips it');
close(worstSampleDrop, 1.419083224218072, 1e-12, 'weakest single sample drop');
close(worstRungDrop, 1.421180555786223, 1e-12, 'weakest single rung drop');
// cardinality matched, exhaustively
const subsets = [];
(function choose(start, cur) {
  if (cur.length === rungLevels.length) { subsets.push(cur.slice()); return; }
  for (let i = start; i < allSampleIdx.length; i++) { cur.push(allSampleIdx[i]); choose(i + 1, cur); cur.pop(); }
})(0, []);
check(subsets.length === 220, 'there are 220 ways to match the sample axis to the ladder at nine levels');
let matchedWins = 0, matchedLo = Infinity, matchedHi = 0;
for (const sub of subsets) { const s = axisSpreads(sub, allRungIdx); const ratio = s.sample / s.cov; if (ratio > 1) matchedWins++; matchedLo = Math.min(matchedLo, ratio); matchedHi = Math.max(matchedHi, ratio); }
check(matchedWins === 220, 'cardinality matching does not explain the ordering: the sample axis wins all 220');
close(matchedLo, 1.307950891324712, 1e-12, 'smallest matched ratio');
close(matchedHi, 1.5853721863594867, 1e-12, 'largest matched ratio');
// the page's own decomposition, on the grid with the family restriction deleted
const freeRows = stored.filter(r => r.fam === 0);
const freeDims = dimensions.filter(d => d.name !== 'fam');
const freeDecomp = mv.decompose(freeDims, mv.runSync(freeRows, (_, i) => ({value:100*(1-Math.exp(freeRows[i].coef)), n:freeRows[i].n})));
check(freeRows.length === 3888 && freeDecomp.exact === true, 'the unrestricted subgrid is complete and balanced');
check(freeDecomp.factors[0].name === 'rung', 'with the family restriction gone the ladder is the largest axis');
close(freeDecomp.factors[0].share, 0.46866409355852756, 1e-14, 'ladder share on the unrestricted subgrid');
check(page.includes((100 * freeDecomp.factors[0].share).toFixed(2)), 'page prints the flipped share it was measured to have');
// a factor with a small main effect and a large interaction must not be called inert
const inert = mv.inertFactors(dimensions, results, 0.02);
const inertNames = inert.inert.map(f => f.name).sort().join(',');
check(inertNames === 'alloc,earnv,tc,wtd', 'four choices are inert on both tests: ' + inertNames);
check(inert.conditional.length === 1 && inert.conditional[0].name === 'sample', 'the worker-definition axis is conditional, not inert');
close(inert.conditional[0].mainShare, 0.005439763983188373, 1e-14, 'worker-definition main share');
close(inert.conditional[0].worstPairShare, 0.030013001691613795, 1e-14, 'worker-definition worst pairwise share');

// ---------------------------------------------------------------------------------------
// THE SOLVER. The shipped coefficients are precomputed, so "they are float64" is a claim
// about a pipeline nobody here can see. This section refits them from the shipped binary
// with an independent column-pivoted Householder QR: orthogonal transformations only, the
// normal-equation matrix never formed. If the shipped grid had come off a normal-equation or
// Cholesky path that quietly accepted a singular matrix, the deep rungs would disagree.
//
// The design is the one documented in research/the-gap-and-its-controls/README.md. Writing
// it out here rather than importing it is deliberate: an independent reimplementation is the
// only version of this check with any teeth.
// ---------------------------------------------------------------------------------------
const EDU_LEVELS = [5,11,15,18,20,22,24,26,28,32,36,38,42];

function pivotedQrLeastSquares(columns, rhs, rows) {
  const p = columns.length;
  const A = columns.map(c => Float64Array.from(c));
  const b = Float64Array.from(rhs);
  const initial = new Float64Array(p);
  const residual = new Float64Array(p);
  for (let c = 0; c < p; c++) {
    let s = 0;
    for (let r = 0; r < rows; r++) s += A[c][r] * A[c][r];
    initial[c] = s;
    residual[c] = s;
  }
  const active = Array.from({length:p}, (_, i) => i);
  const order = [];
  const upper = [];
  const v = new Float64Array(rows);
  for (let step = 0; step < p && step < rows; step++) {
    let bestAt = -1;
    let best = -1;
    for (let k = 0; k < active.length; k++) if (residual[active[k]] > best) { best = residual[active[k]]; bestAt = k; }
    if (bestAt < 0) break;
    const pivot = active[bestAt];
    let exact = 0;
    for (let r = step; r < rows; r++) exact += A[pivot][r] * A[pivot][r];
    residual[pivot] = exact;
    // Rank cut. A column whose remaining norm has collapsed relative to where it started is
    // a linear combination of the columns already taken, and pretending otherwise is exactly
    // the failure this whole section exists to detect.
    if (exact <= 1e-18 * (initial[pivot] || 1)) break;
    active.splice(bestAt, 1);
    order.push(pivot);
    const norm = Math.sqrt(exact);
    const alpha = A[pivot][step] > 0 ? -norm : norm;
    for (let r = step; r < rows; r++) v[r] = A[pivot][r];
    v[step] -= alpha;
    let vv = 0;
    for (let r = step; r < rows; r++) vv += v[r] * v[r];
    const row = new Float64Array(p);
    row[pivot] = alpha;
    if (vv > 0) {
      for (const c of active) {
        let dot = 0;
        for (let r = step; r < rows; r++) dot += v[r] * A[c][r];
        const f = 2 * dot / vv;
        for (let r = step; r < rows; r++) A[c][r] -= f * v[r];
        row[c] = A[c][step];
        const next = residual[c] - A[c][step] * A[c][step];
        residual[c] = next > 0 ? next : 0;
      }
      let dot = 0;
      for (let r = step; r < rows; r++) dot += v[r] * b[r];
      const f = 2 * dot / vv;
      for (let r = step; r < rows; r++) b[r] -= f * v[r];
    } else {
      for (const c of active) row[c] = A[c][step];
    }
    upper.push({row, rhs:b[step]});
  }
  const beta = new Float64Array(p);
  for (let i = order.length - 1; i >= 0; i--) {
    let s = upper[i].rhs;
    for (let j = i + 1; j < order.length; j++) s -= upper[i].row[order[j]] * beta[order[j]];
    beta[order[i]] = s / upper[i].row[order[i]];
  }
  return { beta, rank:order.length, columns:p };
}

function refit(spec) {
  const keep = [];
  const logs = [];
  const [lo, hi] = spec.age.split('-').map(Number);
  for (let i = 0; i < N; i++) {
    if (data.earn[i] <= 0) continue;
    if (spec.sample === 'ftyr' && !(data.wks[i] >= 50 && data.hrs[i] >= 35)) continue;
    if (data.age[i] < lo || data.age[i] > hi) continue;
    if (spec.fam && !(data.mar[i] === 7 && data.kids[i] === 0)) continue;
    if (spec.alloc && data.alloc[i] !== 0) continue;
    if (spec.tc === 'drop' && data.tc[i] !== 0) continue;
    let earnings = spec.earnv === 'wage' ? data.wsal[i] : data.earn[i];
    if (earnings <= 0) continue;
    if (spec.tc === 'x1.4' && data.tc[i] !== 0) earnings *= 1.4;
    if (spec.meas === 'weekly') earnings /= data.wks[i];
    else if (spec.meas === 'hourly') earnings /= data.wks[i] * data.hrs[i];
    keep.push(i);
    logs.push(Math.log(earnings));
  }
  const rows = keep.length;
  const sqrtW = new Float64Array(rows);
  for (let r = 0; r < rows; r++) sqrtW[r] = Math.sqrt(spec.wtd ? data.wt[keep[r]] : 1);
  const columns = [];
  const add = fn => {
    const col = new Float64Array(rows);
    for (let r = 0; r < rows; r++) col[r] = fn(keep[r]) * sqrtW[r];
    columns.push(col);
  };
  add(() => 1);
  add(i => data.female[i]);
  if (spec.rung >= 1) for (const level of EDU_LEVELS) add(i => data.edu2[i] === level ? 1 : 0);
  if (spec.rung >= 2) {
    const exp = i => Math.max(0, data.age[i] - data.edu2[i] / 2 - 6);
    add(exp);
    add(i => Math.pow(exp(i), 2));
    add(i => Math.pow(exp(i), 3));
  }
  if (spec.rung >= 3) {
    for (let v2 = 2; v2 <= 5; v2++) add(i => data.race[i] === v2 ? 1 : 0);
    add(i => data.hisp[i] === 2 ? 1 : 0);
    for (let v2 = 2; v2 <= 9; v2++) add(i => data.div[i] === v2 ? 1 : 0);
  }
  if (spec.rung >= 4) { add(i => Math.log(data.hrs[i])); add(i => Math.log(data.wks[i])); }
  if (spec.rung >= 5) for (let v2 = 2; v2 <= 14; v2++) add(i => data.mjind[i] === v2 ? 1 : 0);
  if (spec.rung >= 6) for (let v2 = 1; v2 <= 11; v2++) add(i => data.mjocc[i] === v2 ? 1 : 0);
  if (spec.rung >= 7) {
    for (let v2 = 2; v2 <= 7; v2++) add(i => data.mar[i] === v2 ? 1 : 0);
    for (let v2 = 1; v2 <= 3; v2++) add(i => Math.min(3, data.kids[i]) === v2 ? 1 : 0);
  }
  if (spec.rung >= 8) for (let v2 = 1; v2 <= 8; v2++) add(i => data.cls[i] === v2 ? 1 : 0);
  const y = new Float64Array(rows);
  for (let r = 0; r < rows; r++) y[r] = logs[r] * sqrtW[r];
  const out = pivotedQrLeastSquares(columns, y, rows);
  return { coef:out.beta[1], rank:out.rank, columns:out.columns, n:rows };
}

const midCell = {sample:'ftyr',age:'25-34',fam:0,alloc:0,tc:'asis',earnv:'total',meas:'annual',wtd:1};
const refitTargets = [];
for (let rung = 0; rung <= 8; rung++) refitTargets.push(Object.assign({}, midCell, {rung}));
refitTargets.push({sample:'ftyr',age:'15-99',fam:0,alloc:0,tc:'asis',earnv:'total',meas:'annual',wtd:1,rung:8});
refitTargets.push({sample:'all',age:'15-99',fam:0,alloc:0,tc:'asis',earnv:'total',meas:'hourly',wtd:1,rung:8});
refitTargets.push({sample:'ftyr',age:'25-34',fam:1,alloc:1,tc:'drop',earnv:'wage',meas:'weekly',wtd:0,rung:6});
refitTargets.push({sample:'ftyr',age:'25-34',fam:1,alloc:1,tc:'drop',earnv:'wage',meas:'weekly',wtd:0,rung:7});
refitTargets.push({sample:'ftyr',age:'25-34',fam:0,alloc:0,tc:'asis',earnv:'total',meas:'hourly',wtd:1,rung:4});

let worstRefit = 0;
const refitted = new Map();
for (const spec of refitTargets) {
  const key = [spec.sample,spec.age,spec.fam,spec.alloc,spec.tc,spec.earnv,spec.meas,spec.wtd,spec.rung].join('|');
  const got = refit(spec);
  refitted.set(key, got);
  const want = byKey.get(key);
  check(got.n === want.n, 'independent refit of ' + key + ' selects the stored row count');
  const delta = Math.abs(got.coef - want.coef);
  worstRefit = Math.max(worstRefit, delta);
  check(delta < 1e-6, 'independent pivoted-QR refit of ' + key + ' reproduces the shipped coefficient (delta ' + delta.toExponential(2) + ')');
}
check(refitTargets.length === 14, 'fourteen cells refitted from the shipped binary, covering every rung');
check(worstRefit < 1e-6, 'largest disagreement between the shipped grid and an independent orthogonal solve is ' + worstRefit.toExponential(2) + ' log points, inside the whole-person weight rounding');
check(page.includes('column-pivoted Householder QR'), 'page names the independent solver rather than only claiming float64');

// The algebra, confirmed by a solver that never saw the stored grid: the measure dial is a
// no-op at rung 4 even when the fit is redone from raw rows.
const refitAnnual4 = refitted.get('ftyr|25-34|0|0|asis|total|annual|1|4').coef;
const refitHourly4 = refitted.get('ftyr|25-34|0|0|asis|total|hourly|1|4').coef;
check(Math.abs(refitAnnual4 - refitHourly4) < 1e-10, 'refitted from raw rows, annual and hourly agree at the hours rung (' + Math.abs(refitAnnual4 - refitHourly4).toExponential(2) + ')');
const refitFam6 = refitted.get('ftyr|25-34|1|1|drop|wage|weekly|0|6').coef;
const refitFam7 = refitted.get('ftyr|25-34|1|1|drop|wage|weekly|0|7').coef;
check(Math.abs(refitFam6 - refitFam7) < 1e-10, 'refitted from raw rows, the family controls change nothing inside the restricted sample (' + Math.abs(refitFam6 - refitFam7).toExponential(2) + ')');

// The rank deficiency the page discloses, proved as an integer identity rather than inferred
// from a condition number. A condition number is a float; this is not.
let dependencyBreaks = 0;
let armedForces = 0;
let armedForcesInFtyr = 0;
let noOccupationCode = 0;
for (let i = 0; i < N; i++) {
  const hasOccupation = data.mjocc[i] >= 1;
  const civilianClass = data.cls[i] >= 1 && data.cls[i] <= 7;
  if (hasOccupation !== civilianClass) dependencyBreaks++;
  if (data.cls[i] === 8) { armedForces++; if (data.wks[i] >= 50 && data.hrs[i] >= 35) armedForcesInFtyr++; }
  if (data.mjocc[i] === 0) noOccupationCode++;
}
check(dependencyBreaks === 0, 'the seven civilian class-of-worker dummies sum to exactly the same column as the eleven major occupation dummies, on all 73,413 rows');
check(noOccupationCode === 4334, '4,334 rows carry no occupation code');
check(armedForces === 12 && armedForcesInFtyr === 0, 'the 12 armed-forces rows do not break it, and none of them is full-time year-round');
check(refitted.get('ftyr|15-99|0|0|asis|total|annual|1|8').columns === 74, 'the deepest shipped design is 74 columns');
check(refitted.get('ftyr|15-99|0|0|asis|total|annual|1|8').rank === 72, 'and rank 72 on the full-time sample, where one class-of-worker category is also empty');
check(refitted.get('all|15-99|0|0|asis|total|hourly|1|8').rank === 73, 'and rank 73 on the all-worker sample, still deficient by exactly one');
check(refitted.get('ftyr|25-34|0|0|asis|total|annual|1|7').rank === 66, 'the rung below it is full rank, so the deficiency arrives with class of worker and is not a solver artefact');

const refusal = mv.runSync([{cell:'empty'}], ()=>null)[0];
check(refusal.ok === false && refusal.value === null && refusal.reason === 'undefined on this subsample', 'shared kit refusal path counts undefined cell');
includes(page, 'No estimate: this specification has no eligible rows.', 'page prints empty-subsample refusal');
includes(page, 'A solve that cannot identify the female contrast is refused, never converted into a number.', 'page prints target-rank refusal');
includes(logic, "byId('selected-gap').textContent = 'undefined'", 'logic renders undefined selection explicitly');
includes(logic, "The cell remains counted as a failed specification.", 'logic says failed cell stays counted');

// The two dead controls must be named where the reader stands, on screen, in the instrument.
// A page that only footnoted them would pass every numeric assertion above and still let a
// reader reach a setting where the control they just moved does nothing.
includes(page, 'id="measure-vacuity"', 'page carries a live banner element for the dead measure dial');
includes(page, 'id="family-vacuity"', 'page carries a live banner element for the dead family controls');
check(page.indexOf('id="measure-vacuity"') < page.indexOf('class="readout"'), 'measure banner sits above the readout it invalidates');
check(page.indexOf('id="family-vacuity"') < page.indexOf('class="readout"'), 'family banner sits above the readout it invalidates');
includes(logic, 'The earnings measure dial is doing nothing here', 'logic writes the dead-dial banner in plain words');
includes(logic, 'The family controls are doing nothing here', 'logic writes the dead-family banner in plain words');
includes(logic, 'spec.rung >= HOURS_RUNG', 'logic gates the dead-dial banner on the hours rung');
includes(logic, "spec.fam === 1 && spec.rung >= FAMILY_RUNG", 'logic gates the dead-family banner on sample and rung');
includes(page, 'log(hourly) = log(annual) - log(weeks) - log(hours)', 'page states the identity that kills the measure dial');

for (const needle of [
  '0.827','0.748','$66,790','$55,240','$56,280','$42,110','7,776','56.11','20.67','46.87','17.76%','23.57%',
  '104 negative earners','73,309 positive earners','0.82709','0.0107','116 of the 7,776 cells',
  'P60-282','P60-286','income year 2023','0.809',
  'The default surface contains 7,776 specifications','Nothing below claims to be the 14,688-cell surface',
  'which axis dominates is itself a specification choice',
  'Bureau of Labor Statistics usual weekly earnings series, and it is not on this page'
]) includes(page, needle, 'page carries verified statement');
// The unverified rung must stay unverified: no BLS figure anywhere in the shipped deliverables.
for (const [name, text] of [['page', page], ['logic', logic], ['frontmatter', front], ['README', readme]]) {
  check(!/\$?\d[\d,.]*\s*(?:dollars|percent|%)?[^.]{0,40}\busual weekly earnings\b/i.test(text) && !/\busual weekly earnings\b[^.]{0,60}\d/i.test(text),
    name + ' quotes no BLS usual-weekly-earnings figure (bls.gov 403d every fetch, so the rung is unchecked)');
}
// The 420-character placard gate forced the under-two count out of `plain`, so it is
// asserted where it actually lives now: on the page itself. Dropping the assertion instead
// would have let a real figure leave the site unnoticed.
for (const needle of ['0.82709','7,776-specification','56.11%','20.67%','46.87%','income year 2023']) includes(front, needle, 'frontmatter claim matches verifier');
includes(page, '116', 'the page itself still prints the count of cells under two percentage points');
includes(readme, 'cdb39cdac34bef99dd0940ab28e306f692404c2eea44d85dfd634214872a0a09', 'README records raw archive hash');
includes(readme, '148,664,101', 'README records raw archive size');
includes(readme, '17 U.S.C. §105', 'README records redistribution basis');
includes(readme, 'The shipped surface is the validated 7,776-cell major-group slice.', 'README discloses reduced surface');

const jsonLdMatch = page.match(/<script type="application\/ld\+json">([\s\S]*?)<\/script>/);
check(jsonLdMatch !== null, 'JSON-LD block exists');
const jsonLd = JSON.parse(jsonLdMatch[1]);
check(jsonLd.datePublished === '2026-08-10' && jsonLd.dateModified === '2026-08-10', 'JSON-LD landing dates');
check(jsonLd.description.includes('7,776-specification') && jsonLd.description.includes('income year 2023') && jsonLd.description.includes('specification choice'), 'JSON-LD description matches verified surface and does not state a settled verdict');
const metaDesc = (page.match(/<meta name="description" content="([^"]*)"/) || [])[1] || '';
check(metaDesc.includes('income year 2023') && metaDesc.includes('P60-282'), 'meta description names the release and income year it reproduces');
check(!/\b56%|\b21%/.test(metaDesc) && !/\b56%|\b21%/.test(jsonLd.description), 'shareable descriptions no longer state the grid-dependent ordering as a bare result');
includes(front, 'date: 2026-08-10', 'frontmatter landing date');
const forbiddenDash = String.fromCodePoint(8212);
check(!page.includes(forbiddenDash) && !logic.includes(forbiddenDash) && !front.includes(forbiddenDash) && !readme.includes(forbiddenDash), 'authored deliverables contain no em dash');
check((page.match(/<script\b/g)||[]).length === (page.match(/<\/script>/g)||[]).length, 'every HTML script closes');
check(page.trimEnd().endsWith('</html>'), 'HTML has load-bearing closing tag');

console.log('PASS: ' + assertions.toLocaleString('en-US') + ' assertions.');
console.log('Anchor: paper 0.827; recomputed ' + anchorRatio.toFixed(8) + '; residual +' + (anchorRatio-0.827).toFixed(8) + '.');
console.log('Grid: 7,776 defined, 0 undefined; paper point percentile ' + (100*belowPaper/curve.nOk).toFixed(1) + '.');
console.log('Variance: family restriction ' + (100*shares.fam).toFixed(2) + '%, ladder ' + (100*shares.rung).toFixed(2) + '%, interaction ' + (100*decomp.interactionShare).toFixed(2) + '%.');
console.log('Raw-cell audit: ' + rawCells + ' recomputed; maximum rounded-weight coefficient delta ' + maxRoundedWeightDelta.toExponential(3) + '.');
console.log('Dead controls: measure dial inert in ' + deadMeasureCells.toLocaleString('en-US') + ' cells (worst ' + deadMeasureWorst.toExponential(2) + ' pts, live ' + liveMeasureLow.toFixed(2) + ' to ' + liveMeasureHigh.toFixed(2) + '); family controls inert in ' + deadFamilyCells + ' (worst ' + deadFamilyWorst.toExponential(2) + ' pts, live ' + liveFamilyLow.toFixed(4) + ' to ' + liveFamilyHigh.toFixed(2) + ').');
console.log('Axis ordering: full grid sample ' + fullAxes.sample.toFixed(4) + ' vs ladder ' + fullAxes.cov.toFixed(4) + '; drop the never-married option and it flips to ' + noFamilyAxes.sample.toFixed(4) + ' vs ' + noFamilyAxes.cov.toFixed(4) + ' (ladder ' + (100 * freeDecomp.factors[0].share).toFixed(2) + '% of the remaining subgrid).');
console.log('Independent solver: ' + refitTargets.length + ' cells refitted by column-pivoted Householder QR from the shipped binary; worst deviation ' + worstRefit.toExponential(3) + ' log points; deepest design 74 columns of rank 72.');
