#!/usr/bin/env node
// verify-a-thousand-times-too-cold.mjs
//
// Independently recomputes every load-bearing number shown by
// public/strata/a-thousand-times-too-cold/index.html and asserts it.
// No dependencies beyond Node 22 built-ins. Exits 0 on success.
//
// Everything here is recomputed from (a) CODATA / IAU constants and
// (b) numbers copied out of the cited published tables. Published table
// entries are marked PUBLISHED in the source arrays below; they are inputs,
// never assertions about our own arithmetic.

'use strict';

let PASS = 0;
const FAILURES = [];

function ok(name, got, want, tol, unit) {
  const rel = Math.abs(want) > 0 ? Math.abs(got - want) / Math.abs(want) : Math.abs(got - want);
  if (!(rel <= tol)) {
    FAILURES.push(`${name}: got ${got}, want ${want} (rel err ${rel.toExponential(3)} > ${tol})`);
  } else {
    PASS++;
    console.log(`  ok  ${name.padEnd(52)} ${fmt(got)}${unit ? ' ' + unit : ''}`);
  }
}
function okTrue(name, cond, detail) {
  if (!cond) FAILURES.push(`${name}: ${detail}`);
  else { PASS++; console.log(`  ok  ${name.padEnd(52)} ${detail}`); }
}
function fmt(x) {
  if (x === 0) return '0';
  const a = Math.abs(x);
  return (a < 1e-3 || a >= 1e6) ? x.toExponential(5) : x.toPrecision(7);
}

// ---------------------------------------------------------------- constants
// CODATA 2022 recommended values.
const KB_EV = 8.617333262e-5;          // eV / K            (exact-ish, CODATA)
const E2_MEVFM = 1.439964548;          // e^2/(4 pi eps0), MeV fm
const ALPHA = 1 / 137.035999177;       // fine-structure constant
const U_MEV = 931.49410242;            // atomic mass unit, MeV
const MP_KG = 1.67262192369e-27;       // proton mass, kg
const AMU_G = 1.66053906892e-24;       // atomic mass unit, g
const MH_G = 1.007825031898 * AMU_G;   // 1H atom mass, g
const G_SI = 6.67430e-11;              // m^3 kg^-1 s^-2
const MEV_ERG = 1.602176634e-6;        // erg / MeV        (exact: e in J)
const MEV_J = 1.602176634e-13;
const BARN_CM2 = 1e-24;
const YEAR_S = 3.1556952e7;            // Julian year, s

// IAU 2015 Resolution B3 nominal solar conversion constants (exact by fiat)
// Prsa et al. 2016, AJ 152, 41.  PUBLISHED.
const GM_SUN = 1.3271244e20;           // m^3 s^-2
const R_SUN = 6.957e8;                 // m
const L_SUN = 3.828e26;                // W
const TSI = 1361;                      // W m^-2
const M_SUN = GM_SUN / G_SI;           // kg (derived: nominal GM / CODATA G)

// Atomic masses (AME2020).  PUBLISHED.
const M_1H_U = 1.00782503190;
const M_4HE_U = 4.00260325413;
const M_12C_U = 12.0;
const M_13C_U = 13.00335483521;
const M_16O_U = 15.99491461960;
const M_17O_U = 16.99913175650;

// ---------------------------------------------------------------- helpers
function erfc(x) {
  // Numerical Recipes erfcc: fractional error everywhere < 1.2e-7
  const z = Math.abs(x), t = 1 / (1 + 0.5 * z);
  const ans = t * Math.exp(-z * z - 1.26551223 + t * (1.00002368 + t * (0.37409196 +
    t * (0.09678418 + t * (-0.18628806 + t * (0.27886807 + t * (-1.13520398 +
    t * (1.48851587 + t * (-0.82215223 + t * 0.17087277)))))))));
  return x >= 0 ? ans : 2 - ans;
}
// two-sided normal sigma equivalent of a p-value
function sigmaOfP(p) {
  let lo = 0, hi = 40;
  for (let i = 0; i < 200; i++) {
    const m = 0.5 * (lo + hi);
    if (erfc(m / Math.SQRT2) > p) lo = m; else hi = m;
  }
  return 0.5 * (lo + hi);
}
// chi-square on 2 degrees of freedom: survival = exp(-x/2)
const chi2sf2 = (x) => Math.exp(-x / 2);

// ---------------------------------------------------------------- part 1
// Classical impossibility.
console.log('\n[1] The classical barrier');

const N_PROTONS = M_SUN / MP_KG;   // protons if the Sun were pure hydrogen
ok('M_sun from nominal GM / CODATA G', M_SUN, 1.98841e30, 5e-5, 'kg');
ok('N_p (upper bound, M_sun/m_p)', N_PROTONS, 1.1888e57, 5e-5);

function barrier(rfm, T) {
  const V_MeV = E2_MEVFM / rfm;
  const T_req = V_MeV * 1e6 / KB_EV;                    // K
  const x = V_MeV * 1e6 / (KB_EV * T);                  // V / kT
  // 3-D Maxwell-Boltzmann fraction above E=V, asymptotic form for x >> 1:
  //   f = (2/sqrt(pi)) sqrt(x) e^-x  (leading term of the upper incomplete gamma)
  const log10f = Math.log10(2 / Math.sqrt(Math.PI)) + 0.5 * Math.log10(x) - x / Math.LN10;
  return { V_MeV, T_req, ratio: T_req / T, x, log10f, log10N: log10f + Math.log10(N_PROTONS) };
}

