#!/usr/bin/env python3
"""Three-loop equal-mass banana (K3): evaluate the closed form at eps^0,

    m1_eps0(t) = 7 zeta_3 * varpi_0(t) - Part_reg(t)

varpi_0 = Domb K3 period (OEIS A002895), Part_reg = MUM-regularized holomorphic
particular of the same order-3 Domb/Picard-Fuchs operator with toric source 24x,
x = t/64.  Self-contained (pip dependency: mpmath only).

Usage:
    python3 banana-evaluate.py                         # gate demo + dps-doubling check
    python3 banana-evaluate.py --point=-7/2 --dps 260  # any point, any precision
    python3 banana-evaluate.py --point 1.25 --dps 500  # (use --point=... for negative t)
    python3 banana-evaluate.py --heldout18             # all 18 points of the record vs their stored strings
    python3 banana-evaluate.py --heldout18 --dps 260   # the same at dps 260
    python3 banana-evaluate.py --heldout18 --mutate-heldout18=-3:80   # the shipped control: FAIL, exit 1
    python3 banana-evaluate.py --continue --point 18            # past the disk: m1[eps^0](18 + i0) vs the record
    python3 banana-evaluate.py --continue --point 10 --dps 60   # a fresh point: goal 60 / goal 40 / the pair floor
    python3 banana-evaluate.py --continue --point 18 --mutate   # the shipped control: FAIL by name, exit 1
    python3 banana-evaluate.py --continue --point 18 --lower-as-physical   # the planted-sign control: FAIL on Im
    python3 banana-evaluate.py --eps1                          # the eps^1 layer at all 18 points of the record vs the stored eps^1 strings
    python3 banana-evaluate.py --eps1 --point 7/2 --dps 200    # one point (a stored point is gated; write --point=-3 for negative t)
    python3 banana-evaluate.py --eps1 --mutate-eps1=T07:30     # the shipped control: FAIL by name, exit 1
    python3 banana-evaluate.py --bessel --dps 60               # alpha_1 recomputed live by quadrature vs the stored string
    python3 banana-evaluate.py --bessel-eps 5                  # the layers eps^0..eps^5 at t = -8 from the Bessel representation vs the stored record (dps 60, N 12, rho 1e-4)
    python3 banana-evaluate.py --bessel-eps 1 --point=-3       # a Euclidean point of the 18-point record: eps^0 and eps^1 vs its strings, eps^0 vs the closed form
    python3 banana-evaluate.py --bessel-eps 1 --point 0 --dps 40     # t = 0: 7 zeta_3 and alpha_1
    python3 banana-evaluate.py --bessel-eps 5 --planted        # the control (J_(+eps) for J_(-eps)): FAIL by name on eps^1, exit 1

Exit codes: 0 every gate passed; 1 a gate FAILED (RuntimeError, fail-closed, named); 2 usage (and the
refusals by name: |t| >= 4 on the disk path, t > 0 for --bessel-eps, a --bessel-eps budget below 20 d);
3 a data file of --continue / --eps1 / --bessel-eps differs from its sha256 pin; 4 such a data file is missing.

Library use:  from banana-evaluate import m1_eps0;  m1_eps0(Fraction(-3), dps=200)

Domain of the series: the MUM disk |t| < 4, t = p^2/m^2 (Euclidean t < 0 and
subthreshold 0 < t < 4; nearest Picard-Fuchs singularity is x = 1/16, i.e. t = 4).
Both pieces are plain power series with exact-rational coefficients from the Domb
recursion, so arbitrary precision = more terms + higher dps; term count is
chosen automatically from (|t|/4)^n decay.  Convergence slows as |t| -> 4;
points with |t| >= 4 are reached by `--continue --point T` (since 2026-09-06): the
closed form is the eps^0 layer of the banana's four-master system, and past the
disk it is that system's solution continued from t = 2 along a path in the upper
half t-plane (the Feynman t -> t + i0), gated against the stored auxiliary-mass-flow
values of the physical region -- see CONTINUATION below.

The reference values embedded below were computed in this work from an
independent high-precision AMFlow evaluation and held out from the fit.
Since 2026-09-06 the stored strings carry the full length of the AMFlow
record: 140 significant digits at t = -3 and t = 1/2 (goal-130 runs, ball
radii below 1e-140) and 110 at t = -7/2 (a goal-100 run, radius 1.33e-110);
the 60-digit literals shipped before were round-to-nearest renderings of
these strings.  Agreement against a stored string is capped by the shorter
of the string and the working precision dps + GUARD (= dps + 15), and the
printed figure names the active cap; the gate bar is min(dps, string
digits) - REF_MARGIN.  The record's own comparison of the closed form
against these values at its working precision 120 read 119.9 / 110.8 /
119.8 d (minimum 110.4 d over its 18 points); that figure is printed beside
each agreement as the record's figure, not as a cap.  The default run
(dps 130) prints 140.0 / 110.0 / 140.0 d; --heldout18 gates all 18 points.

Tiers, measured 2026-09-06 (one process, a shared 96-core host at loadavg 116-136, nice 10, wall clock by
GNU time including the import-time coefficient cache; the previous release then this one):
    default (dps 130: three points + the doubling check 130 -> 260)   0.91 s -> 0.75 s, 32 MB
    --dps 260 (doubling to 520)                                       2.96 s -> 2.98 s, 50 MB
    --dps 30                                                          0.65 s -> 0.75 s
    --point=-7/2 --dps 260                                            3.58 s -> 3.26 s
    --heldout18 (18 points at dps 130; NEW)                           1.72 s (0.46 s inside the tier)
    --heldout18 --dps 260                                             3.15 s (2.53 s inside the tier)
    --heldout18 --dps 30                                              2.12 s (0.10 s inside the tier)
    --continue --point 10 (dps 130; three routes, 9 steps each)      11.12 s (10.34 s inside the tier), 42 MB
    --continue --point 18 (dps 130; 15 steps per route)               27.69 s (27.04 s inside the tier)
    --continue --point 31/2 (dps 130; 15 steps: next to the threshold) 27.47 s (26.83 s inside the tier)
    --continue --point 200 (dps 130; 25 steps per route)              51.71 s (51.04 s inside the tier)
    --continue --point=-8 (dps 130; 10 steps per route)               9.19 s (8.44 s inside the tier)
    --continue --point 10 --dps 60                                    5.67 s (5.02 s inside the tier)
    --continue --point=-3 (the in-disk control; 9 steps)             7.13 s (6.44 s inside the tier)
    (the --continue rows measured at loadavg 95-99, four such runs side by side)
    --eps1 (18 points at dps 130; NEW)                             12.54 s (11.74 s inside the tier), 41 MB
    --eps1 --dps 200                                               24.88 s (24.20 s inside the tier), 48 MB
    --eps1 --dps 260                                               37.66 s (36.13 s inside the tier), 52 MB
    --eps1 --point 7/2 --dps 110 / --dps 200 (one stored point)    5.19 s / 12.05 s
    --eps1 --point=-3 --dps 260                                    8.37 s
    --eps1 --point 1/3 (no stored string; dps 130)                 1.99 s
    --eps1 --mutate-eps1=T07:30 (the control; exit 1)              12.27 s
    --bessel --dps 30 / --dps 60 / the default dps 130             5.46 s / 12.19 s / 103.32 s, 37 MB
    (the --eps1 / --bessel rows measured 2026-09-08 at loadavg 202-203 (the 1-minute figure of 2 readings beside the runs), one process at a time; the rows above them unchanged)
    --bessel-eps 5 (t = -8, dps 60, N 12, rho 1e-4; NEW)                 117.25 s (pass 1 67.66 s, pass 2 48.75 s inside the tier), 38 MB
    --bessel-eps 5 --planted (the control; exit 1)                     125.18 s
    --bessel-eps 1 --point=-3 (dps 60)                                 112.43 s
    --bessel-eps 1 --point 0 --dps 40                                  47.98 s
    (the --bessel-eps rows measured 2026-09-11, the four side by side, each under a 2-CPU / 8 GiB fence at nice 10, loadavg 140-161, GNU time; the rows above them unchanged)

CONTINUATION (2026-09-06): `--continue --point T` continues the closed form past the
disk.  The closed form is the eps^0 layer of the top master m1 of the raw four-master
system of the banana, d/dt m = (A0(t) + eps A1(t)) m with denominator t (t - 4)(t - 16);
graded in eps (orders -3..1) the layers obey one eps-free linear system on 20
components, read as exact rationals from banana-graded-system.json (sha256-pinned,
CONT_PINS; exit 3 / 4).  The base state at t = 2 is the closed form's own value
(m1_eps0, the same code path as every disk tier) beside the exact -Gamma(eps)^3 tower
of m0 and the dotted masters' towers and the eps^1 layer from the holomorphic MUM
recursion of the same system at t = 0 (its free constants m1[eps^K](0) = 0, 0, 0,
7 zeta_3, alpha_1 -- alpha_1 the Bessel-moment constant of the record, 110 digits); the
recursion's own m1[eps^0](2) is a RAISING gate against the closed form.  From there a
fixed-eps Taylor march along [2, 2 + 2i, t + 2i, t] (the Feynman t -> t + i0): every
step's coefficients from the exact recurrence of D(t) y' = N(t) y shifted to the step
point, the step half the distance to the nearest singular point (0, 4, 16), the
Taylor tail certified per step by the zero-run-aware geometric bound of the record's
transport against 10^-(dps+12) ||y||, halving on a miss and RAISING below 1/64.  Route
independence (the same march at height 3) and the Schwarz control (the lower detour
t - i0 = the complex conjugate) are RAISING gates at dps - 8, m1's negative orders are
gated as structural zeros.  At a stored point of banana-minkowski-gates.json (the
record's t = -8; 5, 8, 12, 31/2 real between the pseudo-threshold and the threshold;
18, 25, 40, 100, 200 complex above it -- goal-100 / goal-130 pairs, 110 / 140-digit
strings; the fresh t = 10, 20 goal-60 / goal-40 pairs, predicted before they were
run) every transported component is gated Re and Im separately at bar min(dps,
string digits) - 8 (the eps^1 layer capped by alpha_1's 110 digits; a fresh point at
the floor of its goal-60 / goal-40 pair), FAIL by name, exit 1.  Not established: the
thresholds themselves (never landed on), t -> infinity (the raw system is not
Fuchsian there; the largest stored point is t = 200), the eps^2.. layers, a closed
form of alpha_1 (the eps^2..eps^5 layers, carried by the transport, are gated at t = -8 by
--bessel-eps since 2026-09-11, from an integral representation independent of the system).
--mutate (a digit of the stored m1[eps^0] string) and
--lower-as-physical (the t - i0 value offered as physical) are the shipped controls.
|t| >= 4 without --continue is refused by name (exit 2); the disk tiers are
byte-for-byte the previous release.

THE EPS^1 LAYER (2026-09-08): `--eps1` evaluates m1[eps^1](t) = alpha_1 varpi_0(t) + Part^(1)(t)
on the disk |t| < 4 with the same eps-graded holomorphic recursion that seeds --continue,
summed at the point: at eps^1 the Dyson chain of the certified connection activates the
letters f_2a and f_2b beside 1 and f_4a (twelve words of depth up to four once the record's
regularized zeros are used; the word list ships as banana-eps1-words.json, printed by the
tier, pinned in EPS1_PINS), but because every master is analytic at p^2 = 0 the t-space sum
of those words is one new boundary constant times the K3 period plus a holomorphic
particular of the recursion.  The constant alpha_1 = m1[eps^1](0) is the eps^1 coefficient of
the p^2 = 0 vacuum banana in d = 2 - 2 eps, 16 int_0^oo r ln r K_0(r)^4 dr - 7 zeta_3 (2 ln 2 +
gamma_E), the CONT_ALPHA1 string of the record (110 digits; provenance in
EPS1_ALPHA1_PROVENANCE); `--bessel` recomputes it live by quadrature and gates it against the
string.  At every point of the 18-point record the layer is gated against the eps^1 midpoint
string of the same output file (HELDOUT18_EPS1, beside HELDOUT18, keyed by sha256) at bar
min(dps, string digits, 110) - 8, the printed figure capped by the string, the working precision
and alpha_1's 110 digits with the cap named; three RAISING gates ride beside: the recursion's
eps^0 component against the closed form (at dps), alpha_1 fitted from the string against
CONT_ALPHA1 (the same bar), and at t = 7/2 the decomposition (the recursion re-run with alpha_1
:= 0 is Part^(1); the difference must be alpha_1 varpi_0 to dps - 8).  Measured on the delivered
bytes at dps 130: 18/18 PASS, minimum printed agreement 109.8 d at t = 5/4 (bars 102 d at every
point), alpha_1 fitted from the strings 109.8-110.0 d, the recursion's eps^0 component vs the closed
form >= 144.5 d at every point (bar dps), the decomposition at t = 7/2 148.3 d (bar dps - 8); 12.54
s; at dps 200: 18/18 PASS, minimum 109.8 d at t = 5/4; 24.88 s (dps 260: 18/18, 109.8 d, 37.66 s).
Not established: a closed form of alpha_1 (an integer relation search in the zeta / ln 2 /
gamma_E ring and in the ring extended by L(f_3, 2) found none at height 10^4); the individual
eps^1 boundary data of the canonical frame (only their combination alpha_1 is fixed); the
letters f_2b, f_4a, f_4b, f_6 as explicit functions (the record pins f_2a only; the words are
summed implicitly); the figure at the goal-100 points is capped by the 110-digit strings and no
deeper eps^1 record was run; |t| >= 4 is refused here and carried by --continue.
--mutate-eps1 T[:K] is the shipped control (digit 30 of the t = 7/2 string: t = 7/2 m1[eps^1] (29.7
d < 102.0 d); t = 7/2 alpha_1 fitted from the string (29.9 d < 102.0 d), exit 1).
Observed, not assumed: with the physical boundary data the recursion's series converges with the
radius of the threshold t = 16, not of the pseudo-threshold t = 4 -- at t = 7/2 and dps 110 the
value needs 211 terms against 2085 for the alpha_1 := 0 piece alone and 2206 for the closed form's
Domb series (the pseudo-threshold is absent from the physical sheet and the term count shows it);
above dps 110 the count grows again, because the part of the non-physical solution left by the
110-digit alpha_1 must fall below the tolerance too (1739 terms at dps 200).  The certified tail
rule is unchanged (r = |t|/4 on the trailing window: a valid, conservative envelope either way).

THE BESSEL REPRESENTATION (2026-09-11): `--bessel-eps K` evaluates the layers m1[eps^0..eps^K](t) at a Euclidean
point t <= 0 from the position-space form of the four propagators, exact in d = 2 - 2 eps:
    m1(t; eps) = 2^(3-3eps) int_0^oo r^(1+2eps) (a r)^eps J_{-eps}(a r) K_eps(r)^4 dr,   a = sqrt(-t)
(measure d^dk/pi^{d/2} per loop, no e^{gamma_E eps}; at eps = 0 the classical 8 int r J_0(a r) K_0^4 dr; at t = 0 the
vacuum banana B(eps) of --bessel, eps^0 = 7 zeta_3, eps^1 = alpha_1).  The layers are the Taylor coefficients in eps,
read off the circle |eps| = rho by the trapezoid rule with N nodes (conjugate nodes share one tanh-sinh quadrature with
complex Bessel orders); m1(t; eps) is analytic on |eps| < 1/3 (d = 8/3 is the banana's first divergence), so layer k
carries min(N log10(1/(3 rho)), dps - k log10(1/rho)) digits a priori (aliasing / roundoff), a second pass at dps - 15
gives the two-precision floor, and every printed value is cut to its budget; --dps defaults to 60 in this tier (with
N 12 and rho 1e-4 the aliasing term is 42.3 d, so more working digits need a larger N).  The representation shares
nothing with the four-master system, the MUM recursion or the transport, so it gates what they carry: at t = -8 (the
stored Euclidean point of banana-minkowski-gates.json, pin-checked) every stored order eps^0..eps^5 of both legs; at
t = -7/2 and -3 the eps^0 / eps^1 strings of the 18-point record; at t = 0 the two constants; on -4 < t < 0 the closed
form at eps^0 -- RAISING at min(budget, string digits) - 8, FAIL by name, exit 1.  Measured with this release's code (one
process per run under a 2-CPU / 8 GiB fence at nice 10 on a shared host, loadavg 140-161, GNU time; CHANGES.md carries
the re-run of every row on the final bytes, digit for digit the same):
`--bessel-eps 5` (t = -8, dps 60, N 12, rho 1e-4) 117.25 s: eps^0..eps^5 agree with the goal-100 leg to
41.4 / 41.7 / 41.9 / 42.1 / 42.1 / 42.2 d and with the goal-130 leg to 41.4 / 41.7 / 41.9 / 42.1 / 42.1 / 42.2 d (bars
34.3 / 34.3 / 34.3 / 34.3 / 34.3 / 32.0 d), two-precision floors 46.7 / 43.5 / 40.2 / 36.2 / 32.3 / 29.5 d (bars
34.3 / 33.0 / 29.0 / 25.0 / 21.0 / 17.0 d); `--planted` at the same settings 125.18 s: eps^1 = -71.61317 against the stored
-51.29..., 0.4 d < 34.3 d, FAIL by name, exit 1 (eps^0 unchanged, 39.7 d); `--bessel-eps 1 --point 0 --dps 40`
47.98 s: 7 zeta_3 to 41.0 d (bar 32.0), alpha_1 to 37.7 d (bar 28.0); `--bessel-eps 1 --point=-3` (dps 60)
112.43 s: eps^0 vs the 140-digit string 41.4 d, vs the closed form 41.4 d, eps^1 vs its string 41.8 d (bars
34.3 / 34.3).  Not carried: t > 0 (refused by name, exit 2: below the threshold the kernel continues to the
modified Bessel function of the first kind and above it the integral needs its own prescription; the physical region
is --continue's); layers beyond the budget (a budget under 20 d is refused, naming the knob); a certificate of the
quadrature itself (its error estimate is printed as a diagnostic; the two-precision floor and the strings are the gates).

CHANGELOG
2026-09-11 (--bessel-eps: the eps-layers from the exact-in-d Bessel representation): NEW `--bessel-eps K` with `--N`,
`--rho`, `--planted`; `--dps` given no value resolves per mode (130 as before; 60 for --bessel-eps); the gates file's
pin check reused for the one file this tier reads, the digit helpers reused; no unit of the disk tiers, of --continue,
--eps1 or --bessel changed (masked-AST identical to the previous release; the default, --dps 30 and --heldout18 --dps 30
outputs byte-identical with walls masked).  Measured: the rows above.
2026-09-08 (--eps1 and --bessel: the eps^1 layer on the disk): NEW `--eps1` (the 18 points of the
record, or `--point T` with |t| < 4) and `--bessel`, the HELDOUT18_EPS1 table beside HELDOUT18,
the word list banana-eps1-words.json pinned in EPS1_PINS, the control `--mutate-eps1 T[:K]`; the
recursion, the tail rule, the pin check and the digit-flip of the existing tiers reused, no unit
of the disk tiers or of --continue changed (masked-AST identical to the previous release).
Measured on the delivered bytes: --eps1 12.54 s at dps 130 (18/18 PASS, minimum 109.8 d), 24.88 s at
dps 200, 37.66 s at dps 260; --bessel 12.19 s at dps 60 (alpha_1 live vs the string 70.0 d), 103.32
s at the default dps 130 (110.0 d, the cap of the string); the control exits 1 at t = 7/2 m1[eps^1]
(29.7 d < 102.0 d); t = 7/2 alpha_1 fitted from the string (29.9 d < 102.0 d).
2026-09-06 (--continue: the physical region): NEW `--continue --point T` for |t| >= 4
(and |t| < 4 as the in-disk control against the closed form and the stored strings),
the two data files banana-graded-system.json / banana-minkowski-gates.json pinned by
sha256, the controls `--mutate` / `--lower-as-physical`; the fence paragraph of the
docstring rewritten to name the tier; the refusal of |t| >= 4 on the disk path now by
name (exit 2; the series units themselves still raise on such a point).  No unit of
the disk tiers changed: every 'this work' string, tail bound, N, agreement and bar of
the default, --dps 260, --dps 30, --point and --heldout18 tiers is byte-identical to
the previous release.
2026-09-06 (references at the full length of the record): the three REFS
strings are the eps^0 midpoints of the AMFlow record as written (140 / 110 /
140 significant digits; provenance beside REFS); the second REFS field is
the record's own comparison at its dps 120, printed as that figure and no
longer as a 'full-precision agreement'; the printed agreement is capped by
the working precision dps + GUARD as well as by the string length and names
the active cap (at --dps 30 the value and the parsed string coincide at the
45 working digits, and the line used to print the string's full digit
count); NEW --heldout18: all 18 points of the record gated against their
stored strings (the HELDOUT18 table, per-point provenance), with
--mutate-heldout18 as the shipped control.  The value path is untouched:
every 'this work' string, tail bound, N and gate bar at the default and at
--dps 260 is byte-identical to the previous release.
2026-07-05 (axis3 wave, infinite-precision work order): the closed-form term
count nterms_for(t, dps) is now a STARTING seed only.  Every evaluation
certifies its own truncation at runtime: after the series sum, a certified
trailing-window tail bound (max |c_n x^n| over the last 8 accumulated terms
of BOTH series, times r/(1-r) with r = |t|/4 — the coefficient ratios
D_{n+1}/D_n and b_{n+1}/b_n increase monotonically to 16, so 16|x| = |t|/4
is a certified term ratio; the 8-term window absorbs any residual wobble)
must beat 10^-(dps+TAIL_GUARD).  On failure the series grows x1.5 by EXACT
continuation of the same recurrences up to 8x the seed, then RAISES — a
value the loop did not certify is never returned.  The dps-doubling check
and all stored-reference comparisons are now RAISING gates, not printed
comparisons.  Same refine-until-bound semantics as tools/detransport
(E3/tailcut helpers); implemented inline because this blog script ships
standalone (mpmath-only).  Calibration (2026-07-05, gate set at dps
30/130/260): worst seed-N tail bound 10^-(dps+20.2) vs tol 10^-(dps+12)
=> >=1e8 headroom; healthy self-agreement dps+14.7..+16.4 vs gate at dps+5
=> >=1e9 headroom; defaults never escalate.
"""

