#!/usr/bin/env python3
"""icc-genmass-evaluate.py -- the ice-cream cone (ICC) top master T(x) at eps^0 at ARBITRARY exact rational
squared masses (m1^2, m2^2, m3^2, m4^2) = (1, m2, m3, m4), any Euclidean x < -1/2, from a boundary DERIVED at
runtime at those masses -- the generic-mass cone off the reference configuration (1,2,3,5) that icc-evaluate.py
serves.  2026-09-06: icc-evaluate.py cross-references this script and checks the pair before serving --masses
(it reads this file's PINS entry for it); this file pins icc-evaluate.py's sha256 and refuses a mismatch (exit 3).
A sibling front end over the vendored evaluator of record (vendor_row16_genmass/, every file sha256-pinned below).

WHAT IS COMPUTED, AND HOW IT IS GATED
  Route 1 (the value): the 19-master eps-graded differential equation of the cone in the external invariant x,
  with its connection specialized at the requested masses, transported by high-order local Taylor steps from
  x = -1 to x.  The x = -1 boundary (46 entries, eps^-2..eps^0) is runtime-derived at these masses in two parts:
    * 21 covariant entries (tadpole^2 closed forms, triangle bubble-kernel quadratures with the generalized kernel
      Q(a) = m2 + a(2 - m2) - a^2, sunrise scoop spectral integrals) -- computed live on every run;
    * 25 cusp-solve entries (masters 6,7,8,12,13,14,15,16,17,18) -- the transported state at x = -1 of the
      infinity-cusp analytic solve at these masses (exact pole layers, the four slave resonance slots from the
      expansion-by-regions engine, tau0 = ln(m3^2 m4^2) W, the Mellin conditions); read from the mass pack's
      cusp receipt at this dps when one is shipped, or derived in-process with --derive-boundary.
  Route 2 (the in-house gate, by object): the direct quadrature of the materialized relative-period integral of
  the graph at the SAME masses and x (certified fail-closed quadratures), at a lower working precision.
  Cross-checks printed and gated on every run: route 1 vs route 2; the transported scoop vs a live Bessel-moment
  quadrature; the cusp-transported covariant masters vs the live seeds; the cusp solve's tau1 = 2W identity.
  Independent reference: at squared masses (1,3,2,7) and x = -2 the pack ships the AMFlow value of the same
  quantity (two goals, 60 and 100 digits, agreeing to ~87 digits); at (1,5/2,1/2,3) and x = -2 likewise (goals 60
  and 100, the top master's eps^0 agreeing to 87 digits and every one of the 19 masters to at least 85; the
  dps-60 value this script prints there was in print before that AMFlow run existed and reproduces it to 51
  digits, the evaluator's own dps-60 floor, which is the bar); at the reference masses (1,2,3,5), x = -2, the
  reference is the same independent string icc-evaluate.py carries.  Anywhere else NO independent reference is
  shipped and the run says so by name: the value is then gated by route 2 and the scoop cross-check only.

MASS PACKS (vendor_row16_genmass/masses/<tag>/): m1_3_2_7 (the fixture: coef, layers, slots, cusp receipts at
  dps 30 and 60, reference), m1_5h_1h_3 (the second configuration (1,5/2,1/2,3): the same seven files, its own
  AMFlow reference included; 2026-09-06) and m1_2_3_5 (the reference configuration: layers, slots, cusp receipt at
  dps 30; the connection is the served icc-transport-data.json).  A pack is found by the masses its cfg.json
  declares, not by its directory name (--masses 1,5/2,1/2,3 resolves to m1_5h_1h_3).  Other masses need the
  derivation chain, which specializes
  the symbolic connection from the 59.9 MB witness A_symbolic.json that is NOT distributed with this bundle
  (sha256-pinned by icc_genmass_lib.py): pass --witness PATH (or set ICC_A_SYMBOLIC_PATH) to a sha-matching
  copy and the chain derives layers (exact linear algebra), slots (regions engine), the specialized connection
  with its singularity census, the cusp solve and the value -- else the run refuses by name.

USAGE
  python3 icc-genmass-evaluate.py                                   # = --masses 1,3,2,7 --point=-2 --dps 30
  python3 icc-genmass-evaluate.py --masses 1,3,2,7 --point=-2 --dps 60
  python3 icc-genmass-evaluate.py --masses 1,5/2,1/2,3 --point=-2 --dps 60   # the second configuration vs its AMFlow reference
  python3 icc-genmass-evaluate.py --masses 1,2,3,5 --point=-2       # the positive control vs the served reference
  python3 icc-genmass-evaluate.py --masses 1,3,2,7 --point=-3       # any Euclidean x; no independent reference
  python3 icc-genmass-evaluate.py --masses 1,2,3,5 --point=-2 --dps 60 --derive-boundary
  python3 icc-genmass-evaluate.py --masses 1,M2,M3,M4 --witness A_symbolic.json --workdir W   # masses without a pack
  --masses takes FOUR comma-separated squared masses; m1^2 = 1 is the record's normalization (refused otherwise).
  CURE 2026-09-09: the in-process cusp solve's transport order is 90 up to dps 100 (every shipped pack and record run
  unchanged) and ceil(1.7 dps) + 20 above it, so the 'cusp-transported covariant masters vs live seeds' cross-check keeps pace with its dps - 11 bar.
  --route2-dps R (default 15 at dps <= 30, else min(40, dps - 20)); --slots-dps (default max(60, dps));
  --workdir DIR for the derived receipts (default: a fresh temporary directory, printed); --out JSON (never
  overwrites).

EXIT CODES  0 PASS (every gate met) | 1 FAIL (a gate missed, named) | 2 usage | 3 REFUSED by name (a pin
  mismatch, a point outside the domain, masses without a pack and without the witness, m1^2 != 1) | 4 a pinned
  file MISSING.

MEASURED WALLS (one process, nice 10, a shared 96-core host at loadavg ~120-140; a quiet core is faster):
  see the epilog of --help (the same table).
"""
import argparse
import hashlib
import json
import os
import re
import subprocess
import sys
import tempfile
import time
from fractions import Fraction as F

