#!/usr/bin/env python3
r"""lbl3e-box-evaluate.py -- the sunrise-dressed box of row 27 (the LBL3E top master, [1^6 0^9] of the LBL3Ebox family)
ASSEMBLED at a Euclidean (s, t) point through eps^0 and compared with an independent AMFlow value at the same point.
Third script of the page, beside lbl3e-master-evaluate.py (the d = 2-2eps elliptic master at Euclidean w < 0) and
lbl3e-evaluate.py (psi_1/pi and B^(0)).  This one answers the function-level question for the box itself: the master
that the page's closed form dresses is here computed from scratch as a two-loop sunrise inserted into a one-loop box,
at three (s, t) points, one of them BLIND (its value was written down and its receipt hashed before the independent
computation at that point existed).

THE OBJECT (m^2 = 1, d = 4 - 2 eps, measure int d^dl/(i pi^{d/2}) per loop, no e^{eps gamma_E})
  I(s, t; eps) = int d^dk/(i pi^{d/2})  J_4(k^2; eps) / (D4 D5 D6),
  J_4 = the equal-mass two-loop sunrise with external momentum k, D4 = (k+p2)^2 - 1, D5 = (k+p2+p3)^2 - 1,
  D6 = (k-p1)^2 - 1, s = (p1+p2)^2, t = (p2+p3)^2, u = -s-t; the box's Laurent series eps^-2, eps^-1, eps^0.

THE ROUTE (the evaluator of record, vendored whole: vendor_row27_box/box_assembly.py with its modules)
  The large-momentum asymptotics of the sunrise is subtracted EXACTLY in eps (three region terms with
  Gamma-function coefficients, sunrise_asym.py); the subtracted piece integrates against the box as generalised
  triangles X(alpha) = int (-k^2)^alpha/(D4 D5 D6) at alpha = 1-2eps, -2eps, -eps (Feynman parameters, eps-series,
  gentri.py); the remainder is a one-fold R = -(1/pi) int_0^inf rho_rem(w) B(w) dw of the subtracted sunrise
  spectral density (the closed elliptic density of lbl3disp.py minus the asymptotic series) against the one-loop
  box kernel with rung mass^2 w (the closed dilogarithmic one-loop box continued to complex conjugate roots,
  boxkern.py).  No fit, no stored value and no differential-equation transport enters the computation; the only
  inputs are (s, t) and the working precision.

THE THREE POINTS (vendor_row27_box/points/points.json; every reference file sha256-pinned below)
  P1: (s, t) = (-7/3, -11/10)   the reference point of the row
  P2: (s, t) = (-3/2, -9/5)
  P3: (s, t) = (-5/4, -12/5)    the BLIND point: the assembly's value at P3 (dps 32 and 48) was filed with its
      sha256 at 2026-09-05T00:13:30Z; the two AMFlow runs at P3 were launched at 00:13:56Z and landed at 00:17:43Z;
      the filed prediction agrees with them at eps^0 to 45.33 digits (points/P3/prediction.json carries the stamps,
      the strings and the shas).
  At each point the shipped reference is a pair of AMFlow runs (goal 40 and goal 60 digits) of the same integral;
  their mutual agreement (48.49 / 48.31 / 47.88 digits at eps^0) is the certified depth of the reference.

WHAT THE RUN CHECKS
  The three Laurent coefficients at the point against the goal-60 reference strings, as -log10 of the relative
  difference (the record's convention, relative to the reference).  Bar: 45 digits at dps 48 = the floor of the
  record's own minimum over the three points (46.04 / 45.79 / 45.33); at dps 32 the bar is 29 (the record's floor
  there: 30.57 / 30.40 / 29.99); at another dps min(45, dps - 3).  A figure below the bar is FAIL by name (exit 1).
  --check runs the working-precision pair of record (dps - 16 and dps) and gates their agreement at the lower
  precision's bar as well; the record's reportable-digit rule, min(pair agreement, agreement with the reference),
  is printed.  The eps^0 value string is printed in full (dps + 4 digits) and, at P1/P2/P3 at dps 32 or 48, compared
  string for string with the record's own value (points/P<i>/record.json).
THE SECOND ROUTE (--route tanhsinh; vendor_row27_box/disp_sub.py, the dispersion-subtracted tanh-sinh quadrature)
  The one-fold R = -(1/pi) int_0^inf rho_rem(w) B(w) dw is the only numerical quadrature of the assembly (the poles and the
  asymptotic part of eps^0 are Gamma-function series and the generalised triangles).  The second route integrates the SAME
  rho_rem(w) B(w) -- the served modules rhorem.py and boxkern.py, the evaluator of record's integrand -- with a different
  rule: mpmath's double-exponential (tanh-sinh) quadrature on the panels [0, 9], [9, 30], [30, 200] and [200, inf) through
  w = 200 + 200 (1 + t)/(1 - t), adaptive in the degree up to mpmath's own guess, at working precision dps + 20 inside the
  quadrature (the evaluator of record: a tanh-sinh refinement on [0, 9], geometric Gauss-Legendre panels on [9, 200],
  panels in ln w above, the asymptotic density above 10^8).  The tier prints the degree-capped runs (maxdegree 3, 4, 5, 6)
  beside the adaptive run with their consecutive agreements and node counts, a scan of w B(w) past the kernel's own working
  precision (w = 10^(dps+18+k), k = 0..10: finite and without a jump, or FAIL), R to dps + 4 digits compared STRING FOR
  STRING with the served route's R of record at the point and dps (points/P<i>/record.json), and eps^0 = the record's
  asymptotic part (the same string on both routes) + R, gated against the goal-60 reference at the served bar (29 at dps 32,
  45 at dps 48) and printed beside the served route's own eps^0 (the two differ only by the rounding of the record's
  asymptotic-part string to dps + 4 digits; the recomputed agreement is printed).  At P1/P2/P3 at dps 32 and 48 the printed R
  equals the served route's string to every printed digit (36 and 52 significant digits) and eps^0 reproduces the goal-60
  reference to 30.57 / 30.40 / 29.99 digits at dps 32 and 46.04 / 45.79 / 45.33 at dps 48 (the served route's own figures; recomputed at
  every run).  At a point or dps without a served R string the tier prints R alone and says so by name.  --check runs the
  route's own pair (dps - 16, dps) and gates the agreement of the two R at the lower bar; --mutate scales R by (1 + 1e-9)
  before the gates (exit 1).  The tier costs one one-fold and no triangles: its walls are in the table below.
THE TRIANGLES (--triangles; vendor_row27_box/triangles/, the record's reference files for the generalised-triangle tower)
  The poles and the asymptotic part of eps^0 are the three generalised triangles X(alpha), alpha = 1-2eps, -2eps, -eps, as
  eps-series (gentri.py) times Gamma-function coefficients: I = -C_0 X(1-2eps) + C_1 X(-2eps) + T D_0 X(-eps) + R, and
  through eps^0 of I the assembly consumes nine coefficients -- X(1-2eps) at eps^-1 (= -1/3 exactly, the UV pole), eps^0 and
  eps^1; X(-2eps) and X(-eps) at eps^0 (= T0(s), the massive triangle), eps^1 and eps^2 (their eps^-1 is a structural zero).
  The tier recomputes the tower at the point and dps with the served gentri.py (the same calls, precisions and strings as
  the assembly's run; at P1/P2/P3 at dps 32 and 48 the record's own X strings are compared string for string, and the
  poles and the asymptotic part of eps^0 reassembled from the nine coefficients against the record's strings) and compares
  every consumed coefficient with TWO independent one-loop references, vendored verbatim and pinned: (A) AMFlow on the
  massless-insertion families -- the three-loop family with the three sunrise lines massless (its corner integral and the
  integral with one dot) and the two-loop family with a massless bubble in place of the sunrise -- at goal 40 and goal 60 at
  each point, divided by the exact massless-bubble factors G(a, b) computed as eps-series by two routes (the served epsser
  Gamma series; mpmath's gamma differentiated numerically; their agreement to 60 digits is a gate): X(1-2eps) =
  -I[1^6 0^9]/(G(1,1) G(1,eps)), X(-2eps) = I[1,1,2,1,1,1,0^9]/(G(1,2) G(1,1+eps)), X(-eps) = I[1^5 0^4]/G(1,1);
  (B) a closed one-loop form of X(nu; eps) (Feynman parameters with the rung line, Cheng-Wu on the massive lines, the rung
  integral closed as a Beta function times a 2F1 at complex eps, the Laurent coefficients by a Cauchy contour; no series
  arithmetic, no code shared with gentri.py) at dps 32 and 48 at each point.  The digit rule is the record's: -log10
  |a - b|/|b| with b this run's string, evaluated at 250 digits, capped at the shorter string's significant digits,
  'identical (N significant digits)' when the two agree to the shorter's full length; the paste-ready count is the FLOOR
  of the minimum over the nine coefficients, printed with the members beside it.  Gates: each reference's floor >= the
  served bar at the dps (29 at dps 32, 45 at dps 48; min(45, dps - 3) elsewhere); each reference's own pair (goal 40 vs
  goal 60; dps 32 vs dps 48) >= 40 / 29 digits; the two divisor routes >= 60 digits on every coefficient.  At P1/P2/P3 the
  floors are 31 / 31 digits (A / B) at dps 32 and 47 / 47 at dps 48 at every point, with 3-4 of the nine coefficients
  identical to the full printed length; the references' own pairs floor at 41 (A) and 35 (B) digits.  The closed-form legs
  exist at dps 32 and 48 only: at another dps the tier compares with (A) alone and says so by name.  --check recomputes
  the tower at dps - 16 as well and gates the tower's own pair at the lower bar; --mutate scales X(1-2eps) at eps^0 by
  (1 + 1e-9) before the comparisons (both references FAIL by name, exit 1).  The tier costs the three triangles and no
  one-fold: its walls are in the table below.

USAGE
  python3 lbl3e-box-evaluate.py                          # = --point P1 --dps 32
  python3 lbl3e-box-evaluate.py --point P3 --dps 48      # the blind point at the dps of record (bar 45)
  python3 lbl3e-box-evaluate.py --point P2 --dps 48 --check   # the two-precision pair (32, 48) at P2
  python3 lbl3e-box-evaluate.py --point=-7/3,-11/10      # the same as --point P1 (s,t[,m2] form; m2 must be 1)
  python3 lbl3e-box-evaluate.py --point=-2,-3 --unreferenced --dps 20   # any Euclidean (s, t): the value only,
        # no independent reference shipped there (said by name); without --unreferenced such a point is refused
  python3 lbl3e-box-evaluate.py --mutate                 # control: the one-fold R scaled by (1 + 1e-9) before the
        # assembly; the eps^0 gate must FAIL (exit 1)
  python3 lbl3e-box-evaluate.py --route tanhsinh           # the second route at P1, dps 32: R by the dispersion-subtracted
        # tanh-sinh quadrature vs the served route's R string of record, and eps^0 assembled from it vs the reference
  python3 lbl3e-box-evaluate.py --route tanhsinh --point P3 --dps 48    # the blind point at the dps of record (bar 45)
  python3 lbl3e-box-evaluate.py --route tanhsinh --point P1 --dps 48 --check   # the route's own pair (32, 48)
  python3 lbl3e-box-evaluate.py --route tanhsinh --mutate  # control: R by the second route scaled by (1 + 1e-9); FAIL (exit 1)
  python3 lbl3e-box-evaluate.py --triangles                # the generalised-triangle tower at P1, dps 32, recomputed and
        # compared coefficient by coefficient with the two vendored references (AMFlow goal 40/60; the closed one-loop form)
  python3 lbl3e-box-evaluate.py --triangles --point P3 --dps 48   # the blind point at the dps of record (bar 45)
  python3 lbl3e-box-evaluate.py --triangles --point P1 --dps 48 --check   # the tower's own pair (32, 48) as well
  python3 lbl3e-box-evaluate.py --triangles --dps 8         # the smoke tier of the triangles (the AMFlow reference only; bar 5)
  python3 lbl3e-box-evaluate.py --triangles --mutate        # control: X(1-2eps) at eps^0 scaled by (1 + 1e-9); FAIL (exit 1)
  --out JSON writes the run receipt (values as full strings, agreements, gates, walls; never overwrites: an existing
        # path is refused by name, rc 2, before anything is computed).

EXIT CODES  0 PASS (every gate met) | 1 FAIL (a gate missed, named) | 2 usage (an unknown point name, a point
  outside the Euclidean domain s < 0, t < 0, m^2 != 1, a point without a shipped reference and no --unreferenced,
  --dps < 8, an existing --out path) | 3 REFUSED (a pinned file's sha256 does not match: the recorded and recomputed hashes and the first
  differing position are printed; nothing is imported or computed) | 4 a pinned file, or mpmath, MISSING.

MEASURED WALLS (one process, nice 10, a shared 96-core host at loadavg ~120-130; a quiet core is faster): see the
  epilog of --help (the same table; the cost is the one-fold's kernel evaluations and the triangles, roughly the
  same at every point).  The --route tanhsinh rows were measured on the same host at loadavg ~180 (contended;
  one process, nice 10, inside a two-core CPU-quota scope).  The --triangles rows were measured on the same host at loadavg
  ~120 (contended; one process, nice 10, inside a two-core CPU-quota scope).
"""
import argparse
import hashlib
import json
import os
import subprocess
import sys
import time
from fractions import Fraction as F