import math

from mpmath import mp, mpf, zeta, fabs, log10
from fractions import Fraction

mp.dps = 130
NTERMS = 2600  # import-time cache size; covers the gate demo (|x| <= 7/128 -> ratio <= 7/8 vs nearest singularity x=1/16 at dps=130)
GUARD = 15     # guard digits on top of requested dps

# certified-tail / raising-gate knobs (2026-07-05 axis3 wave; see CHANGELOG)
TAIL_WINDOW = 8   # trailing terms whose max seeds the geometric tail bound
TAIL_GUARD = 12   # accept only if certified tail bound < 10^-(dps+TAIL_GUARD)
TAIL_GROW = 1.5   # series-length growth factor on a failed bound (exact continuation)
TAIL_NCAP = 8     # cap = TAIL_NCAP * seed length; RAISE there (fail-closed)
REF_MARGIN = 8    # raising gate: agreement >= min(dps, ref digits) - REF_MARGIN
SELF_MARGIN = 5   # doubling gate: self-agreement >= dps + SELF_MARGIN digits

# Reference values (computed in this work via independent AMFlow evaluation; held out)
# The three strings are the eps^0 midpoints of the top-sector master [1,1,1,1,0,0,0,0,0] read from the
# AMFlow output files of the record (family BAN, nine propagators, d0 = 2, eps_order 11, msq = 1,
# n_thread 4, ending schemes Tradition + SingleMass; a goal-130 run returns a 140-digit ball, a goal-100
# run a 110-digit ball; where both exist the record takes the goal-130 midpoint).  The 60-digit literals
# shipped before 2026-09-06 were round-to-nearest renderings of these strings (a byte prefix at
# t = -7/2; a rounded last digit at t = -3 and t = 1/2).
# The second field of each entry is the record's own comparison of the closed form against the value at
# the record's working precision 120 (119.9 / 110.8 / 119.8 d): a record figure, not a cap.
#   t = -3: T02_B.json (10624 B), goal_digits 130, eps^0 ball radius 7.7e-142, im 0,
#     140 significant digits; output sha256 883fbc958131496a53c646266006bc1b69042664eb5352876fe4b29807873919;
#     config sha256 e5e7c5899c1f1781ac2c2700e33bbdc3c4db1719c0f38e6543b2f5b32f845f23.
#   t = -7/2: T20_A.json (9635 B), goal_digits 100, eps^0 ball radius 1.33e-110, im 0,
#     110 significant digits; output sha256 1eaeab7a91fea5f69a8133bf78996572dd70e7fc86daecea30fefad51e8db836;
#     config sha256 70d7256383f3aff43effef9764e63b7b2e77a43014bbc3567f6dc8d07a43ec4c.
#   t = 1/2: T05_B.json (10622 B), goal_digits 130, eps^0 ball radius 9.65e-141, im 0,
#     140 significant digits; output sha256 e7528b44ac4228048e3c435ff194e757e5c041a01cb242770e2354dc82b48651;
#     config sha256 6592fccdb87190b6f85b564ca2ed07ecc2e9949ff828cf9844de01f18b66742e.
REFS = {
    "-3":   ("8.0002891185467503010932845048045525364384632031802549617383352277936216141053246806834988327881912036677364016881468604417806312465278036617", 119.9),
    "-7/2": ("7.9378907540142232111525519567317253699938943013554118876577127293677941759913925785513436261309871347922934122", 110.8),
    "1/2":  ("8.4910687364486275996196538511658286450777771420953617425045580365510612503846672622927106138147164475199792230907099158951684332152262394266", 119.8),
}

# The 18 points held out of the fit (--heldout18): every point of the record's verification set with the
# eps^0 midpoint string of its AMFlow output file, in the form of REFS.  Columns: t, output file, output
# sha256, config sha256, goal_digits, ball radius, the record's own comparison at its dps 120, the string.
# Common to all 18: family BAN, eps_order 11, n_thread 4, msq = 1, d0 = 2, imaginary part 0.  t = -7/2 and
# t = -3 are Euclidean, the other sixteen subthreshold (0 < t < 4).  The three REFS entries are the rows at
# t = -3, -7/2, 1/2 (the tier asserts them byte-equal).
HELDOUT18 = [
    ("-7/2", "T20_A.json",
     "1eaeab7a91fea5f69a8133bf78996572dd70e7fc86daecea30fefad51e8db836",
     "70d7256383f3aff43effef9764e63b7b2e77a43014bbc3567f6dc8d07a43ec4c",
     100, "1.33e-110", 110.8,
     "7.9378907540142232111525519567317253699938943013554118876577127293677941759913925785513436261309871347922934122"),
    ("-3", "T02_B.json",
     "883fbc958131496a53c646266006bc1b69042664eb5352876fe4b29807873919",
     "e5e7c5899c1f1781ac2c2700e33bbdc3c4db1719c0f38e6543b2f5b32f845f23",
     130, "7.7e-142", 119.9,
     "8.0002891185467503010932845048045525364384632031802549617383352277936216141053246806834988327881912036677364016881468604417806312465278036617"),
    ("1/8", "T45_A.json",
     "9686d4eb88b231cc564b3d84f7bf5997252c82eb1c5b04a4b4d5cc6ccff1ae64",
     "409690f9ce461fc0e62362349335e293c80c4a2e5e09a334fbbfaaa4d1d3a083",
     100, "1.43e-110", 110.8,
     "8.4333359576690257126609160900431230932193131008174525720034782970715844973735228104566467865111863010060970279"),
    ("1/4", "T26_A.json",
     "e3ed9d905bf1558a64d2041b0ec84a2c30b3e12dfb308f3868a66579a96bcd8d",
     "c92ba288ce7d74130b2feb8fce3a1c76a0d211792c968ef22be7240969cba8f0",
     100, "3.65e-110", 110.4,
     "8.4524253811520755954207448485374429553178847503656071251852041680795720633784919612202663149649209220657067697"),
    ("1/2", "T05_B.json",
     "e7528b44ac4228048e3c435ff194e757e5c041a01cb242770e2354dc82b48651",
     "6592fccdb87190b6f85b564ca2ed07ecc2e9949ff828cf9844de01f18b66742e",
     130, "9.65e-141", 119.8,
     "8.4910687364486275996196538511658286450777771420953617425045580365510612503846672622927106138147164475199792230907099158951684332152262394266"),
    ("5/8", "T46_A.json",
     "07a5682d5a688707011b8414d4748a8ddfedf3a431268f22c06f10ae4a3c360f",
     "52b300d479ff4a349d0cda0952c04798b1dd2b2fae5c570257fb1fbaaaaab959",
     100, "3.66e-110", 110.4,
     "8.5106273698815280228730691581372954665666325396407888961552690357156411056545803961483893531234817997722339413"),
    ("3/4", "T27_A.json",
     "e01c632141ed69477067c56d0bc5592c922804229c2dfc20089ccc5e20fcddfe",
     "a95c492a6d78b2499866fd915589b30b3896f1caf45090cc2f6a51039ab1171d",
     100, "1.86e-110", 110.7,
     "8.5303471976452163693079023167965406236347810670165971959929987161331374255411144585487993588568400308846269616"),
    ("1", "T28_A.json",
     "e598ada0aae5ac552759400f5ad913a55298879ef9d488ad55ae417493a2a64e",
     "ac2846e89cef2ee4af9f6b79a0686481a33cc86b7c0ece5d98deb4515813f068",
     100, "2.34e-110", 110.6,
     "8.5702804433744612681496958242465372861054382173364497361975492796014709719445127039701784007499447741359381478"),
    ("9/8", "T47_A.json",
     "2a6748611f3a4be73eadb8ddf4d517ab762e23e07331dc0b1ba2fa647cca344f",
     "b9c9350e151695c86e1de283b3f1cb51fd1a15ad2dd562cead969d38a7fe6782",
     100, "3.04e-110", 110.5,
     "8.5904990109795521252255041444498997183995147812151696682906014953794364054609515582577379069981180461948579082"),
    ("5/4", "T51_A.json",
     "e66a43f6da79c9fbbdf5f2d299efd6c731bed0553ad54fd3b9b36b09ec47c086",
     "7c8d1d3f934023ef96fcf9b482d55021ecf2bc9c37d94dde23c7ea3b6a730f7d",
     100, "6.07e-111", 111.2,
     "8.6108890758787800518435218570307175091053798197806583981523938355734298849413469715618584623168330668434966832"),
    ("3/2", "T06_B.json",
     "15d2943c75ba58502160bce4a2d5519e162454ccf1fa387b294b351539998489",
     "b2491069e832d5e794dd6c70045e99c65d52e2346838c0d34693eccf7106c8bc",
     130, "3.31e-140", 119.7,
     "8.6521946800128070513095823380416907640415630810004800533181984309441098813462555641875272466524806815819769170093398462363921650665689196273"),
    ("7/4", "T50_A.json",
     "0d8cddab1f86d84cf1883f93a95cf5a8cefcc9b742e6dc6df3d89ab50cffdf61",
     "1b938bc04dddc06cf876fef11df7c01624128fe8a681271104037b809ba4bad8",
     100, "1.97e-110", 110.6,
     "8.6942198870650272470569869585175318201828662219998889911456917095238283858769446919261985308985146198753764521"),
    ("2", "T29_A.json",
     "4d35220703ed36662b252a4272f7b165abb381279707e6b98837aea99c3c7bea",
     "6229a30901c4fe506bc82d10afb3e6c213256911dcd87adbd3c510e6e28c34ef",
     100, "2.72e-110", 110.5,
     "8.7369884438818315840372233133135091174562152438655003948483979361168622314491510740736245960718454686843105194"),
    ("5/2", "T30_A.json",
     "b37c08cc57bf380984e3235a2b684990ba6dc5e0cbf2bb50d3a906afb95ea889",
     "2010b07214221c1547002fb24e028f4488f0aa239fe0abd0cf7755ee2f2886a8",
     100, "2.88e-110", 110.5,
     "8.8248566282395570371447864608673469778203174822391640246613279095356543771770382813261073867439403622289801063"),
    ("11/4", "T48_A.json",
     "fa782b4f35ea2271880ca62529980b49d0ee450587adb1f4ce551d7d09491b53",
     "98973286821c691219616774cf65a24ba52506bd06e7a3f16e8e2a8ccb40473f",
     100, "8.64e-111", 111.0,
     "8.8700100349040369637232790513250251083633752456707108567432401939874573695699846256590952636862040162255563979"),
    ("3", "T31_A.json",
     "f982fc0c97e2a25d4e0b5d9455ae0717b79b5b9aa432ebf5957c9f6956f949df",
     "3b82e6d32b35d1bd661aebd88e61342506406c331d851f2d53c747b366343218",
     100, "1.37e-110", 110.8,
     "8.9160145345817307959133976318405236789833748650764786829755033423617851832252098197533644974963285896234475541"),
    ("13/4", "T32_A.json",
     "72e2d59a06ca0d37bcc7c0bc52613ee4aba9206fd391f1771c60e5f5b4b18ac8",
     "396d6648875d00dc6048fc39e90aa7005c1e2d68d61430baecdc8820e7f6ec80",
     100, "3.93e-110", 110.4,
     "8.9629007161899695973335368784885400590208083886401075479567857053380408765921826338699841721571196949024936789"),
    ("7/2", "T07_B.json",
     "5ffa89b763ccbf2179da99055a0040c591fbf69fa13b65e675882af8ee5275a2",
     "25eea590525b3c01437dc814353e84b1eab2f7dd01a57ef465ae103bc5fab290",
     130, "1.94e-140", 119.5,
     "9.0107008457786770965240725726512975574116732730801652879116986933663301359990316287254131910779898514521336164476965187830145449252963187652"),
]



# The eps^1 layer of the same 18 output files (--eps1, 2026-09-08): the eps^1 midpoint string of the top master read from
# the output file the HELDOUT18 row names -- the same output and configuration sha256 (the tier asserts the rows are keyed
# to each other), the run's goal digits and the ball radius of the eps^1 value; 140 significant digits at the four goal-130
# points, 110 at the fourteen goal-100 points; imaginary part 0 at every point.  Columns: t, output file, output sha256,
# configuration sha256, goal_digits, ball radius, the string.
HELDOUT18_EPS1 = [
    ("-7/2", "T20_A.json",
     "1eaeab7a91fea5f69a8133bf78996572dd70e7fc86daecea30fefad51e8db836",
     "70d7256383f3aff43effef9764e63b7b2e77a43014bbc3567f6dc8d07a43ec4c",
     100, "2.42e-109",
     "-52.741638898679491896167990697965958507080839934225820767005244833436379261750585446798118477536816232155216550"),
    ("-3", "T02_B.json",
     "883fbc958131496a53c646266006bc1b69042664eb5352876fe4b29807873919",
     "e5e7c5899c1f1781ac2c2700e33bbdc3c4db1719c0f38e6543b2f5b32f845f23",
     130, "3.15e-139",
     "-52.909982818793232350416456125835733449147086345408091483599017697405471578277892097909928620085728298367482684418299818013199578029180835239"),
    ("1/8", "T45_A.json",
     "9686d4eb88b231cc564b3d84f7bf5997252c82eb1c5b04a4b4d5cc6ccff1ae64",
     "409690f9ce461fc0e62362349335e293c80c4a2e5e09a334fbbfaaa4d1d3a083",
     100, "2.90e-109",
     "-53.996903737165705819484296397734966551289066424052124862914191174431911038960330639257315159871523394563202151"),
    ("1/4", "T26_A.json",
     "e3ed9d905bf1558a64d2041b0ec84a2c30b3e12dfb308f3868a66579a96bcd8d",
     "c92ba288ce7d74130b2feb8fce3a1c76a0d211792c968ef22be7240969cba8f0",
     100, "6.85e-110",
     "-54.041538795464585606839236573861072935696037765536604856141103184346797805199773795882608263167353984434357742"),
    ("1/2", "T05_B.json",
     "e7528b44ac4228048e3c435ff194e757e5c041a01cb242770e2354dc82b48651",
     "6592fccdb87190b6f85b564ca2ed07ecc2e9949ff828cf9844de01f18b66742e",
     130, "1.62e-139",
     "-54.131046207551007580614738473720638490690260874292813762775398912936219245946134459111795277412185678101588136099550079149985841899338594477"),
    ("5/8", "T46_A.json",
     "07a5682d5a688707011b8414d4748a8ddfedf3a431268f22c06f10ae4a3c360f",
     "52b300d479ff4a349d0cda0952c04798b1dd2b2fae5c570257fb1fbaaaaab959",
     100, "9.04e-110",
     "-54.175915501614118134280017562243580136054832909000658341724193055238893388068858491997583656549907104467891499"),
    ("3/4", "T27_A.json",
     "e01c632141ed69477067c56d0bc5592c922804229c2dfc20089ccc5e20fcddfe",
     "a95c492a6d78b2499866fd915589b30b3896f1caf45090cc2f6a51039ab1171d",
     100, "3.61e-110",
     "-54.220859680444034970572531919020750667696059103971137033784505788679926360399336436227383866592420415576194696"),
    ("1", "T28_A.json",
     "e598ada0aae5ac552759400f5ad913a55298879ef9d488ad55ae417493a2a64e",
     "ac2846e89cef2ee4af9f6b79a0686481a33cc86b7c0ece5d98deb4515813f068",
     100, "1.16e-109",
     "-54.310965657571826122601360701438063188010432823195586470583635883096615617516659274208472425307202086838843886"),
    ("9/8", "T47_A.json",
     "2a6748611f3a4be73eadb8ddf4d517ab762e23e07331dc0b1ba2fa647cca344f",
     "b9c9350e151695c86e1de283b3f1cb51fd1a15ad2dd562cead969d38a7fe6782",
     100, "4.30e-109",
     "-54.356123711189223166858687884167122787105133198269497883510572793581803780225809347272216065340488056570995717"),
    ("5/4", "T51_A.json",
     "e66a43f6da79c9fbbdf5f2d299efd6c731bed0553ad54fd3b9b36b09ec47c086",
     "7c8d1d3f934023ef96fcf9b482d55021ecf2bc9c37d94dde23c7ea3b6a730f7d",
     100, "4.87e-109",
     "-54.401349152002508668645885653209157119691715452109088781210942103841184350135441950483897607980676416166496175"),
    ("3/2", "T06_B.json",
     "15d2943c75ba58502160bce4a2d5519e162454ccf1fa387b294b351539998489",
     "b2491069e832d5e794dd6c70045e99c65d52e2346838c0d34693eccf7106c8bc",
     130, "3.00e-139",
     "-54.491993614910506146723044630901010504397051332075936438622389385945679084210934872629555996263395048161490986991234979923675880187903756830"),
    ("7/4", "T50_A.json",
     "0d8cddab1f86d84cf1883f93a95cf5a8cefcc9b742e6dc6df3d89ab50cffdf61",
     "1b938bc04dddc06cf876fef11df7c01624128fe8a681271104037b809ba4bad8",
     100, "1.21e-109",
     "-54.582880790578540076588745889533563731696945894623970621258459670126948476248702213579715220610202038074280976"),
    ("2", "T29_A.json",
     "4d35220703ed36662b252a4272f7b165abb381279707e6b98837aea99c3c7bea",
     "6229a30901c4fe506bc82d10afb3e6c213256911dcd87adbd3c510e6e28c34ef",
     100, "1.44e-109",
     "-54.673990556351668821526555218897303452194690574853749485524624785545129056054834489261521064249277499704984744"),
    ("5/2", "T30_A.json",
     "b37c08cc57bf380984e3235a2b684990ba6dc5e0cbf2bb50d3a906afb95ea889",
     "2010b07214221c1547002fb24e028f4488f0aa239fe0abd0cf7755ee2f2886a8",
     100, "1.42e-109",
     "-54.856786952666018027527926904399962591725508455055536071187738197731335185956480409192716634376227633512275743"),
    ("11/4", "T48_A.json",
     "fa782b4f35ea2271880ca62529980b49d0ee450587adb1f4ce551d7d09491b53",
     "98973286821c691219616774cf65a24ba52506bd06e7a3f16e8e2a8ccb40473f",
     100, "1.15e-109",
     "-54.948422314405110924772856064622187716147367337093710319127816345993395498949466949098140770826193810786577933"),
    ("3", "T31_A.json",
     "f982fc0c97e2a25d4e0b5d9455ae0717b79b5b9aa432ebf5957c9f6956f949df",
     "3b82e6d32b35d1bd661aebd88e61342506406c331d851f2d53c747b366343218",
     100, "4.74e-109",
     "-55.040177270760194731697184036394714486548405630349275052205238514733939490242367657217637058185664895757247239"),
    ("13/4", "T32_A.json",
     "72e2d59a06ca0d37bcc7c0bc52613ee4aba9206fd391f1771c60e5f5b4b18ac8",
     "396d6648875d00dc6048fc39e90aa7005c1e2d68d61430baecdc8820e7f6ec80",
     100, "2.45e-109",
     "-55.132019296221991114256619652033598740961473280698014311723788703249073675904993493600163088902949336986159150"),
    ("7/2", "T07_B.json",
     "5ffa89b763ccbf2179da99055a0040c591fbf69fa13b65e675882af8ee5275a2",
     "25eea590525b3c01437dc814353e84b1eab2f7dd01a57ef465ae103bc5fab290",
     130, "1.26e-139",
     "-55.223912601741329540426856700102251358712234598197973972403200150557863567383074923656682774335737541401894440614460708874006272769546114367"),
]


def domb_coeffs(n_terms):
    """D_0=1; (n+1)^3 D_{n+1} = 2(2n+1)(5n^2+5n+2) D_n - 64 n^3 D_{n-1}."""
    D = [Fraction(1), Fraction(4)]
    for n in range(1, n_terms):
        D.append((2 * (2 * n + 1) * (5 * n * n + 5 * n + 2) * D[n]
                  - 64 * n ** 3 * D[n - 1]) / Fraction((n + 1) ** 3))
    return D


def part_coeffs(n_terms):
    """b_0=0, b_1=24; n^3 b_n = P(n) b_{n-1} - 64(n-1)^3 b_{n-2},
    P(n) = 2(2n-1)(5n^2-5n+2)  [Domb recursion shifted n -> n-1]."""
    b = [Fraction(0), Fraction(24)]
    for n in range(2, n_terms + 1):
        P = 2 * (2 * n - 1) * (5 * n * n - 5 * n + 2)
        b.append((P * b[n - 1] - 64 * (n - 1) ** 3 * b[n - 2]) / Fraction(n ** 3))
    return b


