#!/usr/bin/env python3
r"""sunrise-genmass-evaluate.py -- two-loop sunrise, eps^0, the uniform per-puncture closed form at a FREE mass triple:
the --masses arm over the shared layer sunrise_empl.py (this bundle's rows 9-11, untouched), gated first on the four mass
sets of record and then on a FIFTH mass set, (1,1,3), that entered no fit.

WHAT IS EVALUATED
  E^(0)(t) = J[1,1,1]^(0)(t) / psihat1(t) = -C_{4,2}(t) - (6/(2 pi)^3) (1/3) sum_{j=1}^{3} [ W(z_j,1) - 8 W(z_j,2) ]
  -- the one formula the mass-family section prints for every assignment (its (36) in the served build).  sunrise_empl.py
  implements it for a generic triple: predict_E / predict_J take the masses as a parameter, the three rational coefficients
  [-1, -1/3, +8/3] are fixed (identified on (1,1,2), verified on (1,2,3) and (1,1,4)), ZERO free parameters at runtime.
  The served row scripts each pin their own masses_sq in their data file; this script is the command-line entry to the
  same library at ANY exact rational squared masses A,B,C and any Euclidean t < 0.  It adds no arithmetic to the value:
  every evaluation below is the library's predict_J / predict_E.

THE FIFTH MASS SET (sunrise-m113-data.json, beside this script; sha256-pinned below)
  (m1^2, m2^2, m3^2) = (1,1,3) is off every fitted / record triple ((1,1,1), (1,1,2), (1,2,3), (1,1,4)).  Its two
  reference values, at t = -3 and t = -6, are independent auxiliary-mass-flow results (goal 150 digits, eps order 11,
  4 threads, run direction NegRe) computed on a family file new to this mass set AFTER the formula's values at both
  points had been filed (the sha256 of that filing is carried in each point, as are the sha256 of the AMFlow input
  configuration and output file, the ball radius -- 160 / 159 digits in the ball -- and the goal-100 twin's agreement,
  110.1 / 109.5 digits).  Both points are flagged never_fit_mass_set and held_out_in_pslq_fit.  The (1,1,3) t = -1
  point puts the three punctures at exact 4-torsion (z = 1/4, 1/4, 1/2): the library evaluates it, no reference is
  shipped there and it is not a gate abscissa; the run says so when asked for it.

WHAT THE DEFAULT RUN CHECKS (exit 0 only if every leg passes)
  1. positive control: equal_mass_control(-3) -- the (1,1,1) marked-point machinery vs the independent classical
     Gamma_1(6) route (the row scripts' control, the library's own);
  2. the fitted sets' three data files (rows 9, 10, 11: (1,1,2), (1,2,3), (1,1,4); every reference point of the three
     fitted-set files, comparison only; the run prints the count) on the SAME code path
     that evaluates a free triple; bar: worst agreement STRICTLY > 30 digits AND relative error < 10^-30/2 (the row
     scripts' bar); one WORST line over the three files;
  3. the fifth set's data file (2 points, never in any fit): the same bar on its own line, each point with its
     provenance; the digit count the mass-family sentence states (paper_claims, measured over the never-fit points);
  4. with --masses A,B,C: the requested triple at every --point, printed at dps digits with the certified q-series
     truncation bound (BOUND, not estimate) and the frame data; when a shipped data file carries that triple at that t
     the agreement vs its reference is printed and gated at the same bar (the row's own gate line reproduced); when
     no shipped reference exists at the requested masses and t the run says so by name -- the value is then covered
     by the gates above and by the certified bound only.
  5. --check: every gated point and every requested point re-evaluated at dps + 60 (two-precision rule); a drift
     below dps - 12 agreeing digits fails by name.

FILES (beside this script; sha256-pinned below and REFUSED on any mismatch, before any computation)
  sunrise_empl.py             the shared Kronecker-eMPL layer (untouched; the same bytes the row scripts pin)
  sunrise-row09-data.json     row 9 (1,1,2) reference values (gate data only)
  sunrise-row10-data.json     row 10 (1,2,3) reference values
  sunrise-row11-data.json     row 11 (1,1,4) reference values
  sunrise-m113-data.json      the fifth set (1,1,3): 2 never-fit reference points with their AMFlow provenance
  The AMFlow family file of the fifth set is not shipped; it is named by its sha256 in each point's
  amflow_config_sha256 (the t = -3 file also stands as the family's configuration of record).

DOMAIN: Euclidean t < 0 (the library's; |q_C| >= 0.8995 refused explicitly).  Physical t > 0 is NOT wired.  A
reference point outside the domain in a --data file is listed by name and not gated.  --masses takes three positive
exact rationals (integers or p/q); m1^2 = m2^2 degeneracies are handled by the library's marked-point grouping.

USAGE
  python3 sunrise-genmass-evaluate.py                                    # default: dps 150, controls + the fitted sets (every reference point of the three files) + the fifth set (2 points)
  python3 sunrise-genmass-evaluate.py --masses 1,1,3 --point=-3 --point=-6      # the fifth set at its two reference points (agreement printed)
  python3 sunrise-genmass-evaluate.py --masses 1,1,2 --point=-3 --point=-7      # a fitted set: the row-9 reference lines reproduced
  python3 sunrise-genmass-evaluate.py --masses 1,1,5/2 --point=-3 --no-controls # any rational triple, any Euclidean t (no reference shipped)
  python3 sunrise-genmass-evaluate.py --masses 1,1,3 --point=-3 --dps 210 --check   # two-precision rule at dps + 60
  python3 sunrise-genmass-evaluate.py --data sunrise-m113-data.json      # gate ONE data file of the row form (masses from its masses_sq)
  python3 sunrise-genmass-evaluate.py --mutate                           # control: +8 -> 8(1+1e-12) in every gate evaluation; MUST exit 1
  --point uses the --point=-3 syntax for negatives; --no-controls skips the data-file tables (the equal-mass control stays).

EXIT CODES: 0 every gate passes; 1 a gate fails (what --mutate must produce); 2 usage error or a --point domain refusal
(named); 3 a pinned file's sha256 does not match, or a --data file is not of the row form (refused by name before any
computation on it); 4 a pinned file or mpmath is missing.

MEASURED WALLS (GNU time, one process, nice 10, a shared 96-core host at loadavg ~100; a quiet core is faster): see the
epilog of --help (the same table, written by the build from its captures).

mp.dps is set inside main() after argparse (module-level mpf footgun avoided).  Dependency: python3 + mpmath.
"""
import argparse
import hashlib
import json
import os
import sys
import time
from fractions import Fraction