const b1 = barrier(1.0, 15.54e6);
ok('Coulomb barrier at r = 1 fm', b1.V_MeV, 1.439964548, 1e-12, 'MeV');
ok('T classically required at 1 fm', b1.T_req, 1.67099e10, 1e-4, 'K');
ok('ratio T_required / 15.54 MK', b1.ratio, 1075.3, 1e-3);
ok('log10 MB tail fraction, 1 fm, 15.54 MK', b1.log10f, -465.43, 1e-4);
ok('log10 expected protons over the barrier', b1.log10N, -408.36, 1e-4);

// the same barrier measured against the mean kinetic energy of a 3-D Maxwell-
// Boltzmann particle, (3/2)kT = V, which is the other defensible convention.
const ratio32 = (2 * b1.V_MeV * 1e6 / (3 * KB_EV)) / 15.54e6;
ok('ratio on the (3/2)kT convention at 1 fm', ratio32, 716.86, 1e-3);
okTrue('the headline factor depends on the convention, and both are shown',
  Math.abs(b1.ratio / ratio32 - 1.5) < 1e-9,
  `kT convention ${b1.ratio.toFixed(0)}x, (3/2)kT convention ${ratio32.toFixed(0)}x`);

// the two contact radii quoted in the check panel's free-choices list
ok('times too cold at 1.4 fm (kT convention)', barrier(1.4, 15.54e6).ratio, 768.07, 1e-3);
ok('times too cold at 2.0 fm (kT convention)', barrier(2.0, 15.54e6).ratio, 537.65, 1e-3);

const b2 = barrier(2.0, 15.54e6);
ok('log10 MB tail fraction, 2 fm, 15.54 MK', b2.log10f, -232.08, 1e-4);
const b3 = barrier(3.0, 15.54e6);
okTrue('conclusion robust to contact radius 0.5-3 fm',
  barrier(3.0, 15.54e6).log10N < -90 && barrier(0.5, 15.54e6).log10N < -800,
  `log10 N = ${b3.log10N.toFixed(1)} at 3 fm, ${barrier(0.5, 15.54e6).log10N.toFixed(0)} at 0.5 fm`);

// how badly M_sun/m_p overcounts, at the bulk composition quoted in the check panel
{
  const X = 0.7381, Y = 0.2485, Z = 0.0134;
  const perU_free = X / 1.00782503190;                            // free protons per u
  const perU_all = perU_free + Y * (2 / 4.00260325413) + Z * 0.5; // + those bound in He and metals
  const naive = 1 / 1.007276466;                                  // M/m_p per u
  ok('M/m_p overcount vs free protons', naive / perU_free - 1, 0.35566, 1e-3);
  ok('M/m_p overcount vs all protons', naive / perU_all - 1, 0.15005, 1e-3);
  okTrue('either convention moves log10 by less than 0.15, against 10^-408',
    Math.log10(naive / perU_free) < 0.15 && Math.log10(naive / perU_all) > 0.05,
    `log10 shift ${Math.log10(naive / perU_all).toFixed(2)} to ${Math.log10(naive / perU_free).toFixed(2)}`);
}

// kT at the two standard-solar-model core temperatures used on the page
ok('kT at 15.54 MK (AGSS09 SSM Tc)', KB_EV * 15.54e6 / 1000, 1.33913, 1e-5, 'keV');
ok('kT at 15.68 MK (GS98 SSM Tc)', KB_EV * 15.68e6 / 1000, 1.35119, 1e-5, 'keV');

// ---------------------------------------------------------------- part 2
// Gamow peak, penetration, and the full rate integral.
console.log('\n[2] The Gamow window');

// PUBLISHED S-factors, Acharya et al. 2025 (Solar Fusion III) Table I.
// [S(0) MeV b, S'(0) b, S''(0) MeV^-1 b]
const REACTIONS = {
  pp:     { Z1: 1, Z2: 1, A1: 1.00727646, A2: 1.00727646, S: [4.09e-25, 4.5e-24, 9.9e-23] },
  he3he3: { Z1: 2, Z2: 2, A1: 3.0160293, A2: 3.0160293, S: [5.21, -4.90, 22.42] },
  c12p:   { Z1: 6, Z2: 1, A1: 12.0, A2: 1.00727646, S: [1.44e-3, 2.71e-3, 3.74e-2] },
  n14p:   { Z1: 7, Z2: 1, A1: 14.003074, A2: 1.00727646, S: [1.68e-3, 0, 0] }
};
const Sof = (r, E) => r.S[0] + r.S[1] * E + 0.5 * r.S[2] * E * E;

function gamow(r, T) {
  const muAmu = r.A1 * r.A2 / (r.A1 + r.A2);
  const muMeV = muAmu * U_MEV;
  const EG_MeV = 2 * muMeV * Math.pow(Math.PI * ALPHA * r.Z1 * r.Z2, 2);
  const b_keV = Math.sqrt(EG_MeV * 1000);            // keV^(1/2)
  const kT_keV = KB_EV * T / 1000;
  const E0 = Math.pow(b_keV * kT_keV / 2, 2 / 3);    // keV
  const dE = 4 * Math.sqrt(E0 * kT_keV / 3);         // keV
  const tau = 3 * E0 / kT_keV;
  return { muAmu, muMeV, EG_keV: EG_MeV * 1000, b_keV, kT_keV, E0, dE, tau, nu: (tau - 2) / 3 };
}