D = domb_coeffs(NTERMS)
B = part_coeffs(NTERMS)

# sanity: series heads (exact values from the recursions)
assert D[:5] == [1, 4, 28, 256, 2716]
assert B[:5] == [0, 24, 216, Fraction(18944, 9), Fraction(204440, 9)]


def nterms_for(t, dps):
    """Terms needed so the geometric tail (|t|/4)^n < 10^-(dps+GUARD)."""
    r = abs(float(t)) / 4
    if r >= 1:
        raise ValueError("domain is the MUM disk |t| < 4 (x = t/64, singularity at x = 1/16)")
    if r == 0:
        return 8
    return int(math.ceil((dps + GUARD) * math.log(10) / -math.log(r))) + 50


def ensure_nterms(n):
    """Extend the exact-rational coefficient caches to index n by EXACT
    continuation of the same recurrences (never recomputed differently)."""
    while len(D) < n + 1:
        m = len(D) - 1   # have D[0..m]; Domb recursion at index m gives D[m+1]
        D.append((2 * (2 * m + 1) * (5 * m * m + 5 * m + 2) * D[m]
                  - 64 * m ** 3 * D[m - 1]) / Fraction((m + 1) ** 3))
    while len(B) < n + 1:
        m = len(B)       # next b index
        P = 2 * (2 * m - 1) * (5 * m * m - 5 * m + 2)
        B.append((P * B[m - 1] - 64 * (m - 1) ** 3 * B[m - 2]) / Fraction(m ** 3))


def series(coeffs, x):
    s, xp = mp.mpf(0), mp.mpf(1)
    for c in coeffs:
        s += mp.mpf(c.numerator) / mp.mpf(c.denominator) * xp
        xp *= x
    return s


def _series_tail(coeffs, x, window=TAIL_WINDOW):
    """Sum the series exactly as series() does (bit-identical accumulation)
    and also return max |term| over the trailing `window` terms — the seed of
    the certified geometric tail bound."""
    s, xp = mp.mpf(0), mp.mpf(1)
    n = len(coeffs)
    tmax = mp.mpf(0)
    for i, c in enumerate(coeffs):
        term = mp.mpf(c.numerator) / mp.mpf(c.denominator) * xp
        s += term
        if i >= n - window:
            tmax = max(tmax, abs(term))
        xp *= x
    return s, tmax


def m1_eps0(t, dps=None, full_output=False):
    """m1 at eps^0 for t = p^2/m^2 in the MUM disk |t| < 4.

    t: Fraction / int / str (parsed exactly) or mpf/float.
    dps: target decimal precision (None = current mp.dps).  The closed-form
    term count nterms_for(t, dps) is a STARTING seed only: the result is
    accepted only when the certified trailing-window tail bound (see module
    CHANGELOG) beats 10^-(dps+TAIL_GUARD); otherwise the series is extended
    (x1.5, EXACT continuation of the same recurrences) up to TAIL_NCAP*seed,
    where a RuntimeError is raised (fail-closed) — a value the loop did not
    certify is never returned.  Result carries dps+GUARD working digits.
    full_output=True returns (value, certified tail bound, accepted N).
    """
    if dps is None:
        dps = mp.dps
    if isinstance(t, (int, str)):
        t = Fraction(t)
    n0 = nterms_for(t, dps)   # STARTING seed (speed, never the answer)
    ncap = TAIL_NCAP * n0
    n = n0
    with mp.workdps(dps + GUARD):
        if isinstance(t, Fraction):  # mpmath 1.3.0 cannot mpf() a Fraction
            tm = mp.mpf(t.numerator) / mp.mpf(t.denominator)
        else:
            tm = mp.mpf(t)
        x = tm / 64
        r = abs(tm) / 4   # certified term ratio: |c_{k+1}/c_k| < 16 => 16|x|
        tol = mp.mpf(10) ** (-(dps + TAIL_GUARD))
        while True:
            ensure_nterms(n)
            sD, tD = _series_tail(D[:n + 1], x)
            sB, tB = _series_tail(B[:n + 1], x)
            val = 7 * zeta(3) * sD - sB
            # value-level tail bound: l1-norm of the exact prefactors (7*zeta3, 1)
            bound = (7 * zeta(3) * tD + tB) * r / (1 - r)
            if bound < tol:
                break
            if n >= ncap:
                raise RuntimeError(
                    "banana tail gate FAILED (fail-closed): certified "
                    "trailing-%d-window tail bound %s >= tol %s at t=%s, "
                    "dps=%d, N=%d (seed %d, cap %d); |t| -> 4 needs analytic "
                    "continuation — never returning an uncertified value"
                    % (TAIL_WINDOW, mp.nstr(bound, 3), mp.nstr(tol, 3),
                       t, dps, n, n0, ncap))
            n = min(ncap, max(n + TAIL_WINDOW, int(math.ceil(TAIL_GROW * n))))
        if full_output:
            return val, bound, n
        return val


def _raise_gate(name, measured_d, threshold_d, detail=""):
    """Raising gate on an agreement measured in digits (fail-closed)."""
    if not (measured_d >= threshold_d):
        raise RuntimeError(
            "banana RAISING gate FAILED (fail-closed): %s = %.2f d < "
            "threshold %.2f d%s" % (name, measured_d, threshold_d,
                                    " (%s)" % detail if detail else ""))


def agree_digits(a, ref_str):
    r = mpf(ref_str)
    d = fabs(a - r)
    return mp.inf if d == 0 else float(-log10(d / fabs(r)))


def printed_agreement(d, nref, dps):
    """The agreement figure as printed: min(measured d, string digits, dps + GUARD), with the active cap
    named.  The measured d is inf when the value and the parsed string coincide at the working precision
    dps + GUARD (e.g. --dps 30 at t = -3), so the print is capped by the working precision as well as by
    the string; the gate bar min(dps, nref) - REF_MARGIN is dps-aware on its own."""
    cap_str, cap_work = float(nref), float(dps + GUARD)
    cap = min(cap_str, cap_work)
    which = ("the %d-digit string" % nref) if cap_str <= cap_work else ("the working precision dps+%d = %d" % (GUARD, dps + GUARD))
    return min(float(d), cap), cap, which


def _fmt_d(d):
    """A measured agreement for the [gate] lines: the raw figure, or 'inf (exact at the working precision)'."""
    return "inf (exact at the working precision)" if d == mp.inf else "%.1f" % float(d)


def _flip_digit(literal, k):
    """Significant digit k (1-based) of a decimal string incremented mod 10 (the --mutate-heldout18 plant)."""
    pos = [i for i, ch in enumerate(literal) if ch.isdigit()]
    first = next(i for i in pos if literal[i] != "0")
    pos = [i for i in pos if i >= first]
    if not 1 <= k <= len(pos):
        raise ValueError("digit %d is outside the %d significant digits of the string" % (k, len(pos)))
    i = pos[k - 1]
    new = str((int(literal[i]) + 1) % 10)
    return literal[:i] + new + literal[i + 1:], literal[i], new


def heldout18_gate(dps, mutate=None):
    """--heldout18: the closed form at every point of the 18-point record, each gated against its stored
    string with the rule of the default demo (bar min(dps, string digits) - REF_MARGIN on the measured
    agreement; printed figure min(measured, string digits, dps + GUARD), the cap named only when the figure sits at it).
    mutate =
    (t, k): significant digit k of that point's stored string incremented mod 10 IN MEMORY before the
    comparison (the shipped control; the table itself is untouched).  Prints one row per point and a
    VERDICT line; a FAIL is raised by name after the table (rc 1)."""
    import time
    t0 = time.perf_counter()
    plant = None
    if mutate is not None:
        tm, k = mutate
        row = next((r for r in HELDOUT18 if r[0] == tm or r[1].split("_")[0] == tm), None)
        if row is None:
            raise ValueError("--mutate-heldout18: no record point %r (give t as in the table, e.g. -3, 1/2, or its label, e.g. T02)" % tm)
        planted, was, now = _flip_digit(row[7], k)
        plant = (row[0], k, was, now, planted)
        print("[control] --mutate-heldout18: significant digit %d of the t = %s stored string %s -> %s (in memory; the table is untouched)"
              % (k, row[0], was, now))
    print("-- the 18 points of the record vs their stored strings (dps %d) --" % dps)
    print("%-6s | %-10s | %-13s | %-12s | %-32s | %-28s | %-7s | %s" % ("t", "source", "record digits", "record d@120", "this work (30 d)", "agreement d (cap when at it)", "bar d", "verdict"))
    fails, shown_min, rows_out = [], None, 0
    for t, srcname, _osha, _csha, _goal, _rad, rec_d, ref in HELDOUT18:
        if plant is not None and t == plant[0]:
            ref = plant[4]
        nref = sum(c.isdigit() for c in ref)
        val, bound, nacc = m1_eps0(Fraction(t), dps=dps, full_output=True)
        with mp.workdps(dps + GUARD):
            d = agree_digits(val, ref)
        shown, cap, which = printed_agreement(d, nref, dps)
        thr = min(dps, nref) - REF_MARGIN
        ok = float(d) >= thr
        if not ok:
            fails.append((t, float(d), thr))
        if shown_min is None or shown < shown_min[0]:
            shown_min = (shown, t)
        print("%-6s | %-10s | %-13d | %-12s | %-32s | %-28s | %-7.1f | %s" % (
            t, srcname, nref, rec_d, mp.nstr(val, 30),
            ("%.1f (%s)" % (shown, "string" if which.endswith("string") else "dps+%d" % GUARD)) if shown == cap else "%.1f" % shown, thr,
            "PASS" if ok else "FAIL (%.1f d < %.1f d)" % (float(d), thr)))
        rows_out += 1
    # the three default-demo references are rows of this table (byte-equal), a gate of its own
    eq = sum(1 for t, (ref, _fig) in REFS.items() if any(r[0] == t and r[7] == ref for r in HELDOUT18))
    print("REFS entries vs the table: %d/3 byte-equal" % eq)
    wall = time.perf_counter() - t0
    if fails or eq != 3:
        names = "; ".join("t = %s (%.1f d < %.1f d)" % f for f in fails)
        if eq != 3:
            names = (names + "; " if names else "") + "REFS entries vs the table %d/3" % eq
        print("VERDICT --heldout18 (dps %d): FAIL at %s -- %d/%d PASS" % (dps, names, rows_out - len(fails), rows_out))
        print("--heldout18 wall time: %.2f s" % wall)
        raise RuntimeError("banana RAISING gate FAILED (fail-closed): --heldout18 record gate at " + names)
    print("VERDICT --heldout18 (dps %d): %d/%d PASS; minimum printed agreement %.1f d at t = %s; bars %.1f d (110-digit strings) / %.1f d (140-digit strings)"
          % (dps, rows_out, rows_out, shown_min[0], shown_min[1], min(dps, 110) - REF_MARGIN, min(dps, 140) - REF_MARGIN))
    print("--heldout18 wall time: %.2f s" % wall)


# ---------------------------------------------------------------------------
# --continue: the closed form past the disk (|t| >= 4), t -> t + i0   (2026-09-06; every unit below is new)
#
# The closed form above is the eps^0 layer of the top master m1 of the raw four-master system of the banana,
#     d/dt m = A(eps, t) m,   m = (m0, m1, m2, m3),   A = A0(t) + eps A1(t),   denominator t (t - 4)(t - 16),
# with m0 = BAN[1,1,1,0] (t-independent, = -Gamma(eps)^3), m1 = BAN[1,1,1,1] (the top), m2 = BAN[1,1,1,1,-2] and
# m3 = BAN[1,1,1,1,0,0,0,-2] (the two dotted masters).  Grading every master in eps, m_j = sum_K eps^K f_{j,K}(t) with
# K = -3..1, the layers obey ONE eps-free linear system y' = M(t) y on the 20 components (j, K): f_{i,K}' =
# sum_j [A0_ij f_{j,K} + A1_ij f_{j,K-1}].  M is read from banana-graded-system.json (exact rationals, 108 entries,
# sha256-pinned in CONT_PINS).  Past the disk the eps^0 layer of m1 is that system's solution continued along a path in
# the upper half t-plane (the Feynman t -> t + i0):
#   * the base state at t = 2: m0 from the exact Gamma tower; m1[eps^0] from the closed form ABOVE (m1_eps0, the same
#     code path as every Euclidean tier); the dotted towers and the eps^1 layer from the holomorphic recursion of the same
#     system at the MUM point t = 0 (the 64 n c_n = N_0 c_n + ... recurrence below), whose free constants are the values
#     m1[eps^K](0) = (0, 0, 0, 7 zeta_3, alpha_1) -- alpha_1 the Bessel-moment constant CONT_ALPHA1; the recursion's own
#     m1[eps^0](2) is gated against the closed form (RAISING);
#   * a fixed-eps Taylor march of y' = M y along [2, 2 + 2i, t + 2i, t]: each step's Taylor coefficients come from the
#     exact recurrence of D(t) y' = N(t) y shifted to the step point (the step a_{n+1} = (n+1)^-1 sum_k M_k a_{n-k} taken
#     through the polynomial denominator, no Cauchy product), the step length CONT_STEP_FRAC x the distance to the nearest
#     singular point (0, 4, 16), and every step's Taylor tail certified by the zero-run-aware geometric bound
#     (t_a + t_b)/(1 - r), r = (t_b/t_a)^(1/gap) clamped at 3/4 over the last two above-floor term magnitudes, against
#     10^-(dps + TAIL_GUARD) ||y||; a step that does not clear is halved (to CONT_MIN_STEP_FRAC, then RAISES);
#   * route independence: the same march at height 3 (agreement printed, RAISING at dps - REF_MARGIN); the Schwarz control:
#     the lower detour (t - i0) must be the complex conjugate (printed, RAISING); m1's negative orders, identically zero,
#     printed as structural zeros (RAISING);
#   * at a gate point of banana-minkowski-gates.json (the record's t = -8, 5, 8, 12, 31/2 real and 18, 25, 40, 100, 200
#     complex, goal-100 / goal-130 pairs; the fresh t = 10, 20 goal-60 / goal-40 pairs, predicted before they were run)
#     every transported component is gated against its stored strings, Re and Im separately, bar min(dps, string digits)
#     - REF_MARGIN (the eps^1 layer additionally capped by the CONT_ALPHA1_DIGITS digits of alpha_1; a fresh point at the
#     floor of its goal-60 / goal-40 pair), FAIL by name (exit 1).  --mutate and --lower-as-physical are the controls.
# Nothing here changes the units above: the disk tiers are byte-for-byte the previous release.
# ---------------------------------------------------------------------------

CONT_PINS = {   # sha256 of the two data files beside this script (exit 3 on a mismatch, exit 4 when missing)
    "banana-graded-system.json": "28ac51082184365034923973be72d18173a31ba3dbe40f4646ec9c783d95f541",
    "banana-minkowski-gates.json": "8c384e630067d5e975bc90527136aa1ecb214cc3e42f908193d76789bbae73e0",
}
CONT_T_BASE = Fraction(2)                       # the base point inside the disk (the record's t = 2 point)
CONT_HEIGHTS = (Fraction(2), Fraction(3))         # the detour height of record and the second route
CONT_SINGULAR = (Fraction(0), Fraction(4), Fraction(16))
CONT_STEP_FRAC = Fraction(1, 2)                   # step = this fraction of the distance to the nearest singular point
CONT_MIN_STEP_FRAC = Fraction(1, 64)              # below this a step RAISES (a singular point on the path)
CONT_WORK_GUARD = 30                              # working digits above dps (the base-point recursion and the march)
CONT_ORDER_CAP = 12                               # Taylor order cap per step = CONT_ORDER_CAP x (dps + TAIL_GUARD)
CONT_ZERO_MARGIN = 10                             # structural zeros: |value| <= 10^-(dps - CONT_ZERO_MARGIN)
CONT_MUTATE_DIGIT = 30                            # --mutate: this significant digit of the gate point's m1[eps^0] string
# alpha_1 = m1[eps^1](t = 0) = B[eps^1] with B(eps) = 2^(3-2eps)/Gamma(1-eps) int_0^oo r^(1+2eps) K_eps(r)^4 dr, i.e.
# 16 int r ln r K_0(r)^4 dr - 7 zeta_3 (2 ln 2 + gamma_E): the Bessel-moment constant of the record (110 significant
# digits, its dps-110 quadrature leg; a one-point fit of alpha_1 from the 140-digit t = -3 record string returns this
# string to 110.0 d).  It fixes the eps^1 layer only; the eps^0 layer and below never use it.
CONT_ALPHA1 = "-53.952349689863762575572488542945775595371575666622896095876615523574054404035302602860001756911473937218573515"
CONT_ALPHA1_DIGITS = 110


def _cont_check_pins(here):
    """Every data file present and sha256-equal to CONT_PINS before anything is computed: exit 4 (missing) / 3 (mismatch), by name."""
    import hashlib
    import os
    import sys
    for name, want in CONT_PINS.items():
        p = os.path.join(here, name)
        if not os.path.isfile(p):
            print("MISSING data file %s (expected beside the script, sha256 %s...): exit 4" % (name, want[:16]))
            sys.exit(4)
        got = hashlib.sha256(open(p, "rb").read()).hexdigest()
        if got != want:
            print("PIN MISMATCH %s: sha256 %s... != pinned %s...: exit 3" % (name, got[:16], want[:16]))
            sys.exit(3)
        print("[pins] %s sha256 %s... OK" % (name, got[:16]))


def _cont_load_system(path):
    """banana-graded-system.json -> (state, num): state = the 20 (master, eps-order) pairs in order, num[(row, col)] = the
    numerator polynomial [c_0..c_4] (exact Fractions) of the entry over the common denominator D(t) = t^3 - 20 t^2 + 64 t."""
    import json
    J = json.load(open(path))
    state = [tuple(s) for s in J["provenance"]["state_order"]]
    if not (J["NC"] == len(state) == 20 and len(J["A_t"]) == 108):
        raise RuntimeError("banana-graded-system.json: unexpected shape (NC %s, %d entries)" % (J["NC"], len(J["A_t"])))
    num = {}
    for key, ent in J["A_t"].items():
        r, c = (int(x) for x in key.split(","))
        den = [(d[0], d[1], Fraction(d[2])) for d in ent["den"]]
        if den != [(0, 3, Fraction(1)), (0, 2, Fraction(-20)), (0, 1, Fraction(64))]:
            raise RuntimeError("banana-graded-system.json: entry %s has a denominator other than t^3 - 20 t^2 + 64 t" % key)
        poly = [Fraction(0)] * 5
        for ke, kt, p in ent["num"]:
            if ke != 0 or not 0 <= kt <= 4:
                raise RuntimeError("banana-graded-system.json: entry %s carries eps or t^%d in its numerator" % (key, kt))
            poly[kt] += Fraction(p)
        num[(r, c)] = poly
    return state, num


def _cont_split_eps(state, num):
    """The 4 x 4 numerator matrices N^(0)_j, N^(1)_j (j = 0..4, the t^j coefficients) of A0 and A1 read off the graded
    entries: (i, K) <- (j, K) carries A0_ij, (i, K) <- (j, K - 1) carries A1_ij; asserted equal across K."""
    N0 = [[[Fraction(0)] * 4 for _ in range(4)] for _ in range(5)]
    N1 = [[[Fraction(0)] * 4 for _ in range(4)] for _ in range(5)]
    seen = {0: {}, 1: {}}
    for (r, c), poly in num.items():
        (i, K), (j, Kp) = state[r], state[c]
        e = 0 if Kp == K else (1 if Kp == K - 1 else None)
        if e is None:
            raise RuntimeError("banana-graded-system.json: entry (%d,%d) couples eps orders %d <- %d" % (r, c, K, Kp))
        if (i, j) in seen[e]:
            if seen[e][(i, j)] != poly:
                raise RuntimeError("banana-graded-system.json: A%d_%d%d differs between eps layers" % (e, i, j))
        else:
            seen[e][(i, j)] = poly
            for jj in range(5):
                (N0 if e == 0 else N1)[jj][i][j] = poly[jj]
    return N0, N1


def _cont_m0_tower(kmax):
    """m0 = BAN[1,1,1,0] = -Gamma(eps)^3, t-independent: {K: the eps^K coefficient}, K = -3..kmax, at the working precision
    (log Gamma(1 + eps) = -gamma_E eps + sum_{j>=2} (-1)^j zeta(j)/j eps^j, exponentiated as a power series)."""
    L = kmax + 4
    lg = [mp.mpf(0)] * (L + 1)
    lg[1] = -3 * mp.euler
    for j in range(2, L + 1):
        lg[j] = 3 * (-1) ** j * zeta(j) / j
    ex = [mp.mpf(0)] * (L + 1)
    ex[0] = mp.mpf(1)
    for n in range(1, L + 1):
        s = mp.mpf(0)
        for j in range(1, n + 1):
            s += j * lg[j] * ex[n - j]
        ex[n] = s / n
    return {K: -ex[K + 3] for K in range(-3, kmax + 1)}


