#!/usr/bin/env python3
"""gg -> Zgamma exact-m_t two-loop elliptic masters (sector E125: g31=R_a, g32=R_b)
— derived-constant closed-form evaluation of the t-cone + independent-oracle gate check.

FINAL FORM (round 3, 2026-07-04). At fixed s=-1/4 the certified 14-master t-cone
connection dM/dt = A_t(eps,t) M (exact rational tables, zgamma-cone-At.json)
has the derived structure — verified EXACTLY (rational arithmetic) at runtime:

  * 11 of the 14 cone masters (incl. g31 = R_a) have A_t row IDENTICALLY ZERO:
    they are exactly t-independent (the Gamma_0(4) curve is s-only).
  * the remaining t-tail (m8, m11, g32) is a strictly triangular VoP chain over
    exact dlog kernels D1 = 200t-53, D2 = (236-448 eps)t+53,
    D3 = eps(200t-53)^2 - (60000 t^2 - 31800 t + 2809) — and its exact VoP
    solution is POLYNOMIAL in t (tensor-decomposition theorem: t enters the
    family only through the ISP numerator (k1-p1)^{2n}; every candidate letter
    cancels identically):
        m8(t)  = c8*(200t-53) + K5/2 + K6/8 + K7/2
        m11(t) = c11*L1(eps,t) + C11(eps),   L1 = 448 eps t - 236 t - 53
        g32(t) = c13*D2q(eps,t) + B0(eps),   D2q = eps(200t-53)^2
                                                   - (60000t^2 - 31800t + 2809)
        g31    = K12                          [exactly t-independent]
    This script verifies dM/dt = A_t M LIVE (eps-Laurent arithmetic, several t
    points including a complex one at the apparent singularity detour) — the
    closed forms are checked against the SAME certified connection the round-2
    quadrature transport used, to ~working-precision cancellation.

  * ALL boundary constants are now DERIVED — ZERO AMFlow-derived constants
    remain anywhere in the runtime path (round-2 cusp seeds were verbatim/
    transported AMFlow E04 artifact values; they are SUPERSEDED and kept only
    as a cross-check target):
      K0..K5   LIVE closed forms (Gamma^2 / 3F2 / 2F1 eps-Laurent series via
               the Ser engine; corner masters of the p1-free vertex subfamily),
               gated below against 54 independent E01 accepted.tsv corner rows
               (leg-B midpoints of the goal-100/goal-130 pair; that pair's own
               certificate is 109-112 digits per order over eps^-2..+4 at E01
               (E02/E04 the same, E03 109-113); every agreement above it is
               agreement with the printed 140-digit strings, not an oracle
               certificate).
      K6,K7,K9,K10 closed forms CLOSED (2026-07-05 closed-form
               derivation: exact Gamma-ratio ladders with TERMINATING
               Thomae-balanced 3F2(1) inner sums; engine vendored
               AST-identical, docstrings trimmed, from the archived
               derivation's core2.py). DEFAULT run (2026-09-06, the
               promotion of the 2026-09-03 re-gate): the closed forms are
               evaluated AT the requested dps via Cauchy/DFT Laurent
               extraction on |eps|=1/64 (recorded recipe K=128 @ dps 160,
               dps-scaled) and SERVED as the values; the dps-190 endpoint
               strings (~184 d stored / 152.3 d mutual-certified) are the
               COMPARE GATE: every stored order checked Re AND Im,
               scale-relative, against the live closed form, a named
               K6K7K9K10GateError (rc=1, no evaluation) below the bar;
               the strings are never a value source on this path.
               --bank PATH writes the four live Laurent towers to a json
               (producer block, date -u stamp) BEFORE the gate consults
               any stored string. --k-strings restores the 2026-07-08
               string-served path (values from the strings, the closed
               forms only as the cheap min(dps,60) gate) for A/B
               comparison. The dps-160 closed-form leg is hour-class on a
               loaded host (the record figure and its load are stated
               once, under INTERFACE --dps).
               Reported/gated agreement digits CLAMP at each constant's own
               certified floor (row21-k3 pattern), never above.
      K12 and the t=-1/3 endpoint values of m8/m11/g32 = the
               FULLY ANALYTIC region-seeded s-transport endpoint (the
               2026-07-03 endpoint derivation: exact Gamma-sum cusp
               boundary + exact A_s connection + Frobenius/march;
               refreshed dps-190 digit strings ~185 d stored / 152.3 d
               mutual-certified, vendored with full provenance in
               zgamma-derived.json["endpoint_constants"]).
               These four (K12=R_a, _M8end, _M11end, _Rbend) are the
               ELLIPTIC march residue — Gamma_0(4) sector, no
               hypergeometric/Gamma-ladder form expected (by structure).
               Seed provenance CLOSED by the 2026-07-04 seed derivation
               (seeds_final record): all 7 analytic-branch A0 G-seeds
               {G5..G11} are DERIVED (uniform cusp Gamma-sum closed
               forms), gated 61.1-65.9 d worst-of-13-orders against the
               dedicated independent AMFlow oracle and re-gated at a second
               quadrature config (dps150/K96/r=1/24); the provisional AMFlow
               seed set is RETIRED (>=159.4 d agreement at seed orders).
      T1,T8,c13 solved AT RUNTIME, exactly: T1/T8 from the m8/m11 endpoint
               equations at t=-1/3 (2x2 Q(eps)-linear solve over the exact
               recorded slope tables); c13 = (Rb_end - B0)/D2q(t=-1/3).
               Z88 is ELIMINATED (its only consumer was the c13 lincombo).
    The c8/c11/c13/B0/C11 slope/embedding tables are exact Q(eps) integer
    tables (zgamma-derived.json["slope_tables"], provenance inside).

The Gamma_0(4) modular spine of the s-direction stays live and untouched from
round 2: the Eichler cocycle of B_{2,4}(tau) = -(E2(tau)-4E2(4tau))/24 is
verified by runtime quadrature of the E2 q-series. The conductor-4 ring
generator Catalan = L(chi_-4,2) is now computed by LIVE alternating-series
summation (not just a literal comparison).
CATALAN NOTE: "w2 = Catalan" as a boundary-constant VALUE is REFUTED (PSLQ,
Class-1 2026-07-03) — Catalan is the conductor-4 ring GENERATOR L(chi_-4,2);
no boundary constant here is claimed equal to Catalan, and the three
independent value-fit refutations of ring closure for the t=0 cusp constants
stand.

This script COMPUTES the masters at runtime and RE-MEASURES agreement as
-log10(|f-oracle|/|oracle|) against the independent AMFlow oracle at
E01 (t=-1/3, consistency: the endpoint derivation's own transport gate
point), E02 (t=-3/2), E03 (t=-6) and E04 (t=-25) — E02/E03/E04 are
INDEPENDENT: E02/E03 were never used in any derivation; E04's contamination
ended when the round-2 seeds (derived from
the E04 artifact) were retired from the runtime path (no surviving constant
touches it; t=-25 is a far polynomial extrapolation from the t=-1/3 endpoint).
Corner gate: 54 independent E01 corner rows never used in the MB/Barnes
derivations.

Self-contained: python3 + mpmath (pip install mpmath) + zgamma-derived.json +
zgamma-cone-At.json + zgamma-cusp-seeds.json (same dir; the last is the
superseded round-2 seed artifact, used only as a cross-check target).

GATE TABLE (re-measured 2026-09-06 on this release, one process each on a
shared host; the 2026-07-04 table printed tail 134.21 d / consistency 137.24 d
at dps 160 -- superseded by the figures below, which the served bytes print;
round-2 table for comparison: worst independent word-vs-oracle 114.89 d at
dps 100):
  --dps 140 (default; K6/K7/K9/K10 = the live closed forms):  corners K0..K5
      vs 54 independent E01 rows: worst 139.34 d;  tail vs oracle, independent
      (E02+E03+E04, all masters, eps^-2..4): worst 139.36 d;  consistency
      (E01): worst 139.53 d;  the live closed forms vs the stored endpoint
      strings (52 Re+Im pairs): 152.3 d (= the per-constant certified floor;
      bar 135.0 d);  derivative identity dM/dt = A_t M: 154.8 d cancellation at
      4 t-points;  round-2 seed supersession: t-indep 139.3 d / t-dep 119.4 d
      (= the old seeds' own caps);  spine cocycle 167.4 d;  ring generator live
      162.0 d;  wall printed.
  --dps 160 (the derivation precision; the string path --k-strings, measured
      2026-09-06):  the same oracle-capped triple 139.34 / 139.36 / 139.53 d;
      derivative identity 175.1 d;  seed cross-check 139.3 / 119.4 d;  spine cocycle
      188.2 d;  ring generator 182.0 d;  the closed-form gate at min(dps,60) = 60:
      73.5 d (bar 55.0 d).  The closed-form path at dps 160 (hour-class) was
      not re-run for this release; the 2026-09-03 re-gate of the derivation
      run's evaluator printed the same triple with the closed forms consumed
      live at dps 160.
  --dps 100 (the closed forms, measured 2026-09-06):  120.95 / 110.96 / 118.50 d, the
      closed forms vs the strings 113.8 d (bar 95.0 d): arithmetic-limited
      (~work-dps-limited) until the stored-string caps bind (corner strings
      ~139-141 d, endpoint strings ~137-140 d).  Doubling --dps grows every
      live agreement until those caps bind; the caps are printed at runtime.
  Every oracle string in the rows above is one of the independent evaluations
  (leg-B midpoints of the goal-100/goal-130 pair; that pair's own certificate
  is 109-112 digits per order over eps^-2..+4 at E01 (E02/E04 the same, E03
  109-113); every agreement above it is agreement with the printed 140-digit
  strings, not an oracle certificate).

INTERFACE (evaluation standard):
  CLI     python3 zgamma-evaluate.py [--help | -h] [--dps N]
                                     [--t P/Q | --point P/Q] [--transport]
                                     [--k-strings] [--bank PATH]
                                     [--deep-closed-forms]
                                     [--boundary-recompute [DPS]]
                                     [--point s,t [--dps 30|45] [--check]
                                     [--mutate] [--workdir DIR] [--out JSON]]
          no args = the gate demo at the default dps 140: the K6/K7/K9/K10
          Gamma-ladder closed forms evaluated at dps 140 and served as the
          values, the endpoint strings the compare gate (a 61-point
          Cauchy/DFT leg over ZG_NP_K6 fork workers) -- minutes-to-tens-of-
          minutes on a loaded host: measured on this release 294.42 s (GNU time, one
          process, ZG_NP_K6 at its default min(8,cpu) = 8 workers, nice
          10) at host load ~108-141 on a shared 96-core host, contended; wall printed. At dps
          140 the default prints the oracle-capped gate triple 139.34 /
          139.36 / 139.53 d, the same digits as at dps 160 (GATE TABLE).
          --help, -h     print this text (the module docstring) and exit 0,
                         before any other argument is read.
          --dps N        working precision in decimal digits (env DPS also
                         honored; CLI wins; default 140). --dps 160 is the
                         derivation precision of the paper: on the default
                         path a 67-point closed-form leg, hour-class on a
                         loaded host (the derivation record: 3276.8 s at dps
                         160 under load ~250, 33 s/point over 65 points in a
                         single niced process; on this release's recipe the
                         promotion's one-point pilot measured 42.0 s/point in
                         a two-core slot at host load ~111-125; not re-run for
                         this release). --k-strings at dps 160 stays
                         minutes-class.
          --deep-closed-forms
                         accepted for compatibility, no effect: the closed
                         forms evaluated at the full requested dps and served
                         as the values ARE the default since 2026-09-06 (the
                         no-args line above; the dps-160 wall under --dps).
          --k-strings    the A/B path (the default until 2026-09-06): the
                         K6/K7/K9/K10 values served from the stored endpoint
                         strings under the cheap min(dps,60) closed-form
                         gate; minutes-class on a loaded host (measured on this release:
                         35.04 s at dps 160 and 30.85 s at dps 140, one
                         process each at host load ~108-129).
                         At dps 160 its output is byte-identical to the
                         previous release's default (stamps and walls
                         masked); at dps 140 it is its own tier, printing
                         the same oracle-capped triple.
          --bank PATH    write the live K6/K7/K9/K10 Laurent towers (Re/Im
                         strings at workdps, the recipe, a producer block
                         with a date -u stamp) to PATH before the compare
                         gate consults any stored string.
          --t P/Q        ALSO evaluate the masters at a different Euclidean
                         point t = P/Q (rational string; t<0). The tail is an
                         exact polynomial in t — no transport, no detour, no
                         tail certificates needed.
          --point s,t    (with a comma) the (s,t) GRID SURFACE tier: the
                         fourteen-master t-cone at an off-line Euclidean point,
                         s one of the five grid values, transported in t from
                         the vendored (s,-1/3) seed by the vendored worker and
                         gated against the vendored fixtures; --dps 30|45,
                         --check, --mutate, --workdir, --out; exit codes and
                         walls under GRID (s,t) SURFACE below.  A CANDIDATE
                         tier (2026-09-06); the served tiers do not read it.
          --transport    ALSO run the round-2 VoP quadrature transport
                         (Chebyshev words over the certified connection),
                         seeded by the DERIVED t=0 values, along the detour
                         path through E01/E02/E03, and compare against the
                         closed forms (slow — minutes-class at dps 100;
                         cost grows steeply with dps).
          --boundary-recompute [DPS]
                         OPT-IN HEAVY leg: recompute the s-transport endpoint
                         with the vendored chain (zgamma_chain/) at DPS (bare
                         flag: max(150, ceil(1.2*dps)); an explicit DPS below
                         max(ceil(1.2*dps), dps+22) refuses up front) and
                         SUBSTITUTE it into K; the cached endpoint strings
                         demote to a compare-on-load cache. Hours-class per
                         production-precision leg: the two complete
                         production-precision legs on the derivation record ran
                         4:16:57 (dps 165) and 4:28:51 (dps 190) end-to-end at
                         host load ~119 (seeds/gcache 5615.5 / 9061.8 s,
                         Frobenius 2188.4 / 1535.6 s, march 7515.5 / 5455.6 s):
                         a contended wall, not a cost; the record's ~0.96 h /
                         ~1.18 h + 28 / 39 min are a rate-fit projection of the
                         march alone. The dps-45 smoke leg is minutes-class.
                         The run prints its own wall. NEEDS the cusp-boundary
                         solver modules of the archived endpoint derivation
                         (core_fast.py with collinear.py / core_engine.py,
                         under the <archive>/solve_row20/cusp_boundary
                         placeholder that zgamma_chain/MANIFEST.json names by
                         sha256), which are NOT part of this bundle: without
                         them on the module search path the flag is REFUSED BY
                         NAME (exit status 2) after the DPS floor check and
                         before any chain leg is spawned, and
                         zgamma_chain/g_precompute.py refuses likewise when run
                         directly; the served path is the default tier (the
                         endpoint read from the stored strings, the closed forms
                         gated against them).
  Python  f(t, dps=100, deep=True) -> {"m8","m11","g31","g32": eps-Laurent
          lists (deep=False = the --k-strings path); the dict carries
          (eps^-2..eps^4, mpmath mpc) and "_deriv_digits": live dM/dt = A_t M
          cancellation digits at that t}. The file name has a dash, so:
            spec = importlib.util.spec_from_file_location("zg", "zgamma-evaluate.py")
DOMAIN: the certified cone tables are the fixed-s slice s=-1/4 (the s-direction
is the Gamma_0(4) modular spine; its cocycle/ring checks are live below, but
s-transport is NOT shipped here — stated scope, not faked). t must be real
Euclidean, t<0. The closed forms are polynomials in t: the round-2 apparent
singularity t=-53/236 was a property of the word REPRESENTATION only; the
masters themselves are entire in t (verified live by the derivative-identity
check at a complex point next to it).
STATED GAPS: K12 + the m8/m11/g32 endpoint values are analytic-transport
DIGIT STRINGS (~185 d stored, 152.3 d mutual-certified), not closed forms —
they are the elliptic (Gamma_0(4)) march residue and a hypergeometric form
for them is not expected by structure; sector E127 not covered on this slice.
(K6/K7/K9/K10 closed forms CLOSED 2026-07-05 and wired live here.)
GRID (s,t) SURFACE (--point s,t; 2026-09-06; a CANDIDATE tier -- the served
tiers above are untouched and never read vendor_row20_grid/):
  WHAT IT COMPUTES  the fourteen sector-125 t-cone masters (the served cone's
      basis order: eleven t-independent masters, m8, m11 and g32 = R_b, with
      g31 = R_a among the fourteen) at an off-line Euclidean point (s, t),
      M = 7/25, m_t^2 = 1, eps^-2..eps^4, by the vendored transport worker of
      record (vendor_row20_grid/grid_leg_worker.py: mpmath odefun on the
      eps-Laurent-expanded exact rational connection A_t(eps, t) at that s,
      sub-nodes of length 1/24, checkpointed after every sub-node, resumed on a
      re-run from --workdir) from the s-march endpoint strings at (s, -1/3) --
      the seeds, shipped as strings at the chain's print width dps - 5: the
      s-march itself needs the cusp-boundary chain and is not servable
      standalone, and the A_t build at a new s needs the 449 MB reduction
      table, so s is one of the five grid values only.  Working precision 30
      or 45 (the two seed members; --dps 60 is NOT ESTABLISHED, refused).
  THE 25 POINTS  s in {-1/20, -1/10, -3/20, -1/5, -9/40} x t in {-1/2, -2/3,
      -5/6, -1, -5/4}: at a grid point the run is GATED, row by row (98 rows =
      14 masters x 7 orders), against the vendored fixture at the precision
      run (vendor_row20_grid/endpoints/: the strings the record's t-legs
      printed): digits = -log10(|run - fixture| / (|fixture| + 10^-(dps-5)))
      at dps 400 (the record's convention; equal strings 999; a row with both
      values below 10^-(dps-10) is an exact zero at this precision, counted
      dps - 10); the RAISING bar per row = min(dps, the fixture string's
      significant digits) - 10 (the record's pass margin: 15..20 d at dps 30,
      30..35 d at dps 45); FAIL by name (rc 1) on any row below its bar.  A
      run at the fixture's own precision reproduces every printed digit (the
      transport is deterministic; the identical rows are counted).  --check
      runs both precisions and adds the pair.
  THE CERTIFICATE  the transport's own two-precision pair, dps 30 vs 45, per
      row -log10(|hi - lo| / (|hi| + 10^-25)) at dps 400 (zero rows counted
      20 d): the record's floor over the 25 points is 17.67 d at (s, t) =
      (-1/5, -5/4), the best point 19.09 d -- the SAME transport chain at two
      precisions, not an independent gate; --check compares the run's pair
      floor with the record's floor at that point (bar = its integer part).
  THE ONE INDEPENDENT GATE  at (s, t) = (-1/5, -1/2) the independent AMFlow
      evaluation (goal 40 against goal 60, the twins agreeing to 45.21 d)
      reproduces the transported cone to 33.49 d over 94 rows (worst R_b at
      eps^4); the certificate there is 18.31 d, capped by the transport's
      dps-30 member, not by the agreement (vendor_row20_grid/GRID_RECORD.json
      carries the figures by object).
  A NON-GRID t  any rational t in the class of the (s, -1/3) seed's
      t-transport -- Euclidean t < 0, above the u = 4 m_t^2 threshold
      t = M - s - 4 (about -3.5 at these s; a contour leg below it is not
      established for this cone), the real segment from -1/3 to t touching no
      root of the connection's denominators at eps = 0 (the cone's apparent
      singularities at these s lie at t ~ -0.02..-0.19, between the seed and
      0) -- is transported at BOTH precisions, the values printed, and the
      pair the only certificate ('no fixture at this point'); anything outside
      the class is REFUSED by name (rc 2), as is any s off the five (rc 2) and
      --M (a second mass ratio; rc 2: NOT ESTABLISHED, below).
  NOT ESTABLISHED (the list of record; two phrases re-worded for this text)
      [2026-09-11: the first two items below and THE ONE INDEPENDENT GATE above
      are this tier's 2026-09-06 record; for the gate count they are superseded
      by the data shelves vendor_row20_p12/ and vendor_row20_a2a/ (README.md in
      each): a dps-60 transport member at all 25 points and the independent
      AMFlow gate at five points, the goal-60 evaluation reproducing the
      transported fourteen masters to 47 digits or better at each; this tier
      reads neither shelf, its fixtures, pins and bars unchanged]
      - the AMFlow gate at the other 24 grid points (one point gated:
        (-1/5,-1/2)); the grid's certificate elsewhere is the transport pair
        only
      - a dps-60 transport member (the certificate at the gated point is
        capped by the dps-30 member at 18.31 d while the agreement reads
        33.49 d)
      - the M=1/4 gate (P2a/P2b NOT RUN; P2b the safe point)
      - idle-box walls: every wall here is CONTENDED (the host's load 113-119
        at the grid's spawns, ~250 at the pilot's)
      - the flatness of the two-variable connection across the 25 points
        (needs A_s at each grid t: the s-cone builder at t != -1/3; not this
        leg)
      - the 8 s-cone masters outside the 14-cone at the grid points except
        the 7 t-independent ones (1 master t-dependent outside the cone: not
        transported)
      - the exact polynomial t-tail coefficients at s != -1/4 (the t-legs
        transport the cone instead)
      - the goal-40/60 walls of the deformed family (no AMFlow run of this
        family at those goals exists)
      - the --M tier: the cusp seeds and corner forms carry M = 7/25 literals
        at 21 sites; no M = 1/4 object beyond the modular descent.
  USAGE
      python3 zgamma-evaluate.py --point -1/5,-1/2             # the AMFlow-gated grid point at dps 30, gated vs its fixture
      python3 zgamma-evaluate.py --point -1/5,-1/2 --dps 45    # the same at dps 45
      python3 zgamma-evaluate.py --point -1/5,-1/2 --check     # both precisions, then the pair vs the record's floor
      python3 zgamma-evaluate.py --point -1/5,-1/2 --mutate    # the planted control: one fixture digit changed in memory -> FAIL by name (rc 1)
      python3 zgamma-evaluate.py --point -1/5,-3/4             # a non-grid t: both precisions, the pair the only certificate
      --workdir DIR (default zgamma-grid-work/ under the current directory):
      checkpoints, heartbeats, worker logs, the points directories and the
      TRANSPORT_*.json results, named by (s, t, dps); --out JSON writes the run
      receipt (refused up front if it exists).  A leg is a minutes-class
      computation (WALLS below); an interrupted leg resumes from its last
      sub-node when the same command is run again with the same --workdir.
  EXIT CODES  0 PASS | 1 FAIL by name (also the expected outcome of --mutate)
      | 2 refused by name (an s off the five, a t outside the class, --dps not
      30/45, --M, a usage slip, --out exists) | 3 a vendored file's sha256 pin
      mismatch | 4 a pinned file missing | 5 the worker did not finish (its rc
      and last line printed; rc 6 from the worker = a checkpoint from another
      configuration under --workdir: move it aside).
  FILES  vendor_row20_grid/ (its README.md names every file): endpoints/ (50
      fixtures), cones/ (5), seeds/ (10), grid_leg_worker.py, GRID_RECORD.json,
      README.md, GRID_MANIFEST.sha256 -- every file but the manifest pinned
      in-code (GRID_PINS; a byte flip refuses rc 3, a missing file rc 4); the
      manifest checks with `sha256sum -c GRID_MANIFEST.sha256` from that
      directory.
  WALLS  (GNU time wall clock, one process each, nice 10, a two-CPU fenced slot
      on a shared 96-core host, CONTENDED; not a cost; the record's own walls
      per leg are in GRID_RECORD.json):
      --point -1/5,-1/2 --dps 30 (the tier's pilot, ALONE): 11.56 s (maxrss 34116 kB; host loadavg 83.90 -> 85.61; rc 0)
      --point -1/5,-1/2 --check (both precisions + the pair): 39.40 s (maxrss 48712 kB; host loadavg 93.45 -> 99.26; rc 0)
      --point -1/5,-1/2 --mutate: 13.00 s (maxrss 34976 kB; host loadavg 90.07 -> 93.45; rc 1)
      --point -1/5,-3/4 (a non-grid t; both precisions + the pair): 86.75 s (maxrss 47220 kB; host loadavg 90.07 -> 101.19; rc 0)
      the served default (dps 140; no arguments) before this cure, ALONE (RULE 2 pilot): 812.47 s (maxrss 29652 kB; host loadavg 89.40 -> 86.62; rc 0)
      the cured default (dps 140; no arguments), alongside the battery: 837.80 s (maxrss 35892 kB; host loadavg 101.52 -> 85.91; rc 0)
      the battery: 25 grid legs at dps 30, four legs at once: 12.41..61.24 s each (sum 834.06 s; host loadavg 88.6-126.63)
      the battery: 25 grid legs at dps 45, four legs at once: 27.11..129.16 s each (sum 1779.97 s; host loadavg 88.6-126.63)
CHANGELOG: round 3 2026-07-04.  2026-07-05: seed-provenance fold -- LABELS
ONLY (all 7 A0 G-seeds {G5..G11} derived + oracle-gated 61.1-65.9 d,
second-config re-gated, provisional set retired; the vendored constants were
already the tag-'final' analytic-seed endpoint: zero wiring change, gates
re-measured identical).  2026-07-05 dps45 SMOKE (pre-revision
verify-then-discard semantics, invocation `--boundary-recompute 45` at the
default --dps 160): chain leg end-to-end, worst 32.9 d vs cached strings = the
run's own E01-oracle floor (32.5 d); endpoint VALUE-IDENTICAL to the
eval_row20.py twin leg; chain leg minutes-class at dps 45, RSS < 1 G;
fixes: zgamma_chain/transport_leg.py outputs cwd-first + cache gate accepts
the run's measured gate_worst floor (mutation-tested on scratch copies).
Record: <archive>/zgamma_smoke_2026-07-05/.  NOTE: under the revised
substitution semantics + FLOORFIX below, THAT invocation now REFUSES up front
by design (brc 45 < the required floor at dps 160); the accepted class is
stated in the FLOORFIX entry.
2026-07-05 (second revision; record <archive>/axis3_wave/row20/):
(a) --boundary-recompute now
SUBSTITUTES the fresh chain endpoint into K (was verify-then-DISCARD); the 52
cached endpoint strings demote to a compare-on-load cache checked on Re AND
Im that RAISES on mismatch. (b) bdps slaved to dps: bare flag => bdps =
max(150, ceil(1.2*dps)); explicit-bdps refusal floor as CORRECTED by the
FLOORFIX entry below (the revision shipped ceil(1.2*dps), the TOOLS-twin
track).
(c) zgamma_chain march hardening (both vendored copies): geometric-envelope
tail certificate (trailing-8 max * q/(1-q), q = |h|/rho from the step rule)
replaces the last-3-coefficient probe; cert-triggered halves RE-CHECK in a
loop with a RuntimeError at the halve cap. Default (no-flag) path unchanged.
2026-07-05 pm ROW-20 FLOORFIX (record
<archive>/axis3_wave/row20/{verifier_legs34,floorfix}/): the
first refusal floor ceil(1.2*dps) was the tools twin's (gates ~dps-6/dps-10);
THIS twin gates at DPS+2 (independent tail) / DPS+4 (consistency,
supersession) through the +22-digit guard, so accepted low-dps substituted
legs exited OVERALL: FAIL (measured: brc 45 at --dps 30 -> independent tail
30.22 d < 32).
Corrected refusal floor: bdps >= max(ceil(1.2*dps), dps+22)  [binding gate
independent-tail >= DPS+2 vs endpoint propagated floor ~bdps-14.8 d measured
at bdps 45; +5.2 d guard; the 1.2 branch dominates for dps >= 110, production
bdps>=150 legs unaffected].  ACCEPTED smoke class: brc >= dps+22 -- minimal
leg `--dps 30 --boundary-recompute 52` re-validated end-to-end on the merged
code (real chain leg): OVERALL: PASS rc=0 (floorfix record); refusal edge
`--dps 30 --boundary-recompute 51` refuses rc=1 fail-closed.
2026-07-08 (closed-form wiring flipped live): K6/K7/K9/K10 closed forms
wired — the 2026-07-05 Gamma-ladder/terminating-3F2 engine (core2.py,
AST-identical with docstrings trimmed; port controls + two production legs
recorded at <archive>/row20_closedforms/, gated 161.3-184.4 d vs two
independent references) is vendored below and evaluated by Cauchy/DFT on
|eps|=1/64 with
K = 4*((dps+35)//6+1) points (recorded K=128 recipe at dps 160, scaled; inner
series tol dps+22, workdps dps+40; DFT points parallelized over ZG_NP_K6
workers, default min(8,cpu), fork pool, deterministic assembly).
PATH of 2026-07-08 (the default until 2026-09-06; now --k-strings): the
values are SERVED from the 4x7 cached endpoint strings, and the closed forms
run only as a CHEAP compare gate at min(dps,60): every stored order checked
Re AND Im, scale-relative, agreement strictly > the gate bar, else a NAMED
K6K7K9K10GateError raises fail-closed (rc=1, no evaluation). OPT-IN
--deep-closed-forms restores the full runtime evaluation at the requested
dps (values = live closed forms, strings = compare-cache; dps160-class = an
hour-class run, measured in the derivation record; the figure and its load
are stated once, under INTERFACE --dps). PER-CONSTANT FLOOR CLAMP
(row21-k3 pattern): the gate bar and every reported agreement digit clamp at
each constant's own certified floor (CERT_FLOOR_K6K7K9K10: min of the
stored strings' 152.3 d mutual certification and the closed form's own
legA-legB two-precision cert 159.9-164.5 d — production.log-printed), never
above. Gate bar below the clamp = min(gate-dps, string-sig-digits)-5 d
(short exact entries like 0.5 gated at gate-dps-5). Null certificates on the
live DFT: c_{-3} (all four) and K10 c_{-2},c_{-1} (endpoint-pruned true zeros)
must be < 1e-(gate-dps-10) rel, else the same named raise. Under
--boundary-recompute the gate compares the live closed forms against the
FRESH endpoint (source -> CROSS-CHECK flip; the fresh chain now sources only
the elliptic quartet). K12/_M8end/_M11end/_Rbend keep the stored-string path
(elliptic residue). Downstream Laurent orders per constant are IDENTICAL to
the string era (same stored-order sets; K10 poles stay pruned). Timing: see
the derivation record.
2026-09-05 (labels only; no value, digit or gate changed): the walls of the two
complete production-precision --boundary-recompute legs and of
--deep-closed-forms at dps 160 are stated once each under INTERFACE with their
load and kind, and the per-leg hours the derivation record projected are
labelled the march-only rate-fit projection they are; the oracle-certificate
clause (what the oracle's own two legs certify vs agreement with its printed
strings) at the corner-gate line and under GATE TABLE; --help / -h prints this
text.
2026-09-06 (the promotion of the 2026-09-03 re-gate; no digit, bar or recipe
changed): the DEFAULT value path for K6/K7/K9/K10 is the live closed forms at
the requested dps (the former --deep-closed-forms), the dps-190 endpoint
strings the compare gate; the default working precision is 140 (was 160): the
same oracle-capped gate triple, a minutes-to-tens-of-minutes leg in place of an
hour-class one, and a bare --boundary-recompute (its recompute precision slaved
to --dps) now slaves to max(150, ceil(1.2*140)) = 168 (was 192); --k-strings
keeps the 2026-07-08 string-served path for A/B; --bank PATH writes the four
live Laurent towers before the gate consults any stored string; the Python
entry f(t, dps, deep=True) follows the default. K12/_M8end/_M11end/_Rbend stay
the analytic-transport strings (elliptic residue). Walls (contended; no
quiet-host wall is on the record): the promotion's record, one two-core slot
per run (ZG_NP_K6=2) on a shared 96-core host at load ~111-125, h:mm:ss -- the
default at dps 140 13:57.55, at dps 100 4:34.71, at dps 40 0:21.91, --k-strings at dps 160
1:00.74 (the previous release's default 0:57.70); this release, one process each, ZG_NP_K6 at its default
min(8,cpu) = 8 workers, nice 10, host load ~108-145, contended: the default
at dps 140 294.42 s, at dps 100 99.38 s, at dps 40 7.92 s; --k-strings at dps
160 35.04 s and at dps 140 30.85 s. The dps-160 closed-form leg was
not re-run (hour-class; the derivation record's 3276.8 s under load ~250 stands).
2026-09-06 (the (s,t) grid tier; no served tier, digit, bar or recipe changed):
--point s,t (with a comma; the served --point P/Q alias of --t is unchanged)
runs the CANDIDATE off-line tier described under GRID (s,t) SURFACE: the
fourteen-master t-cone at one of five grid s-values transported in t from the
vendored (s,-1/3) seed strings by the vendored worker of record, gated against
the 50 vendored fixtures at dps 30 and 45 with the RAISING bar min(dps, fixture
digits) - 10; M = 7/25 is the only mass ratio served (--M refused by name,
rc 2).  The dispatch happens after --help and before any other argument is
read; the served tiers never touch vendor_row20_grid/.
2026-09-11 (--boundary-recompute precondition; no value, digit, bar or recipe
changed): the flag checks, after the DPS floor and before spawning
zgamma_chain/run_recompute.sh, that the cusp-boundary solver module core_fast
can be found (the <archive>/solve_row20/cusp_boundary placeholder, the
chain directory, the module search path) and REFUSES BY NAME with exit status
2 when it cannot -- the solver modules are not part of this bundle, so on the
bundle as shipped the flag always refuses, naming what is missing and the
served path (before: the chain leg was spawned and its first step died on the
import, 'leg FAILED rc=1'); zgamma_chain/g_precompute.py carries the same
check and the same words; the GRID paragraph's NOT ESTABLISHED list gains the
succession note of vendor_row20_grid/README.md, whose in-code pin follows.
"""
import json
import os
import sys
import time
from fractions import Fraction

