#!/usr/bin/env node
'use strict';
import {readFileSync,existsSync} from 'node:fs';
import {dirname,join} from 'node:path';
import {fileURLToPath} from 'node:url';

const LN2=Math.log(2), annual=R=>LN2/Math.log1p(R/100), continuous=R=>LN2/(R/100);
const rule72=R=>72/R, rule693=R=>69.3/R, err=(guess,truth)=>(guess/truth-1)*100;
const decline=R=>Math.log(.5)/Math.log(1-R/100);
let pass=0,fail=0;
function check(name,ok,detail=''){console.log(`${ok?'PASS':'FAIL'} ${name}${detail?'  '+detail:''}`);ok?pass++:fail++;}
function near(a,b,t=1e-9){return Math.abs(a-b)<=t;}

console.log('the-rule-of-72 :: offline verifier');
const e8=annual(8),r728=rule72(8),r6938=rule693(8);
check('8% annual exact = 9.0065 yr',near(e8,9.006468342,.000000001),e8.toFixed(10));
check('8% rule of 72 = 9.0000 yr',near(r728,9),r728.toFixed(4));
check('8% rule of 72 signed error = -0.0718%',near(err(r728,e8),-.0718188501,1e-9),err(r728,e8).toFixed(6)+'%');
check('8% rule of 69.3 = 8.6625 yr',near(r6938,8.6625),r6938.toFixed(4));
check('8% rule of 69.3 signed error = -3.8191%',near(err(r6938,e8),-3.8191256433,1e-9),err(r6938,e8).toFixed(6)+'%');
check('independent annual anchor: 1.08^t = 2',near(Math.pow(1.08,e8),2,1e-12),Math.pow(1.08,e8).toFixed(12));

let lo=7,hi=9;
for(let i=0;i<100;i++){const mid=(lo+hi)/2;if(annual(mid)-rule72(mid)>0)hi=mid;else lo=mid;}
const pin=(lo+hi)/2;
check('72 is exact at 7.8469% annual',near(pin,7.846871453,1e-9),pin.toFixed(9)+'%');
check('pin independently doubles: (1+R)^72/R = 2',near(Math.pow(1+pin/100,72/pin),2,1e-12));

for(const R of [.25,1,4,8,12,18,36,72]){
  const t=annual(R),a=rule72(R),b=rule693(R);
  check(`rate table ${R}% recomputes finite exact and signed errors`,[t,a,b,err(a,t),err(b,t)].every(Number.isFinite),`exact ${t.toFixed(6)}, e72 ${err(a,t).toFixed(4)}%, e69.3 ${err(b,t).toFixed(4)}%`);
}
let tableOK=true;
for(let R=.25;R<=72.00001;R+=.01){const t=annual(R);tableOK&&=Number.isFinite(t)&&near(Math.pow(1+R/100,t),2,2e-12);}
check('full slider table, 7,176 rates, returns exactly 2 within floating tolerance',tableOK);

check('continuous 69.3/R error constant = -0.0212%',near(err(rule693(8),continuous(8)),-.0212336664,1e-9),err(rule693(8),continuous(8)).toFixed(6)+'%');
check('continuous 72/R error constant = +3.8740%',near(err(rule72(8),continuous(8)),3.8740429440,1e-9),err(rule72(8),continuous(8)).toFixed(6)+'%');
check('Taylor constant term ln(2)/2 = 0.3466 yr',near(LN2/2,.3465735903,1e-10),(LN2/2).toFixed(10));

check('18% annual balance doubles in 4.1878 yr',near(annual(18),4.1878351335,1e-10),annual(18).toFixed(10));
check('18% rule says 4.0000 yr',near(rule72(18),4),rule72(18).toFixed(4));
check('18% rule understates by 4.49%',near(err(rule72(18),annual(18)),-4.485256165,1e-9),err(rule72(18),annual(18)).toFixed(6)+'%');
check('3% annual decline halves purchasing power in 22.7566 yr',near(decline(3),22.7565730628,1e-10),decline(3).toFixed(10));
check('independent decline anchor: 0.97^t = 0.5',near(Math.pow(.97,decline(3)),.5,1e-12));

/* ------------------------------------------------------------------ *
 * SECOND CUT (2026-08-23). Everything below re-derives the claims the
 * page's second half makes, from the mathematics, in this file, without
 * reading engine A's artifacts or engine B's output. Where it prints a
 * number the page also prints, the last block asserts the page really
 * says it.
 * ------------------------------------------------------------------ */
console.log('\n-- second cut: the ideal numerator as a function of the per-period rate --');