const gpp = gamow(REACTIONS.pp, 15.54e6);
ok('E_G(p+p)', gpp.EG_keV, 493.13, 1e-4, 'keV');
ok('b = sqrt(E_G) for p+p', gpp.b_keV, 22.2065, 1e-4, 'keV^1/2');
ok('E0(p+p, 15.54 MK)', gpp.E0, 6.0467, 1e-4, 'keV');
ok('Gamow width dE(p+p, 15.54 MK)', gpp.dE, 6.5716, 1e-4, 'keV');
ok('E0/kT for p+p', gpp.E0 / gpp.kT_keV, 4.5152, 1e-4);
ok('nu(p+p) = (3E0/kT - 2)/3', gpp.nu, 3.84869, 1e-5);

const pen = (g, E) => Math.exp(-g.b_keV / Math.sqrt(E));
ok('penetration at E = kT (p+p)', pen(gpp, gpp.kT_keV), 4.63478e-9, 1e-5);
ok('penetration at E = E0 (p+p)', pen(gpp, gpp.E0), 1.196778e-4, 1e-5);
ok('penetration ratio E0 vs kT', pen(gpp, gpp.E0) / pen(gpp, gpp.kT_keV), 25822.4, 1e-4);

const g14 = gamow(REACTIONS.n14p, 15.54e6);
const g12 = gamow(REACTIONS.c12p, 15.54e6);
ok('E0(14N+p, 15.54 MK)', g14.E0, 27.2397, 1e-4, 'keV');
ok('nu(14N+p, 15.54 MK)', g14.nu, 19.6746, 1e-4);
ok('E0(12C+p, 15.54 MK)', g12.E0, 24.4883, 1e-4, 'keV');
ok('nu(12C+p, 15.54 MK)', g12.nu, 17.6200, 1e-4);
okTrue('one formula gives both textbook exponents',
  Math.abs(gpp.nu - 4) < 0.3 && Math.abs(g14.nu - 20) < 0.4,
  `nu(pp) = ${gpp.nu.toFixed(2)} ~ 4, nu(14N+p) = ${g14.nu.toFixed(2)} ~ 20`);
// Bethe's 1967 lecture says T^4 and T^24.  The 4 is ours; the 24 is not, at the
// modern core temperature.  nu(14N+p) reaches 24 only much lower down.
{
  let lo = 4e6, hi = 15.54e6;
  for (let i = 0; i < 200; i++) {
    const m = 0.5 * (lo + hi);
    if (gamow(REACTIONS.n14p, m).nu > 24) lo = m; else hi = m;
  }
  ok('T at which nu(14N+p) reaches Bethe\'s 24', 0.5 * (lo + hi) / 1e6, 8.715, 1e-3, 'MK');
  okTrue("we do NOT reproduce Bethe's T^24 at the solar core, and the page says so",
    g14.nu < 21, `nu(14N+p) = ${g14.nu.toFixed(2)} at 15.54 MK, not 24`);
}

// Bethe's own rule of thumb, Nobel Lecture 1967: "the most important energy
// contributing to the reaction rate is about 20 kT. For T6 = 13, we have
// kT = 1.1 keV; so we are most interested in the cross section around 20 keV."
const g14b = gamow(REACTIONS.n14p, 13e6);
ok("kT at T6 = 13 (Bethe's 1.1 keV)", g14b.kT_keV, 1.1203, 1e-3, 'keV');
okTrue("Bethe's '20 kT / around 20 keV' rule reproduced",
  g14b.E0 / g14b.kT_keV > 18 && g14b.E0 / g14b.kT_keV < 24 && g14b.E0 > 18 && g14b.E0 < 28,
  `E0 = ${g14b.E0.toFixed(1)} keV = ${(g14b.E0 / g14b.kT_keV).toFixed(1)} kT`);

// full non-resonant rate integral
//   <sigma v> = sqrt(8/(pi mu)) (kT)^-3/2 Int S(E) exp(-E/kT - sqrt(E_G/E)) dE
// integrated in MeV, converted to cgs.  UeEV shifts the penetration energy
// (laboratory electron screening, SF III Sec. XII).
function rateIntegral(r, T, UeEV = 0, N = 40000) {
  const muAmu = r.A1 * r.A2 / (r.A1 + r.A2);
  const EG = 2 * muAmu * U_MEV * Math.pow(Math.PI * ALPHA * r.Z1 * r.Z2, 2); // MeV
  const kT = KB_EV * T * 1e-6;                                               // MeV
  const E0 = Math.pow(Math.sqrt(EG) * kT / 2, 2 / 3);
  const dE = 4 * Math.sqrt(E0 * kT / 3);
  const lo = Math.max(1e-10, E0 - 14 * dE), hi = E0 + 20 * dE;
  const h = (hi - lo) / N, dU = UeEV * 1e-6;
  let I = 0;
  for (let i = 0; i <= N; i++) {
    const E = lo + i * h;
    const v = Sof(r, E) * Math.exp(-E / kT - Math.sqrt(EG / (E + dU)));
    I += (i === 0 || i === N ? 0.5 : 1) * v;
  }
  return { I: I * h, EG, kT, E0, dE };
}
function sigmaV(r, T, UeEV = 0) {
  const { I, kT } = rateIntegral(r, T, UeEV);
  const muG = r.A1 * r.A2 / (r.A1 + r.A2) * AMU_G;
  const Icgs = I * MEV_ERG * BARN_CM2 * MEV_ERG;       // erg^2 cm^2
  return Math.sqrt(8 / (Math.PI * muG)) * Math.pow(kT * MEV_ERG, -1.5) * Icgs;
}