HERE = os.path.dirname(os.path.abspath(__file__))
VENDOR = os.path.join(HERE, "vendor_row16_genmass")
RC_FAIL, RC_USAGE, RC_REFUSED, RC_MISSING = 1, 2, 3, 4
REFERENCE_MASSES = (F(2), F(3), F(5))

# --- PINS (script-emitted from the shipped bytes; sha256 of every vendored file and of the served files this
# --- front end uses in place) ---
PINS = {
    "icc-evaluate.py": "71b0d3f5661cf09d4f0d72e6e1cd5bc0e8c356208ff6c399a5b31b4ab5a995ed",
    "icc-transport-data.json": "c72207a9fbfc29208bcfe425b8a029ba643da2ba3602129a8bc882593ea1e6a8",
    "icc_blib.py": "fab5fea1dd5121d3abaefb6ea89684c7591c4d0ab9b7ed7bbde25837cbfaf326",
    "icc_genmass_lib.py": "47fcf43af810884b5ffe5b5870d0b0900797c80d6977a36289db8a98f4ae79e3",
    "icc_layers_generic.json": "4420ef93c24999c70dbb5cc016c005c04c8128ebc5e25b8f4876d099daad3f72",
    "icc_scooplib.py": "e44c3e82bd45a1d07e7a7615d8b7cb0fb579ce9611ca1606c786d71a85cefd4b",
    "row16_coupled.py": "99b971e06b2c397b667d5aeffa6e93f5f73db26f80cb259979c6527495a38885",
    "series_ring.py": "44f2ca91a1986b1e8cff627bcf1603f4ed42e2a36ddc8480d8ea9d3c3bc1f1e0",
    "vendor_row16_genmass/b1gen/assemble.py": "5b28c65b70985c4c218a807ce26cc2bc68d883eae5800f3fd42d9206e944f737",
    "vendor_row16_genmass/b1gen/massparams.py": "e14c05cde9ab127ad48a6685d4655155e097bdb4551044483409f71792950c17",
    "vendor_row16_genmass/b1gen/parametric.py": "669cd753c2295b3a7608245bd513e76d45b4f9e6afe0301ccfbd83e96ef7b707",
    "vendor_row16_genmass/b1gen/reduction.py": "79ea9aa9ea9df0f5880f9f9050277c7d581eb4182810785cb6a3d71b462443d6",
    "vendor_row16_genmass/b1gen/regions.py": "bea5fc8b511c081001460a14d0a3d9febfd36faa7c42b2632c8ac6d40c1a49ea",
    "vendor_row16_genmass/b1gen/slots_gen.py": "b2160bab56f4932c36faf660997c557e25d73a1f4ff671cbde75452e7048b99b",
    "vendor_row16_genmass/elim_series.py": "af3f2758175313be8735f11b7779f5a8357c0144b15100a84dbe3b9d0fcf1115",
    "vendor_row16_genmass/eval_row16.py": "824394aa84f88bea8a953137d1d76947f6424ebe75da80fd91774b29e8ff4983",
    "vendor_row16_genmass/gen_layers.py": "749450d00481769e85ced8c7b02a769480166a18aaf51feed6109219f141601d",
    "vendor_row16_genmass/icc_gen_cfg.py": "b7d0b39fda7e2d47e614a053de26d2c940157fa8db92e305eb812a14ffd62cd8",
    "vendor_row16_genmass/icc_genmass_eval.py": "e86aa1acede464b06260b2c0a04fcec504124d92a51f0d5adc488ba460a4eaa8",
    "vendor_row16_genmass/make_gen_cfg.py": "52c566625870f4f2d945081d9764b6934438eb9a1c18042212a68b30eb859b43",
    "vendor_row16_genmass/masses/m1_2_3_5/cfg.json": "bc1ce6af9ec480a675a973222c7c0d2b8afdb01c7cb93ebad1d19d621764d31b",
    "vendor_row16_genmass/masses/m1_2_3_5/cusp_dps30.json": "883d8d47fc5004cd81602b15c0b7d5dd5d37fe8b6ab3c7141756cb27b6800fd6",
    "vendor_row16_genmass/masses/m1_2_3_5/layers.json": "705801c401ede4dad54311193dbf7b8dc10048e9552ab6ebffd9833fe5e0ad82",
    "vendor_row16_genmass/masses/m1_2_3_5/slots.json": "a1f7de2d60fa321f250cd8ac625c55d2ea0b222e67be1e0daa13990c8e89cdbe",
    "vendor_row16_genmass/masses/m1_3_2_7/cfg.json": "0a4161774d58984f8d888023367bf8fbcf16c885319de9ac10f0c54108ae80de",
    "vendor_row16_genmass/masses/m1_3_2_7/coef.json": "c0229ec12286c23f2ea6d64927662594050bd9c513a4fa0a51dee84cb37d8071",
    "vendor_row16_genmass/masses/m1_3_2_7/cusp_dps30.json": "23b9d9f297ae3ec1d4ffebd0ff3322dd550297fd7f0c4a3a82dfaa9b01fd3377",
    "vendor_row16_genmass/masses/m1_3_2_7/cusp_dps60.json": "345d8538a72f74fed07513e549ae1833eba3d52048e86864085822074eab9b6b",
    "vendor_row16_genmass/masses/m1_3_2_7/layers.json": "eab67c296dc31d3ba1e815670b3ebd901e283ce591ba3a486609ff0f0b5a4a9a",
    "vendor_row16_genmass/masses/m1_3_2_7/reference.json": "1955ee9d92b772bb55187a2019bf886e130d1fc4ba2c79f88218b882ad798eed",
    "vendor_row16_genmass/masses/m1_3_2_7/slots.json": "fc3c1efd9677d985ca212529d2d51a9d0b1320c65764b25acf9ad7b8ace74f2b",
    "vendor_row16_genmass/masses/m1_5h_1h_3/cfg.json": "4240473d59958aafce6cafe25b144acd326094556ba1366755327ae82960d104",
    "vendor_row16_genmass/masses/m1_5h_1h_3/coef.json": "3261dae278fab346bd2813b1bbe9e38d3c61127eaa1a350576ea9008fc16dd22",
    "vendor_row16_genmass/masses/m1_5h_1h_3/cusp_dps30.json": "1b9faa60649f1b921518e14b2c2187d2b56f4b8b0a179fd4f83252e32d2fadac",
    "vendor_row16_genmass/masses/m1_5h_1h_3/cusp_dps60.json": "b87948da124a092c42a24ddd061cd52beeac74d6a55d22acce4fc0ee138f8b63",
    "vendor_row16_genmass/masses/m1_5h_1h_3/layers.json": "85dad7fe56a264f1b699f0bd4bb2db5c6dbba7e66b3b2c4039f1834a7ce60132",
    "vendor_row16_genmass/masses/m1_5h_1h_3/reference.json": "f0fdcbbc9590ad09f190c0897a5744fbdc53dd324a91c3438d6458281c972372",
    "vendor_row16_genmass/masses/m1_5h_1h_3/slots.json": "c901b77fcdc9f4ffe34d027c76ab3957adc73bba4202baf1db530b382e320d56",
    "vendor_row16_genmass/row16_final.py": "a939123c71b6684d01963027da167d98c8cfbfc6fb364ce5a7916743da093b81",
    "vendor_row16_genmass/row16_solve.py": "2dcd7bec291c3f17e82f3c7a69af5da729ec7d4d3917f61e710bc5457e984182",
}
# --- END PINS ---