EXIT_PASS, EXIT_FAIL, EXIT_USAGE, EXIT_PIN, EXIT_MISSING = 0, 1, 2, 3, 4
HERE = os.path.dirname(os.path.abspath(__file__))

# --- PINS (script-emitted from the shipped bytes; sha256 of every file this front end reads in place) ---
PINS = {
    "sunrise_empl.py": "1928e35f0edd8197fc10550ea439acaa21e5c4ae4136396b0493fe49331f62bf",
    "sunrise-row09-data.json": "564a71425c7404b4f06b3d4681546cf864a85fa15bf3e13194167a69f59b3d40",
    "sunrise-row10-data.json": "90e8988c95e4e9435648f7f3ce3a10562bb933a80156d5702528b8730c5910d7",
    "sunrise-row11-data.json": "c1eb77df0da2f182b98bdcea7d2616cf02e2d758774679f53dc585f5258af7f0",
    "sunrise-m113-data.json": "6015e8712e17adeb3b113217711d8bd1a730c102414935c4a982c2206a31930f",
}
# --- END PINS ---
FITTED_FILES = ["sunrise-row09-data.json", "sunrise-row10-data.json", "sunrise-row11-data.json"]
NEVER_FIT_FILE = "sunrise-m113-data.json"
FITTED = {(1, 1, 1), (1, 1, 2), (1, 2, 3), (1, 1, 4)}   # the four mass sets of record (rows 8-11)
FOUR_TORSION = ((Fraction(1), Fraction(1), Fraction(3)), Fraction(-1))   # the (1,1,3) t = -1 special point (stated, not gated)