const svpp = sigmaV(REACTIONS.pp, 15.68e6);
ok('<sigma v>_pp at 15.68 MK', svpp, 1.62867e-43, 2e-4, 'cm^3/s');
ok('<sigma v>_pp at 15.54 MK', sigmaV(REACTIONS.pp, 15.54e6), 1.57249e-43, 2e-4, 'cm^3/s');

// cross section at the Gamow peak
const sigE0 = Sof(REACTIONS.pp, gpp.E0 * 1e-3) / (gpp.E0 * 1e-3) * pen(gpp, gpp.E0) * BARN_CM2;
ok('sigma_pp at the Gamow peak (15.54 MK)', sigE0, 8.6690e-51, 1e-3, 'cm^2');

// numerical temperature exponent, d ln<sigma v> / d ln T, vs the closed form
const T0 = 15.54e6, dlt = 0.002;
const nuNum = (Math.log(sigmaV(REACTIONS.pp, T0 * (1 + dlt))) -
               Math.log(sigmaV(REACTIONS.pp, T0 * (1 - dlt)))) / (2 * dlt);
okTrue('numerical d ln<sv>/d ln T agrees with (3E0/kT-2)/3 for p+p',
  Math.abs(nuNum - gpp.nu) < 0.12,
  `numerical ${nuNum.toFixed(3)} vs closed form ${gpp.nu.toFixed(3)}`);
const g14T = gamow(REACTIONS.n14p, 15.54e6);
const nuNum14 = (Math.log(sigmaV(REACTIONS.n14p, T0 * (1 + dlt))) -
                 Math.log(sigmaV(REACTIONS.n14p, T0 * (1 - dlt)))) / (2 * dlt);
okTrue('numerical exponent for 14N+p agrees with closed form',
  Math.abs(nuNum14 - g14T.nu) < 0.35,
  `numerical ${nuNum14.toFixed(2)} vs closed form ${g14T.nu.toFixed(2)}`);

// the Gaussian (saddle-point) approximation is NOT exact: show its error
function gaussApproxError(r, T) {
  const { I, EG, kT, E0, dE } = rateIntegral(r, T);
  const Ig = Sof(r, E0) * Math.exp(-3 * E0 / kT) * (dE / 2) * Math.sqrt(Math.PI);
  void EG;
  return (Ig - I) / I;
}
const errPP = gaussApproxError(REACTIONS.pp, 15.54e6);
const err14 = gaussApproxError(REACTIONS.n14p, 15.54e6);
okTrue('Gaussian approximation is wrong at the several-percent level (p+p)',
  Math.abs(errPP) > 0.02 && Math.abs(errPP) < 0.30,
  `relative error ${(errPP * 100).toFixed(2)} %`);
okTrue('Gaussian approximation error is smaller for 14N+p',
  Math.abs(err14) < Math.abs(errPP),
  `14N+p ${(err14 * 100).toFixed(2)} % vs p+p ${(errPP * 100).toFixed(2)} %`);

// mean life of a proton against p+p fusion, at declared core conditions
function protonLife(T, rho, X) {
  const np = rho * X / MH_G;
  return 1 / (np * sigmaV(REACTIONS.pp, T));   // s; each proton's own fusion rate
}
const tauGyr = protonLife(15.68e6, 152, 0.342) / (1e9 * YEAR_S);
ok('proton mean life, T=15.68 MK rho=152 X=0.342 (bare)', tauGyr, 6.264, 3e-3, 'Gyr');
okTrue('proton mean life spans several Gyr over plausible core conditions',
  protonLife(15.0e6, 140, 0.34) / (1e9 * YEAR_S) > 6 &&
  protonLife(16.0e6, 160, 0.36) / (1e9 * YEAR_S) < 6,
  `${(protonLife(15.0e6,140,0.34)/(1e9*YEAR_S)).toFixed(1)} Gyr to ` +
  `${(protonLife(16.0e6,160,0.36)/(1e9*YEAR_S)).toFixed(1)} Gyr across the quoted box`);

// Salpeter weak screening, computed from the Debye-Huckel length
function salpeter(Z1, Z2, T, rho, X, Y) {
  const kT_eV = KB_EV * T;
  // sum of Z(Z+1)/A over H, He and a representative metal (Z = 8, A = 16),
  // matching the page's own zeta^2: 8*9/16 = 4.5
  const Zm = Math.max(0, 1 - X - Y);
  const zeta2 = X * 2 + Y * 1.5 + Zm * (8 * 9 / 16);
  const nB = rho / AMU_G;                       // baryon-ish number density, cm^-3
  const e2_eVcm = E2_MEVFM * 1e6 * 1e-13;       // eV cm
  const invLam2 = 4 * Math.PI * e2_eVcm * nB * zeta2 / kT_eV;
  const lamD = 1 / Math.sqrt(invLam2);
  const U = Z1 * Z2 * e2_eVcm / lamD;
  return { f: Math.exp(U / kT_eV), U, lamD, zeta2 };
}
const sc = salpeter(1, 1, 15.54e6, 152, 0.342, 0.638);
okTrue('solar plasma (Salpeter) screening for p+p is a few percent',
  sc.f > 1.03 && sc.f < 1.09, `f = ${sc.f.toFixed(4)} (U = ${sc.U.toFixed(1)} eV)`);