# measured walls (GNU time, the delivered bytes; written by the build from its captures)
WALLS = {
    "default (--masses 1,3,2,7 --point=-2 --dps 30)": "27.27 s",
    "--masses 1,3,2,7 --point=-2 --dps 60": "84.71 s",
    "--masses 1,2,3,5 --point=-2 (positive control, dps 30)": "28.70 s",
    "--masses 1,3,2,7 --point=-3 (no reference)": "38.71 s",
    "--masses 1,3,2,7 --dps 30 --derive-boundary (cusp solve in-process)": "265.49 s",
    "--masses 1,2,3,5 --point=-2 --dps 60 --derive-boundary": "362.54 s",
    "--masses 1,5/2,1/2,3 --point=-2 --dps 30 (the second configuration; its pack, reference at bar 19)": "29.92 s",
    "--masses 1,5/2,1/2,3 --point=-2 --dps 60 (the second configuration vs its AMFlow reference, bar 51)": "92.29 s",
    "--masses 1,5/2,1/2,3 --witness (the derivation chain end to end, dps 30; measured before this pack shipped: with the pack present the chain is not run for these masses)": "444.16 s",
}


def sha256_file(p):
    h = hashlib.sha256()
    with open(p, "rb") as f:
        for ch in iter(lambda: f.read(1 << 20), b""):
            h.update(ch)
    return h.hexdigest()