def _cont_fr_solve(M, b):
    """Exact Gauss-Jordan solve of the square Fraction system M x = b (raises when singular)."""
    n = len(M)
    A = [list(M[i]) + [b[i]] for i in range(n)]
    for col in range(n):
        piv = next((r for r in range(col, n) if A[r][col] != 0), None)
        if piv is None:
            raise RuntimeError("singular exact system in the base-point recursion")
        A[col], A[piv] = A[piv], A[col]
        p = A[col][col]
        A[col] = [v / p for v in A[col]]
        for r in range(n):
            if r != col and A[r][col] != 0:
                f = A[r][col]
                A[r] = [vr - f * vc for vr, vc in zip(A[r], A[col])]
    return [A[i][n] for i in range(n)]


def _cont_fr_rank_rows(M):
    """Indices of a maximal set of linearly independent rows of the Fraction matrix M (greedy exact elimination)."""
    rows, basis = [], []
    for i, row in enumerate(M):
        v = list(row)
        for (pcol, brow) in basis:
            if v[pcol] != 0:
                f = v[pcol] / brow[pcol]
                v = [a - f * b for a, b in zip(v, brow)]
        pc = next((c for c in range(len(v)) if v[c] != 0), None)
        if pc is not None:
            basis.append((pc, v))
            rows.append(i)
    return rows


def _cont_base_series(N0, N1, t, dps, alpha, m0):
    """The holomorphic MUM solution m(t) = sum_n c_n t^n of D m' = N m, eps-graded (K = -3..1), summed at |t| < 4 with its
    boundary data fixed at t = 0: m0[K] = the Gamma tower, m1[K](0) = alpha[K].  Recurrence (the t^n coefficient of
    D = t^3 - 20 t^2 + 64 t against N = sum_j N_j t^j, N = N^(0) + eps N^(1)):
        (64 n I - N^(0)_0) c_{n,K} = N^(1)_0 c_{n,K-1} + sum_{j=1..4} (N^(0)_j c_{n-j,K} + N^(1)_j c_{n-j,K-1})
                                     + 20 (n - 1) c_{n-1,K} - (n - 2) c_{n-2,K};
    at n = 0 the matrix -N^(0)_0 has rank 2 (the MUM point: N^(0)_0 nilpotent), the two free directions are the constant
    master m0 and the MUM constant m1(0) = alpha, the remaining equations must be consistent (checked); at n >= 1 the
    inverse is the finite Neumann series of the nilpotent N^(0)_0.  Returns ({(i,K): value}, certified tail bound, n_used):
    the tail = max |term| over the trailing TAIL_WINDOW terms x r/(1 - r), r = |t|/4, accepted below 10^-(dps + TAIL_GUARD)."""
    Ks = list(range(-3, 2))
    tm = mp.mpf(t.numerator) / t.denominator
    r = abs(tm) / 4
    tol = mp.mpf(10) ** (-(dps + TAIL_GUARD))
    M00 = [[-N0[0][i][j] for j in range(4)] for i in range(4)]
    P = M00
    for _ in range(3):
        P = [[sum(P[i][k] * M00[k][j] for k in range(4)) for j in range(4)] for i in range(4)]
    if any(v != 0 for row in P for v in row):
        raise RuntimeError("base-point recursion: N^(0)_0 is not nilpotent (the MUM structure of record fails)")
    ind = _cont_fr_rank_rows(M00)
    if len(ind) != 2:
        raise RuntimeError("base-point recursion: rank of N^(0)_0 at t = 0 is %d, not 2" % len(ind))
    S = [[Fraction(1), Fraction(0), Fraction(0), Fraction(0)], [Fraction(0), Fraction(1), Fraction(0), Fraction(0)]] + [M00[i] for i in ind]
    Sinv_cols = [_cont_fr_solve(S, [Fraction(1 if k == m else 0) for k in range(4)]) for m in range(4)]
    Sinv = [[mp.mpf(Sinv_cols[m][i].numerator) / Sinv_cols[m][i].denominator for m in range(4)] for i in range(4)]
    N0f = [[[mp.mpf(N0[j][i][k].numerator) / N0[j][i][k].denominator for k in range(4)] for i in range(4)] for j in range(5)]
    N1f = [[[mp.mpf(N1[j][i][k].numerator) / N1[j][i][k].denominator for k in range(4)] for i in range(4)] for j in range(5)]
    M00f = [[mp.mpf(M00[i][k].numerator) / M00[i][k].denominator for k in range(4)] for i in range(4)]
    Npow = [[[Fraction(1 if i == k else 0) for k in range(4)] for i in range(4)]]
    for _ in range(3):
        Npow.append([[sum(Npow[-1][i][k] * N0[0][k][j] for k in range(4)) for j in range(4)] for i in range(4)])
    Npowf = [[[mp.mpf(Q[i][k].numerator) / Q[i][k].denominator for k in range(4)] for i in range(4)] for Q in Npow]

    def mv(Mf, v):
        return [Mf[i][0] * v[0] + Mf[i][1] * v[1] + Mf[i][2] * v[2] + Mf[i][3] * v[3] for i in range(4)]

    hist = {K: [] for K in Ks}          # c_{n,K}, most recent last (at most 5 kept)
    acc = {K: [mp.mpf(0)] * 4 for K in Ks}
    win = {K: [] for K in Ks}
    tpow = mp.mpf(1)
    ncap = CONT_ORDER_CAP * (dps + TAIL_GUARD)
    scale_chk = mp.mpf(10) ** (-(mp.dps - 10))
    n_used = None
    for n in range(0, ncap + 1):
        new = {}
        for K in Ks:
            def get(nn, KK):
                if nn < 0 or KK < -3:
                    return None
                if nn == n:
                    return new.get(KK)
                h = hist[KK]
                k = len(h) - (n - nn)
                return h[k] if 0 <= k < len(h) else None
            rhs = [mp.mpf(0)] * 4
            v = get(n, K - 1)
            if v is not None:
                rhs = [a + b for a, b in zip(rhs, mv(N1f[0], v))]
            for j in range(1, 5):
                v = get(n - j, K)
                if v is not None:
                    rhs = [a + b for a, b in zip(rhs, mv(N0f[j], v))]
                v = get(n - j, K - 1)
                if v is not None:
                    rhs = [a + b for a, b in zip(rhs, mv(N1f[j], v))]
            v = get(n - 1, K)
            if v is not None:
                rhs = [a + 20 * (n - 1) * b for a, b in zip(rhs, v)]
            v = get(n - 2, K)
            if v is not None:
                rhs = [a - (n - 2) * b for a, b in zip(rhs, v)]
            if n == 0:
                sel = [m0[K], alpha[K], rhs[ind[0]], rhs[ind[1]]]
                c = mv(Sinv, sel)
                chk = mv(M00f, c)
                sc = max([abs(x) for x in rhs] + [mp.mpf(1)])
                for i in range(4):
                    if abs(chk[i] - rhs[i]) > scale_chk * sc:
                        raise RuntimeError("base-point recursion: the n = 0 consistency condition fails on row %d at eps^%d "
                                           "(residual %s)" % (i, K, mp.nstr(abs(chk[i] - rhs[i]), 5)))
            else:
                c = [mp.mpf(0)] * 4
                f = mp.mpf(1) / (64 * n)
                for p in range(4):
                    w = mv(Npowf[p], rhs)
                    c = [a + f * b for a, b in zip(c, w)]
                    f = f / (64 * n)
            new[K] = c
        for K in Ks:
            hist[K].append(new[K])
            if len(hist[K]) > 5:
                hist[K].pop(0)
            term = [x * tpow for x in new[K]]
            acc[K] = [a + b for a, b in zip(acc[K], term)]
            win[K].append(max(abs(x) for x in term))
            if len(win[K]) > TAIL_WINDOW:
                win[K].pop(0)
        tpow *= tm
        if n >= 4 * TAIL_WINDOW:
            worst = max(max(w) for w in win.values()) * r / (1 - r)
            if worst < tol:
                n_used = n
                break
    if n_used is None:
        raise RuntimeError("base-point recursion: certified tail bound not reached within %d terms at t = %s (fail-closed)" % (ncap, t))
    vals = {(i, K): acc[K][i] for K in Ks for i in range(4)}
    return vals, worst, n_used


def _cont_step(numf, state, y, z0, h, dps, wp):
    """One Taylor step of y' = M y from z0 over h (complex): the exact recurrence of D(z0 + s) y' = N(z0 + s) y in the
    scaled coefficients b_n = a_n h^n,
        b_{n+1} = [ sum_{j=0..4} (N_j h^(j+1)) b_{n-j} - sum_{m=1..3} (d_m h^m)(n + 1 - m) b_{n+1-m} ] / (d_0 (n + 1)),
    N_j, d_m the Taylor coefficients of the numerator matrix and of D about z0; summed until the zero-run-aware geometric
    tail bound clears 10^-(dps + TAIL_GUARD) ||y||_inf (the record's rule: (t_a + t_b)/(1 - r), r = (t_b/t_a)^(1/gap)
    clamped at 3/4 over the last two above-floor term magnitudes; the pair must be fresh; a trailing roundoff run never
    accepts).  Returns (y(z0 + h), bound, order) or (None, bound, order) when the cap is hit without clearing."""
    NS = len(state)
    zp = [mp.mpc(1)]
    for _ in range(4):
        zp.append(zp[-1] * z0)
    binom = ((1,), (1, 1), (1, 2, 1), (1, 3, 3, 1), (1, 4, 6, 4, 1))
    hp = [mp.mpc(1)]
    for _ in range(5):
        hp.append(hp[-1] * h)
    Nj = [{} for _ in range(5)]
    for (rc, poly) in numf:
        for m in range(5):
            s = mp.mpc(0)
            for k in range(m, 5):
                if poly[k] != 0:
                    s += poly[k] * binom[k][m] * zp[k - m]
            if s != 0:
                Nj[m][rc] = s * hp[m + 1]
    d0 = zp[3] - 20 * zp[2] + 64 * z0
    dm = [None, (3 * zp[2] - 40 * z0 + 64) * hp[1], (3 * z0 - 20) * hp[2], hp[3]]
    inv_d0 = 1 / d0
    ynorm = max(abs(v) for v in y)
    tiny = mp.mpf(10) ** (-(4 * wp))
    thresh = mp.mpf(10) ** (-(dps + TAIL_GUARD)) * max(ynorm, tiny)
    flr_rel = mp.mpf(10) ** (-(wp - 10))
    bs = [list(y)]
    tmag = [ynorm]
    tmax_run = ynorm
    nz_prev, nz_last, gap_max = None, (0, ynorm), 0
    bound = None
    cap = CONT_ORDER_CAP * (dps + TAIL_GUARD)
    for n in range(cap):
        nxt = [mp.mpc(0)] * NS
        for j in range(min(n, 4) + 1):
            v = bs[n - j]
            for (r, c), coef in Nj[j].items():
                if v[c] != 0:
                    nxt[r] += coef * v[c]
        for m in range(1, 4):
            if n + 1 - m >= 0:
                f = dm[m] * (n + 1 - m)
                v = bs[n + 1 - m]
                for i in range(NS):
                    if v[i] != 0:
                        nxt[i] -= f * v[i]
        f = inv_d0 / (n + 1)
        nxt = [v * f for v in nxt]
        bs.append(nxt)
        idx = n + 1
        tm = max(abs(v) for v in nxt)
        tmag.append(tm)
        if tm > tmax_run:
            tmax_run = tm
        if tm > flr_rel * tmax_run:
            g = idx - nz_last[0]
            if g > gap_max:
                gap_max = g
            nz_prev = nz_last
            nz_last = (idx, tm)
        if n > 8 and nz_prev is not None and idx - nz_last[0] < gap_max:
            ta, tb, gap = nz_prev[1], nz_last[1], nz_last[0] - nz_prev[0]
            rm = (tb / ta) ** (mp.mpf(1) / gap)
            if rm > mp.mpf(3) / 4:
                rm = mp.mpf(3) / 4
            b_early = (ta + tb) / (1 - rm)
            if b_early < thresh:
                bound = b_early
                break
    if bound is None:
        if nz_prev is not None and cap - nz_last[0] <= gap_max:
            ta, tb, gap = nz_prev[1], nz_last[1], nz_last[0] - nz_prev[0]
            rm = min(mp.mpf(3) / 4, (tb / ta) ** (mp.mpf(1) / gap))
            bound = (ta + tb) / (1 - rm)
        else:
            tp, tl = tmag[-2], tmag[-1]
            rm = min(mp.mpf(3) / 4, tl / tp) if tp > 0 else mp.mpf(1) / 2
            bound = mp.mpf(0) if (tp == 0 and tl == 0) else (tl + tp) / (1 - rm)
    if bound >= thresh:
        return None, bound, len(bs) - 1
    ynew = [mp.mpc(0)] * NS
    for b in bs:
        for i in range(NS):
            if b[i] != 0:
                ynew[i] += b[i]
    return ynew, bound / max(ynorm, tiny), len(bs) - 1


def _cont_march(numf, state, y0, waypoints, dps, wp):
    """The fixed-eps Taylor march of y' = M y through the straight legs of `waypoints` (complex): the step |h| =
    CONT_STEP_FRAC x the distance to the nearest singular point (halved on a failed tail bound, doubled back after a
    success, never below CONT_MIN_STEP_FRAC).  Returns (y, diag) with diag = {steps, trunc_worst (the worst certified
    per-step relative tail bound), min_hfrac, max_order}."""
    y = list(y0)
    sings = [mp.mpc(mp.mpf(s.numerator) / s.denominator) for s in CONT_SINGULAR]
    diag = {"steps": 0, "trunc_worst": mp.mpf(0), "min_hfrac": mp.mpf(1), "max_order": 0, "legs": []}
    for za, zb in zip(waypoints[:-1], waypoints[1:]):
        z = mp.mpc(za)
        zb = mp.mpc(zb)
        hfrac = mp.mpf(CONT_STEP_FRAC.numerator) / CONT_STEP_FRAC.denominator
        leg_steps = 0
        while True:
            rem = abs(zb - z)
            if rem == 0:
                break
            unit = (zb - z) / rem
            dsing = min(abs(z - s) for s in sings)
            hmag = hfrac * dsing
            if hmag >= rem:
                hmag = rem
            h = hmag * unit
            ynew, bound, order = _cont_step(numf, state, y, z, h, dps, wp)
            if ynew is None:
                hfrac = hfrac / 2
                if hfrac < mp.mpf(CONT_MIN_STEP_FRAC.numerator) / CONT_MIN_STEP_FRAC.denominator:
                    raise RuntimeError("continuation step at t = %s cannot certify its Taylor tail even at step fraction < 1/64 "
                                       "(bound %s): a singular point on or next to the path -- never returning an uncertified value"
                                       % (mp.nstr(z, 8), mp.nstr(bound, 3)))
                continue
            y = ynew
            z = z + h
            if bound > diag["trunc_worst"]:
                diag["trunc_worst"] = bound
            if hfrac < diag["min_hfrac"]:
                diag["min_hfrac"] = hfrac
            if order > diag["max_order"]:
                diag["max_order"] = order
            hfrac = min(mp.mpf(CONT_STEP_FRAC.numerator) / CONT_STEP_FRAC.denominator, hfrac * 2)
            leg_steps += 1
            diag["steps"] += 1
            if diag["steps"] > 4000:
                raise RuntimeError("continuation: more than 4000 steps on the path -- a singular point next to the path")
        diag["legs"].append(leg_steps)
    return y, diag


def _cont_digits_cc(a, b):
    """Digits of agreement of two complex values relative to max(|a|, |b|, 1) (structural zeros absolutely); None = identical."""
    d = abs(a - b)
    if d == 0:
        return None
    return float(-log10(d / max(abs(a), abs(b), mp.mpf(1))))


def _cont_floor(dm):
    """(floor digits, member, identical members) over a {member: digits-or-None} map."""
    vals = [(d, k) for k, d in dm.items() if d is not None]
    ident = sorted(k for k, d in dm.items() if d is None)
    if not vals:
        return None, None, ident
    fl = min(vals)
    return fl[0], fl[1], ident


def _cont_agree(v, re_s, im_s, nd):
    """Re and Im agreement of the complex value v with the stored strings, each relative to |reference| (1 when it is 0);
    a difference below the string's print resolution 10^-nd |ref| is 'identical at nd'.  Returns [(digits, identical)] x 2."""
    ref = mp.mpc(mpf(re_s), mpf(im_s))
    scale = abs(ref) if abs(ref) != 0 else mp.mpf(1)
    out = []
    for d in (abs(v.real - ref.real), abs(v.imag - ref.imag)):
        if d == 0 or d < mp.mpf(10) ** (-nd) * scale:
            out.append((float(nd), True))
        else:
            out.append((float(-log10(d / scale)), False))
    return out


def _cont_fmt_agree(d, ident, nd):
    return ("identical (%d)" % nd) if ident else "%.1f" % min(d, float(nd))


def _cont_pair_floor(legA, legB):
    """The two-leg pair floor over every order both legs carry (digits relative to |leg A|, identical -> the shorter string)."""
    dm = {}
    for mn, MA in legA["masters"].items():
        MB = legB["masters"].get(mn)
        if MB is None:
            continue
        for ks, va in MA["orders"].items():
            vb = MB["orders"].get(ks)
            if vb is None:
                continue
            a = mp.mpc(mpf(va["re"]), mpf(va["im"]))
            b = mp.mpc(mpf(vb["re"]), mpf(vb["im"]))
            scale = abs(a) if abs(a) != 0 else mp.mpf(1)
            d = abs(a - b)
            dm["(%s,%s)" % (mn[1], ks)] = float(min(va["re_digits"], vb["re_digits"])) if d == 0 else float(-log10(d / scale))
    fl = min(dm.values())
    return fl, min(dm, key=dm.get), len(dm)


def _cont_gate_leg(y, idx, leg, dps, label, mutate=None):
    """Every transported component (i, K) with a stored string in `leg` gated Re and Im separately: bar min(dps, string
    digits) - REF_MARGIN (the eps^1 layer also capped by CONT_ALPHA1_DIGITS; a fresh leg at its pair bar, passed in as
    leg['_bar']).  mutate = the planted string of (1,0) re (the --mutate control).  Prints the table; returns (fails, floors)."""
    rows, fails = [], []
    dre, dim = {}, {}
    print("  %-7s | %-32s | %-32s | %-16s | %-16s | %-5s | %s" % ("(i,K)", "this work re (30 d)", "this work im (30 d)", "re agreement", "im agreement", "bar", "verdict"))
    for (i, K), n in idx.items():
        mn = "m%d" % i
        o = leg["masters"].get(mn, {}).get("orders", {}).get(str(K))
        if o is None:
            continue
        re_s, im_s = o["re"], o["im"]
        if mutate is not None and (i, K) == (1, 0):
            re_s = mutate
        nd = min(o["re_digits"], dps)
        (dr, ir), (di, ii) = _cont_agree(y[n], re_s, im_s, nd)
        bar = leg.get("_bar")
        if bar is None:
            bar = min(dps, o["re_digits"]) - REF_MARGIN
            if K == 1:
                bar = min(bar, CONT_ALPHA1_DIGITS - REF_MARGIN)
        ok = dr >= bar and di >= bar
        key = "(%d,%d)" % (i, K)
        dre[key] = None if ir else dr
        dim[key] = None if ii else di
        if not ok:
            fails.append((key, dr, di, bar))
        print("  %-7s | %-32s | %-32s | %-16s | %-16s | %-5.0f | %s" % (
            key, mp.nstr(y[n].real, 30), mp.nstr(y[n].imag, 30), _cont_fmt_agree(dr, ir, nd), _cont_fmt_agree(di, ii, nd), bar,
            "PASS" if ok else "FAIL (re %.1f / im %.1f d < %.0f d)" % (dr, di, bar)))
        rows.append(key)
    fr = _cont_floor(dre)
    fi = _cont_floor(dim)
    nd_cap = min(dps, max([leg["masters"]["m%d" % i]["orders"][str(K)]["re_digits"] for (i, K) in idx if str(K) in leg["masters"].get("m%d" % i, {}).get("orders", {})] or [dps]))
    print("  %s: %d components; floor re %s, im %s" % (
        label, len(rows),
        ("identical (%d)" % len(fr[2])) if fr[0] is None else "%.1f d at %s (identical: %d)" % (fr[0], fr[1], len(fr[2])),
        ("identical (%d)" % len(fi[2])) if fi[0] is None else "%.1f d at %s (identical: %d)" % (fi[0], fi[1], len(fi[2]))))
    return fails, (fr, fi), nd_cap