const C=100*LN2;
const Dg=p=>p===0?C:100*p*LN2/Math.log1p(p);        // growth
const Dd=p=>p===0?C:100*p*LN2/(-Math.log1p(-p));    // decline
const Dpick=(p,dir)=>dir>0?Dg(p):Dd(p);
const div30=N=>{let c=0;for(let d=1;d<=30;d++) if(N%d===0)c++;return c;};
function rateAt(target,dir){                        // per-period rate, per cent
  let lo=1e-15,hi=dir>0?0.4:0.9999999;
  for(let i=0;i<200;i++){const mid=(lo+hi)/2,v=Dpick(mid,dir);
    if(dir>0?(v<target):(v>target)) lo=mid; else hi=mid;}
  return 100*(lo+hi)/2;
}
check('100 ln 2 = 69.3147180560',near(C,69.3147180559945,1e-12),C.toFixed(10));

// THE COLLAPSE: the ideal numerator depends only on the rate per period, so a
// nominal rate and a compounding frequency that share a quotient must share it.
// Written the long way round (out of (1+p)^(mt) = 2) so this is a real test of
// the cancellation, not a restatement of it.
function DviaFirstPrinciples(Rpct,m){
  const p=Rpct/(100*m);
  const t=LN2/(m*Math.log1p(p));                    // years to double
  return Rpct*t;                                    // the numerator that makes N/R exact
}
{
  const pairs=[[2,1],[4,2],[8,4],[24,12],[104,52],[730,365]];
  const vals=pairs.map(([R,m])=>DviaFirstPrinciples(R,m));
  const spread=Math.max(...vals)-Math.min(...vals);
  check('collapse: 2%/yearly, 4%/half-yearly, 8%/quarterly, 24%/monthly, 104%/weekly, 730%/daily share one numerator',
    spread<1e-11, `spread ${spread.toExponential(2)}, value ${vals[0].toFixed(12)}`);
  check('collapse: that shared numerator is 70.005577562293',near(vals[0],70.005577562293,1e-11),vals[0].toFixed(12));
  check('collapse: it equals the one-argument form D(p)=100 p ln2/ln(1+p) at p=2%',
    near(vals[0],Dg(0.02),1e-12));
  // and each of them really does double in the years the numerator implies
  let doublesOK=true;
  for(const [R,m] of pairs){const t=LN2/(m*Math.log1p(R/(100*m)));doublesOK&&=near(Math.pow(1+R/(100*m),m*t),2,1e-11);}
  check('collapse: every one of those six accounts really doubles at that time',doublesOK);
}

// THE ERROR COLLAPSE: relative error is N/D - 1 and does not involve the rate.
{
  let ok=true;
  for(const R of [1,3,8,17,40]) for(const N of [69,70,72,76]){
    const t=LN2/Math.log1p(R/100), approx=N/R, D=Dg(R/100);
    ok&&=near((approx/t-1),(N/D-1),1e-12);
  }
  check('error of numerator N is exactly N/D − 1, at every rate tested',ok);
}

// THE MARCH OF THE NUMERATOR: boundaries are roots of D(p) = N + 1/2.
{
  const edges=[[69.5,0.535086607],[70.5,3.439384537],[71.5,6.370967823],[72.5,9.329453653],
               [73.5,12.314469156],[74.5,15.325651035],[75.5,18.362645229],[76.5,21.425106578],
               [77.5,24.512698514],[78.5,27.625092757],[79.5,30.761969028]];
  let ok=true,worst=0;
  for(const [d,r] of edges){const got=rateAt(d,+1);worst=Math.max(worst,Math.abs(got-r));ok&&=near(got,r,1e-7);}
  check('growth: all eleven band boundaries land where the page says',ok,`worst ${worst.toExponential(2)} pp`);
  check("72's exact band is 6.370968% to 9.329454%",
    near(rateAt(71.5,+1),6.370967823,1e-7)&&near(rateAt(72.5,+1),9.329453653,1e-7));
  check('72 is the nearest whole number at 8% per period, 71 at 5%, 73 at 11%',
    Math.round(Dg(0.08))===72&&Math.round(Dg(0.05))===71&&Math.round(Dg(0.11))===73);
  check('71, 73, 74, 77 and 79 each really are the most accurate whole number somewhere',
    [71,73,74,77,79].every(N=>{
      const lo=rateAt(N-0.5,+1)/100, hi=rateAt(N+0.5,+1)/100, mid=(lo+hi)/2;
      return Math.round(Dg(mid))===N;
    }));
  check('and 71, 73 and 79 are prime, so no whole rate but 1 divides them',
    div30(71)===1&&div30(73)===1&&div30(79)===1);
}