def utc():
    return subprocess.run(["date", "-u", "+%Y-%m-%dT%H:%M:%SZ"], capture_output=True, text=True).stdout.strip()


def die(rc, msg):
    print(msg, flush=True)
    sys.exit(rc)


def check_pins():
    for rel, want in PINS.items():
        p = os.path.join(HERE, rel)
        if not os.path.exists(p):
            die(RC_MISSING, f"icc-genmass-evaluate MISSING: pinned file {rel} is absent (recorded sha256 {want}); not serving")
        got = sha256_file(p)
        if got != want:
            pos = next(i + 1 for i in range(64) if got[i] != want[i])
            die(RC_REFUSED, f"icc-genmass-evaluate REFUSED: {rel} integrity pin mismatch (recorded {want}, recomputed {got}; "
                            f"first differing hex position {pos} of 64, 1-based) -- the shipped file was altered; not serving")
    return len(PINS)


def mass_tag(m):
    return "m" + "_".join(str(v).replace("/", "o") for v in m)


def find_pack(m):
    """the shipped mass pack whose cfg.json declares exactly these squared masses -- found by CONTENT, not by the
    directory name (mass_tag writes 5/2 as '5o2'; the record names the second configuration's pack m1_5h_1h_3).
    None when no shipped pack declares them; two packs declaring the same masses refuse by name."""
    root = os.path.join(VENDOR, "masses")
    found = []
    for d in sorted(os.listdir(root)):
        cfg = os.path.join(root, d, "cfg.json")
        if not os.path.isfile(cfg):
            continue
        ms = json.load(open(cfg))["masses_sq"]
        if tuple(F(ms[k]) for k in ("m2", "m3", "m4")) == tuple(m[1:]):
            found.append(os.path.join(root, d))
    if len(found) > 1:
        die(RC_REFUSED, f"icc-genmass-evaluate REFUSED: {len(found)} shipped mass packs declare the same squared masses "
                        f"({', '.join(os.path.basename(q) for q in found)}); one pack per configuration")
    return found[0] if found else None


def shipped_reference_points():
    """the points at which an independent reference is shipped: every pack with a reference.json (its masses), then the
    served icc-evaluate.py's strings at the reference masses (1,2,3,5); all at x = -2."""
    pts = []
    root = os.path.join(VENDOR, "masses")
    for d in sorted(os.listdir(root)):
        rp = os.path.join(root, d, "reference.json")
        if os.path.isfile(rp):
            ms = json.load(open(rp))["masses_sq"]
            pts.append(f"({ms['m1']},{ms['m2']},{ms['m3']},{ms['m4']})")
    pts.append("(1,2,3,5)")
    return ", ".join(pts[:-1]) + " and " + pts[-1]


def parse_masses(s, ap):
    parts = s.split(",")
    if len(parts) != 4:
        ap.error(f"--masses takes FOUR comma-separated squared masses m1,m2,m3,m4 (got {len(parts)}: '{s}')")
    try:
        m = tuple(F(p.strip()) for p in parts)
    except (ValueError, ZeroDivisionError):
        ap.error(f"--masses must be exact positive rationals (got '{s}')")
    if any(v <= 0 for v in m):
        ap.error(f"--masses must be positive squared masses (got {s})")
    return m


def parse_point(s, ap):
    try:
        return F(s.strip())
    except (ValueError, ZeroDivisionError):
        ap.error(f"--point must be an exact rational (got '{s}')")


def served_reference_strings():
    """the independent reference strings at the reference masses, read from the pinned served icc-evaluate.py."""
    t = open(os.path.join(HERE, "icc-evaluate.py")).read()
    o = re.search(r'\("generic", 0\): "([0-9.]+)"', t).group(1)
    v = re.search(r'ORACLE_VERIFY = \{.*?\("generic", 0\): "([0-9.]+)"', t, re.S).group(1)
    return o, v


def agree(a_str, b_str, dps=200):
    from mpmath import mp, mpf, fabs, log10
    with mp.workdps(dps):
        a, b = mpf(a_str), mpf(b_str)
        if a == b:
            return float("inf")
        return float(-log10(fabs(a - b) / max(fabs(a), fabs(b))))


