#!/usr/bin/env python3
r"""LBL3SE (QED light-by-light box (x) 2-loop kite self-energy) -- COMPLIANT
final form, computed at runtime.  Deps: python3 + mpmath (pip) + the sibling
kite_de_exact_parse.py (the exact parser of the shipped connection; no sympy).

FINAL FORM (one-fold over closed-form kernels in the internal mass variable):

    I(s,t,m^2) = (1/pi) \int_{m^2}^{inf} dw  K(s,t;w) * rho(w),

  [K]    K(s,t;w) = Box1(s,t; m^2,m^2,m^2, M^2=w), the one-loop massive box in
         its CLOSED dilogarithmic 1-dim form (4-root partial fractions + one
         fixed Gauss-Legendre rule; every value computed here from (s,t,m2,w)).
  [rho]  rho(w) = -Im J_top(w+i0), the discontinuity of the eps^0 kite-family
         TOP master J[1,1,1,1,1].  It is NOT a stored table: it is evaluated at
         runtime, to the requested precision, as a Picard-Fuchs / IBP-connection
         SERIES SOLUTION -- the exact rational 8x8 system d/dw J = A(w,d) J
         (lbl3se-kite-de.json) is eps-graded and solved by adaptive local
         Taylor series along (1,inf), seeded once at w=5.  The elliptic content
         is the equal-mass sunrise 2x2 block of A (Gamma_1(6), cusps {0,1,9,inf});
         the singular expansions at the cusps w=1 (turn-on ~ -2pi*(w-1)log(w-1),
         coefficient CLOSED FORM) and w=9 (finite jump) are the Eichler-word
         data of that curve.  All non-elliptic kite masters have Gamma/2F1
         closed forms, and this script VERIFIES the transported masters against
         them live (section [4]) -- exhibiting the IBP-onto-kite-masters
         structure explicitly.
  [rho closed form] (2026-09-11) the same density written out in closed
         form -- the write-up's eqs. (rho_elem), (rho_full), (F23); m^2 = 1:
           rho(w) = -(pi/w) [2 ln(w-1) ln w + 3 Li2(1-w)]           1 < w <= 9
           rho(w) = the same - (1/w) int_9^w v F23(v) dv             w > 9
           F23(v) = [2 Im S(v) - (v+3) Im Sdot(v)] / (v (v-1)^2),
           Im S / Im Sdot = the d=4 equal-mass sunrise three-body cut and
           the dotted-sunrise cut, one-folds over s in [4, (sqrt v - 1)^2]
         (the formulas in full in the block comment of section C2 below).
         THIS is the density the script evaluates by default at the density
         gate points w = 5, 12, 100, in every tier (the fast-start tier
         included: seconds), gated against the AMFlow solve_integrals
         references at the served floors; the series solution of [rho]
         (which the dispersion quadrature consumes -- the value path of the
         integrals is unchanged) is printed beside as the cross-check and
         the agreement of the two densities gated at the rho self-check bar.
         --density series prints the series density alone (the behaviour
         before 2026-09-11); --sum-rule checks the large-l^2 normalisation
         (1/pi) int_1^inf rho dw = 6 zeta_3 on the closed form at a finite
         cutoff W (default 1e50), the no-tail residual gated against the
         cutoff's own truncation (the omitted tail (4 ln W + 10)/W of the
         sum, 4.7e-48 at W = 1e50; the bar capped at the inner working
         precision) and the tail-restored residual against the inner
         working precision (a cutoff too low for a raised --dps, i.e. whose
         next omitted tail (4 ln W + 8)/W^2 does not clear that precision,
         is refused by name).
  [quad] singularity-subtracted tanh-sinh dispersion quadrature: the w=1
         turn-on model A1*(w-1)*log(w-1), A1 = -2*pi (closed form), is
         subtracted and added back as exact power-log moments x kernel-Taylor
         coefficients; panel break at the w=9 Gamma_1(6) cut; mapped real tail.

ARBITRARY PRECISION: there is no numeric node cache anywhere.  Precision is set
by QUAD_DPS/LEVEL/DPS/NORD (env vars): more quadrature levels, more series
terms, smaller truncation guards.  The guards (U_MIN at the w=1 cusp, V_MIN at
the w=9 cusp, W_MAX for the tail) are DERIVED from QUAD_DPS with printed
bounds, and shrink automatically as QUAD_DPS is raised.
SERVED PRECISION RANGE AND ITS CAP (2026-09-06, Q20f; measured, not lifted
here): the closed dilog-box kernel's far tail (BoxKernel._tail) relaxes the
box quadrature to a floor of 18 digits (work 36) past w ~ 1e18; its four-root
partial fraction then resolves 1/M5 only to (36 - log10 w) digits, so the kernel's
tail accuracy, summed over the tail nodes it multiplies, is 4.7e-58 at dps 55
(target 1e-55), 2.2e-61 at dps 60, 3.8e-64 at dps 66, 3.6e-65 at dps 68,
1.6e-66 at dps 70 and 6.1e-72 at dps 80 -- from dps ~62 on it exceeds
10^-QUAD_DPS, so the true accuracy of the value is capped near 1e-62..1e-66
there, whatever --dps says (the printed TOTAL bound does not carry this term).
Past w ~ 1e37.5 that floor returned NaN (log 0 in the partial fraction), which
every --dps >= 72 reached (W_MAX = 10^(dps//2+2)); cured 2026-09-06 by a dps
floor of ceil(log10 w) + 12 at w >= 1e36 (the tail is finite and resolved to
30 relative digits there; nothing below 1e36 changed, so every documented tier
<= dps 55 is byte-identical).  Documented tiers (dps 40, 45, 55) sit below the
cap; digits past ~62 are not claimed at any --dps until a later cure lifts the
relaxation below the onset.

INPUT DATA (same dir; provenance <archive>/phys_lbl3se):
  lbl3se-kite-de.json          exact rational 9x9 connection A(w,d) (Kira IBP,
                               reconstructed from 43 diffeq samples, max
                               validation diff 0) <- numeric/kite_de_symbolic.json
  lbl3se-w5-derived.json       the single transport SEED: eps-Laurent of the
                               kite masters at w=5, DERIVED AMFlow-free
                               (p^2=0 vacuum closed forms + Frobenius at w=0 +
                               exact-DE Taylor march; emitted once at dps 80 by
                               lbl3se-w5-seed.py in this directory -- rerun it
                               with --dps N --json to regenerate at any
                               precision, or pass --boundary-recompute [DPS]
                               to THIS script to do that inline: the stored
                               strings then demote to a byte-agreement
                               fast-start cache).  The whole pipeline is now
                               free of AMFlow inputs; AMFlow artifacts appear
                               only as held-out oracles.
  lbl3se-kite-boundary-w5.json the RETIRED AMFlow w=5 seed (solve_integrals,
                               goal_digits=140) <- numeric/amflow_kite_bnd_w5_out.json
                               Kept as a held-out cross-check only: the run
                               prints the recomputed derived-vs-AMFlow seed
                               agreement; it is never consumed upstream.

HELD-OUT ORACLES (class (a) literals, byte-traced to banked artifacts, never
used in the computation; agreement is RECOMPUTED live as -log10|f-o|/|o|):
  GT_AMF      full LBL3SE at (s,t,m2)=(-1,-1/3,1), eps^0: independent AMFlow
              black-box eps-grid (achieved 40d, LOO 44.1d).
              <- <archive>/phys_lbl3se/amflow_v2/RESULT_epsgrid_eps0.json
  GT_PARENT   same number from the INDEPENDENT 9-prop LBL3KP parent family
              (nu3=0 member of that family's Neville extraction, conv 39.9d).
              <- <archive>/phys_lbl3_qed_parents/GATE_RESULT.json "LBL3SE (nu3=0)"
  RHO_W12     rho(12) from an independent AMFlow solve_integrals run at w=12
              (never used in the transport; the seed is the w=5 run).
              <- <archive>/phys_lbl3se/numeric/amflow_kite_bnd_w12_out.json
  RHO5        -Im M_kite(5) = rho(5), the AMFlow solve_integrals run at w=5
              (140 d); the density at the seed point itself, gated with the
              row script's floor rho(5) >= min(dps, 79) (2026-09-04;
              2026-09-06: was min(dps, 100), a round number above the
              record measurement 79.946 d; --dps 80 failed by the
              script's own gate).
              <- <archive>/phys_lbl3se/numeric/amflow_kite_bnd_w5_out.json
  RHO100      rho(100), the AMFlow solve_integrals bnd_w100 run (140 d),
              confirmed by the row script's closed symbolic density to
              49.7 d; gated with the row script's floor
              rho(100) >= min(0.45*dps + 14, 40) (2026-09-04).  [An older
              Laurent-fit literal for rho(100) is wrong at digit 29 and is
              not used.]  <- <archive>/phys_lbl3se/numeric/amflow_kite_bnd_w100_out.json
  KITE_M1     -Sigma_kite(-1) (AMFlow, >=60d), oracle for the kernel-swap
              self-test <- <archive>/phys_lbl3se/numeric/amflow_kite_eucl_m1_out.json

USAGE (evaluation interface):
  python3 lbl3se-evaluate.py                    gate demo (default, quick)
  python3 lbl3se-evaluate.py --dps 80           same gate point at doubled
                                                precision (LEVEL/DPS/NORD
                                                rescale automatically).
                                                Measured 2026-09-06 (Q20f, the
                                                kernel far-tail cure below):
                                                rc 0, wall 6236.3 s on a
                                                shared 96-core host (contended);
                                                I printed to 44 digits; the
                                                two-precision pair (--dps 80 vs
                                                --dps 60, wall 2914.7 s) prints
                                                strings that agree on all 44 printed digits (the two strings are byte-equal); the
                                                oracle gates 43.2767 d (GT_AMF,
                                                the literal's own depth) and
                                                rho(12) 79.9812 d; TOTAL bound
                                                2.41e-82.  No digit beyond the
                                                pair + oracle is claimed.
  python3 lbl3se-evaluate.py --point -2 -0.2    I(s,t,m2=1) at a different
                                                kinematic point [+ --dps D]
  python3 lbl3se-evaluate.py --no-fastcache     force the full live run at the
                                                gate point (minutes-to-1h)
  python3 lbl3se-evaluate.py --density series   any tier with the density gate
                                                points reported by the series
                                                density alone (the closed form
                                                not evaluated: the prints of the
                                                version before 2026-09-11)
  python3 lbl3se-evaluate.py --sum-rule [LOG10_W]
                                                the spot gate (1/pi) int_1^inf
                                                rho dw = 6 zeta_3 on the closed-
                                                form density at the cutoff W =
                                                10^LOG10_W (default 50; accepted
                                                34..240 where the next omitted tail
                                                (4 ln W + 8)/W^2 clears the inner
                                                working precision at the running
                                                --dps -- the whole range at the
                                                default dps -- else refused by name
                                                with the smallest LOG10_W that does;
                                                minutes, the wall printed): the
                                                no-tail residual gated against the
                                                cutoff's own truncation capped at
                                                the inner working precision, the
                                                tail-restored residual against the
                                                inner working precision, and
                                                rho(5), rho(12), rho(100) from the
                                                same grid against the AMFlow
                                                references; a tier of its own
  python3 lbl3se-evaluate.py --point P1         the tagged point P1 = (-1/2,-1,1):
                                                I_SE computed live and GATED vs
                                                the shipped record points/P1.json
                                                (at dps 55; measured wall 2178 s on the build host).
                                                Since 2026-09-06 the gate reference
                                                is the record's direct AMFlow
                                                solve_integrals of the eight-
                                                propagator target at P1 at goal 70
                                                (amflow_direct.g70; its goal-50 twin
                                                agrees with it to 69.26 d at eps^0)
                                                at the tier bar 55 d =
                                                floor(56.30 - 1): this script's
                                                own dps-55 reading against the
                                                recorded value, with a digit of
                                                margin.  The record's count 59 d
                                                (the recorded value vs the direct
                                                solve, 59.40 d) is printed beside,
                                                reported -- not this tier's to reach
                                                at dps 55.
  python3 lbl3se-evaluate.py --point REF        the tagged reference point REF =
                                                (-1,-1/3,1), the row's own point
                                                (the default gate point): I_SE
                                                computed live and GATED vs the
                                                shipped record points/REF.json
                                                through the same tier machinery
                                                (at dps 55; the P1 tier's wall is
                                                the guide).  The gate reference is
                                                the record's direct AMFlow
                                                solve_integrals of the eight-
                                                propagator target at REF at goal 70
                                                (amflow_direct.g70; its goal-50 twin
                                                agrees with it to 69.25 d at eps^0)
                                                at the tier bar 55 d =
                                                floor(56.30 - 1): this script's
                                                measured dps-55 reading at the P1
                                                tier, with a digit of margin.  The
                                                record's count 59 d (the recorded
                                                value vs the direct solve, 59.41 d)
                                                is printed beside, reported; the
                                                default gate's 43.28 d against the
                                                42-digit eps-grid literal stays as
                                                served beside it.
  python3 lbl3se-evaluate.py ... --checkpoint DIR
                                                any live tier with the transport
                                                sweep (the wall of every live run:
                                                the rho(w) Picard-Fuchs sweep) CHECK-
                                                POINTED at the top of every zone
                                                step: the full sweep state, exact,
                                                written to DIR/<tag>.json.tmp and
                                                atomically replaced onto
                                                DIR/<tag>.json (a kill mid-write
                                                leaves the previous checkpoint
                                                intact and at most one .tmp);
                                                --checkpoint-every S writes at most
                                                once per S seconds (default 0:
                                                every step).
  python3 lbl3se-evaluate.py ... --resume DIR   the same tier continued from the
                                                newest intact checkpoint in DIR:
                                                its pins (this script's sha256, the
                                                data files' sha256, dps / NORD / SF,
                                                the point, the seed mode) are
                                                checked BY NAME (a mismatch is
                                                refused, rc 3; a .tmp with no intact
                                                checkpoint is refused by name), the
                                                sweep re-enters the recorded zone
                                                step and keeps checkpointing into
                                                DIR; every later value is byte-
                                                identical to an unbroken run's at
                                                the same dps (the state is the exact
                                                binary mantissa of every number; see
                                                the checkpoint block below).

FAST-START CACHE (2026-07-06, the disp-fastcache work): lbl3se-fastcache.json in
this directory holds the gate-demo values BANKED from one full live run of
THIS script (provenance + sha pins inside the file).  CERTIFIED DEPTH
(2026-09-06): the stored I string is this script's own dps-45 output
(QUAD_DPS + 8 = 53 significant digits); the depth certified is the
two-precision pair recorded in the cache header (certified_depth_d, the
floor of the smallest recorded agreement in banked_d: 43 d for the
2026-09-06 bank at dps 45), the fast-path prints say so and the printed
gate agreements are capped there, and no digit beyond it is claimed.
Cause (one sentence): the even Gauss-Legendre kernel rule (blog commit
3115ef81, 2026-09-05) moved the sibling lbl3kp evaluator's ill-conditioned
kernel Taylor fit and its truncated add-back, so a dps-45 bank's digits
past ~41 are realisation-dependent there; this script's dps-45 strings
reproduce byte for byte, and the same label applies: no digit beyond the
pair is claimed.  Default behavior
at the banked gate point for --dps <= the banked depth: the banked values
print instantly, every held-out oracle gate is re-asserted on the banked
strings (any mismatch, incl. a 1e-30 mutation of a cached string, exits
nonzero), and live cheap cross-checks run NOW (w=5 seed held-out gate; the
closed dilog-box kernel rebuilt live vs its banked constant).  The cache is a
fast start ONLY -- the live machinery in this file remains the definition:
any --point, --dps above the banked depth, --boundary-recompute,
--no-fastcache, or QUAD_DPS/LEVEL/DPS/NORD/SF env override runs it unchanged.
DOMAIN: deep-Euclidean s<0, t<0, u=-s-t<4 in units m2=1 (the rho seed and the
w=1,9 cusps fix the mass scale; other m2>0 by dimensional rescaling of s,t).
The w one-fold covers (1, W_MAX) with printed truncation bounds.  NOTE the two
GATE oracle literals are themselves ~40d artifacts: raising --dps past 40
saturates the gate agreement at that stated cap, while the rho(12) check
(held-out literal with 160 digits) keeps growing -- the dps-doubling exhibit.

Default settings (QUAD_DPS=40, LEVEL=5, DPS=55, NORD=98): gate-precision run,
single core, wall time printed at the end (measured ~6-9 min).  The archived
full-precision original record (<archive>/phys_lbl3se): gate 41.70d, rho checks
99.89-99.95d at dps=130/N=160 -- quoted as history, not measured here.

CHANGELOG:
  2026-09-11   the density in CLOSED FORM (section C2: rho_elem, the sunrise-
               cut one-folds Im S / Im Sdot, F23, RhoClosed): evaluated by
               default at the density gate points w = 5, 12, 100 in every
               tier and gated against the AMFlow references at the served
               floors, the series density printed beside as the cross-check
               (--density series: the previous prints); --sum-rule the
               6 zeta_3 spot gate.  The dispersion integrand, every value
               string, every bar and every other unit unchanged (RhoPF, the
               kernel, the quadrature, the certificates untouched; the fast-
               start cache's strings unchanged, its evaluator pin moved to
               these bytes).
  2026-09-09   checkpoint form of the transport sweep (--checkpoint DIR /
               --resume DIR / --checkpoint-every S; the block before the
               oracle literals): the rho(w) sweep state is written at the
               top of every zone step as one atomic file (tmp + replace) and
               a resumed run re-enters the recorded zone step from the exact
               state; pins checked by name, a mismatch refused rc 3; the
               resumed values byte-identical to a cold run's (measured, T1
               cold / T2 resume-after-kill; CHANGES.md).  Without the flags
               nothing here runs: every tier is byte-identical to the
               previous bytes (RhoPF.__init__ / RhoPF._leg gained the zone
               table and the loop-top hook; every numeric unit unchanged).
  2026-09-06   (Q20f) BoxKernel._tail far-tail floor: at w >= 1e36 the box
               dps is floored at ceil(log10 w) + 12 and the value asserted
               finite (the served floor of 18 returned NaN past w ~ 1e37.5:
               log 0 in the four-root partial fraction; every --dps >= 72
               reached it).  The fast path re-derives the cache header's
               certified_depth_d from the banked_d rows and refuses a
               disagreeing header by name.  The --dps 80 tier measured (USAGE
               above); the dps ~62 accuracy cap stated (ARBITRARY PRECISION
               above).  Every documented tier <= dps 55 byte-identical.
  2026-09-04   rho(5) and rho(100) spot gates.  The row script for this
               integral compares its spectral density at three points --
               w=5, 12, 100 -- against AMFlow solve_integrals values; this
               file carried only rho(12).  RHO5_STR and RHO100_STR (the row
               script's literals, verbatim) are now gated alongside it: in
               the live path rho_spot_gates() evaluates the SAME transported
               density at w=5 and w=100 right after the rho(12) check and
               RAISES below the row script's floors (GATE_FLOORS: rho(5) >=
               min(dps,79) (2026-09-06: was min(dps,100), a round number
               above the record measurement 79.946 d; --dps 80 failed by
               the script's own gate), rho(100) >= min(0.45*dps+14, 40), dps = the
               --dps target); in the fast path the cached rho(5)/rho(100)
               strings are re-gated in [p2] with the same floors and the
               tight |d_now - d_banked| <= 0.05 bar, so the cache file was
               regenerated by its own command (--dps 45 --fastcache-bank) to
               carry the two strings (the cache writer pins them).  No
               rho-route or value-path change:
               every unit other than the added ones is unchanged; RhoPF,
               the kernel, the quadrature and the bounds are untouched.
  2026-07-06b  rho-transport DPS-margin fix (work directory <archive>/
               axis3_wave/lbl3se-rho-margin/; the "separate DPS-margin fix"
               flagged by the depth-formula work).  MEASURED law: rho(12) held-out
               agreement was NORD-truncation-bound at 0.6115*NORD + 2.14 d
               (51.10 d @dps40, 68.85 d @dps60) because the old default
               NORD = max(80, 1.45*DPS+1) put per-step series truncation at
               ~10^-(0.887*DPS+3.4), ABOVE the 10^-DPS rounding floor.  New
               default NORD = max(80, ceil((DPS+4)/log10 4)) (see the NORD
               comment for the component census: rounding floor DPS-r with
               |r|<~0.7, seed floor = seed_dps with amplification 1.0, eval
               floor DPS+2.3).  rho(12) now tracks DPS = QUAD_DPS+15 up to
               the stored-seed floor ~80 d (--boundary-recompute lifts it).
               Moved default values: NORD-derived lines + the rho(12)
               agreement (51.1006 -> ~55.7 d @dps40, more correct digits vs
               the same 163-d held-out literal); the 50-digit printed rho(12)
               value and the integral/ladder/oracle lines are unchanged.
               Escalation machinery, err_top budget bar, and all gate bars
               unchanged (NORD stays a SEED; fail-closed paths untouched).
  2026-07-06   depth-formula fix (work directory <archive>/axis3_wave/
               lbl3se-depth/; approved fix pass, value-moving
               change by the same exception as the lbl3disp precedent).
               The 2026-07-05c FINDING is FIXED: the add-back kernel-Taylor
               depth is now kernel_nmax_for(dps) = (dps+8)/0.378 + 1 (was
               1.7*dps+10), derived from the MEASURED convergence law
               digits(N) = 0.378*N + 4.4 at the sub_width edge (Taylor radius
               R=1, singularity at w=0; see kernel_nmax_for docstring), with
               two measured conditioning guards in the Taylor build (LU wall
               ~0.63*N -> solve dps 0.7*N+20; coefficient noise floor
               ~fn_dps-0.21*N -> node evals at kd+12+N/4+10).  The gate VALUE
               now certifies ~QUAD_DPS digits instead of ~0.68*QUAD_DPS+9:
               TOTAL certificate 1.87e-35 -> ~1e-41.7 at dps 40 (addback term
               1.4e-52), and the honest refusal floor drops from dps <~ 36 to
               dps <~ 31 (see bar_total comment).  Default gate VALUES MOVE
               at the old ceiling (~10^-36 at dps 40): every moved value is
               re-gated against the held-out oracles in that work directory's ROW_REPORT.
  2026-07-05c  axis3 wave -- WP1 certified-bound treatment of every value-path
               truncation (pilot construction: <archive>/wiring/
               WIRING_LOG.md items 12-13).  (a) rho transport: NORD is now a
               STARTING guess only; every local-series step is certified at
               runtime by the trailing-TAIL_WINDOW geometric tail bound
               (envelope ratio r = |h|/dmin <= SF, certified by the step rule
               + the runtime-verified singularity set {0,1,9} of A); on
               failure the SAME recurrences are continued exactly (N x1.5) to
               cap NCAP, RuntimeError at cap.  The escalation criterion is the
               RELATIVE state tail (the dim-2 masters grow ~ w log w toward
               W_MAX, so absolute state tails are dominated by spectators);
               the VALUE budget accumulates the TOP(rho)-series tails and
               propagates via the l1-norm (1/pi)int|K|, while state-mixing
               integrity is certified by the RAISING held-out gates (rho(12)
               scaled bar, closed-masters two-path, kernel-swap).
               (b) dispersion ladder:
               LEVEL is a starting seed; the accepted value must beat the
               two-successive-depth (tanh-sinh squaring-model, = mpmath's own
               log-extrapolated estimator) tolerance 10^-(QUAD_DPS+QUAD_GUARD)
               or the ladder refines L+1... to LEVEL+LEVEL_EXTRA, RuntimeError
               at cap.  (c) a TOTAL certified error bound (quadrature estimate
               + addback tail + kernel-accuracy probes + GL two-depth probe +
               transport budget + U/V/W guard drops, all live values) is
               printed and ENFORCED against the value-claim bar
               10^-(min(GATE_BAR,QUAD_DPS)+TOTAL_GUARD).  FINDING (measured):
               the kernel-Taylor depth kernel_nmax = 1.7*dps+10 at sub_width
               0.4 caps the GATE VALUE at ~10^-(0.68*dps+9) -- this, not only
               the oracle strings, is why the gate saturates (26.0 d at dps
               25, 36.1 d at dps 40); rho(12) is the true dps-scaling
               exhibit.  The certificate therefore enforces the artifact's
               actual >=30 d value claim and honestly REFUSES dps <~ 36
               (where the artifact under-delivers its own bar); a depth-
               formula fix would move default values and is left to a
               follow-up wave (flagged in CHANGES.md).
               (d) agreement-type checks promoted from
               prints to RAISES with measured-margin bars: closed-masters
               two-path check (bar CM_BAR), derived-seed vs held-out AMFlow
               w=5 vector (bar seed_dps-DSEED_MARGIN), kernel-swap self-test
               (bar min(QUAD_DPS-8,50)); the --boundary-recompute stored-
               string cache check now raises RuntimeError.  All new lines
               carry the [cert] prefix; default gate output is otherwise
               byte-identical (guards calibrated so the default/gate runs
               never escalate -- calibration numbers in
               <archive>/axis3_wave/lbl3se-wp3/ROW_REPORT.md).
  2026-07-05b  ambient-dps + scaled gate bar: main() no longer pins
               mp.mp.dps=90 (that fixed cap clipped the seed-string parse --
               and so the --boundary-recompute path -- at ~90d for --dps>75).
               Ambient precision is now AMBIENT_DPS = max(90, --dps + 30) in
               BOTH seed paths (the default stored-80d-seed path stays the
               documented interim default; the recompute path is now
               genuinely uncapped), and bare --boundary-recompute derives the
               seed at max(80, --dps + 30) instead of a fixed 80.  The
               rho(12) held-out SELF-CHECK PASS bar now scales with --dps
               [min(--dps - 10, oracle-string digits - 10)]; the GT_AMF /
               GT_PARENT oracle bars stay fixed at >=30d (those literals are
               themselves ~40d artifacts) and NO stored oracle reference
               string was changed.
  2026-07-05a  --boundary-recompute [DPS] wiring, the LBL3SE build spec (see CHANGES.md).
"""
import argparse
import hashlib
import importlib.util
import json
import math
import os
import sys
import time
import bisect