// pin it at the precision the page prints, so fourth-decimal drift fails loudly
ok('Salpeter screening factor for p+p, as printed', sc.f, 1.0510143, 1e-6);
ok('Debye length in the core, 15.54 MK rho=152 X=0.342', sc.lamD, 2.161152e-9, 1e-6, 'cm');
ok('solar screening energy U for p+p, as printed', sc.U, 66.62949, 1e-6, 'eV');

// laboratory screening: the enhancement SF III describes for 3He+3He
function labEnhance(r, E_MeV, UeEV) {
  const muAmu = r.A1 * r.A2 / (r.A1 + r.A2);
  const EG = 2 * muAmu * U_MEV * Math.pow(Math.PI * ALPHA * r.Z1 * r.Z2, 2);
  return Math.exp(-Math.sqrt(EG / (E_MeV + UeEV * 1e-6)) + Math.sqrt(EG / E_MeV));
}
const enh = labEnhance(REACTIONS.he3he3, 0.0165, 305);
okTrue('Ue = 305 eV gives a ~40 % lab enhancement near the lowest 3He+3He data',
  enh > 1.30 && enh < 1.55, `enhancement ${((enh - 1) * 100).toFixed(1)} % at E = 16.5 keV`);

// ---------------------------------------------------------------- part 3
console.log('\n[3] The weak bottleneck');
const S11 = REACTIONS.pp.S[0], S12 = 2.03e-7;     // PUBLISHED, SF III Table I
ok('S12(0)/S11(0)', S12 / S11, 4.9633e17, 1e-4);
okTrue('the next step is ~5 x 10^17 more probable at the same energy',
  S12 / S11 > 4e17 && S12 / S11 < 6e17, `${(S12 / S11).toExponential(3)}`);

// ---------------------------------------------------------------- part 4
console.log('\n[4] The luminosity ledger');
const Q_MeV = (4 * M_1H_U - M_4HE_U) * U_MEV;
ok('Q(4 1H -> 4He) from AME atomic masses', Q_MeV, 26.730968, 1e-7, 'MeV');

// PUBLISHED average neutrino energies, Bahcall 2002 (PRC 65, 025801) Table I.
const EBAR = { pp: 0.2668, pep: 1.445, hep: 9.628, be7: 0.814, b8: 6.735, n13: 0.706, o15: 0.996, f17: 0.998 };
// PUBLISHED alpha column of the same table (printed in units of 10 MeV), plus
// alpha(17F) = 2.363 MeV from the text: Table I carries no 17F row.
const ABAH = { pp: 13.0987, pep: 11.9193, hep: 3.7370, be7: 12.6008, b8: 6.6305,
               n13: 3.4577, o15: 21.5706, f17: 2.3630 };
// OUR alpha, from the AME2020 masses, following Bahcall's own definitions.
// pp chain: exactly two neutrinos per 4He, so Q/2 - <Ev> is exact.
// CNO: Bahcall Eqs. (10) and (11) take the mass difference across the arc of
// the cycle that ends in that neutrino; halving Q there is simply wrong.
function alpha(k) {
  if (k === 'n13') return (M_12C_U + M_1H_U - M_13C_U) * U_MEV - EBAR.n13;
  if (k === 'o15') return (3 * M_1H_U + M_13C_U - M_4HE_U - M_12C_U) * U_MEV - EBAR.o15;
  if (k === 'f17') return (M_16O_U + M_1H_U - M_17O_U) * U_MEV - EBAR.f17;
  return Q_MeV / 2 - EBAR[k];
}
// Seven of the eight must land on Bahcall's published coefficient.  7Be does
// not, and the verifier pins the disagreement rather than tolerating it.
for (const k of ['pp', 'pep', 'hep', 'b8', 'n13', 'o15', 'f17']) {
  ok(`alpha(${k}) reproduces Bahcall's published ${ABAH[k]}`, alpha(k), ABAH[k], 1.3e-4, 'MeV');
}
ok('alpha(7Be), ours (Bahcall publishes 12.6008)', alpha('be7'), 12.5515, 1e-5, 'MeV');
okTrue('the 7Be gap is the 7Li excited-state gamma, 0.478 MeV in 10.3 % of captures',
  Math.abs((ABAH.be7 - alpha('be7')) - 0.103 * 0.478) < 5e-4,
  `gap ${(ABAH.be7 - alpha('be7')).toFixed(4)} MeV vs 0.103 x 0.478 = ${(0.103 * 0.478).toFixed(4)} MeV`);
okTrue('halving Q is wrong for the CNO sources, by a lot',
  Math.abs((Q_MeV / 2 - EBAR.n13) / alpha('n13') - 3.66) < 0.02 &&
  Math.abs((Q_MeV / 2 - EBAR.o15) / alpha('o15') - 0.5735) < 0.01,
  `Q/2-<Ev> would give 13N ${((Q_MeV / 2 - EBAR.n13) / alpha('n13')).toFixed(2)}x and ` +
  `15O ${((Q_MeV / 2 - EBAR.o15) / alpha('o15')).toFixed(3)}x the correct coefficient`);