HERE = os.path.dirname(os.path.abspath(__file__))
VENDOR = os.path.join(HERE, "vendor_row27_box")
RC_FAIL, RC_USAGE, RC_REFUSED, RC_MISSING = 1, 2, 3, 4
DPS_PAIR_GAP = 16          # the record's working-precision pair (32, 48)
BAR_TOP = 45               # the record's floor at dps 48 (points.json bars["48"], asserted equal at run time)

# --- PINS (script-emitted from the shipped bytes; sha256 of every vendored file and of the served data file the
# --- vendored modules read in place) ---
PINS = {
    "row27_gate_amflow.json": "951aaac840c4095b9d6f477c662de2783b3a0a2004fe3db38f4b52cb3977de45",
    "vendor_row27_box/box_assembly.py": "807c374f69634c1cd9bb5a82c35c08b42441775161aac78ed113a2096333669c",
    "vendor_row27_box/boxkern.py": "3a5c2bece73e1cbddc26d132e16ec03a38678e895176bdb603609ee8181ab650",
    "vendor_row27_box/disp_sub.py": "7085037c832409db91427f580926afbba2c27efa09be5fd78bed3783422a5aa2",
    "vendor_row27_box/epsser.py": "fa1902e149ace33e08b7506e3d639f811d641d74f8b09223778382ebd5baf26f",
    "vendor_row27_box/gentri.py": "b2c9941cfd9b770cdf9777d7c16d32ca58a5632d9f378bfdbfc0ee9b2e297766",
    "vendor_row27_box/lbl3disp.py": "bf4d5f3efb1611008ecbe96c9144853dcd1ea4a80f6ab3b9bfa225f9f32d6bf1",
    "vendor_row27_box/points/P1/record.json": "b54827a3c7bdb1c9c2b2deae20cbd11de95df90448a1e0053e07e06a5791a41c",
    "vendor_row27_box/points/P1/reference.json": "5e24bc93bdab20da0c7cc97a59cea832418fc78184e9f96d5cda045b5c201cf3",
    "vendor_row27_box/points/P2/record.json": "d3b22df0a8ae50928b42fa615009fe5c0cd30453ef11c87ca5c1cfc81087c829",
    "vendor_row27_box/points/P2/reference.json": "fc6645b92f777177c3800f66b503d0e1e40538cbafa13233ccfb20fa450ab22d",
    "vendor_row27_box/points/P3/prediction.json": "331c20d22c3aa2f6b736d540a92f17c394fe6ac57a410f4fe8550494b8bcbef3",
    "vendor_row27_box/points/P3/record.json": "1177d89c74255f2e16fee3ad27dac817c01f4cc3d9f7c3f1f0d703485830c6eb",
    "vendor_row27_box/points/P3/reference.json": "b461178e52a2e5a4c551aba8a93bed29a8bacad9d249ce6fc059538e20fec57f",
    "vendor_row27_box/points/points.json": "95be986d0aca6ff98e691bbea5fc83701962c41c51ec59eb207699f1d20a4429",
    "vendor_row27_box/rhorem.py": "3b0400930e2b8b1a7530c0fcab6fb74e8ef7f9a9c05f506a0ca8c5a63aea3811",
    "vendor_row27_box/sunrise_asym.py": "b34e3c1bc4eb3f66a0fc8eb9287e61f7653ab1644ef89e69b3fc575b31241020",
    "vendor_row27_box/triangles/GT2_P1_g40.json": "f299d595ce79c520bdb70f1b79256ca1d87318a19c07545b50b09aca258b291b",
    "vendor_row27_box/triangles/GT2_P1_g60.json": "a22eb09f0f382e627c701a9389dedb7213bad381fa88850992053b53ef7a5755",
    "vendor_row27_box/triangles/GT2_P2_g40.json": "769ff1661e9e31d2cb5b109b168a5e7cc55a0a42705d701028c676c33cee5282",
    "vendor_row27_box/triangles/GT2_P2_g60.json": "a3ec21c4f9cf459641a42d51ecbd5e6dae5dc692955028ac3bc8faf8537f849a",
    "vendor_row27_box/triangles/GT2_P3_g40.json": "bb0fd5b7ad8e00f29250f7ad3f869a4f5fe068d05193c0aadf4ef413899aadeb",
    "vendor_row27_box/triangles/GT2_P3_g60.json": "7e2ba61e84bcc211b97ed388e77e0beea33d498d09ab0f73600ef4e1bd89c55c",
    "vendor_row27_box/triangles/GT3_P1_g40.json": "d3bef6ce66eb224ef992b36fee41460b45e4e1703a362158419f96694d4159ff",
    "vendor_row27_box/triangles/GT3_P1_g60.json": "abc758e3b5c89b069977bb29993107ab761c6ac8ccebbc95e1ddb24e13c01e89",
    "vendor_row27_box/triangles/GT3_P2_g40.json": "4779d18c14e0e233546c362ff5faea8de755c322fb65d3d9df22b1136f37ab26",
    "vendor_row27_box/triangles/GT3_P2_g60.json": "1753074d2392543bb522df0b738aa217bad7f6621fd7c5d7f7c8e4c702e3880c",
    "vendor_row27_box/triangles/GT3_P3_g40.json": "549b2f6914d02556919f8d94ebed77865581c9cf40729d212fba8a219eadaace",
    "vendor_row27_box/triangles/GT3_P3_g60.json": "8e4e3e5ac28a2175aee8b1edf9b9aab60b165b62830facefab2f618cf3610361",
    "vendor_row27_box/triangles/closed_P1_d32.json": "d93e284657c38f9ad8602b2940dc8a7f517a2a20976fb1c8a506a656448e3c4e",
    "vendor_row27_box/triangles/closed_P1_d48.json": "5ee9538aaf1013e57f7b4f85f5843e6f72304f420c67103c0edd13c9bc41b187",
    "vendor_row27_box/triangles/closed_P2_d32.json": "eaee08817fb6ea7bc9be400984b7a50f0c61d12d0430afeb45464b26983b7bb2",
    "vendor_row27_box/triangles/closed_P2_d48.json": "db822b83d241d2268e324b9f54ef213a4b9cbd59d5d2130bc90b074248aa844b",
    "vendor_row27_box/triangles/closed_P3_d32.json": "6ac48f26574730b160525e86055005fac5c6d0c84e4ac67d1df9e25063b07046",
    "vendor_row27_box/triangles/closed_P3_d48.json": "333da85492b5385a12c035fc698acb76ce8e2a254b51f12d35bef31c1a43d78d",
}
# --- END PINS ---

