#!/usr/bin/env python3
r"""E4C four-point energy-correlator, elliptic sector -- compute the eight
maximal-cut master periods M_N(u) at runtime and gate them against an
independent direct-quadrature oracle.

Sector: props {5,7,13} of the four-point EEC family (Ma et al.,
arXiv:2506.02061; family3 of PropAnalytic.txt), 8 masters
N in {1, x1, x1^2, x1^3, x2, x1*x2, x2^2, x3}, on the 1D angular slice
z12=1/7, z13=1/5, z14=1/3, z23=2/5, z24=3/7, z34=u free in (0,1).

NOTHING finite-precision is stored on the evaluation path.  What runs at
runtime, from the propagator definitions alone:
  (1) CURVE.  The maximal cut {D5 = D7 = Ddelta = 0} is solved symbolically:
      x1, x2 eliminate linearly, Ddelta clears to a quadratic Q(x4; x3, u)
      whose x4-discriminant is (2*x3-5)^2 * P(x3;u) -- a genus-1 quartic.
      P is built live by exact polynomial algebra (sympy over Q).
  (2) CONNECTION.  The Gauss-Manin connection on the period basis
      {I_k = oint x3^k dx3/sqrt(P), k=0,1,2} is derived live by
      Griffiths-Dwork reduction, and the exact order-2 Picard-Fuchs
      operator I0'' = q1 I0' + q0 I0 is extracted from it; the order-2
      closure residual is verified to be IDENTICALLY ZERO (symbolic, all
      three basis components), every run.
  (3) INITIAL DATA.  The period 4-vector (I0, I1, I2, I3), with
      I3 = oint dx3/((2*x3-5)*sqrt(P)) the third-kind period, is computed
      at the base point u0 = 1/5 by direct segment quadrature between the
      real branch points -- full precision, no finite differences, no
      stored digits.
  (4) TRANSPORT.  (I0..I3) is transported u0 -> u by stepwise Taylor jets
      of the 4x4 first-order system Y' = GM4(u) Y, with adaptive rational
      steps sized off the live-computed singular/apparent loci.
  (5) MASTERS.  Each maxcut master
        M_N(u) = oint_gamma [ N(x1,x2,x3,x4) * (1 - z23*x3) / dQ/dx4 ]_odd dx3
      (measure = the on-shell Jacobian of the cleared cut equations; the
      sheet-odd half carries the elliptic period) is reconstructed from the
      transported periods by its exact Q(u) reduction.
  (6) ORACLE.  At every evaluation point the same M_N(u) is recomputed by an
      INDEPENDENT route -- direct quadrature of the sheet-odd master
      integrand on the cycle, solving the x4 quadratic on both sheets --
      which never touches the connection, the transport, or the reduction.

Retained data of this work -- EXACT rational functions over Q(u), zero decimal
digits (GATE_ALL8.json, 2026-07-02, derived by Griffiths-Dwork
reduction with resubstitution verification):
  GM4_ROW3  -- the third-kind row d/du I3 = sum_k GM4[3][k] I_k of the 4x4
               Gauss-Manin matrix (rows 0-2 are re-derived live, see (2),
               and the live rows are the ones used);
  RED       -- the reduction coefficients M_N = sum_k c_{N,k}(u) I_k,
               c_{N,k} in Q(u).
Both are validated at runtime by the agreement gate itself: a wrong entry
fails the transport-vs-oracle comparison at the 30-digit level.

Measured context from this work (not recomputed here): with a dps-80 direct
oracle the M_1 transport gate reaches 42 digits, and all 8 masters gate at
>= 30 relative digits with the dps-60 oracle (GATE_ALL8.json, verdict PASS;
the direct-quadrature endpoint noise floor ~10^(-0.55*dps), not the
transport, is the ceiling).  The digits PRINTED by this script are measured
live at the precisions of the current run.

Print policy ("never print a value the loop didn't certify",
adopted 2026-07-06): the DEFAULT table truncates each
printed value string to its certified digit count -- the transported column
to the per-point value-level bound (the [cert] line), the oracle column to
its calibrated certification (endpoint-floor model at its working precision
on the default path; the refine-until-bound tolerance on --certify-full).
Truncation is string-level (never re-rounded), so every printed string is a
strict PREFIX of the full working-precision string; --raw restores the full
dps-digit strings, whose digits beyond the certified bound are an
UNCERTIFIED tail.  This is print-layer ONLY: gate digits, [cert]/[gate]
lines, the --check value cranks and every internal value are computed from
the untruncated mpf values and are byte-identical to the pre-policy build.

Interface:
  default run    gate demo: all 8 masters transported to the gate
                 angles u = 3/7 and 5/9 and gated against the live oracle
                 (never used upstream).  PASS bar: >= 30 relative digits on
                 the worst master (reached for --dps >= 60; at lower dps the
                 oracle noise floor ~0.55*dps digits is the measured
                 ceiling and is printed).  The bar RAISES (RuntimeError)
                 since the 2026-07-05 hardening; [cert] lines print the
                 certified bounds next to the values.  Printed value
                 strings are truncated to their certified digits
                 (print-only-certified; see the print-policy paragraph
                 above and --raw).
                 Measured wall time ~50 s at the default --dps 60 on the
                 authors' workstation.
  --dps D        working precision (default 60).  ICs are computed at
                 D+25, the oracle at D+10; gate digits scale with D up to
                 the transport precision.
  --point P/Q    evaluate all 8 masters at a rational angle u = P/Q,
                 transported from u0 = 1/5 and gated against the live
                 oracle.  Domain: the transport corridor 0.0377 < u < 0.7319
                 between the real singular fibre u ~ 0.03765 (a zero of the
                 degree-7 curve discriminant) and the real APPARENT
                 singularity u ~ 0.73191 (a zero of the degree-4 apparent
                 factor -- a pole of the connection coefficients, not a
                 curve degeneration, but the plain-Taylor march cannot cross
                 it; a complex detour would, and is not implemented here).
  --check        dps-crank consistency: rerun the two gates at
                 D+40 (genuinely different internal depths everywhere: the
                 Taylor seeds, quadrature depths and working precisions all
                 scale with D); the transported master VALUES at D and D+40
                 must agree to the D-run's certified digits (RAISES below
                 the calibrated bar) and the gate digits must grow.
  --certify-full definition-level path: ICs and oracle are computed by
                 refine-until-bound quadrature loops certified to
                 10^-(D+guard) (working precision escalates past the
                 measured ~0.5*wp endpoint-cancellation floor of the direct
                 1/sqrt-quartic quadrature), so EVERY printed constant
                 carries >= D certified digits at any D.  The default path
                 keeps the (faster) recorded precisions: its values are
                 byte-stable and its certified floor is printed and gated
                 instead (and, since 2026-07-06, is also the printed digit
                 count).
  --raw          print the full working-precision value strings (dps
                 significant digits, the pre-2026-07-06 output): the digits
                 beyond the printed [cert] bounds are an UNCERTIFIED tail
                 (documented as such in the [cert] print-policy line).
                 Values, gates and rc are identical to the default run --
                 the flag changes the print layer only.

Certification (2026-07-05 -- construction copied from the validated
pilot):
  * transport Taylor length N = 2.4*dps+40 is a STARTING guess only; every
    step carries a certified trailing-8-term geometric tail bound
    max|a_n h^n| * r/(1-r), with r = |h|/R_full measured against the FULL
    connection pole set (all GM4-entry denominator roots -- this includes
    the apparent factor 225u^2-240u+4 of the Gauss-Manin row 2 that the
    scalar PF denominator misses; step SIZING keeps the PF-root radius,
    certification uses the full set).  Bound must beat 10^-(dps+12); on
    failure N escalates x1.5 by EXACT continuation of the same recurrences
    to 8x the seed, then RuntimeError naming step/u/h/bound/tol/N/cap.
    Per-step bounds accumulate and propagate to value level through the
    l1-norm of the exact reduction prefactors and the MEASURED fundamental-
    matrix amplification (row-l1 of the transported identity, ~1.0 across
    the corridor).
  * IC/oracle quadratures: mp.quad values are gated by their engine error
    estimate (error=True; identical value bits), and the ICs are
    additionally certified against an independent refine-until-bound
    quadrature pass (successive tanh-sinh depth agreement, fail-closed;
    core loop ported from tools/detransport/quad.py so this script stays
    standalone) at higher working precision: the measured |ambient - cert|
    must sit at the calibrated endpoint floor (ICs 0.50*wp+1.8 digits,
    oracle 0.50*wp+0.5 digits, fits measured over wp 40-200).
  * agreement gates RAISE: gate demo bar = max(32 d for dps >= 60,
    0.5*(dps+10)+0.5 - 7), PASS strictly-greater only; --point bar drops
    the 32-d floor (corridor-edge cycles legitimately sit at the oracle
    floor).  A 1e-30 perturbation of any retained exact string
    (GM4_ROW3/RED) lands the default-dps agreement at 29.0-30.1 d
    (measured battery), strictly below the 32-d bar, and raises with
    rc != 0 (mutation bar; strict-bar + slack pattern -- a bar at
    exactly 30.0 let the GM4_ROW3[2] mutant land at 30.1 d and pass).

Changelog:
  2026-07-06  print-only-certified print policy adopted.  DEFAULT
              value strings truncate (string-level prefix, never
              re-rounded) to the certified digits: transported column =
              the per-point [cert] value-level bound, oracle column = its
              calibrated floor model (--certify-full already certifies
              >= dps digits, so its strings are unchanged).  NEW --raw
              restores the full dps-digit strings, documented as carrying
              an uncertified tail.  Print-layer ONLY: gate table
              agreements, [cert]/[gate] lines, --check cranks, bars and
              rc behavior are byte-identical (only value-string lengths
              change); --raw reproduces the pre-policy strings exactly.
  2026-07-05c mutation-gate fix (e4c-mutfix): the dps>=60 demo bar sat
              EXACTLY at the 1e-30 mutation scale and used a non-strict
              compare -- GM4_ROW3[2]*(1+1e-30) landed at 30.1 d and passed
              rc=0.  Bar lifted to 30 + MUT_SLACK = 32.0 d, PASS now
              strictly-greater (rc-failclosed pattern).  Zero value-
              path change; only [gate] lines differ.
  2026-07-05b hardening pass: certified refine-until-bound loops
              on the transport jets, IC certification pass + engine-estimate
              gates on the quadratures, raising agreement gates, --check
              crank D -> D+40, --certify-full definition path.  All
              pre-existing output lines byte-identical at default; new
              lines carry the [cert]/[gate] prefix.
  2026-07-05  created (E4C blog evaluator; assessed-then-built from the
              paper's ancillary artifacts EECNote/ancillary/{maxcut,pf_analytic,
              gate2,maxcut_periods}.py + GATE_ALL8.json; all eval-path
              inputs exact/symbolic, ICs and oracle recomputed live).
"""
import argparse
import math
import time
from fractions import Fraction