// PUBLISHED SSM fluxes, Acharya et al. 2025 Table II (from Herrera & Serenelli 2023).
const FLUX = {
  GS98:  { pp: 5.96e10, pep: 1.43e8, hep: 7.95e3, be7: 4.85e9, b8: 5.03e6, n13: 2.80e8, o15: 2.07e8, f17: 5.35e6 },
  AAG21: { pp: 6.00e10, pep: 1.45e8, hep: 8.16e3, be7: 4.52e9, b8: 4.31e6, n13: 2.22e8, o15: 1.58e8, f17: 3.40e6 },
  MB22p: { pp: 5.95e10, pep: 1.42e8, hep: 7.93e3, be7: 4.88e9, b8: 5.07e6, n13: 3.10e8, o15: 2.30e8, f17: 4.70e6 }
};
function ledger(f) {
  let s = 0;
  for (const k of Object.keys(EBAR)) s += alpha(k) * f[k];
  return s * MEV_J * 1e4;                        // MeV cm^-2 s^-1 -> W m^-2
}
const wGS98 = ledger(FLUX.GS98);
ok('luminosity ledger, SF III GS98 fluxes', wGS98, 1359.832, 1e-6, 'W/m^2');
ok('ledger / IAU nominal TSI', wGS98 / TSI, 0.9991419, 1e-6);
// the same ledger evaluated on Bahcall's published alpha column, so the 7Be
// disagreement is priced rather than buried
const wBah = Object.keys(EBAR).reduce((s, k) => s + ABAH[k] * FLUX.GS98[k], 0) * MEV_J * 1e4;
ok('ledger on Bahcall published alphas, GS98 fluxes', wBah, 1360.216, 1e-6, 'W/m^2');
okTrue('our alpha set and Bahcall published alphas agree on the ledger to <0.1 %',
  Math.abs(wBah / wGS98 - 1) < 1e-3,
  `${wGS98.toFixed(2)} vs ${wBah.toFixed(2)} W/m^2, ${(100 * (wBah / wGS98 - 1)).toFixed(3)} %`);
okTrue('all three SF III compositions close on the TSI to better than 1 %',
  [FLUX.GS98, FLUX.AAG21, FLUX.MB22p].every(f => Math.abs(ledger(f) / TSI - 1) < 0.01),
  [FLUX.GS98, FLUX.AAG21, FLUX.MB22p].map(f => ledger(f).toFixed(1)).join(' / ') + ' W/m^2');

// the high-Z / low-Z 8B split the page compares the S11 error against
ok('8B high-Z vs low-Z split (GS98 vs AAG21)', FLUX.GS98.b8 / FLUX.AAG21.b8 - 1, 0.16705, 1e-4);

// ---------------------------------------------------------------- part 5
console.log('\n[5] Flux versus central temperature, across five solar models');
// PUBLISHED: Salmon et al. 2021, A&A 651, A106, Table 2.
const SALMON = [
  { name: 'AGSS09',    Tc: 15.54, pp: 5.995e10, be7: 4.710e9, b8: 5.015e6, n13: 2.273e8, o15: 1.695e8, f17: 3.619e6 },
  { name: 'AGSS09+Ne', Tc: 15.56, pp: 5.991e10, be7: 4.755e9, b8: 5.099e6, n13: 2.264e8, o15: 1.695e8, f17: 3.622e6 },
  { name: 'Caffau11',  Tc: 15.62, pp: 5.965e10, be7: 4.915e9, b8: 5.507e6, n13: 2.801e8, o15: 2.123e8, f17: 4.648e6 },
  { name: 'GS98',      Tc: 15.68, pp: 5.942e10, be7: 5.111e9, b8: 5.918e6, n13: 3.081e8, o15: 2.379e8, f17: 5.765e6 },
  { name: 'GN93',      Tc: 15.69, pp: 5.937e10, be7: 5.106e9, b8: 5.951e6, n13: 3.340e8, o15: 2.590e8, f17: 6.365e6 }
];
function slope(rows, key) {
  const n = rows.length;
  let sx = 0, sy = 0, sxx = 0, sxy = 0;
  for (const r of rows) {
    const x = Math.log(r.Tc), y = Math.log(r[key]);
    sx += x; sy += y; sxx += x * x; sxy += x * y;
  }
  return (n * sxy - sx * sy) / (n * sxx - sx * sx);
}
const M = {}; for (const k of ['pp', 'be7', 'b8', 'n13', 'o15', 'f17']) M[k] = slope(SALMON, k);
ok('fitted m(pp) across the five Salmon models', M.pp, -1.0338, 2e-3);
ok('fitted m(7Be)', M.be7, 8.7999, 2e-3);
ok('fitted m(8B)', M.b8, 18.4303, 2e-3);
ok('fitted m(13N)', M.n13, 39.8992, 2e-3);
ok('fitted m(15O)', M.o15, 43.9438, 2e-3);
ok('fitted m(17F)', M.f17, 59.1189, 2e-3);

// PUBLISHED: Bahcall & Ulmer 1996, PRD 53, 4202, Table II (Monte Carlo column).
const BU = { pp: [-1.1, 0.1], be7: [10, 2], b8: [24, 5], n13: [24.4, 0.2], o15: [27.1, 0.1], f17: [27.8, 0.1] };
const inside = (k) => Math.abs(M[k] - BU[k][0]) <= BU[k][1];
okTrue('pp and 7Be exponents land inside Bahcall & Ulmer 1996 Table II',
  inside('pp') && inside('be7'),
  `pp ${M.pp.toFixed(2)} in -1.1+-0.1, 7Be ${M.be7.toFixed(2)} in 10+-2`);