# measured walls (GNU time, the delivered bytes; written by the build from its captures)
WALLS = {
    "default (--point P1 --dps 32)": "178.50 s",
    "--point P2 --dps 32": "186.57 s",
    "--point P3 --dps 32": "170.94 s",
    "--point P1 --dps 48 (the dps of record, bar 45)": "616.68 s",
    "--point P2 --dps 48": "635.92 s",
    "--point P3 --dps 48 (the blind point)": "633.98 s",
    "--point P1 --dps 48 --check (the pair 32/48)": "803.58 s",
    "--point=-2,-3 --unreferenced --dps 20 (no reference)": "53.63 s",
    "--point P1 --dps 8 (the smoke tier)": "15.00 s",
    "--route tanhsinh (= --point P1 --dps 32; the second route, contended host at loadavg ~180)": "23.57 s",
    "--route tanhsinh --point P2 --dps 32": "23.83 s",
    "--route tanhsinh --point P3 --dps 32": "23.65 s",
    "--route tanhsinh --point P1 --dps 48": "33.41 s",
    "--route tanhsinh --point P2 --dps 48": "31.99 s",
    "--route tanhsinh --point P3 --dps 48 (the blind point)": "45.20 s",
    "--route tanhsinh --point P1 --dps 48 --check (the pair 32/48)": "60.02 s",
    "--route tanhsinh --mutate (the control, dps 32)": "20.09 s",
    "--triangles (= --point P1 --dps 32; the tower vs the two references, contended host at loadavg ~120)": "183.25 s",
    "--triangles --point P2 --dps 32": "171.17 s",
    "--triangles --point P3 --dps 32": "169.54 s",
    "--triangles --point P1 --dps 48": "639.41 s",
    "--triangles --point P2 --dps 48": "639.55 s",
    "--triangles --point P3 --dps 48 (the blind point)": "637.33 s",
    "--triangles --point P1 --dps 48 --check (the pair 32/48)": "778.92 s",
    "--triangles --dps 8 (the smoke tier of the triangles)": "13.46 s",
    "--triangles --mutate (the control, dps 32)": "164.95 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"lbl3e-box-evaluate MISSING: pinned file {rel} is absent (recorded sha256 {want}); download the "
                            f"vendor_row27_box folder from the same page; nothing computed")
        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"lbl3e-box-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; nothing computed")
    return len(PINS)


def agree(a_str, b_str, dps=220):
    """-log10 |a - b| / |b| with b the reference (the record's convention); inf when the strings agree exactly"""
    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) / fabs(b)))


def bar_at(dps, bars):
    if str(dps) in bars:
        return int(bars[str(dps)])
    return max(1, min(BAR_TOP, dps - 3))


def parse_point(s, ap, points):
    """P1|P2|P3 or s,t[,m2] (exact rationals) -> (tag or None, s, t, m2)"""
    if s in points:
        p = points[s]
        return s, F(p["s"]), F(p["t"]), F(p["m2"])
    if s.upper().startswith("P") and s[1:].isdigit():
        ap.error(f"unknown point name '{s}': the shipped points are {', '.join(points)} (or give s,t as exact rationals)")
    parts = s.split(",")
    if len(parts) not in (2, 3):
        ap.error(f"--point takes a point name ({', '.join(points)}) or s,t[,m2] as exact rationals (got '{s}')")
    try:
        vals = [F(x.strip()) for x in parts]
    except (ValueError, ZeroDivisionError):
        ap.error(f"--point components must be exact rationals (got '{s}')")
    sv, tv = vals[0], vals[1]
    m2 = vals[2] if len(vals) == 3 else F(1)
    tag = next((k for k, p in points.items() if F(p["s"]) == sv and F(p["t"]) == tv and F(p["m2"]) == m2), None)
    return tag, sv, tv, m2

TS_PANELS = ({"a": 0, "b": 9, "thresh": None}, {"a": 9, "b": 30, "thresh": None}, {"a": 30, "b": 200, "thresh": None},
             {"a": 200, "map": "tail", "scale": 200})   # the second route's panels: no singular model on any panel; [200, inf) mapped
TS_CAPS = (3, 4, 5, 6)     # the degree-capped runs printed beside the adaptive run (nested nodes: through the caches they cost nothing beyond it)
TS_TAIL_K = 10             # the kernel scan w = 10^(dps+18+k), k = 0..TS_TAIL_K (past the kernel's working precision dps + 18)
TS_W1_LOG10 = 8            # rho_rem from the asymptotic series above 10^8 (the evaluator of record's W1)
TS_NMAX = 12               # the order of that series (the evaluator of record's Nmax)