import mpmath as mp

DPS = int(os.environ.get("DPS", "140"))
GUARD = 22
HERE = os.path.dirname(os.path.abspath(__file__))

# 2026-09-11: --boundary-recompute precondition. The vendored chain's seed step
# (zgamma_chain/g_precompute.py -> cached_g.py -> seeds_build.py) imports the
# cusp-boundary solver modules of the archived endpoint derivation, which are
# not part of this bundle; the flag refuses by name (exit status 2, the
# bundle's 'refused by name' status) before spawning when core_fast cannot be
# found. The words are the same in zgamma_chain/g_precompute.py (REFUSAL).
BREC_CUSP_PLACEHOLDER = "<archive>/solve_row20/cusp_boundary"
BREC_RC_REFUSED = 2
BREC_REFUSAL = (
    "the boundary re-computation needs the cusp-boundary solver modules of the archived endpoint "
    "derivation -- core_fast.py (G5f..G11f; imported by zgamma_chain/g_precompute.py, cached_g.py and "
    "gvalues_analytic.py) together with collinear.py and core_engine.py (imported by seeds_build.py) "
    "-- and those modules are NOT part of this bundle: zgamma_chain/MANIFEST.json names core_fast.py "
    "and boundary_data.json by sha256 under the placeholder <archive>/solve_row20/cusp_boundary, and "
    "no module named core_fast can be found under that placeholder, in zgamma_chain/ or on the module "
    "search path of this run. Nothing was spawned, nothing was computed, no work directory was made. "
    "The served path instead is the default tier, python3 zgamma-evaluate.py [--dps N]: it reads the "
    "s-transport endpoint (K12 and the m8/m11/g32 endpoint values) from the stored analytic-transport "
    "strings in zgamma-derived.json (endpoint_constants; their certification is stated under STATED "
    "GAPS in --help) and serves K6/K7/K9/K10 from the live closed forms with those strings as the "
    "compare gate. With the solver modules on PYTHONPATH the --boundary-recompute leg runs the "
    "vendored chain as --help describes. Exit status 2: refused by name."
)

# eps-Laurent ranges (as in the certified transport): masters eps^-2..eps^4,
# connection eps^-2..eps^6.
OMIN, OMAX = -2, 4
NORD = OMAX - OMIN + 1
AMIN, AMAX = -2, 6
NORD_A = AMAX - AMIN + 1

# ---------------------------------------------------------------------------
# Independent ORACLE (legitimate literals, category: independent oracle).
# Source artifacts (independent AMFlow F2-deformed runs, leg-B midpoints,
# >=109 agreed digits per order; NEVER used to build connection or constants):
#   <archive>/F2-deformed/points/E01/accepted.tsv
#   <archive>/F2-deformed/points/E02/accepted.tsv
#   <archive>/F2-deformed/points/E03/accepted.tsv
# (E04 rows + the 54 E01 corner rows are vendored in zgamma-derived.json with
# the same provenance.)
# Index vectors (family npboxZ):
#   m8  = A1[0,-1,1,1,1,1,0,0,0]   (sector 60, dotted — first master of the chain)
#   m11 = A1[1,-1,0,1,1,1,1,0,0]   (sector 121 — second master)
#   g31 = R_a = A1[1,0,1,1,1,1,1,0,0]  (holomorphic period, t-independent)
#   g32 = R_b = A1[1,-2,1,1,1,1,1,0,0] (quasi-period master)
# Strings below are VERBATIM from the artifacts (byte-traceable by grep).
# Independence bookkeeping (round 3): E02/E03 never used in ANY derivation
# -> INDEPENDENT; E04 (in zgamma-derived.json) INDEPENDENT post-refresh (no
# surviving constant sources the t=-25 artifact); E01 = the endpoint
# derivation's own transport gate point ->
# CONSISTENCY only (the runtime T1/T8/c13 solve reproduces the E01-point
# t-dependent masters by construction).
# ---------------------------------------------------------------------------
ORACLE = {
    "E01": {  # s=-1/4, t=-1/3 (euclidean, u=259/300, values real)
        "t": "-1/3",
        "m8": {
            -2: "1.1391666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666667",
            -1: "-0.18411034541402258333236568028458325248224549852458691872769477157516987582439334709215990334070027425196545637629882193223384792768118431066",
            0: "2.3983169189675101277798019061315293065692578080839845251125457810043985342850246071425131968850597714242271475337616915185768126560347467049",
            1: "-0.89289912296329758457188046428669789705214816221323569407345787312265951759440376829526554876232120053569532813435098324581754672388846784275",
            2: "3.4064685533494678750922527002400276381087979236532825522253086781265684133471210610301072016377271825503567116070045351443853936365539324906",
            3: "-1.6681141351496367348455736385705111361168078429374447377150278683393099838471059119378824967396512439195975553268176972548538377630008815866",
            4: "3.9578644953134594508599310163780140883587909778814997316082551904031284192970493777004770088477034095982736509561795881680837230175418009130",
        },
        "m11": {
            -2: "1.0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000",
            -1: "-1.1064031594354231261026165935000145469014183940244059872714211097403844013904902324664486330823231704304077255756154836162460403220703562452",
            0: "2.1931228507185297570694045948264781740203765601325873143196733162788800661984720759992264725494831321359705331540444155829881147221967483939",
            1: "-2.6804900349084549006040171943060967076933711841871360648697274831170290635180003806145971594720340031442739732226146493932390664107681312294",
            2: "3.3915495668810526294596302148014087340013642033879703368357285497228680072194807801700672853192261341658547762815967951561529760968662594850",
            3: "-3.6675460887566802555143864738539371274315517213076491335546067257445221952444290679314819642499495349569009344709819864510397339528519237093",
            4: "3.3945560808327071461439461007557776290671656071649636392614345466453858037171999562379836660192319270513954285286707428503310135411612331922",
        },
        "g31": {
            0: "0.55129454202113704604185775543436541404184708727908803560545722607310576856872183860477957086157596612593368222815665191208909410043107265185",
            1: "0.90052626519318063053394458091777285943209305940493450449830238938444182430662963855442427923337643404557663561247139085904624707444187762248",
            2: "1.8773840408060890990544239069248336963358645966504007077387736360252441724383999035881397035871780933948849469515251285320428373645000119751",
            3: "2.0783744878542038416072543153949065805072197459730127626299017085781187134226823957738859397584053234320340750042216055301094135577316230826",
            4: "2.8545486087698869972482549799389882867047663730244598082243931283801499653892641524322028219755632409911241444076003995461224128265590639760",
        },
        "g32": {
            -2: "1.0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000",
            -1: "-1.1064031594354231261026165935000145469014183940244059872714211097403844013904902324664486330823231704304077255756154836162460403220703562452",
            0: "2.0152092958724462939329827043474520384265102414415949462525748148345513282505220544547824903401436766753737668508668647519711775889088293288",
            1: "-2.2867938384951714540031538435485168431067868186655680016424498809980917305946915216770294226486083314057618391042870133125954386934687337102",
            2: "2.2689150809916756546948355261397521764619436107191197786013385813025721655961036152364232334462451564824994528583654295514806288949813601125",
            3: "-1.2149064361511582769438132320394197386777788015116305362284203151951561839604410220417866498351525663795180375611283911174915368973627886449",
            4: "-1.9483710367312856148894714938601545201673364833176020255963184688711129471108951518681151664092371393213882649791303855190473256933770472504",
        },
    },
    "E03": {  # s=-1/4, t=-6 (euclidean, u=653/100, cone values real)
        "t": "-6",
        "m8": {
            -2: "1.8475000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000",
            -1: "-0.57962596267036712611851372679286708328286249747760363572070442762048516485922955925895379387735020388264851733786072354055502436342491997333",
            0: "3.6624200871834332677201145671251796976358549449185057099560860080889387943968358188733775362530626055160697212027529670617343281712936410610",
            1: "-1.9028825211734003269576429753137489195243182997672142835242595908874244145146324277382101695815191905437491642748711631621904846911242045229",
            2: "4.7204255970288043068988402247615498267887505790780788245087341334853892752517186375269828770193044109868434470279943138729672943710601078296",
            3: "-2.3284906930501918664462506314089719562867925593152153010807661954068141154667380894313290611445448111574320401588019158636309696369674759259",
            4: "3.3473021078399653559000462738546599162501688467405561430096972026821175932843787952240379827775041182473187005637020891629488381150785317508",
        },
        "m11": {
            -2: "1.0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000",
            -1: "-1.1064031594354231261026165935000145469014183940244059872714211097403844013904902324664486330823231704304077255756154836162460403220703562452",
            0: "2.1892690727895017614429514134303463944557256482976467619823683643258528431174235996863959470297005217480551829215172333407889451397329028987",
            1: "-2.6807254135899047524300193166620777303542334594648719730890166317498934280334936847649642765217574684858849661950857592529091908450794622669",
            2: "3.3855746552105348241495404720182325226694025412955050512838822355515991794393130003098773493975105535520568267114883805903379977720996214046",
            3: "-3.6659351368174427041440530906293468503604448839465335040391599948084884115897644667116027214602844779096449118467182818268270103828293491385",
            4: "3.3886601747116129902471508961541800089232218724862827700461214384263159493681459219987552952396577880765365942353090870502542732546541006972",
        },
        "g31": {
            0: "0.55129454202113704604185775543436541404184708727908803560545722607310576856872183860477957086157596612593368222815665191208909410043107265185",
            1: "0.90052626519318063053394458091777285943209305940493450449830238938444182430662963855442427923337643404557663561247139085904624707444187762248",
            2: "1.8773840408060890990544239069248336963358645966504007077387736360252441724383999035881397035871780933948849469515251285320428373645000119751",
            3: "2.0783744878542038416072543153949065805072197459730127626299017085781187134226823957738859397584053234320340750042216055301094135577316230826",
            4: "2.8545486087698869972482549799389882867047663730244598082243931283801499653892641524322028219755632409911241444076003995461224128265590639760",
        },
        "g32": {
            -2: "1.0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000",
            -1: "-1.1064031594354231261026165935000145469014183940244059872714211097403844013904902324664486330823231704304077255756154836162460403220703562452",
            0: "2.1987155735640074605573818403126802090715366496793229909726551582451771442975077984416054294870201985508044928389245806498590875556863395860",
            1: "-2.2851256851846158977658529049109663127730216088506935819192055893502251973973481779164837507946169433239083955458141443644496574819986839998",
            2: "2.5460326457629228970204643435900828615476561233523226326475251522721021503037453083999902899309818153002673038343052263506035800474215615863",
            3: "-1.3109692731316284886910422453748814170504512990996394627664592892068442411874624903984045570441291663666302612958412675610114895379890214533",
            4: "-1.6765400296418362484950426759843564930387841909084902447124246644918891853724009444828258822291658096002468697701908760991421129667528985042",
        },
    },
    "E02": {  # s=-1/4, t=-3/2 (euclidean, u=203/100, values real)
        "t": "-3/2",
        "m8": {
            -2: "1.2850000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000",
            -1: "-0.26554003131974057743539616044805345294119605713256094869684381840802890591980080253826452786295173035240020422132627226335879601739312988827",
            0: "2.6585734536002001860028074539831632106123807480205035925803334748159215290139269154400440902843544725607829715244363658951092423209409896606",
            1: "-1.1008368814183187374160080400863848722670067199449371683721523444271699375485684922982247354015678455373534708691639614638943280700840606887",
            2: "3.6769891211658018463465501317591645593076117056525053141660139189357374143274793856029933700986401413461039806642671366473287261407169685898",
            3: "-1.8040740147173980854692424312137236579165105786622798537020916415590902462393831249512391423524234489391517139686968010860726590311704745388",
            4: "3.8321604743630341960152488635055588176305452449995407574850226635193908962944407283670925034803094378495476317577283383729088937729170102031",
        },
        "m11": {
            -2: "1.0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000",
            -1: "-1.1064031594354231261026165935000145469014183940244059872714211097403844013904902324664486330823231704304077255756154836162460403220703562452",
            0: "2.1923294258507886991463112927743333958747131371077466123678752379356097555641385661701143055307043594090467845767594074743000503963953684390",
            1: "-2.6805384952252239877446646900852692711823722408619640459736987784237952562123666491161433306293300107146056482463587014231711508531263464430",
            2: "3.3903194380077107283663764442284018669624309200159921898103484262170185426765050607870870043941670440394846101936332980396616570300025398802",
            3: "-3.6672144221809548772910825420135803056816179606744782686543676929047505339037628265038597672050184938001129298130453413813488791002002171800",
            4: "3.3933422178077759964004882645142722366845889559075881661876936126002831866453358903652013543881431337330421391153315784209034493645274117962",
        },
        "g31": {
            0: "0.55129454202113704604185775543436541404184708727908803560545722607310576856872183860477957086157596612593368222815665191208909410043107265185",
            1: "0.90052626519318063053394458091777285943209305940493450449830238938444182430662963855442427923337643404557663561247139085904624707444187762248",
            2: "1.8773840408060890990544239069248336963358645966504007077387736360252441724383999035881397035871780933948849469515251285320428373645000119751",
            3: "2.0783744878542038416072543153949065805072197459730127626299017085781187134226823957738859397584053234320340750042216055301094135577316230826",
            4: "2.8545486087698869972482549799389882867047663730244598082243931283801499653892641524322028219755632409911241444076003995461224128265590639760",
        },
        "g32": {
            -2: "1.0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000",
            -1: "-1.1064031594354231261026165935000145469014183940244059872714211097403844013904902324664486330823231704304077255756154836162460403220703562452",
            0: "2.0282187758624931194901762722101413423563343431483607132717697230473750280054172098329872477464509671657283463594622772023499693662581534354",
            1: "-2.2866755765621901777467511843699012489856189653914026194596875260649665469781670092768981743354443274768094830150846471069895261695061325515",
            2: "2.2885610323952653479163036263169654323268750623118202009170147226579099554156051682914582776043708605323320649829488825628517571778365542375",
            3: "-1.2217167075555246692659213026788491634379932632081892355171710998139032603255769753522728177847304720695451490429353791726466596719167982074",
            4: "-1.9290998701429226573513240461682768866982194786719084883491287286897843819949315665860937579958769414896877715296836697339576252282421209552",
        },
    },
}