okTrue('8B sits just OUTSIDE Bahcall & Ulmer, by about a tenth of their error bar',
  !inside('b8') && (BU.b8[0] - BU.b8[1]) - M.b8 > 0 && (BU.b8[0] - BU.b8[1]) - M.b8 < 1.0,
  `8B ${M.b8.toFixed(2)} against 24+-5, i.e. ${((BU.b8[0]-BU.b8[1])-M.b8).toFixed(2)} below the lower edge`);
okTrue('CNO exponents land far OUTSIDE Bahcall & Ulmer Table II',
  !inside('n13') && !inside('o15') && !inside('f17'),
  `13N ${M.n13.toFixed(1)} vs 24.4+-0.2, 15O ${M.o15.toFixed(1)} vs 27.1+-0.1, 17F ${M.f17.toFixed(1)} vs 27.8+-0.1`);

// ---------------------------------------------------------------- part 6
console.log('\n[6] The composition courtroom (B16 Table 4)');
// PUBLISHED: Vinyoles et al. 2017 (B16), ApJ 835, 202, Table 4 and Sec. 3.1.
const B16 = {
  GS98:      { Ys: 0.2426, sYs: 0.0059, Rcz: 0.7116, sRcz: 0.0048, rho: -0.35, chi2: 0.91 },
  AGSS09met: { Ys: 0.2317, sYs: 0.0059, Rcz: 0.7223, sRcz: 0.0053, rho: -0.41, chi2: 6.45 }
};
const SEIS = { Ys: 0.2485, sYs: 0.0035, Rcz: 0.713, sRcz: 0.001 };

function chi2corr(m) {
  const c11 = m.sYs * m.sYs + SEIS.sYs * SEIS.sYs;
  const c22 = m.sRcz * m.sRcz + SEIS.sRcz * SEIS.sRcz;
  const c12 = m.rho * m.sYs * m.sRcz;             // model correlation only
  const det = c11 * c22 - c12 * c12;
  const d1 = m.Ys - SEIS.Ys, d2 = m.Rcz - SEIS.Rcz;
  return (c22 * d1 * d1 - 2 * c12 * d1 * d2 + c11 * d2 * d2) / det;
}
const x1 = chi2corr(B16.GS98), x2 = chi2corr(B16.AGSS09met);
ok('our chi2 recomputation, B16-GS98', x1, 1.05783, 1e-4);
ok('our chi2 recomputation, B16-AGSS09met', x2, 6.86895, 1e-4);
okTrue('our recomputation does NOT reproduce B16 exactly, and we say so',
  Math.abs(x1 - 0.91) > 0.05 && Math.abs(x2 - 6.45) > 0.05,
  `ours ${x1.toFixed(2)} / ${x2.toFixed(2)} vs B16's published 0.91 / 6.45`);
// B16's OWN chi2 values do convert exactly to their quoted sigma equivalents
ok("sigma equivalent of B16's chi2 = 0.91", sigmaOfP(chi2sf2(0.91)), 0.4757, 3e-3, 'sigma');
ok("sigma equivalent of B16's chi2 = 6.45", sigmaOfP(chi2sf2(6.45)), 2.0576, 3e-3, 'sigma');
okTrue("recovered B16's quoted '0.5 sigma and 2.1 sigma'",
  Math.abs(sigmaOfP(chi2sf2(0.91)) - 0.5) < 0.05 && Math.abs(sigmaOfP(chi2sf2(6.45)) - 2.1) < 0.05,
  `${sigmaOfP(chi2sf2(0.91)).toFixed(2)} sigma and ${sigmaOfP(chi2sf2(6.45)).toFixed(2)} sigma`);
// the sting: the winning model still misses the seismic surface helium
const missSig = (SEIS.Ys - B16.GS98.Ys) / Math.sqrt(B16.GS98.sYs ** 2 + SEIS.sYs ** 2);
ok('high-Z model miss on seismic Y_S, in sigma', missSig, 0.86005, 1e-4, 'sigma');
ok('high-Z model miss on seismic Y_S, absolute', SEIS.Ys - B16.GS98.Ys, 0.0059, 1e-6);

// ---------------------------------------------------------------- part 7
console.log('\n[7] The S11 propagation chain');
// eps ~ S11 . T^nu at fixed structure; hold eps fixed => dlnTc = -dlnS11/nu.
// Then Phi(8B) ~ Tc^m with m = 24 +- 5 (Bahcall & Ulmer 1996 Table II).
function propagate(fracShift, nu, m) {
  const dlnTc = -Math.log1p(fracShift) / nu;   // fracShift is dS11/S11
  return { dlnTc, dTc: dlnTc * 15.54e6, dPhi8B: Math.expm1(m * dlnTc) };
}
const p0 = propagate(0.015, gpp.nu, 24);
ok('dlnTc for +1.5 % in S11 at nu = 3.849', p0.dlnTc, -0.00386849, 1e-5);
ok('dTc for +1.5 % in S11', p0.dTc, -60116.3, 1e-4, 'K');
ok('dPhi(8B) for +1.5 % in S11 at m = 24', p0.dPhi8B, -0.0886638, 1e-5);
const pLo = propagate(0.015, gpp.nu, 19), pHi = propagate(0.015, gpp.nu, 29);
ok('dPhi(8B) at m = 19', pLo.dPhi8B, -0.0708651, 1e-5);
ok('dPhi(8B) at m = 29', pHi.dPhi8B, -0.1061225, 1e-5);
// the sensitivity this chain implies, against the ceiling B16's error budget puts on it.
// B16 (Vinyoles et al. 2017) Table 7 lists the dominant theory errors on Phi(8B) as
// kappa 7.3 %, S17 4.8 %, Diff 4.0 %, S34 3.9 %, with S11 absent, while Sec. 2 adopts a
// 1 % uncertainty on the p+p rate.  So |dlnPhi(8B)/dlnS11| must be under about 3.9.
const B16_CAP = 3.9;
ok('sensitivity |dlnPhi(8B)/dlnS11| implied by the chain', 24 / gpp.nu, 6.23590, 1e-5);
okTrue('the chain is steeper than B16 Table 7 permits, and the page says so',
  24 / gpp.nu > B16_CAP,
  `chain ${(24 / gpp.nu).toFixed(2)} vs a ceiling of ~${B16_CAP} from B16's error budget`);