import mpmath as mp
import sympy as sp

X1, X2, X3, X4, U = sp.symbols('x1 x2 x3 x4 u')
Z12, Z13, Z14, Z23, Z24 = [sp.Rational(v) for v in
                           ('1/7', '1/5', '1/3', '2/5', '3/7')]
BASE_U = sp.Rational(1, 5)          # transport base point
MASTER_NAMES = ['1', 'x1', 'x1^2', 'x1^3', 'x2', 'x1*x2', 'x2^2', 'x3']


def digits(a, b):
    """-log10 |a-b|/|b| : measured agreement in decimal digits."""
    a, b = mp.mpf(a), mp.mpf(b)
    if a == b:
        return float('inf')
    return float(-mp.log10(abs((a - b) / b)))


def cert_prefix(v, full_digits, cert_digits):
    """Print-policy helper (2026-07-06): the full-precision
    decimal string mp.nstr(v, full_digits), TRUNCATED -- never re-rounded
    -- to cert_digits significant digits, so the printed string is a
    strict PREFIX of the --raw string (prefix property verified
    programmatically).  PRINT LAYER ONLY: callers
    keep computing with the untruncated mpf value.  Leading zeros are not
    significant; the integer part is never cut (this slice's masters are
    O(10^-3) with cert_digits >= 20, so the cut always lands after the
    decimal point); an exponent tail ('e...'), if mp.nstr ever produced
    one here, is preserved after truncating the mantissa."""
    s = mp.nstr(v, full_digits)
    if cert_digits >= full_digits:
        return s
    mant, sep, expo = s.partition('e')
    sig, seen = 0, False
    for i, ch in enumerate(mant):
        if not ch.isdigit():
            continue
        if ch != '0':
            seen = True
        if seen:
            sig += 1
        if sig >= cert_digits and '.' in mant[:i + 1]:
            mant = mant[:i + 1]
            break
    return mant + sep + expo


# ===========================================================================
# certification knobs (2026-07-05).  Every entry is a
# SEED or CAP of a fail-closed refine-until-bound loop, or a calibrated
# raising-gate bar; none of them can change a printed value.  Calibration
# measurements recorded with the paper's ancillary material.
# ===========================================================================
TAIL_WINDOW = 8      # trailing-term window of the per-step geometric bound
TAIL_GUARD = 12      # per-step transport tail tol = 10^-(dps+TAIL_GUARD)
ESC_FACT = 1.5       # Taylor-length escalation factor (exact continuation)
NCAP_FACT = 8        # Taylor-length cap = NCAP_FACT * N0 (pilot 8-64x)
RCERT_MAX = 0.75     # certified step ratio r=|h|/R_full hard ceiling
                     # (measures 0.35 corridor-wide; > this raises)
QUAD_GUARD = 8       # --certify-full quadrature guard digits
QESC_FACT = 1.5      # cert-quadrature working-precision escalation factor
QCAP_FACT = 4        # cert-quadrature wp cap = QCAP_FACT * seed
IC_CERT_PAD = 10     # cert-pass reference must beat the ambient floor by this
IC_GATE_MARGIN = 8   # IC |ambient-cert| raising gate margin (10^6.8 measured)
OR_EST_MARGIN = 12   # oracle engine-estimate raising gate margin
GATE_MARGIN = 7      # agreement-gate margin below the oracle floor model
MUT_SLACK = 2.0      # strict-bar slack ABOVE the 1e-30 mutation scale on the
                     # dps>=60 demo floor (30 -> 32 d).  The measured
                     # pattern (rc-failclosed sweep 2026-07-05):
                     # a bar sitting EXACTLY at the mutation scale lets a
                     # (1+1e-30) mutant land epsilon above it and PASS --
                     # measured live: GM4_ROW3[2]*(1+1e-30) -> worst 30.1 d
                     # vs the old 30.0 bar, rc=0 (mutfix evidence dir).
                     # Landings of the retained-string mutant battery:
                     # 29.0-30.1 d; healthy dps-60 worst 35.2 d (determin-
                     # istic), so the strict 32.0 bar keeps >= 10^3.2
                     # healthy headroom (lbl3se deterministic-pinch class).
CRANK_MARGIN = 8     # --check D vs D+40 value-agreement margin
AMP_DPS = 12         # dps of the fundamental-matrix amplification measure
AMP_SLACK = 1.02     # slack factor on the measured amplification