// THE DIVISIBILITY-CONSTRAINED MAP.
{
  const ok70=rateAt(71,+1), ok72=rateAt(73.5,+1), ok75=rateAt(76.5,+1);
  check('with the divisibility constraint, 70 owns 0% to 4.901790%',near(ok70,4.901789673,1e-7),ok70.toFixed(6));
  check('and 72 owns 4.901790% to 12.314469%',near(ok72,12.314469156,1e-7),ok72.toFixed(6));
  check('and 75 owns 12.314469% to 21.425107%',near(ok75,21.425106578,1e-7),ok75.toFixed(6));
  // "usable" here = at least 5 of the whole rates 1..30 divide it evenly
  const usable=[];for(let N=40;N<=160;N++) if(div30(N)>=5) usable.push(N);
  const best=(p,dir)=>usable.reduce((a,b)=>Math.abs(b-Dpick(p,dir))<Math.abs(a-Dpick(p,dir))?b:a);
  check('at 3% per period the best usable numerator for growth is 70',best(0.03,+1)===70);
  check('at 8% per period it is 72',best(0.08,+1)===72);
  check('at 16% per period it is 75',best(0.16,+1)===75);
}

// THE DECLINE BRANCH.
{
  check('decline: the ideal numerator falls below 100 ln 2 at every positive rate',
    [0.01,0.03,0.08,0.15,0.25].every(p=>Dd(p)<C));
  check('decline: the 70-to-66 boundary is at 3.769337%',near(rateAt(68,-1),3.769337365,1e-7),rateAt(68,-1).toFixed(6));
  check('decline at 10% a year: ideal numerator 65.7881347896',near(Dd(0.10),65.7881347896,1e-9),Dd(0.10).toFixed(10));
  check('decline at 10%: 72 overstates the halving time by 9.44%',near((72/Dd(0.10)-1)*100,9.442227,1e-5),((72/Dd(0.10)-1)*100).toFixed(4)+'%');
  check('decline at 10%: 70 overstates it by 6.40%',near((70/Dd(0.10)-1)*100,6.402165,1e-5),((70/Dd(0.10)-1)*100).toFixed(4)+'%');
  const usable=[];for(let N=40;N<=160;N++) if(div30(N)>=5) usable.push(N);
  let ever72=false;
  for(let p=0.0001;p<0.60;p+=0.0001){
    const b=usable.reduce((a,x)=>Math.abs(x-Dd(p))<Math.abs(a-Dd(p))?x:a);
    if(b===72){ever72=true;break;}
  }
  check('72 is never the best numerator for a decline under the threshold the page uses (>=5 divisors), to 60%',!ever72);
  // The unconditional version, which is the one the page states as a pull quote:
  // the decline numerator is below the constant everywhere, so the NEAREST whole
  // number to it is at most 69, whatever set you allow.
  {
    let maxNearest=0;
    for(let p2=0.0001;p2<0.60;p2+=0.0001) maxNearest=Math.max(maxNearest,Math.round(Dd(p2)));
    check('the nearest whole number to a decline numerator is at most 69, at every rate to 60%',maxNearest<=69,`max ${maxNearest}`);
  }
  // And the caveat the page is now careful to state: at a strict threshold that
  // rules out everything nearer, 72 DOES come back on the decline row. The page
  // says so; if that ever stopped being true the page would be over-cautious,
  // and if the page stopped saying it the page would be over-claiming.
  {
    const strict=[];for(let N=40;N<=160;N++) if(div30(N)>=10) strict.push(N);
    const b=strict.reduce((a,x)=>Math.abs(x-Dd(0.01))<Math.abs(a-Dd(0.01))?x:a);
    check('at a threshold of ten divisors the decline row does admit 72, which the page discloses',
      b===72&&/72 then reappears on the shrinking row/.test(readFileSync(join(dirname(fileURLToPath(import.meta.url)),'..','..','public','strata','the-rule-of-72','index.html'),'utf8')),
      `strict set {${strict.join(',')}}, best at 1% decline = ${b}`);
  }
  // and the halving really happens then
  check('independent decline anchor at 10%: 0.9^(65.7881347896/10) = 0.5',
    near(Math.pow(.9,Dd(0.10)/10),.5,1e-12));
}