def continue_tier(t, dps, here, lower_as_physical=False, mutate=False):
    """--continue --point t: the closed form continued to t (|t| >= 4; |t| < 4 as the in-disk control) along the upper
    half-plane path, gated at a stored point; see the block comment above.  A FAIL is raised by name after the tables."""
    import json
    import os
    import time
    t0 = time.perf_counter()
    wp = dps + CONT_WORK_GUARD
    _cont_check_pins(here)
    state, num = _cont_load_system(os.path.join(here, "banana-graded-system.json"))
    gates = json.load(open(os.path.join(here, "banana-minkowski-gates.json")))
    idx = {s: n for n, s in enumerate(state)}
    N0, N1 = _cont_split_eps(state, num)
    ta = CONT_T_BASE
    print("[system] %d components (m0..m3 x eps^-3..eps^1), %d entries, denominator t (t - 4)(t - 16); singular points t = 0, 4, 16" % (len(state), len(num)))
    with mp.workdps(wp):
        numf = [((r, c), [mp.mpf(p.numerator) / p.denominator for p in poly]) for (r, c), poly in num.items()]
        # ---- the base state at t = 2 ----
        ta0 = time.perf_counter()
        m0 = _cont_m0_tower(1)
        alpha = {-3: mp.mpf(0), -2: mp.mpf(0), -1: mp.mpf(0), 0: 7 * zeta(3), 1: mpf(CONT_ALPHA1)}
        vals, abound, nacc = _cont_base_series(N0, N1, ta, dps, alpha, m0)
        v_closed, cbound, ncl = m1_eps0(ta, dps=dps, full_output=True)
        d_base = _cont_digits_cc(mp.mpc(v_closed), mp.mpc(vals[(1, 0)]))
        y0 = [mp.mpc(0)] * len(state)
        for (i, K), n in idx.items():
            y0[n] = mp.mpc(vals[(i, K)])
        y0[idx[(1, 0)]] = mp.mpc(v_closed)
        print("[base] t = %s: m0 from -Gamma(eps)^3; m1[eps^0] from the closed form (N = %d, certified tail %s); the dotted "
              "towers and the eps^1 layer from the MUM recursion at t = 0 (%d terms, certified tail %s < 1e-%d); "
              "m1[eps^K](0) = (0, 0, 0, 7 zeta_3, alpha_1 = %s... (%d digits))"
              % (ta, ncl, mp.nstr(cbound, 3), nacc, mp.nstr(abound, 3), dps + TAIL_GUARD, CONT_ALPHA1[:22], CONT_ALPHA1_DIGITS))
        print("  m1[eps^0](%s): closed form %s" % (ta, mp.nstr(v_closed, 30)))
        print("  m1[eps^0](%s): recursion   %s -> agreement %s d" % (ta, mp.nstr(vals[(1, 0)], 30), "inf (exact at the working precision)" if d_base is None else "%.1f" % d_base))
        _raise_gate("base point: closed form vs the MUM recursion at t = %s" % ta, mp.inf if d_base is None else d_base, float(dps),
                    detail="the two series must agree to dps digits")
        print("  [gate] base-point RAISING gate PASS (%s d >= %.1f d); base wall %.2f s" % ("inf" if d_base is None else "%.1f" % d_base, float(dps), time.perf_counter() - ta0))
        row29 = next((r for r in HELDOUT18 if r[0] == str(ta)), None)
        if row29 is not None:
            with mp.workdps(dps + GUARD):
                d29 = agree_digits(v_closed, row29[7])
            print("  m1[eps^0](%s) vs the stored string %s: %s d (the disk tier's own gate)" % (ta, row29[1], _fmt_d(d29) if d29 == mp.inf else "%.1f" % min(float(d29), sum(c.isdigit() for c in row29[7]))))
        # ---- the march: upper detour h = 2 (the value), h = 3 (route independence), lower detour (Schwarz) ----
        tm = mp.mpf(t.numerator) / t.denominator
        tam = mp.mpf(ta.numerator) / ta.denominator
        routes = {}
        for name, H in (("upper h=2", CONT_HEIGHTS[0]), ("upper h=3", CONT_HEIGHTS[1]), ("lower h=2", -CONT_HEIGHTS[0])):
            Hm = mp.mpf(H.numerator) / H.denominator
            path = [mp.mpc(tam, 0), mp.mpc(tam, Hm), mp.mpc(tm, Hm), mp.mpc(tm, 0)]
            tr0 = time.perf_counter()
            y, dg = _cont_march(numf, state, y0, path, dps, wp)
            routes[name] = y
            sg = "+" if H > 0 else "-"
            print("[march] %s: path [%s, %s %s %si, %s %s %si, %s]; %d steps (%s per leg), Taylor order <= %d, worst certified per-step tail %s (relative), "
                  "smallest step fraction %s; wall %.2f s"
                  % (name, ta, ta, sg, abs(H), t, sg, abs(H), t, dg["steps"], "/".join(str(s) for s in dg["legs"]), dg["max_order"], mp.nstr(dg["trunc_worst"], 3),
                     mp.nstr(dg["min_hfrac"], 4), time.perf_counter() - tr0))
            if name == "upper h=2":
                v = y[idx[(1, 0)]]
                print("  m1[eps^0](%s + i0) = %s %s %s i   (the physical value; t -> t + i0)" % (t, mp.nstr(v.real, 30), "+" if v.imag >= 0 else "-", mp.nstr(abs(v.imag), 30)))
        y_up, y_up2, y_lo = routes["upper h=2"], routes["upper h=3"], routes["lower h=2"]
        keys = ["(%d,%d)" % s for s in state]
        route_fl = _cont_floor({k: _cont_digits_cc(y_up[n], y_up2[n]) for n, k in enumerate(keys)})
        schwarz_fl = _cont_floor({k: _cont_digits_cc(y_up[n], mp.conj(y_lo[n])) for n, k in enumerate(keys)})
        bar_route = float(dps - REF_MARGIN)
        print("[route] route independence (upper h = 2 vs h = 3): floor %s over %d components" % (
            ("identical (%d)" % len(route_fl[2])) if route_fl[0] is None else "%.1f d at %s (identical: %d)" % (route_fl[0], route_fl[1], len(route_fl[2])), len(keys)))
        _raise_gate("route independence (h = 2 vs h = 3) at t = %s" % t, mp.inf if route_fl[0] is None else route_fl[0], bar_route)
        print("[schwarz] the lower detour (t - i0) vs the conjugate of the upper: floor %s over %d components" % (
            ("identical (%d)" % len(schwarz_fl[2])) if schwarz_fl[0] is None else "%.1f d at %s (identical: %d)" % (schwarz_fl[0], schwarz_fl[1], len(schwarz_fl[2])), len(keys)))
        _raise_gate("Schwarz control (lower detour = conjugate of the upper) at t = %s" % t, mp.inf if schwarz_fl[0] is None else schwarz_fl[0], bar_route)
        print("  [gate] route-independence and Schwarz RAISING gates PASS (>= dps - %d = %.1f d)" % (REF_MARGIN, bar_route))
        # a resolved imaginary part: above 10^-(dps - CONT_ZERO_MARGIN) relative; the eps^1 layer above the resolution of
        # alpha_1 (its CONT_ALPHA1_DIGITS digits: an error in alpha_1 adds that much of the non-physical solution)
        def _res_tol(K):
            return mp.mpf(10) ** (-(min(dps, CONT_ALPHA1_DIGITS if K == 1 else dps) - CONT_ZERO_MARGIN))
        nontriv = [k for n, k in enumerate(keys) if abs(y_up[n].imag) > _res_tol(state[n][1]) * max(abs(y_up[n]), mp.mpf(1))]
        ul = _cont_floor({k: _cont_digits_cc(y_up[n], y_lo[n]) for n, k in enumerate(keys)})
        if nontriv:
            print("[monodromy] %d/%d components carry a resolved imaginary part at t + i0: %s; upper vs lower detour differ (they agree to %.1f d: "
                  "the two sheets differ at the leading digit of the imaginary part): the threshold branch is crossed, the value is complex"
                  % (len(nontriv), len(keys), ", ".join(nontriv), max(0.0, ul[0]) if ul[0] is not None else float("inf")))
        else:
            print("[monodromy] 0/%d components carry a resolved imaginary part: the continued value is real; upper vs lower detour agree to %s "
                  "(trivial monodromy on the physical solution; the eps^1 layer at the resolution of alpha_1)"
                  % (len(keys), ("identical (%d)" % len(ul[2])) if ul[0] is None else "%.1f d" % ul[0]))
        zmax = max(abs(y_up[idx[(1, K)]]) for K in (-3, -2, -1))
        zd = float(-log10(zmax)) if zmax > 0 else mp.inf
        print("[zeros] m1's negative orders (identically zero): max |value| %s (%s d below 1)" % (mp.nstr(zmax, 3), "inf" if zd == mp.inf else "%.1f" % zd))
        _raise_gate("structural zeros (m1 at eps^-3..eps^-1) at t = %s" % t, zd, float(dps - CONT_ZERO_MARGIN))
        # ---- the gate at a stored point ----
        y_gate = y_lo if lower_as_physical else y_up
        if lower_as_physical:
            print("[control] --lower-as-physical: the LOWER detour (t - i0) is offered as the physical value below")
        ts = str(t)
        pts = {**gates["record_points"], **gates["fresh_points"]}
        lab = next((L for L, P in pts.items() if P["t"] == ts), None)
        fails_all = []
        if lab is None and abs(t) < 4:
            v_cf = m1_eps0(t, dps=dps)
            d_cf = _cont_digits_cc(mp.mpc(v_cf), y_gate[idx[(1, 0)]])
            print("[control] in-disk control at t = %s: transported m1[eps^0] vs the closed form's series: %s d (bar %.1f d)" % (
                t, "inf (exact at the working precision)" if d_cf is None else "%.1f" % d_cf, float(dps - REF_MARGIN)))
            _raise_gate("in-disk control (transport vs the closed form) at t = %s" % t, mp.inf if d_cf is None else d_cf, float(dps - REF_MARGIN))
            row = next((r for r in HELDOUT18 if r[0] == ts), None)
            if row is not None:
                nref = sum(c.isdigit() for c in row[7])
                with mp.workdps(dps + GUARD):
                    d = agree_digits(y_gate[idx[(1, 0)]].real, row[7])
                thr = min(dps, nref) - REF_MARGIN
                print("  transported m1[eps^0] vs the stored string %s (%d d): %.1f d (bar %.1f d)" % (row[1], nref, min(float(d), float(nref)), thr))
                _raise_gate("in-disk control vs the stored string at t = %s" % t, float(d), thr)
            print("  [gate] in-disk control PASS")
        elif lab is None:
            print("  (no stored reference at this point; gate points live at t = %s)" % ", ".join(P["t"] for P in pts.values()))
        else:
            P = pts[lab]
            fresh = lab in gates["fresh_points"]
            legs = P["legs"]
            mut = None
            if mutate:
                first = next(iter(legs.values()))
                s = first["masters"]["m1"]["orders"]["0"]["re"]
                mut, was, now = _flip_digit(s, CONT_MUTATE_DIGIT)
                print("[control] --mutate: significant digit %d of the %s m1[eps^0] real-part string %s -> %s (in memory; the file is untouched)"
                      % (CONT_MUTATE_DIGIT, next(iter(legs)), was, now))
            if fresh:
                pf, pm, pn = _cont_pair_floor(legs["g60"], legs["g40"])
                bar = float(int(pf))
                print("-- gate: t = %s vs the two fresh points %s (goal 60, output %s...; goal 40, output %s...; predicted before they were run) --"
                      % (t, lab, legs["g60"]["output_sha256"][:16], legs["g40"]["output_sha256"][:16]))
                print("  the goal-60 / goal-40 pair floor: %.1f d at %s over %d members -> bar %.0f d on every component, Re and Im" % (pf, pm, pn, bar))
                floors, caps = {}, {}
                for ln in ("g60", "g40"):
                    L = dict(legs[ln])
                    L["_bar"] = bar
                    f, fl, ndc = _cont_gate_leg(y_gate, idx, L, dps, "this run vs goal %d (%s)" % (legs[ln]["goal_digits"], ln), mutate=(mut if ln == "g60" else None))
                    fails_all += [(ln,) + x for x in f]
                    floors[ln] = fl
                    caps[ln] = ndc
                f60 = min([x for x in (floors["g60"][0][0], floors["g60"][1][0]) if x is not None] or [float("inf")])
                f40 = min([x for x in (floors["g40"][0][0], floors["g40"][1][0]) if x is not None] or [float("inf")])
                print("  [fresh] t = %s: %s d at goal 60 / %s d at goal 40 / the pair floors at %.1f d (bar %.0f)" % (
                    t, ("identical at the cap %d" % caps["g60"]) if f60 == float("inf") else "%.1f" % f60,
                    ("identical at the cap %d" % caps["g40"]) if f40 == float("inf") else "%.1f" % f40, pf, bar))
            else:
                pf, pm, pn = _cont_pair_floor(legs["A"], legs["B"])
                print("-- gate: t = %s vs the record (%s; A goal %d, %d digits, output %s...; B goal %d, %d digits, output %s...) --"
                      % (t, lab, legs["A"]["goal_digits"], legs["A"]["masters"]["m1"]["orders"]["0"]["re_digits"], legs["A"]["output_sha256"][:16],
                         legs["B"]["goal_digits"], legs["B"]["masters"]["m1"]["orders"]["0"]["re_digits"], legs["B"]["output_sha256"][:16]))
                print("  the A / B pair floor of the record itself: %.1f d at %s over %d members" % (pf, pm, pn))
                for ln in ("A", "B"):
                    f, fl, _ndc = _cont_gate_leg(y_gate, idx, legs[ln], dps, "this run vs run %s" % ln, mutate=(mut if ln == "A" else None))
                    fails_all += [(ln,) + x for x in f]
                print("  bars: min(dps, string digits) - %d = %.0f d (110-digit strings) / %.0f d (140-digit strings); the eps^1 layer <= %d - %d = %d d (the %d-digit alpha_1)"
                      % (REF_MARGIN, min(dps, 110) - REF_MARGIN, min(dps, 140) - REF_MARGIN, CONT_ALPHA1_DIGITS, REF_MARGIN, CONT_ALPHA1_DIGITS - REF_MARGIN, CONT_ALPHA1_DIGITS))
            if fails_all:
                names = "; ".join("%s %s (re %.1f / im %.1f d < %.0f d)" % f for f in fails_all)
                print("  [gate] Minkowski gate at t = %s: FAIL at %s" % (t, names))
                raise RuntimeError("banana RAISING gate FAILED (fail-closed): --continue gate at t = %s: %s" % (t, names))
            print("  [gate] Minkowski gate at t = %s: PASS (%s)" % (t, "the lower detour offered as physical passed: the value is real here" if lower_as_physical else "every component, Re and Im"))
    print("--continue wall time: %.2f s" % (time.perf_counter() - t0))


# ---------------------------------------------------------------------------
# --eps1: the eps^1 layer of the top master on the MUM disk   (2026-09-08; every unit below is new)
#
#     m1[eps^1](t) = alpha_1 varpi_0(t) + Part^(1)(t),   |t| < 4
#
# The same eps-graded holomorphic recursion that seeds --continue (_cont_base_series: (64 n I - N^(0)_0) c_{n,K} =
# N^(1)_0 c_{n,K-1} + sum_{j=1..4} (N^(0)_j c_{n-j,K} + N^(1)_j c_{n-j,K-1}) + 20 (n - 1) c_{n-1,K} - (n - 2) c_{n-2,K} on
# the raw four-master system of banana-graded-system.json) is summed AT the point t; the eps^1 component of m1 is the
# layer.  With the boundary data m1[eps^K](0) = (0, 0, 0, 7 zeta_3, alpha_1) the layer is linear in alpha_1: the
# homogeneous piece with unit boundary is the K3 period varpi_0 (the Domb series of the closed form above) and the rest,
# Part^(1), is the holomorphic eps^1 particular of the recursion with m1[eps^1](0) = 0.  alpha_1 = m1[eps^1](0) is the
# Bessel-moment constant CONT_ALPHA1, the eps^1 coefficient of the p^2 = 0 vacuum banana in d = 2 - 2 eps (its provenance
# in EPS1_ALPHA1_PROVENANCE; --bessel recomputes it live).  Every master is analytic at p^2 = 0, which is why the t-space
# sum of the Dyson words of the certified connection collapses to this one new constant: the words themselves are the
# symbolic companion banana-eps1-words.json (EPS1_PINS), printed, never evaluated.
#   * the certified tail: the recursion's own trailing-TAIL_WINDOW-term bound x r/(1 - r), r = |t|/4, below
#     10^-(dps + TAIL_GUARD) (the rule of every disk tier); varpi_0 is summed to the closed form's certified N;
#   * at a stored point (HELDOUT18_EPS1: the eps^1 midpoint of the same output file as the HELDOUT18 row, by sha256)
#     m1[eps^1] is gated against the string at bar min(dps, string digits, CONT_ALPHA1_DIGITS) - REF_MARGIN (the layer
#     carries the CONT_ALPHA1_DIGITS digits of alpha_1 and no more), the printed figure min(measured, string digits,
#     dps + GUARD, CONT_ALPHA1_DIGITS) with the active cap named; beside it three RAISING gates: the eps^0 component of
#     the same recursion vs the closed form (at dps, as --continue's base gate), alpha_1 fitted from the string,
#     (string - Part^(1)) / varpi_0, vs CONT_ALPHA1 at the same bar, and at the record's gate point t = 7/2 (or at
#     --point) the decomposition itself: the recursion re-run with alpha_1 := 0 returns Part^(1) directly and
#     m1[eps^1] - Part^(1) must equal alpha_1 varpi_0 to dps - REF_MARGIN digits;
#   * --mutate-eps1 T[:K] plants a digit of a stored eps^1 string in memory (FAIL by name, exit 1); |t| >= 4 is refused
#     by name (exit 2: past the disk the layer is carried by --continue and gated there); a point of the disk without a
#     stored string prints the value and names the stored points.
# Nothing here changes the units above: every disk tier and --continue are byte-for-byte the previous release.
# ---------------------------------------------------------------------------

EPS1_PINS = {   # sha256 of the word list beside this script (exit 3 on a mismatch, exit 4 when missing); the system file is CONT_PINS'
    "banana-eps1-words.json": "fe0c6cfb98c15d807735136f76897edc7fe1fe8d9959e8568ed70af53f6c52e2",
}
EPS1_DECOMP_POINT = "7/2"       # the record's gate point: the decomposition gate runs there in the 18-point tier
EPS1_MUTATE_DIGIT = 30          # --mutate-eps1 default K (the record's planted-digit control used digit 30)
EPS1_CAP_SAFETY = 2             # the recursion's term cap on the disk = this x the a-priori count (dps + TAIL_GUARD) ln 10 / ln(4/|t|)
EPS1_BESSEL_GUARD = 10          # --bessel: working digits above dps for the quadrature (the record's own guard)
EPS1_BESSEL_SPLIT = (0, 1, 4, 12, mp.inf)   # the record's split of [0, oo) for the tanh-sinh quadrature
# alpha_1 as computed by the record: two quadrature legs, the second one the CONT_ALPHA1 string; every figure copied from
# the record object (B(eps) = 2^(3-2eps)/Gamma(1-eps) int_0^oo r^(1+2eps) K_eps(r)^4 dr; B(0) = 7 zeta_3 the positive control).
EPS1_ALPHA1_PROVENANCE = {
    "formula": "B(eps) = 2^(3-2eps)/Gamma(1-eps) * int_0^inf r^(1+2eps) K_eps(r)^4 dr; B[eps^1] = 16 int r ln r K_0^4 dr - 7 zeta3 (2 ln2 + gamma_E)",
    "legs": [
        {"dps": 80, "B0_vs_7zeta3_digits": "inf (exact at the working precision)", "B1": "-53.952349689863762575572488542945775595371575666622896095876615523574054404035303", "JL_int_r_lnr_K0^4": "-2.3394121388405547302367241705248390038798148223982259753908559243724896483764545", "wall_s": 34.89},
        {"dps": 110, "B0_vs_7zeta3_digits": "120.7", "B1": "-53.952349689863762575572488542945775595371575666622896095876615523574054404035302602860001756911473937218573515", "JL_int_r_lnr_K0^4": "-2.3394121388405547302367241705248390038798148223982259753908559243724896483764544604390352310488056762713961331", "wall_s": 57.46},
    ],
    "two_leg_agreement_digits": "80.1",
    "finite_difference_h": "1e-8",
    "finite_difference_vs_formula_digits": "14.7",
    "quadrature": "mpmath tanh-sinh (mpmath 1.3.0) on [0, 1, 4, 12, oo), working dps = leg dps + 10; the string is the dps-110 leg",
    "closed_form": "not established (an integer relation search in the zeta / ln 2 / gamma_E ring and in the ring extended by L(f_3, 2) found none at height 10^4)",
}


def _eps1_check_pins(here, pins):
    """As _cont_check_pins over a given pin table: exit 4 (missing) / 3 (mismatch), by name, before anything is computed."""
    import hashlib
    import os
    import sys
    for name, want in pins.items():
        p = os.path.join(here, name)
        if not os.path.isfile(p):
            print("MISSING data file %s (expected beside the script, sha256 %s...): exit 4" % (name, want[:16]))
            sys.exit(4)
        got = hashlib.sha256(open(p, "rb").read()).hexdigest()
        if got != want:
            print("PIN MISMATCH %s: sha256 %s... != pinned %s...: exit 3" % (name, got[:16], want[:16]))
            sys.exit(3)
        print("[pins] %s sha256 %s... OK" % (name, got[:16]))