def ic_floor(wp):
    """Measured endpoint-cancellation floor (correct digits) of the direct
    IC segment quadrature at working precision wp (fit over wp 55-140)."""
    return 0.50*wp + 1.8


def oracle_floor(wp):
    """Measured endpoint floor of the direct master-oracle quadrature at
    working precision wp (fit over wp 40-90)."""
    return 0.50*wp + 0.5


def _quad_agree(f, a, b, tol, wp, what):
    """ONE tanh-sinh integral refined until the successive-depth agreement
    |I_d - I_{d-1}| <= tol (E3 double-refinement semantics; core loop
    ported from tools/detransport/quad.py::_segment so this blog script
    stays standalone).  Depth escalation is exact continuation (nested
    tanh-sinh levels reuse the previous sum).  Returns (value, agreement,
    depth); RuntimeError (fail-closed) at the depth cap or on a non-finite
    level sum -- a value the loop did not certify is never returned."""
    from mpmath.calculus.quadrature import TanhSinh
    with mp.workprec(int(wp*3.3333) + 10):
        prec = mp.mp.prec
        rule = TanhSinh(mp.mp)
        d0 = max(rule.guess_degree(prec), 2)
        cap = d0 + 6
        av, bv, tolv = mp.convert(a), mp.convert(b), mp.convert(tol)
        results, agr = [], None
        for depth in range(1, cap + 1):
            nodes = rule.get_nodes(av, bv, depth, prec)
            I = rule.sum_next(f, nodes, depth, prec, results)
            results.append(I)
            z = mp.mpc(I)
            if not (mp.isfinite(z.real) and mp.isfinite(z.imag)):
                raise RuntimeError(
                    "[cert] %s: non-finite tanh-sinh level sum at depth %d "
                    "(wp %d) -- fail-closed" % (what, depth, wp))
            if depth >= 2:
                agr = abs(results[-1] - results[-2])
                if agr <= tolv:
                    return results[-1], agr, depth
        raise RuntimeError(
            "[cert] %s: quadrature agreement %s never beat tol %s by depth "
            "cap %d at wp %d -- fail-closed" %
            (what, mp.nstr(agr, 3) if agr is not None else '?',
             mp.nstr(tolv, 3), cap, wp))


def quad_certified(f_at, a_b_at, tol_exp, wp0, what):
    """Refine-until-bound quadrature: accept only when the successive-depth
    agreement beats 10^-tol_exp.  Depth escalates inside _quad_agree; the
    working precision escalates outside (x QESC_FACT to QCAP_FACT*wp0),
    because the endpoint-cancellation noise floor of these 1/sqrt-quartic
    integrands sits at ~0.5*wp digits (measured) -- no depth can cross it,
    finer arithmetic on the SAME rule can.  f_at(wp) must return the
    integrand built at working precision wp; a_b_at(wp) the endpoints.
    Returns (value, agreement, depth, wp); RuntimeError at the wp cap."""
    wp = int(wp0)
    last = None
    while wp <= int(QCAP_FACT*wp0):
        f = f_at(wp)
        a, b = a_b_at(wp)
        with mp.workdps(wp):
            tol = mp.mpf(10)**(-tol_exp)
        try:
            v, agr, depth = _quad_agree(f, a, b, tol, wp, what)
            return v, agr, depth, wp
        except RuntimeError as exc:
            last = exc
            wp = int(wp*QESC_FACT) + 1
    raise RuntimeError(
        "[cert] %s: refine-until-bound failed up to wp cap %d (seed %d, "
        "tol 1e-%d); last: %s -- fail-closed"
        % (what, int(QCAP_FACT*wp0), int(wp0), int(tol_exp), last))


# ===========================================================================
# (1) the maximal-cut curve, live from the propagators
# ===========================================================================
def build_curve():
    """Solve the cut {D5=D7=Ddelta=0} symbolically; return the genus-1
    quartic P(x3;u), the cleared x4-quadratic Q and the master integrands'
    ingredients.  Pure exact algebra -- no numbers beyond the slice
    rationals that DEFINE the kinematic point."""
    Sigma = (Z12*X1*X2 + Z13*X1*X3 + Z14*X1*X4
             + Z23*X2*X3 + Z24*X2*X4 + U*X3*X4)
    Ddelta = 1 - (X1 + X2 + X3 + X4) + Sigma
    x1s = 1 - X2 - X3 - X4                      # D5 = 0
    x2s = (1 - X3) / (1 - Z23*X3)               # D7 = 0
    Dd = sp.together(Ddelta.subs(X1, x1s).subs(X2, x2s))
    num = sp.expand(sp.fraction(Dd)[0])
    quad = sp.Poly(num, X4)                     # cleared quadratic Q(x4)
    assert quad.degree() == 2, "Ddelta not quadratic in x4 on the cut"
    a2, a1, a0 = quad.all_coeffs()
    disc = sp.expand(a1**2 - 4*a2*a0)
    # strip perfect-square factors -> squarefree kernel P (genus-1 quartic)
    P, squares = sp.Integer(1), []
    for base, e in sp.factor_list(disc)[1]:
        if sp.Poly(base, X3).degree() >= 1:
            if e % 2 == 1:
                P *= base**e
            else:
                squares.append((base, e))
    P = sp.expand(P)
    assert sp.Poly(P, X3).degree() == 4, "kernel not a quartic"
    assert squares and sp.expand(squares[0][0] - (2*X3 - 5)) == 0, \
        "expected spurious square factor (2*x3-5)^2"
    x1full = 1 - x2s - X3 - X4                  # x1 on the cut, in (x3,x4)
    masters = {'1': sp.Integer(1), 'x1': x1full, 'x1^2': x1full**2,
               'x1^3': x1full**3, 'x2': x2s, 'x1*x2': x1full*x2s,
               'x2^2': x2s**2, 'x3': X3}
    return {'P': P, 'a2': a2, 'a1': a1, 'a0': a0,
            'dQdx4': sp.expand(2*a2*X4 + a1),   # on-shell Jacobian numerator
            'detden': 1 - Z23*X3, 'masters': masters}


# ===========================================================================
# (2) Gauss-Manin connection + order-2 PF operator, live Griffiths-Dwork
# ===========================================================================
def gauss_manin(P):
    """d/du (I0,I1,I2)^T = M(u) (I0,I1,I2)^T on the basis {x3^k/sqrt(P)},
    by Griffiths-Dwork reduction (N/P^{3/2} = d/dx(g/sqrt P) + A/sqrt P).
    Also extracts the scalar order-2 PF operator for I0 and asserts its
    closure residual vanishes identically (symbolic)."""
    Pu, Px = sp.diff(P, U), sp.diff(P, X3)

    def gd_reduce(N):
        N = sp.expand(N)
        if N == 0:
            return sp.Integer(0)
        dN = sp.degree(sp.Poly(N, X3))
        asyms = sp.symbols('A0 A1 A2')
        A = sum(asyms[i]*X3**i for i in range(3))
        for extra in range(8):
            gdeg = max(dN - 3, 0) + extra
            gsyms = sp.symbols('g0:%d' % (gdeg + 1))
            g = sum(gsyms[i]*X3**i for i in range(gdeg + 1))
            expr = sp.expand(sp.diff(g, X3)*P - sp.Rational(1, 2)*g*Px
                             + A*P - N)
            sol = sp.solve(sp.Poly(expr, X3).all_coeffs(),
                           list(gsyms) + list(asyms), dict=True)
            if sol:
                return sp.expand(A.subs(sol[0]))
        raise AssertionError("Griffiths-Dwork reduction failed")

    M = sp.zeros(3, 3)
    for k in range(3):
        A = gd_reduce(sp.Rational(-1, 2)*X3**k*Pu)
        for j in range(3):
            M[k, j] = sp.cancel(A.coeff(X3, j))
    # scalar order-2 operator for I0 (row-vector calculus in the basis)
    def dvec(row):
        rp = [sp.diff(c, U) for c in row]
        rM = sp.Matrix([row]) * M
        return [sp.cancel(rp[j] + rM[0, j]) for j in range(3)]
    r0 = [sp.Integer(1), sp.Integer(0), sp.Integer(0)]
    r1 = dvec(r0)
    r2 = dvec(r1)
    q0s, q1s = sp.symbols('q0 q1')
    sol = sp.solve([sp.Eq(r2[j], q1s*r1[j] + q0s*r0[j]) for j in range(3)],
                   [q0s, q1s], dict=True)
    assert sol, "order-2 closure failed"
    q0, q1 = sp.cancel(sol[0][q0s]), sp.cancel(sol[0][q1s])
    resid = [sp.simplify(r2[j] - (q1*r1[j] + q0*r0[j])) for j in range(3)]
    assert all(r == 0 for r in resid), "PF residual nonzero: %s" % resid
    return M, q0, q1