def run_tanhsinh(args, tag, s, t, m2, u, label, ref, rec, bars, npins, stamp0, t_all, mp):
    """--route tanhsinh: the one-fold R by the dispersion-subtracted tanh-sinh quadrature (vendor_row27_box/disp_sub.py) on the
    served bundle's own rho_rem(w) (rhorem.py) and B(w) (boxkern.py) -- the evaluator of record's integrand, a different rule --
    compared string for string with the served route's R of record (points/P<i>/record.json) and, through eps^0 = the record's
    asymptotic part + R, with the goal-60 reference at the served bar.  Returns the exit code (0 PASS / 1 FAIL)."""
    sys.path.insert(0, VENDOR)
    import disp_sub as DS
    import lbl3disp as L
    import rhorem as RR
    import boxkern as BK
    for _mod in (DS, L, RR, BK, RR.SA):
        if os.path.dirname(os.path.abspath(_mod.__file__)) != VENDOR:
            die(RC_REFUSED, f"lbl3e-box-evaluate REFUSED: module {_mod.__name__} resolved outside vendor_row27_box/ ({_mod.__file__})")
    print("[route] the second route: R = -(1/pi) int_0^inf rho_rem(w) B(w) dw by the dispersion-subtracted tanh-sinh quadrature (vendor_row27_box/disp_sub.py): "
          "panels [0, 9], [9, 30], [30, 200] (no singular model) and [200, inf) through w = 200 + 200 (1 + t)/(1 - t); mpmath tanh-sinh on every panel, adaptive in "
          "the degree, working precision dps + 20 inside the quadrature; rho_rem from rhorem.py (-sigma below w = 9, the direct density on [9, 1e8), the asymptotic "
          "series above) and B(w) from boxkern.py -- the evaluator of record's integrand; the poles and the asymptotic part of eps^0 carry no one-fold and are "
          "read from the record")

    def one_fold(dps):
        mp.mp.dps = dps + 10                     # the ambient precision BEFORE the point is cast: the kinematics carry more than dps digits
        S = mp.mpf(s.numerator) / s.denominator
        T = mp.mpf(t.numerator) / t.denominator
        M2 = mp.mpf(m2.numerator) / m2.denominator
        U = -S - T
        W1 = mp.mpf(10) ** TS_W1_LOG10
        kc, rc = {}, {}
        seen = {"w_max": mp.mpf(0), "w_min_pos": None}

        def K(w):
            k = mp.nstr(w, dps + 8)
            if k not in kc:
                r, im = BK.box_dilog_complexsafe(T, U, M2, w, dps)
                if im > mp.mpf(10) ** (-(dps + 5)) * (abs(r) + 1):      # the evaluator of record's guard (box_assembly.B)
                    raise RuntimeError(f"box kernel Im residual {im} at w={w}")
                kc[k] = r
                if w > seen["w_max"]:
                    seen["w_max"] = +w
            return kc[k]

        def rho(w):
            k = mp.nstr(w, dps + 8)
            if k not in rc:
                if w <= 0:
                    rc[k] = mp.mpf(0)
                elif w < 9:
                    rc[k] = -RR.sigma(w, dps)
                elif w < W1:
                    rc[k] = RR.rho_rem_direct(w, dps)
                else:
                    rc[k] = RR.rho_rem_asym(w, dps, TS_NMAX)
                if w > 0 and (seen["w_min_pos"] is None or w < seen["w_min_pos"]):
                    seen["w_min_pos"] = +w
            return rc[k]

        print(f"[run] dps {dps} (the second route):")
        with mp.workdps(dps + 20):
            T0 = -BK.tri0(S, M2, dps=20, n=48)     # the large-w limit of w B(w) is -T0(s)
        tail, prev, ok_tail = [], None, True
        for k in range(TS_TAIL_K + 1):
            w = mp.mpf(10) ** (dps + 18 + k)
            try:
                r, im = BK.box_dilog_complexsafe(T, U, M2, w, dps)
                wb = w * r
                jump = None if prev is None else float(abs(wb - prev) / abs(prev))
                fin = bool(mp.isfinite(wb) and abs(wb) < 10 * abs(T0))
                tail.append({"k": k, "log10_w": dps + 18 + k, "wB": mp.nstr(wb, 20), "im": mp.nstr(im, 3), "rel_step_from_prev": jump, "finite_and_bounded": fin})
                ok_tail = ok_tail and fin and (jump is None or jump < 1e-3)
                prev = wb
            except Exception as e:
                tail.append({"k": k, "log10_w": dps + 18 + k, "error": f"{type(e).__name__}: {e}"})
                ok_tail = False
        print(f"  [tail-scan] w B(w) at w = 10^(dps+18+k), k = 0..{TS_TAIL_K} (the kernel's working precision is dps + 18 = {dps + 18} digits); "
              f"the limit -T0(s) = {mp.nstr(T0, 12)} (2D oracle, 48^2 nodes, dps 20): "
              + "; ".join(f"k={x['k']}: {x.get('wB', x.get('error'))[:22]}" for x in tail) + f" -> {'OK (finite, no jump)' if ok_tail else 'NOT OK'}")
        panels = [dict(p) for p in TS_PANELS]
        degree_runs, prevv = [], None
        t_run0 = time.time()
        for run_label, cap in [(f"maxdegree {c}", c) for c in TS_CAPS] + [("default (adaptive, <= mpmath guess_degree)", None)]:
            t0 = time.time()
            mp.mp.dps = dps + 10
            val = -DS.disp_subtracted(rho, K, panels, dps=dps, maxdegree=cap)
            wall = time.time() - t0
            with mp.workdps(dps + 20):
                ag = None if prevv is None else float(L.agree_digits(val, prevv))
            entry = {"run": run_label, "maxdegree": cap, "R": mp.nstr(val, dps + 4), "wall_s": round(wall, 2), "n_rho_cum": len(rc), "n_kernel_cum": len(kc),
                     "agree_with_previous_run_digits": ag}
            degree_runs.append(entry)
            print(f"  [degree] {run_label}: R = {entry['R']}  ({wall:.1f} s; rho evals {len(rc)}, kernel evals {len(kc)} cumulative"
                  + (f"; agrees with the previous run to {ag:.2f} d" if ag is not None else "") + ")")
            prevv = val
        wall_R = time.time() - t_run0
        print(f"  [R] R (this route's value = the adaptive run) = {mp.nstr(prevv, dps + 4)}; largest w reached by the tail map {mp.nstr(seen['w_max'], 4)} "
              f"(10^{float(mp.log10(seen['w_max'])):.1f}; kernel work 10^{dps + 18}); smallest w > 0 {mp.nstr(seen['w_min_pos'], 4)}; one-fold wall {wall_R:.1f} s")
        return {"R_mpf": prevv, "degree_runs": degree_runs, "n_rho": len(rc), "n_kernel": len(kc), "w_max_reached": mp.nstr(seen["w_max"], 8),
                "log10_w_max": float(mp.log10(seen["w_max"])), "w_min_pos": mp.nstr(seen["w_min_pos"], 8), "tail_scan": tail, "tail_scan_ok": ok_tail,
                "wall_one_fold_s": round(wall_R, 2)}

    runs = {}
    if args.check:
        runs[args.dps - DPS_PAIR_GAP] = one_fold(args.dps - DPS_PAIR_GAP)
    runs[args.dps] = one_fold(args.dps)
    if args.mutate:
        for d, r in runs.items():
            with mp.workdps(d + 20):
                r["R_mpf"] = r["R_mpf"] * (1 + mp.mpf(10) ** (-9))
        print("[mutate] the one-fold R by the second route is scaled by (1 + 1e-9) before the gates: the R string gate and the eps^0 gate must FAIL")
    for d, r in runs.items():
        r["R"] = mp.nstr(r["R_mpf"], d + 4)
        rs = rec["runs"][str(d)]["result"] if (rec is not None and str(d) in rec["runs"]) else None
        r["record"] = {"R": rs["R"], "I_0_asym_part": rs["I_0_asym_part"], "I_0": rs["I_0"]} if rs else None
        if rs:
            with mp.workdps(d + 20):
                r["I_0"] = mp.nstr(mp.mpf(rs["I_0_asym_part"]) + r["R_mpf"], d + 4)
        else:
            r["I_0"] = None
        del r["R_mpf"]
    main_out = runs[args.dps]
    gates = []

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

    bar = bar_at(args.dps, bars)
    comparison = {}
    if main_out["record"]:
        rs = main_out["record"]
        same = main_out["R"] == rs["R"]
        dR = agree(main_out["R"], rs["R"])
        pos = None if same else next((i + 1 for i, (a, b) in enumerate(zip(main_out["R"], rs["R"])) if a != b), min(len(main_out["R"]), len(rs["R"])) + 1)
        d60 = agree(main_out["I_0"], ref["orders"]["0"]["g60"]["mid"])
        d40 = agree(main_out["I_0"], ref["orders"]["0"]["g40"]["mid"])
        dsv = agree(main_out["I_0"], rs["I_0"])
        print(f"[compare] the second route (dps {args.dps}) vs the served route's strings of record at {tag} and the goal-60 reference (bar {bar} = "
              f"{'the record floor at this dps' if str(args.dps) in bars else 'min(45, dps - 3)'}):")
        nsig = len(rs["R"].lstrip("-").replace(".", "").lstrip("0"))
        print(f"  R: {main_out['R']}  vs the served route's R of record {rs['R']}: "
              + (f"identical to every printed digit ({nsig} significant digits)" if same else f"DIFFERENT from character position {pos} of {len(rs['R'])}; agreement {dR:.2f} d"))
        print(f"  eps^0: {main_out['I_0']}  vs goal 60 {d60:.2f} d, vs goal 40 {d40:.2f} d; vs the served route's eps^0 {rs['I_0']}: {dsv:.2f} d")
        comparison = {"R": main_out["R"], "R_served": rs["R"], "R_string_identical": same, "R_first_differing_position": pos, "R_vs_R_served_digits": dR,
                      "I_0": main_out["I_0"], "I_0_served": rs["I_0"], "I_0_asym_part": rs["I_0_asym_part"], "I_0_vs_g60_digits": d60, "I_0_vs_g40_digits": d40,
                      "I_0_vs_I_0_served_digits": dsv}
        gates.append({"gate": "R (second route) == the served route's R string of record", "digits": dR, "bar": "string identity", "pass": same, "note": ""})
        print(f"  [gate] R (second route) == the served route's R string of record: "
              + (f"identical ({nsig} significant digits)" if same else f"DIFFERENT from character position {pos} of {len(rs['R'])}, {dR:.2f} d") + f" -> {'PASS' if same else 'FAIL'}")
        gate("eps^0 (second route) vs the independent reference", d60, bar)
    else:
        print(f"[compare] no served R string at {tag + ' ' if tag else ''}dps {args.dps} (the record carries dps 32 and 48 at P1, P2, P3): R by the second route "
              "stands alone; no agreement is claimed")
    if args.check:
        lo = args.dps - DPS_PAIR_GAP
        barlo = bar_at(lo, bars)
        dpair = agree(runs[lo]["R"], main_out["R"])
        print(f"[check] the second route's own two-precision pair ({lo}, {args.dps}) (bar {barlo} at dps {lo}): R at dps {lo} {runs[lo]['R']}  vs dps {args.dps}: {dpair:.2f} d"
              + (f"; eps^0 at dps {lo} {runs[lo]['I_0']}  vs dps {args.dps}: {agree(runs[lo]['I_0'], main_out['I_0']):.2f} d" if runs[lo]["I_0"] and main_out["I_0"] else ""))
        gate(f"R two-precision pair {lo}/{args.dps} (second route)", dpair, barlo)
        comparison["pair"] = {"dps": [lo, args.dps], "R_lo": runs[lo]["R"], "R_pair_digits": dpair,
                              "I_0_pair_digits": agree(runs[lo]["I_0"], main_out["I_0"]) if runs[lo]["I_0"] and main_out["I_0"] else None}
    n_compare = len(gates)
    for d, r in runs.items():
        gates.append({"gate": f"kernel tail scan past 10^(dps+18) at dps {d}: finite, no jump", "digits": None, "bar": None, "pass": r["tail_scan_ok"], "note": ""})
        print(f"  [gate] kernel tail scan past 10^(dps+18) at dps {d}: {'OK' if r['tail_scan_ok'] else 'NOT OK'} -> {'PASS' if r['tail_scan_ok'] else 'FAIL'}")
    ok = all(g["pass"] for g in gates)
    wall = round(time.time() - t_all, 1)
    print(f"\nVALUE R (second route) at {label}(s, t) = ({s}, {t}), dps {args.dps}: {main_out['R']}")
    if main_out["I_0"]:
        print(f"VALUE eps^0 (the record's asymptotic part + R) at {label}(s, t) = ({s}, {t}): {main_out['I_0']}")
    else:
        print("VALUE eps^0: not assembled (no served asymptotic-part string at this point and dps)")
    if n_compare == 0:
        print(f"VERDICT UNREFERENCED: no served R string at this point and dps (R by the second route stands alone); the guard gate{'s' if len(gates) > 1 else ''} "
              f"{'met' if ok else 'FAILED'}; total wall {wall} s")
    else:
        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:
        recpt = {"PRODUCER": {"script": os.path.basename(__file__), "sha256": sha256_file(__file__), "route": "tanhsinh", "start": stamp0, "stamp": utc(), "wall_s": wall,
                              "pins_verified": npins, "stamp_source": "date -u", "mpmath": mp.__version__},
                 "args": {"point": args.point, "tag": tag, "s": str(s), "t": str(t), "m2": str(m2), "u": str(u), "dps": args.dps, "check": args.check,
                          "mutate": args.mutate, "unreferenced": args.unreferenced, "route": args.route},
                 "quadrature": {"panels": list(TS_PANELS), "caps": list(TS_CAPS), "working_dps_inside": "dps + 20", "ambient_dps": "dps + 10",
                                "integrand": "rhorem.sigma / rho_rem_direct / rho_rem_asym and boxkern.box_dilog_complexsafe of the served bundle"},
                 "bar": bar if main_out["record"] else None, "runs": {str(d): r for d, r in runs.items()}, "comparison": comparison, "gates": gates,
                 "verdict": ("PASS" if ok else "FAIL") if n_compare else "UNREFERENCED"}
        fd = os.open(args.out, os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o644)
        with os.fdopen(fd, "w") as f:
            json.dump(recpt, f, indent=1)
        print(f"[written] {os.path.basename(args.out)}")
    return 0 if ok else RC_FAIL

TRI_DIR = "triangles"       # vendor_row27_box/triangles/: the record's reference files for the tower, verbatim, pinned above
TRI_NEED = {"X_2eps-1": (-1, 0, 1), "X_2eps": (0, 1, 2), "X_eps": (0, 1, 2)}   # the coefficients the assembly consumes through eps^0 of I
TRI_ZEROS = {"X_2eps": (-1,), "X_eps": (-1,)}          # structural zeros (the series' eps^-1 is exactly 0): listed, never counted
TRI_LABEL = {"X_2eps-1": "X(1-2eps)", "X_2eps": "X(-2eps)", "X_eps": "X(-eps)"}
TRI_FAMILIES = {"GT3": {"family": "LBL3Ebox0", "targets": {"X_2eps-1": [1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0], "X_2eps": [1, 1, 2, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0]}},
                "GT2": {"family": "LBL3Ebub", "targets": {"X_eps": [1, 1, 1, 1, 1, 0, 0, 0, 0]}}}   # the vendored AMFlow outs: family + the target indices