def derive_pack(m, tag, witness, workdir, slots_dps):
    """the derivation chain for masses without a shipped pack: layers -> slots -> specialized connection + cfg."""
    m2, m3, m4 = m[1:]
    if m3 == m4:
        die(RC_REFUSED, f"icc-genmass-evaluate REFUSED: the regions engine needs m3^2 != m4^2 (got {m3} = {m4}); no pack for these masses")
    env = dict(os.environ)
    env["ICC_A_SYMBOLIC_PATH"] = witness
    env["PYTHONDONTWRITEBYTECODE"] = "1"
    t0 = time.time()
    print(f"[derive] no shipped pack for {tag}: deriving layers, slots and the specialized connection at masses (1,{m2},{m3},{m4}) into {os.path.basename(workdir)}/", flush=True)
    layers = os.path.join(workdir, f"layers_{tag}.json")
    r = subprocess.run([sys.executable, os.path.join(VENDOR, "gen_layers.py"), str(m2), str(m3), str(m4), tag, layers], env=env, cwd=workdir)
    if r.returncode != 0 or not os.path.exists(layers):
        die(RC_REFUSED, f"icc-genmass-evaluate REFUSED: the layer derivation failed (rc {r.returncode}; the witness at --witness must be the sha-pinned A_symbolic.json)")
    print(f"[derive] layers done [{time.time() - t0:.1f} s]", flush=True)
    t1 = time.time()
    slots = os.path.join(workdir, f"slots_{tag}_dps{slots_dps}.json")
    env2 = dict(env)
    env2["ICC_B1_MASSES"] = f"{m2},{m3},{m4}"
    r = subprocess.run([sys.executable, os.path.join(VENDOR, "b1gen", "slots_gen.py"), str(slots_dps), layers, slots], env=env2, cwd=workdir)
    if r.returncode != 0 or not os.path.exists(slots):
        die(RC_REFUSED, f"icc-genmass-evaluate REFUSED: the slot derivation (regions engine) failed (rc {r.returncode})")
    print(f"[derive] slots done at dps {slots_dps} [{time.time() - t1:.1f} s]", flush=True)
    t2 = time.time()
    os.environ["ICC_A_SYMBOLIC_PATH"] = witness
    sys.path.insert(0, VENDOR)
    import make_gen_cfg
    out_coef, out_cfg, census = make_gen_cfg.build(str(m2), str(m3), str(m4), tag, layers, slots, workdir)
    print(f"[derive] connection specialized + singularity census: real roots {census['real_roots']}, below -1/2: {census['real_roots_below_minus_half']} [{time.time() - t2:.1f} s]", flush=True)
    return out_cfg, {"layers": layers, "slots": slots, "coef": out_coef, "cfg": out_cfg, "wall_s": round(time.time() - t0, 1)}


def derive_cusp(dps, nser, torder, workdir, tag, shipped=None):
    """the in-process cusp solve (row16_final.run through the generic-mass configuration), emitted in the cusp
    receipt form; compared string-for-string with the shipped receipt at this dps when there is one."""
    from mpmath import mp, mpf, nstr, fabs, log
    import row16_solve
    import row16_final
    assert os.path.dirname(os.path.abspath(row16_final.__file__)) == VENDOR
    t0 = time.time()
    stamp0 = utc()
    print(f"[cusp solve] row16_final.run(dps={dps}, NSER={nser}, order={torder}, tfrac=0.10, u0inv=100) at these masses ...", flush=True)
    res = row16_final.run(dps, nser, u0inv=100, torder=torder, tfrac="0.10", tag=None, dump_state=False)
    y, idx, state, env = res["y"], res["idx"], res["state"], res["env"]
    W = env["W"]
    t11 = res["gates"].get("t11_forced", mpf(0))
    mp.dps = dps
    tau1_d = float(-log(fabs(t11 - 2 * W) / fabs(2 * W)) / log(10)) if t11 != 2 * W else 999.0
    pfA = env["out"]["pfA"][3].c[0]
    pfB = env["out"]["pfB"][3].c[0]
    cusp = {"PRODUCER": {"script": os.path.basename(__file__), "sha256": sha256_file(__file__), "start": stamp0, "stamp": utc(),
                         "wall_s": round(time.time() - t0, 1), "solver": "row16_final.run of vendor_row16_genmass/ (in-process)"},
            "masses_sq": {"m1": "1", "m2": str(icc_cfg["m2"]), "m3": str(icc_cfg["m3"]), "m4": str(icc_cfg["m4"])},
            "run": {"dps": dps, "NSER": nser, "order": torder, "tfrac": "0.10", "u0inv": 100, "nsteps": res["nstep"], "slot_shift": None},
            "slots_used": {k: nstr(v, dps) for k, v in row16_solve.LAST_SLOTS.items()},
            "slots_underived": bool(getattr(row16_solve, "SLOTS_UNDERIVED", False)),
            "gates": {"PF_closure_residual_A": nstr(pfA, 3), "PF_closure_residual_B": nstr(pfB, 3),
                      "tau1_identity_t11_vs_2W_digits": tau1_d, "t11_forced": nstr(t11, 30), "two_W": nstr(2 * W, 30),
                      "t0k_expect_zero": [nstr(res["t"].get((0, k), 0), 3) for k in range(4)],
                      "deep_gate_T_digits_reference_only": float(res["digT"])},
            "tau0": nstr(res["tau0"], dps), "W": nstr(W, dps),
            "state_at_xm1": {f"{i},{K}": nstr(y[idx[(i, K)]], dps) for (i, K) in state}}
    fn = os.path.join(workdir, f"cusp_{tag}_dps{dps}.json")
    json.dump(cusp, open(fn, "w"), indent=1)
    print(f"[cusp solve] tau1 identity t11 vs 2W: {tau1_d:.1f} d; PF residuals {nstr(pfA, 3)} {nstr(pfB, 3)}; T(-1) = {nstr(y[idx[(15, 0)]], dps)} [{time.time() - t0:.0f} s]", flush=True)
    cmp = None
    if shipped:
        sd = json.load(open(shipped))["state_at_xm1"]
        same = sum(1 for k in sd if cusp["state_at_xm1"].get(k) == sd[k])
        mind = min(agree(cusp["state_at_xm1"][k], sd[k]) if mpf(sd[k]) != 0 else float("inf") for k in sd)
        cmp = {"shipped": os.path.basename(shipped), "entries": len(sd), "string_identical": same, "min_agreement_digits": mind}
        print(f"[cusp solve] derived boundary vs the shipped receipt {os.path.basename(shipped)}: {same} of {len(sd)} entries string-identical; min agreement {mind:.1f} d", flush=True)
    return fn, cusp, cmp