# measured walls (GNU time wall clock, the delivered bytes; written by the build from its captures)
WALLS = {
    "default (dps 150: control + 17 fitted-set points + the 2 never-fit points)": "3.29 s",
    "--check (the 19 gated points re-evaluated at dps 210)": "6.56 s",
    "--mutate (the control run; exit 1)": "3.25 s",
    "--masses 1,1,3 --point=-3 --point=-6 --dps 150": "3.58 s",
    "--masses 1,1,3 --point=-3 --point=-6 --dps 150 --check": "8.17 s",
    "--masses 1,1,3 --point=-3 --point=-6 --dps 210": "3.82 s",
    "--data sunrise-m113-data.json (the fifth set alone)": "0.47 s",
    "--masses 1,1,2 --point=-3 --point=-7 (a fitted set: the row-9 reference lines reproduced)": "3.78 s",
    "--masses 1,1,5/2 --point=-3 --no-controls (no reference shipped)": "0.34 s",
}


def _pinned_bytes(path, pin):
    """Read a companion file and refuse it unless its sha256 matches the pin (the row scripts' form)."""
    name = os.path.basename(path)
    if not os.path.exists(path):
        print(f"MISSING: {name} must sit beside this script (download it from the same page); nothing computed")
        sys.exit(EXIT_MISSING)
    raw = open(path, "rb").read()
    sha = hashlib.sha256(raw).hexdigest()
    if sha != pin:
        print(f"REFUSED: {name} sha256 {sha} ({len(raw)} bytes) does not match the pin {pin} -- the file was altered "
              f"or is not the released version; nothing computed")
        sys.exit(EXIT_PIN)
    return raw


def check_pins():
    """Every pinned file verified before any computation; returns {name: raw bytes}."""
    raw = {}
    for name, pin in PINS.items():
        raw[name] = _pinned_bytes(os.path.join(HERE, name), pin)
    return raw


def _frac(s, what, ap):
    try:
        f = Fraction(str(s).strip())
    except (ValueError, ZeroDivisionError):
        ap.error(f"{what} must be an exact rational (integer or p/q); got {s!r}")
    return f


def parse_masses(s, ap):
    parts = s.split(",")
    if len(parts) != 3:
        ap.error(f"--masses takes THREE comma-separated squared masses A,B,C (got {len(parts)}: {s!r})")
    m = tuple(_frac(p, "--masses", ap) for p in parts)
    if any(v <= 0 for v in m):
        ap.error(f"--masses must be positive squared masses (got {s})")
    return m


def _mpf_frac(mp, f):
    """exact rational -> mpf at the CURRENT dps (numerator / denominator, the arm's tofrac)."""
    return mp.mpf(f.numerator) / mp.mpf(f.denominator)


def masses_from_fracs(mp, msq):
    """sqrt of the squared masses at the CURRENT dps (re-call after any dps change)."""
    return tuple(mp.sqrt(_mpf_frac(mp, m)) for m in msq)


def _t_label(gp):
    return f"{gp['t_num']}" if gp["t_den"] == 1 else f"{gp['t_num']}/{gp['t_den']}"


def _label(msq):
    return "(" + ",".join(str(m) for m in msq) + ")"


def row_form(data, name):
    """The row form a data file must carry: masses_sq (three positive exact rationals) and gate_points (each with t_num,
    t_den, oracle_mid, oracle_digits, held_out_in_pslq_fit, source).  Returns a refusal message or None."""
    if not isinstance(data, dict) or "masses_sq" not in data or "gate_points" not in data:
        return f"{name} is not of the row form (no masses_sq / gate_points)"
    ms = data["masses_sq"]
    if not isinstance(ms, list) or len(ms) != 3:
        return f"{name}: masses_sq must list three squared masses (got {ms!r})"
    try:
        if any(Fraction(str(m)) <= 0 for m in ms):
            return f"{name}: masses_sq must be positive (got {ms!r})"
    except (ValueError, ZeroDivisionError):
        return f"{name}: masses_sq must be exact rationals (got {ms!r})"
    if not isinstance(data["gate_points"], list) or not data["gate_points"]:
        return f"{name}: gate_points must be a non-empty list"
    need = ("t_num", "t_den", "oracle_mid", "oracle_digits", "held_out_in_pslq_fit", "source")
    for i, gp in enumerate(data["gate_points"]):
        missing = [k for k in need if not isinstance(gp, dict) or k not in gp]
        if missing:
            return f"{name}: gate_points[{i}] lacks {missing} (the row form)"
    return None