def _eps1_words_summary(path):
    """The symbolic companion: the words of the Dyson chain over the certified connection that survive at eps^1 of m1."""
    import json
    W = json.load(open(path))
    tower = W["word_count_tower_g1"]
    L = W["physical_layers"]["m1_eps^1"]
    first = W["letter_first_physical_order"]
    print("[words] the Dyson chain over the certified connection (letters 1, f_2a, f_2b, f_4a, f_4b, f_6): word tower %s "
          "(the top row, eps^0..eps^%d); at eps^1 of m1 %d structural words, %d after the record's regularized zeros "
          "C_{3,2} = C_{4,1} = 0; letters active %s; first physical order of each letter %s"
          % (tower, len(tower) - 1, L["n_words_structural"], L["n_words_after_record_zeros"],
             ", ".join(L["letters_active_after_record_zeros"]), ", ".join("%s: %d" % (k, first[k]) for k in sorted(first, key=lambda k: (first[k], k)))))
    for w in L["words"]:
        if w["known_zero"] is None:
            print("  %+d [%s] %s" % (w["coeff"], " ".join(w["word_outer_to_inner"]) or "()", w["boundary_factor"]))
    print("  (their t-space sum is what the recursion evaluates; the letters are not evaluated one by one here)")


def _eps1_cap_factor(t):
    """The recursion's term cap is CONT_ORDER_CAP x (dps + TAIL_GUARD), sized for the base point t = 2 of --continue
    (r = 1/2); on the disk r = |t|/4 approaches 1 and the a-priori count is (dps + TAIL_GUARD) ln 10 / ln(4/|t|) terms, so
    the factor for the call is EPS1_CAP_SAFETY x ln 10 / ln(4/|t|) + 1, never below the served CONT_ORDER_CAP."""
    if t == 0:
        return CONT_ORDER_CAP
    return max(CONT_ORDER_CAP, int(math.ceil(EPS1_CAP_SAFETY * math.log(10) / -math.log(abs(float(t)) / 4))) + 1)


def _eps1_at(t, dps, N0, N1, alpha1):
    """The recursion at t (|t| < 4) with m1[eps^K](0) = (0, 0, 0, 7 zeta_3, alpha1) -> (values, certified tail bound, n_used).
    The served unit _cont_base_series is called unchanged; only its term cap CONT_ORDER_CAP (read at call time) is raised
    to _eps1_cap_factor(t) for the call and restored after -- the certified tail rule itself is untouched."""
    global CONT_ORDER_CAP
    m0 = _cont_m0_tower(1)
    alpha = {-3: mp.mpf(0), -2: mp.mpf(0), -1: mp.mpf(0), 0: 7 * zeta(3), 1: alpha1}
    keep = CONT_ORDER_CAP
    CONT_ORDER_CAP = _eps1_cap_factor(t)
    try:
        return _cont_base_series(N0, N1, t, dps, alpha, m0)
    finally:
        CONT_ORDER_CAP = keep


def eps1_point(t, dps, N0, N1, decompose=False):
    """m1[eps^1](t) with alpha_1 = CONT_ALPHA1, beside varpi_0(t) (the Domb series at the closed form's certified N),
    Part^(1) = m1[eps^1] - alpha_1 varpi_0, the closed form and the recursion's own eps^0 component; decompose=True re-runs
    the recursion with alpha_1 := 0 and returns its m1[eps^1] as Part^(1) directly.  Values at dps + CONT_WORK_GUARD."""
    with mp.workdps(dps + CONT_WORK_GUARD):
        a1 = mpf(CONT_ALPHA1)
        vals, bound, n_used = _eps1_at(t, dps, N0, N1, a1)
        v_closed, cbound, ncl = m1_eps0(t, dps=dps, full_output=True)
        tm = mp.mpf(t.numerator) / t.denominator
        ensure_nterms(ncl)
        varpi0 = series(D[:ncl + 1], tm / 64)
        m1e1 = vals[(1, 1)]
        out = {"m1_eps1": m1e1, "varpi0": varpi0, "part": m1e1 - a1 * varpi0, "tail": bound, "n": n_used,
               "closed": v_closed, "rec_eps0": vals[(1, 0)], "n_closed": ncl}
        if decompose:
            vals0, _b0, n0 = _eps1_at(t, dps, N0, N1, mp.mpf(0))
            out["part_direct"] = vals0[(1, 1)]
            out["n_direct"] = n0
        return out


def _eps1_shown(d, nref, dps):
    """The printed eps^1 agreement: min(measured, string digits, dps + GUARD, CONT_ALPHA1_DIGITS), the active cap named."""
    caps = [(float(nref), "the %d-digit string" % nref), (float(dps + GUARD), "the working precision dps+%d = %d" % (GUARD, dps + GUARD)),
            (float(CONT_ALPHA1_DIGITS), "the %d-digit alpha_1" % CONT_ALPHA1_DIGITS)]
    cap, which = min(caps, key=lambda c: c[0])
    return min(float(d), cap), cap, which


def eps1_gate(dps, here, point=None, mutate=None):
    """--eps1: the eps^1 layer at every point of the 18-point record (or at --point) gated against the stored eps^1 strings;
    see the block comment above.  mutate = (t, K): significant digit K of that point's stored eps^1 string incremented mod 10
    in memory (the shipped control).  Prints one row per point and a VERDICT; a FAIL is raised by name after the table (rc 1)."""
    import os
    import time
    t0 = time.perf_counter()
    pins = {"banana-graded-system.json": CONT_PINS["banana-graded-system.json"]}
    pins.update(EPS1_PINS)
    _eps1_check_pins(here, pins)
    state, num = _cont_load_system(os.path.join(here, "banana-graded-system.json"))
    N0, N1 = _cont_split_eps(state, num)
    print("[system] %d components (m0..m3 x eps^-3..eps^1), %d entries, denominator t (t - 4)(t - 16); the recursion summed on the disk |t| < 4" % (len(state), len(num)))
    _eps1_words_summary(os.path.join(here, "banana-eps1-words.json"))
    print("[alpha_1] m1[eps^1](0) = %s (%d digits): %s" % (CONT_ALPHA1, CONT_ALPHA1_DIGITS, EPS1_ALPHA1_PROVENANCE["formula"]))
    for leg in EPS1_ALPHA1_PROVENANCE["legs"]:
        print("  quadrature leg dps %d: B(0) vs 7 zeta_3 %s d; B[eps^1] = %s... ; wall %s s" % (leg["dps"], leg["B0_vs_7zeta3_digits"], leg["B1"][:24], leg["wall_s"]))
    print("  the two legs agree to %s d; d/deps by finite difference (h = %s) vs the formula %s d; the closed-form value is not established"
          % (EPS1_ALPHA1_PROVENANCE["two_leg_agreement_digits"], EPS1_ALPHA1_PROVENANCE["finite_difference_h"], EPS1_ALPHA1_PROVENANCE["finite_difference_vs_formula_digits"]))
    plant = None
    if mutate is not None:
        tm_, k = mutate
        row = next((r for r in HELDOUT18_EPS1 if r[0] == tm_ or r[1].split("_")[0] == tm_), None)
        if row is None:
            raise ValueError("--mutate-eps1: no record point %r (give t as in the table, e.g. -3, 1/2, or its label, e.g. T02)" % tm_)
        planted, was, now = _flip_digit(row[6], k)
        plant = (row[0], k, was, now, planted)
        print("[control] --mutate-eps1: significant digit %d of the t = %s stored eps^1 string %s -> %s (in memory; the table is untouched)"
              % (k, row[0], was, now))
    rows = list(HELDOUT18_EPS1)
    if point is not None:
        ts = str(point)
        rows = [r for r in HELDOUT18_EPS1 if r[0] == ts]
    # the eps^1 table is keyed to the eps^0 table by output file and sha256: a gate of its own
    keyed = sum(1 for r in HELDOUT18_EPS1 if any(h[0] == r[0] and h[1] == r[1] and h[2] == r[2] and h[3] == r[3] for h in HELDOUT18))
    print("HELDOUT18_EPS1 rows keyed to HELDOUT18 by (t, output file, output sha256, configuration sha256): %d/%d" % (keyed, len(HELDOUT18_EPS1)))
    if keyed != len(HELDOUT18_EPS1) or len(HELDOUT18_EPS1) != len(HELDOUT18):
        raise RuntimeError("banana RAISING gate FAILED (fail-closed): the eps^1 table is not keyed to the eps^0 table (%d/%d rows; %d vs %d)" % (keyed, len(HELDOUT18_EPS1), len(HELDOUT18_EPS1), len(HELDOUT18)))
    print("-- the eps^1 layer m1[eps^1](t) = alpha_1 varpi_0(t) + Part^(1)(t) vs the stored eps^1 strings (dps %d; bars min(dps, string digits, %d) - %d) --" % (dps, CONT_ALPHA1_DIGITS, REF_MARGIN))
    print("%-6s | %-10s | %-8s | %-32s | %-26s | %-7s | %-12s | %-10s | %s" % ("t", "source", "digits", "this work m1[eps^1] (30 d)", "agreement d (cap when at it)", "bar d", "alpha_1 fit d", "eps^0 rec d", "verdict"))
    fails, shown_min, rows_out, dec_done, fail_pts = [], None, 0, [], set()
    for t, srcname, _osha, _csha, _goal, _rad, ref in rows:
        if plant is not None and t == plant[0]:
            ref = plant[4]
        nref = sum(c.isdigit() for c in ref)
        want_dec = (point is not None) or (t == EPS1_DECOMP_POINT)
        res = eps1_point(Fraction(t), dps, N0, N1, decompose=want_dec)
        with mp.workdps(dps + GUARD):
            d = agree_digits(res["m1_eps1"], ref)
            a_fit = (mpf(ref) - res["part"]) / res["varpi0"]
            d_fit = agree_digits(a_fit, CONT_ALPHA1)
        with mp.workdps(dps + CONT_WORK_GUARD):
            d0 = _cont_digits_cc(mp.mpc(res["closed"]), mp.mpc(res["rec_eps0"]))
        d0f = mp.inf if d0 is None else d0
        shown, cap, which = _eps1_shown(d, nref, dps)
        thr = min(dps, nref, CONT_ALPHA1_DIGITS) - REF_MARGIN
        ok = float(d) >= thr
        ok_fit = float(d_fit) >= thr
        ok0 = d0f >= float(dps)
        if not ok:
            fails.append("t = %s m1[eps^1] (%.1f d < %.1f d)" % (t, float(d), thr))
        if not ok_fit:
            fails.append("t = %s alpha_1 fitted from the string (%.1f d < %.1f d)" % (t, float(d_fit), thr))
        if not ok0:
            fails.append("t = %s the recursion's eps^0 vs the closed form (%s d < %.1f d)" % (t, _fmt_d(d0f), float(dps)))
        if not (ok and ok_fit and ok0):
            fail_pts.add(t)
        if shown_min is None or shown < shown_min[0]:
            shown_min = (shown, t)
        capname = "string" if which.endswith("string") else ("alpha_1" if which.endswith("alpha_1") else "dps+%d" % GUARD)
        print("%-6s | %-10s | %-8d | %-32s | %-26s | %-7.1f | %-12s | %-10s | %s" % (
            t, srcname, nref, mp.nstr(res["m1_eps1"], 30),
            ("%.1f (%s)" % (shown, capname)) if shown == cap else "%.1f" % shown, thr,
            "%.1f" % min(float(d_fit), float(CONT_ALPHA1_DIGITS)), _fmt_d(d0f) if d0f == mp.inf else "%.1f" % d0f,
            "PASS" if (ok and ok_fit and ok0) else "FAIL"))
        print("       Part^(1) = %s; varpi_0 = %s; recursion N = %d (certified tail %s < 1e-%d); closed form N = %d"
              % (mp.nstr(res["part"], 30), mp.nstr(res["varpi0"], 30), res["n"], mp.nstr(res["tail"], 3), dps + TAIL_GUARD, res["n_closed"]))
        if want_dec:
            with mp.workdps(dps + CONT_WORK_GUARD):
                lhs = res["m1_eps1"] - res["part_direct"]
                rhs = mpf(CONT_ALPHA1) * res["varpi0"]
                dd = _cont_digits_cc(mp.mpc(lhs), mp.mpc(rhs))
            ddf = mp.inf if dd is None else dd
            bar_dec = float(dps - REF_MARGIN)
            print("       [decomposition] at t = %s: the recursion with alpha_1 := 0 gives Part^(1) = %s (N = %d); m1[eps^1] - Part^(1) vs alpha_1 varpi_0: %s d (bar %.1f d)"
                  % (t, mp.nstr(res["part_direct"], 30), res["n_direct"], _fmt_d(ddf) if ddf == mp.inf else "%.1f" % ddf, bar_dec))
            if not ddf >= bar_dec:
                fails.append("t = %s decomposition (%s d < %.1f d)" % (t, _fmt_d(ddf), bar_dec))
                fail_pts.add(t)
            dec_done.append(t)
        rows_out += 1
    if point is not None and not rows:
        ts = str(point)
        res = eps1_point(Fraction(point), dps, N0, N1, decompose=True)
        with mp.workdps(dps + CONT_WORK_GUARD):
            d0 = _cont_digits_cc(mp.mpc(res["closed"]), mp.mpc(res["rec_eps0"]))
        d0f = mp.inf if d0 is None else d0
        print("t = %s (no stored eps^1 string at this point; stored points live at t = %s)" % (ts, ", ".join(r[0] for r in HELDOUT18_EPS1)))
        print("  m1[eps^1] = %s" % mp.nstr(res["m1_eps1"], min(dps, CONT_ALPHA1_DIGITS)))
        print("  Part^(1)  = %s" % mp.nstr(res["part"], dps))
        print("  varpi_0   = %s" % mp.nstr(res["varpi0"], dps))
        print("  recursion N = %d (certified tail %s < 1e-%d); closed form N = %d; the eps^0 component vs the closed form %s d (bar %.1f d)"
              % (res["n"], mp.nstr(res["tail"], 3), dps + TAIL_GUARD, res["n_closed"], _fmt_d(d0f) if d0f == mp.inf else "%.1f" % d0f, float(dps)))
        _raise_gate("the recursion's eps^0 vs the closed form at t = %s" % ts, d0f, float(dps))
        with mp.workdps(dps + CONT_WORK_GUARD):
            lhs = res["m1_eps1"] - res["part_direct"]
            rhs = mpf(CONT_ALPHA1) * res["varpi0"]
            dd = _cont_digits_cc(mp.mpc(lhs), mp.mpc(rhs))
        ddf = mp.inf if dd is None else dd
        print("  [decomposition] the recursion with alpha_1 := 0 gives Part^(1) = %s (N = %d); m1[eps^1] - Part^(1) vs alpha_1 varpi_0: %s d (bar %.1f d)"
              % (mp.nstr(res["part_direct"], 30), res["n_direct"], _fmt_d(ddf) if ddf == mp.inf else "%.1f" % ddf, float(dps - REF_MARGIN)))
        _raise_gate("decomposition at t = %s" % ts, ddf, float(dps - REF_MARGIN))
        print("  [gate] eps^0 and decomposition RAISING gates PASS (the value carries at most the %d digits of alpha_1)" % CONT_ALPHA1_DIGITS)
        print("--eps1 wall time: %.2f s" % (time.perf_counter() - t0))
        return
    wall = time.perf_counter() - t0
    if fails:
        print("VERDICT --eps1 (dps %d): FAIL at %s -- %d/%d rows PASS" % (dps, "; ".join(fails), rows_out - len(fail_pts), rows_out))
        print("--eps1 wall time: %.2f s" % wall)
        raise RuntimeError("banana RAISING gate FAILED (fail-closed): --eps1 record gate at " + "; ".join(fails))
    print("VERDICT --eps1 (dps %d): %d/%d PASS; minimum printed agreement %.1f d at t = %s; bars %.1f d (110-digit strings) / %.1f d (140-digit strings, capped by the %d-digit alpha_1); "
          "alpha_1 fitted from every string agrees with the stored constant at the same bars; the recursion's eps^0 equals the closed form to >= dps at every point; decomposition gate at t = %s"
          % (dps, rows_out, rows_out, shown_min[0], shown_min[1], min(dps, 110, CONT_ALPHA1_DIGITS) - REF_MARGIN, min(dps, 140, CONT_ALPHA1_DIGITS) - REF_MARGIN, CONT_ALPHA1_DIGITS, ", ".join(dec_done) or "(none)"))
    print("--eps1 wall time: %.2f s" % wall)


def bessel_tier(dps):
    """--bessel: alpha_1 = m1[eps^1](0) recomputed live by tanh-sinh quadrature at dps (+ EPS1_BESSEL_GUARD working digits):
    B(0) = 8 int_0^oo r K_0(r)^4 dr vs 7 zeta_3 (the positive control, RAISING at dps - REF_MARGIN) and B[eps^1] =
    16 int_0^oo r ln r K_0(r)^4 dr - 7 zeta_3 (2 ln 2 + gamma_E) vs the stored CONT_ALPHA1 (RAISING at min(dps,
    CONT_ALPHA1_DIGITS) - REF_MARGIN; the printed figure capped by the string's CONT_ALPHA1_DIGITS digits and the working
    precision).  The quadrature's own error estimate is printed as a diagnostic, not as a certificate: the gate is the string."""
    import time
    t0 = time.perf_counter()
    wp = dps + EPS1_BESSEL_GUARD
    print("[alpha_1] the stored constant: %s (%d digits); %s" % (CONT_ALPHA1, CONT_ALPHA1_DIGITS, EPS1_ALPHA1_PROVENANCE["formula"]))
    with mp.workdps(wp):
        z3 = zeta(3)
        g = mp.euler
        ln2 = mp.log(2)
        ta = time.perf_counter()
        J0, e0 = mp.quad(lambda r: r * mp.besselk(0, r) ** 4, EPS1_BESSEL_SPLIT, error=True)
        w0 = time.perf_counter() - ta
        ta = time.perf_counter()
        JL, eL = mp.quad(lambda r: r * mp.log(r) * mp.besselk(0, r) ** 4, EPS1_BESSEL_SPLIT, error=True)
        wL = time.perf_counter() - ta
        B0 = 8 * J0
        B1 = 16 * JL - 7 * z3 * (2 * ln2 + g)
        d0 = fabs(B0 - 7 * z3)
        d0 = mp.inf if d0 == 0 else float(-log10(d0 / (7 * z3)))
        d1 = agree_digits(B1, CONT_ALPHA1)
        print("  int_0^oo r K_0(r)^4 dr        = %s  (quadrature error estimate %s; %.2f s)" % (mp.nstr(J0, dps), mp.nstr(e0, 3), w0))
        print("  int_0^oo r ln r K_0(r)^4 dr   = %s  (quadrature error estimate %s; %.2f s)" % (mp.nstr(JL, dps), mp.nstr(eL, 3), wL))
        print("  B(0) = 8 x the first          = %s" % mp.nstr(B0, dps))
        print("  7 zeta_3                      = %s" % mp.nstr(7 * z3, dps))
        print("  B[eps^1] = alpha_1 (live)     = %s" % mp.nstr(B1, dps))
    bar0 = float(dps - REF_MARGIN)
    bar1 = float(min(dps, CONT_ALPHA1_DIGITS) - REF_MARGIN)
    cap1 = float(min(CONT_ALPHA1_DIGITS, wp))
    print("  B(0) vs 7 zeta_3: %s d (bar %.1f d, the positive control)" % (_fmt_d(d0) if d0 == mp.inf else "%.1f" % min(d0, float(wp)), bar0))
    print("  alpha_1 live vs the stored string: %s d (cap %.0f d = %s; bar %.1f d)" % (
        _fmt_d(d1) if d1 == mp.inf else "%.1f" % min(float(d1), cap1), cap1,
        "the %d-digit string" % CONT_ALPHA1_DIGITS if cap1 == CONT_ALPHA1_DIGITS else "the working precision dps+%d = %d" % (EPS1_BESSEL_GUARD, wp), bar1))
    _raise_gate("--bessel positive control B(0) vs 7 zeta_3", d0, bar0)
    _raise_gate("--bessel alpha_1 live vs the stored string", float(d1), bar1)
    print("  [gate] --bessel RAISING gates PASS (%s d >= %.1f d; %s d >= %.1f d)" % (_fmt_d(d0), bar0, _fmt_d(d1), bar1))
    print("--bessel wall time: %.2f s" % (time.perf_counter() - t0))