# Independent 50-digit cross-check of the t=0 value (recorded BEFORE any of
# this): the t->0 cubic-Lagrange extrapolation of four separate AMFlow sample
# points (t=-1/3,-3/2,-6,-25 at s=-1/4), which matched a direct AMFlow run at
# t=0 to ~54 digits. Artifact:
# <archive>/zgamma-t0cusp/clean_t0_from_existing.json["-1/4"].
STORED_RB0_T0 = "2.0138514658029632684164349976875944806115497569193"

# Cone-local indices of the word chain and the headline pair
I_M8, I_M11, I_RA, I_RB = 8, 11, 12, 13
T_INDEP = [0, 1, 2, 3, 4, 5, 6, 7, 9, 10, 12]
APPARENT_POLE = Fraction(-53, 236)  # eps^0 zero of D2 — apparent (representation-only)

HELDOUT_PTS = ("E02", "E03", "E04")
POINT_NOTE = {
    "E01": "consistency (endpoint-derivation transport gate point; "
           "t-dependent masters reproduced by construction)",
    "E02": "INDEPENDENT (never used in any derivation)",
    "E03": "INDEPENDENT (never used in any derivation)",
    "E04": "INDEPENDENT (post-refresh: no constant sources the t=-25 artifact)",
}


# ---------------------------------------------------------------------------
# Exact-rational STRUCTURE CHECK of the shipped connection: the dlog form of
# the diagonal kernels and the zero rows are *derived properties*; verify them
# in exact Fraction arithmetic at runtime before using them.
# ---------------------------------------------------------------------------
def frac_eval(terms, e, t):
    return sum(Fraction(cs) * e ** ke * t ** kt for ke, kt, cs in terms)


def structure_check(cone):
    tabQ = {}
    for key, ent in cone["A_t"].items():
        i, j = (int(v) for v in key.split(","))
        tabQ[(i, j)] = ent
    # (1) zero rows = exact t-independence
    live_rows = sorted(set(i for i, _ in tabQ))
    assert live_rows == [I_M8, I_M11, I_RB], "unexpected nonzero A_t rows"
    # (2) diagonal kernels are exact dlogs of D1, D2, D3 (3 random rational pts)
    pts = [(Fraction(3, 7), Fraction(-5, 11)), (Fraction(-2, 9), Fraction(-31, 8)),
           (Fraction(1, 13), Fraction(-1, 30))]
    for e, t in pts:
        D1v, dD1 = 200 * t - 53, Fraction(200)
        D2v, dD2 = (236 - 448 * e) * t + 53, 236 - 448 * e
        D3v = e * (200 * t - 53) ** 2 - (60000 * t * t - 31800 * t + 2809)
        dD3 = 200 * (2 * e - 3) * (200 * t - 53)
        for (i, i2), (Dv, dD) in (((I_M8, I_M8), (D1v, dD1)),
                                  ((I_M11, I_M11), (D2v, dD2)),
                                  ((I_RB, I_RB), (D3v, dD3))):
            ent = tabQ[(i, i2)]
            val = frac_eval(ent["num"], e, t) / frac_eval(ent["den"], e, t)
            assert val == dD / Dv, "A[%d,%d] != dlog D at (%s,%s)" % (i, i2, e, t)
        # (3) the m8 row is eps-free with the exact source coefficients
        for j, cexp in ((5, Fraction(-100)), (6, Fraction(-25)), (7, Fraction(-100))):
            ent = tabQ[(I_M8, j)]
            val = frac_eval(ent["num"], e, t) / frac_eval(ent["den"], e, t)
            assert val == cexp / D1v, "A[8,%d] != %s/D1" % (j, cexp)
    return len(tabQ)


# ---------------------------------------------------------------------------
# Connection eps-Laurent machinery (round 2, unchanged) — used by the live
# derivative-identity check and the optional --transport cross-check.
# ---------------------------------------------------------------------------
def build_tab(cone):
    tab = {}
    for key, e in cone["A_t"].items():
        i, j = (int(v) for v in key.split(","))
        conv = lambda terms: [(ke, kt, mp.mpf(Fraction(cs).numerator) /
                               mp.mpf(Fraction(cs).denominator)) for ke, kt, cs in terms]
        tab[(i, j)] = (conv(e["num"]), conv(e["den"]))
    return tab


def laurent_A(i, j, tab, tval, tpow):
    """eps-Laurent (AMIN..AMAX) of A_t[i][j] at (complex) t=tval."""
    if (i, j) not in tab:
        return None
    Pn_t, Pd_t = tab[(i, j)]

    def collapse(terms):
        c = {}
        for ke, kt, co in terms:
            tp = tpow.get(kt)
            if tp is None:
                tp = tval ** kt
                tpow[kt] = tp
            c[ke] = c.get(ke, mp.mpc(0)) + co * tp
        return c

    nc, dc = collapse(Pn_t), collapse(Pd_t)
    nlist = [nc.get(k, mp.mpc(0)) for k in range(max(nc) + 1)]
    dlist = [dc.get(k, mp.mpc(0)) for k in range(max(dc) + 1)]
    v0 = 0
    while v0 < len(dlist) and dlist[v0] == 0:
        v0 += 1
    d_red = dlist[v0:]
    u0 = 0
    while u0 < len(nlist) and nlist[u0] == 0:
        u0 += 1
    n_red = nlist[u0:] if u0 < len(nlist) else [mp.mpc(0)]
    if not d_red or d_red[0] == 0:
        raise ZeroDivisionError("A[%d,%d] denominator vanishes at t=%s" % (i, j, tval))
    d0 = d_red[0]
    K = AMAX - AMIN + 6
    a = [mp.mpc(0)] * (K + 1)
    for k in range(K + 1):
        acc = n_red[k] if k < len(n_red) else mp.mpc(0)
        for jj in range(1, min(k, len(d_red) - 1) + 1):
            acc -= d_red[jj] * a[k - jj]
        a[k] = acc / d0
    sh = u0 - v0
    out = [mp.mpc(0)] * NORD_A
    for k, ak in enumerate(a):
        o = k + sh
        if AMIN <= o <= AMAX:
            out[o - AMIN] = ak
    return out


def lmulA(A, B):
    out = [mp.mpc(0)] * NORD
    for i, ai in enumerate(A):
        if ai == 0:
            continue
        for j, bj in enumerate(B):
            if bj == 0:
                continue
            p = i + AMIN + j
            if 0 <= p < NORD:
                out[p] += ai * bj
    return out


def ldiv_lin(S, d0, d1):
    """S / (d0 + eps d1) on the master range — exact (D linear in eps)."""
    out, prev = [mp.mpc(0)] * NORD, mp.mpc(0)
    for k in range(NORD):
        out[k] = (S[k] - d1 * prev) / d0
        prev = out[k]
    return out


def lmul_lin(b, d0, d1):
    out = [d0 * bk for bk in b]
    for k in range(1, NORD):
        out[k] += d1 * b[k - 1]
    return out


def D1(z):
    return 200 * z - 53


def D2(z):
    return 236 * z + 53, -448 * z


def D3(z):
    return -(60000 * z * z - 31800 * z + 2809), (200 * z - 53) ** 2


_CHEB_CACHE = {}


def cheb_grid(N):
    if N not in _CHEB_CACHE:
        cos_tab = [mp.cos(mp.pi * k / N) for k in range(2 * N)]
        _CHEB_CACHE[N] = (cos_tab[:N + 1], cos_tab)
    return _CHEB_CACHE[N]


def cheb_coeffs(vals):
    """DCT-I: values at Lobatto nodes x_k=cos(pi k/N) -> Chebyshev coefficients."""
    N = len(vals) - 1
    _, cos_tab = cheb_grid(N)
    half = mp.mpf('0.5')
    coeffs = []
    for j in range(N + 1):
        s = mp.mpc(0)
        for k in range(N + 1):
            w = half if (k == 0 or k == N) else 1
            s += (vals[k] if w == 1 else vals[k] * half) * cos_tab[(j * k) % (2 * N)]
        coeffs.append(s * 2 / N)
    coeffs[0] /= 2
    coeffs[N] /= 2
    return coeffs


def cheb_antideriv(a):
    n = len(a)
    b = [mp.mpc(0)] * (n + 1)
    for j in range(1, n + 1):
        am = a[j - 1]
        ap = a[j + 1] if j + 1 < n else mp.mpc(0)
        b[j] = (am - ap) / (2 * j)
    b[1] = a[0] - (a[2] / 2 if n > 2 else 0)
    return b


def cheb_eval(coeffs, x):
    b1 = b2 = mp.mpc(0)
    for c in reversed(coeffs[1:]):
        b1, b2 = 2 * x * b1 - b2 + c, b1
    return x * b1 - b2 + coeffs[0]


class ConeWords:
    """Round-2 VoP word evaluator over the certified connection (Chebyshev
    quadrature). Retained as the optional --transport cross-check; now seeded
    by the DERIVED t=0 values (zero AMFlow constants)."""

    def __init__(self, cone_json, seeds, t0=0):
        self.tab = build_tab(cone_json)
        self.t0z = mp.mpc(t0)
        self.C = seeds  # dict i -> Laurent list at t=t0
        S8 = [(-100 * a - 25 * b - 100 * c)
              for a, b, c in zip(seeds[5], seeds[6], seeds[7])]
        self.S8 = S8
        self.b8_0 = [v / D1(self.t0z) for v in seeds[I_M8]]

    def m8(self, z):
        d1z = D1(z)
        fac = 1 - d1z / D1(self.t0z)
        return [d1z * b - (s / 200) * fac for b, s in zip(self.b8_0, self.S8)]

    def _source(self, row, z, m8z, m11z, tpow):
        acc = [mp.mpc(0)] * NORD
        for j in range(0, row):
            A = laurent_A(row, j, self.tab, z, tpow)
            if A is None:
                continue
            mj = m8z if j == I_M8 else (m11z if j == I_M11 else self.C[j])
            acc = [a + p for a, p in zip(acc, lmulA(A, mj))]
        return acc

    def transport(self, path, tail_dps, want, n0=64, n_max=4096):
        """VoP one-folds along polyline `path` (path[0]=t0). Returns
        {vertex: {8:..., 11:..., 13:...}}, diagnostics."""
        assert mp.mpc(path[0]) == self.t0z, "path must start at the seed point"
        b11 = ldiv_lin(self.C[I_M11], *D2(self.t0z))
        b13 = ldiv_lin(self.C[I_RB], *D3(self.t0z))
        out, diags = {}, []
        for seg in range(len(path) - 1):
            za, zb = mp.mpc(path[seg]), mp.mpc(path[seg + 1])
            mid, half = (za + zb) / 2, (zb - za) / 2
            N = n0
            while True:
                xs, _ = cheb_grid(N)
                zs = [mid + half * x for x in xs]
                m8s, F11s = [], []
                for z in zs:
                    tpow = {0: mp.mpc(1), 1: z}
                    m8z = self.m8(z)
                    m8s.append(m8z)
                    F11s.append(ldiv_lin(self._source(I_M11, z, m8z, None, tpow),
                                         *D2(z)))
                cF11 = [cheb_coeffs([f[k] for f in F11s]) for k in range(NORD)]
                tail11 = max(max(abs(c) for c in cs[-6:]) for cs in cF11)
                sc11 = max(max(abs(c) for c in cs) for cs in cF11) + mp.mpf('1e-999')
                aF11 = [cheb_antideriv(cs) for cs in cF11]
                base11 = [cheb_eval(aF11[k], mp.mpf(-1)) for k in range(NORD)]
                m11s = []
                for idx, z in enumerate(zs):
                    I = [b11[k] + half * (cheb_eval(aF11[k], xs[idx]) - base11[k])
                         for k in range(NORD)]
                    m11s.append(lmul_lin(I, *D2(z)))
                F13s = []
                for idx, z in enumerate(zs):
                    tpow = {0: mp.mpc(1), 1: z}
                    F13s.append(ldiv_lin(
                        self._source(I_RB, z, m8s[idx], m11s[idx], tpow), *D3(z)))
                cF13 = [cheb_coeffs([f[k] for f in F13s]) for k in range(NORD)]
                tail13 = max(max(abs(c) for c in cs[-6:]) for cs in cF13)
                sc13 = max(max(abs(c) for c in cs) for cs in cF13) + mp.mpf('1e-999')
                tol = mp.mpf(10) ** (-tail_dps)
                if (tail11 / sc11 < tol and tail13 / sc13 < tol) or N >= n_max:
                    break
                N *= 2
            diags.append((seg, N, float(tail11 / sc11), float(tail13 / sc13)))
            aF13 = [cheb_antideriv(cs) for cs in cF13]
            one = mp.mpf(1)
            for k in range(NORD):
                b11[k] += half * (cheb_eval(aF11[k], one) - base11[k])
                b13[k] += half * (cheb_eval(aF13[k], one) - cheb_eval(aF13[k], -one))
            vi = seg + 1
            if vi in want:
                out[vi] = {I_M8: self.m8(zb),
                           I_M11: lmul_lin(b11, *D2(zb)),
                           I_RB: lmul_lin(b13, *D3(zb))}
        return out, diags


# ---------------------------------------------------------------------------
# eps-Laurent series tools + Ser-valued Gamma/pFq engines (ported from the
# row-20 rowscript tools/rowscripts/eval_row20.py, derivation records folded).
# ---------------------------------------------------------------------------
def make_series_tools(nmin=-4, nmax=8):
    class Ser:
        __slots__ = ("c",)
        def __init__(self, c=None):
            self.c = dict(c) if c else {}
        @staticmethod
        def const(v): return Ser({0: mp.mpc(v)})
        @staticmethod
        def eps():    return Ser({1: mp.mpc(1)})
        def _t(self): return {k: v for k, v in self.c.items() if nmin <= k <= nmax and v != 0}
        def __add__(s, o):
            o = o if isinstance(o, Ser) else Ser.const(o)
            c = dict(s.c)
            for k, v in o.c.items(): c[k] = c.get(k, mp.mpc(0)) + v
            return Ser(c)
        __radd__ = __add__
        def __neg__(s): return Ser({k: -v for k, v in s.c.items()})
        def __sub__(s, o): return s + (-(o if isinstance(o, Ser) else Ser.const(o)))
        def __rsub__(s, o): return (o if isinstance(o, Ser) else Ser.const(o)) + (-s)
        def __mul__(s, o):
            o = o if isinstance(o, Ser) else Ser.const(o)
            c = {}
            for k1, v1 in s._t().items():
                for k2, v2 in o._t().items():
                    k = k1 + k2
                    if k <= nmax: c[k] = c.get(k, mp.mpc(0)) + v1 * v2
            return Ser(c)
        __rmul__ = __mul__
        def inv(s):
            tt = s._t(); v0 = min(tt); a0 = tt[v0]
            x = Ser({k - v0: v / a0 for k, v in tt.items() if k > v0})
            out = Ser.const(1); term = Ser.const(1)
            for _ in range(nmax - nmin + 2):
                term = term * (-1) * x; out = out + term
            return Ser({k - v0: v for k, v in out._t().items()}) * (1 / a0) if v0 == 0 else \
                   Ser({k - v0: v / a0 for k, v in out._t().items()})
        def __truediv__(s, o):
            o = o if isinstance(o, Ser) else Ser.const(o)
            return s * o.inv()
        def __rtruediv__(s, o): return (o if isinstance(o, Ser) else Ser.const(o)) * s.inv()
        def get(s, k): return s.c.get(k, mp.mpc(0))

    def ser_exp(s):
        tt = s._t()
        assert (not tt) or min(tt) >= 1, "ser_exp needs valuation >= 1"
        out = Ser.const(1); term = Ser.const(1)
        for n in range(1, nmax + 3):
            term = term * s / n
            out = out + term
        return out

    def ser_gamma_eps(shift=0):
        """Gamma(eps+shift): Gamma(eps) = exp(-g*eps + sum_{k>=2} zeta(k)(-eps)^k/k)/eps."""
        E = Ser.eps()
        lg = (-mp.euler) * E
        for k in range(2, nmax + 6):
            lg = lg + Ser({k: mp.zeta(k) * (-1) ** k / k})
        G = ser_exp(lg) * Ser({-1: mp.mpc(1)})
        if shift > 0:
            for j in range(shift):
                G = G * (E + j)
        elif shift < 0:
            for j in range(1, -shift + 1):
                G = G / (E - j)
        return G

    def hyper_ser(alist, blist, z):
        """pFq(a0+a1*eps,...;b0+b1*eps,...; z), rational z, |z|<1 -> Ser.
        Params as (Fraction-string, eps-slope int). nterms carries a +40
        margin for the n^k enhancement of higher eps orders."""
        E = Ser.eps()
        fz = Fraction(z)
        zz = mp.mpf(fz.numerator) / mp.mpf(fz.denominator)
        assert abs(zz) < 1, "hyper_ser needs |z|<1"
        nterms = int(mp.mp.dps / float(-mp.log10(abs(zz)))) + 40
        term = Ser.const(1); out = Ser.const(1)
        for n in range(nterms):
            num = Ser.const(1); den = Ser.const(1)
            for (a0, a1) in alist:
                fa = Fraction(a0)
                num = num * (mp.mpf(fa.numerator) / mp.mpf(fa.denominator) + a1 * E + n)
            for (b0, b1) in blist:
                fb = Fraction(b0)
                den = den * (mp.mpf(fb.numerator) / mp.mpf(fb.denominator) + b1 * E + n)
            term = term * num / den * zz / (n + 1)
            out = out + term
        return out

    return Ser, ser_exp, ser_gamma_eps, hyper_ser