// THE WHOLE-QUOTIENT CONTEST.
{
  const winners={};
  for(let R=1;R<=25;R++){
    const D=Dg(R/100);let best=null;
    for(let N=55;N<=100;N++) if(N%R===0&&(best===null||Math.abs(N/D-1)<Math.abs(best/D-1))) best=N;
    (winners[best]??=[]).push(R);
  }
  check('72 wins the whole-quotient contest at 4, 6, 8, 9, 12, 18 and 24',
    (winners[72]||[]).join(',')==='4,6,8,9,12,18,24',(winners[72]||[]).join(','));
  check('70 wins it at 1, 2, 5, 7, 10 and 14',
    (winners[70]||[]).join(',')==='1,2,5,7,10,14',(winners[70]||[]).join(','));
  check('no other numerator wins more than twice',
    Object.entries(winners).every(([N,rs])=>N==='70'||N==='72'||rs.length<=2),
    Object.entries(winners).filter(([N])=>N!=='70'&&N!=='72').map(([N,rs])=>N+':'+rs.length).join(' '));
  check('72 and 70 between them win 13 of the first 25 whole rates',
    (winners[72]||[]).length+(winners[70]||[]).length===13);
  check('at 2% the best whole-quotient rule is 70/2 = 35 years, off by 0.008%',
    winners[70].includes(2)&&near((70/Dg(0.02)-1)*100,-0.007967,1e-5),((70/Dg(0.02)-1)*100).toFixed(6)+'%');
}

// DIVISIBILITY AND THE PARETO FRONTIER.
{
  check('72 has ten divisors among the whole rates 1% to 30%',div30(72)===10);
  check('nothing between 65 and 80 has more',
    Array.from({length:16},(_,i)=>65+i).every(N=>N===72||div30(N)<=10)&&
    Array.from({length:16},(_,i)=>65+i).filter(N=>div30(N)===10).length===1);
  check('in 55 to 100 only 60 beats it, and only 84 and 90 draw level',
    (()=>{const better=[],equal=[];for(let N=55;N<=100;N++){if(div30(N)>10)better.push(N);else if(div30(N)===10&&N!==72)equal.push(N);}
      return better.join(',')==='60'&&equal.join(',')==='84,90';})());
  // |N/D − 1| is monotone in D and D is monotone in p, so the worst case over a
  // band is at one of its two ends. Exact, and no step size to choose.
  const worst=(N,lo,hi)=>100*Math.max(Math.abs(N/Dg(lo/100)-1),Math.abs(N/Dg(hi/100)-1));
  check("72's worst error over 4% to 12% per period is 1.900761%",near(worst(72,4,12),1.900761,1e-4),worst(72,4,12).toFixed(6)+'%');
  check("and over 6% to 10% it is 0.997463%",near(worst(72,6,10),0.997463,1e-4),worst(72,6,10).toFixed(6)+'%');
  const frontier=(lo,hi)=>{
    const c=[];for(let N=55;N<=100;N++) c.push({N,e:worst(N,lo,hi),d:div30(N)});
    return c.filter(a=>!c.some(b=>b!==a&&b.e<=a.e&&b.d>=a.d&&(b.e<a.e||b.d>a.d))).map(a=>a.N).sort((x,y)=>x-y);
  };
  check('over 4% to 12%, the Pareto frontier is exactly {60, 72}',frontier(4,12).join(',')==='60,72',frontier(4,12).join(','));
  check('over 6% to 10%, it is exactly {60, 72}',frontier(6,10).join(',')==='60,72',frontier(6,10).join(','));
  check('over 2% to 6%, 71 and 70 join it: {60, 70, 71, 72}',frontier(2,6).join(',')==='60,70,71,72',frontier(2,6).join(','));
}