ok('dPhi(8B) for +1.5 % in S11 at the B16 ceiling',
  Math.expm1(-B16_CAP * Math.log1p(0.015)), -0.05641194, 1e-6);
okTrue('the S11 theory error moves 8B by about half the metallicity signal',
  Math.abs(p0.dPhi8B) / (FLUX.GS98.b8 / FLUX.AAG21.b8 - 1) > 0.4 &&
  Math.abs(p0.dPhi8B) / (FLUX.GS98.b8 / FLUX.AAG21.b8 - 1) < 0.7,
  `${(Math.abs(p0.dPhi8B) * 100).toFixed(1)} % against a ${((FLUX.GS98.b8 / FLUX.AAG21.b8 - 1) * 100).toFixed(1)} % high-Z/low-Z split`);
// SF II -> SF III: the uncertainty got worse, from the two published values
okTrue('the published S11(0) uncertainty widened between 2011 and 2025',
  0.015 > 0.009, 'SF II 4.01(1+-0.009); SF III 4.09(1+-0.015)');

// ---------------------------------------------------------------- part 8
console.log('\n[8] Before nuclear physics: the Kelvin-Helmholtz clock');
function kh(coef) { return coef * G_SI * M_SUN * M_SUN / (R_SUN * L_SUN) / YEAR_S; }
ok('Kelvin-Helmholtz time, coefficient 1', kh(1), 3.1400e7, 1e-3, 'yr');
ok('Kelvin-Helmholtz time, n = 3 polytrope (3/4)', kh(0.75), 2.3550e7, 1e-3, 'yr');
okTrue('every plausible coefficient is short against the 4.567 Gyr CAI age',
  kh(1.5) < 4.567e9 / 50,
  `even 1.5 GM^2/RL is ${kh(1.5).toExponential(2)} yr, ${(4.567e9 / kh(1.5)).toFixed(0)}x too short`);

// ---------------------------------------------------------------- part 9
console.log('\n[9] pp versus CNO: where the crossing sits');
// One-zone comparison of the two energy-generation rates. DECLARED CHOICES:
// full CNO equilibrium (all catalysts as 14N), CNO catalyst mass fraction
// fCNO * Z, bare (unscreened) rates, energy per pp reaction = alpha(pp),
// energy per CNO cycle = Q - <E(13N)> - <E(15O)>.
const E_PER_CNO = Q_MeV - EBAR.n13 - EBAR.o15;
ok('usable energy per CNO cycle', E_PER_CNO, 25.0291, 1e-4, 'MeV');
function epsilons(T, X, Z, fCNO, rho) {
  const np = rho * X / MH_G;
  const nN = rho * fCNO * Z / (14.003074 * AMU_G);
  const e_pp = 0.5 * np * np * sigmaV(REACTIONS.pp, T) * alpha('pp') * MEV_ERG / rho;
  const e_cno = np * nN * sigmaV(REACTIONS.n14p, T) * E_PER_CNO * MEV_ERG / rho;
  return { e_pp, e_cno };
}
function crossing(X, Z, fCNO) {
  let lo = 5e6, hi = 60e6;
  for (let i = 0; i < 60; i++) {
    const m = 0.5 * (lo + hi), e = epsilons(m, X, Z, fCNO, 100);
    if (e.e_cno < e.e_pp) lo = m; else hi = m;
  }
  return 0.5 * (lo + hi) / 1e6;
}
const xSolar = crossing(0.342, 0.0162, 0.7);
ok('pp/CNO crossing for solar-core composition', xSolar, 17.7782, 1e-4, 'MK');
okTrue('the Sun sits on the pp side of its own crossing',
  15.54 < xSolar && 15.68 < xSolar,
  `Tc = 15.54-15.69 MK, crossing at ${xSolar.toFixed(2)} MK`);
const eSolar = epsilons(15.54e6, 0.342, 0.0162, 0.7, 152);
okTrue('CNO is a small minority of the central energy release',
  eSolar.e_cno / (eSolar.e_pp + eSolar.e_cno) < 0.2,
  `${(100 * eSolar.e_cno / (eSolar.e_pp + eSolar.e_cno)).toFixed(1)} % at the very centre (one-zone, bare)`);
const xBethe = crossing(0.5, 0.02, 0.7);
okTrue("we do NOT reproduce Bethe's 1967 crossing of T6 = 13, and the page says so",
  xBethe > 15,
  `our crossing at Bethe's composition is ${xBethe.toFixed(2)} MK, not 13 MK`);

// ---------------------------------------------------------------- done
console.log('');
if (FAILURES.length) {
  console.error(`FAILED ${FAILURES.length} assertion(s):`);
  for (const f of FAILURES) console.error('  x  ' + f);
  process.exit(1);
}
console.log(`All ${PASS} assertions passed.`);
process.exit(0);