def main():
    ap = argparse.ArgumentParser(
        description="ICC generic-mass cone: T(x) at eps^0 at arbitrary rational squared masses from a runtime-derived boundary "
                    "(route 1), gated by the direct relative-period integral (route 2) and the shipped independent references.",
        epilog="measured walls (GNU time wall clock, one process, nice 10, a shared 96-core host at loadavg ~120-140): "
               + "; ".join(f"{k}: {v}" for k, v in WALLS.items()) + ".  Exit codes: 0 PASS, 1 FAIL, 2 usage, 3 REFUSED by name, 4 pinned file MISSING.")
    ap.add_argument("--masses", default="1,3,2,7", metavar="M1,M2,M3,M4", help="four exact rational squared masses; m1^2 = 1 required (default 1,3,2,7)")
    ap.add_argument("--point", default="-2", metavar="X", help="the Euclidean point x < -1/2 (exact rational; default -2)")
    ap.add_argument("--dps", type=int, default=30, help="working precision of route 1 (default 30; the fixture's second tier is 60)")
    ap.add_argument("--route2-dps", type=int, default=None, metavar="R", help="working precision of the route-2 integral (default 15 at dps <= 30, else min(40, dps - 20))")
    ap.add_argument("--derive-boundary", action="store_true", help="derive the cusp-solve boundary in-process at this dps even when the pack ships a receipt")
    ap.add_argument("--witness", default=None, metavar="PATH", help="a sha-matching copy of A_symbolic.json (or ICC_A_SYMBOLIC_PATH): enables masses without a shipped pack")
    ap.add_argument("--slots-dps", type=int, default=None, help="regions-engine precision for a derived pack (default max(60, dps))")
    ap.add_argument("--workdir", default=None, metavar="DIR", help="where derived receipts are written (default: a fresh temporary directory)")
    ap.add_argument("--out", default=None, metavar="JSON", help="write the run receipt here (never overwrites)")
    args = ap.parse_args()
    try:
        sys.stdout.reconfigure(line_buffering=True)
    except AttributeError:
        pass
    t_all = time.time()
    stamp0 = utc()
    m = parse_masses(args.masses, ap)
    x = parse_point(args.point, ap)
    if args.dps < 20:
        ap.error("--dps must be >= 20")
    r2dps = args.route2_dps if args.route2_dps is not None else (15 if args.dps <= 30 else min(40, args.dps - 20))
    slots_dps = args.slots_dps if args.slots_dps is not None else max(60, args.dps)
    print(f"[mode] ICC generic-mass cone at squared masses ({','.join(str(v) for v in m)}), x = {x}, dps {args.dps} (route 2 at dps {r2dps})"
          + (", boundary derived in-process" if args.derive_boundary else ""))
    npins = check_pins()
    print(f"[pins] {npins} shipped/served files verified by sha256")
    if m[0] != 1:
        die(RC_REFUSED, f"icc-genmass-evaluate REFUSED: m1^2 must be 1 (the record's normalization; got {m[0]}) -- rescale the masses")
    if not (x < F(-1, 2)):
        die(RC_REFUSED, f"icc-genmass-evaluate REFUSED: x = {x} is outside the Euclidean domain of the transport (real x < -1/2; the connection's nearest singularity is x = -1/2); complex or Minkowski points are not implemented")
    tag = mass_tag(m)
    pack = find_pack(m) or os.path.join(VENDOR, "masses", tag)   # by content; the tag path (absent) keeps the no-pack branches as served
    tag = os.path.basename(pack)
    workdir = args.workdir or tempfile.mkdtemp(prefix="icc-genmass-")
    os.makedirs(workdir, exist_ok=True)
    derived_pack = None
    if os.path.isdir(pack):
        cfg_path = os.path.join(pack, "cfg.json")
        print(f"[pack] shipped mass pack vendor_row16_genmass/masses/{tag}/ (cfg.json, pinned)")
    else:
        witness = args.witness or os.environ.get("ICC_A_SYMBOLIC_PATH")
        if not witness:
            die(RC_REFUSED, f"icc-genmass-evaluate REFUSED: no shipped mass pack for squared masses ({','.join(str(v) for v in m)}) "
                            f"(shipped: {', '.join(sorted(os.listdir(os.path.join(VENDOR, 'masses'))))}) and no witness: the derivation chain "
                            f"specializes the symbolic connection from the 59.9 MB A_symbolic.json, which is not distributed with this bundle "
                            f"(sha256 pinned in icc_genmass_lib.py); pass --witness PATH or set ICC_A_SYMBOLIC_PATH to a sha-matching copy")
        if not os.path.exists(witness):
            die(RC_REFUSED, f"icc-genmass-evaluate REFUSED: witness {witness} does not exist")
        cfg_path, derived_pack = derive_pack(m, tag, witness, workdir, slots_dps)
    os.environ["ICC_GEN_CFG"] = cfg_path
    # the generic-mass stack (vendor_row16_genmass/) must shadow the served elim_series/row16_solve/row16_final: first on sys.path
    sys.path[:] = [VENDOR] + [p for p in sys.path if p != VENDOR]
    global icc_cfg
    import icc_gen_cfg
    icc_cfg = icc_gen_cfg.load()
    assert (icc_cfg["m2"], icc_cfg["m3"], icc_cfg["m4"]) == m[1:], "pack masses != requested masses"
    import icc_genmass_lib as gml
    from mpmath import mp
    import eval_row16 as er
    import icc_genmass_eval as ige
    import elim_series, row16_solve, row16_final
    for _mod in (icc_gen_cfg, er, ige, elim_series, row16_solve, row16_final):
        if os.path.dirname(os.path.abspath(_mod.__file__)) != VENDOR:
            die(RC_REFUSED, f"icc-genmass-evaluate REFUSED: module {_mod.__name__} resolved outside vendor_row16_genmass/ ({_mod.__file__}); the generic-mass stack must shadow the served copies")
    # the boundary: the shipped cusp receipt at this dps, or the in-process solve
    shipped_cusp = os.path.join(pack, f"cusp_dps{args.dps}.json") if os.path.isdir(pack) else None
    if shipped_cusp and not os.path.exists(shipped_cusp):
        shipped_cusp = None
    cusp_cmp = None
    if shipped_cusp and not args.derive_boundary:
        cusp_path, cusp_name = shipped_cusp, f"masses/{tag}/cusp_dps{args.dps}.json (shipped, pinned)"
        cusp = json.load(open(cusp_path))
        print(f"[boundary] cusp-solve receipt {cusp_name}: dps {cusp['run']['dps']}, NSER {cusp['run']['NSER']}, order {cusp['run']['order']}; "
              f"tau1 identity t11 = 2W: {cusp['gates']['tau1_identity_t11_vs_2W_digits']:.1f} d; PF residuals "
              f"{cusp['gates']['PF_closure_residual_A']} {cusp['gates']['PF_closure_residual_B']}; slots from the regions engine: "
              f"{'yes' if not cusp['slots_underived'] else 'NO (underived)'}")
    else:
        nser = json.load(open(shipped_cusp))["run"]["NSER"] if shipped_cusp else (60 if args.dps <= 30 else 2 * args.dps + 20)
        if not shipped_cusp and os.path.isdir(pack):
            print(f"[boundary] no shipped cusp receipt at dps {args.dps} in the pack: deriving in-process")
        try:
            torder = 90 if args.dps <= 100 else int(-(-17 * args.dps // 10)) + 20   # CURE 2026-09-09: the cusp transport order tracks dps above 100 (the eval_row16 transport's own rule); the served order 90 saturated the covariant cross-check near ~101 d while the bar dps - 11 walked past it above ~dps 112
            cusp_path, cusp, cusp_cmp = derive_cusp(args.dps, nser, torder, workdir, tag, shipped_cusp)
        except gml.GenMassError as e:
            die(RC_REFUSED, f"icc-genmass-evaluate REFUSED (cusp solve): {e}")
        cusp_name = f"{os.path.basename(cusp_path)} (derived in-process)"
    tau1_d = cusp["gates"]["tau1_identity_t11_vs_2W_digits"]
    # route 1 + route 2 + the cross-checks (the evaluator of record's own run, printed line for line)
    try:
        out = ige.run(cusp_path, args.dps, str(x), r2dps, cusp_name=cusp_name)
    except gml.GenMassError as e:
        die(RC_REFUSED, f"icc-genmass-evaluate REFUSED (boundary): {e}")
    # the covariant seeds, printed in the served icc-evaluate.py --masses form (the same function, the same digits)
    overlay, _W, _conv = er._genmass_seeds(m[1], m[2], m[3], args.dps)
    mp.dps = args.dps
    print(f"    tadpole^2/triangle eps^0 values (x-independent):")
    for i in (0, 1, 3, 4, 9, 2, 10):
        print(f"      master {i:2d} eps^0 = {mp.nstr(overlay[(i, 0)], 30)}")
    # ---- gates -----------------------------------------------------------------------------------------------
    gates = []

    def gate(name, value, bar, note=""):
        ok = value >= bar
        gates.append({"gate": name, "digits": value, "bar": bar, "pass": ok, "note": note})
        print(f"  [gate] {name}: {value:.1f} d vs bar >= {bar} -> {'PASS' if ok else 'FAIL'}{(' (' + note + ')') if note else ''}")
        return ok

    gate("cusp solve tau1 = 2W identity", tau1_d, args.dps - 12, "the solver's internal forced identity")
    gate("cusp-transported covariant masters vs live seeds", out["boundary"]["covariant_xcheck_min_digits"], args.dps - 11, "21 entries")
    gate("route 1 vs route 2 (direct relative-period integral)", out["route2"]["agreement_digits_route1_vs_route2"], r2dps + 2,
         f"route-2 working precision {r2dps}")
    gate("transported scoop S(x) vs live Bessel-moment quadrature", out["scoop_vs_bessel_digits"], min(33, args.dps - 10), "dps 40 quadrature, 35 d cap")
    # the independent reference
    reference = {"kind": "none"}
    ref_path = os.path.join(pack, "reference.json") if os.path.isdir(pack) else None
    if ref_path and os.path.exists(ref_path) and F(json.load(open(ref_path))["x"]) == x:
        ref = json.load(open(ref_path))
        bar = ref["bars"]["dps60"] if args.dps >= 60 else max(1, args.dps - 11)
        d100 = agree(out["T_eps0"], ref["eps0"]["g100"]["mid"])
        d60 = agree(out["T_eps0"], ref["eps0"]["g60"]["mid"])
        print(f"  [reference] INDEPENDENT AMFlow value at masses ({','.join(str(v) for v in m)}), x = {x} (shipped, pinned): "
              f"T(-2) eps^0 = {ref['eps0']['g100']['mid'][:62]}... (goal 100; the goal-60/goal-100 pair agrees to {ref['pair_agreement_digits_g60_vs_g100']} d)")
        print(f"  [reference] this run vs goal 100: {d100:.2f} d; vs goal 60: {d60:.2f} d")
        gate("T(x) vs the independent AMFlow reference", min(d100, d60), bar,
             f"bar = {'the record floor at dps 60' if args.dps >= 60 else 'dps - 11'}")
        reference = {"kind": "amflow", "file": f"masses/{tag}/reference.json", "vs_g100_digits": d100, "vs_g60_digits": d60, "bar": bar}
    elif m[1:] == REFERENCE_MASSES and x == F(-2):
        o, v = served_reference_strings()
        assert o == er.ORACLE and v == er.ORACLE_VERIFY, "the vendored reference strings differ from the served icc-evaluate.py"
        d = agree(out["T_eps0"], o)
        dv = agree(out["T_eps0"], v)
        bar = min(100, max(1, args.dps - 11))
        print(f"  [reference] the served icc-evaluate.py's independent AMFlow strings at the reference masses (1,2,3,5), x = -2 (pinned): "
              f"main {d:.2f} d, independent verification run {dv:.2f} d (the strings carry {len(o) - 2} digits)")
        gate("T(-2) vs the served independent reference (positive control)", min(d, dv), bar, "bar = dps - 11")
        reference = {"kind": "served-oracle", "vs_oracle_digits": d, "vs_verify_digits": dv, "bar": bar}
    else:
        print(f"  [reference] NO independent reference is shipped at masses ({','.join(str(v) for v in m)}), x = {x}: the value is gated by "
              f"route 2 and the scoop cross-check only (the shipped references sit at {shipped_reference_points()}, x = -2)")
    ok = all(g["pass"] for g in gates)
    wall = round(time.time() - t_all, 1)
    print(f"\nT({x}) eps^0 at squared masses ({','.join(str(v) for v in m)}) = {out['T_eps0']}")
    print(f"VERDICT {'PASS' if ok else 'FAIL'}: {sum(g['pass'] for g in gates)} of {len(gates)} gates met"
          + ("" if ok else " -- FAILED: " + "; ".join(g["gate"] for g in gates if not g["pass"])) + f"; total wall {wall} s")
    if args.out:
        rec = {"PRODUCER": {"script": os.path.basename(__file__), "sha256": sha256_file(__file__), "start": stamp0, "stamp": utc(), "wall_s": wall,
                            "pins_verified": npins, "stamp_source": "date -u"},
               "args": {"masses": [str(v) for v in m], "point": str(x), "dps": args.dps, "route2_dps": r2dps, "derive_boundary": args.derive_boundary,
                        "slots_dps": slots_dps},
               "pack": (f"masses/{tag}" if os.path.isdir(pack) else "derived"), "derived_pack": ({k: os.path.basename(v) if isinstance(v, str) else v for k, v in derived_pack.items()} if derived_pack else None),
               "cusp": {"source": cusp_name, "run": cusp["run"], "gates": cusp["gates"], "vs_shipped": cusp_cmp},
               "result": out, "gates": gates, "reference": reference, "verdict": "PASS" if ok else "FAIL"}
        fd = os.open(args.out, os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o644)
        with os.fdopen(fd, "w") as f:
            json.dump(rec, f, indent=1)
        print(f"[written] {os.path.basename(args.out)}")
    sys.exit(0 if ok else RC_FAIL)


if __name__ == "__main__":
    main()