// PUBLISHED RATES PLACED ON THE CURVE. Each figure is a quoted number from the
// body named on the page; what is checked here is only the arithmetic done to
// it, which is all this page ever does to it.
{
  const usable=[];for(let N=40;N<=160;N++) if(div30(N)>=5) usable.push(N);
  const bestU=D=>usable.reduce((a,b)=>Math.abs(b-D)<Math.abs(a-D)?b:a);
  check('FDIC savings 0.38% read yearly: ideal numerator 69.4463',near(Dg(0.0038),69.4463,5e-5),Dg(0.0038).toFixed(4));
  check('a 2% price level doubles in 35.0028 yr, and 70/2 = 35 is 0.008% short',
    near(LN2/Math.log1p(0.02),35.0028,5e-5)&&near((35/(LN2/Math.log1p(0.02))-1)*100,-0.008,5e-4));
  check('CPI 3.4% purchasing power: ideal numerator 68.1296, 72 runs 5.68% long',
    near(Dd(0.034),68.1296,5e-5)&&near((72/Dd(0.034)-1)*100,5.681,5e-3),Dd(0.034).toFixed(4));
  check('mortgage 6.65% read yearly wants 72 (D=71.5947), read monthly wants 70 (D=69.5066)',
    near(Dg(0.0665),71.5947,5e-5)&&Math.round(Dg(0.0665))===72&&
    near(Dg(0.0665/12),69.5066,5e-5)&&Math.round(Dg(0.0665/12))===70);
  check('card 22.15% APR compounding monthly: ideal numerator 69.9525',near(Dg(0.2215/12),69.9525,5e-5),Dg(0.2215/12).toFixed(4));
  check('and 70/22.15 = 3.1603 yr against a true 3.1581, an error of 0.07%',
    near(70/22.15,3.1603,5e-5)&&near(LN2/(12*Math.log1p(0.2215/12)),3.1581,5e-5)&&
    near((70/Dg(0.2215/12)-1)*100,0.0679,5e-4));
  check('read instead as an effective annual rate it wants 76.7355, and 70 is 8.78% small',
    near(Dg(0.2215),76.7355,5e-5)&&near((70/Dg(0.2215)-1)*100,-8.7776,5e-4));
  check('and 72/22.15 = 3.2506 yr, which the monthly reading makes 2.93% long',
    near(72/22.15,3.2506,5e-5)&&near((72/Dg(0.2215/12)-1)*100,2.9270,5e-3),((72/Dg(0.2215/12)-1)*100).toFixed(4)+'%');
  check('MSCI World 9.02% since 1987: ideal numerator 72.3958, 72 off by 0.55%',
    near(Dg(0.0902),72.3958,5e-5)&&near((72/Dg(0.0902)-1)*100,-0.5467,5e-4)&&bestU(Dg(0.0902))===72);
  check('MSCI World 13.29% over ten years: ideal 73.8249, nearest 74, best usable 75, 72 off by 2.47%',
    near(Dg(0.1329),73.8249,5e-5)&&Math.round(Dg(0.1329))===74&&bestU(Dg(0.1329))===75&&
    near((72/Dg(0.1329)-1)*100,-2.4720,5e-4));
  // the direction of the headline: 70 beats 72 on the card, 72 beats 70 on equities
  check('70 beats 72 on the card and 72 beats 70 on the long-run equity return',
    Math.abs(70/Dg(0.2215/12)-1)<Math.abs(72/Dg(0.2215/12)-1)&&
    Math.abs(72/Dg(0.0902)-1)<Math.abs(70/Dg(0.0902)-1));
}

/* ---------------- the page itself ---------------- */
const here=dirname(fileURLToPath(import.meta.url));
const html=readFileSync(join(here,'..','..','public','strata','the-rule-of-72','index.html'),'utf8');
for(const token of ['9.0065','9.0000','8.6625','−0.07%','−3.82%','7.8469%','4.1878','22.7566','69.3147/R + 0.3466']) check(`page contains recomputed anchor ${token}`,html.includes(token));
for(const token of ['69.3147180560','70.005577562293','D(p) = 100 p ln2 / ln(1+p)',
                    '6.370968%','9.329454%','3.439385%','4.901790%','12.314469%',
                    '3.769337%','65.7881347896','9.44%','6.40%',
                    '1.900761%','0.997463%','1.420490%',
                    '69.4463','70.0056','68.1296','71.5947','69.5066','69.9525','72.3958','73.8249',
                    '3.1603','22.15%','9.02%','13.29%','6.65%','0.38%','3.4%',
                    'August 17, 2026','January 27, 2026','August 20, 2026','31 December 1987']) {
  check(`page contains second-cut anchor ${token}`,html.includes(token));
}
check('page still names 71 as the numerator nobody proposed',/nobody has ever proposed it/.test(html)&&html.includes('71 is the most accurate whole number'));
check('page states that 72 never appears on the decline branch',/72 never appears/.test(html));
// The page prints how many assertions the two-engine comparison makes. Hold it to it.
{
  let claimed=null;
  const m=html.match(/<span id="cmp-n">(\d+)<\/span>/);
  if(m) claimed=Number(m[1]);
  let actual=null;
  try{actual=Number(readFileSync(join(here,'results','compare-count.txt'),'utf8').trim());}catch{}
  check('the assertion count the page claims is the count compare.mjs actually made',
    claimed!==null&&actual!==null&&claimed===actual,`page says ${claimed}, compare.mjs made ${actual}`);
}
for(const f of ['divisor-map.mjs','divisor_map.py','compare.mjs']){
  check(`page names ${f} and the file is there`,html.includes('research/the-rule-of-72/'+f)&&existsSync(join(here,f)));
}
for(const token of ['folio 181 recto, article 44','a far capo al[l]&#227;no','Distincto nona. Tracatus quintus',
                    'summadearithmeti00paci','83-1-quod-2f','il00315000','10.1017/S1357321719000254',
                    '72.0517','71.3740','11.8957','9.0065']) {
  check(`page contains 1494 anchor ${token.slice(0,34)}`,html.includes(token));
}
check('page still records that who devised the rule is unverified',/who first devised the rule/.test(html));