TRI_GOALS = (60, 40)        # the AMFlow pair at each point: goal 60 the reference side, goal 40 beside it
TRI_LEG_DPS = (32, 48)      # the closed-form legs at each point
TRI_PAIR_BAR_A = 40         # the AMFlow pair's own bar (goal 40 vs goal 60): the lower goal
TRI_PAIR_BAR_B = 29         # the closed-form pair's own bar (dps 32 vs dps 48): the served bar at dps 32
TRI_DIVISOR_BAR = 60        # the two Gamma-series routes of every massless-bubble divisor must agree to this many digits
TRI_NSER = 8                # series length of the divisors (eps^lead .. eps^(lead+7))
TRI_CMP_DPS = 250           # the digit rule's working precision (the strings are read at this precision)


def tri_sig(s):
    """significant digits printed in a decimal string"""
    import re
    m = re.match(r"\s*[+-]?0*\.?0*([0-9][0-9.]*)", s.split("e")[0].split("E")[0])
    return len(m.group(1).replace(".", "")) if m else 0


def tri_compare(a_str, b_str, mp):
    """the digit rule: a = the reference string, b = this run's string; -log10 |a - b|/|b| at TRI_CMP_DPS digits, capped at the shorter
    printed length; 'identical (N significant digits)' when the two agree to the shorter's full length"""
    na, nb = tri_sig(a_str), tri_sig(b_str)
    cap = min(na, nb)
    with mp.workdps(TRI_CMP_DPS):
        A, B = mp.mpf(a_str), mp.mpf(b_str)
        if B == 0:
            return {"digits": None, "cap": cap, "identical": bool(A == 0), "label": "this run's value is zero (absolute |a| = %s)" % mp.nstr(abs(A), 5)}
        if A == B:
            return {"digits": float(cap), "cap": cap, "identical": True, "label": f"identical ({cap} significant digits)"}
        d = float(-mp.log10(abs(A - B) / abs(B)))
    if d >= cap:
        return {"digits": float(cap), "cap": cap, "identical": True, "label": f"identical ({cap} significant digits)"}
    return {"digits": d, "cap": cap, "identical": False, "label": f"{d:.2f} d (cap {cap})"}


def tri_floor(rows, mp, key="digits"):
    """the paste-ready count: the FLOOR of the minimum over the counted set, with the members (sorted, two decimals)"""
    vals = [r[key] for r in rows if r.get(key) is not None]
    if not vals:
        return None, []
    return int(mp.floor(min(vals))), [round(x, 2) for x in sorted(vals)]


def tri_coeff(block, k):
    """the string of eps^k from a {'lead', 'c'} block (the record's X form); None outside the block"""
    i = k - block["lead"]
    return block["c"][i] if 0 <= i < len(block["c"]) else None