import mpmath as mp

HERE = os.path.dirname(os.path.abspath(__file__))
T0 = time.time()

_ap = argparse.ArgumentParser(
    description="LBL3SE compliant final-form evaluator (see module docstring "
                "for the DOMAIN: s<0, t<0, -s-t<4, units m2=1)",
    epilog="tiers: (no flags) gate demo served from the sha-pinned fast-start "
           "cache, seconds; --no-fastcache the live gate run at dps 40, "
           "~20 min; --point S T a bare point (ungated), the live wall; "
           "--point P1 the tagged point gated vs points/P1.json (at dps 55; measured wall 2178 s on the build host); "
           "--point REF the tagged reference point (-1,-1/3,1) gated vs points/REF.json the same way (at dps 55); "
           "--boundary-recompute [DPS] the live run seeded by the shipped "
           "seed script; --checkpoint DIR / --resume DIR the transport sweep of "
           "any live tier checkpointed at every zone step (one atomic file) and "
           "resumed exactly from the newest intact checkpoint; --density series any tier with the series density alone at the density gate points (the closed form, evaluated and gated there by default since 2026-09-11, switched off); --sum-rule [LOG10_W] the 6 zeta_3 sum-rule spot gate on the closed-form density, a tier of its own (minutes).  Walls measured "
           "on a shared 96-core host.")
_ap.add_argument('--point', nargs='+', metavar='S_T_or_TAG', default=None,
                 help="evaluate I(s,t,m2=1) at this deep-Euclidean point "
                      "(two numbers S T; ungated) instead of only the gate "
                      "demo -- or ONE tag naming a shipped reference record: "
                      "--point P1 = (-1/2,-1,1), gated vs points/P1.json at "
                      "its recorded dps (55 unless --dps is given); "
                      "--point REF = (-1,-1/3,1), the row's reference point, "
                      "gated vs points/REF.json the same way")
_ap.add_argument('--dps', type=int, default=None,
                 help="target quadrature digits (default 40 = gate demo); "
                      "LEVEL/DPS/NORD are re-derived unless set by env")
_ap.add_argument('--boundary-recompute', nargs='?', const=-1, type=int,
                 metavar='DPS', default=None,
                 help="re-derive the w=5 seed by running the shipped "
                      "lbl3se-w5-seed.py at DPS (bare flag: tracks --dps as "
                      "max(80, dps+30), so the path is uncapped) instead of "
                      "reading the cached strings; the stored JSON demotes "
                      "to a byte-agreement cache check (2026-07-05 wiring, "
                      "the LBL3SE build spec)")
_ap.add_argument('--no-fastcache', action='store_true',
                 help="skip the sha-pinned fast-start cache "
                      "(lbl3se-fastcache.json) and run the live machinery "
                      "even at the banked gate point; the cache is a "
                      "fast-start convenience ONLY -- the live machinery in "
                      "this file remains the definition")
_ap.add_argument('--fastcache-bank', action='store_true',
                 help="maintainer mode: run fully live and, on a PASSING "
                      "gate run, write/refresh lbl3se-fastcache.json "
                      "(banked values + measured agreements + sha pins)")
_ap.add_argument('--checkpoint', metavar='DIR', default=None,
                 help="checkpoint the transport sweep (the wall of every live "
                      "tier) at the top of every zone step into DIR/<tag>.json "
                      "(written as <tag>.json.tmp, then atomically replaced; a "
                      "kill mid-write leaves the previous checkpoint intact); "
                      "DIR is created if missing; the fast-cache tier has no "
                      "sweep and writes nothing")
_ap.add_argument('--resume', metavar='DIR', default=None,
                 help="continue the transport sweep from the newest intact "
                      "checkpoint in DIR (its script / data / dps / point pins "
                      "checked by name; a mismatch or a partial .tmp with no "
                      "intact checkpoint is refused, rc 3) and keep "
                      "checkpointing into DIR; the resumed values are byte-"
                      "identical to an unbroken run's at the same dps")
_ap.add_argument('--checkpoint-every', type=float, default=0.0, metavar='S',
                 help="with --checkpoint / --resume: write at most once per S "
                      "seconds of wall (0 = at every zone step, the default; "
                      "the write cost is measured in CHANGES.md)")
_ap.add_argument('--density', choices=('closed', 'series'), default='closed',
                 help="which density reports the density gate points w = 5, 12, 100 "
                      "(2026-09-11): closed (default) = the closed form (weight-two "
                      "dilogarithms below w = 9, the one-fold over the equal-mass "
                      "sunrise cut above) evaluated live in every tier and gated "
                      "against the AMFlow references, the series density printed "
                      "beside as the cross-check; series = the Picard-Fuchs series "
                      "density alone (the closed form not evaluated).  The dispersion "
                      "integrand is the series density under both settings")
_ap.add_argument('--sum-rule', nargs='?', const=50, type=int, metavar='LOG10_W', default=None,
                 help="the spot gate (1/pi) int_1^inf rho dw = 6 zeta_3 on the closed-form "
                      "density at the cutoff W = 10^LOG10_W (default 50; accepted 34..240 where "
                      "the next omitted tail (4 ln W + 8)/W^2 clears the tail-restored bar at the "
                      "running --dps -- the whole range at the default dps; a cutoff too low for a "
                      "raised --dps is refused by name with the smallest LOG10_W that passes): "
                      "a tier of its own (minutes), rc 0 PASS / 1 FAIL / 2 usage or refused cutoff")
_ARGS = _ap.parse_args()

# sha256 of the pinned sibling module (computed by the producer that cut this file, never typed); a byte change
# or a missing file is REFUSED by name (exit 3) before any value is printed
SCRIPT = "lbl3se-evaluate"
PINS = {
    "kite_de_exact_parse.py": "0cc967d6362b63963b2e7ddd3e41f9edc1a4a0cab9cd2d7ebd7aef45aa83d7c1",
}


def _pinned_path(name):
    """Path of a sibling file; a PINNED file (the exact parser module) is refused on any byte
    change (exit 3, the recorded and recomputed sha256 named)."""
    path = os.path.join(HERE, name)
    want = PINS.get(name)
    if want is not None:
        if not os.path.exists(path):
            sys.stderr.write(f"{SCRIPT} REFUSED: pinned file {name} is missing (recorded sha256 {want})\n")
            raise SystemExit(3)
        have = hashlib.sha256(open(path, "rb").read()).hexdigest()
        if have != want:
            pos = next((k + 1 for k, (x, y) in enumerate(zip(want, have)) if x != y), 0)
            sys.stderr.write(f"{SCRIPT} REFUSED: {name} integrity pin mismatch (recorded {want}, recomputed "
                             f"{have}; first differing hex position {pos} of 64, 1-based) -- the shipped file "
                             f"was altered\n")
            raise SystemExit(3)
    return path


def _import_pinned_module(name):
    """Import a sibling module through the pin check (a byte change is REFUSED, exit 3)."""
    spec = importlib.util.spec_from_file_location(name[:-3], _pinned_path(name))
    mod = importlib.util.module_from_spec(spec)
    spec.loader.exec_module(mod)
    return mod


kx = _import_pinned_module("kite_de_exact_parse.py")   # the exact parser of the connection strings (no sympy)

# ---- tagged point tier (2026-09-05): --point P1 ------------------------------
# A tag names a shipped reference record points/<TAG>.json in this directory:
# the point (s,t,m2=1), the tier's default dps and the reference value strings
# (recorded by an independent implementation of the same one-fold and gated
# there against an independent AMFlow eps-grid; provenance and shas inside the
# record).  Unlike a bare `--point S T` (ungated), the tagged tier compares the
# value(s) computed HERE against the record's direct AMFlow solve (the eps^0
# string amflow_direct.g70, 2026-09-06) and exits 1 by name below the record's
# tier bar (tier_bar_d); the record's count of record (bar_d, the recorded
# value's own agreement with the direct solve) is printed beside, reported.
# The record carries an integrity pin over its own body; a
# record that fails its pin is REFUSED (rc 3).  Two records are shipped: P1
# (2026-09-05 / 2026-09-06) and REF, the row's reference point (2026-09-09,
# the same form: the direct solve at goals 50 / 70, the count of record, the
# tier bar); the machinery below is the same for both.
POINT_TAGS = {'P1': 'points/P1.json', 'REF': 'points/REF.json'}


def _point_refuse(msg):
    import sys
    print(f"[point-tag] REFUSED: {msg} (rc 3)", file=sys.stderr)
    raise SystemExit(3)


def _load_point_record(tag):
    import hashlib
    rel = POINT_TAGS[tag]
    path = os.path.join(HERE, rel)
    if not os.path.exists(path):
        _point_refuse(f"reference record {rel} for --point {tag} is missing from "
                      "this directory")
    with open(path) as fh:
        rec = json.load(fh)
    body = {k: v for k, v in rec.items() if k != '_sha256_body'}
    want = rec.get('_sha256_body', '')
    got = hashlib.sha256(json.dumps(body, sort_keys=True, separators=(',', ':'),
                                    ensure_ascii=False).encode()).hexdigest()
    if got != want:
        _point_refuse(f"{rel} integrity pin mismatch (recorded {want}, "
                      f"recomputed {got}; first differing hex position "
                      f"{1 + next((i for i, (a, b) in enumerate(zip(want, got)) if a != b), min(len(want), len(got)))} "
                      f"of 64, 1-based) -- the reference record was altered; "
                      f"not serving --point {tag}")
    if rec.get('tag') != tag:
        _point_refuse(f"{rel} carries tag {rec.get('tag')!r}, not {tag!r}")
    return rec


def _resolve_point_tag(args):
    """--point P1 -> (tag, record) with args.point rewritten to the record's
    decimal (s, t); --point S T -> (None, None), the ungated point mode as
    before; anything else -> usage error."""
    if args.point is None:
        return None, None
    if len(args.point) == 1:
        tag = args.point[0]
        if tag not in POINT_TAGS:
            _ap.error(f"--point {tag}: unknown point tag (known: "
                      f"{', '.join(sorted(POINT_TAGS))}); a bare point is given as "
                      "--point S T (m2 = 1)")
        rec = _load_point_record(tag)
        args.point = [rec['point']['s_decimal'], rec['point']['t_decimal']]
        return tag, rec
    if len(args.point) != 2:
        _ap.error("--point takes S T (a bare point, m2 = 1) or one tag "
                  f"({', '.join(sorted(POINT_TAGS))})")
    return None, None


_POINT_TAG, _POINT_REC = _resolve_point_tag(_ARGS)

QUAD_DPS = _ARGS.dps if _ARGS.dps else (
    int(_POINT_REC['tier_dps']) if _POINT_REC is not None   # the tag's recorded dps
    else int(os.environ.get("QUAD_DPS", "40")))
# tanh-sinh digits roughly double per level: 5 covers the 40d gate, +1/doubling
LEVEL = int(os.environ.get(
    "LEVEL", str(5 + max(0, math.ceil(math.log2(QUAD_DPS / 40.0))))))
DPS = int(os.environ.get("DPS", str(QUAD_DPS + 15)))   # transport working digits
# Taylor order per transport step: NORD is the escalation SEED (taylor_step
# refine-until-bound continues the same recurrences to 16*N0, RuntimeError at
# cap), but the DEFAULT must put per-step truncation BELOW the DPS rounding
# floor or truncation becomes the rho accuracy wall.  MEASURED law (work directory
# <archive>/axis3_wave/lbl3se-rho-margin, 2026-07-06, exact-path
# probes at w=12 vs the 163-d held-out rho(12) literal):
#   truncation digits = 0.6115*N + 2.14  (slope stable +-0.0015 over N=80..122;
#                                          theory -log10(SF=1/4) = 0.60206)
#   rounding floor    = DPS - r, r in [-0.7,+0.3]   (DPS 55..75, N=135)
#   seed floor        = seed_dps (amplification 1.0 measured; stored strings
#                       dps 80; --boundary-recompute lifts to max(80, dps+30))
# The OLD default 1.45*DPS+1 gave truncation ~10^-(0.887*DPS+3.4) > 10^-DPS,
# so truncation ALWAYS bound the rho(12) held-out agreement (51.10 d @dps40,
# 68.85 d @dps60 -- the flagged DPS-margin cap).  NEW: N0 = ceil((DPS+4)/
# log10(4)) puts truncation at <= 10^-(DPS+6.1) (conservative: theory slope,
# no intercept credit), so rho(12) tracks DPS = QUAD_DPS+15 up to the seed
# floor.  Defaults move 80 -> 98 (dps 40), 109 -> 132 (dps 60).
NORD = int(os.environ.get("NORD", str(max(80, math.ceil((DPS + 4)
                                                        / math.log10(4))))))
SF = mp.mpf(os.environ.get("SF", "0.25"))          # step = SF * dist-to-singularity