# ===========================================================================
# Retained EXACT data of this work (Q(u) rational functions, zero decimals):
# third-kind Gauss-Manin row + master reduction coefficients
# (GATE_ALL8.json; validated live by the agreement gate below).
# ===========================================================================
_D7 = ("136744453125*u**7 - 313861078125*u**6 + 234481078125*u**5 - "
       "39091933125*u**4 - 6770993625*u**3 - 10280927775*u**2 - "
       "346729945*u + 28045969")            # the degree-7 curve discriminant
GM4_ROW3 = [
    "(27348890625*u**6 - 69283856250*u**5 + 44078225625*u**4 + "
    "1505290500*u**3 - 3158056125*u**2 - 304349850*u + 13322995)/(" + _D7 + ")",
    "(-574326703125*u**6 + 1394272490625*u**5 - 906137583750*u**4 + "
    "24847688250*u**3 + 53885715975*u**2 + 1087001685*u - 3950716)"
    "/(15*(" + _D7 + "))",
    "(1148653406250*u**6 - 2690088975000*u**5 + 1739225722500*u**4 - "
    "103264119000*u**3 - 92956515750*u**2 + 1892560320*u - 5028184)"
    "/(75*(" + _D7 + "))",
    "0",
]
RED = {
    '1':     ["1/5", "0", "0", "0"],
    'x1':    ["-51/140", "-3*u/10 - 1/25", "0", "-39/28"],
    'x1^2':  ["10125*u/4648 + 160863/162680",
              "387*u**2/332 - 669*u/11620 + 251/1162",
              "36*u**2/83 + 57*u/415 + 16/2075",
              "42885*u/4648 + 132915/32536"],
    'x1^3':  ["(-832068601875*u**4 + 831983410125*u**3 - 51165719550*u**2 + "
              "151583300640*u - 2539232784)/(42532686000*u**2 - "
              "45368198400*u + 756136640)",
              "(-50641959375*u**5 - 180357384375*u**4 + 219361206375*u**3 - "
              "69171244875*u**2 + 37603736610*u - 665972656)/(30380490000*"
              "u**2 - 32405856000*u + 540097600)",
              "(-13200823125*u**5 + 9183152250*u**4 + 9723225825*u**3 - "
              "4255392510*u**2 + 338642928*u - 3683472)/(2170035000*u**2 - "
              "2314704000*u + 38578400)",
              "-73633725*u**2/771568 - 31286205*u/5400976 - "
              "145358427/9451708"],
    'x2':    ["1/2", "0", "0", "3/2"],
    'x1*x2': ["-549*u/332 - 31203/23240",
              "-819*u**2/332 + 1737*u/830 - 129/4150",
              "819*u**2/830 - 2184*u/2075 + 182/10375",
              "-1575*u/332 - 24375/4648"],
    'x2^2':  ["189*u/332 + 2579/1660",
              "441*u**2/166 - 2541*u/830 - 154/2075",
              "-441*u**2/415 + 2352*u/2075 - 196/10375",
              "1875/332 - 315*u/332"],
    'x3':    ["0", "1/5", "0", "0"],
}