/* ------------------------------------------------------------------ *
 * COUPLING, THE PART A TOKEN LIST CANNOT DO.
 *
 * A hand-written list of strings to look for only ever catches the
 * numbers whoever wrote the list happened to think of. The mutation
 * apparatus (research/verifier-independence/mutate.mjs) proved that on
 * this very page: it changed 21.667491 in the prose to 21.689158 and
 * nothing went red, because that boundary was not on the list.
 *
 * So instead of listing, enumerate. Every six-decimal percentage this
 * page prints is a boundary of the map, and the map is computable, so
 * the set of legitimate ones is computable too. Anything on the page
 * outside that set is a number the mathematics does not produce.
 * ------------------------------------------------------------------ */
{
  const legitRaw = [];
  const add = v => legitRaw.push(Number(v));
  for (let N = 55; N <= 100; N++) {
    for (const dir of [+1, -1]) {
      for (const t of [N + 0.5, N - 0.5, N]) {
        const reachable = dir > 0 ? t > C : t < C;
        if (reachable && t > 40 && t < 120) add(rateAt(t, dir));
      }
    }
  }
  // boundaries under every divisibility threshold the page can be set to
  for (let k = 1; k <= 10; k++) {
    const set = []; for (let N = 40; N <= 160; N++) if (div30(N) >= k) set.push(N);
    for (const dir of [+1, -1]) {
      const ord = dir > 0 ? set : [...set].reverse();
      for (let i = 0; i + 1 < ord.length; i++) {
        const mid = (ord[i] + ord[i + 1]) / 2;
        const reachable = dir > 0 ? mid > C : mid < C;
        if (reachable) add(rateAt(mid, dir));
      }
    }
  }
  // The Pareto table's column is an ERROR in per cent, not a rate, so its
  // legitimate values are the worst-case errors themselves. Same rule: the
  // set is computable, so enumerate it rather than listing what you remember.
  {
    const wc = (N, lo, hi) => 100 * Math.max(Math.abs(N / Dg(lo / 100) - 1), Math.abs(N / Dg(hi / 100) - 1));
    for (const [lo, hi] of [[1, 20], [2, 6], [4, 12], [6, 10]])
      for (let N = 55; N <= 100; N++) add(wc(N, lo, hi));
  }
  // Any precision, not just six places: the mutation apparatus lengthens a
  // number rather than replacing it (21.667491 -> 21.689158491), so a pattern
  // pinned to six decimals looks straight past the defect it was written for.
  // The published-rates table prints per-period rates as well as boundaries.
  // Those are quotients of a quoted figure and its compounding frequency, so
  // declare the figures once and derive rather than listing the results.
  const PUBLISHED = [
    [0.38, 1],   // FDIC national savings rate, 17 Aug 2026
    [2, 1],      // Federal Reserve longer-run PCE objective
    [3.4, 1],    // US CPI-U, twelve months to July 2026
    [6.65, 1], [6.65, 12],   // Freddie Mac 30-year fixed, both readings
    [22.15, 12], [22.15, 1], // G.19 credit cards, both readings
    [9.02, 1], [13.29, 1],   // MSCI World, since 1987 and ten-year
    [8, 1], [24, 12],        // the curve instrument's own worked examples
  ];
  for (const [R, m] of PUBLISHED) add(R / m);
  const printed = [...new Set((html.match(/\d+\.\d{4,}(?=%)/g) || []))];
  const strays = printed.filter(v => {
    const dp = v.split('.')[1].length;
    return !legitRaw.some(r => r.toFixed(dp) === v);
  });
  check(`every decimal percentage on the page is a boundary the mathematics produces (${printed.length} found)`,
    strays.length === 0, strays.length ? `not produced: ${strays.join(', ')}` : 'all accounted for');
  check('and there are enough of them that this is doing work', printed.length >= 12, `${printed.length}`);
}