# ---------------------------------------------------------------------------
# VENDORED Gamma-ladder CORE engine for the K6/K7/K9/K10 closed forms
# (closed-form closure, 2026-07-05). Source of truth + full derivation +
# recorded verification (port controls: A0 degenerations bit-identical to the
# gated cusp engine; production legs dps160/dps200 gated 161.3-184.4 d
# against two independent references; positive controls K1/K5 through the
# same pipeline): <archive>/row20_closedforms/{RESULT.md,
# core2.py,production.log}. Functions below are AST-identical to core2.py
# (docstrings trimmed), with only the mpmath-context spelling
# (mp.dps -> mp.mp.dps) adapted to this file's `import mpmath as mp`.
# ---------------------------------------------------------------------------
S_FRAC = Fraction(-1, 4)
M_FRAC = Fraction(7, 25)


def _nm(prec):
    from math import ceil, log10
    return int(ceil((prec + 15) / (-log10(0.0708)))) + 10


def core2(ep, am, ad, b4, b5, inv, wu=0, w1u=0, wxi=0, w1xi=0, wx=0, w1x=0,
          dps=None, sfrac=S_FRAC, mfrac=M_FRAC):
    """CORE with general corner invariants (see core2.py header for the
    derivation; terminating Thomae 3F2, all series geometric <= M/4, |s|/4).
    Returns CORE value at (possibly complex) ep."""
    prec = dps or mp.mp.dps
    NM = _nm(prec)
    tol = mp.mpf(10) ** (-(prec + 10))
    lam = am + ad - 2 + ep
    r0 = am + ad + b4 + b5 - 4
    kt = wx + w1x - w1u
    if kt > 0:
        raise ValueError("kt>0: Thomae termination fails at small n3 -- "
                         "rewrite the numerator weights (see K7 assembly)")
    sgn = (-1) ** (am + ad + b4 + b5)
    both = (b4 > 0 and b5 > 0)
    Sv = mp.mpf(sfrac.numerator) / sfrac.denominator
    Mv = mp.mpf(mfrac.numerator) / mfrac.denominator
    F = [mp.mpf(1)]
    for k in range(3 * NM + 20):
        F.append(F[-1] * (k + 1))

    def garr(x0, n):
        a = [mp.gamma(x0)]
        for k in range(n):
            a.append(a[-1] * (x0 + k))
        return a
    GL = garr(lam, NM + 8)                 # Gamma(lam+k)
    GR = garr(2 * ep, r0 + 3 * NM + 16)    # Gamma(2eps+k)
    GC = garr(ep, am + b4 + b5 + 2 * NM + 16)  # Gamma(eps+k)
    GD = garr(-ep, am + 2 * NM + 16)       # Gamma(k-eps)
    GDD = GD[2 - am + w1x]
    gden = mp.gamma(am) * mp.gamma(ad) * (mp.gamma(b4) if b4 else 1) \
        * (mp.gamma(b5) if b5 else 1)
    if inv == 'V2':
        Sc = [mp.mpf(1)]
        for k in range(NM + 2):
            Sc.append(Sc[-1] * Sv)                      # s^m
        n2slot = False   # scale sits in the n1 (V^2) slot
    elif inv in ('V2mu', 'Vq12mu'):
        # W[m] = Int_0^1 (s+mu(M-s))^m dmu = (M^{m+1}-s^{m+1})/((m+1)(M-s))
        Sc = []
        Mp, Sp = Mv, Sv
        for m in range(NM + 2):
            Sc.append((Mp - Sp) / ((m + 1) * (Mv - Sv)))
            Mp *= Mv
            Sp *= Sv
        n2slot = (inv == 'Vq12mu')
    elif inv == 'Vq12':
        Sc = [mp.mpf(1)]
        for k in range(NM + 2):
            Sc.append(Sc[-1] * Sv)   # fixed (V-q12)^2 value passed via sfrac
        n2slot = True
    elif inv == 'A0q1':
        Sc = [mp.mpf(1)] + [mp.mpf(0)] * (NM + 1)
        n2slot = False
    else:
        raise ValueError(inv)
    if inv == 'V2mu' and b5 != 0:
        raise ValueError("V2mu requires b5=0")
    Mn = [mp.mpf(1)]
    for k in range(NM + 2):
        Mn.append(Mn[-1] * Mv)

    def B_int(p, q):
        return F[p - 1] * F[q - 1] / F[p + q - 1]

    def bxi(n1, n2, n3):
        return B_int(b5 + n2 + n3 + wxi, b4 + n1 + n3 + w1xi) if both \
            else mp.mpf(1)

    total = mp.mpc(0) if isinstance(ep, mp.mpc) else mp.mpf(0)
    m_broke = False
    for m in range(NM + 1):
        if Sc[m] == 0 and m > 0:
            m_broke = True
            break
        s_int = am + m + wu + wx
        alpha_g = GL[m + wu]
        alpha_v = lam + m + wu
        rowm = mp.mpf(0)
        n3_broke = False
        for n3 in range(NM + 1):
            if not both:
                if n3 > 0:
                    n3_broke = True
                    break
            N = m + n3
            sm = (Sc[m] / F[m]) * (bxi(0, m, n3) if n2slot else bxi(m, 0, n3))
            kmax = n3 - kt
            b1 = 2 * ep + s_int + r0 + N
            b2 = -ep + s_int + 2 - am + w1x
            t = mp.mpf(1)
            acc = mp.mpf(1)
            for k in range(kmax):
                t *= (k - kmax) * (alpha_v + k) * (s_int + k) \
                    / ((b1 + k) * (b2 + k) * (k + 1))
                acc += t
            term = (sgn * GR[r0 + N] * Mn[n3] / F[n3] / gden * sm *
                    GC[am + b4 + b5 - 2 + N + wx] * GDD * alpha_g *
                    F[s_int - 1] / (GR[s_int + r0 + N] * GD[s_int + 2 - am + w1x])
                    * acc)
            rowm += term
            if n3 > 3 and abs(term) < tol * max(abs(total + rowm), mp.mpf(1)):
                n3_broke = True
                break
        if both and not n3_broke:
            raise RuntimeError("n3 cap hit without tolerance break (NM=%d)" % NM)
        total += rowm
        if m > 3 and abs(rowm) < tol * max(abs(total), mp.mpf(1)):
            m_broke = True
            break
    if not m_broke and inv != 'A0q1':
        raise RuntimeError("m cap hit without tolerance break (NM=%d)" % NM)
    return total


def k67_pass(ep, dps=None, sfrac=S_FRAC, mfrac=M_FRAC):
    """Merged lattice pass for the three (1,1,1,1;V2=s) COREs of K6/K7:
    returns (C0, CA, CB). Identical math to three core2 calls (asserted in
    the recorded pregate), ~40%% cheaper."""
    am = ad = b4 = b5 = 1
    prec = dps or mp.mp.dps
    NM = _nm(prec)
    tol = mp.mpf(10) ** (-(prec + 10))
    lam = ep          # am+ad-2+ep
    r0 = 0
    Sv = mp.mpf(sfrac.numerator) / sfrac.denominator
    Mv = mp.mpf(mfrac.numerator) / mfrac.denominator
    F = [mp.mpf(1)]
    for k in range(3 * NM + 20):
        F.append(F[-1] * (k + 1))

    def garr(x0, n):
        a = [mp.gamma(x0)]
        for k in range(n):
            a.append(a[-1] * (x0 + k))
        return a
    GL = garr(lam, NM + 8)
    GR = garr(2 * ep, 3 * NM + 16)
    GC = garr(ep, 2 * NM + 18)
    GD = garr(-ep, 2 * NM + 18)
    Sc = [mp.mpf(1)]
    for k in range(NM + 2):
        Sc.append(Sc[-1] * Sv)
    Mn = [mp.mpf(1)]
    for k in range(NM + 2):
        Mn.append(Mn[-1] * Mv)

    def B_int(p, q):
        return F[p - 1] * F[q - 1] / F[p + q - 1]
    zero = mp.mpc(0) if isinstance(ep, mp.mpc) else mp.mpf(0)
    T0, TA, TB = zero, zero, zero
    m_broke = False
    for m in range(NM + 1):
        s_int = 1 + m
        alpha_g = GL[m]
        alpha_v = lam + m
        r0m, rAm, rBm = zero, zero, zero
        n3_broke = False
        for n3 in range(NM + 1):
            N = m + n3
            b1 = 2 * ep + s_int + N
            b2 = -ep + s_int + 1          # K6 (w1x=0)
            b2s = b2 + 1                  # CA/CB (w1x=1)
            t = mp.mpf(1)
            acc0 = mp.mpf(1)
            ts = mp.mpf(1)
            accs = mp.mpf(1)
            for k in range(n3):
                num = (k - n3) * (alpha_v + k) * (s_int + k)
                den = (b1 + k) * (k + 1)
                t *= num / (den * (b2 + k))
                acc0 += t
                ts *= num / (den * (b2s + k))
                accs += ts
            base = GR[N] * Mn[n3] / F[n3] * GC[1 + N] * alpha_g * F[s_int - 1] \
                / GR[s_int + N] * (Sc[m] / F[m])
            bxi0 = B_int(1 + n3, 1 + m + n3)      # wxi=0
            bxiB = B_int(2 + n3, 1 + m + n3)      # wxi=1
            term0 = base * GD[1] / GD[s_int + 1] * bxi0 * acc0
            r0m += term0
            comA = base * GD[2] / GD[s_int + 2] * accs
            rAm += comA * bxi0
            rBm += comA * bxiB
            if n3 > 3 and abs(term0) < tol * max(abs(T0 + r0m), mp.mpf(1)):
                n3_broke = True
                break
        if not n3_broke:
            raise RuntimeError("k67_pass n3 cap hit (NM=%d)" % NM)
        T0 += r0m
        TA += rAm
        TB += rBm
        if m > 3 and abs(r0m) < tol * max(abs(T0), mp.mpf(1)):
            m_broke = True
            break
    if not m_broke:
        raise RuntimeError("k67_pass m cap hit (NM=%d)" % NM)
    return T0, TA, TB


def Bmv(ep, p2):
    z = p2 / 4
    return mp.gamma(ep) * (1 - z) ** (-ep) * \
        mp.hyp2f1(ep, mp.mpf(1) / 2, mp.mpf(3) / 2, z / (z - 1))


def m5f(ep, mfrac=M_FRAC):
    Mv = mp.mpf(mfrac.numerator) / mfrac.denominator
    return -mp.gamma(ep - 1) * Bmv(ep, Mv)


def K67f(ep, dps=None, sfrac=S_FRAC, mfrac=M_FRAC):
    """(K6, K7) from one merged lattice pass + m5 base value."""
    Sv = mp.mpf(sfrac.numerator) / sfrac.denominator
    Mv = mp.mpf(mfrac.numerator) / mfrac.denominator
    C0, CA, CB = k67_pass(ep, dps=dps, sfrac=sfrac, mfrac=mfrac)
    k6 = C0
    k7 = m5f(ep, mfrac) + Sv * k6 - 2 * Sv * CA + (Mv + Sv) * CB
    return k6, k7


def K9f(ep, dps=None, sfrac=S_FRAC, mfrac=M_FRAC):
    return core2(ep, 1, 2, 1, 0, 'V2mu', dps=dps, sfrac=sfrac, mfrac=mfrac)


def K10f(ep, dps=None, sfrac=S_FRAC, mfrac=M_FRAC):
    return core2(ep, 1, 2, 1, 1, 'Vq12mu', dps=dps, sfrac=sfrac, mfrac=mfrac)


# ---------------------------------------------------------------------------
# RUNTIME Laurent extraction of the live K6/K7/K9/K10 closed forms + the
# fail-closed compare-gate against the cached endpoint strings.
# ---------------------------------------------------------------------------
class K6K7K9K10GateError(RuntimeError):
    """Named fail-closed error: live Gamma-ladder closed form vs cached
    endpoint-string compare-gate (or a DFT null certificate) failed. The
    cached strings are a COMPARE-CACHE — never silently trusted; on the
    DEFAULT path they are served as values ONLY after this gate passes."""


# Per-constant certified floors for K6/K7/K9/K10 agreement claims
# (2026-07-08; the row21-k3 clamp pattern). Components — all printed by
# <archive>/row20_closedforms/production.log (RESULT.md
# gate table + honest-certification note): (a) the stored strings' own
# certification = 152.3 d (dps-190 endpoint mutual two-precision vs its
# independent dps-165 leg, uniform across the endpoint); (b) each closed
# form's OWN legA-legB two-precision mutual cert (K6 159.9 / K7 160.4 /
# K9 164.5 / K10 164.5 d). Reported AND gated agreement digits clamp at
# min(a, b) per constant — never above.
CERT_FLOOR_K6K7K9K10 = {"K6": min(152.3, 159.9), "K7": min(152.3, 160.4),
                        "K9": min(152.3, 164.5), "K10": min(152.3, 164.5)}


def _k6k7k9k10_point(args):
    """One Cauchy-circle point (worker-safe; strings cross the pool)."""
    k, KPTS, prec, wdps = args
    with mp.workdps(wdps):
        r = mp.mpf(1) / 64
        th = 2 * mp.pi * k / KPTS
        ep = r * mp.mpc(mp.cos(th), mp.sin(th))
        k6, k7 = K67f(ep, dps=prec)
        vals = {"K6": k6, "K7": k7,
                "K9": K9f(ep, dps=prec), "K10": K10f(ep, dps=prec)}
        return k, {nm: [mp.nstr(mp.mpc(v).real, wdps, strip_zeros=False),
                        mp.nstr(mp.mpc(v).imag, wdps, strip_zeros=False)]
                   for nm, v in vals.items()}