# ---------------------------------------------------------------------------
# --bessel-eps K: the eps-layers of the top master at a Euclidean point, from the exact-in-d Bessel representation
# (2026-09-11; every unit below is new; nothing above is touched)
#
# In position space the four propagators of the equal-mass banana multiply, and with the measure d^dk/pi^(d/2) per loop
# (no e^(gamma_E eps) factor) the top master at a Euclidean point t = p^2/m^2 < 0 in d = 2 - 2 eps is ONE radial integral,
#
#     m1(t; eps) = 2^(3-3eps) int_0^oo r^(1+2eps) (a r)^eps J_{-eps}(a r) K_eps(r)^4 dr,     a = sqrt(-t),            (R)
#
# exact in eps.  At eps = 0 it is 8 int r J_0(a r) K_0(r)^4 dr; at t = 0, where (a r)^eps J_{-eps}(a r) -> 2^eps/Gamma(1-eps),
# it is the vacuum banana B(eps) = 2^(3-2eps)/Gamma(1-eps) int r^(1+2eps) K_eps(r)^4 dr of the --bessel tier, whose eps^0 and
# eps^1 coefficients are 7 zeta_3 and alpha_1 (CONT_ALPHA1).  m1(t; eps) is analytic in eps on |eps| < 1/3: at eps = -1/3
# (d = 8/3) the integrand's small-r behaviour r^(1-6|eps|) stops being integrable -- the superficial divergence of the
# three-loop banana -- so the layers c_k = m1[eps^k](t) grow like 3^k and are read off the circle |eps| = rho by the
# trapezoid rule,
#     c_k ~ (1/N) sum_j m1(t; eps_j) eps_j^(-k),    eps_j = rho e^(2 pi i j/N),
# conjugate nodes sharing one evaluation (N//2 + 1 quadratures per pass), each node one tanh-sinh quadrature of (R) with
# complex Bessel orders on the record's split [0, 1/4, 1, 3, 8, 16, 28, 45] (extended by x3/2 steps while e^(-4 r_max) is
# above 10^-(dps + TAIL_GUARD)).  The a-priori budget of layer k is
#     min( N log10(1/(3 rho))   [aliasing: the trapezoid sum returns c_k + c_(k+N) rho^N + ..., and c_(k+N)/c_k ~ 3^N],
#          dps - k log10(1/rho)  [roundoff: the node values carry dps digits and c_k is divided by rho^k] )
# digits (42.3 / 60 - 4k at the defaults dps 60, N 12, rho 1e-4); a second pass at dps - BESSEL_EPS_DROP gives the
# two-precision floor per layer (RAISING at that pass's budget - REF_MARGIN).  The representation is independent of the
# four-master system, of its MUM recursion and of the --continue transport, so it gates what they carry: at the stored
# Euclidean point t = -8 of banana-minkowski-gates.json every stored order of both legs (eps^0..eps^5; the file pin-checked
# as in --continue), at the two Euclidean points of the 18-point record (t = -7/2, -3) the eps^0 and eps^1 strings
# (HELDOUT18, HELDOUT18_EPS1), at t = 0 the constants 7 zeta_3 and alpha_1, and at any point -4 < t < 0 the eps^0 layer
# against the closed form m1_eps0 -- each RAISING at min(budget, string digits) - REF_MARGIN, FAIL by name, exit 1.  A
# Euclidean point without a stored string (t <= -4, t != -8) prints the layers with the two-precision floor alone.
# --planted flips the order sign (J_(+eps) in place of J_(-eps)): the eps^0 layer is unchanged (J_0 either way) and the
# eps^1 layer moves by 8 pi int r Y_0(a r) K_0(r)^4 dr, so the eps^1 gate FAILS by name; it needs a point with a stored
# eps^1 string (t = -8, -7/2, -3).  t > 0 is refused by name (exit 2): below and above the threshold the kernel continues to
# the modified Bessel function of the first kind and that continuation is not carried here.  The quadratures run at the
# working precision dps itself (the comparisons at dps + BESSEL_EPS_CMP_GUARD); the layers carry the budget, not dps, and
# every printed value is cut to its budget.
# ---------------------------------------------------------------------------

BESSEL_EPS_T = "-8"                    # the default point: the stored Euclidean point of banana-minkowski-gates.json
BESSEL_EPS_DPS = 60                    # the default --dps of this tier (with N 12 and rho 1e-4 the aliasing budget is 42.3 d: more working digits buy nothing without a larger N)
BESSEL_EPS_N = 12                      # trapezoid nodes on the eps-circle (N//2 + 1 quadratures per pass)
BESSEL_EPS_RHO = "1e-4"                # the circle radius
BESSEL_EPS_RADIUS = Fraction(1, 3)     # m1(t; eps) is analytic on |eps| < 1/3 (the first divergence sits at d = 8/3)
BESSEL_EPS_DROP = 15                   # the second pass runs at dps - BESSEL_EPS_DROP (floored at 15)
BESSEL_EPS_CMP_GUARD = 10              # comparisons at dps + this
BESSEL_EPS_MIN_BUDGET = 20             # a (dps, N, rho, K) whose a-priori budget for layer K is below this is refused (exit 2)
BESSEL_EPS_CUTS = (0, Fraction(1, 4), 1, 3, 8, 16, 28, 45)   # the record's split of [0, r_max]
BESSEL_EPS_SHOW = 30                   # digits shown in the table column


def _beps_budget(dps, N, rho, k):
    """The a-priori digits of layer k at (dps, N, rho): (aliasing, roundoff, their minimum); rho a Fraction."""
    alias = N * math.log10(1.0 / float(3 * rho))
    rnd = dps - k * math.log10(1.0 / float(rho))
    return alias, rnd, min(alias, rnd)


def _beps_cuts(dps):
    """The quadrature split: BESSEL_EPS_CUTS, extended by x3/2 steps until e^(-4 r_max) < 10^-(dps + TAIL_GUARD) (the integrand
    decays as r K_eps(r)^4 ~ e^(-4r); at dps <= 66 the record's split is used as it stands)."""
    cuts = [mpf(c.numerator) / c.denominator if isinstance(c, Fraction) else mpf(c) for c in BESSEL_EPS_CUTS]
    rmax = (dps + TAIL_GUARD) * math.log(10.0) / 4.0
    while cuts[-1] < rmax:
        cuts.append(cuts[-1] * 3 / 2)
    return cuts


def _beps_kernel(a, eps, sign):
    """The integrand of (R) without the 2^(3-3eps) factor: r^(1+2eps) (a r)^eps J_(sign eps)(a r) K_eps(r)^4 for a > 0; at a = 0
    (t = 0) its limit 2^eps/Gamma(1-eps) r^(1+2eps) K_eps(r)^4 (the vacuum banana of --bessel; no J, so no sign)."""
    if a == 0:
        pref = mpf(2) ** eps / mp.gamma(1 - eps)
        return lambda r: mpf(0) if r == 0 else pref * r ** (1 + 2 * eps) * mp.besselk(eps, r) ** 4
    return lambda r: mpf(0) if r == 0 else r ** (1 + 2 * eps) * (a * r) ** eps * mp.besselj(sign * eps, a * r) * mp.besselk(eps, r) ** 4


def _beps_value(a, eps, sign, cuts):
    """m1(t; eps) by (R) at one (complex) eps: tanh-sinh on the split; returns (value, the quadrature's error estimate)."""
    v, err = mp.quad(_beps_kernel(a, eps, sign), cuts, error=True)
    pref = mpf(2) ** (3 - 3 * eps)
    return pref * v, abs(pref) * err