def run_triangles(args, tag, s, t, m2, u, label, ref, rec, bars, npins, stamp0, t_all, mp):
    """--triangles: the generalised-triangle tower X(1-2eps), X(-2eps), X(-eps) recomputed at the point and dps with the served
    gentri.py (as the assembly's run calls it) and compared coefficient by coefficient with the two vendored references (A: the
    AMFlow outs on the massless-insertion families at goal 40 and 60, through the massless-bubble divisors; B: the closed one-loop
    form's legs at dps 32 and 48); the floors of the minimum with members, PASS/FAIL vs the served bars by name.  Returns the exit
    code (0 PASS / 1 FAIL)."""
    import re
    sys.path.insert(0, VENDOR)
    import box_assembly as BA
    import epsser as ES
    import gentri as GT
    for _mod in (BA, BA.SA, BA.RR, BA.L, ES, GT):
        if os.path.dirname(os.path.abspath(_mod.__file__)) != VENDOR:
            die(RC_REFUSED, f"lbl3e-box-evaluate REFUSED: module {_mod.__name__} resolved outside vendor_row27_box/ ({_mod.__file__})")
    S = ES.S
    tri = os.path.join(VENDOR, TRI_DIR)
    print("[triangles] the tower of record: I = -C_0 X(1-2eps) + C_1 X(-2eps) + T D_0 X(-eps) + R consumes, through eps^0 of I, nine coefficients -- X(1-2eps) at "
          "eps^-1 (= -1/3, the UV pole), eps^0, eps^1; X(-2eps) and X(-eps) at eps^0 (= T0(s)), eps^1, eps^2 (their eps^-1 is a structural zero, excluded); two "
          "independent one-loop references, vendored verbatim in vendor_row27_box/triangles/ and pinned: (A) AMFlow on the massless-insertion families (the "
          "three-loop family with the sunrise lines massless: the corner integral and the integral with one dot; the two-loop family with a massless bubble) "
          "at goal 40 and 60, divided by the exact massless-bubble factors G(a, b) as eps-series by two routes; (B) the closed one-loop form (Cheng-Wu, "
          "the rung integral as a Beta function times a 2F1 at complex eps, the Laurent coefficients by a Cauchy contour) at dps 32 and 48; the digit rule: "
          f"-log10 |a - b|/|b| with b this run's string at {TRI_CMP_DPS} digits, capped at the shorter string's significant digits, identical (N) at the "
          "shorter's full length; the paste-ready count is the floor of the minimum over the nine, members beside it")

    def one_tower(dps):
        mp.mp.dps = dps + 10                     # the ambient precision of the assembly's run BEFORE the point is cast
        S_ = mp.mpf(s.numerator) / s.denominator
        T_ = mp.mpf(t.numerator) / t.denominator
        M2_ = mp.mpf(m2.numerator) / m2.denominator
        print(f"[run] dps {dps} (the triangles):")
        T0 = time.time()
        n = 6
        with mp.workdps(dps + 20):
            C0 = BA.SA.C_N(0, n); C1 = BA.SA.C_N(1, n); TD0 = BA.SA.tadpole(n) * BA.SA.D_M(0, n)
        gt = GT.GenTri(S_, T_, M2_, dps, nser=5)
        X0 = gt.X_0(); tX0 = time.time() - T0
        X1 = gt.X_q(2); tX1 = time.time() - T0 - tX0
        X2 = gt.X_q(1); tX2 = time.time() - T0 - tX0 - tX1
        if args.mutate:
            with mp.workdps(dps + 20):
                i0 = 0 - X0.lead
                X0.c[i0] = X0.c[i0] * (1 + mp.mpf(10) ** (-9))
        with mp.workdps(dps + 20):
            Iser = (-C0) * X0 + C1 * X1 + TD0 * X2
            X = {k: {"lead": v.lead, "c": [mp.nstr(c, dps + 4) for c in v.c]} for k, v in (("X_2eps-1", X0), ("X_2eps", X1), ("X_eps", X2))}
            cons = float(BA.L.agree_digits(X1.coeff(0), X2.coeff(0)))
            I = {"I_m2": mp.nstr(Iser.coeff(-2), dps + 4), "I_m1": mp.nstr(Iser.coeff(-1), dps + 4), "I_0_asym_part": mp.nstr(Iser.coeff(0), dps + 4)}
        print(f"    [X] walls {tX0:.1f}/{tX1:.1f}/{tX2:.1f} s; inner 2D calls {gt.n_inner_calls}; X(eps)^0 vs X(2eps)^0 {cons:.1f} d")
        if args.mutate:
            print("    [mutate] X(1-2eps) at eps^0 is scaled by (1 + 1e-9) before the comparisons: both references must FAIL")
        for name in TRI_NEED:
            print(f"    [X] {TRI_LABEL[name]}: " + "  ".join(f"eps^{k} {tri_coeff(X[name], k)}" for k in range(X[name]['lead'], X[name]['lead'] + len(X[name]['c']))))
        print(f"    [closure] -C_0 X(1-2eps) + C_1 X(-2eps) + T D_0 X(-eps): eps^-2 {I['I_m2']}  eps^-1 {I['I_m1']}  eps^0 asym-part {I['I_0_asym_part']}")
        record = None
        if rec is not None and str(dps) in rec["runs"]:
            rr = rec["runs"][str(dps)]["result"]
            record = {"X_identical": {}, "closure_identical": {}, "closure_digits": {}}
            parts = []
            for name in TRI_NEED:
                same = rr["X"][name]["lead"] == X[name]["lead"] and rr["X"][name]["c"] == X[name]["c"]
                record["X_identical"][name] = same
                if same:
                    parts.append(f"{TRI_LABEL[name]} identical ({len(X[name]['c'])} strings)")
                else:
                    kd = next((k for k in range(X[name]["lead"], X[name]["lead"] + len(X[name]["c"])) if tri_coeff(rr["X"][name], k) != tri_coeff(X[name], k)), None)
                    dd = agree(tri_coeff(X[name], kd), tri_coeff(rr["X"][name], kd)) if kd is not None and tri_coeff(rr["X"][name], kd) not in (None, "0.0") else None
                    parts.append(f"{TRI_LABEL[name]} DIFFERENT at eps^{kd}" + (f" ({dd:.2f} d)" if dd is not None else ""))
            print(f"    [record] the record's own dps-{dps} X strings at {tag}: " + ", ".join(parts))
            parts = []
            for key, lab in (("I_m2", "eps^-2"), ("I_m1", "eps^-1"), ("I_0_asym_part", "eps^0 asym-part")):
                same = rr[key] == I[key]
                record["closure_identical"][key] = same
                record["closure_digits"][key] = agree(I[key], rr[key])
                parts.append(f"{lab} " + ("identical" if same else f"DIFFERENT ({record['closure_digits'][key]:.2f} d)"))
            print(f"    [record] the record's dps-{dps} poles and asymptotic part at {tag} reassembled from the nine coefficients: " + ", ".join(parts))
        return {"X": X, "I_closure": I, "record": record, "wall_X_s": {"X_2eps-1": round(tX0, 2), "X_2eps": round(tX1, 2), "X_eps": round(tX2, 2)},
                "gentri_params": {"n_in": gt.n_in, "nt": gt.nt, "dw": gt.dw, "n_inner_calls": gt.n_inner_calls}, "X_eps0_consistency_d": cons}

    runs = {}
    if args.check:
        runs[args.dps - DPS_PAIR_GAP] = one_tower(args.dps - DPS_PAIR_GAP)
    runs[args.dps] = one_tower(args.dps)
    main_out = runs[args.dps]
    Xr = main_out["X"]
    D = args.dps
    bar = bar_at(D, bars)
    gates, rows, zeros = [], [], []
    forms = {}

    # ---- the massless-bubble divisors by two Gamma-series routes (the AMFlow integrals -> the triangles)
    def gamma_A(m, k, n):
        g = ES.gamma_ser(m, k, n)
        return g.lead, list(g.c)

    def gamma_B(m, k, n):
        with mp.workdps(mp.mp.dps + 30):
            c = mp.taylor(lambda e: mp.gamma(1 + k * e), 0, n - 1)
            g1 = S([mp.mpf(x) for x in c], 0, n)
            x = S.eps(n) * k
            p = S.const(1, n)
            if m >= 1:
                for j in range(1, m):
                    p = p * (x + j)
                r = g1 * p
            else:
                for j in range(m, 1):
                    p = p * (x + j)
                r = g1 / p
            r = r.normalize()
        return r.lead, [mp.mpf(v) for v in r.c]

    def Gser(a, b_int, b_k, route, n):
        gs = gamma_A if route == "A" else gamma_B

        def g(m, k):
            lead, c = gs(m, k, n)
            return S(c, lead, n)
        t1 = g(a + b_int - 2, b_k + 1)
        t2 = g(2 - a, -1)
        t3 = g(2 - b_int, -1 - b_k)
        d1 = g(a, 0)
        d2 = g(b_int, b_k)
        d3 = g(4 - a - b_int, -2 - b_k)
        return (t1 * t2 * t3 / (d1 * d2 * d3)).normalize()

    def divisors(route, n):
        G11 = Gser(1, 1, 0, route, n)
        G1e = Gser(1, 0, 1, route, n)
        G12 = Gser(1, 2, 0, route, n)
        G11e = Gser(1, 1, 1, route, n)
        return {"X_2eps-1": (-1, (G11 * G1e).normalize()), "X_2eps": (+1, (G12 * G11e).normalize()), "X_eps": (+1, G11)}

    def ser_agree(A, B, orders):
        out = {}
        for k in orders:
            a, b = A.coeff(k), B.coeff(k)
            out[k] = float("inf") if a == b else (float(-mp.log10(abs(a))) if b == 0 else float(-mp.log10(abs(a - b) / abs(b))))
        return out

    def parse_out(path, fam):
        """a vendored AMFlow out -> {tower: (lead, [mpf], [strings])} for the family's targets; a wrong family / target set / a
        non-zero imaginary part is a named FAIL (the file is pinned: only a re-pinned alteration reaches here)"""
        O = json.load(open(path))
        want = TRI_FAMILIES[fam]
        got = {}
        for e in O.get("result") or []:
            if e["integral"].get("family") not in (None, want["family"]):
                return None, f"{os.path.basename(path)}: family {e['integral'].get('family')} is not {want['family']}"
            for tower, idx in want["targets"].items():
                if e["integral"]["indices"] == idx:
                    cs = sorted(e["coefficients"], key=lambda c: int(c["order"]))
                    orders = [int(c["order"]) for c in cs]
                    if orders != list(range(orders[0], orders[0] + len(orders))):
                        return None, f"{os.path.basename(path)}: non-contiguous eps orders {orders}"
                    mids, strs = [], []
                    for c in cs:
                        re_s = c["value"]["re"].strip(); im_s = c["value"]["im"].strip()
                        mid = re_s[1:].split("+/-")[0].strip() if re_s.startswith("[") else re_s
                        imm = im_s[1:].split("+/-")[0].strip() if im_s.startswith("[") else im_s
                        if mp.mpf(imm or "0") != 0:
                            return None, f"{os.path.basename(path)}: non-zero imaginary part {imm} at {idx} eps^{c['order']} (a Euclidean point is real)"
                        mids.append(mp.mpf(mid)); strs.append(mid)
                    got[tower] = (orders[0], mids, strs)
        missing = [tw for tw in want["targets"] if tw not in got]
        if missing:
            return None, f"{os.path.basename(path)}: targets for {missing} absent (family {want['family']})"
        return got, None

    def X_from_out(got, goal, DA):
        out = {}
        for tower, (lead, mids, strs) in got.items():
            sgn, Dv = DA[tower]
            Iv = S(list(mids), lead, len(mids)).normalize()
            Xv = (Iv * sgn / Dv).normalize()
            out[tower] = {"lead": Xv.lead, "c": [mp.nstr(Xv.coeff(k), goal + 2) for k in range(Xv.lead, Xv.lead + 6)], "I_lead": lead, "I_strings": strs,
                          "divisor_sign": sgn, "divisor_lead": Dv.lead, "divisor_c": [mp.nstr(Dv.coeff(k), 30) for k in range(Dv.lead, Dv.lead + 5)]}
        return out

    # ---- Form A: the AMFlow outs at this point, goal 60 (the reference side) and goal 40 (the pair)
    print(f"[compare] the nine coefficients at {tag}, dps {D} (bar {bar} = {'the record floor at this dps' if str(D) in bars else 'min(45, dps - 3)'}; the references' own pairs: "
          f"A goal 40 vs goal 60 bar {TRI_PAIR_BAR_A}, B dps 32 vs dps 48 bar {TRI_PAIR_BAR_B}):")
    named_fail = []
    with mp.workdps(TRI_CMP_DPS):
        DA, DB = divisors("A", TRI_NSER), divisors("B", TRI_NSER)
        div_min, div_at = None, None
        for tower in DA:
            ag = ser_agree(DA[tower][1], DB[tower][1], range(DA[tower][1].lead, DA[tower][1].lead + 5))
            for k, v in ag.items():
                if div_min is None or v < div_min:
                    div_min, div_at = v, f"{TRI_LABEL[tower]} divisor eps^{k}"
        XA = {}
        for goal in TRI_GOALS:
            XA[goal] = {}
            for fam in ("GT3", "GT2"):
                p = os.path.join(tri, f"{fam}_{tag}_g{goal}.json")
                got, err = parse_out(p, fam)
                if err:
                    named_fail.append(f"Form A: {err}")
                    continue
                XA[goal].update(X_from_out(got, goal, DA))
        forms["A"] = {"files": {f"{fam}_{tag}_g{goal}.json": PINS[f"vendor_row27_box/triangles/{fam}_{tag}_g{goal}.json"] for goal in TRI_GOALS for fam in ("GT3", "GT2")},
                      "X_goal60": XA[60], "X_goal40": XA[40],
                      "divisors_route_A": {tw: {"sign": DA[tw][0], "lead": DA[tw][1].lead, "c": [mp.nstr(DA[tw][1].coeff(k), 30) for k in range(DA[tw][1].lead, DA[tw][1].lead + 5)]} for tw in DA},
                      "divisor_routes_min_agreement_d": div_min, "divisor_routes_min_at": div_at}
    for tower in TRI_NEED:
        for k in TRI_NEED[tower]:
            a = tri_coeff(XA[60][tower], k) if tower in XA[60] else None
            b = tri_coeff(Xr[tower], k)
            if a is None or b is None:
                named_fail.append(f"Form A: eps^{k} of {TRI_LABEL[tower]} absent on a side")
                continue
            c = tri_compare(a, b, mp)
            row = {"form": "A", "tower": tower, "order": k, "reference": a, "this_run": b, **c, "bar": bar, "pass": (c["digits"] or 0) >= bar}
            if tower in XA[40]:
                cp = tri_compare(tri_coeff(XA[40][tower], k), a, mp)
                row["pair_g40_vs_g60"] = cp; row["pair_pass"] = (cp["digits"] or 0) >= TRI_PAIR_BAR_A
            rows.append(row)
            print(f"  [A goal 60] {TRI_LABEL[tower]} eps^{k}: reference {a[:D + 8]} vs this run {b[:D + 8]}: {c['label']} {'PASS' if row['pass'] else 'FAIL'}"
                  + (f"; goal 40 vs goal 60 {row['pair_g40_vs_g60']['label']}" if "pair_g40_vs_g60" in row else ""))
        for k in TRI_ZEROS.get(tower, ()):
            zeros.append({"form": "A", "tower": tower, "order": k, "this_run": tri_coeff(Xr[tower], k), "reference": tri_coeff(XA[60][tower], k) if tower in XA[60] else None,
                          "note": "structural zero: excluded from every count (the divisor's lead removes eps^-1 exactly)"})
    # ---- Form B: the closed-form leg at this dps (the reference side) and the leg at the other dps of (32, 48) (the pair)
    XB = pair_leg = None
    if D in TRI_LEG_DPS:
        leg = json.load(open(os.path.join(tri, f"closed_{tag}_d{D}.json")))
        other = [d for d in TRI_LEG_DPS if d != D][0]
        pair_leg = json.load(open(os.path.join(tri, f"closed_{tag}_d{other}.json")))
        for L_, d_ in ((leg, D), (pair_leg, other)):
            if L_.get("verdict") != "DONE" or L_["args"].get("tag") != tag or int(L_["args"]["dps"]) != d_ or L_["args"].get("mutate"):
                named_fail.append(f"Form B: the vendored leg closed_{tag}_d{d_}.json is not a DONE, unmutated leg at {tag} dps {d_}")
        XB = leg["coefficients"]
        forms["B"] = {"files": {f"closed_{tag}_d{d_}.json": PINS[f"vendor_row27_box/triangles/closed_{tag}_d{d_}.json"] for d_ in TRI_LEG_DPS}, "X_leg": XB,
                      "leg_dps": D, "pair_dps": other, "leg_gates": leg.get("gates"), "pair_gates": pair_leg.get("gates")}
        lo, hi = (pair_leg, leg) if other < D else (leg, pair_leg)
        for tower in TRI_NEED:
            for k in TRI_NEED[tower]:
                a = tri_coeff(XB[tower], k); b = tri_coeff(Xr[tower], k)
                c = tri_compare(a, b, mp)
                cp = tri_compare(tri_coeff(lo["coefficients"][tower], k), tri_coeff(hi["coefficients"][tower], k), mp)
                row = {"form": "B", "tower": tower, "order": k, "reference": a, "this_run": b, **c, "bar": bar, "pass": (c["digits"] or 0) >= bar,
                       "pair_32_vs_48": cp, "pair_pass": (cp["digits"] or 0) >= TRI_PAIR_BAR_B}
                rows.append(row)
                print(f"  [B dps {D}] {TRI_LABEL[tower]} eps^{k}: reference {a[:D + 8]} vs this run {b[:D + 8]}: {c['label']} {'PASS' if row['pass'] else 'FAIL'}; dps 32 vs dps 48 {cp['label']}")
            for k in TRI_ZEROS.get(tower, ()):
                zeros.append({"form": "B", "tower": tower, "order": k, "this_run": tri_coeff(Xr[tower], k), "reference": tri_coeff(XB[tower], k),
                              "note": "structural zero: excluded; the closed form's absolute size there is its contour rounding"})
    else:
        print(f"  [B] no closed-form leg is vendored at dps {D} (the legs sit at dps {TRI_LEG_DPS[0]} and {TRI_LEG_DPS[1]}): the comparison is with the AMFlow reference alone")
    # ---- the summaries: floors of the minimum with members; the gates by name
    summ = {}
    for form, pk, pbar, pname, fname in (("A", "pair_g40_vs_g60", TRI_PAIR_BAR_A, "goal 40 vs goal 60", "AMFlow, goal 60"),
                                          ("B", "pair_32_vs_48", TRI_PAIR_BAR_B, "dps 32 vs dps 48", f"closed form, dps {D}")):
        R = [r for r in rows if r["form"] == form]
        if not R:
            continue
        fl, members = tri_floor(R, mp)
        summ[form] = {"n_counted": len(R), "floor_of_min_digits": fl, "members_sorted": members, "all_pass": all(r["pass"] for r in R),
                      "identical_count": sum(1 for r in R if r["identical"]), "bar": bar}
        PR = [r[pk] for r in R if pk in r]
        if PR:
            fl2, m2_ = tri_floor(PR, mp)
            summ[form]["pair"] = {"n": len(PR), "floor_of_min_digits": fl2, "members_sorted": m2_, "bar": pbar, "all_pass": all(r.get("pair_pass", True) for r in R)}
        print(f"  [{form}: {fname}] PASTE-READY {fl} d = the floor of the minimum over the {len(R)} counted coefficients (members {members}); identical to the full printed length "
              f"{summ[form]['identical_count']} of {len(R)}" + (f"; the reference's own pair ({pname}) {summ[form]['pair']['floor_of_min_digits']} d (members {summ[form]['pair']['members_sorted']})" if PR else ""))
        gates.append({"gate": f"Form {form}: every counted coefficient vs this run >= {bar} d", "floor_of_min": fl, "members": members, "pass": summ[form]["all_pass"]})
        if PR:
            gates.append({"gate": f"Form {form}: the reference's own pair ({pname}) >= {pbar} d on every counted coefficient", "floor_of_min": summ[form]["pair"]["floor_of_min_digits"],
                          "members": summ[form]["pair"]["members_sorted"], "pass": summ[form]["pair"]["all_pass"]})
    for z in zeros:
        print(f"  [structural zero, excluded] Form {z['form']} {TRI_LABEL[z['tower']]} eps^{z['order']}: this run '{z['this_run']}', reference {('absent by construction' if z['reference'] is None else repr(z['reference']))}")
    gates.append({"gate": f"the massless-bubble divisors: the two Gamma-series routes agree >= {TRI_DIVISOR_BAR} d on every coefficient",
                  "floor_of_min": (None if div_min is None else ("inf" if div_min == float("inf") else int(mp.floor(div_min)))), "members": [div_at],
                  "pass": div_min is not None and div_min >= TRI_DIVISOR_BAR})
    pair_summary = None
    if args.check:
        lo_ = D - DPS_PAIR_GAP
        barlo = bar_at(lo_, bars)
        PR = []
        for tower in TRI_NEED:
            for k in TRI_NEED[tower]:
                cp = tri_compare(tri_coeff(runs[lo_]["X"][tower], k), tri_coeff(Xr[tower], k), mp)
                PR.append({"tower": tower, "order": k, **cp, "pass": (cp["digits"] or 0) >= barlo})
        fl3, m3 = tri_floor(PR, mp)
        pair_summary = {"dps": [lo_, D], "bar": barlo, "floor_of_min_digits": fl3, "members_sorted": m3, "rows": PR, "all_pass": all(r["pass"] for r in PR)}
        print(f"[check] the tower's own two-precision pair ({lo_}, {D}) on the nine coefficients (bar {barlo} at dps {lo_}): floor {fl3} d (members {m3}); "
              + "; ".join(f"{TRI_LABEL[r['tower']]} eps^{r['order']} {r['label']}" for r in PR))
        gates.append({"gate": f"the tower's own two-precision pair {lo_}/{D} >= {barlo} d on every counted coefficient", "floor_of_min": fl3, "members": m3, "pass": pair_summary["all_pass"]})
    for nf in named_fail:
        gates.append({"gate": nf, "floor_of_min": None, "members": [], "pass": False})
    for g in gates:
        print(f"  [gate] {g['gate']}: " + (f"floor {g['floor_of_min']}" if g["floor_of_min"] is not None else "not established") + f" -> {'PASS' if g['pass'] else 'FAIL'}")
    ok = all(g["pass"] for g in gates)
    wall = round(time.time() - t_all, 1)
    print()
    for tower in TRI_NEED:
        print(f"VALUE {TRI_LABEL[tower]} at {label}(s, t) = ({s}, {t}), dps {D}: " + "  ".join(f"eps^{k} {tri_coeff(Xr[tower], k)}" for k in TRI_NEED[tower]))
    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:
        recpt = {"PRODUCER": {"script": os.path.basename(__file__), "sha256": sha256_file(__file__), "tier": "triangles", "start": stamp0, "stamp": utc(), "wall_s": wall,
                              "pins_verified": npins, "stamp_source": "date -u", "mpmath": mp.__version__},
                 "args": {"point": args.point, "tag": tag, "s": str(s), "t": str(t), "m2": str(m2), "u": str(u), "dps": args.dps, "check": args.check,
                          "mutate": args.mutate, "triangles": True},
                 "needed_orders": TRI_NEED, "structural_zero_orders": TRI_ZEROS,
                 "digit_rule": f"-log10 |a - b|/|b|, b = this run's string, at {TRI_CMP_DPS} digits; capped at the shorter string's significant digits; equal to the shorter's full "
                               "length -> identical (N significant digits); paste-ready counts = floor(min over the counted set), members listed",
                 "bars": {"this_run_vs_reference": bar, "pair_A": TRI_PAIR_BAR_A, "pair_B": TRI_PAIR_BAR_B, "divisor_routes": TRI_DIVISOR_BAR},
                 "runs": {str(d): r for d, r in runs.items()}, "forms": forms, "rows": rows, "structural_zeros_excluded": zeros, "summary": summ,
                 "pair": pair_summary, "gates": gates, "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(recpt, f, indent=1, default=str)
        print(f"[written] {os.path.basename(args.out)}")
    return 0 if ok else RC_FAIL


def main():
    ap = argparse.ArgumentParser(
        description="Row 27 (LBL3E): the sunrise-dressed box assembled at a Euclidean (s, t) point through eps^0 and compared with "
                    "the independent AMFlow value there (three shipped points; P3 blind).",
        epilog="measured walls (GNU time wall clock, one process, nice 10, a shared 96-core host at loadavg ~120-130): "
               + "; ".join(f"{k}: {v}" for k, v in WALLS.items()) + ".  Exit codes: 0 PASS, 1 FAIL, 2 usage, 3 REFUSED by a pin, 4 MISSING.")
    ap.add_argument("--point", default="P1", metavar="P|s,t[,m2]", help="P1, P2, P3 or exact rationals s,t[,m2] (default P1 = -7/3,-11/10,1)")
    ap.add_argument("--route", choices=("served", "tanhsinh"), default="served", metavar="ROUTE",
                    help="served (the default: the evaluator of record) or tanhsinh: the one-fold R by the dispersion-subtracted tanh-sinh quadrature "
                         "(vendor_row27_box/disp_sub.py) on the same rho_rem(w) B(w), compared string for string with the served route's R of record, "
                         "and eps^0 = the record's asymptotic part + R against the reference at the served bar")
    ap.add_argument("--triangles", action="store_true",
                    help="the generalised-triangle tower X(1-2eps), X(-2eps), X(-eps) recomputed at the point and dps and compared coefficient by "
                         "coefficient with the two vendored references (vendor_row27_box/triangles/: AMFlow at goal 40 and 60 on the massless-insertion "
                         "families; the closed one-loop form at dps 32 and 48); the one-fold R is not computed")
    ap.add_argument("--dps", type=int, default=32, help="working precision (default 32; the dps of record for the 45-digit bar is 48)")
    ap.add_argument("--check", action="store_true", help=f"two-precision rule: run at dps-{DPS_PAIR_GAP} and dps, gate their agreement too (the record's pair 32/48)")
    ap.add_argument("--unreferenced", action="store_true", help="allow a point without a shipped reference: the value is printed, no agreement is claimed")
    ap.add_argument("--mutate", action="store_true", help="control: scale the one-fold R by (1 + 1e-9) before the assembly; the run must exit nonzero")
    ap.add_argument("--out", default=None, metavar="JSON", help="write the run receipt here (never overwrites: an existing path is refused by name before anything is computed)")
    args = ap.parse_args()
    if args.triangles and args.route != "served":
        ap.error("--triangles and --route tanhsinh are separate tiers: give one of them")
    if args.triangles and args.unreferenced:
        ap.error("--triangles needs a shipped point (P1, P2, P3): the references are vendored at those points only; --unreferenced does not apply")
    if args.out is not None and os.path.exists(args.out):
        ap.error(f"--out {args.out} exists; this script never overwrites -- give a new path")
    try:
        sys.stdout.reconfigure(line_buffering=True)
    except AttributeError:
        pass
    t_all = time.time()
    stamp0 = utc()
    if args.dps < 8:
        ap.error("--dps must be >= 8")
    if args.check and args.dps - DPS_PAIR_GAP < 8:
        ap.error(f"--check needs --dps >= {8 + DPS_PAIR_GAP} (the pair is dps-{DPS_PAIR_GAP} and dps)")
    try:
        import mpmath as mp
    except ImportError:
        die(RC_MISSING, "lbl3e-box-evaluate MISSING: mpmath is not installed (pip install mpmath); nothing computed")
    npins = check_pins()
    pts = json.load(open(os.path.join(VENDOR, "points", "points.json")))
    points, bars = pts["points"], pts["bars"]
    assert int(bars["48"]) == BAR_TOP, "the shipped bar at dps 48 differs from this script's constant"
    tag, s, t, m2 = parse_point(args.point, ap, points)
    u = -s - t
    label = f"{tag} = " if tag else ""
    print(f"[mode] LBL3E sunrise-dressed box assembled at {label}(s, t, m^2) = ({s}, {t}, {m2}), u = {u}, dps {args.dps}"
          + (f" with --check (pair {args.dps - DPS_PAIR_GAP}/{args.dps})" if args.check else "") + (" [MUTATED control]" if args.mutate else "")
          + (" [--route tanhsinh: eps^0 = the record's asymptotic part + the one-fold R by the second route]" if args.route == "tanhsinh" else "")
          + (" [--triangles: the generalised-triangle tower recomputed and compared with two independent references]" if args.triangles else ""))
    print(f"[pins] {npins} shipped/served files verified by sha256")
    if not (s < 0 and t < 0):
        die(RC_USAGE, f"lbl3e-box-evaluate REFUSED (usage): (s, t) = ({s}, {t}) is outside the Euclidean domain of the assembly "
                      f"(both cut channels below threshold: s < 0 and t < 0); Minkowski or threshold points are not implemented")
    if m2 != 1:
        die(RC_USAGE, f"lbl3e-box-evaluate REFUSED (usage): m^2 = {m2}; the assembly is coded at unit mass (m^2 = 1) -- rescale s and t")
    if tag is None and not args.unreferenced:
        die(RC_USAGE, f"lbl3e-box-evaluate REFUSED (usage): no independent reference is shipped at (s, t) = ({s}, {t}) "
                      f"(the shipped points: {', '.join(f'{k} = ({p[chr(115)]}, {p[chr(116)]})' for k, p in points.items())}); "
                      f"pass --unreferenced to compute the value alone, with no agreement claimed")
    # the reference and the record at a shipped point
    ref = rec = None
    if tag:
        ref = json.load(open(os.path.join(VENDOR, "points", tag, "reference.json")))
        rec = json.load(open(os.path.join(VENDOR, "points", tag, "record.json")))
        assert F(ref["point"]["s"]) == s and F(ref["point"]["t"]) == t and F(rec["point"]["s"]) == s
        o0 = ref["orders"]["0"]
        print(f"[reference] independent AMFlow values at {tag} (shipped, pinned): eps^0 = {o0['g60']['mid'][:62]}... (goal 60; "
              f"the goal-40/goal-60 pair agrees to {o0['pair_agreement_digits_g40_vs_g60']} d at eps^0, "
              f"{ref['orders']['-1']['pair_agreement_digits_g40_vs_g60']} d at eps^-1, {ref['orders']['-2']['pair_agreement_digits_g40_vs_g60']} d at eps^-2)")
        if tag == "P3":
            pr = json.load(open(os.path.join(VENDOR, "points", "P3", "prediction.json")))
            print(f"[blind] P3: the assembly's value was filed at {pr['prediction']['receipt_stamp_utc']} (receipt sha256 {pr['prediction']['receipt_sha256'][:16]}...); "
                  f"the AMFlow pair was launched at {pr['independent_computation']['launched_utc']} and landed at {pr['independent_computation']['landed_utc']}; "
                  f"the filed dps-48 prediction agrees with the goal-60 value at eps^0 to {pr['comparison']['per_order']['0']['prediction_vs_g60_digits']} d")
    else:
        print(f"[reference] NO independent reference is shipped at (s, t) = ({s}, {t}): the value below is computed by the same route, "
              f"no agreement is claimed (the shipped references sit at {', '.join(points)})")
    if args.triangles:
        sys.exit(run_triangles(args, tag, s, t, m2, u, label, ref, rec, bars, npins, stamp0, t_all, mp))
    if args.route == "tanhsinh":
        sys.exit(run_tanhsinh(args, tag, s, t, m2, u, label, ref, rec, bars, npins, stamp0, t_all, mp))
    # the assembly (the evaluator of record, vendored)
    sys.path.insert(0, VENDOR)
    import box_assembly as BA
    for _mod in (BA, BA.SA, BA.RR, BA.L):
        if os.path.dirname(os.path.abspath(_mod.__file__)) != VENDOR:
            die(RC_REFUSED, f"lbl3e-box-evaluate REFUSED: module {_mod.__name__} resolved outside vendor_row27_box/ ({_mod.__file__})")
    if args.mutate:
        _orig = BA.RR.integrate_rho_rem

        def _mutated(kern, dps, *a, **k):
            r, diag = _orig(kern, dps, *a, **k)
            with mp.workdps(dps + 20):
                r = r * (1 + mp.mpf(10) ** (-9))
            return r, diag
        BA.RR.integrate_rho_rem = _mutated
        print("[mutate] the one-fold R is scaled by (1 + 1e-9) before the assembly: the eps^0 gate must FAIL")

    def one_run(dps):
        mp.mp.dps = dps + 10
        print(f"[run] dps {dps}:")
        t0 = time.time()
        out = BA.run(dps, mp.mpf(s.numerator) / s.denominator, mp.mpf(t.numerator) / t.denominator, mp.mpf(m2.numerator) / m2.denominator,
                     log=lambda m: print("  " + m))
        out["wall_s_measured_here"] = round(time.time() - t0, 1)
        return out

    runs = {}
    if args.check:
        runs[args.dps - DPS_PAIR_GAP] = one_run(args.dps - DPS_PAIR_GAP)
    runs[args.dps] = one_run(args.dps)
    main_out = runs[args.dps]
    ORD = (("-2", "I_m2"), ("-1", "I_m1"), ("0", "I_0"))
    gates = []

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

    bar = bar_at(args.dps, bars)
    comparison = {}
    if ref:
        print(f"[compare] this run (dps {args.dps}) vs the goal-60 reference, per order (bar {bar} = "
              f"{'the record floor at this dps' if str(args.dps) in bars else 'min(45, dps - 3)'}):")
        for o, key in ORD:
            d60 = agree(main_out[key], ref["orders"][o]["g60"]["mid"])
            d40 = agree(main_out[key], ref["orders"][o]["g40"]["mid"])
            comparison[o] = {"value": main_out[key], "vs_g60_digits": d60, "vs_g40_digits": d40}
            print(f"  eps^{o}: {main_out[key]}  vs goal 60 {d60:.2f} d, vs goal 40 {d40:.2f} d")
        for o, key in ORD:
            gate(f"eps^{o} vs the independent reference", comparison[o]["vs_g60_digits"], bar)
        # string-for-string with the record's own value at this dps
        if str(args.dps) in rec["runs"]:
            rr = rec["runs"][str(args.dps)]["result"]
            same = {o: rr[key] == main_out[key] for o, key in ORD}
            comparison["record_string_identical"] = same
            print(f"  [record] the record's own dps-{args.dps} strings at {tag}: eps^-2 {'identical' if same['-2'] else 'DIFFERENT'}, "
                  f"eps^-1 {'identical' if same['-1'] else 'DIFFERENT'}, eps^0 {'identical' if same['0'] else 'DIFFERENT'} "
                  f"(the record's eps^0 vs goal 60: {rec['agreements']['0']['dps48_vs_g60'] if args.dps == 48 else rec['agreements']['0']['dps32_vs_g60']} d)")
    if args.check:
        lo = args.dps - DPS_PAIR_GAP
        barlo = bar_at(lo, bars)
        print(f"[check] the two-precision pair ({lo}, {args.dps}) per order (bar {barlo} at dps {lo}):")
        pair = {}
        for o, key in ORD:
            d = agree(runs[lo][key], main_out[key])
            pair[o] = d
            print(f"  eps^{o}: dps {lo} {runs[lo][key]}  vs dps {args.dps}: {d:.2f} d")
        for o, key in ORD:
            gate(f"eps^{o} two-precision pair {lo}/{args.dps}", pair[o], barlo)
        comparison["pair"] = pair
        if ref:
            rep = {o: min(pair[o], comparison[o]["vs_g60_digits"]) for o, _ in ORD}
            comparison["reportable_digits_record_rule"] = rep
            print(f"  [rule] reportable digits (the record's rule: min(pair agreement, agreement with the reference)): "
                  + ", ".join(f"eps^{o} {rep[o]:.2f}" for o, _ in ORD))
    ok = all(g["pass"] for g in gates)
    wall = round(time.time() - t_all, 1)
    print(f"\nVALUE eps^0 at {label}(s, t) = ({s}, {t}): {main_out['I_0']}")
    print(f"      eps^-1: {main_out['I_m1']}\n      eps^-2: {main_out['I_m2']}")
    if not gates:
        print(f"VERDICT UNREFERENCED: no gate (no shipped reference at this point); total wall {wall} s")
    else:
        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:
        recpt = {"PRODUCER": {"script": os.path.basename(__file__), "sha256": sha256_file(__file__), "start": stamp0, "stamp": utc(), "wall_s": wall,
                              "pins_verified": npins, "stamp_source": "date -u", "mpmath": mp.__version__},
                 "args": {"point": args.point, "tag": tag, "s": str(s), "t": str(t), "m2": str(m2), "u": str(u), "dps": args.dps, "check": args.check,
                          "mutate": args.mutate, "unreferenced": args.unreferenced},
                 "bar": bar if ref else None, "runs": {str(d): r for d, r in runs.items()}, "comparison": comparison, "gates": gates,
                 "verdict": ("PASS" if ok else "FAIL") if gates else "UNREFERENCED"}
        fd = os.open(args.out, os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o644)
        with os.fdopen(fd, "w") as f:
            json.dump(recpt, f, indent=1)
        print(f"[written] {os.path.basename(args.out)}")
    sys.exit(0 if ok else RC_FAIL)


if __name__ == "__main__":
    main()