# truncation guards, DERIVED from QUAD_DPS (each bound printed in main):
#   U_MIN : below w=1+U_MIN the subtracted remainder (rho - A1 u log u) ~ B*u,
#           |B|<~10, so the dropped piece is < 10*U_MIN^2*K(1)/pi
#   V_MIN : within V_MIN of the finite-jump cusp w=9 rho is frozen at the edge
#           value; |rho'| ~ |log V_MIN| there, dropped < K(9)*V_MIN^2*log/pi
#   W_MAX : tail truncation; rho ~ 4pi log w/w^2, K ~ c1/w (c1 ~ 0.57 measured
#           live below), dropped < 2*c1*log(W)/W^2
U_MIN = mp.mpf(10) ** -(QUAD_DPS // 2 + 2)
V_MIN = mp.mpf(10) ** -(QUAD_DPS // 2 + 1)
W_MAX = mp.mpf(10) ** (QUAD_DPS // 2 + 2)

# ambient parse/print precision for main(): tracks the caller's --dps with the
# house guard margin (+30 > DPS-QUAD_DPS = +15 transport working digits),
# floored at the legacy 90 so the default gate demo is unchanged.  A fixed 90
# here used to cap the w=5 seed-string parse -- and with it the whole
# --boundary-recompute path -- at ~90d for --dps > 75 (fixed 2026-07-05b).
AMBIENT_DPS = max(90, QUAD_DPS + 30)

# ---- axis3-wave certified-bound machinery (2026-07-05c; WP1 pilot pattern,
# WIRING_LOG items 12-13).  Guards CALIBRATED on the default gate set so
# healthy default runs never escalate (measured numbers in
# <archive>/axis3_wave/lbl3se-wp3/ROW_REPORT.md); at other --dps
# the loops refine/raise as designed.  All new output lines carry "[cert]".
TAIL_WINDOW = 8      # trailing-term window of the geometric tail envelope
TAIL_GUARD = 4       # per-step transport tol = 10^-(QUAD_DPS+TAIL_GUARD) on
                     # the RELATIVE state tail (tail / local state scale --
                     # the dim-2 masters GROW ~ w log w toward W_MAX, so the
                     # absolute state tail is ~1e-27 there while the relative
                     # tail stays ~1e-48).  CALIBRATED 2026-07-05 (cal2 run,
                     # default Q=40/NORD=80): worst rel = 5.03e-48 (at w0=5)
                     # vs tol 1e-44 -> 10^3.7 headroom; at Q=60/NORD=109 the
                     # projected worst is ~1.7e-65 vs 1e-64 -> ~17x, so the
                     # gate set never escalates; higher dps escalate honestly.
                     # 2026-07-06b: the deeper NORD defaults push worst rel
                     # to ~10^-(0.6115*N0-1.6) (measured law): ~1e-58 @N0=98
                     # vs 1e-44, ~1e-79 @N0=132 vs 1e-64 -> headroom GROWS;
                     # defaults still never escalate.
NCAP_FACT = 16       # transport series order cap = NCAP_FACT * starting NORD
QUAD_GUARD = 0       # ladder tol = 10^-(QUAD_DPS+QUAD_GUARD) on the
                     # two-successive-depth squaring-model estimate d1^2/d2
LEVEL_EXTRA = 5      # ladder may refine to LEVEL+LEVEL_EXTRA before raising
CM_BAR = 12          # closed-masters two-path RAISE bar (measured 17.94 d,
                     # capped by the 1e-18 eps probe, dps-independent)
DSEED_MARGIN = 12    # seed held-out RAISE bar = min(seed_dps, 128) - margin
SWAP_MARGIN = 8      # kernel-swap RAISE bar = min(QUAD_DPS-SWAP_MARGIN, 50)
GATE_BAR = 30        # the artifact's value-level CLAIM (fixed >=30 d oracle
                     # bars); the enforced TOTAL certificate must beat
                     # 10^-(min(GATE_BAR,QUAD_DPS)+TOTAL_GUARD).
                     # 2026-07-06: the 2026-07-05 FINDING (add-back depth
                     # 1.7*dps+10 capped the gate VALUE at ~10^-(0.68*dps+9),
                     # forcing refusal for dps <~ 36) is FIXED by
                     # kernel_nmax_for(); the gate value now tracks QUAD_DPS.
                     # Refusal bar RE-DERIVED under the new law: TOTAL is now
                     # quadrature/guard-dominated, ~10^-(QUAD_DPS+1.7)
                     # (measured est_q = 2.17e-42 at dps 40 + U/V/W guard
                     # drops 10^-(2*(QUAD_DPS//2)+~2.5)), so the bar
                     # min(30,Q)+2 is met for QUAD_DPS >= ~31 and the honest
                     # refusal floor drops from ~36 to ~31 (at dps 30 the
                     # V/W guard drops ~7e-33 + est_q ~1e-31.7 still exceed
                     # 1e-32 -- refusal there remains honest, same class as
                     # the pre-existing dps-25 exit-1).
TOTAL_GUARD = 2      # TOTAL certificate tol = 10^-(GATE_BAR+TOTAL_GUARD)

# ---- checkpoint / resume of the transport sweep (2026-09-09) ----------------
# The rho(w) Picard-Fuchs sweep (RhoPF: the zones M, L, the four arc legs
# A1-A4, R2, R3) is the wall of every live tier (measured 2026-09-09 at dps 55:
# 1980 s of the 2019 s wall of the --point REF tier).  With --checkpoint DIR the
# FULL sweep state is written at the top of EVERY zone step (or at most once
# per --checkpoint-every S seconds) to DIR/<tag>.json.tmp and os.replace'd onto
# DIR/<tag>.json: one atomic file, so a kill mid-write leaves the previous
# checkpoint intact and at most one .tmp beside it (the reader never opens a
# .tmp).  With --resume DIR the newest intact checkpoint in DIR is read, its
# pins are checked BY NAME (this script's sha256, the sha256 of every data file
# the sweep reads, QUAD_DPS / DPS / NORD / SF and the guard constants, the point,
# the seed mode; a mismatch is REFUSED, rc 3, the differing field named; a .tmp
# with no intact checkpoint is refused by name), the accumulators and the
# finished zones' results are restored and the interrupted zone is re-entered
# at its recorded step; the run keeps checkpointing into DIR and writes a
# final DONE checkpoint after the sweep.
# EXACTNESS: the state is the exact binary mantissa of every mpf / mpc --
# mpmath's own (sign, mantissa, exponent, bit count) tuple, encoded without
# any rounding -- not a decimal print; and every local-series step is a pure
# function of the exact rational connection, the state at the step's w, the
# step h derived from w, NORD, SF and the working dps (no clock, no RNG, no
# in-process cache enters a value), so a resumed sweep recomputes the
# interrupted step from the same bits and every later value -- rho at any w,
# the [P] value lines, the gate line -- is byte-identical to an unbroken run's
# at the same dps (measured 2026-09-09: T1 cold / T2 resume after a planned
# SIGKILL, CHANGES.md).  Without the flags nothing in this block runs.
CKPT_FORM = 'lbl3se-transport-checkpoint-v1'
CKPT_DATA_FILES = ('lbl3se-kite-de.json', 'lbl3se-w5-derived.json',
                   'lbl3se-kite-boundary-w5.json', 'kite_de_exact_parse.py')


def _ck_sha_file(path):
    import hashlib
    with open(path, 'rb') as fh:
        return hashlib.sha256(fh.read()).hexdigest()


def _ck_refuse(msg):
    print(f"[checkpoint] REFUSED: {msg} (rc 3)", file=sys.stderr)
    raise SystemExit(3)


def _ck_point():
    return (list(_ARGS.point) if _ARGS.point is not None else ['-1', '-1/3'])


def _ck_pins():
    """The identity a checkpoint is bound to; every field is compared by name
    on resume."""
    pt = _ck_point()
    return {'form': CKPT_FORM,
            'script_sha256': _ck_sha_file(os.path.abspath(__file__)),
            'data_sha256': {f: _ck_sha_file(os.path.join(HERE, f))
                            for f in CKPT_DATA_FILES},
            'point_tag': _POINT_TAG, 'point': [str(pt[0]), str(pt[1])],
            'QUAD_DPS': QUAD_DPS, 'DPS': DPS, 'NORD': NORD, 'SF': str(SF),
            'boundary_recompute': _ARGS.boundary_recompute,
            'TAIL_GUARD': TAIL_GUARD, 'TAIL_WINDOW': TAIL_WINDOW,
            'NCAP_FACT': NCAP_FACT}


def _ck_tag():
    pt = _ck_point()
    p = _POINT_TAG if _POINT_TAG is not None else f"s{pt[0]}_t{pt[1]}"
    p = ''.join(ch if (ch.isalnum() or ch in '._-') else '_' for ch in p)
    return f"lbl3se-transport_{p}_dps{QUAD_DPS}"


def _ck_enc(x):
    """Exact encoding: mpf -> 'f<sign>:<mantissa hex>:<exponent>:<bit count>'
    (mpmath's own tuple, no rounding), mpc -> ['c', re, im]; None / int / str
    pass through."""
    if x is None or isinstance(x, (int, str)):
        return x
    if isinstance(x, mp.mpc):
        return ['c', _ck_enc(mp.re(x)), _ck_enc(mp.im(x))]
    if not isinstance(x, mp.mpf):
        x = mp.mpf(x)
    s, m, e, b = x._mpf_
    return f"f{s}:{format(int(m), 'x')}:{e}:{b}"


def _ck_dec(v):
    from mpmath.libmp import MPZ
    if v is None or isinstance(v, int):
        return v
    if isinstance(v, list) and v and v[0] == 'c':
        z = mp.mpc(0)
        z._mpc_ = (_ck_dec(v[1])._mpf_, _ck_dec(v[2])._mpf_)
        return z
    if isinstance(v, str) and v.startswith('f'):
        s, m, e, b = v[1:].split(':')
        x = mp.mpf(0)
        x._mpf_ = (int(s), MPZ(int(m, 16)), int(e), int(b))
        return x
    raise ValueError(f"[checkpoint] undecodable state value {v!r}")


def _ck_enc_M(M):
    return None if M is None else {str(k): [_ck_enc(x) for x in M[k]] for k in (-2, -1, 0)}


def _ck_dec_M(d):
    return None if d is None else {k: [_ck_dec(x) for x in d[str(k)]] for k in (-2, -1, 0)}


def _ck_state(rho, zone, step, M, w, snap, want):
    import datetime
    ck = rho._ck
    ck['seq'] += 1
    zr = rho._zr
    return {'form': CKPT_FORM, 'tag': ck['tag'], 'pins': ck['pins'],
            'zone': zone, 'step': step, 'nsteps_done': ck['nsteps_done'],
            'w': _ck_enc(w), 'M': _ck_enc_M(M),
            'snap': None if snap is None else [_ck_enc(snap[0]), _ck_enc_M(snap[1])],
            'want': [_ck_enc(x) for x in want],
            'acc': {'segs': [[_ck_enc(a), _ck_enc(b), _ck_enc(w0), [_ck_enc(c) for c in ser]]
                             for (a, b, w0, ser) in rho.segs],
                    'checkpoints': [[_ck_enc(k), _ck_enc_M(v)] for k, v in rho.checkpoints.items()],
                    'err_top': _ck_enc(rho.err_top), 'worst_rel': _ck_enc(rho.worst_rel),
                    'worst_at': _ck_enc(rho.worst_at), 'n_grow': rho.n_grow,
                    'max_used': rho.max_used},
            'zr': {'snap': None if zr.get('snap') is None else [_ck_enc(zr['snap'][0]), _ck_enc_M(zr['snap'][1])],
                   'Marc': _ck_enc_M(zr.get('Marc')), 'rho_9m': _ck_enc(zr.get('rho_9m')),
                   'rho_9p': _ck_enc(zr.get('rho_9p'))},
            'seq': ck['seq'], 'written_utc': datetime.datetime.now(datetime.timezone.utc).isoformat(),
            'wall_s': time.time() - T0}


def _ck_write(ck, state):
    path = os.path.join(ck['dir'], ck['tag'] + '.json')
    tmp = path + '.tmp'
    t0 = time.time()
    with open(tmp, 'w') as fh:
        json.dump(state, fh, separators=(',', ':'))
        fh.write('\n')
        fh.flush()
        os.fsync(fh.fileno())
    os.replace(tmp, path)           # atomic: the previous checkpoint stays intact until this instant
    ck['last'] = time.time()
    ck['n_written'] += 1
    ck['write_s'] += ck['last'] - t0
    ck['bytes'] = os.path.getsize(path)
    return path


def _ck_at_step(rho, zone, M, w, snap, want):
    """The loop-top hook of RhoPF._leg: write the full state at this zone step
    (subject to --checkpoint-every)."""
    ck = rho._ck
    if ck['every'] > 0 and time.time() - ck['last'] < ck['every']:
        return
    _ck_write(ck, _ck_state(rho, zone, rho._ns, M, w, snap, want))


def _ck_zone_done(rho, nsteps):
    if rho._ck is not None:
        rho._ck['nsteps_done'] = nsteps


def _ck_final(rho):
    """The DONE checkpoint after the sweep: a resume from it replays no step."""
    ck = rho._ck
    if ck is None:
        return
    if not ck['resumed_done']:
        _ck_write(ck, _ck_state(rho, 'DONE', 0, None, None, None, []))
    print(f"           [checkpoint] {ck['n_written']} written to {os.path.join(ck['dir'], ck['tag'] + '.json')} "
          f"(last {ck['bytes']} bytes; {ck['write_s']:.1f}s of write wall in total)")


def _ck_read_newest(dirpath):
    """The newest intact checkpoint (a parseable DIR/*.json of this form); a
    .tmp is never read and is named when nothing intact exists."""
    if not os.path.isdir(dirpath):
        _ck_refuse(f"--resume {dirpath}: not a directory")
    names = sorted(os.listdir(dirpath))
    tmps = [n for n in names if n.endswith('.json.tmp')]
    cands, bad = [], []
    for n in names:
        if not n.endswith('.json'):
            continue
        p = os.path.join(dirpath, n)
        try:
            with open(p) as fh:
                d = json.load(fh)
        except Exception as ex:
            bad.append(f"{n} ({type(ex).__name__})")
            continue
        if not (isinstance(d, dict) and d.get('form') == CKPT_FORM):
            bad.append(f"{n} (not a {CKPT_FORM} checkpoint)")
            continue
        cands.append((d.get('written_utc', ''), int(d.get('seq', 0)), n, d))
    if not cands:
        parts = [f"--resume {dirpath}: no intact checkpoint"]
        if tmps:
            parts.append(f"{len(tmps)} partial .tmp file(s) ignored by name: {', '.join(tmps)} "
                         "(a write interrupted before its atomic replace is not a checkpoint)")
        if bad:
            parts.append(f"unreadable or foreign json ignored: {', '.join(bad)}")
        _ck_refuse('; '.join(parts) + ' -- nothing to resume')
    cands.sort(key=lambda c: (c[0], c[1]))
    wu, seq, n, d = cands[-1]
    if tmps:
        print(f"[checkpoint] ignoring {len(tmps)} partial .tmp file(s) in {dirpath} by name: "
              f"{', '.join(tmps)} (a write interrupted before its atomic replace)")
    return os.path.join(dirpath, n), d


def _ck_check_pins(path, d):
    want, have = _ck_pins(), d.get('pins', {})
    diffs = []
    for k, v in want.items():
        h = have.get(k)
        if k == 'data_sha256':
            for f, s in v.items():
                hs = (h or {}).get(f)
                if hs != s:
                    diffs.append(f"data_sha256[{f}] {str(hs)[:16]} (this run {s[:16]})")
        elif h != v:
            hv = str(h)[:16] if k == 'script_sha256' else h
            vv = v[:16] if k == 'script_sha256' else v
            diffs.append(f"{k} {hv!r} (this run {vv!r})")
    if diffs:
        _ck_refuse(f"{path} was written for a different run: " + '; '.join(diffs) + " -- not resuming")


def _ck_open():
    """The checkpoint driver of this run (None without --checkpoint / --resume)."""
    if _ARGS.checkpoint is None and _ARGS.resume is None:
        return None
    d = _ARGS.checkpoint if _ARGS.checkpoint is not None else _ARGS.resume
    os.makedirs(d, exist_ok=True)
    ck = {'dir': d, 'tag': _ck_tag(), 'pins': _ck_pins(), 'every': float(_ARGS.checkpoint_every),
          'last': 0.0, 'seq': 0, 'n_written': 0, 'write_s': 0.0, 'bytes': 0,
          'nsteps_done': 0, 'resume': None, 'resumed_done': False}
    if _ARGS.resume is not None:
        path, st = _ck_read_newest(_ARGS.resume)
        _ck_check_pins(path, st)
        if st.get('tag') != ck['tag']:
            _ck_refuse(f"{path} carries tag {st.get('tag')!r}, not {ck['tag']!r}")
        ck['resume'] = (path, st)
        ck['seq'] = int(st.get('seq', 0))
    print(f"           [checkpoint] writing {os.path.join(d, ck['tag'] + '.json')} "
          + (f"at most once per {ck['every']:g} s" if ck['every'] > 0 else "at every zone step"))
    return ck


def _ck_restore(rho):
    """Restore the accumulators and the finished zones' results from the
    checkpoint being resumed; return the loop state of the interrupted zone
    (a dict), or None when not resuming."""
    ck = rho._ck
    if ck is None or ck['resume'] is None:
        return None
    path, st = ck['resume']
    acc = st['acc']
    rho.segs = [(_ck_dec(a), _ck_dec(b), _ck_dec(w0), [_ck_dec(c) for c in ser]) for (a, b, w0, ser) in acc['segs']]
    rho.checkpoints = {_ck_dec(k): _ck_dec_M(v) for k, v in acc['checkpoints']}
    rho.err_top = _ck_dec(acc['err_top'])
    rho.worst_rel = _ck_dec(acc['worst_rel'])
    rho.worst_at = _ck_dec(acc['worst_at'])
    rho.n_grow = int(acc['n_grow'])
    rho.max_used = int(acc['max_used'])
    zr = st['zr']
    rho._zr = {'snap': None if zr['snap'] is None else (_ck_dec(zr['snap'][0]), _ck_dec_M(zr['snap'][1])),
               'Marc': _ck_dec_M(zr['Marc']), 'rho_9m': _ck_dec(zr['rho_9m']), 'rho_9p': _ck_dec(zr['rho_9p'])}
    ck['nsteps_done'] = int(st['nsteps_done'])
    ck['resumed_done'] = (st['zone'] == 'DONE')
    print(f"[resume] from {st['tag']} at zone {st['zone']} step {st['step']} "
          f"({path}, written {st.get('written_utc', '?')}, seq {st.get('seq', '?')}; "
          f"{ck['nsteps_done'] + int(st['step'])} steps and {len(rho.segs)} stored segments restored exactly)")
    return {'zone': st['zone'], 'step': int(st['step']), 'nsteps_done': ck['nsteps_done'],
            'M': _ck_dec_M(st['M']), 'w': _ck_dec(st['w']),
            'snap': None if st['snap'] is None else (_ck_dec(st['snap'][0]), _ck_dec_M(st['snap'][1])),
            'want': [_ck_dec(x) for x in st['want']]}


# ---------------------------------------------------------------- oracles ---
# Held-out literals (provenance in the docstring).  Parsed at high dps inside
# main() -- module-level mp.mpf parse at dps=15 is the trap that once capped
# this very gate at 17.6 digits.
GT_AMF_STR = "0.524957776781144632332996415282646042436171"
GT_PARENT_STR = "0.52495777678114463233299641528264604243617095230296"
RHO_W12_STR = ("0.39118160908247272140297662324912768960644354162754176827840"
               "05818116281784996731939692480451865506078571628503177960305228"
               "830215624118821245684483066354860486343504")
KITE_M1_STR = ("1.33171144142210957679852298285266497336483433353088482372693366"
               "49110878446259902759227207930400179290939159539194525501354138670618")
# 2026-09-04: the row script's two other spectral-density spot references,
# carried verbatim and gated alongside RHO_W12 (live path: rho_spot_gates on
# the transported density; fast path: the cached strings re-gated in [p2]).
# GATE_FLOORS are the row script's floors for these two spot gates, keyed on
# the --dps target (QUAD_DPS); they are unrelated to GATE_BAR (the I-value
# claim) and to the rho(12) self-check bar, which keep their own definitions.
RHO5_STR = ("1.663479584361080173948716060213024634373432582368693673876490533944980"
            "63819387518116473235729360240114759165722492372800189805496698030269")
RHO100_STR = ("0.0077916795514592605197494159377621432968434210826071616597299343160"
              "8722568461946565680546674989984783444333061578558621081701943628764877")
GATE_FLOORS = {
    'rho(5)':   lambda dps: min(float(dps), 79.0),
    'rho(100)': lambda dps: min(0.45 * dps + 14.0, 40.0),
}


def agree_digits(a, b):
    d = mp.fabs(a - b)
    if d == 0:
        return mp.inf
    return -mp.log10(d / mp.fabs(b))


def point_tag_gate(tag, rec, values, ok_run):
    """The tagged tier's gate (2026-09-05; the direct solve 2026-09-06): every
    target in the shipped record points/<tag>.json vs the value computed here,
    agreement = -log10|a-b|/|b| with the record strings parsed at the ambient
    precision.  Two references per target: the eps^0 coefficient of the direct
    AMFlow solve_integrals of the eight-propagator target at this point at its
    finer goal (amflow_direct.g70, certified by its goal pair: the GATE, PASS
    iff every target reaches the record's tier_bar_d AND the run's own
    certificates held) and the recorded evaluator value (value: REPORTED, its
    own agreement with the direct solve named as that string's ceiling); the
    goal-50 twin's agreement is printed beside, reported.  Prints the computed
    and reference strings side by side at min(62, dps+2) digits plus the
    recorded provenance; returns ok."""
    mp.mp.dps = AMBIENT_DPS
    n = min(62, QUAD_DPS + 2)
    pt = rec['point']
    print(f"[P] [{time.time()-T0:6.1f}s] tagged point {tag}: (s,t,m2) = ({pt['s']},{pt['t']},{pt['m2']}) -- "
          f"computed here vs the shipped reference record {POINT_TAGS[tag]}")
    src = rec.get('sources', {})
    ev = src.get('evaluator', {})
    print(f"           reference: {rec.get('record', '')}")
    print(f"           recorded by {ev.get('name', '?')} {ev.get('sha256', '?')[:16]} + {ev.get('library', '?')} "
          f"{ev.get('library_sha256', '?')[:16]}; gated there vs an independent AMFlow eps-grid "
          f"({src.get('independent_grid', {}).get('sha256', '?')[:16]})")
    if QUAD_DPS < int(rec['tier_dps']):
        print(f"           NOTE: --dps {QUAD_DPS} is below the tier's recorded dps {rec['tier_dps']}; "
              "the bar is the recorded claim and may not be reachable here")
    ok = ok_run
    for name, tgt in rec['targets'].items():
        if name not in values:
            continue
        ours = values[name]
        direct = tgt['amflow_direct']
        g70 = mp.mpf(direct['g70'])
        g50 = mp.mpf(direct['g50'])
        ref = mp.mpf(tgt['value'])
        d_g70 = agree_digits(ours, g70)
        d_g50 = agree_digits(ours, g50)
        d_ref = agree_digits(ours, ref)
        bar = float(tgt['tier_bar_d'])
        bar_rec = float(tgt['bar_d'])
        claimed = float(tgt['claimed_digits'])
        shas = direct.get('sources', {}).get('out_sha256', {})
        print(f"           the direct solve: AMFlow solve_integrals of the eight-propagator target at {tag}, goals "
              f"{direct['options']['goal_digits']['g50']} / {direct['options']['goal_digits']['g70']} "
              f"(outputs {shas.get('g50', '?')[:16]} / {shas.get('g70', '?')[:16]}); eps^0 pair "
              f"{float(direct['pair_eps0_d']):.2f} d, worst common Laurent order {float(direct['pair_worst_common_order_d']):.2f} d")
        print(f"           {name:5s} computed          = {mp.nstr(ours, n)}")
        print(f"           {name:5s} direct solve g70  = {mp.nstr(g70, n)}   ({direct['stored_digits']['g70']} stored digits; "
              f"the recorded value agrees with it to {float(direct['vs_recorded_value_d']['g70']):.2f} d)")
        print(f"           {name:5s} agreement (direct g70) = {mp.nstr(d_g70, 6)} d >= tier bar {bar:.0f} d "
              f"(the count of record {bar_rec:.0f} d: {tgt['bar_d_member']}) -- {'OK' if d_g70 >= bar else 'FAIL'}")
        print(f"           {name:5s} agreement (direct g50) = {mp.nstr(d_g50, 6)} d   (reported)")
        print(f"           {name:5s} recorded value    = {mp.nstr(ref, n)}   (recorded at dps {tgt['value_dps']}; "
              f"{claimed:.2f} d = that string's own depth vs the direct solve, the ceiling of the next line)")
        print(f"           {name:5s} agreement (recorded value) = {mp.nstr(d_ref, 6)} d   (reported)")
        ok = ok and (d_g70 >= bar)
    return ok


def rho_spot_gates(rho, dps):
    """rho(5) and rho(100) from the live density vs the two AMFlow
    solve_integrals reference strings (RHO5_STR at the seed point itself,
    RHO100_STR in the tail) -- the row script's density spot gates, carried
    alongside the rho(12) check.  Floors GATE_FLOORS[name](dps); a value
    below its floor RAISES (rc != 0).  Returns {name: (value, digits)}."""
    out = {}
    for name, wv, lit in (("rho(5)", 5, RHO5_STR),
                          ("rho(100)", 100, RHO100_STR)):
        t0 = time.time()
        val = rho(mp.mpf(wv))
        d = agree_digits(val, mp.mpf(lit))
        out[name] = (val, float(d))
        floor = GATE_FLOORS[name](dps)
        print(f"           [cert] {name:8s} spot gate: {mp.nstr(val, 30)}  agree "
              f"{mp.nstr(d, 6)} d >= floor {floor:.2f} d (dps={dps})  "
              f"({time.time()-t0:.1f}s) -- RAISES on fail")
        if not d >= floor:
            raise RuntimeError(f"[cert] {name} vs AMFlow solve_integrals reference: "
                               f"{mp.nstr(d, 6)} d < floor {floor:.2f} d (dps={dps})"
                               f" -- density spot gate not met, STOP")
    return out


# ============== fast-start cache (2026-07-06, the disp-fastcache work) =======
# Doctrine: cache = sha-pinned + compare-gated fast start; the live machinery
# in this file remains the DEFINITION.  See module docstring, FAST-START CACHE.
FASTCACHE_PATH = os.path.join(HERE, 'lbl3se-fastcache.json')
_FC_GATE_KEY = 's=-1,t=-1/3'
_FC_ENV_OVERRIDES = ('QUAD_DPS', 'LEVEL', 'DPS', 'NORD', 'SF')
_FC_PIN_FILES = ('lbl3se-evaluate.py', 'lbl3se-kite-de.json',
                 'lbl3se-w5-derived.json', 'lbl3se-kite-boundary-w5.json')


def _fc_sha(fname):
    import hashlib
    with open(os.path.join(HERE, fname), 'rb') as fh:
        return hashlib.sha256(fh.read()).hexdigest()


def _fc_str_sha(s):
    import hashlib
    return hashlib.sha256(s.encode()).hexdigest()


def _fc_eligible():
    """(cache dict, None) if the fast path serves this invocation, else
    (None, honest wall note or None)."""
    live_note = ("live machinery run (the definition) -- expect the full "
                 "wall (~6-15 min at default --dps 40; ~1 h at --dps 45+)")
    if _ARGS.no_fastcache or _ARGS.fastcache_bank:
        return None, None       # explicit live request: no banner needed
    if _ARGS.point is not None:
        return None, f"requested --point is not the banked gate point; {live_note}"
    if _ARGS.boundary_recompute is not None:
        return None, f"--boundary-recompute forces the live path; {live_note}"
    envs = [k for k in _FC_ENV_OVERRIDES if k in os.environ]
    if envs:
        return None, f"env override {envs} set; {live_note}"
    if not os.path.exists(FASTCACHE_PATH):
        return None, f"no lbl3se-fastcache.json; {live_note}"
    try:
        with open(FASTCACHE_PATH) as fh:
            fc = json.load(fh)
        pt = fc['points'][_FC_GATE_KEY]
    except Exception as ex:
        return None, f"fast cache unreadable ({ex!r}); {live_note}"
    if QUAD_DPS > pt['cached_dps']:
        return None, (f"requested --dps {QUAD_DPS} exceeds the banked depth "
                      f"{pt['cached_dps']}; {live_note}")
    return fc, None


def _fc_fail(msg):
    raise RuntimeError(f"[fast-cache] COMPARE GATE FAIL: {msg} -- refusing "
                       "to serve the cache; rerun with --no-fastcache for "
                       "the live machinery (the definition)")


def _fc_gate(label, d_now, d_banked, floor, cap=None):
    """Tight compare gate: recomputed agreement must reproduce the banked
    agreement (|delta| <= 0.05 d -- the comparison is deterministic string
    parsing, so ANY drift incl. a 1e-30 mutation moves it) AND beat the
    floor of record."""
    ok = (float(d_now) >= floor) and (abs(float(d_now) - float(d_banked)) <= 0.05)
    # 2026-09-06: the PRINTED agreement is min(measured, certified_depth_d), the
    # cap named; the gate rule above compares the measured figure, unchanged
    shown = float(d_now) if cap is None else min(float(d_now), float(cap))
    capnote = ("" if cap is None else
               f" [capped at the certified depth {cap} d; measured {float(d_now):.4f} d]")
    print(f"           [fast-cache gate] {label}: {mp.nstr(mp.mpf(shown), 6)} d{capnote} "
          f"(banked {d_banked:.4f} d, floor {floor} d) -- "
          f"{'OK' if ok else 'FAIL'}")
    if not ok:
        _fc_fail(f"{label}: recomputed {float(d_now):.4f} d vs banked "
                 f"{d_banked:.4f} d (floor {floor} d)")


def _fc_fast_path(fc):
    """Serve the banked gate-demo values: sha pins -> per-string pins ->
    numeric held-out oracle gates recomputed NOW on the banked strings ->
    live cheap cross-checks (seed gate + kernel rebuild).  Any failure
    raises (rc != 0)."""
    pt = fc['points'][_FC_GATE_KEY]
    prov = fc['_provenance']
    cd = fc.get('certified_depth_d')      # 2026-09-06: the header's certified depth
    cdtxt = (f"certified depth {cd} d by the two-precision pair (cache header "
             "certified_depth_d); the printed gate agreements are capped there"
             if cd is not None else "no certified_depth_d in the cache header "
             "(an earlier bank block): refused below")
    mp.mp.dps = AMBIENT_DPS
    print("LBL3SE FAST-CACHE mode -- banked gate-demo values (sha-pinned, "
          f"compare-gated); {cdtxt}.")
    print(f"  cache: {os.path.basename(FASTCACHE_PATH)}  banked "
          f"{prov['generated_utc']} by: {prov['generator_cmd']}")
    print(f"  banked live wall {prov['wall_s']:.0f}s; this fast start serves "
          f"--dps <= {pt['cached_dps']} (requested {QUAD_DPS})")
    print("  cache = fast start ONLY; the live machinery in this file is the "
          "definition (--no-fastcache)\n")
    # --- [p1] integrity pins ------------------------------------------------
    for fname, want in fc['_pins'].items():
        if _fc_sha(fname) != want:
            _fc_fail(f"sha256 pin mismatch on {fname} (definition changed "
                     "since banking; cache is STALE)")
    for key, want in pt['_string_pins'].items():
        if _fc_str_sha(pt[key]) != want:
            _fc_fail(f"cached string '{key}' fails its sha pin (mutated)")
    print(f"[p1] integrity: {len(fc['_pins'])} file pins + "
          f"{len(pt['_string_pins'])} cached-string pins OK")
    if cd is None:   # 2026-09-06: no certified depth recorded -> fail closed
        _fc_fail("cache header lacks certified_depth_d (written by an earlier "
                 "bank block); cache is STALE")
    # 2026-09-06 (Q20f): the header's certified depth is never TRUSTED -- it is
    # re-derived from the banked_d rows the compare gates below re-verify, and a
    # header that disagrees with its own rows is refused by name (the same
    # refusal path as the header-less case)
    cd_rows = int(math.floor(min(float(v) for v in pt['banked_d'].values())))
    if cd != cd_rows:
        _fc_fail(f"cache header certified_depth_d {cd} != floor(min banked_d) "
                 f"{cd_rows} (the header disagrees with the cache's own rows); "
                 "cache is STALE")
    # --- [p2] held-out oracle gates recomputed NOW on the banked strings ----
    I_c = mp.mpf(pt['I_gate'])
    r12_c = mp.mpf(pt['rho12'])
    sw_c = mp.mpf(pt['kernel_swap_rich'])
    print("[p2] held-out oracle gates recomputed NOW from the banked strings "
          "vs the in-script literals:")
    print(f"           I(-1,-1/3,1)   = {mp.nstr(I_c, 44)}   (banked; "
          f"certified depth {cd} d by the two-precision pair; "
          f"{len(pt['I_gate'])} stored characters)")
    _fc_gate("I vs GT_AMF (indep. AMFlow eps-grid)",
             agree_digits(I_c, mp.mpf(GT_AMF_STR)), pt['banked_d']['dA'], 30, cap=cd)
    _fc_gate("I vs GT_PARENT (indep. 9-prop family)",
             agree_digits(I_c, mp.mpf(GT_PARENT_STR)), pt['banked_d']['dP'], 30, cap=cd)
    print(f"           rho(12)        = {mp.nstr(r12_c, 50)}   (banked)")
    _fc_gate("rho(12) vs held-out AMFlow w=12",
             agree_digits(r12_c, mp.mpf(RHO_W12_STR)), pt['banked_d']['d12'],
             min(QUAD_DPS - 10, 30), cap=cd)
    # 2026-09-04: the row script's rho(5)/rho(100) spot gates on the cached
    # density strings (floors GATE_FLOORS at the requested --dps)
    r5_c = mp.mpf(pt['rho5'])
    r100_c = mp.mpf(pt['rho100'])
    print(f"           rho(5)         = {mp.nstr(r5_c, 50)}   (banked)")
    _fc_gate("rho(5) vs AMFlow solve_integrals w=5",
             agree_digits(r5_c, mp.mpf(RHO5_STR)), pt['banked_d']['d5'],
             GATE_FLOORS['rho(5)'](QUAD_DPS), cap=cd)
    print(f"           rho(100)       = {mp.nstr(r100_c, 50)}   (banked)")
    _fc_gate("rho(100) vs AMFlow solve_integrals bnd_w100",
             agree_digits(r100_c, mp.mpf(RHO100_STR)), pt['banked_d']['d100'],
             GATE_FLOORS['rho(100)'](QUAD_DPS), cap=cd)
    print(f"           kernel-swap    = {mp.nstr(sw_c, 44)}   (banked 2L-L)")
    _fc_gate("kernel-swap vs -Sigma_kite(-1) (AMFlow >=60d)",
             agree_digits(sw_c, mp.mpf(KITE_M1_STR)), pt['banked_d']['dSwap'], 30, cap=cd)
    # --- [p3] live cheap cross-checks ----------------------------------------
    print("[p3] live cheap cross-checks (machinery exercised NOW):")
    t0 = time.time()
    funcs, masters = load_kite_de()
    M0, d_seed, seed_dps = load_kite_boundary(masters)
    bar_seed = min(seed_dps, 128) - DSEED_MARGIN
    print(f"           live w=5 seed held-out gate: {mp.nstr(d_seed, 5)} d >= "
          f"bar {bar_seed} d  ({time.time()-t0:.1f}s) -- RAISES on fail")
    if not d_seed >= bar_seed:
        _fc_fail(f"live seed held-out gate {mp.nstr(d_seed, 5)} d < {bar_seed} d")
    t0 = time.time()
    kdps_live = 28          # kernel-gate class: dilog box REBUILT live, cheap
    Kl = BoxKernel(mp.mpf(-1), mp.mpf(-1) / 3, mp.mpf(1), kdps_live,
                   verbose=False)
    dK = agree_digits(Kl.tay1[0], mp.mpf(pt['K1_const']))
    bar_K = kdps_live - 4
    print(f"           live dilog-box kernel rebuild (dps {kdps_live}): K(1) "
          f"vs banked constant {mp.nstr(dK, 5)} d >= bar {bar_K} d  "
          f"({time.time()-t0:.1f}s)")
    if not dK >= bar_K:
        _fc_fail(f"live kernel rebuild vs banked K(1): {mp.nstr(dK, 5)} d "
                 f"< bar {bar_K} d")
    # --- [p4] the closed-form density at the density gate points (2026-09-11, section C2) ---
    if _ARGS.density == 'closed':
        print("[p4] the closed-form density evaluated NOW at the density gate points "
              "(the cached series strings of [p2] are the cross-check):")
        closed_density_gates({'rho(5)': pt['rho5'], 'rho(12)': pt['rho12'], 'rho(100)': pt['rho100']},
                             f"the cached strings of the --dps {pt['cached_dps']} run above",
                             bar12=min(QUAD_DPS - 10, 30), bar_series=min(QUAD_DPS - 10, 30))
    print(f"\ntotal wall time: {time.time()-T0:.1f}s")
    print("PASS (fast-cache) -- banked values re-gated vs all held-out "
          "oracles + live seed/kernel cross-checks; for the full live run "
          "use --no-fastcache")
    raise SystemExit(0)


def _fc_bank(payload, wall_s):
    """Write lbl3se-fastcache.json after a PASSING live gate run."""
    import datetime
    pt = dict(payload)
    pt['_string_pins'] = {k: _fc_str_sha(pt[k]) for k in
                          ('I_gate', 'rho12', 'kernel_swap_rich', 'K1_const')}
    pt['_string_pins'].update({k: _fc_str_sha(pt[k]) for k in ('rho5', 'rho100')})
    fc = {
        '_doc': ("fast-start cache for lbl3se-evaluate.py: banked from ONE "
                 "full live run (command below).  The live machinery is the "
                 "definition; this file only fast-starts the banked gate "
                 "demo and is refused on any sha-pin or compare-gate "
                 "mismatch.  Regenerate: --fastcache-bank."),
        '_provenance': {
            'generated_utc': datetime.datetime.now(
                datetime.timezone.utc).isoformat(),
            'generator_cmd': 'python3 lbl3se-evaluate.py --dps '
                             f'{QUAD_DPS} --fastcache-bank',
            'settings': {'QUAD_DPS': QUAD_DPS, 'LEVEL': LEVEL, 'DPS': DPS,
                         'NORD': NORD},
            'wall_s': wall_s,
            'source': '<archive>/axis3_wave/disp-fastcache/',
        },
        # 2026-09-06: the certified depth = floor of the smallest recorded agreement
        # in banked_d (the two-precision pair the cache itself records); read, never typed
        'certified_depth_d': int(math.floor(min(float(v) for v in pt['banked_d'].values()))),
        'depth_note': (f"the stored strings are the evaluator's own dps-{QUAD_DPS} output "
                       f"(mp.nstr at QUAD_DPS + 8 = {QUAD_DPS + 8} significant digits); "
                       "certified_depth_d is the floor of the smallest agreement in "
                       "banked_d (the two-precision pair the cache records, 2026-09-06); "
                       "no digit beyond it is claimed"),
        '_pins': {f: _fc_sha(f) for f in _FC_PIN_FILES},
        'points': {_FC_GATE_KEY: pt},
    }
    with open(FASTCACHE_PATH, 'w') as fh:
        json.dump(fc, fh, indent=1)
    print(f"[fast-cache] BANKED {FASTCACHE_PATH} (dps {pt['cached_dps']}; certified "
          f"depth {fc['certified_depth_d']} d by the two-precision pair; "
          f"{len(fc['_pins'])} file pins)")


# ======================= A. Box1 kernel: closed dilogarithmic form ===========
# One-loop massive box, four on-shell massless legs, masses (M5,m2,m2,m2),
# pySecDec normalization.  Cheng-Wu + degenerate (x1,x2) quadratic reduce the
# Feynman parametrisation to a single dv integral of a 4-root partial-fraction
# log sum g(v); complex singularities of g sit at v=-1 and |v|=1, independent
# of M5, so one fixed Gauss-Legendre rule converges uniformly in M5=w.
# (Port of <archive>/phys_lbl3se/numeric/box1_dilog.py, verified >=50d there.)
_GL_CACHE = {}


def _gl(n, work):
    key = (n, work)
    xw = _GL_CACHE.get(key)
    if xw is None:
        old = mp.mp.dps
        mp.mp.dps = work
        xw = mp.gauss_quadrature(n, 'legendre')
        mp.mp.dps = old
        _GL_CACHE[key] = xw
    return xw


def _g_of_v(v, s, u, m2, M5, a):
    vp1 = v + 1
    p1 = a * v + (M5 + m2)
    r1 = m2 * vp1 * vp1
    p2 = (M5 + m2) * vp1
    r2 = r1 - u * v
    sd1 = mp.sqrt(p1 * p1 - 4 * M5 * r1)
    sd2 = mp.sqrt(p2 * p2 - 4 * M5 * r2)
    twoM5 = 2 * M5
    mal = (p1 - sd1) / twoM5; malp = (p1 + sd1) / twoM5
    mbe = (p2 - sd2) / twoM5; mbep = (p2 + sd2) / twoM5
    Ral = -1 / ((u + s * mal) * sd1); Ralp = 1 / ((u + s * malp) * sd1)
    Rbe = 1 / ((u + s * mbe) * sd2); Rbep = -1 / ((u + s * mbep) * sd2)
    return -(Ral * mp.log(mal) + Ralp * mp.log(malp)
             + Rbe * mp.log(mbe) + Rbep * mp.log(mbep))


def box1(s, t, m2, M5, dps=40):
    """eps^0 of the one-loop massive box, >= dps digits, computed at runtime.
    Deep-Euclidean region: s<0, t<0, m2>0, M5>0, u=-s-t < 4 m2."""
    work = dps + 18
    old_dps = mp.mp.dps
    mp.mp.dps = work
    s = mp.mpf(s); t = mp.mpf(t); m2 = mp.mpf(m2); M5 = mp.mpf(M5)
    u = -s - t
    a = M5 + m2 - s
    if not (s < 0 and t < 0 and m2 > 0 and M5 > 0) or u >= 4 * m2:
        mp.mp.dps = old_dps
        raise ValueError("box1: need s<0, t<0, m2>0, M5>0, u=-s-t<4m2")
    n = work + 12
    n += n % 2   # even rule: an odd rule places a node at the midpoint v = 2 exactly, where
                 # (u + s*malp) and (u + s*mbep) vanish together as M5 -> inf at kinematic
                 # points with -u/s = 3 (t = 2s), a removable singularity that the node would
                 # divide by; an even rule has no node there.
    nodes, weights = _gl(n, work)
    L = mp.mpf(2)
    one = mp.mpf(1)
    tot = mp.mpf(0)
    for tk, wk in zip(nodes, weights):
        v = L * (one + tk) / (one - tk)
        dv = L * 2 / (one - tk) ** 2
        tot += wk * _g_of_v(v, s, u, m2, M5, a) * dv
    mp.mp.dps = old_dps
    return +tot


# ---- fast kernel evaluation: runtime-built interpolants of the CLOSED form.
# K is analytic on (0,inf) (Euclidean s,t); on each finite region a Chebyshev
# interpolant (built and VERIFIED at runtime, degree set by QUAD_DPS via the
# Bernstein-ellipse rate to the nearest singularity w=0) evaluates it in ~1ms.
# This is an evaluation device for the closed form, not stored data.
class BoxKernel:
    def __init__(self, s, t, m2, qd, taylor_nmax=None, verbose=True):
        self.s, self.t, self.m2 = s, t, m2
        self.kd = qd + 8                      # kernel target digits
        # 2026-07-06 depth fix: tay1 depth follows the corrected add-back
        # formula (+6 pad over the disp_subtracted slice) instead of the old
        # 1.9*qd+6 -- see kernel_nmax_for() for the measured derivation.
        self.nmax = taylor_nmax or kernel_nmax_for(qd) + 6
        self._direct_cache = {}
        old = mp.mp.dps
        mp.mp.dps = self.kd + 20
        # region A: Taylor about w=1 on [0.62,1.38] (also the addback coeffs).
        # 2026-07-06: the collocation samples carry a MEASURED coefficient
        # noise floor ~ fn_dps - 0.21*nmax (monomial-Vandermonde amplification
        # of the function-value error; probe_depth.log showed the old build
        # saturating at 13.5-18 d at qd=25, nmax=95, fn evals at kd=33) -- so
        # the node evaluations are guarded at fn_dps = kd+12 + nmax/4 + 10,
        # and the solve inherits fn_dps+25 >= the 0.7*nmax LU wall for all
        # qd <= ~230.
        fn_dps = self.kd + 12 + self.nmax // 4 + 10
        self.tay1 = kernel_taylor(lambda w, _d=fn_dps: self._direct(w, dps=_d),
                                  mp.mpf(1), self.nmax,
                                  radius=mp.mpf('0.4'), dps=fn_dps)
        # regions B, C1, C2: barycentric Chebyshev (numerically stable)
        ln10 = mp.log(10)
        self.bary = []
        for (a, b) in ((mp.mpf('1.38'), mp.mpf(9)), (mp.mpf(9), mp.mpf(40)),
                       (mp.mpf(40), mp.mpf(200))):
            c, L = (a + b) / 2, (b - a) / 2
            rho_e = c / L + mp.sqrt((c / L) ** 2 - 1)   # sing at w=0
            N = int(mp.ceil(qd * ln10 / mp.log(rho_e))) + 15
            xs = [c + L * mp.cos(mp.pi * j / N) for j in range(N + 1)]
            fs = [self._direct(x) for x in xs]
            ws = [(mp.mpf(1) if j % 2 == 0 else mp.mpf(-1)) *
                  (mp.mpf('0.5') if j in (0, N) else mp.mpf(1))
                  for j in range(N + 1)]
            self.bary.append((a, b, xs, fs, ws))
        mp.mp.dps = old
        if verbose:
            self.verify()

    def _direct(self, w, dps=None):
        return box1(self.s, self.t, self.m2, w, dps=dps or self.kd)

    # 2026-09-06 (Q20f): the far-tail floor.  The closed dilog box's four-root
    # partial fraction resolves mal = (p1 - sd1)/(2 M5) ~ 1/M5 only while its working digits
    # (dps + 18) exceed log10 w: past that the discriminant rounds to p1^2,
    # sd1 == p1, mal = mbe = 0, log 0 = -inf and Ral*log(mal) + Rbe*log(mbe)
    # is inf - inf = NaN (measured onset w ~ 1e37.5 at the served floor of 18,
    # dps-independent; reached by every --dps >= 72, whose W_MAX = 10^(dps//2+2)
    # exceeds it).  Below TAIL_W_SWITCH the served relaxation is kept EXACTLY
    # (every documented tier <= dps 55 has W_MAX <= 1e29 there, so no such tier
    # can change a bit); at or above it the box dps is floored at
    # ceil(log10 w) + TAIL_MARGIN, which resolves mal to TAIL_MARGIN + 18 = 30
    # relative digits (the artifact's value-claim bar) at every tail node, and
    # every tail value is asserted finite (rc 1 naming the node and the
    # quantity: fail closed).  Below the onset the served relaxation still caps
    # the kernel's tail accuracy (see the module docstring); this floor does
    # not lift that cap.
    TAIL_W_SWITCH = 10 ** 36     # a half-decade under the measured onset 1e37.5
    TAIL_MARGIN = 12

    def _tail(self, w):
        """direct eval with dps relaxed by the tail suppression (w/200)^-2;
        at or above TAIL_W_SWITCH the dps is floored at ceil(log10 w) +
        TAIL_MARGIN and the value asserted finite (2026-09-06, Q20f)."""
        key = mp.nstr(w, 30)
        v = self._direct_cache.get(key)
        if v is None:
            drop = int(2 * mp.log10(w / 200))
            d = max(18, self.kd - drop)
            if w >= self.TAIL_W_SWITCH:
                d = max(d, int(mp.ceil(mp.log10(w))) + self.TAIL_MARGIN)
            v = self._direct(w, dps=d)
            if not mp.isfinite(v):
                raise RuntimeError(
                    f"[kernel] K(w) (the closed dilog box on the far tail) is "
                    f"not finite (nan/inf) at the tail node w = {mp.nstr(w, 8)} "
                    f"(box dps {d}) -- fail closed")
            self._direct_cache[key] = v
        return v

    def __call__(self, w):
        w = mp.mpf(w)
        if mp.mpf('0.62') <= w <= mp.mpf('1.38'):
            u = w - 1
            acc = mp.mpf(0)
            for cn in reversed(self.tay1):
                acc = acc * u + cn
            return acc
        for (a, b, xs, fs, ws) in self.bary:
            if a <= w <= b:
                num = den = mp.mpf(0)
                for xj, fj, wj in zip(xs, fs, ws):
                    d = w - xj
                    if d == 0:
                        return fj
                    r = wj / d
                    num += r * fj
                    den += r
                return num / den
        return self._tail(w)

    def verify(self):
        """live self-check: interpolants vs the closed form at interior points.
        axis3 wave: also a Gauss-Legendre two-depth probe (same closed form at
        node counts n and n+24: certifies the fixed GL rule inside box1 by
        depth agreement), both RAISING.  Returns (worst interpolant digits,
        worst GL two-depth |diff|) for the value-level error budget."""
        worst = mp.inf
        for w in ('1.03', '1.21', '2.71', '6.9', '13.7', '33.3', '77.7', '181'):
            worst = min(worst, agree_digits(self(mp.mpf(w)), self._direct(mp.mpf(w))))
        print(f"           kernel interpolant self-check (8 pts): "
              f">= {mp.nstr(worst, 5)} d vs direct closed form")
        if worst < QUAD_DPS + 3:
            raise SystemExit("kernel interpolant below target accuracy -- STOP")
        gl_worst = mp.mpf(0)
        for w in ('1.21', '6.9'):
            v1 = self._direct(mp.mpf(w))
            v2 = self._direct(mp.mpf(w), dps=self.kd + 12)   # n -> n+12 nodes,
            gl_worst = max(gl_worst, abs(v1 - v2))           # +12 work digits
        with mp.workdps(20):
            print(f"           [cert] kernel GL two-depth probe (2 pts, "
                  f"n vs n+12 nodes): worst |diff| {mp.nstr(gl_worst, 3)} "
                  f"(bar 1e-{self.kd - 6})")
        if gl_worst > mp.mpf(10) ** -(self.kd - 6):
            raise RuntimeError(f"[cert] GL two-depth probe {mp.nstr(gl_worst, 4)}"
                               f" > 1e-{self.kd - 6} -- kernel closed form not "
                               "certified at target depth, STOP")
        self.worst_interp_d = worst
        self.gl_worst = gl_worst
        return worst, gl_worst


# ============ B. subtracted tanh-sinh dispersion quadrature ==================
# Port of <archive>/phys_lbl3se/numeric/tools/dispersion_subtracted/disp_sub.py:
# subtract the closed-form threshold model S(w) on a sub-panel, add back
# \int S*K in closed form (kernel Taylor x exact power-log moments), tanh-sinh
# the analytic remainder.  Exponentially convergent in the level L.
def moment_powerlog(p, m, L):
    r"""\int_0^L u^p (log u)^m du, closed form (p>-1, m in {0,1,2})."""
    p = mp.mpf(p); L = mp.mpf(L)
    pp = p + 1
    Lp = L ** pp
    lnL = mp.log(L)
    if m == 0:
        return Lp / pp
    if m == 1:
        return Lp / pp * (lnL - 1 / pp)
    if m == 2:
        return Lp / pp * (lnL * lnL - 2 * lnL / pp + 2 / pp ** 2)
    raise ValueError("m in {0,1,2}")


def kernel_nmax_for(dps):
    """Corrected add-back/kernel-Taylor depth (2026-07-06 depth-formula fix,
    work directory <archive>/axis3_wave/lbl3se-depth/).

    DERIVATION (measured; probe_depth2.log in that directory): K = Box1 is
    analytic about w=1 with nearest singularity at w=0, so its Taylor radius
    is R=1 and the degree-N truncation at offset u behaves like (u/R)^{N+1}:
    at the sub_width edge u ~ 0.4 that is log10(1/0.4) = 0.398 digits/term in
    theory; the MEASURED law on conditioning-guarded builds is

        digits(N) = 0.378*N + 4.4    (u = 0.3989; slope stable to 0.01 across
                                      dps 25/40/60; theory minus subleading
                                      coefficient growth)

    The old depth N = 1.7*dps+10 therefore delivered only 0.398*(1.7*dps+10)
    ~ 0.68*dps+9 digits -- exactly the 2026-07-05 flagged gate-value ceiling
    (26.04 d at dps 25, 36.14 d at dps 40, refusal at dps 30).  Requiring the
    add-back truncation to certify dps+8 digits at u=0.4 with the MEASURED
    slope gives

        N = (dps + 8) / 0.378 + 1    (measured delivery ~ dps+12 at the live
                                      probe offsets -> add-back bound after
                                      the intS/pi factor ~ 1e-(dps+13))

    Wall cost measured: guarded Taylor build 1.8 / 3.9 / 9.0 s at dps
    25/40/60 -- negligible vs the quadrature/transport walls."""
    return int((dps + 8) / 0.378) + 1


def kernel_taylor(K, wstar, nmax, radius=None, dps=40):
    """Taylor coeffs of the analytic kernel about w* via Chebyshev collocation
    (real evaluations only), computed at runtime.  2026-07-06 depth fix: the
    solve precision is guarded against monomial-Vandermonde LU pivot
    underflow, MEASURED at ~0.63*nmax digits (nmax=134 at 85 dps raises
    'numerically singular', nmax=95 at 70 dps passes -- probe_depth.log):
    solve dps >= 0.7*nmax + 20 with margin."""
    wstar = mp.mpf(wstar)
    radius = mp.mpf(radius if radius is not None else '0.4')
    old = mp.mp.dps
    mp.mp.dps = max(dps + 25, int(0.7 * nmax) + 20)
    N = nmax + 1
    us = [radius * mp.cos(mp.pi * (j + mp.mpf('0.5')) / N) for j in range(N)]
    fs = [mp.mpf(K(wstar + u)) for u in us]
    V = mp.matrix(N, N)
    for j in range(N):
        p = mp.mpf(1)
        for n in range(N):
            V[j, n] = p
            p *= us[j]
    a = mp.lu_solve(V, mp.matrix(fs))
    mp.mp.dps = old
    return [a[n] for n in range(N)]


def addback_endpoint(coeffs, Kc, L, side='left'):
    r"""Closed-form \int_panel S(w) K(w) dw from exact power-log moments."""
    L = mp.mpf(L)
    tot = mp.mpf(0)
    sgn = mp.mpf(1) if side == 'left' else mp.mpf(-1)
    for (c, alpha, m) in coeffs:
        c = mp.mpf(c); alpha = mp.mpf(alpha)
        for n, Kn in enumerate(Kc):
            tot += c * Kn * (sgn ** n) * moment_powerlog(alpha + n, m, L)
    return tot


def _Smodel(coeffs, wstar, side, wp):
    s = (wp - wstar) if side == 'left' else (wstar - wp)
    if s <= 0:
        return mp.mpf(0)
    val = mp.mpf(0)
    for (c, alpha, m) in coeffs:
        t = mp.mpf(c) * s ** mp.mpf(alpha)
        if m:
            t *= mp.log(s) ** int(m)
        val += t
    return val


def disp_subtracted(rho, K, panels, dps=40, kernel_nmax=None, maxdegree=None,
                    Kc_pre=None):
    r"""(1/pi) \int rho K dw -- the quadrature RUNS here at every call.
    Kc_pre: optional precomputed kernel-Taylor coeffs about the threshold.
    axis3 wave: returns (value, engine error estimate) -- the estimate is the
    sum over panels of mpmath's own tanh-sinh error estimates (error=True;
    same node arithmetic, value unchanged), divided by pi like the value."""
    work = dps + 20
    old = mp.mp.dps
    mp.mp.dps = work
    if kernel_nmax is None:
        # 2026-07-06 depth fix: was int(1.7*dps)+10, which capped the add-back
        # (and with it the gate value) at ~0.68*dps+9 digits -- measured
        # derivation in kernel_nmax_for().
        kernel_nmax = kernel_nmax_for(dps)
    errs = [mp.mpf(0)]

    def _ts(f, a, b):
        if maxdegree is None:
            v, e = mp.quad(f, [a, b], method='tanh-sinh', error=True)
        else:
            v, e = mp.quad(f, [a, b], method='tanh-sinh', maxdegree=maxdegree,
                           error=True)
        errs[0] += abs(e)
        return v

    tot = mp.mpf(0)
    for P in panels:
        a = mp.mpf(P['a'])
        thr = P.get('thresh', None)
        if P.get('map') == 'tail':
            scale = mp.mpf(P.get('scale', a if a > 0 else mp.mpf(1)))
            def ft(t, a=a, scale=scale):
                wp = a + scale * (1 + t) / (1 - t)
                r = rho(wp)
                if r == 0:
                    return mp.mpf(0)      # beyond W_MAX guard
                return r * K(wp) * scale * 2 / (1 - t) ** 2
            tot += _ts(ft, mp.mpf(-1), mp.mpf(1))
            continue
        b = mp.mpf(P['b'])
        if thr is None:
            tot += _ts(lambda wp: rho(wp) * K(wp), a, b)
            continue
        side, wstar, coeffs = thr[0], mp.mpf(thr[1]), thr[2]
        delta = mp.mpf(P.get('sub_width', min(mp.mpf('0.5'), (b - a) / 2)))
        if side == 'left':
            sa, sb = a, a + delta
            ra, rb = a + delta, b
        else:
            sa, sb = b - delta, b
            ra, rb = a, b - delta
        gsm = lambda wp: (rho(wp) - _Smodel(coeffs, wstar, side, wp)) * K(wp)
        tot += _ts(gsm, sa, sb)
        Kc = Kc_pre if Kc_pre is not None else \
            kernel_taylor(K, wstar, kernel_nmax, radius=P.get('radius'), dps=work)
        tot += addback_endpoint(coeffs, Kc[:kernel_nmax + 1], delta, side=side)
        if rb > ra:
            tot += _ts(lambda wp: rho(wp) * K(wp), ra, rb)
    res = tot / mp.pi
    err = errs[0] / mp.pi
    mp.mp.dps = old
    return +res, +err


def lbl3se_panels(A1, Wcut=200):
    """w=1 turn-on subtraction (A1=-2pi closed form); break at the w=9
    Gamma_1(6) cut (finite jump); real [Wcut,inf) tail map."""
    return [{'a': 1, 'b': 9, 'thresh': ('left', 1, [(A1, mp.mpf(1), 1)]),
             'sub_width': mp.mpf(0.4), 'radius': mp.mpf('0.4')},
            {'a': 9, 'b': Wcut, 'thresh': None},
            {'a': Wcut, 'map': 'tail'}]


# ====== C. rho(w) as a runtime Picard-Fuchs series solution ==================
# The exact rational 9x9 kite system (master 4 = [1,1,3,0,0] is a decoupled
# sink, dropped -> 8x8) is eps-expanded at d=4-2eps to eps^{0,1,2} and the
# 24-component Laurent-block system is solved by adaptive local Taylor series
# from the single w=5 seed.  ONE monotone sweep per zone covers (1,inf); every
# step's local series is kept, so rho at ANY w is a Horner evaluation of an
# analytic series -- no stored numeric nodes, precision set by (DPS, NORD, SF).
_KEEP = [0, 1, 2, 3, 5, 6, 7, 8]
_TOP = 7          # local index of J[1,1,1,1,1] in the kept list


def load_kite_de():
    """eps-expand the exact rational DE: the sibling kite_de_exact_parse.py parses
    the shipped symbolic system and grades it at d = 4 - 2 eps in exact rational
    arithmetic (fractions.Fraction; the same integer coefficient lists the earlier
    sympy parse produced, in lowest terms; no numerics happen there).  axis3 wave:
    the denominator root set is VERIFIED at load to be {0,1,9} -- this certifies
    the transport step rule (dmin = min dist to {0,1,9} = local series radius,
    so h <= SF*dmin gives envelope ratio r = |h|/dmin <= SF); the parser proves
    it by exact division (every denominator = a constant times powers of w,
    w - 1, w - 9), a string outside the grammar is REFUSED by name (exit 3)."""
    J = json.load(open(os.path.join(HERE, 'lbl3se-kite-de.json')))
    n = len(_KEEP)
    funcs = [[[None] * n for _ in range(n)] for _ in range(3)]
    try:
        lists = kx.graded_lists(J['A'], _KEEP, 2)
    except kx.ParseError as ex:
        sys.stderr.write(f"{SCRIPT} REFUSED: lbl3se-kite-de.json: {ex}\n")
        raise SystemExit(3)
    try:
        sing = kx.singular_certificate(lists)
    except kx.ParseError as ex:
        raise RuntimeError(f"[cert] kite DE singularities: {ex} -- != subset of "
                           "{0,1,9} -- transport step rule not certified, STOP")
    for (i, j, k), (num, den) in lists.items():
        ii, jj = _KEEP.index(i), _KEEP.index(j)
        # descending coefficient lists, each integer converted as mpf(p) / mpf(q)
        nc = [mp.mpf(c.numerator) / mp.mpf(c.denominator) for c in reversed(num)]
        dc = [mp.mpf(c.numerator) / mp.mpf(c.denominator) for c in reversed(den)]
        funcs[k][ii][jj] = (nc, dc)
    if not sing <= {0, 1, 9}:
        raise RuntimeError(f"[cert] kite DE singularities {sing} != subset of "
                           "{0,1,9} -- transport step rule not certified, STOP")
    return funcs, [tuple(J['masters'][i]) for i in _KEEP]


_ARB_RE = None


def _pb(sv):
    global _ARB_RE
    if _ARB_RE is None:
        import re
        _ARB_RE = re.compile(r'^\s*\[\s*([^\s\]]*)\s*\+/-')
    m = _ARB_RE.match(str(sv).strip())
    return mp.mpf(m.group(1)) if m else mp.mpf(str(sv).strip())


def _seed_cache_check(st, rg):
    """Stored-vs-regenerated seed string check (comparator logic:
    <archive>/small_feeds/compare_seed_strings.py, w5 mode):
    PASS per component iff byte-prefix either way, OR final-digit
    round-to-nearest, OR numerical zero (each value below its own run's
    noise floor 10^-(dps+5) -- the mathematically-vanishing components:
    sub-threshold Im parts and the finite kite's eps^-2/eps^-1)."""
    assert st['masters'] == rg['masters'] and st['orders'] == rg['orders']
    ok = ncomp = 0
    bad = []
    with mp.workdps(max(int(st['dps']), int(rg['dps'])) + 20):
        zt_st = mp.mpf(10) ** (-(int(st['dps']) + 5))
        zt_rg = mp.mpf(10) ** (-(int(rg['dps']) + 5))
        for mi, mname in enumerate(st['masters']):
            for oi, o in enumerate(st['orders']):
                for c, part in enumerate(('re', 'im')):
                    s_st = st['values'][mi][oi][c]
                    s_new = rg['values'][mi][oi][c]
                    ncomp += 1
                    short, long_ = sorted((s_st, s_new), key=len)
                    if long_.startswith(short):
                        ok += 1
                        continue
                    p = 0
                    for x, y in zip(s_st, s_new):
                        if x != y:
                            break
                        p += 1
                    if p >= min(len(s_st), len(s_new)) - 1:  # last-digit rounding
                        ok += 1
                        continue
                    if abs(mp.mpf(s_st)) < zt_st and abs(mp.mpf(s_new)) < zt_rg:
                        ok += 1                              # numerical zeros
                        continue
                    bad.append((str(mname), o, part,
                                f"prefix {p}/{min(len(s_st), len(s_new))}"))
    return ok, ncomp, bad


def load_kite_boundary(masters):
    """Laurent coeffs eps^{-2..0} of the 8 masters at w=5 -- the transport
    SEED, now the DERIVED AMFlow-free vector lbl3se-w5-derived.json (emitted
    once at dps 80 by lbl3se-w5-seed.py in this directory: p^2=0 vacuum closed
    forms + Frobenius at w=0 + exact-DE Taylor march to w=5; rerunnable).
    With --boundary-recompute [DPS] the seed is REGENERATED live by that
    script and the stored strings demote to a byte-agreement cache check.
    The retired AMFlow w=5 vector (lbl3se-kite-boundary-w5.json) is NOT
    consumed upstream: it is loaded only as a held-out cross-check of the
    derived seed, and the recomputed agreement is returned for printing."""
    D = json.load(open(os.path.join(HERE, 'lbl3se-w5-derived.json')))
    if getattr(_ARGS, 'boundary_recompute', None) is not None:
        import subprocess
        import sys as _sys
        import tempfile
        _bdps = _ARGS.boundary_recompute
        if _bdps <= 0:      # bare flag: track --dps so the path is uncapped
            _bdps = max(80, QUAD_DPS + 30)
        print(f"           [boundary-recompute] deriving the w=5 seed live: "
              f"lbl3se-w5-seed.py --dps {_bdps} --json <tmp> ...")
        _tf = tempfile.NamedTemporaryFile(suffix='.json', delete=False)
        _tf.close()
        subprocess.run([_sys.executable, os.path.join(HERE, 'lbl3se-w5-seed.py'),
                        '--dps', str(_bdps), '--json', _tf.name, '-q'],
                       check=True)
        D_LIVE = json.load(open(_tf.name))
        os.unlink(_tf.name)
        _ok, _ncomp, _bad = _seed_cache_check(D, D_LIVE)
        print(f"           [boundary-recompute] stored-string cache check: "
              f"{_ok}/{_ncomp} -> {'PASS' if _ok == _ncomp else 'FAIL'}")
        if _ok != _ncomp:
            raise RuntimeError("[cert] [boundary-recompute] stored-string "
                               f"cache check FAILED ({_ok}/{_ncomp}): "
                               f"{_bad[:5]} -- stored fast-start cache does "
                               "not match the live derivation, STOP")
        D = D_LIVE
    dmast = [tuple(m) for m in D['masters']]
    n = len(masters)
    out = {k: [mp.mpc(0)] * n for k in (-2, -1, 0)}
    for loc, idx in enumerate(masters):
        i = dmast.index(idx)
        for t, o in enumerate(D['orders']):
            if o in out:
                re_s, im_s = D['values'][i][t]
                out[o][loc] = mp.mpc(mp.mpf(re_s), mp.mpf(im_s))
    # held-out cross-check: derived seed vs the retired AMFlow vector
    J = json.load(open(os.path.join(HERE, 'lbl3se-kite-boundary-w5.json')))
    worst = mp.inf
    for r in J['result']:
        idx = tuple(r['integral']['indices'])
        if idx not in masters:
            continue
        loc = masters.index(idx)
        for c in r['coefficients']:
            o = c['order']
            if o not in out:
                continue
            ref = mp.mpc(_pb(c['value']['re']), _pb(c['value']['im']))
            dv = mp.fabs(out[o][loc] - ref)
            if dv != 0:
                worst = min(worst, -mp.log10(dv / max(mp.fabs(ref), mp.mpf(1))))
    return out, worst, int(D['dps'])


def _shiftpoly(coefs, x0, zero):
    """ascending Taylor coeffs about x0 of the poly with DESCENDING coefs."""
    p = [coefs[0] + zero]
    for c in coefs[1:]:
        pn = [zero] * (len(p) + 1)
        for m_, a in enumerate(p):
            pn[m_] += a * x0
            pn[m_ + 1] += a
        pn[0] += c
        p = pn
    return p


def _sparse_A_taylor(funcs, w0, N, real):
    """Per-eps-order Taylor series of A about w0; real arithmetic on the real
    axis (2x faster complex-times-real products in the state recursion)."""
    zero = mp.mpf(0) if real else mp.mpc(0)
    n = len(_KEEP)
    out = []
    for jj in range(3):
        ser_m = [[] for _ in range(N + 1)]
        for i in range(n):
            for jc in range(n):
                cd = funcs[jj][i][jc]
                if cd is None:
                    continue
                nc, dc = cd
                ph = _shiftpoly(nc, w0, zero)
                qh = _shiftpoly(dc, w0, zero)
                q0 = qh[0]
                r = [1 / q0]
                for m_ in range(1, N + 1):
                    sacc = zero
                    for l in range(1, min(m_, len(qh) - 1) + 1):
                        sacc += qh[l] * r[m_ - l]
                    r.append(-sacc / q0)
                for m_ in range(N + 1):
                    sacc = zero
                    for l in range(min(m_, len(ph) - 1) + 1):
                        sacc += ph[l] * r[m_ - l]
                    if sacc != 0:
                        ser_m[m_].append((i, jc, sacc))
        out.append(ser_m)
    return out


def _c_recursion(C, Aser, n, m_lo, m_hi):
    """Continue the state-coefficient recursion for orders m_lo..m_hi-1
    (EXACT continuation: same recurrence, same lower coefficients)."""
    for m_ in range(m_lo, m_hi):
        for k in (-2, -1, 0):
            sacc = [mp.mpc(0)] * n
            for j in range(3):
                if k - j < -2:
                    continue
                Clist = C[k - j]
                Alist = Aser[j]
                for l in range(m_ + 1):
                    cv = Clist[m_ - l]
                    for (ri, ci, a) in Alist[l]:
                        sacc[ri] += a * cv[ci]
            inv = mp.mpf(1) / (m_ + 1)
            C[k].append([x * inv for x in sacc])


def _tail_bound(C, N, absh, r):
    """Certified geometric tail bounds (WP1 pilot construction, WIRING_LOG
    items 12-13): max |c_n h^n| over the trailing TAIL_WINDOW orders, times
    r/(1-r) with r = |h|/dmin certified by the step rule (h <= SF*dmin) + the
    verified singularity set {0,1,9}.  Returns (tail_all, tail_top):
    tail_all over ALL components and eps orders (state integrity; compared
    RELATIVELY to the local state scale, since the dim-2 masters grow ~w),
    tail_top over the eps^0 TOP component only (= the rho value path)."""
    mx = mp.mpf(0)
    mxt = mp.mpf(0)
    hp = absh ** (N - TAIL_WINDOW + 1)
    for m_ in range(N - TAIL_WINDOW + 1, N + 1):
        for k in (-2, -1, 0):
            for x in C[k][m_]:
                ax = abs(x) * hp
                if ax > mx:
                    mx = ax
        axt = abs(C[0][m_][_TOP]) * hp
        if axt > mxt:
            mxt = axt
        hp *= absh
    fac = r / (1 - r)
    return mx * fac, mxt * fac


def taylor_step(funcs, M, w0, h, N, real, dmin=None, tol=None, ncap=None):
    """One local-series step of the Laurent-block system.  Returns the state
    at w0+h AND the eps^0 TOP-component series (for later rho evaluation).
    axis3 wave: N is a STARTING guess; if (dmin, tol, ncap) are given the
    trailing-window geometric tail bound RELATIVE to the local state scale
    must beat tol, else the SAME recurrences are continued exactly at N*1.5
    up to ncap (RuntimeError at cap, naming step/x0/h/achieved bound/tol/N/
    cap).  Returns (state, top_series, relative state-tail, absolute TOP
    (rho-path) tail, N used)."""
    n = len(_KEEP)
    Aser = _sparse_A_taylor(funcs, w0, N, real)
    C = {k: [list(M[k])] for k in (-2, -1, 0)}
    _c_recursion(C, Aser, n, 0, N)
    rel = btop = None
    if tol is not None:
        absh = abs(h)
        r = absh / dmin
        if not r < mp.mpf('0.9'):
            raise RuntimeError(f"[cert] transport step at w0={mp.nstr(mp.mpc(w0), 12)}: "
                               f"envelope ratio r={mp.nstr(r, 6)} >= 0.9 -- "
                               "step rule violated (SF too large), STOP")
        s0 = mp.mpf(1)
        for k in (-2, -1, 0):
            for x in C[k][0]:
                ax = abs(x)
                if ax > s0:
                    s0 = ax
        while True:
            ball, btop = _tail_bound(C, N, absh, r)
            rel = ball / s0
            if rel < tol:
                break
            if N >= ncap:
                raise RuntimeError(
                    f"[cert] transport step at w0={mp.nstr(mp.mpc(w0), 12)}, "
                    f"h={mp.nstr(mp.mpc(h), 12)}: certified relative tail "
                    f"{mp.nstr(rel, 4)} >= tol {mp.nstr(tol, 4)} at "
                    f"N={N} (cap {ncap}) -- refine-until-bound FAILED, STOP")
            N2 = min(ncap, int(1.5 * N) + 1)
            Aser = _sparse_A_taylor(funcs, w0, N2, real)
            _c_recursion(C, Aser, n, N, N2)
            N = N2
    out = {}
    for k in (-2, -1, 0):
        v = [mp.mpc(0)] * n
        hp = mp.mpc(1) if not real else mp.mpf(1)
        for m_ in range(N + 1):
            cm = C[k][m_]
            for i in range(n):
                v[i] += cm[i] * hp
            hp *= h
        out[k] = v
    top_series = [C[0][m_][_TOP] for m_ in range(N + 1)]
    return out, top_series, rel, btop, N


class RhoPF:
    """rho(w) = -Im J_top(w+i0) as a runtime PF-series solution on (1,inf)."""

    def __init__(self, funcs, M0, dps=DPS, N=NORD, sf=SF, verbose=True):
        self.funcs, self.N, self.sf = funcs, N, sf
        self.dps = dps
        self.segs = []          # (a, b, w0, top_eps0_series)
        self.checkpoints = {}   # w -> full state (for closed-form master checks)
        self._starts = None
        old = mp.mp.dps
        mp.mp.dps = dps
        # axis3 wave: certified per-step tail budget (refine-until-bound; the
        # starting N above is a seed, never the answer)
        self.steptol = mp.mpf(10) ** -(QUAD_DPS + TAIL_GUARD)   # RELATIVE
        self.ncap = NCAP_FACT * N
        self.err_top = mp.mpf(0)     # accumulated TOP(rho)-series tail bounds
        self.worst_rel = mp.mpf(0)   # worst relative state tail (escalation)
        self.worst_at = None         # w0 of the worst relative step
        self.n_grow = 0
        self.max_used = N
        t0 = time.time()
        nsteps = 0
        # 2026-09-09 checkpoint form (--checkpoint DIR / --resume DIR; the
        # block before the oracle literals): the zone sequence below is the
        # previous one, driven with a finished-zone skip -- a resumed run
        # restores the accumulators and the finished zones' results (self._zr)
        # from the checkpoint and re-enters the interrupted zone at its
        # recorded step; without the flags self._ck is None, every leg runs
        # as before and nothing else here changes.
        self._zr = {}
        self._ck = _ck_open()
        rs = _ck_restore(self)        # the loop state of the resumed zone, or None
        zones = ('M', 'L', 'A1', 'A2', 'A3', 'A4', 'R2', 'R3', 'DONE')
        done = zones[:zones.index(rs['zone'] if rs is not None else 'M')]
        if rs is not None:
            nsteps = rs['nsteps_done']

        def _rs(z):
            return rs if (rs is not None and rs['zone'] == z) else None
        # zone M: 5 -> 9-V_MIN (up); snapshot the state near 8.4 for the arc hop
        if 'M' not in done:
            _, snap = self._leg(M0, mp.mpf(5), 9 - V_MIN, snap_at=mp.mpf('8.4'),
                                zone='M', resume=_rs('M'))
            nsteps += self._ns
            self.rho_9m = self._scan_eval(9 - V_MIN)
            self._zr['snap'], self._zr['rho_9m'] = snap, self.rho_9m
            _ck_zone_done(self, nsteps)
        else:
            snap, self.rho_9m = self._zr['snap'], self._zr['rho_9m']
        # zone L: 5 -> 1+U_MIN (down)
        if 'L' not in done:
            self._leg(M0, mp.mpf(5), 1 + U_MIN, zone='L', resume=_rs('L'))
            nsteps += self._ns
            _ck_zone_done(self, nsteps)
        # arc hop: snapshot -> 9.5 via the Im(w)>0 semicircle (Feynman s+i0
        # sheet; the Im<0 arc gives the conjugate branch -- verified in the original computation)
        wsn, Marc = snap
        for k, wp in enumerate((mp.mpc('8.5', '0.5'), mp.mpc(9, '0.5'),
                                mp.mpc('9.5', '0.5'), mp.mpc('9.5'))):
            z = f'A{k + 1}'
            if z not in done:
                Marc, _ = self._leg(Marc, wsn, wp, store=False, zone=z, resume=_rs(z))
                nsteps += self._ns
                self._zr['Marc'] = Marc
                _ck_zone_done(self, nsteps)
            else:
                Marc = self._zr['Marc']
            wsn = wp
        # zone R2: 9.5 -> 9+V_MIN (down)
        if 'R2' not in done:
            self._leg(Marc, mp.mpf('9.5'), 9 + V_MIN, zone='R2', resume=_rs('R2'))
            nsteps += self._ns
            self.rho_9p = self._scan_eval(9 + V_MIN)
            self._zr['rho_9p'] = self.rho_9p
            _ck_zone_done(self, nsteps)
        else:
            self.rho_9p = self._zr['rho_9p']
        # zone R3: 9.5 -> W_MAX (up); checkpoint the full state at w=12
        if 'R3' not in done:
            self._leg(Marc, mp.mpf('9.5'), W_MAX, want=(mp.mpf(12),),
                      zone='R3', resume=_rs('R3'))
            nsteps += self._ns
            _ck_zone_done(self, nsteps)
        self.segs.sort(key=lambda s: s[0])
        self._starts = [s[0] for s in self.segs]
        self._wcap = max(s[1] for s in self.segs)
        self.nsteps = nsteps
        _ck_final(self)
        mp.mp.dps = old
        if verbose:
            print(f"           PF sweep: {nsteps} local-series steps "
                  f"(dps={dps}, order={N}, step={float(sf)}*dist), "
                  f"{len(self.segs)} stored segments, {time.time()-t0:.1f}s")
            with mp.workdps(20):
                print(f"           [cert] transport: {nsteps} steps certified; "
                      f"per-step RELATIVE state-tail tol "
                      f"{mp.nstr(self.steptol, 3)} (TAIL_GUARD={TAIL_GUARD}, "
                      f"window={TAIL_WINDOW}); worst rel "
                      f"{mp.nstr(self.worst_rel, 3)} at "
                      f"w0={mp.nstr(mp.mpc(self.worst_at), 8)}")
                print(f"           [cert] transport: TOP(rho)-series tail "
                      f"budget {mp.nstr(self.err_top, 3)}; escalations "
                      f"{self.n_grow} (N start {N}, max used {self.max_used}, "
                      f"cap {self.ncap}); state-mixing certified by the "
                      f"raising held-out gates (rho(12), closed-masters, "
                      f"kernel-swap)")

    # -- internals ------------------------------------------------------------
    def _leg(self, M, w_from, w_to, store=True, snap_at=None, want=(), zone=None,
             resume=None):
        """straight leg w_from -> w_to (real or complex), adaptive local series.
        Returns (final state, snapshot (w, state) if snap_at was crossed).
        2026-09-09: zone names the leg for the checkpoint form; resume = the
        checkpointed loop state of THIS zone (M, w, snap, want, the step
        index), re-entered exactly in place of the leg's start."""
        self._ns = 0
        M = {k: list(M[k]) for k in M}
        w = w_from
        snap = None
        want = list(want)
        real = (mp.im(mp.mpc(w)) == 0 and mp.im(mp.mpc(w_to)) == 0)
        if real:
            w, w_to = mp.re(mp.mpc(w)), mp.re(mp.mpc(w_to))
        if resume is not None:
            M, w, snap, want = resume['M'], resume['w'], resume['snap'], list(resume['want'])
            self._ns = resume['step']
        tol = mp.mpf(10) ** (-self.dps + 8)
        while abs(w_to - w) > tol * max(1, abs(w_to)):
            if self._ck is not None:
                _ck_at_step(self, zone, M, w, snap, want)   # the loop-top checkpoint
            d = min(abs(w), abs(w - 1), abs(w - 9))
            hmax = self.sf * d
            dirn = w_to - w
            h = dirn if abs(dirn) <= hmax else dirn / abs(dirn) * hmax
            if real:
                h = mp.re(mp.mpc(h))
            M2, tser, rel, btop, nu = taylor_step(self.funcs, M, w, h, self.N,
                                                  real, dmin=d,
                                                  tol=self.steptol,
                                                  ncap=self.ncap)
            self.err_top += btop
            if rel > self.worst_rel:
                self.worst_rel = rel
                self.worst_at = w
            if nu > self.N:
                self.n_grow += 1
                if nu > self.max_used:
                    self.max_used = nu
            if real:
                lo, hi = (w, w + h) if h > 0 else (w + h, w)
                if store:
                    self.segs.append((lo, hi, w, tser))
                if snap_at is not None and snap is None and lo <= snap_at <= hi:
                    snap = (w + h, {k: list(M2[k]) for k in M2})
                for wc in list(want):
                    if lo <= wc <= hi:
                        Mc, _, relc, btc, nuc = taylor_step(self.funcs, M, w,
                                                            wc - w, self.N,
                                                            real, dmin=d,
                                                            tol=self.steptol,
                                                            ncap=self.ncap)
                        self.err_top += btc
                        self.checkpoints[wc] = Mc
                        want.remove(wc)
            M = M2
            w = w + h
            self._ns += 1
        return M, snap

    def _scan_eval(self, w):
        """rho during construction (linear scan of stored segments)."""
        for (a, b, w0, ser) in reversed(self.segs):
            if a <= w <= b:
                return self._horner(ser, w - w0)
        raise KeyError(f"rho: w={mp.nstr(w, 20)} not covered yet")

    def _eval(self, w):
        """rho at w from the covering stored local series (Horner)."""
        i = bisect.bisect_right(self._starts, w) - 1
        for j in (i, i + 1, i - 1):
            if 0 <= j < len(self.segs):
                a, b, w0, ser = self.segs[j]
                if a <= w <= b:
                    return self._horner(ser, w - w0)
        return None

    @staticmethod
    def _horner(ser, hh):
        acc = mp.mpc(0)
        for cn in reversed(ser):
            acc = acc * hh + cn
        return -mp.im(acc)

    # -- public ---------------------------------------------------------------
    def __call__(self, w):
        w = mp.mpf(w)
        if w <= 1:
            return mp.mpf(0)
        u = w - 1
        if u < U_MIN:
            return u * (-2 * mp.pi) * mp.log(u)   # closed-form turn-on word
        if abs(w - 9) < V_MIN:
            return self.rho_9m if w < 9 else self.rho_9p
        if w > W_MAX:
            return mp.mpf(0)
        v = self._eval(w)
        if v is not None:
            return v
        # rounding-gap fallbacks at the guard edges (widths ~1 ulp of the guards)
        if u < 2 * U_MIN:
            return u * (-2 * mp.pi) * mp.log(u)
        if abs(w - 9) < 2 * V_MIN:
            return self.rho_9m if w < 9 else self.rho_9p
        if w > mp.mpf('0.9') * self._wcap:
            return mp.mpf(0)
        raise KeyError(f"rho: w={mp.nstr(w, 20)} not covered")


# ====== C2. rho(w) in CLOSED FORM: the printed density (2026-09-11) ==========
# The kite spectral density written out in closed form (the write-up's eqs.
# rho_elem / rho_full / F23; m^2 = 1, w = l^2/m^2):
#
#   rho(w) = rho_elem(w)                                          1 < w <= 9
#   rho(w) = rho_elem(w) - R(w)/w,  R(w) = int_9^w v F23(v) dv          w > 9
#   rho_elem(w) = -(pi/w) [ 2 ln(w-1) ln w + 3 Li2(1-w) ]
#   F23(v)     = [ 2 Im S(v) - (v+3) Im Sdot(v) ] / ( v (v-1)^2 ),
#                                                     x_pm = (sqrt v pm 1)^2
#   Im S(v)    = -(pi/v) int_4^{x_-} sqrt((x_- - s)(x_+ - s)) sqrt((s-4)/s) ds
#   Im Sdot(v) = +(pi/v) int_4^{x_-} (v-1+s)/sqrt((x_- - s)(x_+ - s))
#                                                      * sqrt((s-4)/s) ds
#
# rho_elem is the weight-two part (the bubble and (m,0,0)-sunrise pieces of
# the kite system's inhomogeneity integrated in closed form; its threshold
# expansion -2 pi (w-1) ln(w-1) + 3 pi (w-1) carries the turn-on constant
# A1 = -2 pi as a theorem of the closed form); Im S is the d = 4 equal-mass
# sunrise three-body cut (the Gamma_1(6) object) and Im Sdot the dotted-
# sunrise cut, so above w = 9 the density is a one-fold over the sunrise cut.
# THIS is the density the script evaluates by default at the density gate
# points (w = 5, 12, 100) in every tier, gated against the AMFlow
# solve_integrals references at the served floors; the Picard-Fuchs series
# density (RhoPF above: the transport of the exact kite system, which the
# dispersion quadrature consumes -- the value path of the integrals is not
# touched by this section) is the cross-check, the agreement of the two
# densities printed and gated at the rho self-check bar.  --density series
# restores the previous prints (the series density alone, the closed form
# not evaluated).  --sum-rule runs the spot gate (1/pi) int_1^W rho dw =
# 6 zeta_3 (the large-l^2 normalisation of the kite) on the closed form.
# NUMERICS (every difference formed without cancellation): the two
# s-integrals are taken in two pieces, s = 4 cosh^2 xi on [4, s_mid]
# (sqrt((s-4)/s) = tanh xi) and, on [s_mid, x_-] with s_mid = 2 sqrt(x_-),
# s = s_mid + D cos^2 phi, sin^2 phi = (4 sqrt v / D) sinh^2 eta (so that
# x_+ - s = 4 sqrt v cosh^2 eta), D = x_- - s_mid -- tanh-sinh on the raw
# limits loses half the working digits in Im Sdot at the 1/sqrt(x_- - s)
# endpoint; R(w) by Gauss-Legendre panels in y = ln v with 9, 12, 100 and the
# cutoff among the panel ends (the node count per panel from the Bernstein
# ellipse to the nearest singularity y = 0, as for the kernel device); the
# inner one-folds at CLOSED_DPS_IN = DPS + 11 digits, the sums at DPS + 20.
CLOSED_DPS_IN = DPS + 11      # inner one-fold working digits (the closed form's accuracy)
CLOSED_DPS = DPS + 20         # outer sums / Li2 / the sum-rule integrals
CLOSED_AMBIENT = max(90, CLOSED_DPS + 10)   # parse / compare precision of the gates
CLOSED_PANEL_ENDS = ('9', '9.25', '9.5', '10', '11', '12', '13', '16', '20', '30', '50',
                     '100', '300', '1000', '1e4', '1e6', '1e9', '1e14', '1e22', '1e34',
                     '1e50', '1e75', '1e110', '1e160', '1e240')
CLOSED_ELEM_ENDS = ('1.5', '2', '3', '5', '9', '16', '30', '100', '1000', '1e5', '1e8', '1e12',
                    '1e18', '1e26', '1e38', '1e57', '1e85', '1e128', '1e190')
SUMRULE_LOG10_W_RANGE = (34, 240)           # --sum-rule LOG10_W static range (default 50); within it the
#                                             next-omitted-tail rule of _sum_rule_tier refuses a cutoff
#                                             too low for the running --dps by name


def rho_elem(w):
    """The weight-two closed form -(pi/w)[2 ln(w-1) ln w + 3 Li2(1-w)] at the
    ambient precision; 0 at and below the threshold w = 1."""
    w = mp.mpf(w)
    if w <= 1:
        return mp.mpf(0)
    return -(mp.pi / w) * (2 * mp.log(w - 1) * mp.log(w) + 3 * mp.polylog(2, 1 - w))


def _sunrise_cut(v, dps, dotted):
    """Im S(v) (dotted=False) or Im Sdot(v) (dotted=True) for v > 9 from the
    printed one-folds, in two pieces with the cancellation-free substitutions
    of the block comment.  Returns (value, tanh-sinh engine error estimate)."""
    with mp.workdps(dps):
        v = mp.mpf(v)
        sv = mp.sqrt(v)
        xm = (sv - 1) ** 2            # x_-
        g = 4 * sv                    # x_+ - x_-
        smid = 2 * mp.sqrt(xm)
        D = xm - smid
        ximax = mp.acosh(mp.sqrt(smid) / 2)

        def f1(xi):                   # s = 4 cosh^2 xi on [4, s_mid]
            ch, sh = mp.cosh(xi), mp.sinh(xi)
            s = 4 * ch * ch
            xms = xm - s
            if xms <= 0:
                return mp.mpf(0)
            xps = g + xms
            jac = mp.tanh(xi) * 8 * ch * sh
            if dotted:
                return (v - 1 + s) / mp.sqrt(xms * xps) * jac
            return mp.sqrt(xms * xps) * jac
        I1, e1 = mp.quad(f1, [0, ximax], error=True)
        etamax = mp.asinh(mp.sqrt(D / g))

        def f2(eta):                  # s = s_mid + D cos^2 phi on [s_mid, x_-]
            sh, ch = mp.sinh(eta), mp.cosh(eta)
            S2 = (g / D) * sh * sh    # sin^2 phi
            if S2 >= 1:
                return mp.mpf(0)
            s = smid + D * (1 - S2)
            r = mp.sqrt(((smid - 4) + D * (1 - S2)) / s)
            if dotted:
                return 2 * (v - 1 + s) * r
            return 2 * g * g * r * ch * ch * sh * sh
        I2, e2 = mp.quad(f2, [0, etamax], error=True)
        val = (mp.pi / v) * (I1 + I2)
        return (val if dotted else -val), abs(e1) + abs(e2)


def F23(v, dps):
    """The sunrise-cut inhomogeneity F23(v) of the printed density (v > 9) at
    dps inner digits.  Returns (value, engine error estimate)."""
    with mp.workdps(dps):
        v = mp.mpf(v)
        iS, eS = _sunrise_cut(v, dps, False)
        iSd, eSd = _sunrise_cut(v, dps, True)
        den = v * (v - 1) ** 2
        return (2 * iS - (v + 3) * iSd) / den, (2 * eS + (v + 3) * eSd) / den


class RhoClosed:
    """The closed-form density: rho_elem below w = 9, rho_elem - R(w)/w above,
    R(w) = int_9^w v F23(v) dv on Gauss-Legendre panels in y = ln v (F23 at
    dps_in inner digits at every node; the panel integrals of v F23 and, for
    the sum rule, of v F23 ln(W/v) from the same nodes).  Panels are built on
    demand up to the requested w; a w strictly inside a panel gets one more
    rule on the part panel [panel start, w]."""

    def __init__(self, dps_in=None, dps_out=None, wmax=None):
        self.dps_in = dps_in or CLOSED_DPS_IN
        self.dps = dps_out or CLOSED_DPS
        ends = [mp.mpf(e) for e in CLOSED_PANEL_ENDS]
        if wmax is not None:
            wmax = mp.mpf(wmax)
            ends = [e for e in ends if e < wmax] + [wmax]
        self.ends = ends
        self.panels = []              # per panel: dict(a, b, n, nodes [(y, v, f, wt*h*v^2)], R)
        self.Rcum = {0: mp.mpf(0)}    # index k -> R(ends[k])
        self.n_eval = 0
        self.err_in = mp.mpf(0)       # engine estimates of the inner one-folds, propagated into R
        self.wall = 0.0

    @staticmethod
    def n_nodes(ya, yb, dps_in):
        """Gauss-Legendre node count for the panel [ya, yb] in y = ln v: the
        Bernstein-ellipse rate to the nearest singularity of F23 in y (y = 0,
        i.e. v = 1) for dps_in + 4 digits, floor 12."""
        c, L = (ya + yb) / 2, (yb - ya) / 2
        r = c / L + mp.sqrt((c / L) ** 2 - 1)
        return max(12, int(mp.ceil((dps_in + 4) * mp.log(10) / (2 * mp.log(r)))) + 4)

    def _rule(self, a, b):
        """one Gauss-Legendre rule on [a, b] in y = ln v: returns (n, nodes, sum of v F23 dv)."""
        ya, yb = mp.log(a), mp.log(b)
        h, c = (yb - ya) / 2, (ya + yb) / 2
        n = self.n_nodes(ya, yb, self.dps_in)
        xs, ws = _gl(n, self.dps)
        nodes = []
        acc = mp.mpf(0)
        for x, wt in zip(xs, ws):
            y = c + h * x
            v = mp.exp(y)
            f, e = F23(v, self.dps_in)
            self.n_eval += 1
            gw = wt * h * v * v            # int v F23 dv = int v^2 F23 dy
            acc += gw * f
            self.err_in += abs(gw) * e
            nodes.append((y, v, f, gw))
        return n, nodes, acc

    def _build_panel(self, k):
        """panel k = [ends[k], ends[k+1]]: F23 at the nodes, the R increment."""
        t0 = time.time()
        with mp.workdps(self.dps):
            a, b = self.ends[k], self.ends[k + 1]
            n, nodes, pR = self._rule(a, b)
            self.panels.append({'a': a, 'b': b, 'n': n, 'nodes': nodes, 'R': pR})
            self.Rcum[k + 1] = self.Rcum[k] + pR
        self.wall += time.time() - t0

    def _extend(self, w):
        """build every panel whose end is <= w; returns the index j of the
        largest panel end ends[j] <= w (0 when w is below the first end)."""
        k = len(self.panels)
        while k + 1 < len(self.ends) and self.ends[k + 1] <= w:
            self._build_panel(k)
            k += 1
        j = k
        while j > 0 and self.ends[j] > w:
            j -= 1
        return j

    def R(self, w):
        """R(w) = int_9^w v F23(v) dv (0 at and below 9)."""
        w = mp.mpf(w)
        if w <= 9:
            return mp.mpf(0)
        if w > self.ends[-1]:
            raise ValueError(f"RhoClosed: w = {mp.nstr(w, 8)} lies beyond the last panel end "
                             f"{mp.nstr(self.ends[-1], 6)}")
        j = self._extend(w)
        acc = self.Rcum[j]
        if self.ends[j] < w:              # a part panel [ends[j], w]: one more rule
            t0 = time.time()
            with mp.workdps(self.dps):
                acc = acc + self._rule(self.ends[j], w)[2]
            self.wall += time.time() - t0
        return acc

    def __call__(self, w):
        w = mp.mpf(w)
        with mp.workdps(self.dps):
            if w <= 9:
                return rho_elem(w)
            return rho_elem(w) - self.R(w) / w

    # -- the sum rule (1/pi) int_1^W rho dw = 6 zeta_3 -------------------------
    def sum_rule(self, W):
        """The finite-cutoff Fubini form (exact):
            int_1^W rho dw = int_1^W rho_elem dw - int_9^W v F23(v) ln(W/v) dv,
        W a panel end (the constructor's wmax).  The elementary integral: tanh-
        sinh on [1, 3/2], then Gauss-Legendre panels in ln w.  Returns a dict
        of mpf: I_elem, J (the sunrise-cut part), S = (I_elem - J)/pi,
        six_zeta3, tail = the leading omitted tail (4 pi (ln W + 1) + 6 pi)/(pi W)
        of (1/pi) int_W^inf rho, from rho ~ (4 pi ln w + 6 pi)/w^2 at large w."""
        W = mp.mpf(W)
        j = self._extend(W)
        if self.ends[j] != W:
            raise ValueError("RhoClosed.sum_rule: W must be a panel end (construct with wmax=W)")
        t0 = time.time()
        with mp.workdps(self.dps):
            Y = mp.log(W)
            J = mp.mpf(0)
            for P in self.panels[:j]:
                for (y, v, f, gw) in P['nodes']:
                    J += gw * f * (Y - y)
            el_ends = [mp.mpf(e) for e in CLOSED_ELEM_ENDS]
            el_ends = [e for e in el_ends if e < W] + [W]
            I_el = mp.quad(rho_elem, [1, el_ends[0]])
            n_el = 0
            for a, b in zip(el_ends[:-1], el_ends[1:]):
                ya, yb = mp.log(a), mp.log(b)
                h, c = (yb - ya) / 2, (ya + yb) / 2
                n = self.n_nodes(ya, yb, self.dps_in)
                xs, ws = _gl(n, self.dps)
                for x, wt in zip(xs, ws):
                    wv = mp.exp(c + h * x)
                    I_el += wt * h * wv * rho_elem(wv)
                    n_el += 1
            S = (I_el - J) / mp.pi
            tail = (4 * mp.pi * (Y + 1) + 6 * mp.pi) / (mp.pi * W)
            res = {'W': W, 'I_elem': I_el, 'J': J, 'S': S, 'six_zeta3': 6 * mp.zeta(3),
                   'tail': tail, 'n_elem_nodes': n_el, 'n_elem_panels': len(el_ends) - 1,
                   'wall_elem': time.time() - t0}
        return res


def _closed_fail(msg):
    raise RuntimeError(f"[closed form] DENSITY GATE FAIL: {msg} -- the closed-form density does not "
                       "reproduce its references; STOP")


def closed_density_gates(series, series_label, bar12, bar_series, indent='           '):
    """The closed-form density evaluated NOW at the three density gate points
    w = 5, 12, 100 and gated: against the AMFlow solve_integrals references
    (RHO5_STR / RHO_W12_STR / RHO100_STR) at the served floors (GATE_FLOORS
    at the --dps target for w = 5 and 100; bar12, the rho self-check bar of
    the calling tier, for w = 12), and against the series density `series`
    ({'rho(5)': mpf, 'rho(12)': mpf, 'rho(100)': mpf}: the cached strings in
    the fast-start tier, the live transport's values in the live tiers) at
    bar_series.  Prints one value line (min(50, CLOSED_DPS_IN - 10) digits)
    and one gate line per point; RAISES (rc 1) naming every failed
    comparison.  Returns the RhoClosed object."""
    t0 = time.time()
    pad = ' ' * len(indent)
    print(f"{indent}[closed form] the density in CLOSED FORM (rho_elem = -(pi/w)[2 ln(w-1) ln w + 3 Li2(1-w)] "
          "below w = 9;")
    print(f"{pad}rho_elem - R(w)/w above, R the one-fold over the equal-mass sunrise cut) evaluated NOW at the")
    print(f"{pad}density gate points; the cross-check is the series density ({series_label}):")
    rc = RhoClosed(wmax=100)
    vals = {name: rc(wv) for name, wv in (('rho(5)', 5), ('rho(12)', 12), ('rho(100)', 100))}
    refs = {'rho(5)': (RHO5_STR, 'AMFlow solve_integrals w=5', float(GATE_FLOORS['rho(5)'](QUAD_DPS))),
            'rho(12)': (RHO_W12_STR, 'AMFlow solve_integrals w=12', float(bar12)),
            'rho(100)': (RHO100_STR, 'AMFlow solve_integrals bnd_w100', float(GATE_FLOORS['rho(100)'](QUAD_DPS)))}
    failed = []
    with mp.workdps(CLOSED_AMBIENT):
        for name in ('rho(5)', 'rho(12)', 'rho(100)'):
            val = vals[name]
            lit, what, floor = refs[name]
            d_ref = agree_digits(val, mp.mpf(lit))
            d_ser = agree_digits(val, mp.mpf(series[name])) if name in series else None
            ok_ref = bool(d_ref >= floor)
            ok_ser = True if d_ser is None else bool(d_ser >= bar_series)
            print(f"{pad}[closed form] {name:8s} = {mp.nstr(val, min(50, CLOSED_DPS_IN - 10))}")
            line = (f"{pad}             vs {what}: {mp.nstr(d_ref, 6)} d >= floor {floor:.2f} d -- "
                    f"{'OK' if ok_ref else 'FAIL'}")
            if d_ser is not None:
                line += (f"; vs the series density: {mp.nstr(d_ser, 6)} d >= bar {float(bar_series):.0f} d -- "
                         f"{'OK' if ok_ser else 'FAIL'}")
            print(line)
            if not ok_ref:
                failed.append(f"{name} vs {what} {mp.nstr(d_ref, 6)} d < floor {floor:.2f} d")
            if not ok_ser:
                failed.append(f"{name} vs the series density {mp.nstr(d_ser, 6)} d < bar {float(bar_series):.0f} d")
        err = mp.nstr(rc.err_in, 3)
    n_ser = sum(1 for k in vals if k in series)
    print(f"{pad}[closed form] density gate: {3 - sum(1 for f in failed if 'AMFlow' in f)}/3 points within the "
          f"AMFlow floors, {n_ser - sum(1 for f in failed if 'series' in f)}/{n_ser} within the series bar "
          f"(dps={QUAD_DPS}) -- RAISES on fail")
    print(f"{pad}             ({rc.n_eval} F23 evaluations on {len(rc.panels)} panels over [9, 100], inner one-folds at "
          f"{rc.dps_in} digits, sums at {rc.dps}; the engine's estimate for the one-folds, propagated into R: {err}, "
          f"informational; {time.time()-t0:.1f}s)")
    if failed:
        _closed_fail('; '.join(failed))
    return rc


def _sum_rule_tier():
    """--sum-rule [LOG10_W]: the spot gate (1/pi) int_1^inf rho(w) dw = 6 zeta_3
    on the closed-form density, at the finite cutoff W = 10^LOG10_W in the
    Fubini form of RhoClosed.sum_rule (the elementary and the sunrise-cut parts
    integrated separately, so their large-w cancellation never happens
    numerically).  GATE: the no-tail residual against the cutoff's own
    truncation CAPPED at the inner working precision (bar min(floor(-log10(
    tail / 6 zeta_3)) - 2, CLOSED_DPS_IN - 12), tail = the leading omitted
    tail (4 pi (ln W + 1) + 6 pi)/(pi W); a residual is never resolved below
    the inner one-folds' working precision, so the truncation bar alone -- 66
    at W = 1e70, 95 at W = 1e100 against 66 inner digits at the default dps --
    would fail correct bytes), the tail-restored residual against the inner
    working precision (bar CLOSED_DPS_IN - 12), and the density gate points
    w = 5, 12, 100 from the same grid against the AMFlow references at the
    served floors.  ACCEPTED CUTOFFS: LOG10_W in SUMRULE_LOG10_W_RANGE and
    such that the NEXT omitted tail clears the tail-restored bar: that tail is
    below (4 ln W + 8)/W^2 (rho's next large-w term measured below
    2 (4 pi ln w + 6 pi)/w^3: rho w^2/(4 pi ln w + 6 pi) - 1 = 1.73/w, 1.87/w,
    1.94/w at w = 1e4, 1e9, 1e22), and the tier requires floor(-log10((4 ln W
    + 8)/(W^2 6 zeta_3))) - 2 >= CLOSED_DPS_IN - 12 -- the whole static range
    at the default dps; a cutoff too low for a raised --dps is refused by name
    (rc 2) with the smallest LOG10_W that passes.  rc 0 PASS / 1 FAIL / 2
    usage or refused cutoff."""
    tag = SCRIPT.split('-')[0].upper()
    others = [n for n in ('point', 'fastcache_bank', 'boundary_recompute', 'checkpoint', 'resume')
              if getattr(_ARGS, n, None) not in (None, False)]
    if others:
        print(f"{SCRIPT}: --sum-rule is a tier of its own; it does not combine with "
              f"{', '.join('--' + n.replace('_', '-') for n in others)}", file=sys.stderr)
        raise SystemExit(2)
    if _ARGS.density != 'closed':
        print(f"{SCRIPT}: --sum-rule integrates the closed-form density; --density series turns it off",
              file=sys.stderr)
        raise SystemExit(2)
    lw = int(_ARGS.sum_rule)
    lo, hi = SUMRULE_LOG10_W_RANGE
    if not lo <= lw <= hi:
        print(f"{SCRIPT}: --sum-rule LOG10_W must lie in [{lo}, {hi}] (got {lw}), the tier's static range ({hi}: the "
              f"last panel end; below {lo} the cutoff's own truncation (4 ln W + 10)/W of the sum leaves the no-tail "
              "check under 32 digits); within the range a cutoff whose next omitted tail does not clear the "
              "tail-restored bar at the running --dps is refused by name", file=sys.stderr)
        raise SystemExit(2)
    W = mp.mpf(10) ** lw
    # the bars under the running precision: bar1 = the inner one-folds' working precision (the tail-restored bar and
    # the cap of the no-tail bar); bar2 = the agreement the NEXT omitted tail lets the tail-restored residual reach at
    # this cutoff, from the bound (4 ln W + 8)/W^2 on (1/pi) int_W^inf of rho's next large-w term (measured below
    # 2 (4 pi ln w + 6 pi)/w^3: rho w^2/(4 pi ln w + 6 pi) - 1 = 1.73/w, 1.87/w, 1.94/w at w = 1e4, 1e9, 1e22); a cutoff
    # with bar2 < bar1 cannot pass on correct bytes and is refused by name, with the smallest cutoff that can
    bar1 = CLOSED_DPS_IN - 12
    with mp.workdps(30):
        z30 = 6 * mp.zeta(3)

        def next_tail(L):
            return (4 * L * mp.log(10) + 8) / mp.mpf(10) ** (2 * L)

        def next_bar(L):
            return int(mp.floor(-mp.log10(next_tail(L) / z30))) - 2
        tail2, bar2 = next_tail(lw), next_bar(lw)
        if bar2 < bar1:
            lmin = next((L for L in range(lw + 1, hi + 1) if next_bar(L) >= bar1), None)
            print(f"{SCRIPT}: --sum-rule {lw} refused at --dps {QUAD_DPS}: the tail-restored residual is gated at "
                  f"{bar1} d (CLOSED_DPS_IN - 12, the inner one-folds' working precision) and the next omitted tail at "
                  f"W = 1e{lw}, below (4 ln W + 8)/W^2 = {mp.nstr(tail2, 3)}, lets it reach {bar2} d at most; "
                  + (f"raise LOG10_W to {lmin} or more, or lower --dps" if lmin is not None else
                     f"no cutoff up to LOG10_W = {hi} passes at this --dps; lower --dps"), file=sys.stderr)
            raise SystemExit(2)
    print(f"{tag} SUM-RULE tier -- the closed-form density's large-l^2 normalisation")
    print("  (1/pi) int_1^inf rho(w) dw = 6 zeta_3, checked at the finite cutoff W = 1e%d in the Fubini form" % lw)
    print("  int_1^W rho dw = int_1^W rho_elem dw - int_9^W v F23(v) ln(W/v) dv   (exact; the elementary and the")
    print("  sunrise-cut parts integrated separately, so their large-w cancellation never happens numerically)")
    print(f"  settings: QUAD_DPS={QUAD_DPS} DPS={DPS}; inner one-folds at CLOSED_DPS_IN={CLOSED_DPS_IN} digits, "
          f"sums at CLOSED_DPS={CLOSED_DPS};")
    print(f"  bars: the tail-restored residual at CLOSED_DPS_IN - 12 = {bar1} d, the no-tail residual at the cutoff's own "
          f"truncation capped there; the next omitted tail at this cutoff, below (4 ln W + 8)/W^2 = {mp.nstr(tail2, 3)}, "
          f"allows {bar2} d;")
    print("  Gauss-Legendre panels in ln v / ln w, node counts from the Bernstein ellipse to ln = 0\n")
    print(f"[s1] [{time.time()-T0:6.1f}s] building the Gauss-Legendre panels of the sunrise-cut part on [9, 1e{lw}] "
          "and the elementary integral ...")
    rc = RhoClosed(wmax=W)
    res = rc.sum_rule(W)
    k = len(rc.panels)
    print(f"           the sunrise-cut part: {k} panels ({', '.join(str(P['n']) for P in rc.panels)} nodes), "
          f"{rc.n_eval} F23 evaluations in {rc.wall:.1f}s;")
    print(f"           the elementary part: tanh-sinh on [1, 3/2] + {res['n_elem_panels']} panels "
          f"({res['n_elem_nodes']} nodes) in {res['wall_elem']:.1f}s")
    with mp.workdps(CLOSED_AMBIENT):
        S, z, tail = res['S'], res['six_zeta3'], res['tail']
        r0 = S - z                    # the residuals formed at the compare precision, printed below
        r1 = (S + tail) - z
        d0 = agree_digits(S, z)
        d1 = agree_digits(S + tail, z)
        bar_trunc = int(mp.floor(-mp.log10(tail / z))) - 2      # the cutoff's own truncation
        bar0 = min(bar_trunc, bar1)                             # capped at the inner working precision
        ok0, ok1 = bool(d0 >= bar0), bool(d1 >= bar1)
        nd = CLOSED_DPS_IN                                      # the printed digits follow the inner precision
        print(f"[s2] [{time.time()-T0:6.1f}s] (1/pi) int_1^W rho dw = {mp.nstr(S, nd)}")
        print(f"           6 zeta_3              = {mp.nstr(z, nd)}")
        print(f"           residual (no tail)    = {mp.nstr(r0, 4)}   [the omitted tail (1/pi) int_W^inf rho: "
              f"leading term (4 pi (ln W + 1) + 6 pi)/(pi W) = {mp.nstr(tail, 4)}")
        print("                                               from rho ~ (4 pi ln w + 6 pi)/w^2 (1 + c/w + ...), "
              f"c < 2 measured; the next term is below (4 ln W + 8)/W^2 = {mp.nstr(tail2, 3)}]")
        print(f"           residual, tail added  = {mp.nstr(r1, 4)}")
        print(f"           [gate] no-tail agreement {mp.nstr(d0, 6)} d >= bar {bar0} d "
              f"(= min(floor(-log10(tail / 6 zeta_3)) - 2 = {bar_trunc}, CLOSED_DPS_IN - 12 = {bar1}): the cutoff's "
              f"own truncation, capped at the inner one-folds' working precision) -- {'OK' if ok0 else 'FAIL'}")
        print(f"           [gate] tail-restored agreement {mp.nstr(d1, 6)} d >= bar {bar1} d "
              f"(= CLOSED_DPS_IN - 12: the inner one-folds' working precision; the next omitted tail allows {bar2} d "
              f"here) -- {'OK' if ok1 else 'FAIL'}")
        print(f"[s3] [{time.time()-T0:6.1f}s] the density gate points from the same grid (12 and 100 are panel ends; "
              "5 is rho_elem alone):")
        oks = []
        for name, wv, lit, what, floor in (
                ('rho(5)', 5, RHO5_STR, 'AMFlow solve_integrals w=5', float(GATE_FLOORS['rho(5)'](QUAD_DPS))),
                ('rho(12)', 12, RHO_W12_STR, 'AMFlow solve_integrals w=12', float(QUAD_DPS - 10)),
                ('rho(100)', 100, RHO100_STR, 'AMFlow solve_integrals bnd_w100', float(GATE_FLOORS['rho(100)'](QUAD_DPS)))):
            val = rc(wv)
            d = agree_digits(val, mp.mpf(lit))
            ok = bool(d >= floor)
            oks.append(ok)
            print(f"           {name:8s} = {mp.nstr(val, min(50, CLOSED_DPS_IN - 10))}   vs {what}: {mp.nstr(d, 6)} d "
                  f">= floor {floor:.2f} d -- {'OK' if ok else 'FAIL'}")
        ok_all = ok0 and ok1 and all(oks)
        lim = ("the cutoff's truncation" if bar_trunc <= bar1 else
               "the inner working precision, the cutoff's truncation below it")
        print(f"\ntotal wall time: {time.time()-T0:.1f}s")
        print(f"PASS (sum rule) -- (1/pi) int rho dw of the closed-form density reproduces 6 zeta_3 to "
              f"{int(mp.floor(d0))} digits at the cutoff W = 1e{lw} ({lim}) and to {int(mp.floor(d1))} "
              "digits with the leading tail restored; the density gate points within their floors"
              if ok_all else "FAIL (sum rule) -- see the [gate] / floor lines above")
    raise SystemExit(0 if ok_all else 1)


# ====== D. closed-form checks of the non-elliptic kite masters ===============
# AMFlow normalization: each loop carries measure d^dk/(i pi^{d/2}) e^{eps g},
# g = EulerGamma.  With m^2 = 1:
#   TAD      = -e^{eps g} Gamma(eps-1)                    (massive tadpole)
#   FMIX(w)  = e^{eps g} Gamma(eps) \int_0^1 dx x^{-eps} (1-(1-x)w-i0)^{-eps}
#              (one-loop bubble, one massive + one massless line, external w;
#               the integral is the exact all-orders Feynman-parameter form,
#               = 2F1(eps,1;2-eps;w)/(1-eps); branch (neg-i0)^{-eps} explicit)
# so   J[1,1,0,0,0] = TAD^2          (w-independent)
#      J[1,1,0,1,0] = TAD * FMIX(w)
#      J[1,1,0,1,1] = FMIX(w)^2      (two one-loop bubbles sharing only l)
# These Gamma/2F1 closed forms are checked LIVE against the transported
# Laurent blocks at the w=12 checkpoint by small-eps evaluation; agreement is
# limited by the O(eps) truncation of the transported Laurent block (~18 d at
# eps=1e-18) and by the transport precision itself.
def _fmix(e, w):
    xstar = 1 - 1 / mp.mpf(w)

    def f_below(x):     # 1-(1-x)w < 0: (A e^{-i pi})^{-eps} = A^{-eps} e^{i pi eps}
        A = (1 - x) * w - 1
        return x ** (-e) * A ** (-e) * mp.exp(1j * mp.pi * e)

    def f_above(x):
        return x ** (-e) * (1 - (1 - x) * w) ** (-e)

    val = mp.quad(f_below, [0, xstar]) + mp.quad(f_above, [xstar, 1])
    return mp.exp(e * mp.euler) * mp.gamma(e) * val


def closed_masters_check(state, w, masters, eps_list=('1e-18', '1e-20')):
    old = mp.mp.dps
    mp.mp.dps = 70
    rows = []
    for name, idx in (("J[1,1,0,0,0] = TAD^2", (1, 1, 0, 0, 0)),
                      ("J[1,1,0,1,0] = TAD*FMIX", (1, 1, 0, 1, 0)),
                      ("J[1,1,0,1,1] = FMIX^2", (1, 1, 0, 1, 1))):
        loc = masters.index(idx)
        worst = mp.inf
        for es in eps_list:
            e = mp.mpf(es)
            tad = -mp.exp(e * mp.euler) * mp.gamma(e - 1)
            fmix = _fmix(e, w)
            closed = {"J[1,1,0,0,0] = TAD^2": tad * tad,
                      "J[1,1,0,1,0] = TAD*FMIX": tad * fmix,
                      "J[1,1,0,1,1] = FMIX^2": fmix * fmix}[name]
            laurent = state[-2][loc] / e ** 2 + state[-1][loc] / e + state[0][loc]
            worst = min(worst, agree_digits(laurent, closed))
        rows.append((name, worst))
    mp.mp.dps = old
    return rows


# ---------------- axis3-wave certified value-level error budget --------------
def _l1_bounds(rho, K, Wcut=200):
    """Bound-grade l1 norms for the error budget (2-digit accuracy is enough;
    they only multiply certified error terms): returns
      l1K  = (1/pi) int_1^W_MAX |K| dw   (tail via the measured c1'/w envelope,
                                          c1' = 1.2*|K(Wcut-1)|*(Wcut-1))
      Irho = (1/pi) int_1^W_MAX rho dw   (mapped tail; rho=0 beyond W_MAX)
      c1   = |K(Wcut-1)|*(Wcut-1)        (live tail coefficient)"""
    with mp.workdps(30):
        c1 = abs(K(mp.mpf(Wcut - 1))) * (Wcut - 1)
        qK = mp.quad(lambda w: abs(K(w)), [1, 9, Wcut],
                     method='tanh-sinh', maxdegree=4)
        l1K = (qK + mp.mpf('1.2') * c1 * mp.log(mp.mpf(W_MAX) / Wcut)) / mp.pi
        qr = mp.quad(lambda w: abs(rho(w)), [1, 9, Wcut],
                     method='tanh-sinh', maxdegree=4)
        scale = mp.mpf(Wcut)

        def ft(t):
            wp = Wcut + scale * (1 + t) / (1 - t)
            r = rho(wp)
            if r == 0:
                return mp.mpf(0)
            return abs(r) * scale * 2 / (1 - t) ** 2
        qr += mp.quad(ft, [-1, 1], method='tanh-sinh', maxdegree=4)
        Irho = qr / mp.pi
        return +l1K, +Irho, +c1


def _guard_drops(Kf, c1):
    """Live-value versions of the documented U/V/W guard-drop bounds (the
    header prints keep their frozen gate-point constants; these enter the
    ENFORCED total)."""
    with mp.workdps(30):
        dU = 10 * U_MIN ** 2 * abs(Kf(mp.mpf(1) + U_MIN)) / mp.pi
        dV = V_MIN ** 2 * mp.fabs(mp.log(V_MIN)) * abs(Kf(mp.mpf(9) + V_MIN)) / mp.pi
        dW = 2 * c1 * mp.log(W_MAX) / W_MAX ** 2
        return +(dU + dV + dW)


def _addback_probe_bound(K, A1, delta=mp.mpf('0.4')):
    """Certified add-back remainder for the box kernel: the addback uses the
    Taylor polynomial P_N (N = kernel_nmax) of K about w=1; the remainder is
    |int_0^delta S (K - P_N)| <= max_probe |K_direct - P_N| * int_0^delta |S|,
    with the max measured LIVE against the closed form (same probe pattern as
    BoxKernel.verify) and int |S| = |A1| (d^2/4 - d^2 log(d)/2) exact."""
    nmax = kernel_nmax_for(QUAD_DPS)             # kernel_nmax used in the quad
    Kc = K.tay1[:nmax + 1]
    worst = mp.mpf(0)
    # probe offsets deliberately NON-round: the closed dilog form has SPURIOUS
    # partial-fraction poles at algebraic (w,v) coincidences (e.g. w=21/20 puts
    # mal(v=2)=u exactly, and v=2 is a GL node for odd n) -- the named-form
    # spurious-pole minefield; K itself is analytic there.
    for us in ('0.0503', '0.1507', '0.2511', '0.3517', '0.3989'):
        u = mp.mpf(us)
        acc = mp.mpf(0)
        for cn in reversed(Kc):
            acc = acc * u + cn
        worst = max(worst, abs(K._direct(1 + u) - acc))
    intS = abs(A1) * (delta ** 2 / 4 - delta ** 2 * mp.log(delta) / 2)
    return +(worst * intS / mp.pi), +worst


def _addback_swap_bound(A1, nmax, delta=mp.mpf('0.4')):
    """Exact-geometric add-back tail for the swap kernel 1/(w+1): Taylor
    coefficients about w=1 are exactly (-1)^n/2^(n+1), so
    |term_n| <= |A1| (|log d|+1) d^{n+2} / 2^{n+2}; sum the geometric tail
    from n = nmax+1 in closed form (ratio d/2 = 0.2, certified)."""
    with mp.workdps(30):
        r = delta / 2
        t0 = abs(A1) * (mp.fabs(mp.log(delta)) + 1) * delta ** 2 / 2 \
            * r ** (nmax + 1)
        return +(t0 / (1 - r) / mp.pi)


# ==================================== main ===================================
def main():
    if _ARGS.sum_rule is not None:
        _sum_rule_tier()            # the 6 zeta_3 spot gate on the closed form (2026-09-11); raises SystemExit
    _fc, _fc_note = _fc_eligible()
    if _fc_note:
        print(f"[fast-cache] {_fc_note}")
    if _fc is not None:
        _fc_fast_path(_fc)          # raises SystemExit(0) on success
    mp.mp.dps = AMBIENT_DPS
    GT_AMF = mp.mpf(GT_AMF_STR)
    GT_PARENT = mp.mpf(GT_PARENT_STR)
    RHO_W12 = mp.mpf(RHO_W12_STR)
    KITE_M1 = mp.mpf(KITE_M1_STR)
    A1 = -2 * mp.pi

    print("LBL3SE compliant final form -- one-fold dispersion in the internal mass,")
    print("closed dilog-box kernel x runtime Picard-Fuchs series for rho.  No node cache.")
    print(f"settings: QUAD_DPS={QUAD_DPS} LEVEL={LEVEL} DPS={DPS} NORD={NORD}")
    print(f"guards (derived from QUAD_DPS, all bounds << gate target):")
    print(f"  U_MIN={mp.nstr(U_MIN,3)}  (dropped < {mp.nstr(10*U_MIN**2*mp.mpf('0.18')/mp.pi,3)})")
    print(f"  V_MIN={mp.nstr(V_MIN,3)}  (dropped < {mp.nstr(V_MIN**2*mp.fabs(mp.log(V_MIN))*mp.mpf('0.02')/mp.pi,3)})")
    print(f"  W_MAX={mp.nstr(W_MAX,3)}  (dropped < {mp.nstr(2*mp.mpf('0.57')*mp.log(W_MAX)/W_MAX**2,3)})\n")

    # --- [0] the exact rational connection + the single boundary seed --------
    print(f"[0] [{time.time()-T0:6.1f}s] loading exact rational kite IBP connection ...")
    funcs, masters = load_kite_de()
    M0, d_seed, seed_dps = load_kite_boundary(masters)
    print(f"           8 masters, eps-graded to eps^2; seed = w=5 Laurent vector "
          f"(DERIVED, AMFlow-free:")
    print(f"           lbl3se-w5-derived.json, emitted at dps {seed_dps} by "
          f"lbl3se-w5-seed.py -- vacuum")
    print(f"           closed forms + Frobenius at w=0 + exact-DE march; "
          f"rerunnable here)")
    print(f"           seed vs held-out retired AMFlow w=5 vector "
          f"(goal_digits=140): >= {mp.nstr(d_seed, 5)} d agreement")
    bar_seed = min(seed_dps, 128) - DSEED_MARGIN
    print(f"           [cert] seed held-out gate: {mp.nstr(d_seed, 5)} d >= "
          f"bar {bar_seed} d (min(seed_dps,128)-{DSEED_MARGIN}) -- RAISES on fail")
    if not d_seed >= bar_seed:
        raise RuntimeError(f"[cert] derived w=5 seed vs held-out AMFlow vector: "
                           f"{mp.nstr(d_seed, 6)} d < bar {bar_seed} d "
                           f"(seed_dps={seed_dps}) -- seed not certified, STOP")

    # --- [1] rho(w) as a PF-series sweep over (1, inf) -----------------------
    print(f"[1] [{time.time()-T0:6.1f}s] building rho(w) by one adaptive local-series sweep ...")
    rho = RhoPF(funcs, M0)

    # held-out check: rho(12) vs the independent AMFlow w=12 run
    mp.mp.dps = DPS
    r12 = rho(mp.mpf(12))
    d12 = agree_digits(r12, RHO_W12)
    r12_cap = len(RHO_W12_STR.replace('.', '').lstrip('0'))
    # rho(12) is the dps-scaling SELF-CHECK exhibit: its PASS bar tracks --dps
    # (clipped by the held-out literal's own digit capacity).  The GT_AMF /
    # GT_PARENT oracle bars below stay fixed at 30 (those literals are ~40d
    # artifacts and saturate there regardless of --dps).
    bar_rho = min(QUAD_DPS - 10, r12_cap - 10)
    print(f"           rho(12) live      = {mp.nstr(r12, min(50, DPS-4))}")
    print(f"           held-out oracle   = {mp.nstr(RHO_W12, 50)}")
    print(f"           MEASURED agreement = {mp.nstr(d12, 6)} d "
          f"[self-check bar >= {bar_rho} d, scales with --dps]")
    print(f"           (limited by DPS={DPS}; oracle string carries {r12_cap} digits;")
    print(f"            archived dps=130 record: 99.95 d)\n")
    with mp.workdps(20):
        print(f"           [cert] rho truncation budget (TOP-series certified "
              f"tails, l1): <= {mp.nstr(rho.err_top, 3)} "
              f"[enforced < 1e-{bar_rho + 2}]")
    if not rho.err_top < mp.mpf(10) ** -(bar_rho + 2):
        raise RuntimeError(f"[cert] rho TOP-series truncation budget "
                           f"{mp.nstr(rho.err_top, 4)} does not certify the "
                           f"rho(12) bar {bar_rho}+2 d -- STOP")
    # the row script's other two density spot gates on the SAME live density:
    # w=5 (the seed point) and w=100 (the tail); RAISE below the row script's
    # floors GATE_FLOORS at the --dps target
    spot = rho_spot_gates(rho, QUAD_DPS)
    # the CLOSED-FORM density at the same three points (2026-09-11, section
    # C2): gated against the AMFlow references at the served floors and
    # against the live series density above at the rho self-check bar
    if _ARGS.density == 'closed':
        closed_density_gates({'rho(5)': spot['rho(5)'][0], 'rho(12)': r12, 'rho(100)': spot['rho(100)'][0]},
                             f"the live transport above, DPS={DPS}", bar12=bar_rho, bar_series=bar_rho)

    # --- [2] closed-form Gamma/2F1 checks of the non-elliptic masters --------
    print(f"[2] [{time.time()-T0:6.1f}s] IBP-onto-kite-masters exhibit: transported masters vs")
    print("           Gamma/2F1 closed forms at the w=12 checkpoint (small-eps Laurent probe):")
    if mp.mpf(12) in rho.checkpoints:
        cm_worst = mp.inf
        for name, d in closed_masters_check(rho.checkpoints[mp.mpf(12)], 12, masters):
            print(f"             {name:26s}  {mp.nstr(d, 5)} d")
            cm_worst = min(cm_worst, d)
        print("           (the remaining masters are the Gamma_1(6) sunrise block --")
        print("            the elliptic content -- and the m00 sunset + top one-fold)\n")
        print(f"           [cert] closed-masters two-path gate: worst "
              f"{mp.nstr(cm_worst, 5)} d >= bar {CM_BAR} d (eps-probe capped "
              f"~17.9 d) -- RAISES on fail")
        if not cm_worst >= CM_BAR:
            raise RuntimeError(f"[cert] transported masters vs Gamma/2F1 closed "
                               f"forms: worst {mp.nstr(cm_worst, 5)} d < bar "
                               f"{CM_BAR} d -- transport not certified, STOP")
    else:
        raise RuntimeError("[cert] w=12 checkpoint missed -- closed-masters "
                           "two-path gate cannot run, STOP")

    # --- [3] the gate (default) or the requested --point, eps^0 --------------
    mp.mp.dps = AMBIENT_DPS
    point_mode = _ARGS.point is not None
    if point_mode:
        S, T = mp.mpf(_ARGS.point[0]), mp.mpf(_ARGS.point[1])
    else:
        S, T = mp.mpf(-1), mp.mpf(-1) / 3
    M2 = mp.mpf(1)
    if not (S < 0 and T < 0 and -S - T < 4 * M2):
        raise SystemExit("DOMAIN: need s<0, t<0, u=-s-t<4*m2 "
                         "(deep Euclidean, units m2=1)")
    print(f"[3] [{time.time()-T0:6.1f}s] kernel: closed dilog box at "
          f"(s,t)=({mp.nstr(S, 8)},{mp.nstr(T, 8)}), "
          "runtime Chebyshev evaluation device:")
    K = BoxKernel(S, T, M2, QUAD_DPS)
    panels = lbl3se_panels(A1)
    print(f"[3] [{time.time()-T0:6.1f}s] I = (1/pi) int rho K dw -- subtracted tanh-sinh ladder:")
    prev = None
    vals = {}
    engs = {}
    for lev in range(3, LEVEL + 1):
        t0 = time.time()
        vals[lev], engs[lev] = disp_subtracted(rho, K, panels, dps=QUAD_DPS,
                                               maxdegree=lev, Kc_pre=K.tay1)
        mp.mp.dps = AMBIENT_DPS
        step = mp.nstr(vals[lev] - prev, 4) if prev is not None else '-'
        print(f"           L{lev}: I = {mp.nstr(vals[lev], 44)}   step={step}"
              f"  ({time.time()-t0:.1f}s)")
        prev = vals[lev]
    # [cert] refine-until-bound: LEVEL is a starting seed.  The accepted value
    # must beat the two-successive-depth squaring-model estimate d1^2/d2 (the
    # standard tanh-sinh extrapolation; mpmath's own estimator is the same
    # d1^2/d2 in log space) at tol 10^-(QUAD_DPS+QUAD_GUARD), else the ladder
    # keeps refining to LEVEL+LEVEL_EXTRA and RAISES at the cap.
    tol_q = mp.mpf(10) ** -(QUAD_DPS + QUAD_GUARD)
    lev = LEVEL

    def _ladder_est(lv):
        if lv - 1 not in vals:
            return mp.inf
        d1 = abs(vals[lv] - vals[lv - 1])
        if lv - 2 not in vals or abs(vals[lv] - vals[lv - 2]) == 0:
            return d1
        d2 = abs(vals[lv] - vals[lv - 2])
        return max(d1 * d1 / d2, mp.mpf(10) ** -(QUAD_DPS + 22))  # work-dps floor
    def _refine_finite(lv, est):
        # 2026-09-06 (Q20e): fail CLOSED on a non-finite level value or estimate,
        # BEFORE the continue-test below -- `est_q >= tol_q` is False for a NaN
        # by IEEE ordering, so a NaN level would leave the loop as 'converged'
        # and I_gate = nan then enters the TOTAL bound (the --dps 80 capture of
        # 2026-09-06).  Every level computed so far is checked, by name; est_q's
        # own +inf sentinel (no second level yet) is the served refine trigger
        # and is not a NaN, so the estimate is checked for NaN.
        for k in sorted(vals):
            if not mp.isfinite(vals[k]):
                raise RuntimeError(f"[refine] L{k}: I (the subtracted tanh-sinh "
                                   "level value) is not finite (nan/inf) -- fail "
                                   "closed")
        if mp.isnan(est):
            raise RuntimeError(f"[refine] L{lv}: est_q (the two-depth estimate "
                               "d1^2/d2) is not finite (nan/inf) -- fail closed")
    est_q = _ladder_est(lev)
    _refine_finite(lev, est_q)
    while est_q >= tol_q:
        if lev >= LEVEL + LEVEL_EXTRA:
            raise RuntimeError(
                f"[cert] dispersion ladder: two-depth estimate "
                f"{mp.nstr(est_q, 4)} >= tol {mp.nstr(tol_q, 4)} at level "
                f"{lev} (cap {LEVEL + LEVEL_EXTRA}) -- refine-until-bound "
                "FAILED, STOP")
        lev += 1
        t0 = time.time()
        vals[lev], engs[lev] = disp_subtracted(rho, K, panels, dps=QUAD_DPS,
                                               maxdegree=lev, Kc_pre=K.tay1)
        mp.mp.dps = AMBIENT_DPS
        print(f"           L{lev}: I = {mp.nstr(vals[lev], 44)}   "
              f"step={mp.nstr(vals[lev] - prev, 4)}  ({time.time()-t0:.1f}s)  "
              f"[cert] ladder refined past seed LEVEL={LEVEL}")
        prev = vals[lev]
        est_q = _ladder_est(lev)
        _refine_finite(lev, est_q)
    I_gate = vals[lev]
    with mp.workdps(20):
        print(f"           [cert] quadrature: two-depth estimate d1^2/d2 = "
              f"{mp.nstr(est_q, 3)} < tol {mp.nstr(tol_q, 3)} "
              f"(QUAD_GUARD={QUAD_GUARD}, level {lev}); mpmath engine "
              f"estimate {mp.nstr(engs[lev], 3)}")
    # [cert] TOTAL certified error bound at the value level (enforced):
    #   quadrature est + add-back remainder (live probe vs closed form)
    #   + kernel accuracy (interpolant probe, relative) + GL two-depth probe
    #   + transport budget * (1/pi)int|K|  + U/V/W guard drops (live values)
    ab_bound, ab_worst = _addback_probe_bound(K, A1)
    l1K, Irho, c1 = _l1_bounds(rho, K)
    kern_acc = mp.mpf(10) ** -K.worst_interp_d * 2 * abs(I_gate) \
        + K.gl_worst * Irho
    tr_bound = rho.err_top * l1K
    drops = _guard_drops(K, c1)
    total = est_q + ab_bound + kern_acc + tr_bound + drops
    bar_total = min(GATE_BAR, QUAD_DPS) + TOTAL_GUARD
    with mp.workdps(20):
        print(f"           [cert] TOTAL value bound: quad {mp.nstr(est_q, 3)} "
              f"+ addback {mp.nstr(ab_bound, 3)} + kernel {mp.nstr(kern_acc, 3)} "
              f"+ transport {mp.nstr(tr_bound, 3)} (l1K={mp.nstr(l1K, 3)}) "
              f"+ guards {mp.nstr(drops, 3)}")
        print(f"           [cert] TOTAL = {mp.nstr(total, 3)} -> certifies "
              f"{mp.nstr(-mp.log10(total), 4)} digits [enforced < 1e-{bar_total}"
              f" = value-claim bar {min(GATE_BAR, QUAD_DPS)}+{TOTAL_GUARD}; "
              f"kernel-Taylor depth corrected 2026-07-06, the value now "
              f"tracks QUAD_DPS -- see kernel_nmax_for]")
    if not total < mp.mpf(10) ** -bar_total:
        raise RuntimeError(f"[cert] TOTAL certified error bound "
                           f"{mp.nstr(total, 4)} does not certify the "
                           f"value-claim bar {bar_total} d -- STOP")
    if point_mode:
        print(f"           I({mp.nstr(S, 8)},{mp.nstr(T, 8)},1) = "
              f"{mp.nstr(I_gate, min(50, QUAD_DPS + 2))}")
        if _POINT_TAG is not None:
            # the tagged tier: gated vs the shipped record (bar from the record)
            ok = point_tag_gate(_POINT_TAG, _POINT_REC, {'I_SE': I_gate},
                                d12 >= bar_rho)
            print(f"total wall time: {time.time()-T0:.1f}s")
            print(f"PASS -- tagged point {_POINT_TAG}: I_SE within its tier bar of the "
                  f"shipped record's direct AMFlow solve; rho(12) gate met (>= {bar_rho} d)"
                  if ok else f"FAIL -- tagged point {_POINT_TAG}: see above")
            raise SystemExit(0 if ok else 1)
        print("           (level-step self-consistency above is NOT an oracle "
              "gate; no independent")
        print("            oracle exists at this point -- rho itself is gated "
              "held-out at w=12)\n")
        ok = (d12 >= bar_rho)
        print(f"total wall time: {time.time()-T0:.1f}s")
        print(f"PASS -- rho held-out gate met at requested precision "
              f"(>= {bar_rho} d, scales with --dps)" if ok
              else "FAIL -- see above")
        raise SystemExit(0 if ok else 1)
    dA = agree_digits(I_gate, GT_AMF)
    dP = agree_digits(I_gate, GT_PARENT)
    gtA_cap = len(GT_AMF_STR.replace('.', '').lstrip('0'))
    print(f"           oracle GT_AMF    = {mp.nstr(GT_AMF, 43)}  (AMFlow eps-grid, 40d)")
    print(f"           oracle GT_PARENT = {mp.nstr(GT_PARENT, 43)}  (indep. 9-prop family)")
    print(f"           MEASURED agreement: vs GT_AMF {mp.nstr(dA, 6)} d, "
          f"vs GT_PARENT {mp.nstr(dP, 6)} d")
    print(f"           (oracle-string caps: GT_AMF literal carries {gtA_cap} digits, itself a")
    print(f"            ~40d artifact; GT_PARENT achieved 39.9d -- gate agreement saturates")
    print(f"            near 40d for any --dps > 40; dps growth shows on rho(12) above,")
    print(f"            whose held-out literal carries {len(RHO_W12_STR.replace('.', '').lstrip('0'))} digits)\n")

    # --- [4] kernel-swap self-test: same rho, kernel 1/(w+1) -----------------
    print(f"[4] [{time.time()-T0:6.1f}s] kernel-swap self-test: "
          "(1/pi) int rho/(w+1) dw vs -Sigma_kite(-1):")
    # Taylor of 1/(w+1) about w=1 is exactly (-1)^n / 2^(n+1) -- closed form
    mp.mp.dps = QUAD_DPS + 20
    Kc_swap = [mp.mpf(-1) ** n / mp.mpf(2) ** (n + 1)
               for n in range(max(150, kernel_nmax_for(QUAD_DPS) + 10))]
    v5, e5 = disp_subtracted(rho, lambda wp: 1 / (wp + 1), panels,
                             dps=QUAD_DPS, maxdegree=LEVEL, Kc_pre=Kc_swap)
    v6, e6 = disp_subtracted(rho, lambda wp: 1 / (wp + 1), panels,
                             dps=QUAD_DPS, maxdegree=LEVEL + 1, Kc_pre=Kc_swap)
    mp.mp.dps = AMBIENT_DPS
    rich = 2 * v6 - v5
    print(f"           2L{LEVEL+1}-L{LEVEL} = {mp.nstr(rich, 44)}")
    print(f"           oracle    = {mp.nstr(KITE_M1, 44)}  (AMFlow solve_integrals >=60d)")
    dSwap = agree_digits(rich, KITE_M1)
    print(f"           MEASURED agreement = {mp.nstr(dSwap, 6)} d\n")
    # [cert] swap-kernel certified budget (exact kernel: no interpolant/GL
    # terms; l1 prefactors of rich = 2 v6 - v5 are exact -> l1 = 2+1):
    ab_sw = _addback_swap_bound(A1, kernel_nmax_for(QUAD_DPS))
    l1_sw = mp.log((W_MAX + 1) / 2) / mp.pi          # (1/pi) int_1^W dw/(w+1)
    with mp.workdps(20):
        tot_sw = 2 * abs(v6 - v5) + 2 * e6 + e5 + ab_sw \
            + rho.err_top * l1_sw \
            + _guard_drops(lambda w: 1 / (w + 1), mp.mpf(1))
        print(f"           [cert] kernel-swap bound: 2|L{LEVEL+1}-L{LEVEL}| "
              f"{mp.nstr(2 * abs(v6 - v5), 3)} + engine {mp.nstr(2 * e6 + e5, 3)}"
              f" + addback {mp.nstr(ab_sw, 3)} + transport "
              f"{mp.nstr(rho.err_top * l1_sw, 3)} + guards -> total "
              f"{mp.nstr(tot_sw, 3)}")
    bar_swap = min(QUAD_DPS - SWAP_MARGIN, 50)
    print(f"           [cert] kernel-swap held-out gate: {mp.nstr(dSwap, 5)} d "
          f">= bar {bar_swap} d -- RAISES on fail")
    if not dSwap >= bar_swap:
        raise RuntimeError(f"[cert] kernel-swap self-test vs -Sigma_kite(-1): "
                           f"{mp.nstr(dSwap, 6)} d < bar {bar_swap} d -- STOP")

    # --- [5] second kinematic point: same rho, new kernel --------------------
    print(f"[5] [{time.time()-T0:6.1f}s] f(s,t): same rho, kernel rebuilt at "
          "(s,t)=(-2,-1/5)  [reduced precision demo]")
    K2 = BoxKernel(mp.mpf(-2), mp.mpf(-1) / 5, mp.mpf(1), 22, verbose=False)
    v2, e2 = disp_subtracted(rho, K2, panels, dps=22, maxdegree=3, Kc_pre=K2.tay1)
    mp.mp.dps = AMBIENT_DPS
    print(f"           I(-2,-1/5,1) L3 = {mp.nstr(v2, 20)}")
    print("           (any deep-Euclidean point runs; no independent oracle was")
    print("            computed here, so no digit claim is made at this point)\n")
    with mp.workdps(20):
        print(f"           [cert] [5] is a fixed-L3 speed demo (explicit "
              f"no-digit-claim above); mpmath engine estimate "
              f"{mp.nstr(e2, 3)} -- for certified digits at this point run "
              "--point -2 -0.2")

    ok = (dA >= 30 and dP >= 30 and d12 >= bar_rho)
    if _ARGS.fastcache_bank and ok:
        # banked_d MUST be derived from the STORED strings (what the fast
        # path re-checks), not the in-memory values -- string truncation
        # otherwise shifts the recomputed agreement past the 0.05 d tight
        # bar (caught live in the lbl3vp scratch run of the disp-fastcache work).
        s_I = mp.nstr(I_gate, QUAD_DPS + 8)
        s_r12 = mp.nstr(r12, DPS + 10)
        s_sw = mp.nstr(rich, QUAD_DPS + 6)
        s_r5 = mp.nstr(spot['rho(5)'][0], DPS + 10)
        s_r100 = mp.nstr(spot['rho(100)'][0], DPS + 10)
        with mp.workdps(AMBIENT_DPS):   # = the fast path's parse precision
            bd = {'dA': float(agree_digits(mp.mpf(s_I), mp.mpf(GT_AMF_STR))),
                  'dP': float(agree_digits(mp.mpf(s_I),
                                           mp.mpf(GT_PARENT_STR))),
                  'd12': float(agree_digits(mp.mpf(s_r12),
                                            mp.mpf(RHO_W12_STR))),
                  'dSwap': float(agree_digits(mp.mpf(s_sw),
                                              mp.mpf(KITE_M1_STR)))}
        with mp.workdps(AMBIENT_DPS):   # rho(5)/rho(100) spot gates, same rule
            bd['d5'] = float(agree_digits(mp.mpf(s_r5), mp.mpf(RHO5_STR)))
            bd['d100'] = float(agree_digits(mp.mpf(s_r100), mp.mpf(RHO100_STR)))
        _fc_bank({'cached_dps': QUAD_DPS, 'I_gate': s_I, 'rho12': s_r12,
                  'kernel_swap_rich': s_sw,
                  'K1_const': mp.nstr(K.tay1[0], 60),
                  'rho5': s_r5, 'rho100': s_r100,
                  'banked_d': bd}, time.time() - T0)
    elif _ARGS.fastcache_bank:
        print("[fast-cache] bank REFUSED: gate run did not PASS")
    print(f"total wall time: {time.time()-T0:.1f}s")
    print("PASS -- computed-at-runtime values agree with all held-out oracles "
          f"(oracle bars >=30d fixed by the ~40d literals; rho(12) self-check "
          f"bar >={bar_rho}d, scales with --dps)"
          if ok else "FAIL -- see above")
    raise SystemExit(0 if ok else 1)


if __name__ == '__main__':
    main()