/* ------------------------------------------------------------------ *
 * THE PAGE'S OWN ARITHMETIC, RUN.
 *
 * The same mutation run changed constants inside the page's shipped
 * script and nothing noticed, because a check that reads bytes reads
 * bytes. It cannot read bytes and also not run them. So: lift the
 * page's own function declarations out of its script, evaluate them in
 * an isolated context, and make them answer to the implementations in
 * this file. A browser is not needed for that, only honesty about
 * which code is being tested.
 * ------------------------------------------------------------------ */
{
  const wanted = ['Dg', 'Dd', 'D', 'div30', 'rateAt'];
  const src = [];
  let missing = [];
  for (const name of wanted) {
    // Function declarations in the page are single-purpose and brace-balanced;
    // walk the braces rather than trusting a regex to find the end.
    const at = html.indexOf(`function ${name}(`);
    if (at < 0) { missing.push(name); continue; }
    let i = html.indexOf('{', at), depth = 0, end = -1;
    for (; i < html.length; i++) {
      if (html[i] === '{') depth++;
      else if (html[i] === '}') { depth--; if (depth === 0) { end = i + 1; break; } }
    }
    if (end < 0) { missing.push(name); continue; }
    src.push(html.slice(at, end));
  }
  check('the page still declares the five functions its instruments run', missing.length === 0, missing.join(','));
  if (!missing.length) {
    const vm = await import('node:vm');
    const ctx = vm.createContext({ Math, Number });
    vm.runInContext(`var LN2=Math.log(2), C=100*LN2;\n${src.join('\n')}\n`, ctx);
    const call = (fn, ...a) => vm.runInContext(`${fn}(${a.join(',')})`, ctx);
    let worstD = 0;
    for (const p2 of [0, 0.005, 0.02, 0.0665, 0.08, 0.1329, 0.2215, 0.3]) {
      worstD = Math.max(worstD, Math.abs(call('Dg', p2) - Dg(p2)), Math.abs(call('Dd', p2) - Dd(p2)));
    }
    check('the page\'s own D(p), growth and decline, agrees with this file at every rate tested',
      worstD < 1e-9, `worst ${worstD.toExponential(2)}`);
    let worstR = 0;
    for (const t of [69.5, 71, 71.5, 72, 72.5, 73.5, 76.5]) worstR = Math.max(worstR, Math.abs(call('rateAt', t, 1) - rateAt(t, +1)));
    for (const t of [68, 66, 63.5]) worstR = Math.max(worstR, Math.abs(call('rateAt', t, -1) - rateAt(t, -1)));
    check('the page\'s own root finder lands where this file\'s does', worstR < 1e-7, `worst ${worstR.toExponential(2)} pp`);
    let divOK = true;
    for (let N = 55; N <= 100; N++) divOK &&= call('div30', N) === div30(N);
    check('the page\'s own divisor count agrees for every N in 55 to 100', divOK);
    check('the page\'s own constant is 100 ln 2',
      Math.abs(vm.runInContext('C', ctx) - C) < 1e-12);
  }
}