def point_kind(gp):
    if gp.get("never_fit_mass_set"):
        return "never-fit mass set"
    if gp.get("held_out_in_pslq_fit"):
        return "held out of the PSLQ fit"
    return "fit/verify point"


def gate_file(mp, R, name, data, mutate, refs):
    """The record-point table of ONE data file on the free-triple code path: every gate point evaluated with predict_J at
    the file's masses, compared with its reference midpoint (the arm's line form).  Returns (worst, worst_rel, rows,
    skipped); rows carry (t, J, d, cap, gp) for --check; refs gains (masses, t) -> (name, gp) for the --masses lookup."""
    msq = tuple(Fraction(str(m)) for m in data["masses_sq"])
    ms = masses_from_fracs(mp, msq)
    worst = None
    worst_rel = mp.mpf(0)
    rows = []
    skipped = []
    for gp in data["gate_points"]:
        tq = Fraction(gp["t_num"], gp["t_den"])
        refs[(msq, tq)] = (name, gp)
        t = mp.mpf(gp["t_num"]) / mp.mpf(gp["t_den"]); diag = {}
        if tq >= 0:
            skipped.append(_t_label(gp))
            print(f"  record set {_label(msq)} t = {mp.nstr(t, 8):>8}: NOT GATED (t >= 0: only Euclidean t < 0 is wired in this script)")
            continue
        J = R.predict_J(t, ms, diag=diag, mutate=mutate)
        rel = abs(J - mp.mpf(gp["oracle_mid"])) / abs(mp.mpf(gp["oracle_mid"]))
        dd = int(-mp.log10(rel)) if rel > 0 else mp.mp.dps
        cap = min(gp["oracle_digits"], mp.mp.dps)
        worst = dd if worst is None else min(worst, dd)
        worst_rel = max(worst_rel, rel)
        rows.append((t, J, dd, cap, gp))
        print(f"  record set {_label(msq)} t = {mp.nstr(t, 8):>8}: agree {dd:>4} d (cap {cap}; {point_kind(gp)}; |q_C| {mp.nstr(abs(diag['qC']), 4)}, Nq {diag['Nq']})")
    return worst, worst_rel, rows, skipped


def bar_line(mp, worst, worst_rel):
    """The row scripts' bar: worst STRICTLY > 30 digits AND worst relative error < 10^-30/2 (directed-rounding slack)."""
    bar_rel = mp.mpf(10) ** (-30) / 2
    ok = worst is not None and (worst > 30) and (worst_rel < bar_rel)
    return ok, (f"[{'PASS' if ok else 'FAIL'}: strict bar > 30 d AND worst-rel {mp.nstr(worst_rel, 3)} < 10^-30/2, directed-rounding slack]")