def build_live_k6k7k9k10(dps):
    """RUNTIME evaluation of the four 2026-07-05 closed forms as
    eps-Laurent coefficients at the requested dps.

    Recipe = the recorded production one (row20_closedforms/laurent_run.py:
    K=128 points on |eps|=1/64 at dps 160), scaled: K = 4*((dps+35)//6+1)
    (alias suppression 32^-K <= 1e-(dps+35)), inner series tolerance
    1e-(dps+22), workdps dps+40, upper-half circle + conjugate symmetry.
    Points parallelized over ZG_NP_K6 fork workers (default min(8, cpu));
    assembly is deterministic (ordered by point index).

    Returns {"K6"|"K7"|"K9"|"K10": {order: mpc, -3..5}} after fail-closed
    null certificates: c_{-3} (all four) and K10 c_{-2},c_{-1} (endpoint-pruned
    true zeros) must be < 1e-(dps-10) relative to the constant's scale."""
    prec = dps + 12
    wdps = dps + 40
    KPTS = 4 * ((dps + 35) // 6 + 1)
    half = KPTS // 2
    names = ("K6", "K7", "K9", "K10")
    tasks = [(k, KPTS, prec, wdps) for k in range(half + 1)]
    try:
        npw = max(1, int(os.environ.get(
            "ZG_NP_K6", str(min(8, os.cpu_count() or 1)))))
    except ValueError:
        npw = 1
    recs = None
    if npw > 1 and len(tasks) > 2:
        try:
            import multiprocessing
            with multiprocessing.get_context("fork").Pool(npw) as pool:
                recs = pool.map(_k6k7k9k10_point, tasks)
        except (ImportError, OSError, ValueError):
            recs = None
    if recs is None:
        recs = [_k6k7k9k10_point(t) for t in tasks]
    out = {}
    with mp.workdps(wdps):
        r = mp.mpf(1) / 64
        fv = {nm: [None] * KPTS for nm in names}
        for k, sv in sorted(recs):
            for nm in names:
                fv[nm][k] = mp.mpc(mp.mpf(sv[nm][0]), mp.mpf(sv[nm][1]))
        for k in range(half + 1, KPTS):
            for nm in names:
                fv[nm][k] = mp.conj(fv[nm][KPTS - k])
        for nm in names:
            out[nm] = {}
            for j in range(-3, 6):
                acc = mp.mpc(0)
                for k in range(KPTS):
                    th = -2 * mp.pi * j * k / KPTS
                    acc += fv[nm][k] * mp.mpc(mp.cos(th), mp.sin(th))
                out[nm][j] = acc / (KPTS * r ** j)
        for nm in names:
            scale = max(abs(v) for v in out[nm].values())
            nulls = [(-3, out[nm][-3])]
            if nm == "K10":
                nulls += [(-2, out[nm][-2]), (-1, out[nm][-1])]
            for j, v in nulls:
                if not (abs(v) / scale < mp.mpf(10) ** (-(dps - 10))):
                    raise K6K7K9K10GateError(
                        "[k6k7k9k10-null] %s c_{%d} = %.1e rel is NOT a "
                        "numerical zero at dps %d (need < 1e-%d rel): the "
                        "live DFT contradicts the recorded pole structure. "
                        "Fail-closed, no evaluation."
                        % (nm, j, float(abs(v) / scale), dps, dps - 10))
    return out


def _sig_digits(s_):
    """Significant decimal digits of a stored string (leading zeros and
    sign/point/exponent stripped)."""
    m = s_.strip().lstrip("+-").split("e")[0].split("E")[0]
    m = m.replace(".", "").lstrip("0")
    return sum(c.isdigit() for c in m)


def producer_block(script_path):
    """PRODUCER block for the --bank json (2026-09-06): the script file name, its sha256,
    a `date -u` stamp (never typed)."""
    import hashlib
    import subprocess
    return {"script": os.path.basename(script_path),
            "sha256": hashlib.sha256(open(script_path, "rb").read()).hexdigest(),
            "stamp": subprocess.run(["date", "-u", "+%FT%TZ"], capture_output=True,
                                    text=True).stdout.strip()}


# ---------------------------------------------------------------------------
# CONSTANT PROVIDERS — every boundary constant derived, zero AMFlow upstream.
#   K0..K5:  LIVE MB/Barnes closed forms (Gamma^2 / 3F2 / 2F1 eps-Laurent),
#            provenance <archive>/solve_row20/corner_forms.json (2026-07-03
#            corner-form derivation).
#   K6,K7,K9,K10: LIVE Gamma-ladder/terminating-3F2 closed forms
#            (2026-07-05 derivation, vendored core2 engine above), runtime
#            Cauchy/DFT at the requested dps, compare-GATED per order
#            (Re AND Im, scale-rel, strictly > min(dps, string sig digits)-5)
#            against the cached endpoint strings, which DEMOTE to a
#            compare-cache.
#   K12 + m8/m11/g32 endpoint values at t=-1/3: the fully analytic
#            s-transport endpoint strings (zgamma-derived.json
#            ["endpoint_constants"], provenance inside) — the elliptic
#            residue.
#   T1,T8,c13: solved exactly AT RUNTIME from the endpoint (2x2 Q(eps) solve
#            + c13 = (Rb_end - B0)/D2q); Z88 eliminated.
# ---------------------------------------------------------------------------
def build_constants(Ser, ser_exp, ser_gamma_eps, hyper_ser, derived, dps,
                    quiet=False, deep=True, bank=None):
    """dict name -> Ser for K0..K10, K12 (+ _M8end/_M11end/_Rbend).

    deep=True (DEFAULT since 2026-09-06): full runtime closed-form evaluation
    of K6/K7/K9/K10 at the requested dps; the values are the live closed
    forms and the stored dps-190 strings are the compare gate.
    deep=False (--k-strings, the 2026-07-08 path): K6/K7/K9/K10 values SERVED
    from the stored strings after the cheap min(dps,60) closed-form gate.
    bank: path of a json receiving the live Laurent towers BEFORE the gate
    consults any stored string (None = no bank)."""
    E = Ser.eps()
    s = Fraction(-1, 4); M = Fraction(7, 25)
    G_em1 = ser_gamma_eps(-1)     # Gamma(eps-1)
    G_e = ser_gamma_eps(0)        # Gamma(eps)
    K = {}
    # ---- LIVE closed forms (m0..m5; convention: d^dk/(i pi^{d/2}), no exp(eps*gammaE)) ----
    K["K0"] = G_em1 * G_em1                                   # m0 = Gamma(eps-1)^2

    def SR(p2):                                               # sunrise(0,1,1; p^2)
        F = hyper_ser([("1", 0), ("0", 1), ("-1", 2)],
                      [("2", -1), ("1/2", 1)], Fraction(p2, 4))
        return G_e * G_e / ((1 - 2 * E) * (1 - E)) * F

    K["K1"] = SR(s)                                           # m1
    K["K3"] = SR(M)                                           # m3
    F2 = hyper_ser([("1", 0), ("0", 1), ("-1", 2)],
                   [("3", -1), ("1/2", 1)], Fraction(s, 4))
    sv = mp.mpf(-1) / 4
    K["K2"] = K["K0"] + sv * K["K1"] - 2 * sv * G_e * G_e / ((1 - 2 * E) * (2 - E)) * F2  # m2
    zM = Fraction(M, 4)                                       # 7/100
    A4 = G_e * G_e * hyper_ser([("1", 0), ("0", 1), ("0", 2)],
                               [("3", -1), ("1/2", 1)], zM) / 2
    B4 = (-2) * (1 - E) * G_e * G_e / (1 - 2 * E) * \
        hyper_ser([("1", 0), ("0", 1), ("-1", 2)], [("3", -1), ("1/2", 1)], zM)
    Mv = mp.mpf(7) / 25
    PK = Mv / ((1 - E) * (2 - E)) * (A4 + B4)
    K["K4"] = -2 * PK - Mv * K["K3"]                          # m4 = -2*PK - M*SR(M)
    lgM = mp.log(1 - mp.mpf(7) / 100)
    pref = ser_exp(E * (-lgM))                                # (1-z_M)^(-eps)
    F5 = hyper_ser([("0", 1), ("1/2", 0)], [("3/2", 0)], zM / (zM - 1))
    K["K5"] = -G_em1 * G_e * pref * F5                        # m5 = T x B(1,1;M)
    # ---- Gamma-ladder closed forms K6/K7/K9/K10 (runtime Cauchy/DFT) ----
    # DEFAULT (deep=False): the cached endpoint strings are the
    # VALUE source, served only after a CHEAP compare gate — the live closed
    # forms evaluated at gdps = min(dps, 60) and checked against every
    # stored order (Re AND Im, fail-closed named raise). DEEP (opt-in
    # --deep-closed-forms): the closed forms run at the full requested dps
    # and ARE the value source; the strings gate them. Both directions clamp
    # reported/gated agreement digits at CERT_FLOOR_K6K7K9K10 (per-constant,
    # never above). Downstream Laurent order sets are kept IDENTICAL to the
    # string era (K10 poles stay pruned). Under --boundary-recompute the
    # "cache" is the fresh chain endpoint, so this gate flips from
    # source-check to CROSS-CHECK (two independent live computations),
    # exactly as specified in row20_closedforms/RESULT.md.
    LIVE4 = ("K6", "K7", "K9", "K10")
    gdps = dps if deep else min(dps, 60)
    live = build_live_k6k7k9k10(gdps)
    if bank:
        # 2026-09-06: the four live Laurent towers are written
        # to disk BEFORE the compare loop below consults any stored string.
        wd = gdps + 40
        with mp.workdps(wd):
            bj = {"what": "eps-Laurent coefficients of the K6,K7,K9,K10 closed forms "
                          "(vendored core2 closed forms; runtime "
                          "Cauchy/DFT), written BEFORE the compare gate consults any "
                          "stored endpoint string",
                  "point": "s=-1/4, M=7/25, m_t^2=1; AMFlow normalization, no exp(eps*gammaE)",
                  "dps": gdps, "value_path": "closed forms" if deep else "strings (--k-strings)",
                  "recipe": {"KPTS": 4 * ((gdps + 35) // 6 + 1), "prec": gdps + 12,
                             "workdps": wd, "circle": "|eps|=1/64"},
                  "orders": list(range(-3, 6)),
                  "coeffs": {nm: {str(o): [mp.nstr(mp.mpc(v).real, wd, strip_zeros=False),
                                           mp.nstr(mp.mpc(v).imag, wd, strip_zeros=False)]
                                  for o, v in live[nm].items()} for nm in LIVE4},
                  "producer": producer_block(__file__)}
        json.dump(bj, open(bank, "w"), indent=1)
        if not quiet:
            print("  [k6k7k9k10-bank] live closed-form Laurent towers WRITTEN -> %s "
                  "(stamp %s; before the compare gate)" % (bank, bj["producer"]["stamp"]))
    gate_worst, need_max, npairs = mp.inf, 0.0, 0
    # ---- analytic s-transport endpoint constants (no AMFlow upstream) ----
    for nm, ser in derived["endpoint_constants"]["series"].items():
        if nm not in LIVE4:
            K[nm] = Ser({int(o): mp.mpc(mp.mpf(v[0]), mp.mpf(v[1]))
                         for o, v in ser.items()})
            continue
        if deep:
            K[nm] = Ser({int(o): live[nm][int(o)] for o in ser})
        else:
            K[nm] = Ser({int(o): mp.mpc(mp.mpf(v[0]), mp.mpf(v[1]))
                         for o, v in ser.items()})
        floor = CERT_FLOOR_K6K7K9K10[nm]
        scale = max(abs(mp.mpf(v[0])) for v in ser.values())
        for o, v in ser.items():
            lv = mp.mpc(live[nm][int(o)])
            slen = _sig_digits(v[0])
            # gate bar: min(gate-dps, string sig digits)-5, CLAMPED at the
            # constant's own certified floor (never demand uncertified digits)
            need = min(float((min(gdps, slen) if slen > 20 else gdps) - 5),
                       floor)
            need_max = max(need_max, need)
            for part, sv_, pv in (("Re", v[0], lv.real), ("Im", v[1], lv.imag)):
                dd = abs(pv - mp.mpf(sv_))
                d = float(mp.mp.dps) if dd == 0 else float(-mp.log10(dd / scale))
                gate_worst = min(gate_worst, min(d, floor))  # reported: clamped
                npairs += 1
                if not (d > need):
                    raise K6K7K9K10GateError(
                        "[k6k7k9k10-gate] %s eps^%s %s: live closed form vs "
                        "cached endpoint string agree %.1f d, NOT strictly > "
                        "need %.1f d (= min(gate dps, string sig digits)-5 "
                        "clamped at the constant's certified floor %.1f d; "
                        "gate dps %d, string %d sig digits, scale-rel). The "
                        "runtime Gamma-ladder value and the cached string "
                        "disagree beyond this run's resolution -- "
                        "investigate the provenance of BOTH before trusting "
                        "either. Fail-closed: no evaluation performed."
                        % (nm, o, part, min(d, floor), need, floor, gdps,
                           slen))
    if not quiet:
        if deep:
            print("  [k6k7k9k10-gate] DEFAULT (closed forms = the value path): LIVE "
                  "Gamma-ladder closed forms (runtime Cauchy/DFT at dps %d) "
                  "SERVED as values, gated vs the stored dps-190 endpoint strings "
                  "(the compare gate, %d Re+Im pairs, scale-rel): worst %.1f d "
                  "(need strictly > %.1f; digits clamped at per-constant "
                  "certified floors) [PASS]"
                  % (gdps, npairs, gate_worst, need_max))
        else:
            print("  [k6k7k9k10-gate] LEGACY (--k-strings): values SERVED from the "
                  "stored reference strings (~184 d stored / 152.3 d certified); "
                  "CHEAP compare gate = live Gamma-ladder closed forms "
                  "(runtime Cauchy/DFT) at dps %d = min(dps, 60) vs the "
                  "strings (%d Re+Im pairs, scale-rel): worst %.1f d (need "
                  "strictly > %.1f; digits clamped at per-constant "
                  "certified floors) [PASS]. The default run serves the closed "
                  "forms at the full dps (see module docstring)."
                  % (gdps, npairs, gate_worst, need_max))
    return K


def solve_endpoint_tail(Ser, K, slope_tables):
    """Close the tail-constant set from the transport endpoint (t=-1/3),
    exactly: T1, T8 from the m8/m11 endpoint equations (2x2 Q(eps)-linear
    solve over the exact recorded slope tables); c13 = (Rb_end - B0)/D2q.
    Z88 is ELIMINATED (its
    only consumer was the c13 lincombo). Mutates and returns K."""
    E = Ser.eps()
    t0 = mp.mpf(-1) / 3

    def epspoly(coeffs):
        return Ser({i: mp.mpc(c) for i, c in enumerate(coeffs) if c != 0})

    def split(tab):
        """table -> (K-part Ser, dict of T-coefficient Sers)"""
        deninv = epspoly(tab["den"]).inv()
        base = Ser.const(0); coef = {}
        for name, cl in tab["num"].items():
            c = epspoly(cl) * deninv
            if name in ("T1", "T8", "Z88"):
                coef[name] = c
            else:
                base = base + c * K[name]
        return base, coef

    f8 = 200 * t0 - 53
    L1v = E * (448 * t0) - 236 * t0 - 53
    b8, c8T = split(slope_tables["c8"])
    b11, c11T = split(slope_tables["c11"])
    bC, C11T = split(slope_tables["C11"])
    # eq A:  M8end  = (b8 + a1*T1 + a8*T8)*f8 + K5/2 + K6/8 + K7/2
    RA = K["_M8end"] - b8 * f8 - K["K5"] / 2 - K["K6"] / 8 - K["K7"] / 2
    a1, a8 = c8T["T1"] * f8, c8T["T8"] * f8
    # eq B:  M11end = (b11 + ...)*L1v + (bC + ...)
    RB = K["_M11end"] - b11 * L1v - bC
    g1 = c11T["T1"] * L1v + C11T["T1"]
    g8 = c11T["T8"] * L1v + C11T["T8"]
    det = a1 * g8 - a8 * g1
    K["T1"] = (RA * g8 - RB * a8) / det
    K["T8"] = (a1 * RB - g1 * RA) / det
    # c13 = (Rbend - B0)/D2q(t0);  B0 table = {K5,K10,K12,T1}
    bB, B0T = split(slope_tables["B0"])
    B0 = bB + B0T["T1"] * K["T1"]
    D2qv = E * (200 * t0 - 53) ** 2 - (60000 * t0 ** 2 - 31800 * t0 + 2809)
    K["c13"] = (K["_Rbend"] - B0) / D2qv
    return K


def assemble_tail(Ser, K, slope_tables):
    """Vendored exact Q(eps) slope tables -> tail coefficients + closed-form
    callables m8(t), m11(t), g32(t), g31() -> Ser (polynomials in t)."""
    E = Ser.eps()

    def epspoly(coeffs):
        return Ser({i: mp.mpc(c) for i, c in enumerate(coeffs) if c != 0})

    def lincombo(tab):
        num = Ser.const(0)
        for name, cl in tab["num"].items():
            num = num + epspoly(cl) * K[name]
        return num / epspoly(tab["den"])

    C11 = lincombo(slope_tables["C11"])
    B0 = lincombo(slope_tables["B0"])
    c8 = lincombo(slope_tables["c8"])
    c11 = lincombo(slope_tables["c11"])
    c13 = K["c13"]

    def L1(t):  return E * (448 * t) - 236 * t - 53
    def D2q(t): return E * (200 * t - 53) ** 2 - (60000 * t ** 2 - 31800 * t + 2809)

    def g31():  return K["K12"]
    def g32(t): return c13 * D2q(t) + B0
    def m8(t):  return c8 * (200 * t - 53) + K["K5"] / 2 + K["K6"] / 8 + K["K7"] / 2
    def m11(t): return c11 * L1(t) + C11
    coeffs = {"c8": c8, "c11": c11, "c13": c13, "B0": B0, "C11": C11}
    return {"g31": g31, "g32": g32, "m8": m8, "m11": m11}, coeffs


def ser_to_list(ser):
    return [ser.get(o) for o in range(OMIN, OMAX + 1)]


def masters_at(K, forms, tval):
    """dict cone-index -> Laurent list at (complex) t=tval."""
    M = {}
    for i in T_INDEP:
        M[i] = ser_to_list(K["K%d" % i])
    M[I_M8] = ser_to_list(forms["m8"](tval))
    M[I_M11] = ser_to_list(forms["m11"](tval))
    M[I_RB] = ser_to_list(forms["g32"](tval))
    return M


def derivative_identity_check(Ser, tab, K, forms, coeffs, tvals):
    """LIVE check that the closed polynomial forms solve the certified cone
    connection: dM/dt - A_t(eps,t) M = 0 on the three nonzero rows, measured
    as -log10 of the residual (normalized per row) at each t. This ties the
    round-3 closed forms to the SAME certified object the round-2 quadrature
    transport integrated — including at a complex point beside the round-2
    apparent singularity t=-53/236 (the closed forms are entire there)."""
    E = Ser.eps()
    worst = mp.inf
    for tval in tvals:
        tz = mp.mpc(tval)
        tpow = {0: mp.mpc(1), 1: tz}
        M = masters_at(K, forms, tz)
        dM = {I_M8: ser_to_list(200 * coeffs["c8"]),
              I_M11: ser_to_list(coeffs["c11"] * (E * 448 - 236)),
              I_RB: ser_to_list(coeffs["c13"] *
                                (E * (400 * (200 * tz - 53)) - (120000 * tz - 31800)))}
        for row in (I_M8, I_M11, I_RB):
            acc = [mp.mpc(0)] * NORD
            for j in range(14):
                A = laurent_A(row, j, tab, tz, tpow)
                if A is None:
                    continue
                acc = [a + p for a, p in zip(acc, lmulA(A, M[j]))]
            sc = max(abs(v) for v in dM[row]) + mp.mpf('1e-999')
            res = max(abs(d - a) for d, a in zip(dM[row], acc)) / sc
            dg = float(-mp.log10(res)) if res > 0 else float(mp.mp.dps)
            worst = min(worst, dg)
    return worst


def digits(pred, truth):
    dev = abs(pred - truth) / abs(truth) if truth != 0 else abs(pred)
    return float(-mp.log10(dev)) if dev > 0 else float(mp.mp.dps)


def run_corner_gate(K, derived, quiet=False):
    """LIVE K0..K5 closed forms vs 54 independent E01 accepted.tsv corner rows
    (t-independent masters, orders eps^-2..+6; never used in the MB/Barnes
    derivations). Returns worst digits."""
    worst = mp.inf
    for nm in ("K0", "K1", "K2", "K3", "K4", "K5"):
        w = mp.inf
        for o_str, (re_, im_, agreed) in sorted(
                derived["corner_oracle"]["rows"][nm].items(), key=lambda kv: int(kv[0])):
            o = int(o_str)
            if o < -2 or o > 6:
                continue
            truth = mp.mpc(mp.mpf(re_), mp.mpf(im_))
            if truth == 0:
                continue
            w = min(w, digits(K[nm].get(o), truth))
        worst = min(worst, w)
        if not quiet:
            print("    %s: worst %.2f d over eps^-2..+6  [independent E01 rows]" % (nm, w))
    return worst


def run_tail_gate(K, forms, derived, quiet=False):
    """Closed-form masters vs the oracle at all four points; per-order
    -log10 agreement recomputed live. Returns (worst_heldout, worst_consist)."""
    worst_held, worst_cons = mp.inf, mp.inf
    for pt in ("E01", "E02", "E03", "E04"):
        if pt == "E04":
            rec = derived["oracle_E04"]
            rows = {lab: {int(o): mp.mpc(mp.mpf(v[0]), mp.mpf(v[1]))
                          for o, v in rec["masters"][mkey].items()}
                    for lab, mkey in (("m8", "M8"), ("m11", "M11"),
                                      ("g31", "g31"), ("g32", "g32"))}
            t_str = rec["t"]
        else:
            rows = {lab: {o: mp.mpc(mp.mpf(s_)) for o, s_ in ORACLE[pt][lab].items()}
                    for lab in ("m8", "m11", "g31", "g32")}
            t_str = ORACLE[pt]["t"]
        tf = Fraction(t_str)
        tv = mp.mpf(tf.numerator) / mp.mpf(tf.denominator)
        preds = {"m8": forms["m8"](tv), "m11": forms["m11"](tv),
                 "g31": forms["g31"](), "g32": forms["g32"](tv)}
        held = pt in HELDOUT_PTS
        if not quiet:
            print("  %s (s=-1/4, t=%s): %s" % (pt, t_str, POINT_NOTE[pt]))
        for lab in ("m8", "m11", "g31", "g32"):
            for o in sorted(rows[lab]):
                if o < OMIN or o > OMAX:
                    continue
                truth = rows[lab][o]
                if truth == 0:
                    continue
                dg = digits(preds[lab].get(o), truth)
                if held:
                    worst_held = min(worst_held, dg)
                else:
                    worst_cons = min(worst_cons, dg)
                if not quiet:
                    print("    %-3s eps^%+d = %s   [%.2f d %s]"
                          % (lab, o, mp.nstr(preds[lab].get(o).real, 24), dg,
                             "independent" if held else "consistency"))
    return worst_held, worst_cons


# ---------------------------------------------------------------------------
# Modular-spine cocycle check (live quadrature of the E2 q-series) — round 1/2
# machinery, UNTOUCHED.
# ---------------------------------------------------------------------------
def E2(tau, nterms):
    q = mp.exp(2j * mp.pi * tau)
    s_ = mp.mpc(0)
    qn = [mp.mpc(1)]
    for n in range(1, nterms + 1):
        qn.append(qn[-1] * q)
    for n in range(1, nterms + 1):
        sig = sum(dd for dd in range(1, n + 1) if n % dd == 0)
        s_ += sig * qn[n]
    return 1 - 24 * s_


def cocycle_check():
    tau0 = mp.mpc("0.31", "0.80")
    N = int((mp.mp.dps + 12) * mp.log(10) / (2 * mp.pi * mp.mpf("0.80"))) + 4

    def B24(tau):
        return -(E2(tau, N) - 4 * E2(4 * tau, N)) / 24

    integral = mp.quad(lambda x: B24(tau0 + x), [0, 1])
    delta = 2j * mp.pi * integral
    target = 1j * mp.pi / 4
    dev = abs(delta - target) / abs(target)
    return delta, (-mp.log10(dev)) if dev > 0 else mp.mpf(mp.mp.dps)


def ring_generator_check():
    """Conductor-4 ring GENERATOR: Catalan = L(chi_-4,2) = sum (-1)^k/(2k+1)^2,
    LIVE alternating-series acceleration vs mp.catalan.
    NOTE: 'w2 = Catalan' as a boundary-constant VALUE was PSLQ-refuted
    (Class-1, 2026-07-03); Catalan enters this row's arithmetic only as the
    ring generator. This check validates the generator identity, never any
    boundary value."""
    Llive = mp.nsum(lambda k: (-1) ** k / (2 * k + 1) ** 2, [0, mp.inf], method="a")
    dev = abs(Llive - mp.catalan) / mp.catalan
    return float(-mp.log10(dev)) if dev > 0 else float(mp.mp.dps)


def f(t, dps=100, deep=True):
    """Evaluate the E125 t-cone masters at kinematic point t (Euclidean t<0 on
    the certified fixed-s slice s=-1/4; see module docstring for domain) at
    working precision `dps` decimal digits, from the DERIVED constants
    (closed corner forms + the analytic transport endpoint + runtime
    T1/T8/c13 solve). The tail is an exact polynomial in t.

    Returns {"m8"|"m11"|"g31"|"g32": [eps^-2, ..., eps^4] (mpmath mpc),
             "_deriv_digits": live dM/dt = A_t M residual digits at this t}."""
    t = Fraction(t)
    assert t < 0, "Euclidean t<0 only (domain: see module docstring)"
    old_dps = mp.mp.dps
    mp.mp.dps = dps + GUARD
    try:
        derived = json.load(open(os.path.join(HERE, "zgamma-derived.json")))
        cone = json.load(open(os.path.join(HERE, "zgamma-cone-At.json")))
        structure_check(cone)
        Ser, ser_exp, ser_gamma_eps, hyper_ser = make_series_tools()
        K = build_constants(Ser, ser_exp, ser_gamma_eps, hyper_ser, derived,
                            dps, quiet=True, deep=deep)
        solve_endpoint_tail(Ser, K, derived["slope_tables"])
        forms, coeffs = assemble_tail(Ser, K, derived["slope_tables"])
        tv = mp.mpf(t.numerator) / mp.mpf(t.denominator)
        dg = derivative_identity_check(Ser, build_tab(cone), K, forms, coeffs, [tv])
        return {"m8": ser_to_list(forms["m8"](tv)),
                "m11": ser_to_list(forms["m11"](tv)),
                "g31": ser_to_list(forms["g31"]()),
                "g32": ser_to_list(forms["g32"](tv)),
                "_deriv_digits": dg}
    finally:
        mp.mp.dps = old_dps


# ===========================================================================
# THE (s,t) GRID TIER (2026-09-06): --point s,t [--dps 30|45] [--check] [--mutate] [--workdir DIR] [--out JSON]
# A CANDIDATE tier: the fourteen sector-125 t-cone masters at an off-line Euclidean point (s, t) -- s one of the five
# grid values (the cone exists only there), t any rational in the class of the (s, -1/3) seed's t-transport -- by the
# vendored transport worker of record from the (s, -1/3) seed strings, gated against the vendored grid fixtures at the
# two precisions.  The served tiers above never read vendor_row20_grid/; every unit below is new (grid_*), and main()
# dispatches to grid_main() before any other argument is read when --point carries a comma.
# ===========================================================================
import hashlib as _hashlib
import subprocess as _subprocess

GRID_VENDOR = "vendor_row20_grid"
GRID_S = ["-1/20", "-1/10", "-3/20", "-1/5", "-9/40"]
GRID_T = ["-1/2", "-2/3", "-5/6", "-1", "-5/4"]
GRID_DPS = [30, 45]
GRID_M, GRID_MT2 = "7/25", "1"
GRID_SEED_T = "-1/3"
GRID_PASS_MARGIN = 10      # the record's pass_margin: the bar at a fixture row = min(dps, the fixture string's significant digits) - 10
GRID_GATE_DPS = 400        # the record's gate dps: the strings are parsed and the deviation formed here, never at the working dps
GRID_MAX_SEG = "1/24"      # the record's sub-node length (the checkpoint cadence)
GRID_RC_FAIL, GRID_RC_REFUSED, GRID_RC_PIN, GRID_RC_MISSING, GRID_RC_WORKER = 1, 2, 3, 4, 5
# --- GRID PINS (script-emitted from the shipped bytes: sha256 of every file under vendor_row20_grid/ but GRID_MANIFEST.sha256) ---
GRID_PINS = {
    "GRID_RECORD.json": "802fb72d6b38dbc8f2afbeb736231d51b553e4f8f6e55e237a0a2438d293df74",
    "README.md": "5beccdb4539aa53aac136ad50081c26c6fc6787118e41ab7b65706123b12dcb4",
    "cones/cone_At14_gm1_10.json": "2046a6fe9120ac6b2be377cdf518e6e8ce4425df1f03f7c1a1f204e14e780a6e",
    "cones/cone_At14_gm1_20.json": "3a716a666b4b469a6e2f1b010a27aae88306a98f33d4caf1037c522351d45c29",
    "cones/cone_At14_gm1_5.json": "c08cde1ac366b8314d0c5304c9c183545a777659e86e9e7d74e35025312b301e",
    "cones/cone_At14_gm3_20.json": "c175c8ba93d39c2ba9543472de7d67f24931896d8633d342361043fef0509a46",
    "cones/cone_At14_gm9_40.json": "350d931e809af1ef6cc13cfd7587a05e0fe8e7851ebcf6058c3cedad44fadbf1",
    "endpoints/ENDPOINT_grid_m1_10_tm1_2_dps30.json": "720434149576dfd9e3a1fe8db6d0f21d4a1d165322ded4499afc706bb2344419",
    "endpoints/ENDPOINT_grid_m1_10_tm1_2_dps45.json": "fd16492e5ea64c82d7394b4017775da18fb401a82b75112a4db2e950d5aa5e05",
    "endpoints/ENDPOINT_grid_m1_10_tm1_dps30.json": "ea385189459507ff2547787254abc09112ba37c370b1a71c769d7781e8323028",
    "endpoints/ENDPOINT_grid_m1_10_tm1_dps45.json": "08c0f06bde13a44c75da0c5eaa0de7105001fad922a8675fcc4c67e9382e1510",
    "endpoints/ENDPOINT_grid_m1_10_tm2_3_dps30.json": "53b3f7a11d1b836f6479cc7d65169fc843962d05f690c6b03ddcf68e7ee68687",
    "endpoints/ENDPOINT_grid_m1_10_tm2_3_dps45.json": "169af6a05ab1da5cf52cfb73d9f7b07b5226f2963bcba5eb2ddd3743a0f36fcd",
    "endpoints/ENDPOINT_grid_m1_10_tm5_4_dps30.json": "ad272331f0b67b7b92bef04b384a545ce0c02539f3cc2e00f986b6ba08fdf802",
    "endpoints/ENDPOINT_grid_m1_10_tm5_4_dps45.json": "850da3dc004c8421640bc4b89fcd89d1ac213fbce1a8538c96822f69e3394eb5",
    "endpoints/ENDPOINT_grid_m1_10_tm5_6_dps30.json": "82eaa60dbeaef51e9b9a996ea5107eefb3fe08a79b2db1a565b8a882bc18d90f",
    "endpoints/ENDPOINT_grid_m1_10_tm5_6_dps45.json": "898f4fbe3d3b2b650008cfb03211cde86a248de863729fbef2a9176c937baf21",
    "endpoints/ENDPOINT_grid_m1_20_tm1_2_dps30.json": "ae0ec5d5ec706f1e38e54dbb4a407c9c3689ce147f961e4e7b9996a7c6b810e8",
    "endpoints/ENDPOINT_grid_m1_20_tm1_2_dps45.json": "21039b2cf944ab393c06f0592721ce18cc2a84ae6a717022f6c4c5608f0a4e14",
    "endpoints/ENDPOINT_grid_m1_20_tm1_dps30.json": "a2aea105c0355be6a287c7ea4a0610a09dbc935d7974d09df58dd97250b0f706",
    "endpoints/ENDPOINT_grid_m1_20_tm1_dps45.json": "83b5fefccfef4d7bb5693558a37ca2232398231eb007fcff7aa1f4f3f5cebbcc",
    "endpoints/ENDPOINT_grid_m1_20_tm2_3_dps30.json": "4e32df21e128657db929e631a088d48b73a1ab70a298dbe8f8e83ff412a700ee",
    "endpoints/ENDPOINT_grid_m1_20_tm2_3_dps45.json": "1e5d413f361c2575a9c8f27923d6e4abe890990891cb12faedb7f0e4836067d7",
    "endpoints/ENDPOINT_grid_m1_20_tm5_4_dps30.json": "9d9560544a63b6d20ea7b3759a803525e7aaf11b0b939a2e6013107243e791c3",
    "endpoints/ENDPOINT_grid_m1_20_tm5_4_dps45.json": "3cda40d16cd0233dfd4404535346ebfc35dc6473cd57bd7a902be5206d5fa8ac",
    "endpoints/ENDPOINT_grid_m1_20_tm5_6_dps30.json": "127ab3faa7269f845cbcd028ca3e715c111ffc87b43048ddab3e973fa05964be",
    "endpoints/ENDPOINT_grid_m1_20_tm5_6_dps45.json": "ea1fda05940397f480f332a33c9f8c09dd5fa3a6902be98e3fd34543dd700536",
    "endpoints/ENDPOINT_grid_m1_5_tm1_2_dps30.json": "ca3e25d0411516b7d7a42760f8427238cf703e76151e85f8f5a1e96cb99ee57d",
    "endpoints/ENDPOINT_grid_m1_5_tm1_2_dps45.json": "fb7d61a1e9b786cf93a1a16b1a014a0f8fd60bb36897913231d2316fc5903325",
    "endpoints/ENDPOINT_grid_m1_5_tm1_dps30.json": "e8ddafc53e8f021d3ff32db2ef66c4a5977839d81151ce1c6981db7bd6825227",
    "endpoints/ENDPOINT_grid_m1_5_tm1_dps45.json": "b613974d4564e6ae458b15c89feabd1ab819e5ac9e55d837b11ea8a69e5c10c9",
    "endpoints/ENDPOINT_grid_m1_5_tm2_3_dps30.json": "4d4d40d4bf36b3a163d2361f0ce270048563ec9541e44eaa3e394acc98f2aeb3",
    "endpoints/ENDPOINT_grid_m1_5_tm2_3_dps45.json": "8d338066655d154ce9da1213ab0580c3d1608599ed0ffe92caa17d9817a9b901",
    "endpoints/ENDPOINT_grid_m1_5_tm5_4_dps30.json": "65212fbc3d347cc024a609ce5fd96eabc4aa4485130a83cfc93a7122769823b8",
    "endpoints/ENDPOINT_grid_m1_5_tm5_4_dps45.json": "005be9c827354b1d5a6604039e49df4b4da35ccf51c40705a16b2c9d5ea287b1",
    "endpoints/ENDPOINT_grid_m1_5_tm5_6_dps30.json": "6516986c625fd1f0a8a2ee57516703ff7b8da2dde3918538dd34ae61b369d58c",
    "endpoints/ENDPOINT_grid_m1_5_tm5_6_dps45.json": "9b1f8e97d48ed4b01adb4d12fa04680447cd23f7419129d202c245b7dca37345",
    "endpoints/ENDPOINT_grid_m3_20_tm1_2_dps30.json": "fb8d5d74ab5a7c35594781f0400349ef68bebe4274b1c97e1ebbb6e4be26e833",
    "endpoints/ENDPOINT_grid_m3_20_tm1_2_dps45.json": "a0c0280d305bcac078816436541d0394b89d100167bab963499503fae1118592",
    "endpoints/ENDPOINT_grid_m3_20_tm1_dps30.json": "f07c40e6d6bfc16a825a42526c88f0a4a9cbd0ee20db395f6cc89d12a8dcc946",
    "endpoints/ENDPOINT_grid_m3_20_tm1_dps45.json": "d95a4a3795859c370a549b8023af7f2f6dcbc8f2fd4d1519958f1b7c1dc853fb",
    "endpoints/ENDPOINT_grid_m3_20_tm2_3_dps30.json": "a3c5dc6d26addc77df64c439152752ea073ed0ea965a0cb998b004c4837f6089",
    "endpoints/ENDPOINT_grid_m3_20_tm2_3_dps45.json": "12ae3c61286e76b7473345a6fc87221282122b919707e2e0f4d1900b6e8f89b8",
    "endpoints/ENDPOINT_grid_m3_20_tm5_4_dps30.json": "9e4c22916b2c03be35724cdcd2db3a9923f52e3171c79c3647ce117787799c6c",
    "endpoints/ENDPOINT_grid_m3_20_tm5_4_dps45.json": "f456f9e0d66a11d101a8b39223574fe99dd0f59f6b3be006aba633320c7043d2",
    "endpoints/ENDPOINT_grid_m3_20_tm5_6_dps30.json": "c9f2926416618191c9df06fc36f147fa6b9f86c29b1ef29da4bc039024a4e30e",
    "endpoints/ENDPOINT_grid_m3_20_tm5_6_dps45.json": "6d78bd356b37bbf3391461e7670c14accf5d1363dcd8f4673d321cba30471e8d",
    "endpoints/ENDPOINT_grid_m9_40_tm1_2_dps30.json": "d791f07a056a23170fb7650f6184b01c0259c9b816923321b781c7c23d7a20b6",
    "endpoints/ENDPOINT_grid_m9_40_tm1_2_dps45.json": "dac8ea62254b97061c899f92b1c00aad9ced171b5dde3d7de0c4a9c68d6283e4",
    "endpoints/ENDPOINT_grid_m9_40_tm1_dps30.json": "eab832ebfe1d87be8bba19cc16fc8d864503f75b89e44a713422b302edf86370",
    "endpoints/ENDPOINT_grid_m9_40_tm1_dps45.json": "749b832d78075094ad8ec76f122e89f539e6e6c729109f7fae9155ecb9cb660f",
    "endpoints/ENDPOINT_grid_m9_40_tm2_3_dps30.json": "030de78de0480655748ef89858b9629ada3df38f72ea31a73a024cd3a9acb811",
    "endpoints/ENDPOINT_grid_m9_40_tm2_3_dps45.json": "7fa823b06e8def62dd3d1d76271757fe4afe693675e7d273d0545c73fd4ce3bc",
    "endpoints/ENDPOINT_grid_m9_40_tm5_4_dps30.json": "86b3d073240f84c44175f0cf0171505ba256b17e3eb5cf8e1341e485c3468598",
    "endpoints/ENDPOINT_grid_m9_40_tm5_4_dps45.json": "a0fae17b47eab6aeb8ed7c7cb4e57473dbdadfe5bb959fdc81fd589eba9706a2",
    "endpoints/ENDPOINT_grid_m9_40_tm5_6_dps30.json": "d24474319db257b835dc2bd0efbff6fdbe52e2080ae192a5634c4051343c5fc8",
    "endpoints/ENDPOINT_grid_m9_40_tm5_6_dps45.json": "5872d53fd12e893d5ac64f2ae4356e265e17863a4d0bc302be6f299d07376971",
    "grid_leg_worker.py": "70fd8c0b30afcb5e5e71d21a21642e9d3eddcd8fd09a0bafd5765a35cf7426d3",
    "seeds/seed_gm1_10_dps30.tsv": "ddf4afaafdb9166976d58de6a984b55caa0e36fb97861f03bd7d0a6373bb2294",
    "seeds/seed_gm1_10_dps45.tsv": "931b924a6d7da46167b6773bdd76e9e14ad9f0a21d0c9b1ec087531793a7d44b",
    "seeds/seed_gm1_20_dps30.tsv": "d0328e9c7bdfe2e0d9502487712aceab2208f4e30120d6911c96c4c8f662b720",
    "seeds/seed_gm1_20_dps45.tsv": "9f7bedb77e57ef46dca1c057e49446afd28723f6ab4274e56220648ca7cf06ee",
    "seeds/seed_gm1_5_dps30.tsv": "eb58ed2fc77284a5361333631d2bfa1fb7c4b9ca7f5b15ab7f92226f2bd3890f",
    "seeds/seed_gm1_5_dps45.tsv": "1eb2a08514c665b1aafc0183308e43b0a44edafe78ea2931de0d22043b80d6a4",
    "seeds/seed_gm3_20_dps30.tsv": "5d51c504a0fac68c8326c66d2b8e91bfba65697f0ec97a36b34dbff7acd29577",
    "seeds/seed_gm3_20_dps45.tsv": "e1d0255a965ac845c9128862248067ee9af761cbf5f9c2af9c14d5f20f3f75ee",
    "seeds/seed_gm9_40_dps30.tsv": "e3971f0e1de02ab9063403c906485123ae2daf4b82b1680064fff1375c2c202c",
    "seeds/seed_gm9_40_dps45.tsv": "bb2dce8de6e742be3678c1878c00f28b51e495e781760305909666ecd5a72f63",
}
# --- END GRID PINS ---


class GridExit(Exception):
    def __init__(self, rc, msg):
        super().__init__(msg)
        self.rc = rc


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


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


def grid_tag(x):
    f = Fraction(x)
    return ("m%d_%d" % (-f.numerator, f.denominator)) if f.denominator != 1 else ("m%d" % (-f.numerator))


def grid_check_pins():
    """every vendored file present and byte-identical to its pin; MISSING -> rc 4, a mismatch -> rc 3 (both by name)."""
    for rel, want in GRID_PINS.items():
        p = os.path.join(HERE, GRID_VENDOR, rel)
        if not os.path.exists(p):
            raise GridExit(GRID_RC_MISSING, "zgamma-evaluate --point MISSING: pinned file %s/%s is absent (recorded sha256 %s); not serving" % (GRID_VENDOR, rel, want))
        got = grid_sha256(p)
        if got != want:
            pos = next(i + 1 for i in range(64) if got[i] != want[i])
            raise GridExit(GRID_RC_PIN, "zgamma-evaluate --point REFUSED: %s/%s integrity pin mismatch (recorded %s, recomputed %s; first differing hex position %d of 64, 1-based) -- the shipped file was altered; not serving" % (GRID_VENDOR, rel, want, got, pos))
    return len(GRID_PINS)


def grid_sig(s):
    """significant digits of a decimal string (trailing zeros count: '1.0' -> 2; a bare zero -> 1)."""
    t = str(s).strip().split("e")[0].split("E")[0].lstrip("+-").replace(".", "")
    st = t.lstrip("0")
    return len(st) if st else 1


def grid_agree(pred, truth, dps):
    """the record's digit convention at the gate dps on the complex value: equal strings -> 999; both below the chain
    tolerance 10^-(dps-10) -> an exact zero at this precision, counted dps-10; else -log10(|pred-truth| / (|truth| + 10^-(dps-5)))."""
    if pred[0] == truth[0] and pred[1] == truth[1]:
        return 999.0, "identical"
    with mp.workdps(GRID_GATE_DPS):
        P = mp.mpc(mp.mpf(pred[0]), mp.mpf(pred[1]))
        T = mp.mpc(mp.mpf(truth[0]), mp.mpf(truth[1]))
        if max(abs(P), abs(T)) < mp.mpf(10) ** (-(dps - 10)):
            return float(dps - 10), "zero row"
        dev = abs(P - T) / (abs(T) + mp.mpf(10) ** (-(dps - 5)))
        return (float(-mp.log10(dev)) if dev > 0 else 999.0), ""


def grid_pair_digits(lo, hi, dps_lo):
    """the record's pair convention: -log10(|hi-lo| / (|hi| + 10^-25)) at the gate dps; both below 10^-(dps_lo-10) -> dps_lo-10."""
    with mp.workdps(GRID_GATE_DPS):
        x = mp.mpc(mp.mpf(lo[0]), mp.mpf(lo[1]))
        y = mp.mpc(mp.mpf(hi[0]), mp.mpf(hi[1]))
        if max(abs(x), abs(y)) < mp.mpf(10) ** (-(dps_lo - 10)):
            return float(dps_lo - 10), True
        dev = abs(x - y) / (abs(y) + mp.mpf(10) ** (-(dps_lo - 5)))
        return (float(-mp.log10(dev)) if dev > 0 else float(GRID_GATE_DPS)), False


def grid_den_roots(cone):
    """the real roots of every A_t denominator at eps = 0 (the connection's poles on the real t-axis; the apparent
    singularities of the cone at this s) -- the segment from the seed to the target must not touch one."""
    roots = set()
    with mp.workdps(50):
        for ent in cone["A_t"].values():
            c = {}
            for ke, kt, co in ent["den"]:
                if int(ke) == 0:
                    c[int(kt)] = c.get(int(kt), Fraction(0)) + Fraction(co)
            if not c or max(c) == 0:
                continue
            deg = max(c)
            if deg == 1:
                roots.add(Fraction(-c.get(0, Fraction(0)), c[1]))
                continue
            poly = [mp.mpf(c.get(k, Fraction(0)).numerator) / c.get(k, Fraction(0)).denominator for k in range(deg, -1, -1)]
            for r in mp.polyroots(poly, maxsteps=200, extraprec=100):
                if abs(mp.im(r)) < mp.mpf(10) ** -30:
                    roots.add(Fraction(mp.nstr(mp.re(r), 40)))
    return sorted(roots)


def grid_t_class(cone, s, t):
    """the class of the (s, -1/3) seed's t-transport for this cone: Euclidean t < 0, above the u = 4 m_t^2 threshold
    t = M - s - 4 (a contour leg below it is not established for the fourteen-master cone), the real segment from the seed
    -1/3 to t touching no root of the connection's denominators at eps = 0.  Returns the refusal text, or None."""
    thr = Fraction(GRID_M) - Fraction(s) - 4
    seed = Fraction(GRID_SEED_T)
    if t >= 0:
        return "t = %s is not Euclidean (t < 0 only)" % t
    if t == seed:
        return "t = -1/3 is the seed point itself: its strings are the vendored seed (seeds/seed_g%s_dps<D>.tsv), no transport" % grid_tag(s)
    if t <= thr:
        return "t = %s is at or below the u = 4 m_t^2 threshold t = M - s - 4 = %s at s = %s: a contour leg around the threshold is NOT ESTABLISHED for the fourteen-master cone (the sector-127 legs of zgamma-s127-evaluate.py carry it at s = -1/4)" % (t, thr, s)
    roots = grid_den_roots(cone)
    lo, hi = min(seed, t), max(seed, t)
    hit = [r for r in roots if lo <= r <= hi]
    if hit:
        return "t = %s: the real segment from the seed -1/3 to t touches a root of the connection's denominators at eps = 0 (t = %s; the apparent singularities of the cone at s = %s lie at %s): outside the class of the (s,-1/3) seed's t-transport" % (t, ", ".join(str(r) for r in hit), s, ", ".join(mp.nstr(mp.mpf(r.numerator) / r.denominator, 6) for r in roots))
    return None


def grid_fixture_path(s, t, dps):
    return os.path.join(HERE, GRID_VENDOR, "endpoints", "ENDPOINT_grid_%s_t%s_dps%d.json" % (grid_tag(s), grid_tag(t), dps))


def grid_points_dir(workdir, label, s, t, seed_path, cone):
    """the worker's points directory for one run: COORD.json (the fixed s and the t of S0 and TX), S0/accepted.tsv = the
    vendored seed byte for byte, TX/accepted.tsv = the synthetic target (zeros, validated 0: the front end gates it)."""
    pd = os.path.join(workdir, "points_" + label)
    for sub in ("S0", "TX"):
        os.makedirs(os.path.join(pd, sub), exist_ok=True)
    json.dump({"S": str(s), "points": {"S0": GRID_SEED_T, "TX": str(t)}, "note": "the points of one t-leg: S0 = the vendored seed at (s,-1/3), TX = the target (no truth: zeros, validated 0)"}, open(os.path.join(pd, "COORD.json"), "w"), indent=1)
    with open(seed_path, "rb") as fi, open(os.path.join(pd, "S0", "accepted.tsv"), "wb") as fo:
        fo.write(fi.read())
    OMIN_, OMAX_ = cone["eps_orders"]
    with open(os.path.join(pd, "TX", "accepted.tsv"), "w") as f:
        f.write("# point TX: s=%s t=%s Msq=%s msq=%s SYNTHETIC target (no truth): zeros, validated 0\n" % (s, t, GRID_M, GRID_MT2))
        f.write("indices\torder\tre\tim\tagreed_digits\tvalidated\n")
        for nu in cone["cone_nu"]:
            for o in range(OMIN_, OMAX_ + 1):
                f.write("%s\t%d\t0\t0\t0\t0\n" % (",".join(str(v) for v in nu), o))
    return pd


def grid_worker_cmd(cone_path, dps, ckpt, hb, outdir, label):
    """the command line of record (the grid's t-legs): base S0 -> target TX, detour auto, max-seg 1/24, gate dps 400, margin 10."""
    return [sys.executable, os.path.join(HERE, GRID_VENDOR, "grid_leg_worker.py"), "--cone", cone_path, "--base", "S0", "--targets", "TX", "--dps", str(dps),
            "--detour", "auto", "--max-seg", GRID_MAX_SEG, "--ckpt", ckpt, "--heartbeat", hb, "--out-dir", outdir, "--label", label,
            "--gate-dps", str(GRID_GATE_DPS), "--pass-margin", str(GRID_PASS_MARGIN)]


def grid_disp(p):
    """a path for the printed line: relative to the current directory when it lies under it, else as given."""
    cwd = os.getcwd()
    return os.path.relpath(p, cwd) if p.startswith(cwd + os.sep) else p


def grid_run_worker(cmd, workdir, label, points_dir):
    """drive the vendored worker; stream its log (the sub-node lines carry the rate: this run's own step lines)."""
    env = dict(os.environ)
    env["PYTHONDONTWRITEBYTECODE"] = "1"
    env["ROW20_POINTS"] = points_dir
    print("  [worker] " + " ".join(os.path.relpath(c, HERE) if c.startswith(HERE) else ("python3" if c == sys.executable else grid_disp(c)) for c in cmd), flush=True)
    log = open(os.path.join(workdir, "worker_%s.log" % label), "a")
    log.write("=== %s launch: %s\n" % (grid_utc(), " ".join(cmd)))
    t0 = time.time()
    last = ""
    p = _subprocess.Popen(cmd, stdout=_subprocess.PIPE, stderr=_subprocess.STDOUT, text=True, cwd=workdir, env=env)
    for ln in p.stdout:
        ln = ln.rstrip("\n")
        last = ln
        log.write(ln + "\n")
        log.flush()
        if "sub-node" in ln or "LEG " in ln or "GATE at" in ln or "REFUSED" in ln:
            print("  [worker] " + ln, flush=True)
    rc = p.wait()
    log.write("=== %s exit rc %d\n" % (grid_utc(), rc))
    log.close()
    return rc, round(time.time() - t0, 1), last


def grid_values(T):
    """{nu csv: {order: [re, im]}} from the worker's TRANSPORT json (gate_rows pred_re / pred_im; every order)."""
    out = {}
    for r in T["legs"][0]["gate_rows"]:
        out[",".join(str(v) for v in r["nu"])] = {o: [po["pred_re"], po["pred_im"]] for o, po in r["per_order"].items()}
    return out


def grid_transport(s, t, dps, workdir, cone_path, cone, label):
    """one t-leg from the (s,-1/3) seed at this dps (checkpointed; a re-run resumes); returns (values, wall, T)."""
    seed = os.path.join(HERE, GRID_VENDOR, "seeds", "seed_g%s_dps%d.tsv" % (grid_tag(s), dps))
    pd = grid_points_dir(workdir, label, s, t, seed, cone)
    ckpt = os.path.join(workdir, "ckpt_%s.json" % label)
    out = os.path.join(workdir, "TRANSPORT_%s.json" % label)
    if os.path.exists(ckpt):
        try:
            ck = json.load(open(ckpt))
            print("  checkpoint present: %s status %s (%s/%s sub-nodes done) -- the worker resumes from it" % (os.path.basename(ckpt), ck.get("status"), ck.get("nodes_done"), ck.get("n_subnodes")))
        except Exception:
            print("  checkpoint present but unreadable: %s" % os.path.basename(ckpt))
    cmd = grid_worker_cmd(cone_path, dps, ckpt, os.path.join(workdir, "heartbeat_%s.json" % label), workdir, label)
    rc, wall, last = grid_run_worker(cmd, workdir, label, pd)
    if rc != 0 or not os.path.exists(out):
        raise GridExit(GRID_RC_WORKER, "zgamma-evaluate --point WORKER DID NOT FINISH at (s,t) = (%s, %s), dps %d: rc %d; last line: %r%s" % (s, t, dps, rc, last, " -- rc 6 = a checkpoint from another configuration under --workdir; move it aside" if rc == 6 else ""))
    T = json.load(open(out))
    Lg = T["legs"][0]
    print("  transported (s,t) = (%s, %s) from the seed t = -1/3 at dps %d: %d sub-nodes, %d F calls, worker wall %s s (this host, this load); path %s" % (
        s, t, dps, Lg["n_subnodes"], T["n_F_calls"], Lg["wall_s"], "straight" if not Lg["crossing"] else "contour around " + str(Lg["crossing"])))
    return grid_values(T), wall, T


def grid_print_values(vals, cone, dps):
    OMIN_, OMAX_ = cone["eps_orders"]
    print("  the fourteen masters (index vector; eps^-2..eps^4 as Re, Im at the worker's printed width, dps %d):" % dps)
    for i, nu in enumerate(cone["cone_nu"]):
        key = ",".join(str(v) for v in nu)
        tagm = " (R_a)" if i == cone["RA"] else (" (R_b)" if i == cone["RB"] else "")
        print("    master %2d  %s  sector %d%s" % (i, key, cone["cone_sec"][i], tagm))
        for o in range(OMIN_, OMAX_ + 1):
            re_, im_ = vals[key][str(o)]
            print("      eps^%-2d  %s   %s" % (o, re_, im_))


def grid_gate(vals, fix, dps):
    """every row of the fixture at this dps: digits vs the fixture string (the record's convention), the row's bar
    min(dps, significant digits of the fixture string) - 10; FAIL by name on the first row below its bar."""
    rows = []
    for key, ser in fix["masters"].items():
        for o, truth in ser.items():
            pred = vals[key][o]
            d, tagr = grid_agree(pred, truth, dps)
            bar = min(dps, grid_sig(truth[0])) - GRID_PASS_MARGIN
            rows.append((d, key, int(o), bar, tagr, pred, truth))
    rows.sort(key=lambda r: (r[0] - r[3], r[0]))
    fails = [r for r in rows if r[0] < r[3]]
    n_id = sum(1 for r in rows if r[4] == "identical")
    worst = min(rows, key=lambda r: r[0])
    return {"n_rows": len(rows), "identical_rows": n_id, "worst_d": round(worst[0], 2) if worst[0] < 999 else 999.0, "worst_member": {"nu": worst[1], "order": worst[2]}, "worst_bar": worst[3],
            "bar_rule": "min(dps, fixture significant digits) - %d per row" % GRID_PASS_MARGIN, "bar_min": min(r[3] for r in rows), "bar_max": max(r[3] for r in rows),
            "fails": [{"nu": r[1], "order": r[2], "digits": round(r[0], 2), "bar": r[3], "pred": r[5][0][:30], "fixture": r[6][0][:30]} for r in fails[:5]], "n_fails": len(fails),
            "worst_5": [{"nu": r[1], "order": r[2], "digits": (round(r[0], 2) if r[0] < 999 else 999.0), "bar": r[3]} for r in sorted(rows, key=lambda r: r[0])[:5]]}


def grid_pair(v30, v45):
    rows = []
    zeros = 0
    for key in v45:
        for o in v45[key]:
            d, z = grid_pair_digits(v30[key][o], v45[key][o], GRID_DPS[0])
            zeros += z
            rows.append((d, key, o))
    rows.sort()
    return {"n_rows": len(rows), "floor_d": round(rows[0][0], 2), "member": {"nu": rows[0][1], "order": rows[0][2]}, "zero_rows": zeros,
            "worst_5": [{"digits": round(d, 2), "master": k, "order": o} for d, k, o in rows[:5]], "median_d": round(sorted(r[0] for r in rows)[len(rows) // 2], 2)}


def grid_mutate(fix):
    """the planted control, in memory: the 12th significant digit of the Re string of R_a at eps^0 changed by one (the
    record's planted-digit control on the comparator: 10.77 d, FAIL by name); the file is never touched."""
    key = "1,0,1,1,1,1,1,0,0"
    v = fix["masters"][key]["0"][0]
    digs = [i for i, c in enumerate(v) if c.isdigit()]
    sig = [i for i in digs if v[:i].lstrip("-0.") != "" or v[i] != "0"]
    i = sig[11]
    new = v[:i] + str((int(v[i]) + 1) % 10) + v[i + 1:]
    fix["masters"][key]["0"][0] = new
    return {"master": key, "order": 0, "significant_digit": 12, "char_index": i, "from": v[i], "to": new[i]}


def grid_usage():
    return ("usage: zgamma-evaluate.py --point s,t [--dps 30|45] [--check] [--mutate] [--workdir DIR] [--out JSON]   "
            "(s one of %s; t a rational in the class of the (s,-1/3) seed's t-transport; --help for the tier's text)" % ", ".join(GRID_S))


def grid_main(argv):
    """the tier: returns the exit code (0 PASS | 1 FAIL by name / the caught --mutate | 2 refused by name | 3 pin mismatch |
    4 pinned file missing | 5 the worker did not finish)."""
    t_all = time.time()
    stamp0 = grid_utc()
    try:
        sys.stdout.reconfigure(line_buffering=True)
    except AttributeError:
        pass
    args = {"point": None, "dps": GRID_DPS[0], "check": False, "mutate": False, "workdir": None, "out": None}
    i = 0
    try:
        while i < len(argv):
            a = argv[i]
            if a == "--point" and i + 1 < len(argv):
                args["point"] = argv[i + 1]; i += 2
            elif a == "--dps" and i + 1 < len(argv):
                args["dps"] = int(argv[i + 1]); i += 2
            elif a == "--check":
                args["check"] = True; i += 1
            elif a == "--mutate":
                args["mutate"] = True; i += 1
            elif a == "--workdir" and i + 1 < len(argv):
                args["workdir"] = argv[i + 1]; i += 2
            elif a == "--out" and i + 1 < len(argv):
                args["out"] = argv[i + 1]; i += 2
            else:
                raise GridExit(GRID_RC_REFUSED, "zgamma-evaluate --point: unknown or incomplete argument %r\n%s" % (a, grid_usage()))
        try:
            s_str, t_str = args["point"].split(",")
            s_frac, t_frac = Fraction(s_str.strip()), Fraction(t_str.strip())
        except Exception:
            raise GridExit(GRID_RC_REFUSED, "zgamma-evaluate --point: the point must be two rationals s,t (got %r)\n%s" % (args["point"], grid_usage()))
        if args["out"] and os.path.exists(args["out"]):
            raise GridExit(GRID_RC_REFUSED, "zgamma-evaluate --point: --out %s exists; nothing is overwritten and nothing was computed" % args["out"])
        s = next((x for x in GRID_S if Fraction(x) == s_frac), None)
        if s is None:
            raise GridExit(GRID_RC_REFUSED, "zgamma-evaluate --point REFUSED by name: s = %s is not one of the five grid values %s -- the fourteen-master t-cone and the (s,-1/3) seed exist only there; the s-march is not servable standalone (it needs the cusp-boundary chain) and the A_t build at a new s needs the 449 MB reduction table" % (s_frac, ", ".join(GRID_S)))
        if args["dps"] not in GRID_DPS:
            raise GridExit(GRID_RC_REFUSED, "zgamma-evaluate --point REFUSED by name: --dps %d -- the (s,-1/3) seeds exist at dps 30 and 45 only (the record's two members); a dps-60 transport member is NOT ESTABLISHED" % args["dps"])
        if args["check"] and args["mutate"]:
            raise GridExit(GRID_RC_REFUSED, "zgamma-evaluate --point: --check and --mutate are separate tiers")
        npins = grid_check_pins()
        rec = json.load(open(os.path.join(HERE, GRID_VENDOR, "GRID_RECORD.json")))
        cone_path = os.path.join(HERE, GRID_VENDOR, "cones", "cone_At14_g%s.json" % grid_tag(s))
        cone = json.load(open(cone_path))
        assert Fraction(cone["s"]) == s_frac and cone["M"] == GRID_M and cone["mt2"] == GRID_MT2 and cone["NC"] == 14 and cone["n_entries"] == 30, "the vendored cone does not carry this s"
        refusal = grid_t_class(cone, s, t_frac)
        if refusal:
            raise GridExit(GRID_RC_REFUSED, "zgamma-evaluate --point REFUSED by name: " + refusal)
        t = str(t_frac)
        on_grid = any(Fraction(x) == t_frac for x in GRID_T)
        key = "%s|%s" % (s, t)
        workdir = os.path.abspath(args["workdir"] or os.path.join(os.getcwd(), "zgamma-grid-work"))
        os.makedirs(workdir, exist_ok=True)
        print("gg->Zgamma exact-m_t E125 fourteen-master t-cone OFF the s=-1/4 line: (s,t) = (%s, %s), M = %s, m_t^2 = %s -- a CANDIDATE tier" % (s, t, GRID_M, GRID_MT2))
        print("  [pins] %d shipped files under %s/ verified by sha256" % (npins, GRID_VENDOR))
        print("  [workdir] %s" % grid_disp(workdir))
        print("  the certificate of the surface is the transport's own two-precision pair (dps 30 vs 45; the record's floor over the 25 points %s d at (%s, %s), best %s d); ONE point carries an independent gate: (s,t) = (%s, %s), AMFlow goal 40 vs 60 reproduces the transported cone to %s d over %s rows, certified %s d (capped by the dps-30 member)" % (
            rec["pair_floor_over_grid"]["floor_d"], rec["pair_floor_over_grid"]["worst_point"]["s"], rec["pair_floor_over_grid"]["worst_point"]["t"], rec["pair_floor_over_grid"]["best_point_floor_d"],
            rec["amflow_gate_one_point"]["point"]["s"], rec["amflow_gate_one_point"]["point"]["t"], rec["amflow_gate_one_point"]["cross_floor_d"], rec["amflow_gate_one_point"]["n_rows"], rec["amflow_gate_one_point"]["certified_d"]))
        if on_grid:
            print("  (s,t) is one of the 25 grid points: the run is GATED against the vendored fixture at each precision run (bar per row = min(dps, fixture digits) - %d, the record's margin)%s" % (GRID_PASS_MARGIN, "; this is the AMFlow-gated point" if key == "%s|%s" % (rec["amflow_gate_one_point"]["point"]["s"], rec["amflow_gate_one_point"]["point"]["t"]) else ""))
        else:
            print("  no fixture at this point (t = %s is not a grid t-value): the values are printed with the two-precision self-check dps 30 vs 45 (the record's pair form) as the only certificate" % t)
        dps_list = [args["dps"]] if (on_grid and not args["check"]) else list(GRID_DPS)
        results = {}
        rc = 0
        planted = None
        for D in dps_list:
            label = "grid_%s_t%s_dps%d" % (grid_tag(s), grid_tag(t), D)
            print("\n[leg] (s,t) = (%s, %s) at dps %d: the seed = the vendored s-march endpoint at (s,-1/3) (seeds/seed_g%s_dps%d.tsv), the cone cones/cone_At14_g%s.json" % (s, t, D, grid_tag(s), D, grid_tag(s)))
            if on_grid:
                fx = rec["per_point"][key]["fixtures"]["dps%d" % D]
                print("  the record's leg at this precision: %s sub-nodes, %s F calls, worker wall %s s (CONTENDED, the record's host)" % (fx["n_subnodes"], fx["n_F_calls"], fx["worker_wall_s_CONTENDED"]))
            vals, wall, T = grid_transport(s, t, D, workdir, cone_path, cone, label)
            r = {"dps": D, "label": label, "n_subnodes": T["legs"][0]["n_subnodes"], "n_F_calls": T["n_F_calls"], "worker_wall_s": T["legs"][0]["wall_s"], "subprocess_wall_s": wall, "result_sha256": grid_sha256(os.path.join(workdir, "TRANSPORT_%s.json" % label)), "stamp_utc": T["stamp_utc"]}
            if D == args["dps"] or not on_grid:
                grid_print_values(vals, cone, D)
            if on_grid:
                fix = json.load(open(grid_fixture_path(s, t, D)))
                assert fix["dps"] == D and fix["point"] == {"s": s, "t": t, "M": GRID_M, "mt2": GRID_MT2}
                if args["mutate"] and D == args["dps"]:
                    planted = grid_mutate(fix)
                    print("  [mutate] MUTATION CONTROL: in memory, the fixture's R_a eps^0 Re string has its 12th significant digit changed '%s' -> '%s' (char %d); expected: the gate FAILS by name (rc 1)" % (planted["from"], planted["to"], planted["char_index"]))
                g = grid_gate(vals, fix, D)
                r["gate"] = g
                print("  gate vs the fixture at dps %d (%d rows = 14 masters x 7 orders; %d identical strings): worst %s d at master %s eps^%d (its bar %d; bars %d..%d = min(dps, fixture digits) - %d); rows below their bar: %d -> %s" % (
                    D, g["n_rows"], g["identical_rows"], g["worst_d"], g["worst_member"]["nu"], g["worst_member"]["order"], g["worst_bar"], g["bar_min"], g["bar_max"], GRID_PASS_MARGIN, g["n_fails"], "PASS" if g["n_fails"] == 0 else "FAIL"))
                for fl in g["fails"]:
                    print("    FAIL by name: master %s eps^%d agrees to %s d < its bar %d (run %s... vs fixture %s...)" % (fl["nu"], fl["order"], fl["digits"], fl["bar"], fl["pred"], fl["fixture"]))
                if g["n_fails"]:
                    rc = GRID_RC_FAIL
            results["dps%d" % D] = r
            results["dps%d" % D]["values"] = vals
        pair = None
        if len(dps_list) == 2:
            pair = grid_pair(results["dps30"]["values"], results["dps45"]["values"])
            if on_grid:
                rp = rec["per_point"][key]
                bar = int(rp["pair_floor_d"])
                pair["bar"] = bar
                pair["record_floor_d"] = rp["pair_floor_d"]
                pair["record_member"] = rp["worst_5"][0]
                pair["pass"] = pair["floor_d"] >= bar
                print("\n[pair] dps 30 vs 45 over %d rows: floor %s d at master %s eps^%s (%d zero rows counted 20 d); the record's floor at this point %s d at %s eps^%s -> bar %d (its floor): %s" % (
                    pair["n_rows"], pair["floor_d"], pair["member"]["nu"], pair["member"]["order"], pair["zero_rows"], rp["pair_floor_d"], rp["worst_5"][0]["master"], rp["worst_5"][0]["order"], bar, "PASS" if pair["pass"] else "FAIL"))
                if not pair["pass"]:
                    rc = GRID_RC_FAIL
            else:
                print("\n[pair] dps 30 vs 45 over %d rows: floor %s d at master %s eps^%s (%d zero rows counted 20 d) -- the only certificate at this point (no fixture; the record's grid floor %s d is the class)" % (
                    pair["n_rows"], pair["floor_d"], pair["member"]["nu"], pair["member"]["order"], pair["zero_rows"], rec["pair_floor_over_grid"]["floor_d"]))
        wall_all = round(time.time() - t_all, 1)
        if planted is not None:
            caught = rc == GRID_RC_FAIL
            verdict = "MUTATION CAUGHT (the gate FAILS by name)" if caught else "MUTATION NOT CAUGHT (a defect of the control, never a pass)"
            rc = GRID_RC_FAIL if caught else GRID_RC_WORKER
        else:
            verdict = "PASS" if rc == 0 else "FAIL"
        print("\nVERDICT %s: (s,t) = (%s, %s); " % (verdict, s, t) + "; ".join("dps %d: %s" % (r["dps"], ("worst vs fixture %s d (bar %d)" % (r["gate"]["worst_d"], r["gate"]["worst_bar"]) if "gate" in r else "no fixture")) for r in results.values())
              + ("; pair 30/45 floor %s d%s" % (pair["floor_d"], (" vs bar %d" % pair["bar"]) if "bar" in pair else "") if pair else "") + "; total wall %s s" % wall_all)
        if args["out"]:
            recp = {"PRODUCER": {"script": os.path.basename(__file__), "sha256": grid_sha256(os.path.abspath(__file__)), "start": stamp0, "stamp": grid_utc(), "wall_s": wall_all, "pins_verified": npins, "stamp_source": "date -u"},
                    "point": {"s": s, "t": t, "M": GRID_M, "mt2": GRID_MT2}, "on_grid": on_grid, "args": {k: v for k, v in args.items() if k != "workdir"}, "workdir": os.path.basename(workdir),
                    "legs": {k: {kk: vv for kk, vv in v.items() if kk != "values"} for k, v in results.items()}, "values": {k: v["values"] for k, v in results.items()}, "pair": pair, "planted": planted, "verdict": verdict, "rc": rc}
            fd = os.open(args["out"], os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o644)
            with os.fdopen(fd, "w") as f:
                json.dump(recp, f, indent=1)
            print("[written] %s" % os.path.basename(args["out"]))
        return rc
    except GridExit as ex:
        print(str(ex), flush=True)
        return ex.rc


def main():
    global DPS
    t_start = time.time()
    argv = sys.argv[1:]
    if "--help" in argv or "-h" in argv:
        # 2026-09-05: --help / -h prints the module docstring (the help
        # text, INTERFACE included) and exits 0 before any other argument
        # is read; every other flag is handled exactly as before.
        sys.stdout.write(__doc__)
        return 0
    # 2026-09-06: the (s,t) grid tier -- dispatched here, after --help and
    # before any other argument is read; the served tiers below are untouched.
    if "--M" in argv:
        print("zgamma-evaluate --M REFUSED by name: a second mass ratio is NOT ESTABLISHED -- the cusp seeds and corner "
              "forms carry M = 7/25 literals at 21 sites and no M = 1/4 object exists beyond the modular descent; the "
              "served value is M = m_Z^2/m_t^2 = 7/25 (m_t^2 = 1) on every tier", flush=True)
        return GRID_RC_REFUSED
    if "--point" in argv:
        _k = argv.index("--point")
        if _k + 1 < len(argv) and "," in argv[_k + 1]:
            return grid_main(argv)
    # axis3 wave2 (2026-07-05): --dps pre-scan so --boundary-recompute bdps
    # slaving sees the final DPS regardless of flag order on the command line.
    for _j, _a in enumerate(argv):
        if _a == "--dps" and _j + 1 < len(argv):
            DPS = int(argv[_j + 1])
    brec_series = None    # set by --boundary-recompute; consumed at derived-load
    brec_dps = None
    t_extra = None
    do_transport = False
    deep_cf = True        # 2026-09-06: closed forms = the value path (default);
    bank_path = None      # --k-strings restores the string-served path; --bank PATH
    i = 0
    while i < len(argv):
        if argv[i] in ("--t", "--point") and i + 1 < len(argv):
            t_extra = Fraction(argv[i + 1])
            assert t_extra < 0, "Euclidean t<0 only (domain: see docstring)"
            i += 2
        elif argv[i] == "--dps" and i + 1 < len(argv):
            DPS = int(argv[i + 1])
            i += 2
        elif argv[i] == "--transport":
            do_transport = True
            i += 1
        elif argv[i] == "--deep-closed-forms":
            deep_cf = True        # the default since 2026-09-06 (kept for compatibility)
            i += 1
        elif argv[i] == "--k-strings":
            deep_cf = False       # LEGACY A/B: the 2026-07-08 string-served path
            i += 1
        elif argv[i] == "--bank" and i + 1 < len(argv):
            bank_path = argv[i + 1]
            i += 2
        elif argv[i] == "--boundary-recompute":
            # Chain vendoring (2026-07-05) + second revision (2026-07-05
            # pm): HEAVY full boundary recompute via the vendored
            # region-seeded transport chain (zgamma_chain/); hours-class per
            # leg at production precision (run_recompute.sh header names the
            # classes; the two measured end-to-end walls, their load and the
            # march-only rate-fit projection they supersede are stated once
            # in the module docstring under INTERFACE --boundary-recompute;
            # the dps45 smoke leg is minutes-class; a wall-budget checkpoint
            # loop bounds each launch). The fresh endpoint is SUBSTITUTED into
            # K at derived-load (the recompute path consumes its own output);
            # the 52 cached endpoint strings demote to a compare-on-load cache
            # that RAISES on Re or Im mismatch. Bare flag: bdps slaved to
            # --dps as max(150, ceil(1.2*DPS)); explicit bdps below
            # max(ceil(1.2*DPS), DPS+22) refuses up front (fail-closed).
            import math
            bdps = None
            if i + 1 < len(argv) and argv[i + 1].isdigit():
                bdps = int(argv[i + 1]); i += 1
            i += 1
            if bdps is None:          # bare flag: bdps slaved to dps (6b)
                bdps = max(150, math.ceil(1.2 * DPS))
            # row-20 FLOORFIX (2026-07-05 pm): THIS
            # twin's gates track DPS+2 (independent tail) / DPS+4 (consistency,
            # seed supersession) through the +22-digit guard -- NOT the tools
            # twin's ~dps-6/dps-10 tracks -- so the tools formula
            # ceil(1.2*dps) alone ACCEPTS legs that then exit OVERALL: FAIL.
            # Calibration (verifier_legs34/B2s, real endpoint bdps 45 at
            # --dps 30): independent tail 30.22 d (floor ~bdps-14.8, BINDING vs
            # DPS+2 => bdps >= dps+16.8), consistency 32.95 d (~bdps-12.05),
            # supersession t-indep 32.9 d (~bdps-12.1), march gate_worst
            # 32.5 d (~bdps-12.5).  +5.2 d guard (march-floor scatter) =>
            # accepted class brc >= dps+22, with the ceil(1.2*dps) floor
            # retained (it dominates for dps >= 110; production bdps>=150
            # unaffected).
            req = max(math.ceil(1.2 * DPS), DPS + 22)
            if bdps < req:
                raise SystemExit(
                    f"[boundary-recompute] REFUSED: bdps {bdps} < required "
                    f"max(ceil(1.2*dps), dps+22) = {req} for --dps {DPS}. "
                    f"This twin gates at DPS+2/DPS+4 (through the +22 "
                    f"guard) and the SUBSTITUTED endpoint's propagated "
                    f"floor is ~bdps-14.8 d (measured at bdps 45: "
                    f"independent tail 30.22 d), so bdps must be >= dps+22 as well "
                    f"as >= ceil(1.2*dps). Raise the recompute DPS or lower "
                    f"--dps (fail-closed; no chain leg launched).")
            # 2026-09-11: the precondition, checked BEFORE spawning: the chain's
            # seed step imports core_fast from the archive placeholder, the
            # chain directory or the module search path; absent -> refuse by
            # name (exit status 2), nothing spawned, no work directory made.
            import importlib.machinery
            _chain_dir = os.path.join(os.path.dirname(os.path.abspath(__file__)), "zgamma_chain")
            if importlib.machinery.PathFinder.find_spec(
                    "core_fast", [BREC_CUSP_PLACEHOLDER, _chain_dir] + sys.path) is None:
                print("zgamma-evaluate --boundary-recompute %d REFUSED by name: %s" % (bdps, BREC_REFUSAL), flush=True)
                return BREC_RC_REFUSED
            import subprocess
            _here = os.path.dirname(os.path.abspath(__file__))
            chain = os.path.join(_here, "zgamma_chain")
            tag = f"brec{bdps}"
            print(f"[boundary-recompute {bdps}] HEAVY mode: vendored chain "
                  f"leg (seeds dps {bdps + 10} -> init -> march) ...")
            rc = subprocess.run(["bash",
                                 os.path.join(chain, "run_recompute.sh"),
                                 str(bdps), os.environ.get("ZG_NP", "24"),
                                 tag]).returncode
            if rc != 0:
                raise SystemExit(f"[boundary-recompute] leg FAILED rc={rc}")
            epj = json.load(open(os.path.join(
                chain, f"work_{tag}",
                f"endpoint_{tag}_dps{bdps}.json")))
            ep = epj["endpoint"]
            F5MAP = {"K6": 10, "K7": 11, "K9": 16, "K10": 18, "K12": 20,
                     "_M8end": 12, "_M11end": 19, "_Rbend": 21}
            ser = json.load(open(os.path.join(
                _here, "zgamma-derived.json")))["endpoint_constants"]["series"]
            worst = 1e9
            with mp.workdps(max(bdps, 200) + 20):
                for key, mi in F5MAP.items():
                    sc = max(abs(mp.mpf(v[0])) for v in ser[key].values())
                    for o, (re_s, im_s) in ser[key].items():
                        er, ei = ep[str(mi)][o]
                        # axis3 wave2: Re AND Im compared (both scale-rel to
                        # the key's max |Re|; Im legs are noise-floor pairs,
                        # measured 34.2 d at bdps 45 vs Re 32.9 d).
                        for dd in (abs(mp.mpf(er) - mp.mpf(re_s)),
                                   abs(mp.mpf(ei) - mp.mpf(im_s))):
                            d = 999.0 if dd == 0 else float(-mp.log10(dd / sc))
                            worst = min(worst, d)
            need = min(bdps, 137) - 12
            # 2026-07-05 dps45 smoke fix: agreement down to the run's OWN
            # independent-E01-oracle floor (gate_worst in the endpoint json)
            # is a PASS; the -12 heuristic is ~0.5 d tight at low dps for the
            # NT=ceil(1.69*DPS) trajectory.  bdps>=150 unaffected.
            gw = float(epj.get("gate_worst", 1e9))
            okc = (worst >= need) or (worst >= gw - 1.0)
            print(f"[boundary-recompute] compare-on-load cache gate: fresh "
                  f"endpoint vs cached endpoint strings (52, Re AND Im, "
                  f"scale-rel): worst {worst:.1f} d "
                  f"({'PASS' if okc else 'MISMATCH'} at bdps {bdps}; need >= "
                  f"{need} d or >= run's E01-oracle floor {gw:.1f} - 1.0 d; "
                  f"cache = dps-190 leg strings, certified 152.3 d mutual)")
            if not okc:
                raise RuntimeError(
                    f"[boundary-recompute] COMPARE-CACHE MISMATCH: cached "
                    f"stored strings vs fresh endpoint worst {worst:.1f} d < "
                    f"need {need} d AND < E01-oracle floor {gw:.1f} - 1.0 d "
                    f"(Re and Im, scale-rel, 52 strings, bdps {bdps}). The "
                    f"cache and the fresh endpoint disagree beyond this "
                    f"run's resolution -- investigate the provenance of "
                    f"BOTH before trusting either. Fail-closed: no "
                    f"evaluation performed.")
            # (a) SUBSTITUTION payload: consumed where main() loads derived
            # (the stored strings are compare-cache only for this run).
            brec_series = {
                key: {o: [ep[str(mi)][o][0], ep[str(mi)][o][1]]
                      for o in ser[key]}
                for key, mi in F5MAP.items()}
            brec_dps = bdps
            print(f"[boundary-recompute] fresh endpoint will be SUBSTITUTED "
                  f"into K (8 constants x eps^-2..+4; Re strings {bdps - 5} "
                  f"digits, march floor ~bdps-12 = {bdps - 12} d): stored "
                  f"strings NOT consumed by this evaluation.\n")
        else:
            raise SystemExit("usage: zgamma-evaluate.py [--help | -h] [--dps N] "
                             "[--t P/Q | --point P/Q] [--transport] "
                             "[--k-strings] [--bank PATH] [--deep-closed-forms] "
                             "[--boundary-recompute [DPS]] "
                             "[--point s,t [--dps 30|45] [--check] [--mutate] [--workdir DIR] [--out JSON]]")
    mp.mp.dps = DPS + GUARD
    ok = True
    print("gg->Zgamma exact-m_t E125 t-cone: derived-constant closed-form "
          "evaluation at s=-1/4, dps=%d (+%d guard)" % (DPS, GUARD))
    print("  constants: K0..K5 live 3F2/2F1 closed forms; K6,K7,K9,K10 "
          "Gamma-ladder/terminating-3F2 closed forms (2026-07-05 closed-form "
          "derivation) — %s; "
          "K12 + endpoint = analytic s-transport strings (elliptic residue); "
          "T1/T8/c13 solved exactly at runtime; ZERO AMFlow-derived "
          "constants in the evaluation path"
          % ("default: runtime Cauchy/DFT at the full dps, the closed forms "
             "served as the values, the stored strings the compare gate"
             if deep_cf else
             "LEGACY --k-strings: stored reference strings served under the "
             "cheap min(dps,60) closed-form compare gate"))
    print("  seed provenance (2026-07-04 derivation): all 7 A0 G-seeds derived, "
          "gated 61.1-65.9 d vs the dedicated independent AMFlow oracle + "
          "second-config re-gate; provisional set retired")

    cone = json.load(open(os.path.join(HERE, "zgamma-cone-At.json")))
    nent = structure_check(cone)
    print("  structure check (EXACT rational arithmetic): %d A_t entries; "
          "zero rows = 11 t-independent masters; diagonal kernels are exact "
          "dlogs of D1, D2, D3; m8 row eps-free  [PASS]" % nent)

    derived = json.load(open(os.path.join(HERE, "zgamma-derived.json")))
    if brec_series is not None:
        # Revision 2026-07-05: the recompute path CONSUMES its own output
        # -- the fresh chain endpoint replaces the stored endpoint strings
        # for this entire evaluation (compare-cache only, gated above).
        derived["endpoint_constants"]["series"] = brec_series
        print("  [boundary-recompute] fresh endpoint SUBSTITUTED into K "
              "(bdps %d; stored strings not consumed)" % brec_dps)
    t0c = time.time()
    Ser, ser_exp, ser_gamma_eps, hyper_ser = make_series_tools()
    K = build_constants(Ser, ser_exp, ser_gamma_eps, hyper_ser, derived, DPS,
                        deep=deep_cf, bank=bank_path)
    solve_endpoint_tail(Ser, K, derived["slope_tables"])
    forms, coeffs = assemble_tail(Ser, K, derived["slope_tables"])
    print("  constants built + T1/T8/c13 solved (%.1f s)" % (time.time() - t0c))

    # live proof the closed forms solve the certified connection (incl. a
    # complex point beside the round-2 apparent singularity t=-53/236)
    tab = build_tab(cone)
    ap = mp.mpf(APPARENT_POLE.numerator) / mp.mpf(APPARENT_POLE.denominator)
    tvals = [mp.mpf(-7) / 5, mp.mpf(-1) / 9, mp.mpc(ap, mp.mpf("0.18")), mp.mpf(-31)]
    dder = derivative_identity_check(Ser, tab, K, forms, coeffs, tvals)
    print("  derivative identity dM/dt = A_t(eps,t) M (LIVE eps-Laurent "
          "arithmetic, 4 t-points incl. complex): worst residual %.1f d" % dder)
    if dder < DPS - 10:
        ok = False

    print("  corner gate (LIVE closed forms K0..K5 vs 54 independent E01 rows):")
    wc = run_corner_gate(K, derived)
    worst_held, worst_cons = run_tail_gate(K, forms, derived)
    print("  worst corner (independent): %.2f d   worst independent tail "
          "(E02+E03+E04): %.2f d   worst consistency (E01): %.2f d"
          % (wc, worst_held, worst_cons))
    if wc < min(139, DPS + 8) or worst_held < min(133.5, DPS + 2) or \
            worst_cons < min(136, DPS + 4):
        ok = False

    # supersession cross-check: derived t=0 values vs the round-2 seed
    # artifact (verbatim/transported AMFlow E04 values, certified ~105 d,
    # strings 119-141 d) — the OLD seeds are now REPRODUCED, not consumed.
    # The seed file is a cross-check TARGET only: if it is absent the check
    # is skipped with a note (nothing downstream consumes it).
    z = mp.mpf(0)
    pred0 = {I_M8: forms["m8"](z), I_M11: forms["m11"](z), I_RB: forms["g32"](z)}
    _seed_path = os.path.join(HERE, "zgamma-cusp-seeds.json")
    if not os.path.exists(_seed_path):
        print("  round-2 seed supersession: SKIPPED (zgamma-cusp-seeds.json "
              "not found beside the script; it is a superseded cross-check "
              "target only — download it to enable this check)")
    else:
        sj = json.load(open(_seed_path))
        w_ind, w_dep = mp.inf, mp.inf
        for i_str, ser in sj["seeds"].items():
            idx = int(i_str)
            pser = K["K%d" % idx] if idx in T_INDEP else pred0[idx]
            for o_str, sval in ser.items():
                o = int(o_str)
                if o < OMIN or o > OMAX:
                    continue
                truth = mp.mpc(mp.mpf(sval[0]), mp.mpf(sval[1]))
                if truth == 0:
                    continue
                dg = digits(pser.get(o), truth)
                if idx in T_INDEP:
                    w_ind = min(w_ind, dg)
                else:
                    w_dep = min(w_dep, dg)
        print("  round-2 seed supersession: derived t=0 values vs "
              "zgamma-cusp-seeds.json: t-independent worst %.1f d (their E04-"
              "string cap ~139-141 d); t-dependent worst %.1f d (their transport "
              "noise floor ~119.5 d)" % (w_ind, w_dep))
        if w_ind < min(136.5, DPS + 4) or w_dep < min(118.5, DPS + 2):
            ok = False

    # independent 50-d stored cross-check of g32(t=0) eps^0 (pre-dates every derivation)
    d_seed = digits(pred0[I_RB].get(0).real, mp.mpf(STORED_RB0_T0))
    print("  stored cross-check: g32 eps^0(t=0) vs independent t->0 "
          "extrapolation artifact = %.1f d (artifact precision ~50 d)" % d_seed)
    if d_seed < min(46, DPS - 4):
        ok = False

    # modular spine (s-direction), live — UNTOUCHED round-2 machinery
    delta, dcoc = cocycle_check()
    print("  spine cocycle: 2*pi*i Int_{tau0}^{tau0+1} B_2,4 dtau = %s ~ i*pi/4"
          "  [%.1f d, live E2 q-series quadrature]" % (mp.nstr(delta, 15), float(dcoc)))
    if dcoc < mp.mp.dps - 25:
        ok = False
    drng = ring_generator_check()
    print("  ring generator: Catalan = L(chi_-4,2) by LIVE alternating-series "
          "summation: %.1f d" % drng)
    print("    [\"w2 = Catalan\" as a boundary-constant VALUE: PSLQ-refuted "
          "(Class-1 2026-07-03); Catalan is the ring GENERATOR only]")
    if drng < mp.mp.dps - 15:
        ok = False

    # explicit stored-string caps (measured at runtime, not asserted)
    o_cap = min(sum(ch.isdigit() for ch in s2)
                for pt2 in ORACLE.values()
                for lab2 in ("m8", "m11", "g32", "g31")
                for s2 in pt2[lab2].values() if abs(mp.mpf(s2)) > 1e-3)
    f_cap = min(sum(ch.isdigit() for ch in v[0])
                for ser in derived["endpoint_constants"]["series"].values()
                for o, v in ser.items()
                if sum(ch.isdigit() for ch in v[0]) > 20)  # skip exact short entries
    print("  precision caps: working dps %d (+%d guard); oracle strings %d d "
          "(certified >=109 d); endpoint strings %d d stored, gated "
          "136.8 d worst upstream. Doubling --dps grows every live agreement "
          "until these caps bind." % (DPS, GUARD, o_cap, f_cap))

    if t_extra is not None:
        tv = mp.mpf(t_extra.numerator) / mp.mpf(t_extra.denominator)
        dg_x = derivative_identity_check(Ser, tab, K, forms, coeffs, [tv])
        print("  extra point t=%s (no oracle; exact polynomial tail; "
              "derivative identity %.1f d):" % (t_extra, dg_x))
        for lab in ("m8", "m11", "g31", "g32"):
            pser = forms[lab]() if lab == "g31" else forms[lab](tv)
            for o in range(OMIN, OMAX + 1):
                v = pser.get(o)
                if v != 0:
                    print("    %-3s eps^%+d = %s"
                          % (lab, o, mp.nstr(v.real, min(DPS, 40))))

    if do_transport:
        # round-2 VoP quadrature words over the certified connection, seeded
        # by the DERIVED t=0 values; compared against the closed forms.
        print("  --transport: round-2 Chebyshev VoP words from derived t=0 "
              "seeds (slow; minutes-class at dps 100):")
        seeds = masters_at(K, forms, mp.mpf(0))
        CW = ConeWords(cone, seeds)
        path = [mp.mpf(0), mp.mpf("-0.12"), mp.mpc(ap, mp.mpf("0.18")),
                mp.mpf(-1) / 3, mp.mpf("-0.7"), mp.mpf(-3) / 2, mp.mpf(-3),
                mp.mpf(-6)]
        t0t = time.time()
        out, diags = CW.transport(path, DPS + 8, want={3, 5, 7})
        for seg, N, s11, s13 in diags:
            print("    segment %d: N=%d Chebyshev terms, tail certificates "
                  "(m11, g32) = (%.1e, %.1e)" % (seg, N, s11, s13))
        im_max = max(abs(out[v][mi][k].imag) for v in (3, 5, 7)
                     for mi in (I_M8, I_M11, I_RB) for k in range(NORD))
        print("    detour Im-cancellation: max |Im| = %.1e" % im_max)
        if im_max > mp.mpf(10) ** (-(DPS + 4)):
            ok = False
        w_tr = mp.inf
        for vi, tt, lbl in ((3, Fraction(-1, 3), "E01"), (5, Fraction(-3, 2), "E02"),
                            (7, Fraction(-6), "E03")):
            tv = mp.mpf(tt.numerator) / mp.mpf(tt.denominator)
            cf = {I_M8: forms["m8"](tv), I_M11: forms["m11"](tv),
                  I_RB: forms["g32"](tv)}
            w = mp.inf
            for mi in (I_M8, I_M11, I_RB):
                for k in range(NORD):
                    w = min(w, digits(out[vi][mi][k], cf[mi].get(k + OMIN)))
            w_tr = min(w_tr, w)
            print("    %s transport-vs-closed-form worst: %.2f d" % (lbl, w))
        print("    (transport wall %.1f s)" % (time.time() - t0t))
        if w_tr < DPS + 2:
            ok = False

    print("OVERALL: %s   (wall %.1f s)"
          % ("PASS" if ok else "FAIL", time.time() - t_start))
    return 0 if ok else 1


if __name__ == "__main__":
    raise SystemExit(main())