def _beps_layers(a, K, N, rho, sign, cuts, tag):
    """c_0..c_K by the trapezoid rule on |eps| = rho with N nodes at the CURRENT working precision (nodes j and N - j are
    conjugate: N//2 + 1 quadratures).  Prints one progress line per node.  Returns (layers as mpc, node values, the largest
    quadrature error estimate, wall)."""
    import time
    t0 = time.perf_counter()
    vals = [None] * N
    errmax = mpf(0)
    for j in range(N // 2 + 1):
        e = rho * mp.expj(2 * mp.pi * j / N)
        tj = time.perf_counter()
        v, err = _beps_value(a, e, sign, cuts)
        vals[j] = v
        errmax = max(errmax, err)
        print("  [%s] node %2d/%d: eps = %-26s m1 = %s  (quadrature error estimate %s; %.1f s)"
              % (tag, j, N // 2, mp.nstr(e, 6), mp.nstr(v, 22), mp.nstr(err, 2), time.perf_counter() - tj))
    for j in range(N // 2 + 1, N):
        vals[j] = mp.conj(vals[N - j])
    cs = []
    for k in range(K + 1):
        s = mp.mpc(0)
        for j in range(N):
            s += vals[j] * (rho * mp.expj(2 * mp.pi * j / N)) ** (-k)
        cs.append(s / N)
    return cs, vals, errmax, time.perf_counter() - t0


def _beps_check_gates_pin(here):
    """banana-minkowski-gates.json present beside the script and sha256-equal to its CONT_PINS entry (exit 4 / 3 by name), as
    _cont_check_pins does for both --continue files; --bessel-eps reads this one file only."""
    import hashlib
    import os
    import sys
    name = "banana-minkowski-gates.json"
    want = CONT_PINS[name]
    p = os.path.join(here, name)
    if not os.path.isfile(p):
        print("MISSING data file %s (expected beside the script, sha256 %s...): exit 4" % (name, want[:16]))
        sys.exit(4)
    got = hashlib.sha256(open(p, "rb").read()).hexdigest()
    if got != want:
        print("PIN MISMATCH %s: sha256 %s... != pinned %s...: exit 3" % (name, got[:16], want[:16]))
        sys.exit(3)
    print("[pins] %s %s... (sha256 = CONT_PINS)" % (name, want[:16]))
    return p


def _beps_refs(t, K, here, cmp_dps):
    """The stored references the layers are gated against at t, {k: [(label, string, significant digits)]}, and a description.
    t <= -4: the Euclidean entries of banana-minkowski-gates.json (every leg, every stored order <= K; the record stores t = -8);
    -4 < t < 0: the 18-point record (HELDOUT18 at eps^0, HELDOUT18_EPS1 at eps^1) where t is one of its points;
    t = 0: 7 zeta_3 (written at cmp_dps digits) and alpha_1 = CONT_ALPHA1."""
    import json
    refs = {k: [] for k in range(K + 1)}
    desc = []
    ts = str(t)
    if t <= -4:
        p = _beps_check_gates_pin(here)
        G = json.load(open(p))
        pts = {**G["record_points"], **G.get("fresh_points", {})}
        lab = next((L for L, P in pts.items() if Fraction(P["t"]) == t), None)
        if lab is None:
            desc.append("no stored string at t = %s (the stored Euclidean point of banana-minkowski-gates.json is t = %s)"
                        % (ts, ", ".join(P["t"] for P in pts.values() if Fraction(P["t"]) < 0)))
        else:
            P = pts[lab]
            for ln, leg in P["legs"].items():
                od = leg["masters"]["m1"]["orders"]
                got = []
                for k in range(K + 1):
                    o = od.get(str(k))
                    if o is None:
                        continue
                    refs[k].append(("%s leg %s (goal %s, output %s...)" % (lab, ln, leg.get("goal_digits"), leg["output_sha256"][:12]), o["re"], int(o["re_digits"])))
                    got.append(k)
                desc.append("t = %s is %s of banana-minkowski-gates.json, leg %s: goal %s, m1 orders %s stored as %d-digit strings (Im 0), output %s..."
                            % (ts, lab, ln, leg.get("goal_digits"), ",".join(str(k) for k in got), od["0"]["re_digits"], leg["output_sha256"][:16]))
    elif t < 0:
        row0 = next((r for r in HELDOUT18 if Fraction(r[0]) == t), None)
        row1 = next((r for r in HELDOUT18_EPS1 if Fraction(r[0]) == t), None)
        if row0 is not None:
            refs[0].append(("HELDOUT18 %s (goal %d)" % (row0[1], row0[4]), row0[7], sum(c.isdigit() for c in row0[7])))
            desc.append("t = %s is a point of the 18-point record: eps^0 string %s (%d digits)" % (ts, row0[1], sum(c.isdigit() for c in row0[7])))
        if row1 is not None and K >= 1:
            refs[1].append(("HELDOUT18_EPS1 %s (goal %d)" % (row1[1], row1[4]), row1[6], sum(c.isdigit() for c in row1[6])))
            desc.append("eps^1 string %s (%d digits)" % (row1[1], sum(c.isdigit() for c in row1[6])))
        if row0 is None:
            desc.append("no stored string at t = %s (the Euclidean points of the 18-point record are t = %s); the eps^0 layer is gated against the closed form"
                        % (ts, ", ".join(r[0] for r in HELDOUT18 if Fraction(r[0]) < 0)))
    else:
        with mp.workdps(cmp_dps):
            z3s = mp.nstr(7 * zeta(3), cmp_dps)
        refs[0].append(("7 zeta_3 (at %d digits)" % cmp_dps, z3s, cmp_dps))
        desc.append("t = 0: the vacuum banana B(eps); eps^0 = 7 zeta_3 (exact), eps^1 = alpha_1 (CONT_ALPHA1, %d digits)" % CONT_ALPHA1_DIGITS)
        if K >= 1:
            refs[1].append(("alpha_1 = CONT_ALPHA1", CONT_ALPHA1, CONT_ALPHA1_DIGITS))
    return refs, desc


def bessel_eps_tier(t, K, dps, N, rho, here, planted=False, rho_label=None):
    """--bessel-eps K [--point T] [--dps D] [--N N] [--rho R] [--planted]: the layers m1[eps^0..eps^K](t) at a Euclidean point
    t <= 0 from the Bessel representation (R), two passes (dps and dps - BESSEL_EPS_DROP), the two-precision floor per layer,
    and the gates against every stored string at t (see the block comment above); rho a Fraction.  A FAIL is raised by name
    after the table (exit 1); --planted must FAIL on the eps^1 layer."""
    import sys
    import time
    t0 = time.perf_counter()
    sign = +1 if planted else -1
    dps2 = max(dps - BESSEL_EPS_DROP, 15)
    cmp_dps = dps + BESSEL_EPS_CMP_GUARD
    L = math.log10(1.0 / float(rho))
    A = N * math.log10(1.0 / float(3 * rho))
    rho_s = rho_label if rho_label is not None else str(rho)
    print("[representation] m1(t; eps) = 2^(3-3eps) int_0^oo r^(1+2eps) (a r)^eps J_(%seps)(a r) K_eps(r)^4 dr, a = sqrt(-t), d = 2 - 2 eps, "
          "measure d^dk/pi^(d/2) per loop, no exp(gamma_E eps)%s" % ("+" if planted else "-", "   [PLANTED: the order sign is flipped; the eps^1 layer must FAIL]" if planted else ""))
    if t == 0:
        print("[point] t = 0: the kernel's limit 2^eps/Gamma(1-eps) r^(1+2eps) K_eps(r)^4, i.e. B(eps) of --bessel")
    else:
        print("[point] t = %s (a = sqrt(%s)); Euclidean, %s" % (t, -t, "inside the MUM disk" if t > -4 else "outside the MUM disk (|t| >= 4)"))
    print("[extraction] c_k = m1[eps^k](t), k = 0..%d, by the trapezoid rule on |eps| = %s with N = %d nodes (%d quadratures per pass); "
          "analytic radius 1/3 in eps; a-priori budget per layer min(aliasing %d log10(1/(3 rho)) = %.1f d, roundoff dps - k log10(1/rho) = %d - %.1f k)"
          % (K, rho_s, N, N // 2 + 1, N, A, dps, L))
    if dps - A > 20:
        print("  (aliasing-limited: at rho = %s, N >= %d nodes would let the layers carry dps = %d digits)" % (rho_s, int(math.ceil(dps / math.log10(1.0 / float(3 * rho)))), dps))
    refs, desc = _beps_refs(t, K, here, cmp_dps)
    for d_ in desc:
        print("[stored] " + d_)
    has_eps1_ref = K >= 1 and len(refs.get(1, [])) > 0 and t != 0
    if planted and not has_eps1_ref:
        print("REFUSED (exit 2): --planted flips the sign of the Bessel J order and is caught by the eps^1 gate; it needs K >= 1 and a "
              "point with a stored eps^1 string (t = -8, or the Euclidean points of the 18-point record t = -7/2, -3); t = 0 has no J at all")
        sys.exit(2)
    with mp.workdps(dps):
        cuts = _beps_cuts(dps)
        print("[quadrature] tanh-sinh on the split %s (r_max = %s: e^(-4 r_max) = 1e-%.0f); pass 1 at dps %d, pass 2 at dps %d; comparisons at dps %d"
              % ([mp.nstr(c, 4) for c in cuts], mp.nstr(cuts[-1], 4), float(4 * cuts[-1] / mp.log(10)), dps, dps2, cmp_dps))
        rho1 = mpf(rho.numerator) / rho.denominator
        a1 = mp.sqrt(-(mpf(t.numerator) / t.denominator)) if t != 0 else mpf(0)
        cs1, vals1, err1, w1 = _beps_layers(a1, K, N, rho1, sign, cuts, "pass 1, dps %d" % dps)
        im1 = max(abs(mp.im(c)) / max(abs(c), mpf(1)) for c in cs1)
    print("  pass 1: %d quadratures, wall %.2f s, largest quadrature error estimate %s, largest |Im c_k| / max(|c_k|, 1) = %s (the layers are real; "
          "the imaginary parts are roundoff of the node sum)" % (N // 2 + 1, w1, mp.nstr(err1, 2), mp.nstr(im1, 2)))
    with mp.workdps(dps2):
        cuts2 = _beps_cuts(dps2)
        rho2 = mpf(rho.numerator) / rho.denominator
        a2 = mp.sqrt(-(mpf(t.numerator) / t.denominator)) if t != 0 else mpf(0)
        cs2, vals2, err2, w2 = _beps_layers(a2, K, N, rho2, sign, cuts2, "pass 2, dps %d" % dps2)
    print("  pass 2: %d quadratures, wall %.2f s, largest quadrature error estimate %s" % (N // 2 + 1, w2, mp.nstr(err2, 2)))
    fails = []
    rows = []
    with mp.workdps(cmp_dps):
        print("-- the layers m1[eps^k](t = %s), k = 0..%d%s --" % (t, K, " [PLANTED]" if planted else ""))
        print("%-2s | %-33s | %-22s | %-24s | %-60s | %s" % ("k", "m1[eps^k] (%d d)" % BESSEL_EPS_SHOW, "budget d (alias/round)", "two-precision d (bar)", "vs stored: d (bar) [source]", "verdict"))
        for k in range(K + 1):
            ck = mp.re(cs1[k])
            al, rn, bud = _beps_budget(dps, N, rho, k)
            al2, rn2, bud2 = _beps_budget(dps2, N, rho, k)
            d2 = _cont_digits_cc(mp.mpc(ck), mp.mpc(mp.re(cs2[k])))
            d2f = mp.inf if d2 is None else d2
            bar2 = bud2 - REF_MARGIN
            ok = True
            if not (d2f >= bar2):
                ok = False
                fails.append("k = %d two-precision floor (%.1f d < %.1f d)" % (k, d2f, bar2))
            cells = []
            for (label, s, nd) in refs.get(k, []):
                d = agree_digits(ck, s)
                bar = min(bud, float(nd)) - REF_MARGIN
                shown = min(float(d), float(nd), float(cmp_dps)) if d != mp.inf else float(min(nd, cmp_dps))
                good = float(d) >= bar
                cells.append("%.1f (%.1f) [%s]%s" % (shown, bar, label, "" if good else " FAIL"))
                if not good:
                    ok = False
                    fails.append("k = %d vs %s (%.1f d < %.1f d)" % (k, label, float(d), bar))
            if t > -4 and t < 0 and k == 0:
                v_cf = m1_eps0(t, dps=dps)
                dcf = _cont_digits_cc(mp.mpc(ck), mp.mpc(v_cf))
                dcff = mp.inf if dcf is None else dcf
                bar = bud - REF_MARGIN
                good = dcff >= bar
                cells.append("%.1f (%.1f) [the closed form m1_eps0, this script's disk tier]%s" % (min(float(dcff), float(cmp_dps)), bar, "" if good else " FAIL"))
                if not good:
                    ok = False
                    fails.append("k = 0 vs the closed form (%.1f d < %.1f d)" % (dcff, bar))
            print("%-2d | %-33s | %5.1f (%5.1f / %5.1f)  | %-24s | %-60s | %s" % (
                k, mp.nstr(ck, BESSEL_EPS_SHOW), bud, al, rn,
                "%s (%.1f)" % ("identical" if d2 is None else "%.1f" % d2, bar2),
                "; ".join(cells) if cells else "(no stored string at this point)", "PASS" if ok else "FAIL"))
            rows.append((k, ck, bud))
        print("-- the layers cut to their a-priori budget (digits beyond it are not claimed) --")
        for k, ck, bud in rows:
            shown_k = mp.nstr(ck, max(2, int(bud)), strip_zeros=False)   # trailing zeros kept: the string carries exactly its budget of significant digits
            print("  m1[eps^%d](%s) = %s   (%d digits)" % (k, t, shown_k, sum(c.isdigit() for c in shown_k.partition("e")[0].lstrip("-0."))))
        sg = " ".join("-" if mp.re(cs1[k]) < 0 else "+" for k in range(K + 1))
        print("  signs of the layers: %s (%s)" % (sg, "alternating" if all((mp.re(cs1[k]) < 0) == (k % 2 == 1) for k in range(K + 1)) else "not alternating"))
    wall = time.perf_counter() - t0
    nref = sum(len(v) for v in refs.values()) + (1 if (t > -4 and t < 0) else 0)
    if fails:
        print("VERDICT --bessel-eps (t = %s, K = %d, dps %d, N %d, rho %s%s): FAIL at %s" % (t, K, dps, N, rho_s, ", PLANTED" if planted else "", "; ".join(fails)))
        print("--bessel-eps wall time: %.2f s (pass 1 %.2f s, pass 2 %.2f s)" % (wall, w1, w2))
        raise RuntimeError("banana RAISING gate FAILED (fail-closed): --bessel-eps at t = %s: %s" % (t, "; ".join(fails)))
    print("VERDICT --bessel-eps (t = %s, K = %d, dps %d, N %d, rho %s): %d/%d layers PASS; %s"
          % (t, K, dps, N, rho_s, K + 1, K + 1,
             ("%d stored-string / closed-form comparisons, each above min(budget, string digits) - %d; the two-precision floor above the second pass's budget - %d at every layer" % (nref, REF_MARGIN, REF_MARGIN))
             if nref else ("no stored string at this point: the two-precision floor above the second pass's budget - %d at every layer is the only gate" % REF_MARGIN)))
    print("--bessel-eps wall time: %.2f s (pass 1 %.2f s, pass 2 %.2f s)" % (wall, w1, w2))


if __name__ == "__main__":
    import argparse
    import os
    import time

    ap = argparse.ArgumentParser(
        description="3-loop equal-mass banana m1 at eps^0 (K3 closed form). "
                    "Domain: MUM disk |t| < 4, t = p^2/m^2; --continue reaches |t| >= 4 (t -> t + i0).")
    ap.add_argument("--point", help="kinematic point t as a rational or decimal; "
                                    "write --point=-7/2 for negative t; "
                                    "default: run the 3-point gate demo")
    try:  # let bare '--point -7/2' parse too (rational starting with '-')
        import re
        ap._negative_number_matcher = re.compile(r'^-\d+(/\d+)?(\.\d+)?$')
    except Exception:
        pass  # '--point=-7/2' form always works
    ap.add_argument("--dps", type=int, default=None, help="decimal precision (default 130; %d for --bessel-eps, whose default N and rho "
                    "cap the layers at 42 digits: raise --N with --dps there)" % BESSEL_EPS_DPS)
    ap.add_argument("--heldout18", action="store_true",
                    help="evaluate all 18 points of the record and gate each against its stored "
                         "string (110-140 digits) at --dps; a FAIL is named and exits 1")
    ap.add_argument("--mutate-heldout18", metavar="T[:K]",
                    help="the shipped control for --heldout18: significant digit K (default 80; an integer, "
                         "1 <= K <= the string's significant digits, else refused with exit 2) of the "
                         "stored string at point T (as in the table, e.g. =-3, 1/2, or its label T02) "
                         "incremented in memory -> that row FAILs by name, exit 1; write --mutate-heldout18=-3:80")
    ap.add_argument("--continue", dest="continue_", action="store_true",
                    help="continue the closed form past the disk to --point T (|t| >= 4; t -> t + i0) and gate it "
                         "against the stored auxiliary-mass-flow values where the point is stored (t = -8, 5, 8, 10, 12, 31/2, "
                         "18, 20, 25, 40, 100, 200); |t| < 4 runs the in-disk control; needs banana-graded-system.json and "
                         "banana-minkowski-gates.json beside the script (sha256-pinned: exit 3 / 4)")
    ap.add_argument("--mutate", action="store_true",
                    help="the shipped control of --continue: significant digit %d of the stored point's m1[eps^0] real-part "
                         "string incremented in memory -> the gate FAILs by name, exit 1" % CONT_MUTATE_DIGIT)
    ap.add_argument("--lower-as-physical", action="store_true",
                    help="the planted-sign control of --continue: the lower detour (t - i0, the complex conjugate) offered "
                         "as the physical value -> at a stored point above the threshold the gate FAILs by name on Im, exit 1")
    ap.add_argument("--eps1", action="store_true",
                    help="the eps^1 layer m1[eps^1](t) = alpha_1 varpi_0(t) + Part^(1)(t) of the same recursion at every point of "
                         "the 18-point record (or at --point T, |t| < 4), gated against the stored eps^1 strings at bar "
                         "min(dps, string digits, %d) - %d; a FAIL is named and exits 1; needs banana-graded-system.json and "
                         "banana-eps1-words.json beside the script (sha256-pinned: exit 3 / 4)" % (CONT_ALPHA1_DIGITS, REF_MARGIN))
    ap.add_argument("--mutate-eps1", metavar="T[:K]",
                    help="the shipped control for --eps1: significant digit K (default %d; an integer, 1 <= K <= the string's "
                         "significant digits, else refused with exit 2) of the stored eps^1 string at point T (as in the table, "
                         "e.g. =-3, 1/2, or its label T07) incremented in memory -> that row FAILs by name, exit 1" % EPS1_MUTATE_DIGIT)
    ap.add_argument("--bessel", action="store_true",
                    help="alpha_1 = m1[eps^1](0) recomputed live by quadrature at --dps (the Bessel moments int r K_0^4 and "
                         "int r ln r K_0^4), gated against the stored %d-digit string and 7 zeta_3; minutes at the default dps" % CONT_ALPHA1_DIGITS)
    ap.add_argument("--bessel-eps", type=int, metavar="K",
                    help="the layers m1[eps^0..eps^K](t) at a Euclidean point t <= 0 (default t = %s; --point=T) from the exact-in-d "
                         "Bessel representation 2^(3-3eps) int r^(1+2eps) (a r)^eps J_(-eps)(a r) K_eps(r)^4 dr, a = sqrt(-t), read off the "
                         "circle |eps| = --rho with --N trapezoid nodes at --dps, a second pass at dps - %d for the two-precision floor; "
                         "gated against every stored string at t (t = -8: eps^0..eps^5 of banana-minkowski-gates.json, needed beside the "
                         "script, sha256-pinned, exit 3 / 4; t = -7/2, -3: the eps^0 / eps^1 strings of the 18-point record; t = 0: 7 zeta_3 "
                         "and alpha_1; -4 < t < 0: the closed form at eps^0); t > 0 is refused (exit 2); the cost is N+2 complex-order "
                         "quadratures at dps and at dps - %d" % (BESSEL_EPS_T, BESSEL_EPS_DROP, BESSEL_EPS_DROP))
    ap.add_argument("--N", type=int, default=None, help="--bessel-eps: trapezoid nodes on the eps-circle (default %d)" % BESSEL_EPS_N)
    ap.add_argument("--rho", default=None, help="--bessel-eps: the circle radius |eps| = rho (default %s; a rational or decimal, 0 < rho < 1/3)" % BESSEL_EPS_RHO)
    ap.add_argument("--planted", action="store_true",
                    help="the control of --bessel-eps: J_(+eps) in place of J_(-eps) -> the eps^1 layer FAILs by name, exit 1 "
                         "(needs K >= 1 and a point with a stored eps^1 string: t = -8, -7/2, -3)")
    args = ap.parse_args()
    if args.dps is None:   # 2026-09-11: the default precision resolves per mode (130 everywhere as before; BESSEL_EPS_DPS for --bessel-eps)
        args.dps = BESSEL_EPS_DPS if args.bessel_eps is not None else 130
    if args.bessel_eps is not None:
        if args.N is None:      # --N / --rho take their defaults here, so that either one given without --bessel-eps is refused by name below
            args.N = BESSEL_EPS_N
        if args.rho is None:
            args.rho = BESSEL_EPS_RHO
        if args.continue_ or args.heldout18 or args.mutate_heldout18 is not None or args.eps1 or args.mutate_eps1 is not None or args.bessel or args.mutate or args.lower_as_physical:
            ap.error("--bessel-eps is a mode of its own (with --point, --dps, --N, --rho, --planted); --continue, --heldout18, --eps1, --bessel and their controls are other modes")
        if args.bessel_eps < 0:
            ap.error("--bessel-eps K: K >= 0 (the highest eps-layer)")
        _tb = Fraction(args.point) if args.point is not None else Fraction(BESSEL_EPS_T)
        if _tb > 0:
            ap.error("--bessel-eps: t = %s > 0 refused; the Euclidean axis t <= 0 only. For 0 < t the kernel (a r)^eps J_(-eps)(a r) continues to "
                     "(sqrt(t) r)^eps I_(-eps)(sqrt(t) r) and above the threshold the integral needs its own prescription; neither is carried "
                     "by this tier (the physical region is --continue's)" % args.point)
        try:
            _rb = Fraction(args.rho)
        except (ValueError, ZeroDivisionError):
            ap.error("--rho: a rational or decimal, e.g. 1e-4 or 1/10000; got %r" % args.rho)
        if not (0 < _rb < BESSEL_EPS_RADIUS):
            ap.error("--rho = %s is outside 0 < rho < 1/3 (the eps-radius of analyticity of the representation)" % args.rho)
        if args.N < 2 or args.N <= args.bessel_eps:
            ap.error("--N = %d: the trapezoid rule needs N >= 2 and N > K = %d (layer k aliases with layer k + N)" % (args.N, args.bessel_eps))
        if args.dps < 20:
            ap.error("--bessel-eps: --dps >= 20")
        _ab, _rn, _bud = _beps_budget(args.dps, args.N, _rb, args.bessel_eps)
        if _bud < BESSEL_EPS_MIN_BUDGET:
            ap.error("--bessel-eps: the a-priori budget of layer K = %d at dps %d, N %d, rho %s is %.1f d (aliasing N log10(1/(3 rho)) = %.1f d, "
                     "roundoff dps - K log10(1/rho) = %.1f d) < %d d: raise --dps against roundoff, --N against aliasing, or lower K"
                     % (args.bessel_eps, args.dps, args.N, args.rho, _bud, _ab, _rn, BESSEL_EPS_MIN_BUDGET))
    elif args.planted:
        ap.error("--planted is the control of --bessel-eps; give --bessel-eps K too")
    elif args.N is not None or args.rho is not None:
        ap.error("%s given without --bessel-eps: --N and --rho set the eps-circle extraction of --bessel-eps only (trapezoid nodes, "
                 "circle radius); give --bessel-eps K too" % " and ".join(n for n, v in (("--N", args.N), ("--rho", args.rho)) if v is not None))
    if args.eps1 and (args.continue_ or args.heldout18 or args.mutate_heldout18 is not None or args.bessel):
        ap.error("--eps1 is a mode of its own; --continue, --heldout18 and --bessel are others; choose one")
    if args.bessel and (args.continue_ or args.heldout18 or args.mutate_heldout18 is not None or args.point is not None):
        ap.error("--bessel takes --dps only (the constant is alpha_1 = m1[eps^1](0)); --point, --continue and --heldout18 are other modes")
    if (args.mutate or args.lower_as_physical) and args.eps1:
        ap.error("--mutate and --lower-as-physical are the controls of --continue; the control of --eps1 is --mutate-eps1 T[:K]")
    if args.mutate_eps1 is not None and not args.eps1:
        ap.error("--mutate-eps1 is the control of --eps1; give --eps1 too")
    if args.eps1 and args.point is not None:
        _te = Fraction(args.point)
        if abs(_te) >= 4:
            ap.error("t = %s is outside the MUM disk |t| < 4, where the recursion of --eps1 does not converge; past the disk the "
                     "eps^1 layer is carried and gated by the continuation tier: --continue --point %s" % (args.point, args.point))
    if args.eps1 and args.mutate_eps1 is not None and args.point is not None:
        ap.error("--mutate-eps1 plants a digit in the 18-point table; it does not combine with --point")
    if args.mutate_eps1 is not None:
        _tm1, _, _k1 = args.mutate_eps1.partition(":")
        _row1 = next((r for r in HELDOUT18_EPS1 if r[0] == _tm1 or r[1].split("_")[0] == _tm1), None)
        if _row1 is None:
            ap.error("--mutate-eps1: no record point %r (give t as in the table, e.g. =-3, 1/2, or its label, e.g. T07)" % _tm1)
        _nsig1 = sum(c.isdigit() for c in _row1[6].lstrip("-0."))
        try:
            _k1 = int(_k1) if _k1 else EPS1_MUTATE_DIGIT
        except ValueError:
            ap.error("--mutate-eps1: K must be an integer, a significant digit 1..%d of the t = %s stored eps^1 string; got %r" % (_nsig1, _row1[0], _k1))
        if not 1 <= _k1 <= _nsig1:
            ap.error("--mutate-eps1: K = %d is outside 1..%d, the significant digits of the t = %s stored eps^1 string" % (_k1, _nsig1, _row1[0]))
    if args.continue_ and args.point is None:
        ap.error("--continue needs --point T (a rational; write --point=-8 for negative t)")
    if args.continue_ and (args.heldout18 or args.mutate_heldout18 is not None):
        ap.error("--continue and --heldout18 are two modes; choose one")
    if (args.mutate or args.lower_as_physical) and not args.continue_:
        ap.error("--mutate and --lower-as-physical are the controls of --continue; give --continue too")
    if args.continue_:
        _tc = Fraction(args.point)
        if _tc in CONT_SINGULAR:
            ap.error("t = %s is a singular point of the system (t = 0 the MUM point, t = 4 the pseudo-threshold, t = 16 the "
                     "threshold): the continuation lands only off them" % args.point)
        if args.lower_as_physical and _tc <= 16:
            ap.error("--lower-as-physical needs a stored point above the threshold (t > 16): below it the continued value is "
                     "real and the lower detour equals the upper")
    if args.heldout18 and args.point is not None:
        ap.error("--heldout18 and --point are two modes; choose one")
    if args.mutate_heldout18 is not None and not args.heldout18:
        ap.error("--mutate-heldout18 is the control of --heldout18; give --heldout18 too")
    if args.mutate_heldout18 is not None:
        _tm, _, _k = args.mutate_heldout18.partition(":")
        _row = next((r for r in HELDOUT18 if r[0] == _tm or r[1].split("_")[0] == _tm), None)
        if _row is None:
            ap.error("--mutate-heldout18: no record point %r (give t as in the table, e.g. =-3, 1/2, or its label, e.g. T02)" % _tm)
        _nsig = sum(c.isdigit() for c in _row[7].lstrip("0."))   # the significant digits of the stored string, as _flip_digit counts them
        try:
            _k = int(_k) if _k else 80
        except ValueError:
            ap.error("--mutate-heldout18: K must be an integer, a significant digit 1..%d of the t = %s stored string; got %r" % (_nsig, _row[0], _k))
        if not 1 <= _k <= _nsig:
            ap.error("--mutate-heldout18: K = %d is outside 1..%d, the significant digits of the t = %s stored string" % (_k, _nsig, _row[0]))

    print("m1_eps0(t) = 7*zeta_3*varpi_0(t) - Part_reg(t)   (d=2-2eps, m^2=1)")

    if args.eps1:
        print("-- --eps1: the eps^1 layer on the MUM disk, m1[eps^1](t) = alpha_1 varpi_0(t) + Part^(1)(t)%s, dps %d --"
              % ((", t = %s" % args.point) if args.point is not None else " at the 18 points of the record", args.dps))
        eps1_gate(args.dps, os.path.dirname(os.path.abspath(__file__)),
                  point=(Fraction(args.point) if args.point is not None else None),
                  mutate=((_tm1, _k1) if args.mutate_eps1 is not None else None))
    elif args.bessel:
        print("-- --bessel: alpha_1 = m1[eps^1](0) by quadrature, dps %d (working dps %d) --" % (args.dps, args.dps + EPS1_BESSEL_GUARD))
        bessel_tier(args.dps)
    elif args.bessel_eps is not None:
        print("-- --bessel-eps: the layers m1[eps^0..eps^%d](t) from the exact-in-d Bessel representation, t = %s, dps %d, N %d, rho %s%s --"
              % (args.bessel_eps, _tb, args.dps, args.N, args.rho, " [PLANTED]" if args.planted else ""))
        bessel_eps_tier(_tb, args.bessel_eps, args.dps, args.N, _rb, os.path.dirname(os.path.abspath(__file__)), planted=args.planted, rho_label=args.rho)
    elif args.continue_:
        print("-- --continue: the closed form past the disk (t -> t + i0), t = %s, dps %d --" % (args.point, args.dps))
        continue_tier(Fraction(args.point), args.dps, os.path.dirname(os.path.abspath(__file__)),
                      lower_as_physical=args.lower_as_physical, mutate=args.mutate)
    elif args.heldout18:
        mut = (_tm, _k) if args.mutate_heldout18 is not None else None   # validated above: the point is in the table, 1 <= K <= its significant digits
        heldout18_gate(args.dps, mutate=mut)
    elif args.point is not None:
        tfrac = Fraction(args.point)
        if abs(tfrac) >= 4:
            ap.error("t = %s is outside the MUM disk |t| < 4, where the series do not converge; the point is reached by "
                     "the continuation tier: --continue --point %s" % (args.point, args.point))
        t0 = time.perf_counter()
        val, bound, n = m1_eps0(tfrac, dps=args.dps, full_output=True)
        wall = time.perf_counter() - t0
        tail_d = n * (-math.log10(abs(float(tfrac)) / 4)) if tfrac != 0 else mp.inf
        print(f"t = {args.point}, dps = {args.dps}, {n} series terms "
              f"(a-priori tail < 1e-{tail_d:.0f})")
        print(f"  m1_eps0 = {mp.nstr(val, args.dps)}")
        with mp.workdps(8):
            print(f"  [certified] trailing-{TAIL_WINDOW}-window tail bound "
                  f"{mp.nstr(bound, 3)} < tol 1e-{args.dps + TAIL_GUARD} "
                  f"(accepted N={n}, seed cap {TAIL_NCAP}x; raises, never "
                  f"truncates silently)")
        if args.point in REFS:
            ref, rec_d = REFS[args.point]
            nref = sum(c.isdigit() for c in ref)
            with mp.workdps(args.dps + GUARD):
                d = agree_digits(val, ref)
            shown, cap, which = printed_agreement(d, nref, args.dps)
            print(f"  agreement: {shown:.1f} d vs {nref}-digit stored ref "
                  f"(cap {cap:.0f} d = {which}; the record's own comparison at its dps 120: {rec_d} d)")
            thr = min(args.dps, nref) - REF_MARGIN
            _raise_gate("stored-ref agreement (t=%s)" % args.point, float(d), thr)
            print(f"  [gate] stored-ref agreement RAISING gate PASS "
                  f"({_fmt_d(d)} d >= {thr:.1f} d)")
        else:
            print("  (no stored reference at this point; gate refs live at t = -3, -7/2, 1/2)")
        print(f"  wall time: {wall:.2f} s")
    else:
        # ---- gate demo (default): the 3 held-out AMFlow-anchored points ----
        # (agreement is a RAISING gate since 2026-07-05, not a printed comparison)
        print(f"dps={args.dps}, series terms chosen per point\n")
        t0 = time.perf_counter()
        for ts, (ref, rec_d) in REFS.items():
            nref = sum(c.isdigit() for c in ref)
            val, bound, nacc = m1_eps0(Fraction(ts), dps=args.dps, full_output=True)
            with mp.workdps(args.dps + GUARD):
                d = agree_digits(val, ref)
            shown, cap, which = printed_agreement(d, nref, args.dps)
            print(f"t = {ts}")
            print(f"  this work : {mp.nstr(val, 60)}")
            print(f"  reference : {ref}  (AMFlow-anchored, held out)")
            print(f"  agreement : {shown:.1f} d vs {nref}-digit stored ref "
                  f"(cap {cap:.0f} d = {which}; the record's own comparison at its dps 120: {rec_d} d)")
            thr = min(args.dps, nref) - REF_MARGIN
            _raise_gate("stored-ref agreement (t=%s)" % ts, float(d), thr)
            with mp.workdps(8):
                print(f"  [certified] tail bound {mp.nstr(bound, 3)} < tol "
                      f"1e-{args.dps + TAIL_GUARD} (N={nacc})   [gate] agreement "
                      f"RAISING gate PASS ({_fmt_d(d)} >= {thr:.1f} d)\n")
        print(f"gate demo wall time: {time.perf_counter() - t0:.2f} s")

        # ---- dps-doubling RAISING gate: same point, 2x precision ----
        # (was a printed comparison; promoted to fail-closed gates 2026-07-05:
        #  digits must track dps and both runs must hit the stored oracle)
        ts = "-3"
        ref, rec_d = REFS[ts]
        nref = sum(c.isdigit() for c in ref)
        d1, d2 = args.dps, 2 * args.dps
        v1 = m1_eps0(Fraction(ts), dps=d1)
        t0 = time.perf_counter()
        v2 = m1_eps0(Fraction(ts), dps=d2)
        wall2 = time.perf_counter() - t0
        with mp.workdps(d2 + GUARD):
            a1 = agree_digits(v1, ref)
            a2 = agree_digits(v2, ref)
            self_d = float(-log10(fabs(v2 - v1) / fabs(v2)))
        print(f"\n-- dps-doubling check (t = {ts}, dps {d1} -> {d2}) --")
        s1, c1, w1 = printed_agreement(a1, nref, d1)
        s2, c2, w2 = printed_agreement(a2, nref, d2)
        print(f"  vs stored oracle string : {s1:.1f} d -> {s2:.1f} d "
              f"(printed figures capped at {c1:.0f} / {c2:.0f} d by {w1} / {w2}; "
              f"the record's own comparison at its dps 120: {rec_d} d)")
        print(f"  live self-agreement dps{d1} vs dps{d2}: {self_d:.1f} d "
              f"-> doubling dps grows the computed digits past the stored-string cap")
        thr1 = min(d1, nref) - REF_MARGIN
        thr2 = min(d2, nref) - REF_MARGIN
        thr_self = d1 + SELF_MARGIN
        _raise_gate("doubling check vs stored ref at dps %d" % d1, float(a1), thr1)
        _raise_gate("doubling check vs stored ref at dps %d" % d2, float(a2), thr2)
        _raise_gate("dps-doubling self-agreement", self_d, thr_self,
                    detail="digits must track dps: the dps %d run must carry "
                           ">= dps+%d certified digits" % (d1, SELF_MARGIN))
        print(f"  [gate] dps-doubling RAISING gates PASS: vs-ref {_fmt_d(a1)}/"
              f"{_fmt_d(a2)} d >= {thr1:.1f}/{thr2:.1f} d; self-agreement "
              f"{self_d:.1f} d >= dps+{SELF_MARGIN} = {thr_self:.1f} d")
        print(f"  wall time (one point at dps {d2}): {wall2:.2f} s")