// THE FORMULAS, VERBATIM, BOTH THE ONES YOU SEE AND THE ONES A SCREEN READER
// SPEAKS. A mutation run changed a digit inside a .math block's aria-label,
// which is prose that only some readers ever meet, and nothing noticed. Every
// formula this page states is short and fixed, so state them here too.
for (const frag of [
  'D(p) = 100 p ln2 / ln(1+p)',
  'm t ln(1+p) = ln 2',
  'D = R t = 100 m p &#183; ln2 / (m ln(1+p))'.replace('&#183;', '·'),
  'error = (N/R) / (D/R) &#8722; 1 = N/D &#8722; 1'.replace(/&#8722;/g, '−'),
  'D(p) = 100 p ln2 / ( &#8722;ln(1&#8722;p) )'.replace(/&#8722;/g, '−'),
  'the ideal numerator D equals 100 p ln 2 divided by the natural log of 1 plus p',
  'the number of compounding periods per year cancelling out',
  'The relative error of numerator N equals N divided by D minus one',
  '100 p ln 2 divided by minus the natural log of one minus p',
]) check(`formula or its spoken label is intact: ${frag.slice(0, 44)}`, html.includes(frag));


/* ------------------------------------------------------------------ *
 * THE SHIPPED INSTRUMENTS, RUN.
 *
 * research/the-rule-of-72/run-page.mjs boots this page's own <script>
 * against a strict stub of exactly the DOM it touches, so the curve, the
 * band strip and the whole-quotient table actually execute. What they
 * write into their readouts is then held to the arithmetic in this file.
 * Lifting the pure functions out (above) proved the formulas; this
 * proves the instrument that calls them, which is what a reader meets.
 * ------------------------------------------------------------------ */
{
  const { bootPage } = await import('./run-page.mjs');
  let page = null, bootErr = null;
  try { page = bootPage(); } catch (e) { bootErr = e; }
  check('the shipped instruments boot and run outside a browser', page !== null,
    bootErr ? String(bootErr.message).slice(0, 120) : 'ok');

  if (page) {
    const { el, fire, read } = page;
    const num = id => Number(String(read(id)).replace(/[^0-9.−-]/g, '').replace('−', '-'));

    // as it loads: 8%, once a year, growing
    check('on load the instrument computes p = 8.0000%', read('p-out') === '8.0000%', read('p-out'));
    check('on load it computes D = 72.0517, which is this file\'s Dg(0.08)',
      Math.abs(num('d-out') - Dg(0.08)) < 5e-5, `${read('d-out')} vs ${Dg(0.08).toFixed(4)}`);
    check('on load it names 72 as nearest', read('n-out') === '72');
    check('on load it labels the answer a doubling time', read('t-lab') === 'time to double', read('t-lab'));

    // the collapse, driven through the instrument rather than asserted about it
    el('nom').value = '24'; el('freq').value = '12'; el('freq').selectedIndex = 3;
    fire('freq', 'change');
    check('driven to 24% compounded monthly, the instrument reports p = 2.0000%',
      read('p-out') === '2.0000%', read('p-out'));
    check('and D = 70.0056, the same numerator 2% compounded yearly gets',
      Math.abs(num('d-out') - Dg(0.02)) < 5e-5, `${read('d-out')} vs ${Dg(0.02).toFixed(4)}`);
    check('and the nearest whole number is 70', read('n-out') === '70', read('n-out'));

    // continuous compounding really is the p -> 0 limit, in the instrument
    el('freq').value = '0'; el('freq').selectedIndex = 6; fire('freq', 'change');
    check('set to compound continuously, the instrument reports p = 0.0000% and D = 69.3147',
      read('p-out') === '0.0000%' && Math.abs(num('d-out') - C) < 5e-5,
      `${read('p-out')} / ${read('d-out')}`);

    // the decline branch, and its label
    el('freq').value = '12'; el('freq').selectedIndex = 3; fire('freq', 'change');
    el('dir').value = '-1'; el('dir').selectedIndex = 1; fire('dir', 'change');
    check('switched to a shrinking quantity it reports D = 68.6192, this file\'s Dd(0.02)',
      Math.abs(num('d-out') - Dd(0.02)) < 5e-5, `${read('d-out')} vs ${Dd(0.02).toFixed(4)}`);
    check('and relabels the answer a halving time', read('t-lab') === 'time to halve', read('t-lab'));

    // the band strip, at the threshold the page's prose quotes
    el('k').value = '5'; fire('k', 'input');
    const st5 = read('strip-status');
    check('at a threshold of five the strip names the growing bands 70, 72, 75, 78, 80',
      st5.includes('Growing: 70, 72, 75, 78, 80'), st5.slice(0, 90));
    check('and the shrinking bands 70, 66, 64, 63, 60',
      st5.includes('Shrinking: 70, 66, 64, 63, 60'));
    check('and puts 72 between 4.9018% and 12.3145%, where this file puts it',
      st5.includes('72 owns growth from 4.9018% to 12.3145%') &&
      Math.abs(rateAt(71, +1) - 4.9018) < 5e-4 && Math.abs(rateAt(73.5, +1) - 12.3145) < 5e-4);
    check('and says 72 is absent from the shrinking row at that threshold',
      st5.includes('72 does not appear on the shrinking row'));
    el('k').value = '10'; fire('k', 'input');
    check('at a threshold of ten it discloses that 72 comes back on the shrinking row',
      read('strip-status').includes('On the shrinking row 72 appears only because'));

    // the whole-quotient table, as rendered
    const body = el('wq-body').innerHTML;
    check('the whole-quotient table renders 25 rows', (body.match(/<tr/g) || []).length === 25,
      String((body.match(/<tr/g) || []).length));
    const winners = {};
    for (const m of body.matchAll(/<tr[^>]*><td>(\d+)%<\/td><td>([\d.]+)<\/td><td>[^<]*<\/td><td class="win">(\d+)<\/td>/g)) {
      (winners[m[3]] ??= []).push(Number(m[1]));
      const R = Number(m[1]);
      if (Math.abs(Number(m[2]) - Dg(R / 100)) > 5e-5) winners.__bad = true;
    }
    check('every ideal numerator the table renders matches this file\'s Dg', !winners.__bad);
    check('the rendered table gives 72 the rates 4, 6, 8, 9, 12, 18, 24',
      (winners['72'] || []).join(',') === '4,6,8,9,12,18,24', (winners['72'] || []).join(','));
    check('and 70 the rates 1, 2, 5, 7, 10, 14',
      (winners['70'] || []).join(',') === '1,2,5,7,10,14', (winners['70'] || []).join(','));

    // the first cut's bench still works too
    el('rate').value = '8'; fire('rate', 'input');
    check('the original bench still recomputes 9.0065 yr at 8% annual',
      read('exact').startsWith('9.0065'), read('exact'));
  }
}

check('load-bearing closing tags present',html.trim().endsWith('</script></body></html>'));
// Last check, so the arithmetic below is deterministic: the page states how many
// assertions this file makes. It has to be right, including this line.
{
  const m=html.match(/<span id="ver-n">(\d+)<\/span>/);
  const claimed=m?Number(m[1]):null, actual=pass+fail+1;
  check('the assertion count the page claims for this verifier is the count it made',
    claimed===actual,`page says ${claimed}, this run made ${actual}`);
}
console.log(`\n${pass} passed, ${fail} failed`);
process.exit(fail?1:0);