# ===========================================================================
# runtime engine
# ===========================================================================
class E4C:
    def __init__(self, verbose=True):
        t0 = time.time()
        self.C = build_curve()
        t1 = time.time()
        self.M3, self.q0, self.q1 = gauss_manin(self.C['P'])
        t2 = time.time()
        # 4x4 system: rows 0-2 live (col 3 = 0), row 3 retained exact
        self.GM4 = [[self.M3[r, c] for c in range(3)] + [sp.Integer(0)]
                    for r in range(3)]
        self.GM4.append([sp.sympify(e) for e in GM4_ROW3])
        self.RED = {k: [sp.sympify(c) for c in v] for k, v in RED.items()}
        # singular + apparent loci = roots of the PF denominator (live)
        den = sp.Poly(sp.denom(sp.cancel(self.q0)), U)
        cs = [mp.mpf(sp.Rational(c).p)/mp.mpf(sp.Rational(c).q)
              for c in den.all_coeffs()]
        with mp.workdps(40):
            self.sing = mp.polyroots(cs, maxsteps=300, extraprec=160)
        # FULL connection pole set for step CERTIFICATION: the union of all
        # GM4-entry denominator roots.  The Gauss-Manin rows carry apparent
        # factors that cancel in the scalar PF operator (measured live:
        # row 2 has 225u^2-240u+4, roots u ~ 0.016936 / 1.04973, both
        # outside the corridor) -- step SIZING keeps self.sing (unchanged
        # values), the certified series ratio r uses this full set.
        fset = {sp.expand(den.as_expr())}
        for r in range(4):
            for c in range(4):
                e = sp.cancel(self.GM4[r][c])
                if e == 0:
                    continue
                for base, _ in sp.factor_list(sp.denom(e))[1]:
                    if sp.Poly(base, U).degree() >= 1:
                        fset.add(sp.expand(sp.Poly(base, U).monic()
                                           .as_expr()))
        self.certpoles = []
        with mp.workdps(40):
            for fac in fset:
                fc = [mp.mpf(sp.Rational(c).p)/mp.mpf(sp.Rational(c).q)
                      for c in sp.Poly(fac, U).all_coeffs()]
                self.certpoles += list(mp.polyroots(fc, maxsteps=300,
                                                    extraprec=160))
        self._amp_cache = {}
        self._last_oracle_est = mp.mpf(0)
        if verbose:
            print("[curve]     P(x3;u) quartic built from the cut "
                  "propagators           (%.1f s)" % (t1 - t0))
            print("[connection] Gauss-Manin + order-2 PF derived live "
                  "(Griffiths-Dwork);\n             closure residual == 0 "
                  "symbolically, all 3 components  (%.1f s)" % (t2 - t1))
            reals = sorted(float(mp.re(r)) for r in self.sing
                           if abs(mp.im(r)) < 1e-20 and 0 < mp.re(r) < 1)
            print("[loci]      real singular/apparent u in (0,1): %s"
                  % ', '.join('%.5f' % r for r in reals))
            print("[cert]      step-certification pole set: %d connection-"
                  "denominator roots (%d beyond the PF denominator)"
                  % (len(self.certpoles),
                     len(self.certpoles) - len(self.sing)))

    # ---- (3) periods by direct segment quadrature -------------------------
    def _quartic_cycle(self, uval, dps):
        Pe = sp.expand(self.C['P'].subs(U, sp.Rational(uval)))
        Pp = sp.Poly(Pe, X3)
        cs = [mp.mpf(sp.Rational(c).p)/mp.mpf(sp.Rational(c).q)
              for c in Pp.all_coeffs()]
        rts = mp.polyroots(cs, maxsteps=400, extraprec=dps*4)
        reals = sorted([mp.re(r) for r in rts
                        if abs(mp.im(r)) < mp.mpf(10)**(-dps//2)])
        if len(reals) < 2:
            raise ValueError("u=%s: < 2 real branch points; the real cycle "
                             "quadrature route needs the physical corridor"
                             % uval)
        a, b = reals[0], reals[1]
        if a < mp.mpf(5)/2 < b:
            raise ValueError("third-kind pole x3=5/2 inside the cycle")
        return Pe, a, b

    def periods_direct(self, uval, dps):
        """(I0,I1,I2,I3) at u=uval, live segment quadrature (no stored
        digits, no finite differences)."""
        with mp.workdps(dps):
            Pe, a, b = self._quartic_cycle(uval, dps)
            Pf = sp.lambdify(X3, Pe, 'mpmath')
            Y = [2*mp.quad(lambda t, k=k: t**k/mp.sqrt(Pf(t)), [a, b])
                 for k in range(3)]
            Y.append(2*mp.quad(lambda t: 1/((2*t - 5)*mp.sqrt(Pf(t))),
                               [a, b]))
            return [mp.mpf(mp.re(y)) for y in Y]

    def _ic_integrand_factory(self, uval):
        """Closures rebuilding the four IC integrands + cycle at a given
        working precision (for the refine-until-bound certification passes;
        the ambient periods_direct arithmetic is untouched).

        Endpoint collar: deep tanh-sinh levels place nodes within the
        branch-point ROOT-ERROR collar (|t-a| ~ ulp), where the evaluated
        quartic can round to <= 0; those nodes are clamped to 0.  Their
        true weighted contribution is |w/sqrt(P'(a) d)| ~ sqrt(d) -- MEASURED
        4.3e-69 at wp 120 vs cert tol 1e-54, and it shrinks faster than any
        tolerance this script can request (ROW_REPORT calibration note)."""
        cache = {}

        def cyc(wp):
            if wp not in cache:
                with mp.workdps(wp):
                    Pe, a, b = self._quartic_cycle(uval, wp)
                    cache[wp] = (sp.lambdify(X3, Pe, 'mpmath'), a, b)
            return cache[wp]

        def f_at(k):
            def build(wp, k=k):
                P = cyc(wp)[0]

                def f(t):
                    pv = P(t)
                    if pv <= 0:          # branch-point root-error collar
                        return mp.mpf(0)
                    if k < 3:
                        return t**k/mp.sqrt(pv)
                    return 1/((2*t - 5)*mp.sqrt(pv))
                return f
            return build

        return f_at, (lambda wp: cyc(wp)[1:3])

    def certify_ics(self, uval, wp_amb, Y_amb):
        """Fail-closed certification of the AMBIENT IC vector: recompute
        each period by an independent refine-until-bound quadrature pass at
        higher working precision and require the measured |ambient - cert|
        to sit at the calibrated endpoint floor (0.50*wp_amb + 1.8 digits,
        measured) within IC_GATE_MARGIN.  Returns the certified ambient IC
        error bound (max over components); RuntimeError on gate failure."""
        f_at, ab_at = self._ic_integrand_factory(uval)
        target = ic_floor(wp_amb) + IC_CERT_PAD
        wp0 = wp_amb + 35
        deltas = []
        for k in range(4):
            v, agr, depth, wpu = quad_certified(
                f_at(k), ab_at, target, wp0, "IC I%d certification" % k)
            with mp.workdps(wpu + 10):
                delta = abs(mp.mpf(Y_amb[k]) - 2*mp.re(v)) + 2*agr
                gate = mp.mpf(10)**(-(ic_floor(wp_amb) - IC_GATE_MARGIN))
                deltas.append(delta)
                if not delta < gate:
                    raise RuntimeError(
                        "[cert] IC I%d at u=%s: |ambient - certified| = %s "
                        ">= raising gate %s (ambient wp %d, floor model "
                        "0.50*wp+1.8, margin %d) -- fail-closed"
                        % (k, uval, mp.nstr(delta, 3), mp.nstr(gate, 3),
                           wp_amb, IC_GATE_MARGIN))
        return max(deltas)

    def periods_certified(self, uval, dps):
        """--certify-full definition path: (I0..I3) by refine-until-bound
        quadrature certified to 10^-(dps+QUAD_GUARD) (any dps; the working
        precision escalates past the measured ~0.5*wp endpoint floor).
        Returns (Y, err) with err the certified bound (max component)."""
        f_at, ab_at = self._ic_integrand_factory(uval)
        target = dps + QUAD_GUARD
        wp0 = 2*(dps + QUAD_GUARD) + 30
        Y, errs = [], []
        for k in range(4):
            v, agr, depth, wpu = quad_certified(
                f_at(k), ab_at, target, wp0, "IC I%d (certified)" % k)
            with mp.workdps(wpu):
                Y.append(mp.mpf(2*mp.re(v)))
                errs.append(2*agr)
        return Y, max(errs)

    # ---- (6) independent oracle: direct master quadrature -----------------
    def _master_integrand_at(self, uval, name, wp):
        """Sheet-odd master integrand + cycle, built at working precision
        wp (shared by the ambient oracle and its certified variant)."""
        uu = sp.Rational(uval)
        with mp.workdps(wp):
            _, a, b = self._quartic_cycle(uval, wp)
            sub = {U: uu}
            a2 = sp.lambdify(X3, self.C['a2'].subs(sub), 'mpmath')
            a1 = sp.lambdify(X3, self.C['a1'].subs(sub), 'mpmath')
            disc = sp.lambdify(X3, sp.expand(
                (self.C['a1']**2 - 4*self.C['a2']*self.C['a0']).subs(sub)),
                'mpmath')
            dQ = sp.lambdify((X3, X4), self.C['dQdx4'].subs(sub), 'mpmath')
            dden = sp.lambdify(X3, self.C['detden'].subs(sub), 'mpmath')
            Nf = sp.lambdify((X3, X4), self.C['masters'][name].subs(sub),
                             'mpmath')

            def f(x3, sheet):
                x4 = (-a1(x3) + sheet*mp.sqrt(disc(x3)))/(2*a2(x3))
                return Nf(x3, x4)*dden(x3)/dQ(x3, x4)

            def fodd(t):
                # branch-point root-error collar clamp (same measured
                # bound as _ic_integrand_factory; certification pass only)
                if disc(t) <= 0:
                    return mp.mpf(0)
                try:
                    return (f(t, 1) - f(t, -1))/2
                except ZeroDivisionError:
                    return mp.mpf(0)

            return fodd, a, b

    def master_direct(self, uval, name, dps):
        """M_name(u) by direct quadrature of the sheet-odd master integrand
        (solves the x4 quadratic on both sheets; never touches the
        connection, the transport or the reduction).  The engine error
        estimate (error=True; value bits unchanged) is gated fail-closed
        against the calibrated endpoint-floor model."""
        uu = sp.Rational(uval)
        with mp.workdps(dps):
            _, a, b = self._quartic_cycle(uval, dps)
            sub = {U: uu}
            a2 = sp.lambdify(X3, self.C['a2'].subs(sub), 'mpmath')
            a1 = sp.lambdify(X3, self.C['a1'].subs(sub), 'mpmath')
            disc = sp.lambdify(X3, sp.expand(
                (self.C['a1']**2 - 4*self.C['a2']*self.C['a0']).subs(sub)),
                'mpmath')
            dQ = sp.lambdify((X3, X4), self.C['dQdx4'].subs(sub), 'mpmath')
            dden = sp.lambdify(X3, self.C['detden'].subs(sub), 'mpmath')
            Nf = sp.lambdify((X3, X4), self.C['masters'][name].subs(sub),
                             'mpmath')

            def f(x3, sheet):
                x4 = (-a1(x3) + sheet*mp.sqrt(disc(x3)))/(2*a2(x3))
                return Nf(x3, x4)*dden(x3)/dQ(x3, x4)

            v, est = mp.quad(lambda t: (f(t, 1) - f(t, -1))/2, [a, b],
                             error=True)
            val = 2*v
            gate = mp.mpf(10)**(-(oracle_floor(dps) - OR_EST_MARGIN))
            if not est < gate:
                raise RuntimeError(
                    "[cert] oracle M[%s] at u=%s: engine error estimate %s "
                    ">= raising gate %s (wp %d, floor model 0.50*wp+0.5, "
                    "margin %d) -- fail-closed"
                    % (name, uval, mp.nstr(est, 3), mp.nstr(gate, 3), dps,
                       OR_EST_MARGIN))
            self._last_oracle_est = est
            return mp.mpf(mp.re(val))

    def master_certified(self, uval, name, dps):
        """--certify-full oracle: the same sheet-odd master integral by the
        refine-until-bound quadrature loop, certified to
        10^-(dps+QUAD_GUARD).  Returns the value; stores the certified
        agreement in _last_oracle_est."""
        target = dps + QUAD_GUARD
        wp0 = 2*(dps + QUAD_GUARD) + 20

        def f_at(wp):
            fodd, _, _ = self._master_integrand_at(uval, name, wp)
            return fodd

        def ab_at(wp):
            _, a, b = self._master_integrand_at(uval, name, wp)
            return a, b

        v, agr, depth, wpu = quad_certified(
            f_at, ab_at, target, wp0, "oracle M[%s] (certified)" % name)
        with mp.workdps(wpu):
            self._last_oracle_est = 2*agr
            return mp.mpf(2*mp.re(v))

    # ---- (4) transport by stepwise Taylor jets ----------------------------
    def _ratfunc_taylor(self, e, u0r, Nterms):
        """mpf Taylor coefficients of the exact rational function e(u)
        about the rational point u0r."""
        s = sp.symbols('s')
        num, den = sp.fraction(sp.cancel(e))
        Np = sp.Poly(sp.expand(num.subs(U, u0r + s)), s)
        Dp = sp.Poly(sp.expand(den.subs(U, u0r + s)), s)

        def coeffs(P):
            c = [mp.mpf(0)]*(Nterms + 3)
            for mono, co in P.terms():
                if mono[0] < len(c):
                    r = sp.Rational(co)
                    c[mono[0]] = mp.mpf(r.p)/mp.mpf(r.q)
            return c

        n, d = coeffs(Np), coeffs(Dp)
        t = [mp.mpf(0)]*(Nterms + 1)
        for k in range(Nterms + 1):
            acc = n[k]
            for i in range(1, k + 1):
                acc -= d[i]*t[k - i]
            t[k] = acc/d[0]
        return t

    def _radius(self, upt):
        return float(min(abs(mp.mpc(float(upt)) - r) for r in self.sing))

    def _cert_radius(self, upt):
        """Distance to the nearest pole of ANY connection entry (full
        certified pole set; >= constraint set of _radius inside the
        corridor, see __init__)."""
        return float(min(abs(mp.mpc(float(upt)) - r) for r in self.certpoles))

    @staticmethod
    def _tail_bound(a, ds, rcert):
        """Certified trailing-window geometric tail bound of the step's
        Taylor sum: max over the last TAIL_WINDOW orders of the largest
        component term |a_n h^n|, times r/(1-r) with r = |h|/R_full
        certified by the step rule (pilot construction, build-record items
        12-13)."""
        hh = abs(ds)
        tail = mp.mpf(0)
        for n in range(max(len(a) - TAIL_WINDOW, 0), len(a)):
            m = max(abs(a[n][r]) for r in range(len(a[n])))*hh**n
            if m > tail:
                tail = m
        return tail*rcert/(1 - rcert)

    def transport(self, u0, u1, Y0, dps):
        """Transport Y=(I0..I3) from u0 to u1: adaptive rational steps
        (step <= 0.35 x distance to the nearest singular/apparent point),
        Taylor jets of Y' = GM4(u) Y.  N = 2.4*dps+40 terms is the STARTING
        guess; every step is accepted only when its certified trailing-
        window tail bound beats 10^-(dps+TAIL_GUARD), escalating N x1.5 by
        exact continuation of the same recurrences to NCAP_FACT*N0, then
        RuntimeError (fail-closed).  Returns (Y, cert) with cert =
        {'steps', 'worst_bound', 'err_steps', 'escalations'}."""
        with mp.workdps(dps + 25):
            f0, f1 = (Fraction(sp.Rational(v).p, sp.Rational(v).q)
                      for v in (u0, u1))
            Nterms = int(2.4*dps) + 40
            N0, NCAP = Nterms, NCAP_FACT*Nterms
            tol_step = mp.mpf(10)**(-(dps + TAIL_GUARD))
            err_steps, worst_bound, nsteps, nesc = \
                mp.mpf(0), mp.mpf(0), 0, 0
            Y, cur, sgn = list(Y0), f0, (1 if f1 >= f0 else -1)
            for _ in range(400):
                rem = abs(f1 - cur)
                if rem == 0:
                    break
                R = self._radius(cur)
                if R < 1e-3:
                    raise ValueError(
                        "transport stalled at u=%s: %.2g from a "
                        "singular/apparent point" % (cur, R))
                h = 0.35*R
                if float(rem) <= h:
                    hq = rem                    # exact final step
                else:
                    hq = Fraction(math.floor(h*10**6), 10**6)
                if hq <= 0:
                    raise ValueError("step underflow")
                # certified series ratio off the FULL connection pole set
                Rf = self._cert_radius(cur)
                rcert = mp.mpf(float(hq))/Rf
                if not rcert < RCERT_MAX:
                    raise RuntimeError(
                        "[cert] transport step %d at u=%s: series ratio "
                        "r=%.3f >= %.2f (h=%s, R_full=%.3g) -- fail-closed"
                        % (nsteps, cur, float(rcert), RCERT_MAX, hq, Rf))
                u0r = sp.Rational(cur.numerator, cur.denominator)
                Nterms = N0
                Ac = [[None if self.GM4[r][c] == 0 else
                       self._ratfunc_taylor(self.GM4[r][c], u0r, Nterms)
                       for c in range(4)] for r in range(4)]
                a = [list(Y)]
                for n in range(Nterms):
                    nxt = []
                    for r in range(4):
                        acc = mp.mpf(0)
                        for c in range(4):
                            col = Ac[r][c]
                            if col is None:
                                continue
                            for k in range(n + 1):
                                acc += col[k]*a[n - k][c]
                        nxt.append(acc/(n + 1))
                    a.append(nxt)
                ds = sgn*mp.mpf(hq.numerator)/hq.denominator
                while True:
                    val, p = [mp.mpf(0)]*4, mp.mpf(1)
                    for n in range(len(a)):
                        for r in range(4):
                            val[r] += a[n][r]*p
                        p *= ds
                    bound = self._tail_bound(a, ds, rcert)
                    if bound < tol_step:
                        break
                    if Nterms >= NCAP:
                        raise RuntimeError(
                            "[cert] transport step %d at u=%s: certified "
                            "tail bound %s >= tol %s at N=%d (cap %d), "
                            "h=%s, r=%.3f -- fail-closed"
                            % (nsteps, cur, mp.nstr(bound, 3),
                               mp.nstr(tol_step, 3), Nterms, NCAP, hq,
                               float(rcert)))
                    # escalate by EXACT continuation: the longer rational
                    # Taylor columns reproduce the lower coefficients bit-
                    # identically; the jet recursion continues in place.
                    nesc += 1
                    Nnew = min(int(Nterms*ESC_FACT) + 1, NCAP)
                    Ac = [[None if self.GM4[r][c] == 0 else
                           self._ratfunc_taylor(self.GM4[r][c], u0r, Nnew)
                           for c in range(4)] for r in range(4)]
                    for n in range(Nterms, Nnew):
                        nxt = []
                        for r in range(4):
                            acc = mp.mpf(0)
                            for c in range(4):
                                col = Ac[r][c]
                                if col is None:
                                    continue
                                for k in range(n + 1):
                                    acc += col[k]*a[n - k][c]
                            nxt.append(acc/(n + 1))
                        a.append(nxt)
                    Nterms = Nnew
                err_steps += bound
                if bound > worst_bound:
                    worst_bound = bound
                nsteps += 1
                Y, cur = val, cur + sgn*hq
            else:
                raise ValueError("transport did not converge in 400 steps")
            return Y, {'steps': nsteps, 'worst_bound': worst_bound,
                       'err_steps': err_steps, 'escalations': nesc,
                       'N0': N0}

    # ---- (5) masters from transported periods -----------------------------
    def reduce_masters(self, uval, Y):
        uu = sp.Rational(uval)
        out = {}
        for name in MASTER_NAMES:
            acc = mp.mpf(0)
            for k, c in enumerate(self.RED[name]):
                r = sp.Rational(c.subs(U, uu))
                acc += (mp.mpf(r.p)/mp.mpf(r.q))*Y[k]
            out[name] = acc
        return out

    def reduce_bound(self, uval, errY):
        """Value-level certified bound per master: l1-norm of the EXACT
        reduction prefactors times the per-component period error bounds
        (pilot construction: per-step bounds -> err_total -> value level)."""
        uu = sp.Rational(uval)
        out = {}
        for name in MASTER_NAMES:
            acc = mp.mpf(0)
            for k, c in enumerate(self.RED[name]):
                r = sp.Rational(c.subs(U, uu))
                acc += abs(mp.mpf(r.p)/mp.mpf(r.q))*errY[k]
            out[name] = acc
        return out

    def path_amplification(self, u1):
        """MEASURED row-l1 norms of the fundamental transport matrix
        u0 -> u1 (transport of the 4x4 identity at low precision AMP_DPS,
        times AMP_SLACK): the amplification factors that carry the IC and
        per-step error bounds to the endpoint.  Measured 0.93-1.05 across
        the corridor gate points.  Cached per target."""
        key = str(sp.Rational(u1))
        if key not in self._amp_cache:
            cols = []
            for j in range(4):
                ej = [mp.mpf(1) if k == j else mp.mpf(0) for k in range(4)]
                cols.append(self.transport(BASE_U, u1, ej, AMP_DPS)[0])
            with mp.workdps(AMP_DPS + 10):
                self._amp_cache[key] = [
                    AMP_SLACK*sum(abs(cols[j][k]) for j in range(4))
                    for k in range(4)]
        return self._amp_cache[key]

    def evaluate(self, uval, dps, Y0=None, ic_err=None):
        """f(point, dps): all 8 maxcut masters M_N(u) via the bootstrapped
        route (live ICs at u0=1/5 -> exact-connection transport -> exact
        Q(u) reduction).  Returns {'periods': Y, 'masters': {...},
        'cert': {...}} with the certified transport/IC error budget."""
        if Y0 is None:
            Y0 = self.periods_direct(BASE_U, dps + 25)
            ic_err = self.certify_ics(BASE_U, dps + 25, Y0)
        Y, tcert = self.transport(BASE_U, uval, Y0, dps)
        tcert['ic_err'] = ic_err
        return {'periods': Y, 'masters': self.reduce_masters(uval, Y),
                'cert': tcert}


# ===========================================================================
# drivers
# ===========================================================================
def gate_bar(dps, bar30=True, certify=False):
    """Calibrated raising bar for the transport-vs-oracle agreement.
    Default path: the measured oracle endpoint-floor model at its working
    precision dps+10, minus GATE_MARGIN (measured headroom >= 10^6.9 at
    dps 30/60); the gate demo additionally enforces the documented 30-d
    PASS bar at dps >= 60 PLUS the strict-bar slack MUT_SLACK (32.0 d
    total; healthy dps-60 worst 35.2 d, deterministic run-to-run -- this
    is the bar that catches 1e-30 mutations of the retained exact
    strings: the mutant battery lands at 29.0-30.1 d, so a bar
    sitting exactly at 30.0 let the GM4_ROW3[2] mutant escape at 30.1 d;
    see MUT_SLACK).  --point runs drop the 30-d floor (corridor-edge
    cycles legitimately sit at the oracle floor).
    --certify-full: both routes are certified past dps, bar = dps -
    CRANK_MARGIN."""
    if certify:
        return dps - CRANK_MARGIN
    bar = oracle_floor(dps + 10) - GATE_MARGIN
    if bar30 and dps >= 60:
        bar = max(bar, 30.0 + MUT_SLACK)
    return bar


def gate_run(e4c, uvals, dps, label='', bar30=True, certify=False,
             collect=None, raw=False):
    """Transport + reduce all 8 masters at each u in uvals; gate each
    against the live independent oracle.  RAISES (fail-closed) when the
    worst agreement drops below the calibrated bar.  Returns worst rel.
    digits; stores transported values in collect (for the --check value
    crank) when given.  raw=False (default) truncates the printed value
    strings to their certified digits (print-only-certified, print
    layer only); raw=True prints the full dps-digit strings (uncertified tail,
    documented in the [cert] print-policy line)."""
    t0 = time.time()
    if certify:
        Y0, ic_err = e4c.periods_certified(BASE_U, dps)
        print("[ICs]       (I0..I3)(u0=1/5) by certified refine-until-"
              "bound quadrature: err <= %s  (%.1f s)"
              % (mp.nstr(ic_err, 3), time.time() - t0))
    else:
        Y0 = e4c.periods_direct(BASE_U, dps + 25)
        print("[ICs]       (I0..I3)(u0=1/5) by live segment quadrature at "
              "dps %d  (%.1f s)" % (dps + 25, time.time() - t0))
        t1 = time.time()
        ic_err = e4c.certify_ics(BASE_U, dps + 25, Y0)
        print("[cert]      IC certification: worst |ambient - certified| "
              "= %s (raising gate 1e-%.0f; floor model 0.50*wp+1.8 at "
              "wp %d)  (%.1f s)"
              % (mp.nstr(ic_err, 3),
                 ic_floor(dps + 25) - IC_GATE_MARGIN, dps + 25,
                 time.time() - t1))
    worst = float('inf')
    for us in uvals:
        t0 = time.time()
        res = e4c.evaluate(us, dps, Y0=Y0, ic_err=ic_err)
        ttr = time.time() - t0
        print("\n  u = %s%s   (transport %.1f s)" % (us, label, ttr))
        tc = res['cert']
        amp = e4c.path_amplification(us)
        with mp.workdps(dps + 25):
            errY = [amp[k]*(mp.mpf(ic_err) + tc['err_steps'])
                    for k in range(4)]
            bnds = e4c.reduce_bound(us, errY)
            certd = min(float(-mp.log10(bnds[n]/abs(res['masters'][n])))
                        for n in MASTER_NAMES)
        print("  [cert] transport: %d steps, worst tail bound %s (tol "
              "1e-%d, %d escalation(s), N0=%d); value level: worst master "
              "certified to %.1f rel. digits (IC err %s x amp <= %.2f)"
              % (tc['steps'], mp.nstr(tc['worst_bound'], 3),
                 dps + TAIL_GUARD, tc['escalations'], tc['N0'], certd,
                 mp.nstr(mp.mpf(ic_err), 3), float(max(amp))))
        # print-only-certified policy (2026-07-06): never print a value
        # the loop didn't certify.  Certified digit counts of the two value
        # columns: transported = the per-point value-level bound certd (the
        # [cert] line above); oracle = the refine-until-bound tolerance on
        # --certify-full (>= dps), else the calibrated endpoint-floor model
        # at its working precision dps+10.  PRINT LAYER ONLY: gate digits,
        # the --check collect values and every computation below use the
        # untruncated mpf values.
        kt_cert = max(1, min(dps, int(certd)))
        ko_cert = dps if certify else max(1, min(dps,
                                                 int(oracle_floor(dps + 10))))
        if raw:
            kt, ko = dps, dps
            print("  [cert] print policy: --raw full working-precision "
                  "strings (%d significant digits); digits beyond the "
                  "certified bounds (transported %d d, oracle %d d) are an "
                  "UNCERTIFIED tail" % (dps, kt_cert, ko_cert))
        else:
            kt, ko = kt_cert, ko_cert
            print("  [cert] print policy: value strings truncated to their "
                  "certified digits (transported %d, oracle %d, of the "
                  "%d-digit working strings; print-only-certified policy) -- --raw "
                  "prints the full strings" % (kt, ko, dps))
        print("  %-7s %-*s %-*s %s" % ('master', dps + 6, 'transported',
                                       dps + 6, 'oracle (independent)',
                                       'agreement'))
        worst_est = mp.mpf(0)
        for name in MASTER_NAMES:
            t1 = time.time()
            if certify:
                dv = e4c.master_certified(us, name, dps)
            else:
                dv = e4c.master_direct(us, name, dps + 10)
            worst_est = max(worst_est, e4c._last_oracle_est)
            tv = res['masters'][name]
            gd = digits(tv, dv)
            worst = min(worst, gd)
            if collect is not None:
                collect[(str(us), name)] = tv
            print("  %-7s %-*s %-*s %6.1f d  (%.1f s)"
                  % (name, dps + 6, cert_prefix(tv, dps, kt), dps + 6,
                     cert_prefix(dv, dps, ko), gd, time.time() - t1))
        if certify:
            print("  [cert] oracle certified agreements <= %s (tol "
                  "1e-%d)" % (mp.nstr(worst_est, 3), dps + QUAD_GUARD))
        else:
            print("  [cert] oracle engine estimates <= %s (raising gate "
                  "1e-%.0f)" % (mp.nstr(worst_est, 3),
                                oracle_floor(dps + 10) - OR_EST_MARGIN))
    bar = gate_bar(dps, bar30=bar30, certify=certify)
    # STRICTLY-GREATER compare (rc-failclosed pattern): PASS requires
    # worst > bar, never worst == bar -- a mutant landing exactly on the bar
    # must fail loudly (rc != 0).
    if not (worst > bar):
        raise RuntimeError(
            "[gate] transport-vs-oracle agreement %.1f d NOT STRICTLY ABOVE "
            "the raising bar %.1f d at dps %d -- fail-closed (healthy runs "
            "measure >= bar + 3 d; a 1e-30 mutation of any retained exact "
            "string lands at 29.0-30.1 d, below the 32-d demo floor; see "
            "gate_bar/MUT_SLACK docstrings)" % (worst, bar, dps))
    print("  [gate] agreement raising bar %.1f d (strict): worst %.1f d "
          "-> PASS" % (bar, worst))
    return worst


def main():
    ap = argparse.ArgumentParser(
        description="E4C four-point EEC elliptic sector: live maxcut-master "
                    "evaluator + agreement gate (see module docstring).")
    ap.add_argument('--dps', type=int, default=60,
                    help='working precision (default 60; >= 60 reaches the '
                         '30-digit documented bar; raising gate 32 d strict, '
                         'see gate_bar)')
    ap.add_argument('--point', metavar='P/Q',
                    help='rational angle u=P/Q in the transport corridor '
                         '(0.0377, 0.7319); default: gate demo at the '
                         'gate angles 3/7 and 5/9')
    ap.add_argument('--check', action='store_true',
                    help='dps-crank consistency: rerun the gates at dps+40 '
                         '(genuinely different internal depths); the '
                         'transported values must agree to the dps-run\'s '
                         'certified digits (RAISES below the calibrated '
                         'bar) and the gate digits must grow')
    ap.add_argument('--certify-full', action='store_true',
                    help='definition-level path: certify EVERY printed '
                         'constant to >= dps digits by refine-until-bound '
                         'quadrature (slower; the default path keeps the '
                         'recorded precisions byte-stable and gates their '
                         'measured floor instead)')
    ap.add_argument('--raw', action='store_true',
                    help='print the full working-precision value strings '
                         '(dps significant digits, the pre-2026-07-06 '
                         'output); digits beyond the printed [cert] bounds '
                         'are an UNCERTIFIED tail.  The default truncates '
                         'value strings to their certified digits '
                         '(print-only-certified); values, gates and rc are identical '
                         'either way (print layer only)')
    args = ap.parse_args()
    dps = args.dps
    T0 = time.time()
    mp.mp.dps = dps + 30
    e4c = E4C()

    if args.point:
        uq = sp.Rational(args.point)
        uf = float(uq)
        if not (0.0377 < uf < 0.7319):
            raise SystemExit(
                "u=%s outside the transport corridor (0.0377, 0.7319): "
                "bounded by the real singular fibre u~0.03765 and the real "
                "apparent singularity u~0.73191 (see docstring)" % uq)
        worst = gate_run(e4c, [str(uq)], dps, bar30=False,
                         certify=args.certify_full, raw=args.raw)
        print("\nworst master agreement: %.1f d" % worst)
    else:
        runs = [dps, dps + 40] if args.check else [dps]
        results, values = [], []
        for d in runs:
            print("\n== gate demo at dps %d ==" % d)
            coll = {}
            worst = gate_run(e4c, ['3/7', '5/9'], d,
                             certify=args.certify_full, collect=coll,
                             raw=args.raw)
            results.append(worst)
            values.append(coll)
            bar = ("PASS (>= 30 d bar)" if worst >= 30 else
                   "below the 30 d bar -- expected for dps < 60: the "
                   "oracle noise floor is ~0.55*dps digits")
            print("\n  worst master agreement at dps %d: %.1f d  -> %s"
                  % (d, worst, bar))
        if args.check:
            # value crank: the transported masters at D
            # and D+40 come from genuinely different internal depths
            # (Taylor seeds, quadrature depths, working precisions) and
            # must agree to the D-run's certified digits.
            bar_crank = ((dps - CRANK_MARGIN) if args.certify_full
                         else (ic_floor(dps + 25) - CRANK_MARGIN))
            with mp.workdps(2*dps + 100):
                worst_cr = min(digits(values[0][key], values[1][key])
                               for key in values[0])
            print("\n[check] value crank dps %d vs %d: worst transported-"
                  "master agreement %.1f d (raising bar %.1f d)"
                  % (dps, dps + 40, worst_cr, bar_crank))
            if worst_cr < bar_crank:
                raise RuntimeError(
                    "[check] value crank FAILED: %.1f d below the "
                    "calibrated bar %.1f d -- fail-closed"
                    % (worst_cr, bar_crank))
            grew = results[1] > results[0] + 5
            print("[check] dps crank: worst agreement %.1f d -> %.1f d "
                  "at dps+40: %s" % (results[0], results[1],
                                     "GROWS (consistent)" if grew else
                                     "FAILED TO GROW"))
            if not grew:
                raise SystemExit(1)
    print("\nTotal wall time: %.1f s" % (time.time() - T0))


if __name__ == '__main__':
    main()