def main():
    ap = argparse.ArgumentParser(
        description="the uniform per-puncture sunrise closed form (eps^0) at a free mass triple, over the untouched shared "
                    "layer; gated on the four fitted / record mass sets and on the fifth, never-fit set (1,1,3) first",
        epilog="measured walls (GNU time wall clock, one process, nice 10, a shared 96-core host at loadavg ~100): "
               + "; ".join(f"{k}: {v}" for k, v in WALLS.items()) + ".  Exit codes: 0 PASS, 1 FAIL, 2 usage / domain refusal, "
               "3 REFUSED by name (a pin mismatch, a --data file not of the row form), 4 a pinned file MISSING.")
    ap.add_argument("--masses", default=None, metavar="A,B,C", help="three exact rational squared masses (integers or p/q); e.g. 1,1,3")
    ap.add_argument("--point", action="append", default=[], metavar="T", help="Euclidean t < 0, exact rational (use --point=-3 for negatives); repeatable")
    ap.add_argument("--dps", type=int, default=150, help="reported decimal digits (default 150; +10 guard digits internally)")
    ap.add_argument("--check", action="store_true", help="two-precision rule: re-evaluate every gated and requested point at dps+60 and diff")
    ap.add_argument("--mutate", action="store_true", help="control: +8 -> 8(1+1e-12) in every gate and --point evaluation (never in the equal-mass control); the run must exit nonzero")
    ap.add_argument("--no-controls", action="store_true", help="skip the data-file gate tables (the equal-mass control stays); the --masses value only")
    ap.add_argument("--data", default=None, metavar="FILE", help="gate ONE data file of the row form instead of the shipped four (its masses_sq; a shipped file keeps its pin)")
    args = ap.parse_args()
    if args.dps < 30:
        ap.error("--dps must be >= 30 (the gate bar is 30 digits)")   # argparse exits 2
    if args.point and not args.masses and not args.data:
        ap.error("--point needs --masses A,B,C (or --data FILE, whose masses_sq it takes)")
    if args.no_controls and not (args.masses or args.data):
        ap.error("--no-controls needs --masses or --data (nothing would be gated)")
    try:
        sys.stdout.reconfigure(line_buffering=True)
    except AttributeError:
        pass
    try:
        import mpmath as mp
    except ImportError:
        print("MISSING: python3 module mpmath (pip install mpmath); nothing computed")
        return EXIT_MISSING

    raw = check_pins()   # refused before any computation
    sys.path.insert(0, HERE)
    import sunrise_empl as R  # noqa: E402
    print(f"[pins] {len(PINS)} shipped files verified by sha256: " + ", ".join(f"{n} {p[:16]}..." for n, p in PINS.items()))
    t0 = time.time()
    mp.mp.dps = args.dps + 10  # guard digits; gate digits reported vs the references
    mutate = bool(args.mutate)
    msq = parse_masses(args.masses, ap) if args.masses else None
    pts = [_frac(p, "--point", ap) for p in args.point]
    msq_key = tuple(int(m) for m in msq) if msq and all(m.denominator == 1 for m in msq) else None

    # the data files this run gates (the row form; a --data file replaces the shipped set and takes its masses_sq)
    tables = []
    if args.data:
        if os.sep not in args.data and args.data in PINS:
            dp = os.path.join(HERE, args.data)   # a bare shipped name resolves to the shipped file (pinned)
        else:
            dp = args.data if os.path.isabs(args.data) else os.path.join(os.getcwd(), args.data)
        base = os.path.basename(dp)
        shipped = os.path.realpath(dp) == os.path.realpath(os.path.join(HERE, base)) and base in PINS
        if shipped:
            d_raw = raw[base]; d_note = "shipped, pinned"
        else:
            if not os.path.exists(dp):
                print(f"MISSING: --data {args.data}; nothing computed")
                return EXIT_MISSING
            d_raw = open(dp, "rb").read(); d_note = f"sha256 {hashlib.sha256(d_raw).hexdigest()}, not a shipped file (unpinned)"
        try:
            d = json.loads(d_raw)
        except ValueError as e:
            print(f"REFUSED: --data {base} is not JSON ({e}); nothing computed")
            return EXIT_PIN
        why = row_form(d, base)
        if why:
            print(f"REFUSED: {why}; nothing computed")
            return EXIT_PIN
        tables.append((base, d, d_note))
        if msq is None:
            msq = tuple(Fraction(str(m)) for m in d["masses_sq"])
            msq_key = tuple(int(m) for m in msq) if all(m.denominator == 1 for m in msq) else None
    elif not args.no_controls:
        for name in FITTED_FILES + [NEVER_FIT_FILE]:
            d = json.loads(raw[name])
            why = row_form(d, name)
            if why:
                print(f"REFUSED: {why}; nothing computed")
                return EXIT_PIN
            tables.append((name, d, "shipped, pinned"))

    print("=" * 78)
    if msq is not None:
        kind = ("FITTED/record mass set" if msq_key in FITTED else
                "NEVER-FIT mass set, the shipped fifth set (off every record triple (1,1,1),(1,1,2),(1,2,3),(1,1,4))" if msq_key == (1, 1, 3) else
                "NEVER-FIT mass set (off every record triple (1,1,1),(1,1,2),(1,2,3),(1,1,4) and off the shipped fifth set (1,1,3))")
        print(f"formula at squared masses {_label(msq)} -- {kind}")
    else:
        print("formula at the four mass sets of record and at the fifth, never-fit set (1,1,3) -- the shipped data files")
    print(f"dps = {mp.mp.dps}")
    print("=" * 78)
    if mutate:
        print("[mutate] CONTROL RUN: per-puncture coefficient +8 -> 8 (1 + 1e-12) in every gate-table and --point evaluation "
              "(the equal-mass control untouched); this run MUST fail and exit nonzero")
    failures = []

    # (1) the served positive control (the library's own, as the row scripts run it)
    Em, Er, agree = R.equal_mass_control(mp.mpf(-3))
    ctrl_ok = agree >= min(30, mp.mp.dps - 8)
    if not ctrl_ok:
        failures.append(f"equal-mass control t=-3 agree {agree}d < bar {min(30, mp.mp.dps - 8)}d")
    print(f"positive control @ t=-3.0 (1,1,1): marked-point vs Gamma_1(6) classical route agree {agree} digits [{'PASS' if ctrl_ok else 'FAIL'}]")

    # (2)/(3) the data-file tables on the free-triple code path
    refs = {}
    checks = []       # (label, t, msq, J_low) for --check
    fitted_worst, fitted_rel, n_fitted = None, mp.mpf(0), 0
    for name, d, note in tables:
        dm = tuple(Fraction(str(m)) for m in d["masses_sq"])
        never = all(gp.get("never_fit_mass_set") for gp in d["gate_points"])
        print(f"\n{name} ({note}): {_label(dm)}, {len(d['gate_points'])} reference points" + (" -- never in any fit" if never else ""))
        worst, worst_rel, rows, skipped = gate_file(mp, R, name, d, mutate, refs)
        checks += [(f"{name} t = {_t_label(gp)}", t, dm, J) for (t, J, dd, cap, gp) in rows]
        if never or args.data or name == NEVER_FIT_FILE:
            for (t, J, dd, cap, gp) in rows:
                if "amflow_goal_digits" in gp:
                    print(f"    provenance t = {_t_label(gp)}: AMFlow goal {gp['amflow_goal_digits']} digits, eps order {gp['amflow_eps_order']}"
                          + (f", {gp['amflow_n_thread']} threads" if "amflow_n_thread" in gp else "")
                          + f", ball radius {gp['amflow_ball_radius']} ({gp['amflow_ball_digits']} digits in the ball); input configuration sha256 "
                          f"{gp['amflow_config_sha256'][:16]}..., output sha256 {gp['amflow_output_sha256'][:16]}..."
                          + (f"; the goal-{gp['twin_goal_digits']} twin agrees to {gp['twin_pair_agree_digits_float']:.1f} digits" if "twin_goal_digits" in gp else "")
                          + (f"; the formula's values were filed before the run (filing sha256 {gp['prediction_filed_before_the_run_sha256'][:16]}...)" if "prediction_filed_before_the_run_sha256" in gp else "")
                          + " (full values in the data file)")
            ok, bl = bar_line(mp, worst, worst_rel)
            if not ok:
                failures.append(f"{name} {_label(dm)}: worst agree {worst}d not STRICTLY > 30d, or rel error {mp.nstr(worst_rel, 3)} not < 10^-30/2")
            per = "; ".join(f"t = {_t_label(gp)}: {dd} digits (cap {cap})" for (t, J, dd, cap, gp) in rows)
            print(f"  {'fifth set' if never else 'data file'} {_label(dm)}{' (never in any fit)' if never else ''}: {per}; worst {worst} digits over "
                  f"{len(rows)} points{' (' + str(len(skipped)) + ' not gated: t = ' + ', '.join(skipped) + ')' if skipped else ''}  {bl}")
            # the digit count the mass-family sentence STATES (paper_claims), measured over the named subset
            for cl in d.get("paper_claims", []):
                sub = cl.get("measured_over")
                if sub == "never_fit_points":
                    subset = [r for r in rows if r[4].get("never_fit_mass_set")]
                elif sub == "held_out_points":
                    subset = [r for r in rows if r[4].get("held_out_in_pslq_fit")]
                else:
                    failures.append(f"claim '{cl['text']}': measured_over = {sub!r} is neither 'never_fit_points' nor 'held_out_points'")
                    continue
                if not subset:
                    failures.append(f"claim '{cl['text']}': no point of {name} is flagged {sub}")
                    continue
                need = int(cl["held_out_digits"])
                w = min(r[2] for r in subset)
                cap = min(min(r[4]["oracle_digits"] for r in subset), mp.mp.dps)
                if cap >= need:
                    cl_ok = w >= need - 1   # one digit slack: the reference's own last digit
                    if not cl_ok:
                        failures.append(f"claim '{cl['text']}': worst agreement {w}d < {need - 1}d")
                    print(f"  stated digit count '{cl['text']}' [{cl['where']}]: measured here as this run's worst agreement over the "
                          f"{len(subset)} {sub.replace('_', ' ')} above = {w} digits (cap {cap}; bar {need} - 1) [{'PASS' if cl_ok else 'FAIL'}]")
                else:
                    print(f"  stated digit count '{cl['text']}' [{cl['where']}]: not testable at this precision (cap {cap} < {need}; rerun with --dps {need}) [SKIP]")
        else:
            n_fitted += len(rows)
            if worst is not None:
                fitted_worst = worst if fitted_worst is None else min(fitted_worst, worst)
                fitted_rel = max(fitted_rel, worst_rel)
            if name == FITTED_FILES[-1] and n_fitted:
                ok, bl = bar_line(mp, fitted_worst, fitted_rel)
                if not ok:
                    failures.append(f"fitted sets' table worst {fitted_worst}d not STRICTLY > 30d, or rel error {mp.nstr(fitted_rel, 3)} not < 10^-30/2")
                print(f"\n  WORST agreement over the three served data files (fitted sets (1,1,2), (1,2,3), (1,1,4); every reference point, "
                      f"{n_fitted} points): {fitted_worst} digits  {bl}")

    # (4) the requested triple
    results = []
    if msq is not None and pts:
        ms = masses_from_fracs(mp, msq)
        for tq in pts:
            t = _mpf_frac(mp, tq); diag = {}
            try:
                E = R.predict_E(t, ms, diag=diag, mutate=mutate)
            except ValueError as e:
                print(f"\n--point t = {tq}: REFUSED ({e})")
                return EXIT_USAGE   # a domain refusal exits 2 by name (never a silent rc 0)
            J = diag["psihat1"] * E
            results.append((tq, t, J, E))
            zm = [(mp.nstr(z.real, 12), mp.nstr(z.imag, 3), k) for z, k in diag["z_mults"]]
            print(f"\n--masses {_label(msq)} --point t = {mp.nstr(t, 12)}:")
            print(f"  E^(0) = J/psihat1 = {mp.nstr(E, mp.mp.dps)}")
            print(f"  psihat1 = {mp.nstr(diag['psihat1'], 30)}")
            print(f"  J^(0)  = {mp.nstr(J, mp.mp.dps)}")
            print(f"  frame: |q_C| = {mp.nstr(abs(diag['qC']), 8)}, Nq = {diag['Nq']}, punctures (Re z, Im z, mult) = {zm}")
            print(f"  certified bound: |Delta E| <= {mp.nstr(diag['err_E'], 3)}, |Delta J| <= {mp.nstr(diag['psihat1'] * diag['err_E'], 3)}  (q-series truncation; BOUND, not estimate)")
            if (msq, tq) == FOUR_TORSION:
                print("  note: at (1,1,3), t = -1 the three punctures sit at exact 4-torsion (z = 1/4, 1/4, 1/2); no reference is shipped "
                      "there and it is not a gate abscissa (evaluated, not gated)")
            ref = refs.get((msq, tq))
            if ref is None and not args.data and args.no_controls:
                # the shipped files were not tabulated: look the point up without evaluating them
                for name in FITTED_FILES + [NEVER_FIT_FILE]:
                    d = json.loads(raw[name])
                    if tuple(Fraction(str(m)) for m in d["masses_sq"]) == msq:
                        for gp in d["gate_points"]:
                            if Fraction(gp["t_num"], gp["t_den"]) == tq:
                                ref = (name, gp)
            if ref is not None:
                name, gp = ref
                rel = abs(J - mp.mpf(gp["oracle_mid"])) / abs(mp.mpf(gp["oracle_mid"]))
                dd = int(-mp.log10(rel)) if rel > 0 else mp.mp.dps
                cap = min(gp["oracle_digits"], mp.mp.dps)
                ok, bl = bar_line(mp, dd, rel)
                if not ok:
                    failures.append(f"--masses {_label(msq)} t = {tq} vs the shipped reference in {name}: agree {dd}d not STRICTLY > 30d")
                print(f"  vs the shipped reference in {name} ({gp['source']}): agree {dd} digits (cap: {cap} = min(oracle {gp['oracle_digits']}d, dps); "
                      f"{point_kind(gp)})  {bl}")
            else:
                print(f"  [reference] NO independent reference is shipped at squared masses {_label(msq)}, t = {tq}: the value is covered by the "
                      f"gate tables above and the certified truncation bound only (the shipped references sit at (1,1,2), (1,2,3), (1,1,4) and (1,1,3))")
    print(f"\nmeasured wall time: {time.time() - t0:.2f} s")

    # (5) the two-precision rule
    if args.check and (checks or results):
        old = mp.mp.dps; mp.mp.dps = old + 60
        print(f"\n--check: re-evaluating {len(checks)} gated and {len(results)} requested points at dps {mp.mp.dps} ...")
        okall = True
        t1 = time.time()
        hi_masses = {}
        for label, t, dm, J in checks:
            if dm not in hi_masses:
                hi_masses[dm] = masses_from_fracs(mp, dm)   # re-sqrt at the new dps
            Jh = R.predict_J(t, hi_masses[dm], mutate=mutate)
            dd = abs(Jh - J) / abs(Jh); stab = int(-mp.log10(dd)) if dd > 0 else mp.mp.dps
            ok = stab >= old - 12; okall &= ok
            print(f"  {label:>34}: low-dps value stable to {stab} digits (target ~{old}) [{'ok' if ok else 'DRIFT'}]")
        if results:
            ms_hi = masses_from_fracs(mp, msq)
            for tq, t, J, E in results:
                Jh = R.predict_J(_mpf_frac(mp, tq), ms_hi, mutate=mutate)
                dd = abs(Jh - J) / abs(Jh); stab = int(-mp.log10(dd)) if dd > 0 else mp.mp.dps
                ok = stab >= old - 12; okall &= ok
                print(f"  {'--masses ' + _label(msq) + ' t = ' + str(tq):>34}: low-dps value stable to {stab} digits (target ~{old}) [{'ok' if ok else 'DRIFT'}]")
        mp.mp.dps = old
        print(f"--check wall time: {time.time() - t1:.2f} s")
        print(f"--check verdict: {'PASS' if okall else 'FAIL'}")
        if not okall:
            failures.append("--check two-precision DRIFT (see table)")

    if failures:
        print(f"\n[gate] FAIL (exit {EXIT_FAIL}): " + "; ".join(failures))
        return EXIT_FAIL
    legs = ["equal-mass control"]
    if n_fitted:
        legs.append(f"the fitted sets' record-point table (worst {fitted_worst} d over {n_fitted} points, strict bar > 30)")
    legs += [f"{name} {_label(tuple(Fraction(str(m)) for m in d['masses_sq']))} (strict bar > 30)" for name, d, _ in tables
             if name == NEVER_FIT_FILE or args.data or all(gp.get('never_fit_mass_set') for gp in d['gate_points'])]
    if results:
        legs.append(f"the requested {_label(msq)} value{'s' if len(results) > 1 else ''} at {len(results)} point{'s' if len(results) > 1 else ''}"
                    + (" (gated where a shipped reference exists)"))
    print(f"\n[gate] PASS: " + ", ".join(legs) + (" and the two-precision --check" if args.check else ""))
    return EXIT_PASS


if __name__ == "__main__":
    sys.exit(main())
