"""Step 11. Build the machine-readable claim ledger, the verification report, the research timeline and the research
report from the JSON/CSV results (so that every number in the prose is the number that was computed).

Outputs: claim_ledger.json, verification_report.md, research_timeline.json, research_report.md, results/all_checks.csv
"""
import os, json
from common import ROOT, RES, LOG, Tee, event, load_json, read_csv, save_csv, now


def J(n):
    return load_json(n)


def main():
    S = J("slope_constants.json"); FD = J("fd_summary.json"); T2 = J("table2_reanalysis.json"); FA = J("functional_analysis.json")
    H = J("hp_hagedorn.json"); Q = J("hp_quartic.json"); L = J("hp_landau.json"); V = J("validation_summary.json"); X = J("extraction_summary.json")
    CAP = J("figure_captions.json")["captions"]
    q = Q["quartic"]; sa, sb = Q["series"]["a"], Q["series"]["b"]
    tr = {r["lambda"]: r for r in read_csv("hp_temperatures.csv")}
    fb = read_csv("functional_bounds.csv")
    npts = len(fb); cs = sorted(set(int(r["c"]) for r in fb)); pmax = {c: max(int(r["P"]) for r in fb if int(r["c"]) == c) for c in cs}

    # ------------------------------------------------------------------ all checks in one table
    allc = []
    for nm, obj in (("s02_slope_endpoint", S), ("s05_table2_reanalysis", T2), ("s06_hp_hagedorn", H), ("s07_hp_series_quartic", Q), ("s08_hp_landau", L), ("s09_functional_analysis", FA)):
        for c in obj["checks"]:
            allc.append([nm, c["label"], c["computed"], c["paper"], c["absdiff"], c["tol"], c["pass"], c["source"]])
    save_csv("all_checks.csv", ["script", "check", "computed", "reference", "absdiff", "tolerance", "pass", "reference_source"], allc)
    nchk = len(allc); npass = sum(bool(c[6]) for c in allc)

    # ------------------------------------------------------------------ claim ledger
    E = FA
    led = []

    def add(id_, paper, loc, claim, status, action, verdict, result, evidence, scope="", second=""):
        led.append(dict(id=id_, paper=paper, location=loc, claim=claim, paper_status=status, what_was_done=action, second_method=second, verdict=verdict, quantitative_result=result,
                        evidence=evidence, scope_limit=scope))
    B, HP = "The Spinless Modular Bootstrap at Large Central Charge (2611.00174v1)", "The Hawking–Page Transition at Weak Coupling (2611.00175v1)"
    add("B01", B, "Thm 1; eq. (4-slope)", "x1* = arcsinh(1)/π = 0.2805499, ξ1* = 0.0262361, Λ_V = 12π²/(π²+4 arcsinh²1) = 9.1266340", "definition / closed form",
        "50-digit evaluation; bisection root of sinh(πx)=1", "independently reproduced", f"x* = {S['x_star'][:22]}, Λ_V = {S['Lambda_V'][:18]}", ["results/slope_constants.json", "logs/s02_slope_endpoint.log"],
        "numerical value of the constants only", "Newton iteration in Python decimal with own sinh series (validate_all V1): agreement to 4e-41")
    add("B02", B, "§6.6 (orientation)", "The slit position at which the majorant U_s is tangent to the Cardy line is s = x1*; γ_tip = −0.16, −0.02, ≈0, +0.02, +0.16 at s = 0.24, 0.275, x1*, 0.285, 0.32", "orientation (not used in proofs)",
        "Poisson integral for U_s derived here for general s; tangency condition πs = J(s) solved by bisection", "independently reproduced",
        f"tangency root − arcsinh(1)/π = {S['s_tangency_minus_xstar']:.1e}; γ_tip = −0.1609, −0.0221, 0, +0.0177, +0.1566", ["results/gamma_tip.csv", "figures/fig04_tangency.png"],
        "floating-point (50 digits), not interval arithmetic", f"finite-difference Laplace solve: sign change of the tip coefficient at s = {FD['s_root_fd']:.4f}")
    add("B03", B, "Lemma 6.3", "b(z) = (1/2π) log((z−1)/(z(z+1))) maps the upper half-plane onto the slit strip; b(i)=0, b(1∓√2)=±x1*, b(√2−1)=i/2", "proved",
        "special values, critical points b′(z)=0 at z = 1±√2, images of the four boundary intervals", "consistent (proof sub-steps verified numerically)", "all values to 1e-30; boundary images land on edges/slits",
        ["results/slope_constants.json"], "conformality/bijectivity onto D not proved here")
    add("B04", B, "Lemma 6.5; eq. (6-U), (6-identity), (6-axes)", "Extremal potential in closed form; U0 = −0.388748; U = 0 on the edges; key identity ∫asin(sinh)+∫asinh(sin) = ½ arcsinh 1", "proved",
        "quadrature of both integrals; path independence; boundary values of p(b); spectral-curve identity", "independently reproduced (numerically)",
        f"U0 = −0.388747872; identity holds to 1e-30; U(i/2) = 0 to 1e-30", ["results/slope_constants.json", "results/potential_axes.csv"],
        "uniqueness argument (barrier) not re-derived", f"finite differences: U(0) Richardson {FD['U0_richardson']:.6f}, order {FD['orders'][-1]:.2f}; Gauss–Legendre float64 (V2); Poisson integral")
    add("B05", B, "Lemma 6.7; eq. (6-kappa-bounds)", "κ(δ) = 0.0026, 0.029, 0.083, 0.23 at δ = 0.01, 0.05, 0.1, 0.2; κ ≃ 2.650 δ^{3/2}; κ ≥ 2.228 δ^{3/2} on (0, x1*]", "proved",
        "quadrature; inequality tested on a 400-point grid", "consistent (numerical check of a proved inequality)", f"min κ/δ^1.5 on the grid = {S['kappa_ratio_min']:.4f} ≥ 2.2281", ["results/slope_constants.json", "figures/fig03_extremal_potential.png"],
        "grid check, not a proof")
    add("B06", B, "Thm 3, Prop 6.4, App. A–B", "Concentration: every g in the class has exponentially little Cardy-weighted mass below ξ1* c′", "proved",
        "not re-proved; only its inputs (U, κ) and the half-mass identity on explicit functionals were checked", "not verified here (proof read, inputs checked)", "—", ["verification_report.md"],
        "Poisson–Jensen, entropy and Bessel lemmas of App. A/B were not checked; constants C_δ, c_opt are not computed in the paper either")
    add("B07", B, "Thm 4; eq. (6-rate)", "t1 ≥ ξ1* c′ − 0.44 c′^{1/3} log^{2/3} c′ for c ≥ c_opt; (2/3)x1* λ0^{2/3} = 0.4393; bound is below the trivial floor for c′ ≲ 414", "proved (c_opt not computed)",
        "arithmetic of the rate constants", "arithmetic reproduced", f"0.43933; κ0λ0 = 8.021 > 8; δ < x1* for c′ > {S['delta_threshold_cprime']:.2f}; floor crossing at c′ = {S['rate_floor_cprime']:.1f}", ["results/slope_constants.json"],
        "the theorem itself rests on B06")
    add("B08", B, "Thm 5, Cor. 6, App. G", "An explicit functional is feasible at ξ1* c′ + 0.483 c′^{1/3} + O(1) for c ≥ c_att (computer-assisted)", "proved, computer-assisted",
        "not attempted", "not verified here", "—", ["verification_report.md"], "requires the comb construction, steepest descent with uniform remainders and the interval-arithmetic certificates of App. G; no certified upper bound was produced in this session")
    add("B09", B, "§2.2; eq. (2-hellerman)", "Order P=2: t1 = a + 2/π + 2/(e^{2π}−1) − ε_c with 0 < ε_c = O(1/c); Δ1 < c/6 + 0.4737", "proved (Hellerman)",
        "P=2 extremal problem solved by Newton and, independently, from the roots of the explicit cubic", "independently reproduced", "constant 0.473695; ε_c·c → 0.0674 (c = 4…1024), ε_c > 0", ["logs/validate_all.log", "results/validation_summary.json"], "",
        "cubic roots (numpy) vs multiprecision Newton: agreement 1e-15")
    add("B10", B, "§2.2", "Exact optima: Δ1 ≤ 1 at c = 4 and Δ1 ≤ 2 at c = 12", "quoted from HMR",
        "fresh order-P extremal functionals", "independently reproduced (approached from above)", f"Δ1^(P={E['anchor_c4']['Pmax']}) − 1 = {E['anchor_c4']['excess']:.2e}; Δ1^(P={E['anchor_c12']['Pmax']}) − 2 = {E['anchor_c12']['excess']:.2e}",
        ["results/functional_bounds.csv", "figures/fig05_functional_convergence.png"], "finite order; limit inferred", "LP (HiGHS) at P = 4 agrees to 1e-5; at P > 4 the float64 LP upper-bounds the Newton value within 3e-3")
    add("B11", B, "§2.2, §2.4; eq. (2-sumrule), (2-halfmass), (2-gvac-cardy)", "Extremal functional: g ≥ 0 above t1, g_vac = 0, negative lobe carries exactly half of the Cardy-weighted mass", "derivation",
        f"{npts} fresh functionals (c = {cs[0]}…{cs[-1]}, P ≤ {max(pmax.values())}): grid positivity, exact polynomial factorisation, cofactor roots, Bessel-weighted mass integrals", "independently reproduced",
        f"all {npts} nonnegative on [t1, ∞); |g_vac|/scale ≤ 1e-53; f_neg − 1/2 = {E['half_mass']['max_dev']:.0e} on {E['half_mass']['n']} functionals; identity g_vac = −∫gρ_C to {E['half_mass']['max_identity_violation']:.0e}",
        ["results/functional_bounds.csv", "results/functional_analysis.json"], "multiprecision floating point with a-posteriori checks, not interval arithmetic; c ≤ 64", "two solver routes (P-continuation, c-homotopy) agree exactly on 15+ points")
    add("B12", B, "eq. (5-conv), App. G.2", "Δ1^(P) − Δ1^(∞) ≈ C exp(−k √(P/c)), k ≈ 4.7–5.7; free exponent s = 0.57–0.58", "numerical (empirical)",
        "fits to the fresh data", "consistent", f"k = {E['k_range'][0]:.2f}–{E['k_range'][1]:.2f} (s = 1/2 fixed); free s = 0.55–0.60", ["results/functional_extrapolation.csv"], "P/c ≤ 4 for c ≥ 24, P/c ≤ 1 at c = 64")
    add("B13", B, "Table 2", "24 extrapolated gaps Δ1^(∞)(c), σ, ratios c/Δ1 for 24 ≤ c ≤ 2048 (implementations I, II)", "numerical",
        "parsed from TeX; ratios recomputed exactly; c = 24, 48, 64 compared with fresh finite-P data", "ratios reproduced; values used as inputs (consistent with fresh data)",
        f"24/24 printed ratios reproduced to printed rounding; fresh bounds lie above the published limits; c=24 extrapolation {E['extrap_c24']['Dinf_s_half']:.4f}/{E['extrap_c24']['Dinf_s_free']:.4f} vs 3.440977",
        ["results/table2_extracted.csv", "results/functional_extrapolation.csv"], "the Arb runs (P ≤ 3072, 768–1600 bits) were not rerun; the published points are INPUTS")
    add("B14", B, "eq. (5-meas)", "ξ_meas = 0.026240 ± 0.000025, Λ_meas = 9.1263 ± 0.002 from a fit in {1, c^-2/3, c^-1, c^-4/3}", "numerical",
        "least-squares refit, window/form/weight scans, leave-one-out, subsets I/II", "reproduced within the quoted uncertainty (central value differs by 0.0009)",
        f"ξ = {T2['fit_central']['xi']:.6f}, Λ = {T2['fit_central']['Lambda']:.4f}; spread over forms/windows Λ ∈ [{T2['fit_spread_unweighted_F3_F4_F4log']['Lambda_min']:.4f}, {T2['fit_spread_unweighted_F3_F4_F4log']['Lambda_max']:.4f}]; "
        f"{100*T2['fraction_of_fits_inside_published_band']['Lambda']:.0f}% of scanned fits inside the published band", ["results/table2_fits.csv", "figures/fig02_fit_sensitivity.png"],
        "the paper's exact fit recipe (weights, window set) is not specified; our spread is wider than ±0.002 when the three-term basis on wide windows is included", "normal equations in 50 digits (V4)")
    add("B15", B, "Conj. 1(a); eq. (4-airy)", "Δ_best = c/Λ_V + 0.27666 c^{1/3} + O(1), no log c at order c^{1/3}", "conjecture",
        "constant recomputed; Table 2 residuals; competing log term", "constant reproduced; conjecture supported, not established",
        f"A_opt = {S['A_opt'][:10]}; remainder in [{T2['remainder']['min']:+.3f}, {T2['remainder']['max']:+.3f}], ≈ {T2['remainder']['fit_r0']:+.3f} {T2['remainder']['fit_r1']:+.2f} c^(-1/3); fitted A = {T2['fit_spread_F3_F4']['A_min']:.3f}–{T2['fit_spread_F3_F4']['A_max']:.3f}; γ_log = {T2['gamma_log']['min']:+.3f}…{T2['gamma_log']['max']:+.3f}",
        ["results/table2_residuals.csv", "results/table2_reanalysis.json", "figures/fig01_slope_drift.png"], "asymptotic statement; data stop at c = 2048 where the remainder still drifts; our fitted A range (0.233–0.275) is wider/lower than the paper's 0.269–0.285")
    add("B16", B, "§5.2", "AHT-type forms fitted to the exact two-term law return (9.085, 0.48) on [300,700], (9.02, 0.28) on [20,300], ≈(9.11, 0.71) on [500,4000]; c/A+B1 → 9.004; c/A+B1+B2/c → 9.043; log fit off by 0.22 at c = 2048", "numerical",
        "refit on integer grids of c", "independently reproduced", "(9.085, 0.477), (9.017, 0.280), (9.109, 0.718); 9.004; 9.043; 0.218", ["results/table2_aht_forms.csv", "logs/s05_table2_reanalysis.log"],
        "the AHT numbers themselves (9.08, 0.439, −0.896) are taken as quoted in [B], not from the original paper")
    add("B17", B, "eq. (4-offset) and footnote", "ξ1* + ∫(1−ρ_V)dξ = 1/24; Landen identity", "exact identity", "quadrature and series to 1e-20…1e-30", "independently reproduced (numerically)", "both hold to working precision", ["results/slope_constants.json"])
    add("B18", B, "Conj. 1(e); §5.3", "Exactly one zero between the vacuum and t1, t_int → 1/4π (t_int = 1/4π + 0.058/c)", "conjecture",
        "real roots of the fresh polynomials", "supported for c ≥ 16; small-c exception found", f"exactly one zero for all (c,P) with c ≥ 16; for c = {E['zeros_between_vacuum_and_t1']['c_with_second_zero_next_to_vacuum']} a second zero sits within 0.002 of the vacuum (at the vacuum itself for c = 4, 12, forced by g_vac = 0 with integer spectrum); t_int(c=64, P={pmax[64]}) = {[r for r in fb if int(r['c'])==64 and int(r['P'])==pmax[64]][0]['t_int'][:8]} vs 0.080484",
        ["results/functional_anatomy.csv"], "large-c statement; our data reach c = 64 only")
    add("B19", B, "§5.3, §6.7", "Complex zeros lie on |Im b| = 𝔥/2 with 𝔥 = 1.0000 ± 0.0005; u_g(0) approaches U0 from below (U−u_g = 0.053 at (64,256))", "numerical",
        "complex roots and Cardy-weighted profiles of the fresh functionals", "consistent (trend), not reproduced quantitatively", "median 2|Im b| = 1.14, 1.07, 1.04 at c = 16, 32, 64; U0 − u_g(0) = 0.105, 0.079, 0.057", ["results/functional_anatomy.csv", "figures/fig06_functional_anatomy.png"],
        "orders P ≤ 64 versus the paper's 256–3072")
    add("B20", B, "Table 1, §1.2", "Ladder of slopes: 6 (Hellerman), 8.503 (HMR), 9.08 (AHT extrapolation), c/8.956 at c = 1800 (AHT), 12 (FKS/FK)", "literature as quoted",
        "tabulated with provenance; not re-derived (except Hellerman, B09)", "quoted, not independently checked", "see results/slope_ladder.csv", ["results/slope_ladder.csv", "sources.md"], "original papers were not consulted in this offline session")
    add("H01", HP, "§2; eq. (zBzF), (z), (xH)", "z(x) = 2y²(3−y)/(1−y)³, y_H = 2−√3, x_H = 7−4√3, β0 = 2.6339158, T_H⁰ = 0.37966", "review (Sundborg, AMMPV)",
        "explicit S³ mode enumeration and bisection; exact symbolic factorisation", "independently reproduced", f"x_H(mode sum) − (7−4√3) < 1e-37; β0 = {H['beta_0'][:12]}", ["results/hp_hagedorn.json", "results/hp_modesum_convergence.csv"], "",
        "numpy.roots of the cubic; exact rational mode sum (V6)")
    add("H02", HP, "eq. (slope), (d1), (d1H), (TH1)", "x z′(x) = 3/2 at x_H; d1(x_H) = 3/2; d1 = 33x² + …; T_H = T_H⁰(1 + 2g² + …)", "review (Spradlin–Volovich)",
        "symbolic derivative; series; numerical derivatives", "independently reproduced from the printed closed form", "3/2 exactly; d1 = 33y⁴ + 240y⁵ + …; ∂βd1 = −(8√3−9)", ["results/hp_hagedorn.json"], "the closed form of d1 itself is taken from the paper")
    add("H03", HP, "eq. (HW), (target), (d4target)", "Two-loop coefficient −11.50399 (Harmark–Wilhelm closed form); target d4(x_H) = −10.7287; bracket terms 61.25, −36.05, −15.80, +134.77; 115.91", "literature + arithmetic",
        "closed form evaluated; target assembled; closure test by solving m1²(T)=0 numerically", "arithmetic reproduced; closure verified", f"−11.503990; d4 = {H['d4_target'][:9]}; recovered g⁴ coefficient {H['TH_g4_coefficient_closure'][:9]}", ["results/hp_hagedorn.json"],
        "C41 = 8.353829 and the direct d4 = −10.71(2)(6) are paper inputs; the Harmark–Wilhelm result itself was not re-derived")
    add("H04", HP, "App. B Tables; eq. (q4a), (q4b)", "q4(a) = −0.7340(1), q4(b) = −1.500(3); geometric remainders −0.0001 and −0.007; Padé range −1.4987…−1.5044; unconfirmed part −0.34", "computed in the paper (single engine for b_n, n ≥ 7)",
        "re-summation at the independently computed y_H with exact rationals; three tail models; Padé table; truncation scan", "sums reproduced from the paper's coefficients",
        f"q4(a) = {sa['centre_power_law']:.5f} (range {sa['min']:.5f}…{sa['max']:.5f}); q4(b) = {sb['centre_power_law']:.4f} (range {sb['min']:.4f}…{sb['max']:.4f}); all printed terms and partial sums reproduced; single-engine part {Q['unconfirmed_part_q4b']['without_tail']:.3f}",
        ["results/hp_series_resum.csv", "results/hp_series_truncation.csv", "figures/fig08_series.png"], "coefficients a_n, b_n are microscopic outputs of the paper and were NOT recomputed", "Decimal×Fraction partial sums; mpmath.pade vs own Padé (V7)")
    add("H05", HP, "eq. (master2), (b), (b-lambda); §7.1", "b = g⁴[−4β0² I + β0 q4] = −36.94(1) g⁴ = −1.481×10⁻³ λ²; pieces −29.45, −1.61, −1.93, −3.95; one-loop share 84%", "computed in the paper",
        "assembly from the paper's c3, Q4, q4 with A2, β0 recomputed; linear and Monte Carlo error propagation", "arithmetic reproduced from paper inputs",
        f"b/g⁴ = {q['b_over_g4']:.4f} ± {q['db']:.4f}; b/λ² = {q['b_over_lambda2']:.4e}; I = {q['I']:.5f}", ["results/hp_quartic.json", "results/hp_budget.csv", "figures/fig09_quartic_budget.png"],
        "c3 = 0.16821, Q4 = 2.1222 (and hence 84% of b) are taken from the paper", "Decimal arithmetic from printed digits (V9)")
    add("H06", HP, "§7.1, §6.4, §8.2", "Sign margin: b > 0 would need q4 > 11.79; margin 'fourteen'", "computed in the paper",
        "critical q4 and stress scenarios", "arithmetic reproduced; conclusion conditional on the paper's I and q4", f"q4_crit = {q['q4_crit']:.4f}; margin {q['margin']:.3f} ({q['margin_in_units_of_dq4']:.0f} quoted σ of q4); b stays negative when the single-engine terms are dropped or flipped and for q4 ± 0.8",
        ["results/hp_sign_scenarios.csv"], "a sign flip would require an error in I of order 100% or in q4 of order 14; neither can be excluded by arithmetic alone")
    add("H07", HP, "eq. (schemes)", "I is scheme independent: 1.11918(15) (literal) vs 1.1200(16) (commutator)", "computed in the paper", "I recomputed from each row", "arithmetic reproduced", f"1.11918 vs {q['I_commutator']:.4f}; difference within the quoted 0.0016", ["results/hp_quartic.json"], "scheme-dependent c3, Q4 not recomputed")
    add("H08", HP, "§3.2; eq. (V), (Vcubic)", "Measure potential V(u) = u² (u ≤ ½), ¼ − ½ ln[2(1−u)] (u ≥ ½); C² junction; V − u² = (4/3)ε³", "review (Gross–Witten, Wadia)",
        "junction derivatives; Legendre transform of the GWW free energy; finite-N Toeplitz determinants", "independently reproduced", "Legendre transform equals V(u) to 1e-9; det[I_{j−k}(2Nβ)] at N = 32 within 4e-4 of the large-N free energy (gapped phase)",
        ["results/hp_landau.json", "results/hp_gww_finiteN.csv"], "large-N statement; finite-N check has O(1/N²)–O(log N/N²) corrections")
    add("H09", HP, "§3.3; Table (regimes); Fig. 2 caption", "Three saddles; thresholds m1² = |b|/2 and |b|/4 at leading order; at |b| = 0.1: 0.053 and 0.032; jump to ½ + √|b|/4; latent heat 3/8 N²/R", "derivation (AMMPV)",
        "exact saddles on the restricted domain 0 ≤ u < 1 with the gapped branch; scan in |b|", "independently reproduced; wall corrections quantified",
        f"|b| = 0.1: m²_min = {L['b_0p1']['m2_min']:.5f}, m²_c = {L['b_0p1']['m2_c']:.5f}, u_c = {L['b_0p1']['u_c']:.4f}; m²_c/|b| − ¼ ≈ {L['scan_fit']['coef_c']:.3f}|b|^{L['scan_fit']['exp_c']:.2f}; four regimes reproduced",
        ["results/hp_landau_scan.csv", "results/hp_potential_curves.csv", "figures/fig10_landau_transition.png"], "single-moment potential; higher moments and O(λ³) terms neglected as in the paper", "brute-force grid scan (V8)")
    add("H10", HP, "eq. (window), (three-T)", "(T_H−T_c)/T_H = 2.337 g⁴ = 9.37×10⁻⁵ λ²; (T_H−T_min)/T_H = 4.67 g⁴; T_c, T_min coefficients −13.84, −16.18; ordering T_min < T_c < T_H", "computed in the paper",
        "coefficients assembled; exact inversion of m1²(T) through two loops for λ = 0.01…5", "arithmetic reproduced; ordering confirmed; finite-λ correction quantified",
        f"2.3375, 4.675, −13.841, −16.179; ordering holds at all six couplings; at λ = 1 the exact window is {float(tr['1.0']['window_c_exact']):.3e} ({100*(L['window_lambda1_exact_over_leading']-1):.1f}% above leading order)",
        ["results/hp_temperatures.csv"], "conditional on b < 0 and on the truncation to order λ²; d4, C41 are paper inputs")
    add("H11", HP, "§7.3 Table (near-BPS)", "b/G̃² < 0 in nine decoupling limits", "computed in the paper", "last column recomputed from the printed A2, c3, Q4; su(2) row from the closed forms of App. B", "internal consistency reproduced",
        "9/9 rows consistent within rounding; all negative; su(2) = −3/4 exactly", ["results/hp_nearbps_check.csv"], "sector functions not recomputed (except su(2))")
    add("H12", HP, "§8.2 Table (ym)", "Pure Yang–Mills comparison with AMMPV: six classes agree, class 7 differs (−2.095 vs −3.388); 0.8 in units of q4", "computed in the paper; unresolved discrepancy",
        "column sums and unit conversion", "arithmetic reproduced; discrepancy not adjudicated", f"sums {Q['ym']['sum_this']:.2f} vs {Q['ym']['sum_AMMPV']:.2f}; class-7 difference {Q['ym']['class7_diff']:.3f} = {Q['ym']['class7_in_q4_units']:.2f} in q4 units",
        ["results/hp_ym_extracted.csv", "results/hp_quartic.json"], "neither three-loop calculation was repeated")
    add("H13", HP, "§5–§6", "Microscopic coefficients c3, Q4, q4 series, C41 from the Coulomb-gauge Hamiltonian / three-loop diagrams", "computed in the paper",
        "not attempted", "not verified here", "—", ["verification_report.md"], "a full three-loop (fourth-order degenerate perturbation theory) computation with hundreds of vertex coefficients is outside the scope of this session")
    add("H14", HP, "§1 eq. (THP)", "AdS₅: T_min = √2/πR, T_HP = 3/2πR", "review (Hawking–Page, Witten)", "Schwarzschild–AdS₅ thermodynamics evaluated numerically", "independently reproduced", "0.450158, 0.477465 (R = 1)", ["results/hp_gravity_branches.csv"], "classical gravity")
    json.dump({"generated_utc": now(), "n_claims": len(led), "verdict_counts": {v: sum(1 for x in led if x["verdict"] == v) for v in sorted(set(x["verdict"] for x in led))}, "claims": led},
              open(os.path.join(ROOT, "claim_ledger.json"), "w"), indent=1, ensure_ascii=False)

    # ------------------------------------------------------------------ timeline
    ev = [json.loads(l) for l in open(os.path.join(LOG, "events.jsonl")) if l.strip()]
    ev.sort(key=lambda e: e["t"])
    json.dump({"note": "Real wall-clock events of this session (UTC), appended by the scripts as they ran; nothing here is simulated.", "n_events": len(ev), "events": ev},
              open(os.path.join(ROOT, "research_timeline.json"), "w"), indent=1, ensure_ascii=False)

    # ------------------------------------------------------------------ verification report
    W = []
    W.append("# Verification report\n")
    W.append(f"Generated {now()} (UTC) by `code/s11_ledger_reports.py` from the JSON/CSV in `results/`.\n")
    W.append("## 1. What was executed\n")
    W.append("| Script | Purpose | Checks passed |\n|---|---|---|")
    for nm, obj, pur in (("s01_extract_sources", None, "parse published tables from TeX, hashes"), ("s02_slope_endpoint", S, "constants, endpoint three ways, Lemmas 6.3/6.5/6.7"), ("s03_dirichlet_fd", None, "finite-difference Laplace solve (second method)"),
                         ("s04/s04b functional solvers", None, f"{npts} fresh extremal functionals"), ("s05_table2_reanalysis", T2, "Table 2 refits, residuals, windows"), ("s06_hp_hagedorn", H, "Hagedorn equation, d1, Harmark–Wilhelm target"),
                         ("s07_hp_series_quartic", Q, "App. B series, quartic coefficient, tables"), ("s08_hp_landau", L, "restricted-domain Landau analysis"), ("s09_functional_analysis", FA, "convergence, certificates, anatomy"),
                         ("validate_all", None, "separate-algorithm validation")):
        if obj is not None:
            W.append(f"| `{nm}.py` | {pur} | {obj['n_pass']}/{obj['n_checks']} |")
        elif nm == "validate_all":
            W.append(f"| `{nm}.py` | {pur} | {V['n_pass']}/{V['n']} |")
        else:
            W.append(f"| `{nm}` | {pur} | (see log) |")
    W.append(f"\nTotal: **{npass}/{nchk}** paper-referenced checks pass (`results/all_checks.csv`) and **{V['n_pass']}/{V['n']}** cross-algorithm comparisons pass (`results/validation_summary.json`). "
             "Logs with timestamps are in `logs/`.\n")
    W.append("## 2. Second methods used\n")
    W.append("| Quantity | Primary | Independent | Agreement |\n|---|---|---|---|")
    vb = {}
    for c in V["comparisons"]:
        vb.setdefault(c["block"], []).append(c)
    desc = {"V1": ("x*, Λ_V", "mpmath closed form", "Newton in `decimal`, own sinh series"), "V2": ("U0, identity (6-identity)", "mpmath quadrature", "Gauss–Legendre, float64"),
            "V3": ("U_s for general slit", "mpmath Poisson integral", "scipy.quad; finite differences"), "V4": ("Table 2 fit", "numpy lstsq", "normal equations, 50 digits; exact Fractions"),
            "V5": ("extremal gap", "multiprecision Newton", "LP (HiGHS); cubic roots"), "V6": ("Hagedorn root", "mode-sum bisection", "numpy.roots; exact rationals"),
            "V7": ("series sums, Padé", "mpmath + own Padé", "Decimal×Fraction; mpmath.pade"), "V8": ("Landau thresholds", "root solving", "brute-force grid"), "V9": ("b/g⁴", "mpmath", "Decimal from printed digits")}
    for k, cl in vb.items():
        d = desc[k]
        W.append(f"| {d[0]} | {d[1]} | {d[2]} | {sum(c['pass'] for c in cl)}/{len(cl)} pass; max |diff| {max(c['absdiff'] for c in cl if c['tol'] < 0.9):.1e} |")
    W.append("\nCaveat on V5: at orders P > 4 the float64 linear program is biased high by up to 2.5×10⁻³ (the vacuum action per unit mass rises very slowly past the optimum), so only the one-sided duality "
             "statement LP ≥ Newton is tested there; equality to 10⁻⁵ is tested at P = 4 for c = 4, 8, 12, 24.\n")
    W.append("## 3. Problems met during the work (kept, not hidden)\n")
    W.append("* First implementation of the tangency integral lost all precision by cancellation (γ_tip of order 10²–10³); rewritten with an exact difference formula, after which the four values quoted in [B] §6.6 are reproduced.")
    W.append("* Upward continuation in P stalled for c ≥ 16 (c = 64 at P = 4); replaced by a homotopy in c at fixed P seeded at c = 4. Where both routes exist they agree to all digits.")
    W.append("* The half-mass quadrature crashed twice inside mpmath's error estimator (ZeroDivisionError); a Gauss–Legendre fallback was added. The P = 80 homotopy therefore stopped after c = 8 and was not rerun; P = 96 was abandoned for time.")
    W.append("* A direct-comparison tolerance for the LP validation failed and was replaced by the one-sided test described above.")
    W.append(f"* The single check that initially failed on physics grounds — 'window at λ = 1 equals 9.37×10⁻⁵' — is a real finite-coupling effect: the exact two-loop inversion gives {float(tr['1.0']['window_c_exact']):.3e}; "
             "the leading coefficient is recovered at λ = 0.01.")
    W.append("* 'Exactly one zero between the vacuum and t1' fails for c = 4, 8, 12 (a second zero at or next to the vacuum); it holds for all c ≥ 16. Recorded as a finding (ledger B18).\n")
    W.append("## 4. What was NOT done, and why\n")
    W.append("* **No certified two-sided bootstrap proof.** The optimality half ([B] Thm 3–4) depends on potential-theoretic lemmas (App. A, B) that were read but not re-proved; the attainment half ([B] Thm 5) needs the "
             "interval-arithmetic certificates of App. G, which were not rerun. Our functionals are verified a posteriori in multiprecision floating point, not in interval arithmetic, and only for c ≤ 64.")
    W.append("* **No rerun of the Table 2 solver.** P up to 3072 at 768–1600 bits is far beyond this session; the 24 published points are inputs.")
    W.append("* **No three-loop computation.** c₃, Q₄, the series a_n, b_n and C₄₁ of [HP] are taken from the paper; only arithmetic built on them is verified.")
    W.append(f"* **No Lean (or other formal) rerun.** No Lean toolchain is installed in this runtime, and a text search of both TeX sources finds {len(X['formal_proof_mentions'])} mentions of Lean/Coq/Isabelle/formalisation: the supplied v1 archives provide no Lean project to replay. The original research announcement reports a formal verification.")
    W.append("* **Historical papers were not re-read.** Numbers attributed to Hellerman, Friedan–Keller, HMR, AHT, AMMPV, Spradlin–Volovich and Harmark–Wilhelm are the values quoted in [B]/[HP].")
    W.append("* **Verifiable proof sub-steps that were checked**: the map values and fold points of Lemma 6.3; boundary values of p(b), path independence, the identity (6-identity) and U = 0 on the edges of Lemma 6.5; "
             "the deficit inequality of Lemma 6.7 on a grid; the arithmetic of the rate in Thm 4; the eigen-identity/half-mass identity on explicit functionals.\n")
    W.append("## 5. Notebook and laboratory: how they were executed and tested\n")
    W.append("* `research_notebook.ipynb` was executed cell by cell in one namespace by the in-process executor in `code/s12_build_notebook.py`; outputs and 11 figures are stored in the file. A real Jupyter kernel could not be started "
             "because the session sandbox forbids binding local sockets (nbclient raised PermissionError); this was not worked around. The same cells' computations were also run through the application's live notebook tool during the session.")
    lab_log = os.path.join(LOG, "lab_smoke_test.log")
    if os.path.exists(lab_log):
        sm = [l.strip() for l in open(lab_log).read().split("\n") if l.startswith("SUMMARY")]
        W.append(f"* `black_hole_research_lab.html` was tested with node (`scene/test_html.mjs`, `scene/test_lab.mjs`): {'; '.join(sm)}. The tests parse the embedded JSON, syntax-check both inline modules, confirm the absence of network references, "
                 "build the real Three.js scene graph, and drive walking, dragging, the six stations, sliders, timeline replay, the 2D map and the no-WebGL fallback through a DOM stub. "
                 "**Not tested:** rendered pixels, layout and touch behaviour in a real browser — none was available inside the sandbox — so visual quality in the preview pane is unverified.")
    W.append("* The laboratory embeds the timeline as it stood when the file was built; the last build/test events appear only in `research_timeline.json`.\n")
    W.append("## 6. Claim ledger (summary; full machine-readable version in `claim_ledger.json`)\n")
    W.append("| ID | Location | Paper status | Verdict | Result |\n|---|---|---|---|---|")
    for x in led:
        W.append(f"| {x['id']} | {x['location']} | {x['paper_status']} | **{x['verdict']}** | {x['quantitative_result']} |")
    open(os.path.join(ROOT, "verification_report.md"), "w").write("\n".join(W) + "\n")

    # ------------------------------------------------------------------ research report
    R = []
    R.append("# Independent Reproduction of AI-Assisted Black Hole Physics Discoveries\n")
    R.append("**Papers.** [B] *The Spinless Modular Bootstrap at Large Central Charge*, Hexagon 2611.00174v1; [HP] *The Hawking–Page Transition at Weak Coupling*, Hexagon 2611.00175v1 "
             "(both: author line 'Claude (Anthropic)', CC BY 4.0; local copies and hashes in `sources.md`).\n")
    R.append(f"**Session.** One research session on 2026-11-19 (UTC); all computations were run here (`logs/`, `research_timeline.json`). {npass}/{nchk} paper-referenced checks and {V['n_pass']}/{V['n']} "
             "cross-algorithm comparisons pass.\n")
    R.append("## Summary of findings\n")
    R.append(f"1. **Endpoint of the optimal-slope argument ([B] Thm 1, §6.6).** Solved three ways: root of sinh πx = 1; a tangency condition derived here for a slit at general position (root equals arcsinh(1)/π to {S['s_tangency_minus_xstar']:.0e}); "
             f"and a finite-difference Laplace solve (sign change at s = {FD['s_root_fd']:.4f}). Λ_V = 9.126634026.")
    R.append(f"2. **Finite-order functionals.** {npts} extremal functionals (c = 4…64, P ≤ {max(pmax.values())}) were constructed with an independent solver and tested numerically for nonnegativity on [t₁, ∞), vanishing vacuum action and a negative Cardy mass fraction of ½. "
             f"They reproduce the exact optima at c = 4, 12 from above (excess {E['anchor_c4']['excess']:.1e}, {E['anchor_c12']['excess']:.1e}) and the convergence law of [B] eq. (5-conv) (k = {E['k_range'][0]:.2f}–{E['k_range'][1]:.2f}).")
    R.append(f"3. **Table 2.** All 24 printed ratios follow from the printed gaps. Refit: Λ = {T2['fit_central']['Lambda']:.4f} (paper 9.1263 ± 0.002; Λ_V = 9.1266). Finite-c drift: c/Δ₁ = {T2['drift']['ratio_c2048']:.4f} at c = 2048, "
             f"still {T2['drift']['LambdaV_minus_ratio_2048']:.3f} below Λ_V; reaching 0.01 would need c ≈ {T2['drift']['c_needed_for_0p01']:.1e}. A log-form fit drifts from {T2['drift_logform_Lambda_range'][0]:.3f} to {T2['drift_logform_Lambda_range'][1]:.3f} with the window.")
    R.append(f"4. **Hagedorn point ([HP] §2).** Mode-sum root = 7 − 4√3 to 10⁻³⁷; β₀ = 2.6339158; x z′ = 3/2; state counting grows at 2 + √3.")
    R.append(f"5. **Series and quartic coefficient.** q₄⁽ᵃ⁾ = {sa['centre_power_law']:.5f}, q₄⁽ᵇ⁾ = {sb['centre_power_law']:.4f} (estimators {sb['min']:.4f}…{sb['max']:.4f}); with the paper's c₃, Q₄: b = {q['b_over_g4']:.3f} ± {q['db']:.3f} g⁴, "
             f"sign margin {q['margin']:.2f} in q₄.")
    R.append(f"6. **Transition.** On the restricted domain with the gapped branch, T_min < T_c < T_H for every coupling tested; at |b| = 0.1 the exact thresholds are {L['b_0p1']['m2_min']:.4f} and {L['b_0p1']['m2_c']:.4f} "
             f"(leading order 0.05, 0.025), and the loop jumps to u = {L['b_0p1']['u_c']:.3f}.")
    R.append("7. **Not verified:** the proofs of [B] Thm 3–5, the Table 2 solver runs, the three-loop coefficients of [HP]; the v1 source archives contain no Lean project. The authors report formal verification in the original study. This session did not replay it. See §8.\n")
    R.append("## 1. Starting equations and feasibility\n")
    R.append("The plan (`research_plan.md`, frozen before computation) lists the equations used and splits them into locally checkable and not checkable. In brief: [B] reduces the spinless bootstrap to functions "
             "g(t) = p(t)e^{−2πt} with p in the span of odd Laguerre polynomials L_{2k−1}(4πt) ([B] eq. 2-deriv), with vacuum action g_vac = g(−a) − 2g(−a+1) + g(−a+2), a = (c−1)/12 ([B] eq. 2-sumrule). "
             "The slope claim is lim c/Δ_best = Λ_V with 1/Λ_V = 1/12 + (x₁*)²/3 and sinh πx₁* = 1 ([B] Thm 1). [HP] reduces the weak-coupling transition to the sign of b in S/N² = m₁²|u₁|² + b|u₁|⁴ ([HP] eq. landau-intro) "
             "with b = g⁴[−4β₀²I + β₀q₄] ([HP] eq. master2).\n")
    R.append("## 2. Primary study: the two sides of the optimal-slope argument\n")
    R.append("**Hypotheses** (H1–H4 of the plan): tangency at x₁*; fresh finite-P bounds lie above and converge to the published limits; the Table 2 ratios extrapolate to Λ_V only with a c^{1/3} correction; "
             "A_opt is supported but not established.\n")
    R.append("**Optimality side** ([B] §6). The chain is: (i) continuation of G(b) = g(c′b²/3) to the strip |Im b| ≤ ½; (ii) edge bound; (iii) Cardy-weighted mean bound on the slits; (iv) harmonic majorant U_s by the maximum "
             "principle; (v) closed form for s = x₁* and strict deficit below the Cardy line; (vi) half-mass condition. Steps (i)–(iv) are analysis (App. A, B) that we did not re-prove. Steps (v) and the ingredients of (vi) are "
             "explicit and were checked:\n")
    R.append(f"* *Closed form* ([B] Lemma 6.5): U₀ = −0.388747872, U(i/2) = 0, U(x₁*) = −L(x₁*), identity (6-identity) to 10⁻³⁰; path independence of ∫p db; sinh πb = i sinh πp.")
    R.append(f"* *Second method*: a finite-difference solution of the Dirichlet problem ([B] eq. 6-dirichlet) without any conformal map converges with order {FD['orders'][-1]:.2f}; Richardson value {FD['U0_richardson']:.6f} (Figure 3).")
    R.append(f"* *Endpoint solved independently*: for a slit at general s we mapped the strip to a half-plane (w = sinh πb, ζ = w², m = (ζ+1)/(σ²−ζ), q = √m) and obtained U_s as a Poisson integral. The square-root "
             f"coefficient at the tip is γ_tip(s) ∝ L(s) − (2/3)J(s); its unique zero is s = {S['s_tangency'][:20]}, i.e. arcsinh(1)/π (Figure 4). For s < x₁*, max(U_s + L) < 0 on (−s, s); for s = 0.30, 0.32 it is "
             f"+{S['max_Us_plus_L']['0.3000']:.4f}, +{S['max_Us_plus_L']['0.3200']:.4f}. This reproduces the paper's γ_tip values and its statement that s = x₁* is the largest useful slit.")
    R.append(f"* *Deficit* ([B] Lemma 6.7): κ(0.01…0.2) = 0.00265, 0.02947, 0.08303, 0.23378; min κ/δ^{{3/2}} = {S['kappa_ratio_min']:.4f} ≥ 2.2281.")
    R.append(f"* *Rate arithmetic* ([B] Thm 4): 0.4393; the bound is vacuous for c′ < {S['rate_floor_cprime']:.0f}, as the paper states.\n")
    R.append("**Attainment side** ([B] §7–8). The explicit comb functional and its certificates were not reproduced. What we can say locally is weaker but concrete: finite-order functionals exist with the "
             "required sign structure, and we built them.\n")
    R.append(f"**Finite-order derivative functionals (fresh optimizer output).** The dual problem F_k = v_k + Σ d_n φ_k(t_n) = 0 was solved by damped Newton in 60–264 digits, by continuation in P and by homotopy in c "
             f"(the two agree on every common point). For each of the {npts} solutions we formed the functional and checked: d_n > 0; |g_vac|/scale ≤ 10⁻⁵³; g ≥ 0 on a dense grid; numerical polynomial division of p(t) by "
             "(t−t₁)∏(t−t_n)² with remainder ≤ 10⁻⁵⁸ and no real cofactor root above t₁; and, with the three-Bessel weight V, the half-mass identity. Results (Figure 5, `results/functional_bounds.csv`):\n")
    R.append("| c | largest P | Δ₁^(P) | c/Δ₁^(P) | reference | excess |\n|---|---|---|---|---|---|")
    for r in read_csv("functional_extrapolation.csv"):
        R.append(f"| {r['c']} | {r['Pmax']} | {float(r['Delta1_at_Pmax']):.6f} | {float(r['c'])/float(r['Delta1_at_Pmax']):.4f} | {r['reference_value'] or '—'} ({r['reference_kind']}) | "
                 + (f"{float(r['Delta1_minus_reference']):.2e}" if r['Delta1_minus_reference'] else "—") + " |")
    R.append(f"\nThe c = 24 data (P/c ≤ {pmax[24]/24:.1f}) extrapolate to {E['extrap_c24']['Dinf_s_half']:.4f} (s = ½) or {E['extrap_c24']['Dinf_s_free']:.4f} (free s = {E['extrap_c24']['s_free']:.2f}) against the published 3.440977. "
             f"With the free exponent the c = 48 and c = 64 extrapolations ({E['extrap_c48']['Dinf_s_free']:.5f}, {E['extrap_c64']['Dinf_s_free']:.5f}) differ from Table 2 by {E['extrap_c48']['Dinf_s_free']-E['extrap_c48']['table2']:+.1e} and {E['extrap_c64']['Dinf_s_free']-E['extrap_c64']['table2']:+.1e}. "
             "These are consistency checks of three Table 2 entries to four or five digits, with a form-dependence of a few 10⁻³ (s = ½ versus free s); they are not a reproduction of the table. Anatomy (Figure 6): the complex zeros approach |Im b| = ½ and u_g(0) approaches U₀ from below as c grows; "
             "for c ≤ 12 a second real zero sits at or next to the vacuum, an exception to the large-c statement [B] Conj. 1(e) that disappears for c ≥ 16.\n")
    R.append("**Table 2 reanalysis** (Figures 1–2). Input versus fresh points are kept apart everywhere (`provenance` column).\n")
    R.append(f"* Ratios: 24/24 printed ratios equal c/Δ to the printed rounding. Provenance: 9 rows implementation I, 15 rows II; 14 rows have P_max/c ≥ 4.")
    R.append(f"* Refit in the paper's basis, all rows, unweighted: ξ = {T2['fit_central']['xi']:.6f}, Λ = {T2['fit_central']['Lambda']:.4f}, coefficient of c^(−2/3) = {T2['fit_central']['A']:.4f} (A_opt = 0.27666). "
             f"Leave-one-out: Λ ∈ [{T2['leave_one_out']['Lambda_min']:.4f}, {T2['leave_one_out']['Lambda_max']:.4f}]. Implementation I only: {T2['subsets']['impl I (9 rows)']['Lambda']:.4f}; II only: {T2['subsets']['impl II (15 rows)']['Lambda']:.4f}.")
    R.append(f"* Sensitivity: over three bases and seven windows Λ ∈ [{T2['fit_spread_unweighted_F3_F4_F4log']['Lambda_min']:.4f}, {T2['fit_spread_unweighted_F3_F4_F4log']['Lambda_max']:.4f}]; "
             f"{100*T2['fraction_of_fits_inside_published_band']['Lambda']:.0f}% of these fits fall inside 9.1263 ± 0.002. A five-term basis gives {T2['fit_F5']['Lambda_min']:.4f}–{T2['fit_F5']['Lambda_max']:.4f}. "
             "Weighted by 1/σ the all-row fit has χ²/dof = 13 (dominated by c = 24), dropping to 1.3 and 0.2 for c ≥ 48, 64: the σ are not statistical errors, as the paper says.")
    R.append(f"* Residuals: Δ − c/Λ_V − A_opt c^(1/3) runs from {T2['remainder']['max']:+.3f} (c = 24) to {T2['remainder']['min']:+.3f} (c = 2048), well described by {T2['remainder']['fit_r0']:+.3f} {T2['remainder']['fit_r1']:+.2f} c^(−1/3) "
             f"(rms {T2['remainder']['rms_resid']:.4f}). A competing γ log c term fits to γ = {T2['gamma_log']['min']:+.3f}…{T2['gamma_log']['max']:+.3f} (paper: −0.07…−0.005).")
    R.append("* The '9.08' explanation of [B] §5.2 is reproduced in all eight quoted numbers.\n")
    R.append("**Asymptotics and conjectures, stated precisely.** Λ_V is a statement about the limit c → ∞ taken after P → ∞, for functionals in the class of [B] Def. 2-Abar; that the numerical P → ∞ limit equals the "
             "infimum over that class is itself conjectural ([B] §2.6). The c^(1/3) coefficient A_opt, the absence of a log term, the zero law and t_int → 1/4π are parts of [B] Conj. 1 and are supported, not proved; the proved "
             "bounds bracket the correction between −0.44 c′^(1/3) log^(2/3) c′ and +0.483 c^(1/3). Nothing in our finite-c work can confirm or refute an asymptotic statement; it shows that the data to c = 2048 are compatible "
             "with it and incompatible with a 9.08 asymptote under the c^(1/3) form.\n")
    R.append("## 3. Secondary study: the Hawking–Page transition at weak coupling\n")
    R.append(f"**Hagedorn equation** (Figure 7). Enumerating the modes of [HP] Table 1 — 6n² scalar states at energy n, 2n(n+2) gauge states at n+1, 8n(n+1) fermion states at n+½ — and solving z(x) = 1 by bisection gives the root as a function "
             f"of the cut-off (error 2×10⁻², 2×10⁻⁵, 10⁻¹³ at n_max = 1, 4, 12) converging to x_H = 7 − 4√3. Closed forms, the cubic (y+1)(y²−4y+1), x z′ = 3/2, w″ = −(3/2)√3, A₂ = {H['A2'][:9]}, d₁(x_H) = 3/2 and ∂_β d₁ = −(8√3−9) all check. "
             f"The Harmark–Wilhelm coefficient evaluates to −11.50399 and the target d₄ = {H['d4_target'][:8]}; solving m₁²(T) = 0 numerically returns {H['TH_g4_coefficient_closure'][:8]}, closing the algebra of [HP] eq. (target).\n")
    R.append(f"**Series** (Figure 8). Every printed term and partial sum of both Appendix B tables is reproduced. Tails: for q₄⁽ᵃ⁾ geometric, power-law and Aitken estimates agree at −1.2×10⁻⁴; for q₄⁽ᵇ⁾ they give −0.0069/−0.0068 "
             f"and four Padé approximants give {min(sb['pade_top'].values()):.4f}…{max(sb['pade_top'].values()):.4f}, all inside the paper's quoted range. The last term ratios (0.365, 0.360) have not reached y_H = 0.268, and the fitted coefficient growth is n^{sa['p']:.1f} and n^{sb['p']:.1f}. "
             f"Sensitivity to the root is negligible (dq/dy ≈ −21, −32). The single-engine part of q₄⁽ᵇ⁾ is {Q['unconfirmed_part_q4b']['without_tail']:.3f} ({Q['unconfirmed_part_q4b']['with_tail']:.3f} with tail).\n")
    R.append(f"**Quartic coefficient and sign margin** (Figure 9). From the paper's c₃ = 0.16821(1), Q₄ = 2.1222(3): I = {q['I']:.5f} ± {q['dI']:.5f}; b = {q['b_over_g4']:.4f} ± {q['db']:.4f} g⁴ = {q['b_over_lambda2']:.3e} λ²; contributions "
             f"−29.45, −1.61, −1.93, −3.95. b = 0 requires q₄ = {q['q4_crit']:.2f}; margin {q['margin']:.2f}. With our re-summed series b = {q['b_resummed_here']:.3f} g⁴. Dropping (flipping) the single-engine terms gives "
             f"{q['scenarios'][2][2]:.2f} ({q['scenarios'][3][2]:.2f}). These numbers attribute: c₃, Q₄, a_n, b_n to [HP] §5–6 and App. B (microscopic, not recomputed); β₀, A₂, all sums and the assembly to this work.\n")
    R.append(f"**Transition on the restricted holonomy domain** (Figures 10–11). The order parameter lives on 0 ≤ u < 1; for u > ½ the eigenvalue density is gapped and the measure term is ¼ − ½ ln[2(1−u)] ([HP] eq. V). "
             "We verified that branch as the Legendre transform of the Gross–Witten–Wadia free energy and that free energy against finite-N Toeplitz determinants. With the exact branch (not its cubic expansion):\n")
    R.append(f"* thresholds at |b| = 0.1: m²_min = {L['b_0p1']['m2_min']:.5f}, m²_c = {L['b_0p1']['m2_c']:.5f} (caption of [HP] Fig. 2: 0.053, 0.032); jump to u_c = {L['b_0p1']['u_c']:.4f}, barrier {L['b_0p1']['barrier_at_c']:.5f};")
    R.append(f"* small |b|: m²_min/|b| → ½ with corrections ∝ |b|, m²_c/|b| = ¼ + {L['scan_fit']['coef_c']:.3f}|b|^{L['scan_fit']['exp_c']:.2f}, jump → ½ + √|b|/4, latent heat → 3/8;")
    R.append(f"* temperatures: exact inversion of m₁²(T) with b = −36.94 g⁴ gives T_min < T_c < T_H at λ = 0.01, 0.1, 0.5, 1, 2, 5. At λ = 1: T_min, T_c, T_H = {float(tr['1.0']['T_min_exact']):.6f}, {float(tr['1.0']['T_c_exact']):.6f}, {float(tr['1.0']['T_H_exact']):.6f}; "
             f"window {float(tr['1.0']['window_c_exact']):.3e} versus the leading 9.37×10⁻⁵.")
    R.append("* for b > 0 the same code gives the second-order point and the Gross–Witten–Wadia point at m₁² = −b/2.\n")
    R.append("**Limits of truncated potentials and of pictures.** The quartic polynomial alone is unbounded below for b < 0; the wall is what makes the deconfined saddle exist, so any plot or model that omits the gapped branch "
             "(or extends u beyond 1) is qualitatively wrong. Conversely the wall is known exactly only for the pure measure with a single moment; terms of order λ·u₂, λ³ and higher moments are dropped, so thresholds beyond leading order in |b| "
             "are indicative. The exaggerated |b| = 0.1 used in figures (and in the 3D laboratory) corresponds to no perturbative coupling: at λ = 1, |b| = 1.5×10⁻³. Visual models show structure, not magnitudes.\n")
    R.append("**Conditional conclusions.** 'First order at weak coupling' follows if b < 0. Our work shows that the paper's inputs imply b < 0 robustly against errors in q₄; it does not test the inputs. "
             "The paper itself records one unresolved discrepancy with AMMPV in pure Yang–Mills (0.8 in units of q₄) and that b_n for n ≥ 7 come from a single engine.\n")
    R.append("## 4. Comparison with earlier work (as quoted in the sources)\n")
    R.append("| Result | Value | Status | Where quoted |\n|---|---|---|---|")
    for r in read_csv("slope_ladder.csv"):
        R.append(f"| {r['entry']} | {float(r['Lambda']):.4f} | {r['status']} | {r['source']} |")
    R.append("\nFor [HP]: Hawking–Page (1983) and Witten (1998) for T_HP = 3/2πR; Sundborg (2000) and Aharony et al. (2004) for the free transition and the Landau criterion; Aharony et al. (2005) for pure Yang–Mills, "
             f"b = −5.7×10⁻⁴ λ_A² (= −1.4×10⁻⁴ λ²), against which [HP] finds a coefficient {q['b_over_lambda2']/(-5.7e-4/4):.1f} times larger for N = 4; Spradlin–Volovich (2005) for the one-loop shift; Harmark–Wilhelm (2018) for −11.50399. "
             "Full references are in `sources.md`. These works were not re-read in this session; the values are those quoted in [B] and [HP].\n")
    R.append("## 5. Figures\n")
    for k in sorted(CAP):
        R.append(f"![{k}](figures/{k}.png)\n\n{CAP[k]}\n")
    R.append("## 6. Reproducibility\n")
    R.append("Run from the package root, offline, with Python ≥ 3.10, numpy, scipy, mpmath, sympy, matplotlib:\n\n```\nfor s in s01_extract_sources s02_slope_endpoint s03_dirichlet_fd; do python code/$s.py; done\n"
             "python code/s04_functional_newton.py 4 40          # continuation in P (also c = 8, 12)\nfor P in 8 16 24 32 40 48 56 64; do python code/s04b_functional_homotopy.py $P 64; done\n"
             "for s in s05_table2_reanalysis s06_hp_hagedorn s07_hp_series_quartic s08_hp_landau s09_functional_analysis validate_all s10_figures s11_ledger_reports; do python code/$s.py; done\n```\n"
             "`research_notebook.ipynb` loads the saved results, re-runs the fast steps live and displays the figures. Data tables: `results/*.csv`, `results/*.json`.\n")
    R.append('## 7. The orbital observatory\n')
    R.append('Open `black_hole_research_lab.html` to enter the six-station observatory. Select a planet, an orbit card or a number key. The stations contain the two original papers, the executed notebook and eleven figures, the modular bound, the Hawking–Page calculation, the claim ledger and the dated research timeline. Both papers can be read offline inside the scene.\n\nThe visual edition uses Blender 5.3 and Three.js r160. A Schwarzschild null-ray integration supplies an illustrative image of an inclined accretion disk. Procedurally textured planets, orbiting dust and the star field provide navigation. The field display uses the calculated Dirichlet solution, and the potential curve responds to the weak-coupling controls. Distances, planetary sizes, disk brightness and the illustrative enhancement of |b| are display choices. The equations, figure files and numerical evidence retain their research definitions.\n\nThe editable Blender file and asset generator are in `scene/orbit/`. To rebuild the single-file HTML from the saved scientific data and visual assets, run `python code/s13_build_lab.py --visual-only`. All textures, scripts and PDF bytes are embedded.\n')
    R.append("## 8. Verification scope\n")
    R.append("See `verification_report.md` §4 and `claim_ledger.json`. In one sentence: closed forms, constants, the endpoint condition, finite-order functionals for c ≤ 64, the statistical reanalysis of Table 2, the free Hagedorn "
             "point, the series sums, the assembly of b and the Landau analysis were independently computed; the proofs of [B] Thm 3–5, the high-order Table 2 runs and the three-loop coefficients of [HP] were not, and no formal-proof rerun was possible.\n")
    open(os.path.join(ROOT, "research_report.md"), "w").write("\n".join(R) + "\n")
    print(f"ledger: {len(led)} claims; checks {npass}/{nchk}; validation {V['n_pass']}/{V['n']}; timeline events {len(ev)}")


if __name__ == "__main__":
    with Tee("s11_ledger_reports"):
        main()
